text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2017 ASTRON - Netherlands Institute for Radio Astronomy
// Copyright 2017 NLeSC - Netherlands eScience Center
//
// 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.
// Contributor: Alessio Sclocco <[email protected]>
#include <Trigger.hpp>
void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, triggeredEvents_t & triggeredEvents) {
unsigned int nrDMs = 0;
if ( subbandDedispersion ) {
nrDMs = observation.getNrDMsSubbanding() * observation.getNrDMs();
} else {
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) {
for ( unsigned int dm = 0; dm < nrDMs; dm++ ) {
if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) {
triggeredEvent event;
event.beam = beam;
event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm];
event.integration = integration;
event.DM = dm;
event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm];
if ( triggeredEvents.at(beam).at(dm) != std::out_of_range ) {
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
} else {
// Add event to new list
std::vector<triggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<triggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation & observation, const triggeredEvents_t & triggeredEvents, compactedEvents_t & compactedEvents) {
compactedEvents_t temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
#pragma omp parallel for
for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) {
compactedEvent event;
for ( auto dmEvent = beamEvents->second.begin(); dmEvent != beamEvents->second.end(); ++dmEvent ) {
if ( dmEvent->SNR > event.SNR ) {
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
temporaryEvents.at(event.beam).push_back(event);
}
// Compact DM
#pragma omp parallel for
for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) {
for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) {
compactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM ) {
finalEvent.beam = event->beam;
finalEvent.sample = event->sample;
finalEvent.integration = event->integration;
finalEvent.DM = event->DM;
finalEvent.SNR = event->SNR;
finalEvent.compactedDMs += window;
window++;
}
event += (window - 1);
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
}
}
}
<commit_msg>Found out I should have expected an exception, not a return value. Fixed.<commit_after>// Copyright 2017 ASTRON - Netherlands Institute for Radio Astronomy
// Copyright 2017 NLeSC - Netherlands eScience Center
//
// 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.
// Contributor: Alessio Sclocco <[email protected]>
#include <Trigger.hpp>
void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, triggeredEvents_t & triggeredEvents) {
unsigned int nrDMs = 0;
if ( subbandDedispersion ) {
nrDMs = observation.getNrDMsSubbanding() * observation.getNrDMs();
} else {
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) {
for ( unsigned int dm = 0; dm < nrDMs; dm++ ) {
if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) {
triggeredEvent event;
event.beam = beam;
event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm];
event.integration = integration;
event.DM = dm;
event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm];
try {
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
} catch ( std::out_of_range err ) {
// Add event to new list
std::vector<triggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<triggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation & observation, const triggeredEvents_t & triggeredEvents, compactedEvents_t & compactedEvents) {
compactedEvents_t temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
#pragma omp parallel for
for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) {
compactedEvent event;
for ( auto dmEvent = beamEvents->second.begin(); dmEvent != beamEvents->second.end(); ++dmEvent ) {
if ( dmEvent->SNR > event.SNR ) {
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
temporaryEvents.at(event.beam).push_back(event);
}
// Compact DM
#pragma omp parallel for
for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) {
for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) {
compactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM ) {
finalEvent.beam = event->beam;
finalEvent.sample = event->sample;
finalEvent.integration = event->integration;
finalEvent.DM = event->DM;
finalEvent.SNR = event->SNR;
finalEvent.compactedDMs += window;
window++;
}
event += (window - 1);
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Pieter Wuille
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addrman.h"
#include "hash.h"
using namespace std;
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
{
CDataStream ss1(SER_GETHASH, 0);
std::vector<unsigned char> vchKey = GetKey();
ss1 << nKey << vchKey;
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
CDataStream ss2(SER_GETHASH, 0);
std::vector<unsigned char> vchGroupKey = GetGroup();
ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
}
int CAddrInfo::GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const
{
CDataStream ss1(SER_GETHASH, 0);
std::vector<unsigned char> vchGroupKey = GetGroup();
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
ss1 << nKey << vchGroupKey << vchSourceGroupKey;
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
CDataStream ss2(SER_GETHASH, 0);
ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
}
bool CAddrInfo::IsTerrible(int64 nNow) const
{
if (nLastTry && nLastTry >= nNow-60) // never remove things tried the last minute
return false;
if (nTime > nNow + 10*60) // came in a flying DeLorean
return true;
if (nTime==0 || nNow-nTime > ADDRMAN_HORIZON_DAYS*86400) // not seen in over a month
return true;
if (nLastSuccess==0 && nAttempts>=ADDRMAN_RETRIES) // tried three times and never a success
return true;
if (nNow-nLastSuccess > ADDRMAN_MIN_FAIL_DAYS*86400 && nAttempts>=ADDRMAN_MAX_FAILURES) // 10 successive failures in the last week
return true;
return false;
}
double CAddrInfo::GetChance(int64 nNow) const
{
double fChance = 1.0;
int64 nSinceLastSeen = nNow - nTime;
int64 nSinceLastTry = nNow - nLastTry;
if (nSinceLastSeen < 0) nSinceLastSeen = 0;
if (nSinceLastTry < 0) nSinceLastTry = 0;
fChance *= 600.0 / (600.0 + nSinceLastSeen);
// deprioritize very recent attempts away
if (nSinceLastTry < 60*10)
fChance *= 0.01;
// deprioritize 50% after each failed attempt
for (int n=0; n<nAttempts; n++)
fChance /= 1.5;
return fChance;
}
CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int *pnId)
{
std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
if (it == mapAddr.end())
return NULL;
if (pnId)
*pnId = (*it).second;
std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
if (it2 != mapInfo.end())
return &(*it2).second;
return NULL;
}
CAddrInfo* CAddrMan::Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId)
{
int nId = nIdCount++;
mapInfo[nId] = CAddrInfo(addr, addrSource);
mapAddr[addr] = nId;
mapInfo[nId].nRandomPos = vRandom.size();
vRandom.push_back(nId);
if (pnId)
*pnId = nId;
return &mapInfo[nId];
}
void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
{
if (nRndPos1 == nRndPos2)
return;
assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
int nId1 = vRandom[nRndPos1];
int nId2 = vRandom[nRndPos2];
assert(mapInfo.count(nId1) == 1);
assert(mapInfo.count(nId2) == 1);
mapInfo[nId1].nRandomPos = nRndPos2;
mapInfo[nId2].nRandomPos = nRndPos1;
vRandom[nRndPos1] = nId2;
vRandom[nRndPos2] = nId1;
}
int CAddrMan::SelectTried(int nKBucket)
{
std::vector<int> &vTried = vvTried[nKBucket];
// random shuffle the first few elements (using the entire list)
// find the least recently tried among them
int64 nOldest = -1;
int nOldestPos = -1;
for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
{
int nPos = GetRandInt(vTried.size() - i) + i;
int nTemp = vTried[nPos];
vTried[nPos] = vTried[i];
vTried[i] = nTemp;
assert(nOldest == -1 || mapInfo.count(nTemp) == 1);
if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
nOldest = nTemp;
nOldestPos = nPos;
}
}
return nOldestPos;
}
int CAddrMan::ShrinkNew(int nUBucket)
{
assert(nUBucket >= 0 && (unsigned int)nUBucket < vvNew.size());
std::set<int> &vNew = vvNew[nUBucket];
// first look for deletable items
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
assert(mapInfo.count(*it));
CAddrInfo &info = mapInfo[*it];
if (info.IsTerrible())
{
if (--info.nRefCount == 0)
{
SwapRandom(info.nRandomPos, vRandom.size()-1);
vRandom.pop_back();
mapAddr.erase(info);
mapInfo.erase(*it);
nNew--;
}
vNew.erase(it);
return 0;
}
}
// otherwise, select four randomly, and pick the oldest of those to replace
int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
int nI = 0;
int nOldest = -1;
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
{
assert(nOldest == -1 || mapInfo.count(*it) == 1);
if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
nOldest = *it;
}
nI++;
}
assert(mapInfo.count(nOldest) == 1);
CAddrInfo &info = mapInfo[nOldest];
if (--info.nRefCount == 0)
{
SwapRandom(info.nRandomPos, vRandom.size()-1);
vRandom.pop_back();
mapAddr.erase(info);
mapInfo.erase(nOldest);
nNew--;
}
vNew.erase(nOldest);
return 1;
}
void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
{
assert(vvNew[nOrigin].count(nId) == 1);
// remove the entry from all new buckets
for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
{
if ((*it).erase(nId))
info.nRefCount--;
}
nNew--;
assert(info.nRefCount == 0);
// what tried bucket to move the entry to
int nKBucket = info.GetTriedBucket(nKey);
std::vector<int> &vTried = vvTried[nKBucket];
// first check whether there is place to just add it
if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
{
vTried.push_back(nId);
nTried++;
info.fInTried = true;
return;
}
// otherwise, find an item to evict
int nPos = SelectTried(nKBucket);
// find which new bucket it belongs to
assert(mapInfo.count(vTried[nPos]) == 1);
int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
std::set<int> &vNew = vvNew[nUBucket];
// remove the to-be-replaced tried entry from the tried set
CAddrInfo& infoOld = mapInfo[vTried[nPos]];
infoOld.fInTried = false;
infoOld.nRefCount = 1;
// do not update nTried, as we are going to move something else there immediately
// check whether there is place in that one,
if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
{
// if so, move it back there
vNew.insert(vTried[nPos]);
} else {
// otherwise, move it to the new bucket nId came from (there is certainly place there)
vvNew[nOrigin].insert(vTried[nPos]);
}
nNew++;
vTried[nPos] = nId;
// we just overwrote an entry in vTried; no need to update nTried
info.fInTried = true;
return;
}
void CAddrMan::Good_(const CService &addr, int64 nTime)
{
// printf("Good: addr=%s\n", addr.ToString().c_str());
int nId;
CAddrInfo *pinfo = Find(addr, &nId);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastSuccess = nTime;
info.nLastTry = nTime;
info.nTime = nTime;
info.nAttempts = 0;
// if it is already in the tried set, don't do anything else
if (info.fInTried)
return;
// find a bucket it is in now
int nRnd = GetRandInt(vvNew.size());
int nUBucket = -1;
for (unsigned int n = 0; n < vvNew.size(); n++)
{
int nB = (n+nRnd) % vvNew.size();
std::set<int> &vNew = vvNew[nB];
if (vNew.count(nId))
{
nUBucket = nB;
break;
}
}
// if no bucket is found, something bad happened;
// TODO: maybe re-add the node, but for now, just bail out
if (nUBucket == -1) return;
printf("Moving %s to tried\n", addr.ToString().c_str());
// move nId to the tried tables
MakeTried(info, nId, nUBucket);
}
bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty)
{
if (!addr.IsRoutable())
return false;
bool fNew = false;
int nId;
CAddrInfo *pinfo = Find(addr, &nId);
if (pinfo)
{
// periodically update nTime
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
// add services
pinfo->nServices |= addr.nServices;
// do not update if no new information is present
if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
return false;
// do not update if the entry was already in the "tried" table
if (pinfo->fInTried)
return false;
// do not update if the max reference count is reached
if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
return false;
// stochastic test: previous nRefCount == N: 2^N times harder to increase it
int nFactor = 1;
for (int n=0; n<pinfo->nRefCount; n++)
nFactor *= 2;
if (nFactor > 1 && (GetRandInt(nFactor) != 0))
return false;
} else {
pinfo = Create(addr, source, &nId);
pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
nNew++;
fNew = true;
}
int nUBucket = pinfo->GetNewBucket(nKey, source);
std::set<int> &vNew = vvNew[nUBucket];
if (!vNew.count(nId))
{
pinfo->nRefCount++;
if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
ShrinkNew(nUBucket);
vvNew[nUBucket].insert(nId);
}
return fNew;
}
void CAddrMan::Attempt_(const CService &addr, int64 nTime)
{
CAddrInfo *pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastTry = nTime;
info.nAttempts++;
}
CAddress CAddrMan::Select_(int nUnkBias)
{
if (size() == 0)
return CAddress();
double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
double nCorNew = sqrt(nNew) * nUnkBias;
if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
{
// use a tried node
double fChanceFactor = 1.0;
while(1)
{
int nKBucket = GetRandInt(vvTried.size());
std::vector<int> &vTried = vvTried[nKBucket];
if (vTried.size() == 0) continue;
int nPos = GetRandInt(vTried.size());
assert(mapInfo.count(vTried[nPos]) == 1);
CAddrInfo &info = mapInfo[vTried[nPos]];
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
return info;
fChanceFactor *= 1.2;
}
} else {
// use a new node
double fChanceFactor = 1.0;
while(1)
{
int nUBucket = GetRandInt(vvNew.size());
std::set<int> &vNew = vvNew[nUBucket];
if (vNew.size() == 0) continue;
int nPos = GetRandInt(vNew.size());
std::set<int>::iterator it = vNew.begin();
while (nPos--)
it++;
assert(mapInfo.count(*it) == 1);
CAddrInfo &info = mapInfo[*it];
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
return info;
fChanceFactor *= 1.2;
}
}
}
#ifdef DEBUG_ADDRMAN
int CAddrMan::Check_()
{
std::set<int> setTried;
std::map<int, int> mapNew;
if (vRandom.size() != nTried + nNew) return -7;
for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
{
int n = (*it).first;
CAddrInfo &info = (*it).second;
if (info.fInTried)
{
if (!info.nLastSuccess) return -1;
if (info.nRefCount) return -2;
setTried.insert(n);
} else {
if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
if (!info.nRefCount) return -4;
mapNew[n] = info.nRefCount;
}
if (mapAddr[info] != n) return -5;
if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
if (info.nLastTry < 0) return -6;
if (info.nLastSuccess < 0) return -8;
}
if (setTried.size() != nTried) return -9;
if (mapNew.size() != nNew) return -10;
for (int n=0; n<vvTried.size(); n++)
{
std::vector<int> &vTried = vvTried[n];
for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
{
if (!setTried.count(*it)) return -11;
setTried.erase(*it);
}
}
for (int n=0; n<vvNew.size(); n++)
{
std::set<int> &vNew = vvNew[n];
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
if (!mapNew.count(*it)) return -12;
if (--mapNew[*it] == 0)
mapNew.erase(*it);
}
}
if (setTried.size()) return -13;
if (mapNew.size()) return -15;
return 0;
}
#endif
void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
{
int nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
if (nNodes > ADDRMAN_GETADDR_MAX)
nNodes = ADDRMAN_GETADDR_MAX;
// perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
for (int n = 0; n<nNodes; n++)
{
int nRndPos = GetRandInt(vRandom.size() - n) + n;
SwapRandom(n, nRndPos);
assert(mapInfo.count(vRandom[n]) == 1);
vAddr.push_back(mapInfo[vRandom[n]]);
}
}
void CAddrMan::Connected_(const CService &addr, int64 nTime)
{
CAddrInfo *pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
int64 nUpdateInterval = 20 * 60;
if (nTime - info.nTime > nUpdateInterval)
info.nTime = nTime;
}
<commit_msg>Delete addrman.cpp<commit_after><|endoftext|> |
<commit_before>//
// likelihood.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 13/04/2016.
//
#include "likelihood.h"
Likelihood::Likelihood() {}
double Likelihood::binomial_lik(double reporting_rate, double process, int size, int start, int end, int num_groups, bool return_log) {
// Assuming no data is observed
double loglik=0.0;
for (int group_id=0; group_id!=num_groups; ++group_id) {
double total_incidence = process;//0.0;
// for (int i=start; i!=end; ++i) {
// total_incidence += *(process+group_id*size+i-start);
// }
loglik += log(1.0-reporting_rate) * (double)total_incidence;//dbinom(0.0, total_incidence, params[5], 1);
}
if (return_log) return(loglik);
return(exp(loglik));
}
double Likelihood::binomial_lik(double reporting_rate, double process, std::vector<double>::iterator data, int size, int start, int end, int shift, int num_groups, bool return_log) {
double loglik=0.0;
for (int group_id=0; group_id!=num_groups; ++group_id) {
double total_incidence = process;//0.0;
double total_data = 0.0;
for (int i=start; i!=end; ++i) {
// total_incidence += *(process+group_id*size+i-start);
// double curr_inc = *(data+group_id*size+i-shift);
double curr_inc = *(data+group_id*(size-shift)+i);
total_data += curr_inc;
if (total_data < 0) {
if (curr_inc >= 0) {
total_data = curr_inc;
}
}
}
if (total_data < 0) {
if (return_log) return(0.0);
return(1.0);
}
// if (total_data < 1.0) {
// if (return_log) return(0.0);
// return(1.0);
// }
// double total_diff = abs(total_incidence-total_data/reporting_rate);
// if (total_diff > (total_data/reporting_rate)) total_diff = total_data/reporting_rate;
// if (return_log) return (log(1.0-total_diff/(total_data/reporting_rate)));
// else return (1.0-total_diff/(total_data/reporting_rate));
if (total_data > total_incidence) {
if (return_log) return(-std::numeric_limits<double>::max());
return(0.0);
}
if (total_data == 0.0) {
loglik += log(1.0-reporting_rate) * (double)total_incidence;
}
else {
loglik += log(gsl_ran_binomial_pdf(total_data, reporting_rate, total_incidence));
}
}
if (return_log) return(loglik);
return(exp(loglik));
}
double Likelihood::coalescent_lik(std::vector<double>::iterator sim_prev, std::vector<double>::iterator sim_coal_rate,
std::vector<double>::iterator binomial, std::vector<double>::iterator intervals,
std::vector<double>::iterator indices, int start, int end, int shift, bool return_log) {
double weight = 0.0;
for (int deltaT=start; deltaT!=end; ++deltaT) {
// Loop over each simulation time step
double NtoNe = *(sim_coal_rate+deltaT-start);
double prev = *(sim_prev+deltaT-start);
double coal_rate = NtoNe/prev;
if (prev<1.0) coal_rate = 0.0;
int first_index;
if ((deltaT)==0) first_index = 0;
else first_index = *(indices+deltaT-1)+1;
int last_index = *(indices+deltaT);
for (int event=first_index; event<=last_index; ++event) {
// Loop over event during a simulation time step (either coalescence or sampling)
double binom_coeff = *(binomial+event);
if (binom_coeff > 0) {
if ((prev <= 1.0) | ((prev*(prev-1.0)/2.0) < binom_coeff)) {
if (return_log) return(-std::numeric_limits<double>::max());
return (0.0);
}
double coal_rate_population = binom_coeff*coal_rate;
double time_to_next_event = *(intervals+event);
if (time_to_next_event < 0.0) {
// Coalescent ended interval
if (coal_rate == 0.0){
// If epidemic has died out before the most recent tip
if (return_log) return(-std::numeric_limits<double>::max());
return (0.0);
}
double time_to_coal = -*(intervals+event);
weight += log(coal_rate_population)-(coal_rate_population*time_to_coal);
}
else {
// Sampling ended interval, or the end of the simulation time step
double time_to_event = *(intervals+event);
weight += -(coal_rate_population*time_to_event);
}
}
}
if (!std::isfinite(weight)) {
if (return_log) return (-std::numeric_limits<double>::max());
return (0.0);
}
}
if (return_log) return (weight);
return (exp(weight));
}
<commit_msg>use poisson instead of binomial likelihood<commit_after>//
// likelihood.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 13/04/2016.
//
#include "likelihood.h"
Likelihood::Likelihood() {}
double Likelihood::binomial_lik(double reporting_rate, double process, int size, int start, int end, int num_groups, bool return_log) {
// Assuming no data is observed
double loglik=0.0;
for (int group_id=0; group_id!=num_groups; ++group_id) {
double total_incidence = process;//0.0;
// for (int i=start; i!=end; ++i) {
// total_incidence += *(process+group_id*size+i-start);
// }
loglik += log(1.0-reporting_rate) * (double)total_incidence;//dbinom(0.0, total_incidence, params[5], 1);
}
if (return_log) return(loglik);
return(exp(loglik));
}
double Likelihood::binomial_lik(double reporting_rate, double process, std::vector<double>::iterator data, int size, int start, int end, int shift, int num_groups, bool return_log) {
double loglik=0.0;
for (int group_id=0; group_id!=num_groups; ++group_id) {
double total_incidence = process;//0.0;
double total_data = 0.0;
for (int i=start; i!=end; ++i) {
// total_incidence += *(process+group_id*size+i-start);
// double curr_inc = *(data+group_id*size+i-shift);
double curr_inc = *(data+group_id*(size-shift)+i);
total_data += curr_inc;
if (total_data < 0) {
if (curr_inc >= 0) {
total_data = curr_inc;
}
}
}
if (total_data < 0) {
if (return_log) return(0.0);
return(1.0);
}
// if (total_data < 1.0) {
// if (return_log) return(0.0);
// return(1.0);
// }
// double total_diff = abs(total_incidence-total_data/reporting_rate);
// if (total_diff > (total_data/reporting_rate)) total_diff = total_data/reporting_rate;
// if (return_log) return (log(1.0-total_diff/(total_data/reporting_rate)));
// else return (1.0-total_diff/(total_data/reporting_rate));
if (total_data > total_incidence) {
if (return_log) return(-std::numeric_limits<double>::max());
return(0.0);
}
if (total_data == 0.0) {
loglik += log(1.0-reporting_rate) * (double)total_incidence;
}
else {
loglik += log(gsl_ran_poisson_pdf(1, total_incidence*reporting_rate/total_data));
//loglik += log(gsl_ran_binomial_pdf(total_data, reporting_rate, total_incidence));
}
}
if (return_log) return(loglik);
return(exp(loglik));
}
double Likelihood::coalescent_lik(std::vector<double>::iterator sim_prev, std::vector<double>::iterator sim_coal_rate,
std::vector<double>::iterator binomial, std::vector<double>::iterator intervals,
std::vector<double>::iterator indices, int start, int end, int shift, bool return_log) {
double weight = 0.0;
for (int deltaT=start; deltaT!=end; ++deltaT) {
// Loop over each simulation time step
double NtoNe = *(sim_coal_rate+deltaT-start);
double prev = *(sim_prev+deltaT-start);
double coal_rate = NtoNe/prev;
if (prev<1.0) coal_rate = 0.0;
int first_index;
if ((deltaT)==0) first_index = 0;
else first_index = *(indices+deltaT-1)+1;
int last_index = *(indices+deltaT);
for (int event=first_index; event<=last_index; ++event) {
// Loop over event during a simulation time step (either coalescence or sampling)
double binom_coeff = *(binomial+event);
if (binom_coeff > 0) {
if ((prev <= 1.0) | ((prev*(prev-1.0)/2.0) < binom_coeff)) {
if (return_log) return(-std::numeric_limits<double>::max());
return (0.0);
}
double coal_rate_population = binom_coeff*coal_rate;
double time_to_next_event = *(intervals+event);
if (time_to_next_event < 0.0) {
// Coalescent ended interval
if (coal_rate == 0.0){
// If epidemic has died out before the most recent tip
if (return_log) return(-std::numeric_limits<double>::max());
return (0.0);
}
double time_to_coal = -*(intervals+event);
weight += log(coal_rate_population)-(coal_rate_population*time_to_coal);
}
else {
// Sampling ended interval, or the end of the simulation time step
double time_to_event = *(intervals+event);
weight += -(coal_rate_population*time_to_event);
}
}
}
if (!std::isfinite(weight)) {
if (return_log) return (-std::numeric_limits<double>::max());
return (0.0);
}
}
if (return_log) return (weight);
return (exp(weight));
}
<|endoftext|> |
<commit_before>#include "wvtftps.h"
int main()
{
WvTFTPs tftps("/tftpboot", 30*1000);
while (tftps.isok())
{
if (tftps.select(0))
tftps.callback();
}
wvcon->print("TFTPs is not okay; aborting.\n");
}
<commit_msg>Support for blksize option (RFC 2348).<commit_after>#include "wvtftps.h"
int main()
{
WvTFTPs tftps("/tftpboot", 30, 30);
while (tftps.isok())
{
if (tftps.select(0))
tftps.callback();
}
wvcon->print("TFTPs is not okay; aborting.\n");
}
<|endoftext|> |
<commit_before>//
// Copyright 2020 Google LLC
//
// 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 "src/lint_errors.h"
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "zetasql/base/status.h"
#include "zetasql/base/status_macros.h"
#include "zetasql/base/statusor.h"
#include "zetasql/public/parse_helpers.h"
#include "zetasql/public/parse_location.h"
namespace zetasql::linter {
std::string LintError::GetErrorMessage() { return message_; }
std::string LintError::ConstructPositionMessage() {
return absl::StrCat("In line ", line_, ", column ", column_, ": ");
}
void LintError::PrintError() {
if (filename_ == "") {
std::cout << ConstructPositionMessage() << GetErrorMessage() << std::endl;
} else {
std::cout << filename_ << ":" << ConstructPositionMessage()
<< GetErrorMessage() << std::endl;
}
}
void LinterResult::PrintResult() {
// Need to sort according to increasing line number
sort(errors_.begin(), errors_.end(),
[&](const LintError &a, const LintError &b) {
return a.GetLineNumber() < b.GetLineNumber();
});
for (LintError error : errors_) error.PrintError();
for (absl::Status status : status_) std::cerr << status << std::endl;
std::cout << "Linter results are printed" << std::endl;
}
LinterResult::LinterResult(const absl::Status &status) {
if (!status.ok()) status_.push_back(status);
}
absl::Status LinterResult::Add(ErrorCode type, absl::string_view filename,
absl::string_view sql, int character_location,
std::string message) {
ParseLocationPoint lp =
ParseLocationPoint::FromByteOffset(character_location);
ParseLocationTranslator lt(sql);
std::pair<int, int> error_pos;
ZETASQL_ASSIGN_OR_RETURN(error_pos, lt.GetLineAndColumnAfterTabExpansion(lp));
LintError t(type, filename, error_pos.first, error_pos.second, message);
errors_.push_back(t);
return absl::OkStatus();
}
void LinterResult::Add(ErrorCode type, absl::string_view sql,
int character_location, std::string message) {
Add(type, "", sql, character_location, message);
}
void LinterResult::Add(LinterResult result) {
for (LintError error : result.GetErrors())
errors_.push_back(error);
for (absl::Status status : result.GetStatus()) status_.push_back(status);
}
bool LinterResult::ok() { return errors_.empty() && status_.empty(); }
void LinterResult::clear() { errors_.clear(); }
} // namespace zetasql::linter
<commit_msg>format<commit_after>//
// Copyright 2020 Google LLC
//
// 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 "src/lint_errors.h"
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "zetasql/base/status.h"
#include "zetasql/base/status_macros.h"
#include "zetasql/base/statusor.h"
#include "zetasql/public/parse_helpers.h"
#include "zetasql/public/parse_location.h"
namespace zetasql::linter {
std::string LintError::GetErrorMessage() { return message_; }
std::string LintError::ConstructPositionMessage() {
return absl::StrCat("In line ", line_, ", column ", column_, ": ");
}
void LintError::PrintError() {
if (filename_ == "") {
std::cout << ConstructPositionMessage() << GetErrorMessage() << std::endl;
} else {
std::cout << filename_ << ":" << ConstructPositionMessage()
<< GetErrorMessage() << std::endl;
}
}
void LinterResult::PrintResult() {
// Need to sort according to increasing line number
sort(errors_.begin(), errors_.end(),
[&](const LintError &a, const LintError &b) {
return a.GetLineNumber() < b.GetLineNumber();
});
for (LintError error : errors_) error.PrintError();
for (absl::Status status : status_) std::cerr << status << std::endl;
std::cout << "Linter results are printed" << std::endl;
}
LinterResult::LinterResult(const absl::Status &status) {
if (!status.ok()) status_.push_back(status);
}
absl::Status LinterResult::Add(ErrorCode type, absl::string_view filename,
absl::string_view sql, int character_location,
std::string message) {
ParseLocationPoint lp =
ParseLocationPoint::FromByteOffset(character_location);
ParseLocationTranslator lt(sql);
std::pair<int, int> error_pos;
ZETASQL_ASSIGN_OR_RETURN(error_pos, lt.GetLineAndColumnAfterTabExpansion(lp));
LintError t(type, filename, error_pos.first, error_pos.second, message);
errors_.push_back(t);
return absl::OkStatus();
}
void LinterResult::Add(ErrorCode type, absl::string_view sql,
int character_location, std::string message) {
Add(type, "", sql, character_location, message);
}
void LinterResult::Add(LinterResult result) {
for (LintError error : result.GetErrors()) errors_.push_back(error);
for (absl::Status status : result.GetStatus()) status_.push_back(status);
}
bool LinterResult::ok() { return errors_.empty() && status_.empty(); }
void LinterResult::clear() { errors_.clear(); }
} // namespace zetasql::linter
<|endoftext|> |
<commit_before>/*
* 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 <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
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "lua/session.h"
#include "lua/init.h"
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include "fiber.h"
#include "session.h"
#include "sio.h"
static const char *sessionlib_name = "box.session";
extern lua_State *root_L;
/**
* Return a unique monotonic session
* identifier. The identifier can be used
* to check whether or not a session is alive.
* 0 means there is no session (e.g.
* a procedure is running in a detached
* fiber).
*/
static int
lbox_session_id(struct lua_State *L)
{
lua_pushnumber(L, fiber->sid);
return 1;
}
/**
* Check whether or not a session exists.
*/
static int
lbox_session_exists(struct lua_State *L)
{
if (lua_gettop(L) != 1)
luaL_error(L, "session.exists(sid): bad arguments");
uint32_t sid = luaL_checkint(L, -1);
lua_pushnumber(L, session_exists(sid));
return 1;
}
/**
* Pretty print peer name.
*/
static int
lbox_session_peer(struct lua_State *L)
{
if (lua_gettop(L) > 1)
luaL_error(L, "session.peer(sid): bad arguments");
uint32_t sid = lua_gettop(L) == 1 ?
luaL_checkint(L, -1) : fiber->sid;
int fd = session_fd(sid);
struct sockaddr_in addr;
sio_getpeername(fd, &addr);
lua_pushstring(L, sio_strfaddr(&addr));
return 1;
}
struct lbox_session_trigger
{
struct session_trigger *trigger;
int ref;
};
static struct lbox_session_trigger on_connect =
{ &session_on_connect, LUA_NOREF};
static struct lbox_session_trigger on_disconnect =
{ &session_on_disconnect, LUA_NOREF};
static void
lbox_session_run_trigger(void *param)
{
struct lbox_session_trigger *trigger =
(struct lbox_session_trigger *) param;
/* Copy the referenced callable object object stack. */
lua_State *L = lua_newthread(tarantool_L);
int coro_ref = luaL_ref(tarantool_L, LUA_REGISTRYINDEX);
lua_rawgeti(tarantool_L, LUA_REGISTRYINDEX, trigger->ref);
/** Move the function to be called to the new coro. */
lua_xmove(tarantool_L, L, 1);
try {
lua_call(L, 0, 0);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
} catch (const Exception& e) {
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
throw;
} catch (...) {
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
tnt_raise(ClientError, ER_PROC_LUA, lua_tostring(L, -1));
}
}
static int
lbox_session_set_trigger(struct lua_State *L,
struct lbox_session_trigger *trigger)
{
if (lua_gettop(L) != 1 ||
(lua_type(L, -1) != LUA_TFUNCTION &&
lua_type(L, -1) != LUA_TNIL)) {
luaL_error(L, "session.on_connect(chunk): bad arguments");
}
/* Pop the old trigger */
if (trigger->ref != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, trigger->ref);
luaL_unref(L, LUA_REGISTRYINDEX, trigger->ref);
} else {
lua_pushnil(L);
}
/*
* Set or clear the trigger. Return the old value of the
* trigger.
*/
if (lua_type(L, -2) == LUA_TNIL) {
trigger->ref = LUA_NOREF;
trigger->trigger->trigger = NULL;
trigger->trigger->param = NULL;
} else {
/* Move the trigger to the top of the stack. */
lua_insert(L, -2);
/* Reference the new trigger. Pops it. */
trigger->ref = luaL_ref(L, LUA_REGISTRYINDEX);
trigger->trigger->trigger = lbox_session_run_trigger;
trigger->trigger->param = trigger;
}
/* Return the old trigger. */
return 1;
}
static int
lbox_session_on_connect(struct lua_State *L)
{
return lbox_session_set_trigger(L, &on_connect);
}
static int
lbox_session_on_disconnect(struct lua_State *L)
{
return lbox_session_set_trigger(L, &on_disconnect);
}
void
session_storage_cleanup(int sid)
{
int top = lua_gettop(root_L);
lua_pushliteral(root_L, "box");
lua_rawget(root_L, LUA_GLOBALSINDEX);
lua_pushliteral(root_L, "session");
lua_rawget(root_L, -2);
lua_getmetatable(root_L, -1);
lua_pushliteral(root_L, "aggregate_storage");
lua_rawget(root_L, -2);
lua_pushnil(root_L);
lua_rawseti(root_L, -2, sid);
lua_settop(root_L, top);
}
static const struct luaL_reg sessionlib[] = {
{"id", lbox_session_id},
{"exists", lbox_session_exists},
{"peer", lbox_session_peer},
{"on_connect", lbox_session_on_connect},
{"on_disconnect", lbox_session_on_disconnect},
{NULL, NULL}
};
void
tarantool_lua_session_init(struct lua_State *L)
{
luaL_register(L, sessionlib_name, sessionlib);
lua_pop(L, 1);
}
<commit_msg>gh-26: minor optimization of session destructor<commit_after>/*
* 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 <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
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "lua/session.h"
#include "lua/init.h"
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include "fiber.h"
#include "session.h"
#include "sio.h"
static const char *sessionlib_name = "box.session";
extern lua_State *root_L;
/**
* Return a unique monotonic session
* identifier. The identifier can be used
* to check whether or not a session is alive.
* 0 means there is no session (e.g.
* a procedure is running in a detached
* fiber).
*/
static int
lbox_session_id(struct lua_State *L)
{
lua_pushnumber(L, fiber->sid);
return 1;
}
/**
* Check whether or not a session exists.
*/
static int
lbox_session_exists(struct lua_State *L)
{
if (lua_gettop(L) != 1)
luaL_error(L, "session.exists(sid): bad arguments");
uint32_t sid = luaL_checkint(L, -1);
lua_pushnumber(L, session_exists(sid));
return 1;
}
/**
* Pretty print peer name.
*/
static int
lbox_session_peer(struct lua_State *L)
{
if (lua_gettop(L) > 1)
luaL_error(L, "session.peer(sid): bad arguments");
uint32_t sid = lua_gettop(L) == 1 ?
luaL_checkint(L, -1) : fiber->sid;
int fd = session_fd(sid);
struct sockaddr_in addr;
sio_getpeername(fd, &addr);
lua_pushstring(L, sio_strfaddr(&addr));
return 1;
}
struct lbox_session_trigger
{
struct session_trigger *trigger;
int ref;
};
static struct lbox_session_trigger on_connect =
{ &session_on_connect, LUA_NOREF};
static struct lbox_session_trigger on_disconnect =
{ &session_on_disconnect, LUA_NOREF};
static void
lbox_session_run_trigger(void *param)
{
struct lbox_session_trigger *trigger =
(struct lbox_session_trigger *) param;
/* Copy the referenced callable object object stack. */
lua_State *L = lua_newthread(tarantool_L);
int coro_ref = luaL_ref(tarantool_L, LUA_REGISTRYINDEX);
lua_rawgeti(tarantool_L, LUA_REGISTRYINDEX, trigger->ref);
/** Move the function to be called to the new coro. */
lua_xmove(tarantool_L, L, 1);
try {
lua_call(L, 0, 0);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
} catch (const Exception& e) {
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
throw;
} catch (...) {
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, coro_ref);
tnt_raise(ClientError, ER_PROC_LUA, lua_tostring(L, -1));
}
}
static int
lbox_session_set_trigger(struct lua_State *L,
struct lbox_session_trigger *trigger)
{
if (lua_gettop(L) != 1 ||
(lua_type(L, -1) != LUA_TFUNCTION &&
lua_type(L, -1) != LUA_TNIL)) {
luaL_error(L, "session.on_connect(chunk): bad arguments");
}
/* Pop the old trigger */
if (trigger->ref != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, trigger->ref);
luaL_unref(L, LUA_REGISTRYINDEX, trigger->ref);
} else {
lua_pushnil(L);
}
/*
* Set or clear the trigger. Return the old value of the
* trigger.
*/
if (lua_type(L, -2) == LUA_TNIL) {
trigger->ref = LUA_NOREF;
trigger->trigger->trigger = NULL;
trigger->trigger->param = NULL;
} else {
/* Move the trigger to the top of the stack. */
lua_insert(L, -2);
/* Reference the new trigger. Pops it. */
trigger->ref = luaL_ref(L, LUA_REGISTRYINDEX);
trigger->trigger->trigger = lbox_session_run_trigger;
trigger->trigger->param = trigger;
}
/* Return the old trigger. */
return 1;
}
static int
lbox_session_on_connect(struct lua_State *L)
{
return lbox_session_set_trigger(L, &on_connect);
}
static int
lbox_session_on_disconnect(struct lua_State *L)
{
return lbox_session_set_trigger(L, &on_disconnect);
}
void
session_storage_cleanup(int sid)
{
static int ref = LUA_REFNIL;
int top = lua_gettop(root_L);
if (ref == LUA_REFNIL) {
lua_getfield(root_L, LUA_GLOBALSINDEX, "box");
lua_getfield(root_L, -1, "session");
lua_getmetatable(root_L, -1);
lua_getfield(root_L, -1, "aggregate_storage");
ref = luaL_ref(root_L, LUA_REGISTRYINDEX);
}
lua_rawgeti(root_L, LUA_REGISTRYINDEX, ref);
lua_pushnil(root_L);
lua_rawseti(root_L, -2, sid);
lua_settop(root_L, top);
}
static const struct luaL_reg sessionlib[] = {
{"id", lbox_session_id},
{"exists", lbox_session_exists},
{"peer", lbox_session_peer},
{"on_connect", lbox_session_on_connect},
{"on_disconnect", lbox_session_on_disconnect},
{NULL, NULL}
};
void
tarantool_lua_session_init(struct lua_State *L)
{
luaL_register(L, sessionlib_name, sessionlib);
lua_pop(L, 1);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"
#include <string>
namespace libtorrent
{
std::string make_magnet_uri(torrent_handle const& handle)
{
if (!handle.is_valid()) return "";
char ret[1024];
int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s"
, base32encode(std::string((char*)handle.info_hash().begin(), 20)).c_str());
std::string name = handle.name();
if (!name.empty())
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s"
, escape_string(name.c_str(), name.length()).c_str());
char const* tracker = 0;
torrent_status st = handle.status();
if (!st.current_tracker.empty())
{
tracker = st.current_tracker.c_str();
}
else
{
std::vector<announce_entry> const& tr = handle.trackers();
if (!tr.empty()) tracker = tr[0].url.c_str();
}
if (tracker)
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s"
, escape_string(tracker, strlen(tracker)).c_str());
return ret;
}
std::string make_magnet_uri(torrent_info const& info)
{
char ret[1024];
int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s"
, base32encode(std::string((char*)info.info_hash().begin(), 20)).c_str());
std::string const& name = info.name();
if (!name.empty())
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s"
, escape_string(name.c_str(), name.length()).c_str());
std::vector<announce_entry> const& tr = info.trackers();
if (!tr.empty())
{
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s"
, escape_string(tr[0].url.c_str(), tr[0].url.length()).c_str());
}
return ret;
}
#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, std::string const& save_path
, storage_mode_t storage_mode
, bool paused
, storage_constructor_type sc
, void* userdata)
{
std::string name;
std::string tracker;
error_code ec;
std::string display_name = url_has_argument(uri, "dn");
if (!display_name.empty()) name = unescape_string(display_name.c_str(), ec);
std::string tracker_string = url_has_argument(uri, "tr");
if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec);
std::string btih = url_has_argument(uri, "xt");
if (btih.empty()) return torrent_handle();
if (btih.compare(0, 9, "urn:btih:") != 0) return torrent_handle();
sha1_hash info_hash;
if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);
else info_hash.assign(base32decode(btih.substr(9)));
return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
, name.empty() ? 0 : name.c_str(), save_path, entry()
, storage_mode, paused, sc, userdata);
}
#endif
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, add_torrent_params p)
{
error_code ec;
torrent_handle ret = add_magnet_uri(ses, uri, p, ec);
if (ec) throw libtorrent_exception(ec);
return ret;
}
#endif
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, add_torrent_params p, error_code& ec)
{
std::string name;
std::string tracker;
error_code e;
std::string display_name = url_has_argument(uri, "dn");
if (!display_name.empty()) name = unescape_string(display_name.c_str(), e);
std::string tracker_string = url_has_argument(uri, "tr");
if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), e);
std::string btih = url_has_argument(uri, "xt");
if (btih.empty())
{
ec = error_code(errors::missing_info_hash_in_uri, libtorrent_category);
return torrent_handle();
}
if (btih.compare(0, 9, "urn:btih:") != 0)
{
ec = error_code(errors::missing_info_hash_in_uri, libtorrent_category);
return torrent_handle();
}
sha1_hash info_hash;
if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);
else info_hash.assign(base32decode(btih.substr(9)));
if (!tracker.empty()) p.tracker_url = tracker.c_str();
p.info_hash = info_hash;
if (!name.empty()) p.name = name.c_str();
return ses.add_torrent(p, ec);
}
}
<commit_msg>clean up in magnet_uri.cpp<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/torrent_handle.hpp"
#include "libtorrent/escape_string.hpp"
#include <string>
namespace libtorrent
{
std::string make_magnet_uri(torrent_handle const& handle)
{
if (!handle.is_valid()) return "";
char ret[1024];
sha1_hash const& ih = handle.info_hash();
int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s"
, base32encode(std::string((char const*)&ih[0], 20)).c_str());
std::string name = handle.name();
if (!name.empty())
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s"
, escape_string(name.c_str(), name.length()).c_str());
char const* tracker = 0;
torrent_status st = handle.status();
if (!st.current_tracker.empty())
{
tracker = st.current_tracker.c_str();
}
else
{
std::vector<announce_entry> const& tr = handle.trackers();
if (!tr.empty()) tracker = tr[0].url.c_str();
}
if (tracker)
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s"
, escape_string(tracker, strlen(tracker)).c_str());
return ret;
}
std::string make_magnet_uri(torrent_info const& info)
{
char ret[1024];
sha1_hash const& ih = info.info_hash();
int num_chars = snprintf(ret, sizeof(ret), "magnet:?xt=urn:btih:%s"
, base32encode(std::string((char*)&ih[0], 20)).c_str());
std::string const& name = info.name();
if (!name.empty())
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&dn=%s"
, escape_string(name.c_str(), name.length()).c_str());
std::vector<announce_entry> const& tr = info.trackers();
if (!tr.empty())
{
num_chars += snprintf(ret + num_chars, sizeof(ret) - num_chars, "&tr=%s"
, escape_string(tr[0].url.c_str(), tr[0].url.length()).c_str());
}
return ret;
}
#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, std::string const& save_path
, storage_mode_t storage_mode
, bool paused
, storage_constructor_type sc
, void* userdata)
{
std::string name;
std::string tracker;
error_code ec;
std::string display_name = url_has_argument(uri, "dn");
if (!display_name.empty()) name = unescape_string(display_name.c_str(), ec);
std::string tracker_string = url_has_argument(uri, "tr");
if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), ec);
std::string btih = url_has_argument(uri, "xt");
if (btih.empty()) return torrent_handle();
if (btih.compare(0, 9, "urn:btih:") != 0) return torrent_handle();
sha1_hash info_hash;
if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);
else info_hash.assign(base32decode(btih.substr(9)));
return ses.add_torrent(tracker.empty() ? 0 : tracker.c_str(), info_hash
, name.empty() ? 0 : name.c_str(), save_path, entry()
, storage_mode, paused, sc, userdata);
}
#endif
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, add_torrent_params p)
{
error_code ec;
torrent_handle ret = add_magnet_uri(ses, uri, p, ec);
if (ec) throw libtorrent_exception(ec);
return ret;
}
#endif
torrent_handle add_magnet_uri(session& ses, std::string const& uri
, add_torrent_params p, error_code& ec)
{
std::string name;
std::string tracker;
error_code e;
std::string display_name = url_has_argument(uri, "dn");
if (!display_name.empty()) name = unescape_string(display_name.c_str(), e);
std::string tracker_string = url_has_argument(uri, "tr");
if (!tracker_string.empty()) tracker = unescape_string(tracker_string.c_str(), e);
std::string btih = url_has_argument(uri, "xt");
if (btih.empty())
{
ec = error_code(errors::missing_info_hash_in_uri, libtorrent_category);
return torrent_handle();
}
if (btih.compare(0, 9, "urn:btih:") != 0)
{
ec = error_code(errors::missing_info_hash_in_uri, libtorrent_category);
return torrent_handle();
}
sha1_hash info_hash;
if (btih.size() == 40 + 9) from_hex(&btih[9], 40, (char*)&info_hash[0]);
else info_hash.assign(base32decode(btih.substr(9)));
if (!tracker.empty()) p.tracker_url = tracker.c_str();
p.info_hash = info_hash;
if (!name.empty()) p.name = name.c_str();
return ses.add_torrent(p, ec);
}
}
<|endoftext|> |
<commit_before>/*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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 "lib/logger.h"
#include "global.h"
#include "main_window.h"
#include "models/session.h"
#include "views/console.h"
#include "views/jobs_view.h"
#include "views/session_dialog.h"
#include "views/session_view.h"
const int MainWindow::CANCEL_JOBS_TIMEOUT_IN_MS = 30000;
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags),
m_sessionTabs(new QTabWidget(this)),
m_jobsView(new JobsView(this))
{
setWindowTitle(SL_APP_NAME);
setCentralWidget(m_sessionTabs);
m_jobsDock = new QDockWidget("Jobs", this);
m_jobsDock->setObjectName("jobs dock");
m_jobsScroll = new QScrollArea;
m_jobsScroll->setWidget(m_jobsView);
m_jobsScroll->setWidgetResizable(true);
m_jobsDock->setWidget(m_jobsScroll);
addDockWidget(Qt::BottomDockWidgetArea, m_jobsDock);
m_consoleDock = new QDockWidget("Log", this);
m_consoleDock->setObjectName("console dock");
m_consoleDock->setWidget(Console::Instance());
addDockWidget(Qt::BottomDockWidgetArea, m_consoleDock);
tabifyDockWidget(m_jobsDock, m_consoleDock);
setTabPosition(Qt::BottomDockWidgetArea, QTabWidget::North);
CreateMenus();
ReadSettings();
LOG_INFO("STARTING DS3 Browser Session");
}
int
MainWindow::GetNumActiveJobs() const
{
int num = 0;
for (int i = 0; i < m_sessionViews.size(); i++) {
num += m_sessionViews[i]->GetNumActiveJobs();
}
return num;
}
void
MainWindow::CreateSession()
{
SessionDialog* sessionDialog = static_cast<SessionDialog*>(sender());
Session* session = new Session(sessionDialog->GetSession());
SessionView* sessionView = new SessionView(session, m_jobsView);
m_sessionViews << sessionView;
m_sessionTabs->addTab(sessionView, session->GetHost());
// The MainWindow will not have been shown for the first time when
// creating the initial session.
show();
}
void
MainWindow::closeEvent(QCloseEvent* event)
{
if (GetNumActiveJobs() > 0) {
QString title = "Active Jobs In Progress";
QString msg = "There are active jobs still in progress. " \
"Are you sure wish to cancel those jobs and " \
"quit the applcation?";
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, title, msg,
QMessageBox::Ok |
QMessageBox::Cancel,
QMessageBox::Cancel);
if (ret == QMessageBox::Ok) {
CancelActiveJobs();
} else {
event->ignore();
return;
}
}
LOG_INFO("CLOSING DS3 Browser Session");
QSettings settings;
settings.setValue("mainWindow/geometry", saveGeometry());
settings.setValue("mainWindow/windowState", saveState());
QMainWindow::closeEvent(event);
}
void
MainWindow::ReadSettings()
{
QSettings settings;
restoreGeometry(settings.value("mainWindow/geometry").toByteArray());
restoreState(settings.value("mainWindow/windowState").toByteArray());
}
void
MainWindow::CreateMenus()
{
m_aboutAction = new QAction(tr("&About %1").arg(APP_NAME), this);
connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(About()));
m_settingsAction = new QAction(tr("&Settings"), this);
connect(m_settingsAction, SIGNAL(triggered()), this, SLOT(Settings()));
m_editMenu = new QMenu(tr("&Edit"), this);
m_editMenu->addAction(m_settingsAction);
menuBar()->addMenu(m_editMenu);
m_viewMenu = new QMenu(tr("&View"), this);
m_viewMenu->addAction(m_consoleDock->toggleViewAction());
m_viewMenu->addAction(m_jobsDock->toggleViewAction());
menuBar()->addMenu(m_viewMenu);
m_helpMenu = new QMenu(tr("&Help"), this);
m_helpMenu->addAction(m_aboutAction);
menuBar()->addMenu(m_helpMenu);
}
void
MainWindow::CancelActiveJobs()
{
for (int i = 0; i < m_sessionViews.size(); i++) {
m_sessionViews[i]->CancelActiveJobs();
}
// All jobs are currently run via QtConcurrent::run, which uses
// the global thread pool. This will need to be modified if certain
// job tasks are ever switched to using a custom thread pool.
bool ret = QThreadPool::globalInstance()->waitForDone(CANCEL_JOBS_TIMEOUT_IN_MS);
if (!ret) {
LOG_ERROR("ERROR: TIMED OUT waiting for all jobs to stop");
}
}
void
MainWindow::About()
{
QString text = tr("<b>%1</b><br/>Version %2")
.arg(APP_NAME).arg(APP_VERSION);
QMessageBox::about(this, tr("About %1").arg(APP_NAME), text);
}
void
MainWindow::Settings()
{
m_tabs = new QTabWidget;
m_tabs->setWindowTitle(tr("Settings"));
CreateLoggingPage();
const QString& logName = "Logging";
m_tabs->addTab(m_logging, logName);
m_tabs->setWindowModality(Qt::WindowModal);
m_tabs->setFixedHeight(m_tabs->sizeHint().height());
m_tabs->setFixedWidth(m_tabs->sizeHint().width()+100);
m_tabs->show();
}
void
MainWindow::CreateLoggingPage()
{
QSettings settings;
// Default log name based on app name
QString logName = APP_NAME;
logName.replace(" ", "_");
logName = logName.toCaseFolded()+".log";
m_logFile = settings.value("mainWindow/logFileName", QDir::homePath()+"/"+logName).toString();
bool loggingEnabled = settings.value("mainWindow/loggingEnabled", true).toBool();
m_logFileSize = settings.value("mainWindow/logFileSize", 52428800).toDouble();
m_logNumberLimit = settings.value("mainWindow/logNumberLimit", 10).toInt();
m_logging = new QWidget;
m_enableLoggingBox = new QCheckBox;
m_fileSizeInput = new QLineEdit;
m_fileSizeSuffix = new QComboBox;
m_fileInputDialog = new QLineEdit;
m_logNumberInput = new QLineEdit;
m_browse = new QPushButton;
QPushButton* apply = new QPushButton;
QDialogButtonBox* buttons = new QDialogButtonBox;
QGridLayout* layout = new QGridLayout(m_logging);
m_logging->setWindowTitle(tr("Settings"));
m_enableLoggingBox->setCheckState(Qt::Unchecked);
if(loggingEnabled)
m_enableLoggingBox->setCheckState(Qt::Checked);
m_enableLoggingBox->setText("Enable Logging to Log File");
connect(m_enableLoggingBox, SIGNAL(stateChanged(int)), this, SLOT(ChangedEnabled(int)));
m_fileSizeInput->setText(FormatFileSize());
m_fileSizeInput->setAlignment(Qt::AlignRight);
m_fileSizeSuffix->addItem(tr("MB"));
m_fileSizeSuffix->addItem(tr("GB"));
if(m_logFileSizeSuffix == "MB") {
m_fileSizeSuffix->setCurrentIndex(0);
} else {
m_fileSizeSuffix->setCurrentIndex(1);
}
m_logNumberInput->setText(QString::number(m_logNumberLimit));
m_logNumberInput->setAlignment(Qt::AlignRight);
m_fileInputDialog->setText(m_logFile);
m_fileInputDialog->setAlignment(Qt::AlignJustify);
apply->setText("Apply");
m_browse->setText("Browse");
buttons->addButton("Cancel", QDialogButtonBox::RejectRole);
buttons->addButton(apply, QDialogButtonBox::ApplyRole);
connect(m_browse, SIGNAL(clicked(bool)), this, SLOT(ChooseLogFile()));
connect(buttons, SIGNAL(rejected()), this, SLOT(ClosePreferences()));
connect(apply, SIGNAL(clicked(bool)), this, SLOT(ApplyChanges()));
layout->setContentsMargins (6, 6, 6, 6);
layout->setHorizontalSpacing(6);
layout->setVerticalSpacing(6);
layout->addWidget(new QLabel("Location:"), 1, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_fileInputDialog, 1, 2, 1, 1);
layout->addWidget(m_browse, 1, 3, 1, 1, Qt::AlignLeft);
layout->addWidget(new QLabel("Maximum Log Size:"), 2, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_fileSizeInput, 2, 2, 1, 1);
layout->addWidget(m_fileSizeSuffix, 2, 3, 1, 1, Qt::AlignLeft);
layout->addWidget(new QLabel("Maximum Number of Saved Logs:"), 3, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_logNumberInput, 3, 2, 1, 1);
layout->addWidget(m_enableLoggingBox, 4, 2, 1, 1, Qt::AlignLeft);
layout->addWidget(buttons, 5, 3, 1, 1, Qt::AlignRight);
m_logging->setLayout(layout);
ChangedEnabled(loggingEnabled);
}
void
MainWindow::ChooseLogFile()
{
QSettings settings;
m_logFileBrowser = new QWidget;
QBoxLayout* layout = new QVBoxLayout(m_logFileBrowser);
QFileDialog* fileDialog = new QFileDialog;
QString defaultFilter("Text files (*.txt)");
fileDialog->setAcceptMode(QFileDialog::AcceptSave);
fileDialog->setWindowTitle("Log File Location");
fileDialog->selectNameFilter(defaultFilter);
fileDialog->selectFile(m_logFile);
if(fileDialog->exec()) {
layout->addWidget(fileDialog);
m_logFileBrowser->setLayout(layout);
m_logFile = fileDialog->selectedFiles()[0];
m_fileInputDialog->setText(m_logFile);
delete m_logFileBrowser;
}
}
void
MainWindow::ClosePreferences()
{
delete m_tabs;
}
void
MainWindow::ApplyChanges()
{
QSettings settings;
settings.setValue("mainWindow/loggingEnabled", m_enableLoggingBox->checkState());
m_logFile = m_fileInputDialog->text();
settings.setValue("mainWindow/logFileName", m_logFile);
m_logFileSizeSuffix = m_fileSizeSuffix->currentText();
settings.setValue("mainWindow/logFileSize", DeFormatFileSize());
m_logNumberLimit = m_logNumberInput->text().toInt();
if(m_logNumberLimit > 0) {
settings.setValue("mainWindow/logNumberLimit", m_logNumberLimit);
}
ClosePreferences();
}
QString
MainWindow::FormatFileSize()
{
double sizeHolder = m_logFileSize;
m_logFileSizeSuffix = "B";
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "KB";
}
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "MB";
}
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "GB";
}
if(m_logFileSizeSuffix == "KB" && sizeHolder/1024 >= 0.01) {
sizeHolder/=1024.0;
m_logFileSizeSuffix = "MB";
} else if(m_logFileSizeSuffix == "KB" && sizeHolder/1024 < 0.01){
sizeHolder = 50;
m_logFileSizeSuffix = "MB";
}
// Round to two decimal places
double ret = ceil((sizeHolder*100.0)-0.49)/100.0;
return QString::number(ret);
}
double
MainWindow::DeFormatFileSize()
{
double sizeHolder = m_fileSizeInput->text().toDouble();
if((sizeHolder < 0.01 && m_logFileSizeSuffix == "MB") || (sizeHolder*1024.0 < 0.01 && m_logFileSizeSuffix == "GB")) {
sizeHolder = 50;
m_logFileSizeSuffix = "MB";
}
if(m_logFileSizeSuffix == "GB") {
sizeHolder *= 1024.0;
m_logFileSizeSuffix = "MB";
}
if(m_logFileSizeSuffix == "MB") {
sizeHolder *= 1024.0;
m_logFileSizeSuffix = "KB";
}
if(m_logFileSizeSuffix == "KB") {
sizeHolder *= 1024.0;
}
double ret = ceil((sizeHolder*100.0)-0.49)/100.0;
if(ret < 10485)
ret = 52428800;
m_logFileSize = ret;
return ret;
}
void
MainWindow::ChangedEnabled(int state)
{
m_fileSizeInput->setEnabled(state);
m_fileSizeSuffix->setEnabled(state);
m_fileInputDialog->setEnabled(state);
m_logNumberInput->setEnabled(state);
m_browse->setEnabled(state);
}<commit_msg>Better text formatting for settings menu<commit_after>/*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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 "lib/logger.h"
#include "global.h"
#include "main_window.h"
#include "models/session.h"
#include "views/console.h"
#include "views/jobs_view.h"
#include "views/session_dialog.h"
#include "views/session_view.h"
const int MainWindow::CANCEL_JOBS_TIMEOUT_IN_MS = 30000;
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags),
m_sessionTabs(new QTabWidget(this)),
m_jobsView(new JobsView(this))
{
setWindowTitle(SL_APP_NAME);
setCentralWidget(m_sessionTabs);
m_jobsDock = new QDockWidget("Jobs", this);
m_jobsDock->setObjectName("jobs dock");
m_jobsScroll = new QScrollArea;
m_jobsScroll->setWidget(m_jobsView);
m_jobsScroll->setWidgetResizable(true);
m_jobsDock->setWidget(m_jobsScroll);
addDockWidget(Qt::BottomDockWidgetArea, m_jobsDock);
m_consoleDock = new QDockWidget("Log", this);
m_consoleDock->setObjectName("console dock");
m_consoleDock->setWidget(Console::Instance());
addDockWidget(Qt::BottomDockWidgetArea, m_consoleDock);
tabifyDockWidget(m_jobsDock, m_consoleDock);
setTabPosition(Qt::BottomDockWidgetArea, QTabWidget::North);
CreateMenus();
ReadSettings();
LOG_INFO("STARTING DS3 Browser Session");
}
int
MainWindow::GetNumActiveJobs() const
{
int num = 0;
for (int i = 0; i < m_sessionViews.size(); i++) {
num += m_sessionViews[i]->GetNumActiveJobs();
}
return num;
}
void
MainWindow::CreateSession()
{
SessionDialog* sessionDialog = static_cast<SessionDialog*>(sender());
Session* session = new Session(sessionDialog->GetSession());
SessionView* sessionView = new SessionView(session, m_jobsView);
m_sessionViews << sessionView;
m_sessionTabs->addTab(sessionView, session->GetHost());
// The MainWindow will not have been shown for the first time when
// creating the initial session.
show();
}
void
MainWindow::closeEvent(QCloseEvent* event)
{
if (GetNumActiveJobs() > 0) {
QString title = "Active Jobs In Progress";
QString msg = "There are active jobs still in progress. " \
"Are you sure wish to cancel those jobs and " \
"quit the applcation?";
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, title, msg,
QMessageBox::Ok |
QMessageBox::Cancel,
QMessageBox::Cancel);
if (ret == QMessageBox::Ok) {
CancelActiveJobs();
} else {
event->ignore();
return;
}
}
LOG_INFO("CLOSING DS3 Browser Session");
QSettings settings;
settings.setValue("mainWindow/geometry", saveGeometry());
settings.setValue("mainWindow/windowState", saveState());
QMainWindow::closeEvent(event);
}
void
MainWindow::ReadSettings()
{
QSettings settings;
restoreGeometry(settings.value("mainWindow/geometry").toByteArray());
restoreState(settings.value("mainWindow/windowState").toByteArray());
}
void
MainWindow::CreateMenus()
{
m_aboutAction = new QAction(tr("&About %1").arg(APP_NAME), this);
connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(About()));
m_settingsAction = new QAction(tr("&Settings"), this);
connect(m_settingsAction, SIGNAL(triggered()), this, SLOT(Settings()));
m_editMenu = new QMenu(tr("&Edit"), this);
m_editMenu->addAction(m_settingsAction);
menuBar()->addMenu(m_editMenu);
m_viewMenu = new QMenu(tr("&View"), this);
m_viewMenu->addAction(m_consoleDock->toggleViewAction());
m_viewMenu->addAction(m_jobsDock->toggleViewAction());
menuBar()->addMenu(m_viewMenu);
m_helpMenu = new QMenu(tr("&Help"), this);
m_helpMenu->addAction(m_aboutAction);
menuBar()->addMenu(m_helpMenu);
}
void
MainWindow::CancelActiveJobs()
{
for (int i = 0; i < m_sessionViews.size(); i++) {
m_sessionViews[i]->CancelActiveJobs();
}
// All jobs are currently run via QtConcurrent::run, which uses
// the global thread pool. This will need to be modified if certain
// job tasks are ever switched to using a custom thread pool.
bool ret = QThreadPool::globalInstance()->waitForDone(CANCEL_JOBS_TIMEOUT_IN_MS);
if (!ret) {
LOG_ERROR("ERROR: TIMED OUT waiting for all jobs to stop");
}
}
void
MainWindow::About()
{
QString text = tr("<b>%1</b><br/>Version %2")
.arg(APP_NAME).arg(APP_VERSION);
QMessageBox::about(this, tr("About %1").arg(APP_NAME), text);
}
void
MainWindow::Settings()
{
m_tabs = new QTabWidget;
m_tabs->setWindowTitle(tr("Settings"));
CreateLoggingPage();
const QString& logName = "Logging";
m_tabs->addTab(m_logging, logName);
m_tabs->setWindowModality(Qt::WindowModal);
m_tabs->setFixedHeight(m_tabs->sizeHint().height());
m_tabs->setFixedWidth(m_tabs->sizeHint().width()+100);
m_tabs->show();
}
void
MainWindow::CreateLoggingPage()
{
QSettings settings;
// Default log name based on app name
QString logName = APP_NAME;
logName.replace(" ", "_");
logName = logName.toCaseFolded()+".log";
m_logFile = settings.value("mainWindow/logFileName", QDir::homePath()+"/"+logName).toString();
bool loggingEnabled = settings.value("mainWindow/loggingEnabled", true).toBool();
m_logFileSize = settings.value("mainWindow/logFileSize", 52428800).toDouble();
m_logNumberLimit = settings.value("mainWindow/logNumberLimit", 10).toInt();
m_logging = new QWidget;
m_enableLoggingBox = new QCheckBox;
m_fileSizeInput = new QLineEdit;
m_fileSizeSuffix = new QComboBox;
m_fileInputDialog = new QLineEdit;
m_logNumberInput = new QLineEdit;
m_browse = new QPushButton;
QPushButton* apply = new QPushButton;
QDialogButtonBox* buttons = new QDialogButtonBox;
QGridLayout* layout = new QGridLayout(m_logging);
m_logging->setWindowTitle(tr("Settings"));
m_enableLoggingBox->setCheckState(Qt::Unchecked);
if(loggingEnabled)
m_enableLoggingBox->setCheckState(Qt::Checked);
m_enableLoggingBox->setText("Enable Logging to Log File");
connect(m_enableLoggingBox, SIGNAL(stateChanged(int)), this, SLOT(ChangedEnabled(int)));
m_fileSizeInput->setText(FormatFileSize());
m_fileSizeInput->setAlignment(Qt::AlignRight);
m_fileSizeSuffix->addItem(tr("MB"));
m_fileSizeSuffix->addItem(tr("GB"));
if(m_logFileSizeSuffix == "MB") {
m_fileSizeSuffix->setCurrentIndex(0);
} else {
m_fileSizeSuffix->setCurrentIndex(1);
}
m_logNumberInput->setText(QString::number(m_logNumberLimit));
m_logNumberInput->setAlignment(Qt::AlignRight);
m_fileInputDialog->setText(m_logFile);
m_fileInputDialog->setAlignment(Qt::AlignJustify);
apply->setText("Apply");
m_browse->setText("Browse");
buttons->addButton("Cancel", QDialogButtonBox::RejectRole);
buttons->addButton(apply, QDialogButtonBox::ApplyRole);
connect(m_browse, SIGNAL(clicked(bool)), this, SLOT(ChooseLogFile()));
connect(buttons, SIGNAL(rejected()), this, SLOT(ClosePreferences()));
connect(apply, SIGNAL(clicked(bool)), this, SLOT(ApplyChanges()));
layout->setContentsMargins (6, 6, 6, 6);
layout->setHorizontalSpacing(6);
layout->setVerticalSpacing(6);
layout->addWidget(new QLabel("Location:"), 1, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_fileInputDialog, 1, 2, 1, 1);
layout->addWidget(m_browse, 1, 3, 1, 1, Qt::AlignLeft);
layout->addWidget(new QLabel("Maximum Log Size:"), 2, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_fileSizeInput, 2, 2, 1, 1);
layout->addWidget(m_fileSizeSuffix, 2, 3, 1, 1, Qt::AlignLeft);
QLabel* temp = new QLabel(tr("Maximum Number\nof Saved Logs:"));
temp->setAlignment(Qt::AlignRight);
layout->addWidget(temp, 3, 1, 1, 1, Qt::AlignRight);
layout->addWidget(m_logNumberInput, 3, 2, 1, 1);
layout->addWidget(m_enableLoggingBox, 4, 2, 1, 1, Qt::AlignLeft);
layout->addWidget(buttons, 5, 3, 1, 1, Qt::AlignRight);
m_logging->setLayout(layout);
ChangedEnabled(loggingEnabled);
}
void
MainWindow::ChooseLogFile()
{
QSettings settings;
m_logFileBrowser = new QWidget;
QBoxLayout* layout = new QVBoxLayout(m_logFileBrowser);
QFileDialog* fileDialog = new QFileDialog;
QString defaultFilter("Text files (*.txt)");
fileDialog->setAcceptMode(QFileDialog::AcceptSave);
fileDialog->setWindowTitle("Log File Location");
fileDialog->selectNameFilter(defaultFilter);
fileDialog->selectFile(m_logFile);
if(fileDialog->exec()) {
layout->addWidget(fileDialog);
m_logFileBrowser->setLayout(layout);
m_logFile = fileDialog->selectedFiles()[0];
m_fileInputDialog->setText(m_logFile);
delete m_logFileBrowser;
}
}
void
MainWindow::ClosePreferences()
{
delete m_tabs;
}
void
MainWindow::ApplyChanges()
{
QSettings settings;
settings.setValue("mainWindow/loggingEnabled", m_enableLoggingBox->checkState());
m_logFile = m_fileInputDialog->text();
settings.setValue("mainWindow/logFileName", m_logFile);
m_logFileSizeSuffix = m_fileSizeSuffix->currentText();
settings.setValue("mainWindow/logFileSize", DeFormatFileSize());
m_logNumberLimit = m_logNumberInput->text().toInt();
if(m_logNumberLimit > 0) {
settings.setValue("mainWindow/logNumberLimit", m_logNumberLimit);
}
ClosePreferences();
}
QString
MainWindow::FormatFileSize()
{
double sizeHolder = m_logFileSize;
m_logFileSizeSuffix = "B";
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "KB";
}
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "MB";
}
if(sizeHolder >= 1024) {
sizeHolder /= 1024.0;
m_logFileSizeSuffix = "GB";
}
if(m_logFileSizeSuffix == "KB" && sizeHolder/1024 >= 0.01) {
sizeHolder/=1024.0;
m_logFileSizeSuffix = "MB";
} else if(m_logFileSizeSuffix == "KB" && sizeHolder/1024 < 0.01){
sizeHolder = 50;
m_logFileSizeSuffix = "MB";
}
// Round to two decimal places
double ret = ceil((sizeHolder*100.0)-0.49)/100.0;
return QString::number(ret);
}
double
MainWindow::DeFormatFileSize()
{
double sizeHolder = m_fileSizeInput->text().toDouble();
if((sizeHolder < 0.01 && m_logFileSizeSuffix == "MB") || (sizeHolder*1024.0 < 0.01 && m_logFileSizeSuffix == "GB")) {
sizeHolder = 50;
m_logFileSizeSuffix = "MB";
}
if(m_logFileSizeSuffix == "GB") {
sizeHolder *= 1024.0;
m_logFileSizeSuffix = "MB";
}
if(m_logFileSizeSuffix == "MB") {
sizeHolder *= 1024.0;
m_logFileSizeSuffix = "KB";
}
if(m_logFileSizeSuffix == "KB") {
sizeHolder *= 1024.0;
}
double ret = ceil((sizeHolder*100.0)-0.49)/100.0;
if(ret < 10485)
ret = 52428800;
m_logFileSize = ret;
return ret;
}
void
MainWindow::ChangedEnabled(int state)
{
m_fileSizeInput->setEnabled(state);
m_fileSizeSuffix->setEnabled(state);
m_fileInputDialog->setEnabled(state);
m_logNumberInput->setEnabled(state);
m_browse->setEnabled(state);
}<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2016
**
** This file is generated by the Magus toolkit
**
** 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
#include "stdafx.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QFile>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QCloseEvent>
#include <QDockWidget>
#include <QSettings>
#include <QFileDialog>
#include <QStandardPaths>
#include <QSettings>
#include <QDebug>
#include <QMessageBox>
#include "lightwidget.h"
#include "ogremanager.h"
#include "ogrewidget.h"
#include "objimporter.h"
#include "objexporter.h"
#include "OgreMesh2Serializer.h"
#include "batchconversiondialog.h"
#define _STR(x) #x
#define STR(X) _STR(x)
MainWindow::MainWindow()
{
ui = new Ui::MainWindow;
ui->setupUi(this);
mOgreManager = new OgreManager;
mOgreWidget = new OgreWidget;
setCentralWidget(mOgreWidget);
mOgreManager->registerOgreWidget(mOgreWidget);
mOgreWidget->createRenderWindow(mOgreManager);
mOgreManager->initialize();
mOgreWidget->createCompositor();
mTimer = new QTimer(this);
mTimer->setInterval(16);
connect(mTimer, &QTimer::timeout, this, &MainWindow::Tick);
createDockWindows();
// Set the title
setWindowTitle("Ogre v2 Mesh Viewer v" STR(APP_VERSION_NUMBER));
readSettings();
connect(mOgreManager, &OgreManager::sceneCreated, this, &MainWindow::onSceneLoaded);
// actions
connect(ui->actionOpenOgreMesh, &QAction::triggered, this, &MainWindow::actionOpenMesh);
connect(ui->actionSaveOgreMesh, &QAction::triggered, this, &MainWindow::actionSaveMesh);
connect(ui->actionImportObj, &QAction::triggered, this, &MainWindow::actionImportObj);
connect(ui->actionExportObj, &QAction::triggered, this, &MainWindow::actionExportObj);
connect(ui->actionBatchConverter, &QAction::triggered, this, &MainWindow::actionBatchConverter);
connect(ui->actionExit, &QAction::triggered, this, &MainWindow::doQuitMenuAction);
}
MainWindow::~MainWindow()
{
delete mOgreManager;
delete ui;
}
void MainWindow::closeEvent( QCloseEvent* event )
{
mIsClosing = true;
mTimer->stop();
QSettings settings("DisplaySweet", "OgreModelViewer");
settings.setValue( "geometry", saveGeometry() );
settings.setValue( "windowState", saveState() );
QMainWindow::closeEvent( event );
}
void MainWindow::readSettings()
{
QSettings settings( "DisplaySweet", "OgreModelViewer" );
restoreGeometry( settings.value( "geometry" ).toByteArray() );
restoreState( settings.value( "windowState" ).toByteArray() );
}
void MainWindow::onSceneLoaded()
{
}
void MainWindow::Tick()
{
if (mOgreManager)
mOgreManager->renderOgreWidgetsOneFrame();
}
void MainWindow::createDockWindows()
{
QDockWidget* pDockWidget1 = new QDockWidget("Lights", this);
addDockWidget(Qt::LeftDockWidgetArea, pDockWidget1);
mLightWidget = new LightWidget(this);
pDockWidget1->setWidget(mLightWidget);
mLightWidget->init(mOgreManager);
}
void MainWindow::startTimer()
{
mOgreManager->createScene();
mTimer->start();
}
void MainWindow::doQuitMenuAction()
{
close();
}
void MainWindow::actionOpenMesh()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionOpenMesh", sUserDoc).toString();
QString sMeshFileName = QFileDialog::getOpenFileName(this, "Open Ogre Mesh",
sLastOpenLocation,
"Ogre Mesh (*.mesh)");
if (sMeshFileName.isEmpty())
{
return;
}
Q_ASSERT(QFile::exists(sMeshFileName));
QFileInfo info(sMeshFileName);
settings.setValue("actionOpenMesh", info.absolutePath());
mOgreManager->clearScene();
auto& manager = Ogre::ResourceGroupManager::getSingleton();
manager.addResourceLocation(info.absolutePath().toStdString(), "FileSystem", "OgreSpooky");
auto all_mtl = manager.findResourceNames("OgreSpooky", "*.material.json");
for (std::string m : *all_mtl)
{
Ogre::Root::getSingleton().getHlmsManager()->loadMaterials(m, "OgreSpooky");
}
try
{
mOgreManager->loadMesh(sMeshFileName);
}
catch (...)
{
qDebug() << "Ogre mesh load failed";
QMessageBox::information(this, "Error", "Filed to load ogre mesh");
}
}
void MainWindow::actionSaveMesh()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionSaveMesh", sUserDoc).toString();
QString sMeshFileName = QFileDialog::getSaveFileName(this, "Save Ogre Mesh",
sLastOpenLocation + "/a.mesh",
"Ogre Mesh (*.mesh)");
if (sMeshFileName.isEmpty())
{
return;
}
QFileInfo info(sMeshFileName);
settings.setValue("actionSaveMesh", info.absolutePath());
if (QFile::exists(sMeshFileName)) QFile::remove(sMeshFileName);
Q_ASSERT(!QFile::exists(sMeshFileName));
Ogre::Mesh* mesh = mOgreManager->currentMesh();
if (mesh != nullptr)
{
Ogre::Root* root = Ogre::Root::getSingletonPtr();
Ogre::MeshSerializer meshSerializer2(root->getRenderSystem()->getVaoManager());
meshSerializer2.exportMesh(mesh, sMeshFileName.toStdString());
if (!QFile::exists(sMeshFileName))
{
qDebug() << "Failed to export obj model.";
QMessageBox::information(this, "Error", "Filed to export obj model");
}
}
}
void MainWindow::actionImportObj()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionImportObj", sUserDoc).toString();
QString sObjFileName = QFileDialog::getOpenFileName(this, "Open Obj",
sLastOpenLocation,
"Wavefront obj (*.obj)");
if (sObjFileName.isEmpty())
{
return;
}
auto ret = QMessageBox::question(this, "Coordinate system", "Convert from Z-up to Y-up?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
Q_ASSERT(QFile::exists(sObjFileName));
QFileInfo info(sObjFileName);
settings.setValue("actionImportObj", info.absolutePath());
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(info.absolutePath().toStdString(), "FileSystem", "OgreSpooky");
QString sOutFile = info.absolutePath() + "/" + info.baseName() + ".mesh";
mOgreManager->clearScene();
ObjImporter objImporter;
objImporter.setZUpToYUp(ret == QMessageBox::Yes);
bool b = objImporter.import(sObjFileName, sOutFile);
qDebug() << "Obj=" << sObjFileName << ", Success=" << b;
if (b)
{
try
{
mOgreManager->loadMesh(sOutFile);
}
catch (...)
{
qDebug() << "Failed to Load obj.";
}
}
else
{
qDebug() << "Failed to import obj model.";
QMessageBox::information(this, "Error", "Filed to import obj model");
}
}
void MainWindow::actionExportObj()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionExportObj", sUserDoc).toString();
QString sObjFileName = QFileDialog::getSaveFileName(this, "Export Obj",
sLastOpenLocation + "/a.obj",
"Wavefront obj (*.obj)");
if (sObjFileName.isEmpty())
{
return;
}
//QString sObjFileName = "C:/Users/Matt/Desktop/a.obj";
if (QFile::exists(sObjFileName)) QFile::remove(sObjFileName);
Q_ASSERT(!QFile::exists(sObjFileName));
QFileInfo info(sObjFileName);
settings.setValue("actionExportObj", info.absolutePath());
Ogre::Mesh* mesh = mOgreManager->currentMesh();
if (mesh != nullptr)
{
ObjExporter objExporter;
bool ok = objExporter.exportFile(mesh, sObjFileName);
qDebug() << "Obj=" << sObjFileName << ", Success=" << ok;
if (!ok)
{
qDebug() << "Failed to export obj model.";
QMessageBox::information(this, "Error", "Filed to export obj model");
}
}
}
void MainWindow::actionBatchConverter()
{
BatchConversionDialog dialog;
dialog.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
dialog.exec();
}
<commit_msg>clean up<commit_after>/****************************************************************************
**
** Copyright (C) 2016
**
** This file is generated by the Magus toolkit
**
** 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
#include "stdafx.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include <QFile>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QCloseEvent>
#include <QDockWidget>
#include <QSettings>
#include <QFileDialog>
#include <QStandardPaths>
#include <QSettings>
#include <QDebug>
#include <QMessageBox>
#include "lightwidget.h"
#include "ogremanager.h"
#include "ogrewidget.h"
#include "objimporter.h"
#include "objexporter.h"
#include "OgreMesh2Serializer.h"
#include "batchconversiondialog.h"
#define _STR(x) #x
#define STR(X) _STR(x)
MainWindow::MainWindow()
{
ui = new Ui::MainWindow;
ui->setupUi(this);
mOgreManager = new OgreManager;
mOgreWidget = new OgreWidget;
setCentralWidget(mOgreWidget);
mOgreManager->registerOgreWidget(mOgreWidget);
mOgreWidget->createRenderWindow(mOgreManager);
mOgreManager->initialize();
mOgreWidget->createCompositor();
mTimer = new QTimer(this);
mTimer->setInterval(16);
connect(mTimer, &QTimer::timeout, this, &MainWindow::Tick);
createDockWindows();
// Set the title
setWindowTitle("Ogre v2 Mesh Viewer v" STR(APP_VERSION_NUMBER));
readSettings();
connect(mOgreManager, &OgreManager::sceneCreated, this, &MainWindow::onSceneLoaded);
// actions
connect(ui->actionOpenOgreMesh, &QAction::triggered, this, &MainWindow::actionOpenMesh);
connect(ui->actionSaveOgreMesh, &QAction::triggered, this, &MainWindow::actionSaveMesh);
connect(ui->actionImportObj, &QAction::triggered, this, &MainWindow::actionImportObj);
connect(ui->actionExportObj, &QAction::triggered, this, &MainWindow::actionExportObj);
connect(ui->actionBatchConverter, &QAction::triggered, this, &MainWindow::actionBatchConverter);
connect(ui->actionExit, &QAction::triggered, this, &MainWindow::doQuitMenuAction);
}
MainWindow::~MainWindow()
{
delete mOgreManager;
delete ui;
}
void MainWindow::closeEvent( QCloseEvent* event )
{
mIsClosing = true;
mTimer->stop();
QSettings settings("DisplaySweet", "OgreModelViewer");
settings.setValue( "geometry", saveGeometry() );
settings.setValue( "windowState", saveState() );
QMainWindow::closeEvent( event );
}
void MainWindow::readSettings()
{
QSettings settings( "DisplaySweet", "OgreModelViewer" );
restoreGeometry( settings.value( "geometry" ).toByteArray() );
restoreState( settings.value( "windowState" ).toByteArray() );
}
void MainWindow::onSceneLoaded()
{
}
void MainWindow::Tick()
{
if (mOgreManager)
mOgreManager->renderOgreWidgetsOneFrame();
}
void MainWindow::createDockWindows()
{
QDockWidget* pDockWidget1 = new QDockWidget("Lights", this);
addDockWidget(Qt::LeftDockWidgetArea, pDockWidget1);
mLightWidget = new LightWidget(this);
pDockWidget1->setWidget(mLightWidget);
mLightWidget->init(mOgreManager);
}
void MainWindow::startTimer()
{
mOgreManager->createScene();
mTimer->start();
}
void MainWindow::doQuitMenuAction()
{
close();
}
void MainWindow::actionOpenMesh()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionOpenMesh", sUserDoc).toString();
QString sMeshFileName = QFileDialog::getOpenFileName(this, "Open Ogre Mesh", sLastOpenLocation, "Ogre Mesh (*.mesh)");
if (sMeshFileName.isEmpty())
{
return;
}
Q_ASSERT(QFile::exists(sMeshFileName));
QFileInfo info(sMeshFileName);
settings.setValue("actionOpenMesh", info.absolutePath());
mOgreManager->clearScene();
auto& manager = Ogre::ResourceGroupManager::getSingleton();
manager.addResourceLocation(info.absolutePath().toStdString(), "FileSystem", "OgreSpooky");
auto all_mtl = manager.findResourceNames("OgreSpooky", "*.material.json");
for (std::string m : *all_mtl)
{
Ogre::Root::getSingleton().getHlmsManager()->loadMaterials(m, "OgreSpooky");
}
try
{
mOgreManager->loadMesh(sMeshFileName);
}
catch (...)
{
qDebug() << "Ogre mesh load failed";
QMessageBox::information(this, "Error", "Filed to load ogre mesh");
}
}
void MainWindow::actionSaveMesh()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionSaveMesh", sUserDoc).toString();
QString sMeshFileName = QFileDialog::getSaveFileName(this, "Save Ogre Mesh",
sLastOpenLocation + "/a.mesh",
"Ogre Mesh (*.mesh)");
if (sMeshFileName.isEmpty())
{
return;
}
QFileInfo info(sMeshFileName);
settings.setValue("actionSaveMesh", info.absolutePath());
if (QFile::exists(sMeshFileName)) QFile::remove(sMeshFileName);
Q_ASSERT(!QFile::exists(sMeshFileName));
Ogre::Mesh* mesh = mOgreManager->currentMesh();
if (mesh != nullptr)
{
Ogre::Root* root = Ogre::Root::getSingletonPtr();
Ogre::MeshSerializer meshSerializer2(root->getRenderSystem()->getVaoManager());
meshSerializer2.exportMesh(mesh, sMeshFileName.toStdString());
if (!QFile::exists(sMeshFileName))
{
qDebug() << "Failed to export obj model.";
QMessageBox::information(this, "Error", "Filed to export obj model");
}
}
}
void MainWindow::actionImportObj()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionImportObj", sUserDoc).toString();
QString sObjFileName = QFileDialog::getOpenFileName(this, "Open Obj",
sLastOpenLocation,
"Wavefront obj (*.obj)");
if (sObjFileName.isEmpty())
{
return;
}
auto ret = QMessageBox::question(this, "Coordinate system", "Convert from Z-up to Y-up?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
Q_ASSERT(QFile::exists(sObjFileName));
QFileInfo info(sObjFileName);
settings.setValue("actionImportObj", info.absolutePath());
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(info.absolutePath().toStdString(), "FileSystem", "OgreSpooky");
QString sOutFile = info.absolutePath() + "/" + info.baseName() + ".mesh";
mOgreManager->clearScene();
ObjImporter objImporter;
objImporter.setZUpToYUp(ret == QMessageBox::Yes);
bool b = objImporter.import(sObjFileName, sOutFile);
qDebug() << "Obj=" << sObjFileName << ", Success=" << b;
if (b)
{
try
{
mOgreManager->loadMesh(sOutFile);
}
catch (...)
{
qDebug() << "Failed to Load obj.";
}
}
else
{
qDebug() << "Failed to import obj model.";
QMessageBox::information(this, "Error", "Filed to import obj model");
}
}
void MainWindow::actionExportObj()
{
mTimer->stop();
ON_SCOPE_EXIT(mTimer->start());
QString sUserDoc = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0];
QSettings settings("DisplaySweet", "OgreModelViewer");
QString sLastOpenLocation = settings.value("actionExportObj", sUserDoc).toString();
QString sObjFileName = QFileDialog::getSaveFileName(this, "Export Obj",
sLastOpenLocation + "/a.obj",
"Wavefront obj (*.obj)");
if (sObjFileName.isEmpty())
{
return;
}
//QString sObjFileName = "C:/Users/Matt/Desktop/a.obj";
if (QFile::exists(sObjFileName)) QFile::remove(sObjFileName);
Q_ASSERT(!QFile::exists(sObjFileName));
QFileInfo info(sObjFileName);
settings.setValue("actionExportObj", info.absolutePath());
Ogre::Mesh* mesh = mOgreManager->currentMesh();
if (mesh != nullptr)
{
ObjExporter objExporter;
bool ok = objExporter.exportFile(mesh, sObjFileName);
qDebug() << "Obj=" << sObjFileName << ", Success=" << ok;
if (!ok)
{
qDebug() << "Failed to export obj model.";
QMessageBox::information(this, "Error", "Filed to export obj model");
}
}
}
void MainWindow::actionBatchConverter()
{
BatchConversionDialog dialog;
dialog.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
dialog.exec();
}
<|endoftext|> |
<commit_before>/* Mobile On Desktop - A Smartphone emulator on desktop
* Copyright (c) 2012 Régis FLORET
*
* 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 Régis FLORET 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 REGENTS 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 REGENTS AND 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 "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "webpage.h"
#include "urlinputdialog.h"
#include "preferencesdialog.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(qApp->applicationName());
mWebWidget = new WebWidget(this);
mWebWidget->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
setCentralWidget(mWebWidget);
setFixedSize(320,480);
mWebInspector = new QWebInspector;
mWebInspector->setPage(mWebWidget->page());
mProgressBar = new QProgressBar(this);
mProgressBar->setMaximum(100);
mProgressBar->setMinimum(0);
mProgressBar->setValue(0);
mProgressBar->setVisible(false);
statusBar()->addWidget(mProgressBar, 1);
connect(ui->actionNewWindow, SIGNAL(triggered()), SLOT(onNewWindow()));
connect(ui->action_Close, SIGNAL(triggered()), SLOT(close()));
connect(ui->actionLoadURL, SIGNAL(triggered()), SLOT(onLoadURL()));
connect(ui->actionReload, SIGNAL(triggered()), SLOT(onReload()));
connect(ui->actionQuit, SIGNAL(triggered()), SLOT(onQuit()));
connect(ui->actionPreferences, SIGNAL(triggered()), SLOT(onPreferences()));
connect(ui->actionAbout, SIGNAL(triggered()), SLOT(onAbout()));
connect(ui->actionIOS, SIGNAL(triggered()), SLOT(onChangeForIOs()));
connect(ui->actionAndroid, SIGNAL(triggered()), SLOT(onChangeForAndroid()));
connect(ui->actionWebOS, SIGNAL(triggered()), SLOT(onChangeForWebOs()));
connect(ui->action320x400, SIGNAL(triggered()), SLOT(onResolution400()));
connect(ui->action320x480, SIGNAL(triggered()), SLOT(onResolution480()));
connect(ui->action1024x768, SIGNAL(triggered()), SLOT(onResolution768()));
connect(ui->actionInspector, SIGNAL(triggered()), SLOT(onShowHideInspector()));
connect(ui->actionStop, SIGNAL(triggered()), SLOT(onStop()));
connect(ui->actionBack, SIGNAL(triggered()), SLOT(onGoBack()));
connect(ui->actionForward, SIGNAL(triggered()), SLOT(onGoForward()));
connect(mWebWidget, SIGNAL(loadFinished(bool)), SLOT(onViewLoadFinished(bool)));
connect(mWebWidget, SIGNAL(loadStarted()), SLOT(onViewLoadStart()));
connect(mWebWidget, SIGNAL(loadProgress(int)), SLOT(onViewLoadProgress(int)));
connect(mWebWidget, SIGNAL(linkClicked(QUrl)), SLOT(onViewLinkClicked(QUrl)));
connect(mWebWidget, SIGNAL(urlChanged(QUrl)), SLOT(onViewUrlChanged(QUrl)));
connect(mWebWidget, SIGNAL(pageNotFound(QUrl)), SLOT(onPageNotFound(QUrl)));
connect(mWebWidget, SIGNAL(noHostFound(QUrl)), SLOT(onNoHostFound(QUrl)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent(QResizeEvent *)
{
mWebWidget->refitPage();
}
void MainWindow::onNewWindow()
{
MainWindow * w = new MainWindow;
w->show();
}
void MainWindow::onLoadURL()
{
URLInputDialog dlg(this);
if (dlg.exec() == QDialog::Accepted)
{
mWebWidget->stop();
mWebWidget->load(dlg.url());
mWebInspector->setPage(mWebWidget->page());
}
}
void MainWindow::onReload()
{
mWebWidget->stop();
mWebWidget->reload();
}
void MainWindow::onQuit()
{
qApp->quit();
}
void MainWindow::onPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void MainWindow::onAbout()
{
AboutDialog(this).exec();
}
void MainWindow::onChangeForIOs()
{
mWebWidget->changeFor(WebPage::IOS);
ui->actionAndroid->setChecked(false);
ui->actionWebOS->setChecked(false);
}
void MainWindow::onChangeForAndroid()
{
mWebWidget->changeFor(WebPage::Android);
ui->actionIOS->setChecked(false);
ui->actionWebOS->setChecked(false);
}
void MainWindow::onChangeForWebOs()
{
mWebWidget->changeFor(WebPage::WebOs);
ui->actionIOS->setChecked(false);
ui->actionAndroid->setChecked(false);
}
void MainWindow::onResolution400()
{
setFixedSize(320,400);
ui->action320x480->setChecked(false);
ui->action1024x768->setChecked(false);
}
void MainWindow::onResolution480()
{
setFixedSize(320,480);
ui->action1024x768->setChecked(false);
ui->action320x400->setChecked(false);
}
void MainWindow::onResolution768()
{
setFixedSize(1024,768);
ui->action320x480->setChecked(false);
ui->action320x400->setChecked(false);
}
void MainWindow::onGoBack()
{
}
void MainWindow::onGoForward()
{
}
void MainWindow::onStop()
{
mWebWidget->stop();
}
void MainWindow::onViewLoadStart()
{
mProgressBar->setVisible(true);
mProgressBar->setValue(0);
}
void MainWindow::onViewLoadFinished(bool)
{
mProgressBar->setVisible(false);
mWebInspector->setPage(mWebWidget->page());
}
void MainWindow::onViewLoadProgress(int progress)
{
mProgressBar->setValue(progress);
}
void MainWindow::onViewUrlChanged(const QUrl & url)
{
}
void MainWindow::onViewLinkClicked(const QUrl & url)
{
}
void MainWindow::onPageNotFound(QUrl url)
{
QMessageBox::critical(this, tr("Error"), tr("Page %1 was not found").arg(url.toString()));
}
void MainWindow::onShowHideInspector()
{
qDebug() << (mWebWidget->page() == NULL);
qDebug() << mWebWidget->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled);
mWebInspector->setVisible(!mWebInspector->isVisible());
}
void MainWindow::onNoHostFound(QUrl url)
{
QMessageBox::critical(this, tr("No host found"), tr("The host %1 was not found").arg(url.toString()));
}
<commit_msg>Make back and forward working<commit_after>/* Mobile On Desktop - A Smartphone emulator on desktop
* Copyright (c) 2012 Régis FLORET
*
* 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 Régis FLORET 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 REGENTS 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 REGENTS AND 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 "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "webpage.h"
#include "urlinputdialog.h"
#include "preferencesdialog.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(qApp->applicationName());
mWebWidget = new WebWidget(this);
mWebWidget->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
setCentralWidget(mWebWidget);
setFixedSize(320,480);
mWebInspector = new QWebInspector;
mWebInspector->setPage(mWebWidget->page());
mProgressBar = new QProgressBar(this);
mProgressBar->setMaximum(100);
mProgressBar->setMinimum(0);
mProgressBar->setValue(0);
mProgressBar->setVisible(false);
statusBar()->addWidget(mProgressBar, 1);
connect(ui->actionNewWindow, SIGNAL(triggered()), SLOT(onNewWindow()));
connect(ui->action_Close, SIGNAL(triggered()), SLOT(close()));
connect(ui->actionLoadURL, SIGNAL(triggered()), SLOT(onLoadURL()));
connect(ui->actionReload, SIGNAL(triggered()), SLOT(onReload()));
connect(ui->actionQuit, SIGNAL(triggered()), SLOT(onQuit()));
connect(ui->actionPreferences, SIGNAL(triggered()), SLOT(onPreferences()));
connect(ui->actionAbout, SIGNAL(triggered()), SLOT(onAbout()));
connect(ui->actionIOS, SIGNAL(triggered()), SLOT(onChangeForIOs()));
connect(ui->actionAndroid, SIGNAL(triggered()), SLOT(onChangeForAndroid()));
connect(ui->actionWebOS, SIGNAL(triggered()), SLOT(onChangeForWebOs()));
connect(ui->action320x400, SIGNAL(triggered()), SLOT(onResolution400()));
connect(ui->action320x480, SIGNAL(triggered()), SLOT(onResolution480()));
connect(ui->action1024x768, SIGNAL(triggered()), SLOT(onResolution768()));
connect(ui->actionInspector, SIGNAL(triggered()), SLOT(onShowHideInspector()));
connect(ui->actionStop, SIGNAL(triggered()), SLOT(onStop()));
connect(ui->actionBack, SIGNAL(triggered()), SLOT(onGoBack()));
connect(ui->actionForward, SIGNAL(triggered()), SLOT(onGoForward()));
connect(mWebWidget, SIGNAL(loadFinished(bool)), SLOT(onViewLoadFinished(bool)));
connect(mWebWidget, SIGNAL(loadStarted()), SLOT(onViewLoadStart()));
connect(mWebWidget, SIGNAL(loadProgress(int)), SLOT(onViewLoadProgress(int)));
connect(mWebWidget, SIGNAL(linkClicked(QUrl)), SLOT(onViewLinkClicked(QUrl)));
connect(mWebWidget, SIGNAL(urlChanged(QUrl)), SLOT(onViewUrlChanged(QUrl)));
connect(mWebWidget, SIGNAL(pageNotFound(QUrl)), SLOT(onPageNotFound(QUrl)));
connect(mWebWidget, SIGNAL(noHostFound(QUrl)), SLOT(onNoHostFound(QUrl)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent(QResizeEvent *)
{
mWebWidget->refitPage();
}
void MainWindow::onNewWindow()
{
MainWindow * w = new MainWindow;
w->show();
}
void MainWindow::onLoadURL()
{
URLInputDialog dlg(this);
if (dlg.exec() == QDialog::Accepted)
{
mWebWidget->stop();
mWebWidget->load(dlg.url());
mWebInspector->setPage(mWebWidget->page());
}
}
void MainWindow::onReload()
{
mWebWidget->stop();
mWebWidget->reload();
}
void MainWindow::onQuit()
{
qApp->quit();
}
void MainWindow::onPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void MainWindow::onAbout()
{
AboutDialog(this).exec();
}
void MainWindow::onChangeForIOs()
{
mWebWidget->changeFor(WebPage::IOS);
ui->actionAndroid->setChecked(false);
ui->actionWebOS->setChecked(false);
}
void MainWindow::onChangeForAndroid()
{
mWebWidget->changeFor(WebPage::Android);
ui->actionIOS->setChecked(false);
ui->actionWebOS->setChecked(false);
}
void MainWindow::onChangeForWebOs()
{
mWebWidget->changeFor(WebPage::WebOs);
ui->actionIOS->setChecked(false);
ui->actionAndroid->setChecked(false);
}
void MainWindow::onResolution400()
{
setFixedSize(320,400);
ui->action320x480->setChecked(false);
ui->action1024x768->setChecked(false);
}
void MainWindow::onResolution480()
{
setFixedSize(320,480);
ui->action1024x768->setChecked(false);
ui->action320x400->setChecked(false);
}
void MainWindow::onResolution768()
{
setFixedSize(1024,768);
ui->action320x480->setChecked(false);
ui->action320x400->setChecked(false);
}
void MainWindow::onGoBack()
{
mWebWidget->back();
}
void MainWindow::onGoForward()
{
mWebWidget->forward();
}
void MainWindow::onStop()
{
mWebWidget->stop();
}
void MainWindow::onViewLoadStart()
{
mProgressBar->setVisible(true);
mProgressBar->setValue(0);
}
void MainWindow::onViewLoadFinished(bool)
{
mProgressBar->setVisible(false);
mWebInspector->setPage(mWebWidget->page());
}
void MainWindow::onViewLoadProgress(int progress)
{
mProgressBar->setValue(progress);
}
void MainWindow::onViewUrlChanged(const QUrl & url)
{
}
void MainWindow::onViewLinkClicked(const QUrl & url)
{
}
void MainWindow::onPageNotFound(QUrl url)
{
QMessageBox::critical(this, tr("Error"), tr("Page %1 was not found").arg(url.toString()));
}
void MainWindow::onShowHideInspector()
{
qDebug() << (mWebWidget->page() == NULL);
qDebug() << mWebWidget->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled);
mWebInspector->setVisible(!mWebInspector->isVisible());
}
void MainWindow::onNoHostFound(QUrl url)
{
QMessageBox::critical(this, tr("No host found"), tr("The host %1 was not found").arg(url.toString()));
}
<|endoftext|> |
<commit_before>// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected])
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <filesystem>
#include <stdexcept>
#include <Nazara/Renderer/Debug.hpp>
#ifdef NAZARA_COMPILER_MSVC
#define NazaraRendererPrefix "./"
#else
#define NazaraRendererPrefix "./lib"
#endif
#ifdef NAZARA_DEBUG
#define NazaraRendererDebugSuffix "-d"
#else
#define NazaraRendererDebugSuffix ""
#endif
namespace Nz
{
Renderer::Renderer(Config config) :
ModuleBase("Renderer", this)
{
LoadBackend(config);
}
Renderer::~Renderer()
{
// reset Renderer impl before unloading library
m_rendererImpl.reset();
}
std::shared_ptr<RenderDevice> Renderer::InstanciateRenderDevice(std::size_t deviceIndex, const RenderDeviceFeatures& enabledFeatures)
{
return m_rendererImpl->InstanciateRenderDevice(deviceIndex, enabledFeatures);
}
RenderAPI Renderer::QueryAPI() const
{
return m_rendererImpl->QueryAPI();
}
std::string Renderer::QueryAPIString() const
{
return m_rendererImpl->QueryAPIString();
}
UInt32 Renderer::QueryAPIVersion() const
{
return m_rendererImpl->QueryAPIVersion();
}
const std::vector<RenderDeviceInfo>& Renderer::QueryRenderDevices() const
{
return m_rendererImpl->QueryRenderDevices();
}
void Renderer::LoadBackend(const Config& config)
{
constexpr std::array<const char*, RenderAPICount> rendererPaths = {
NazaraRendererPrefix "NazaraDirect3DRenderer" NazaraRendererDebugSuffix, // Direct3D
NazaraRendererPrefix "NazaraMantleRenderer" NazaraRendererDebugSuffix, // Mantle
NazaraRendererPrefix "NazaraMetalRenderer" NazaraRendererDebugSuffix, // Metal
NazaraRendererPrefix "NazaraOpenGLRenderer" NazaraRendererDebugSuffix, // OpenGL
NazaraRendererPrefix "NazaraVulkanRenderer" NazaraRendererDebugSuffix, // Vulkan
nullptr // Unknown
};
struct RendererImplementations
{
std::filesystem::path fileName;
int score;
};
std::vector<RendererImplementations> implementations;
auto RegisterImpl = [&](RenderAPI api, auto ComputeScore)
{
const char* rendererName = rendererPaths[UnderlyingCast(api)];
assert(rendererName);
std::filesystem::path fileName(rendererName);
fileName.replace_extension(NAZARA_DYNLIB_EXTENSION);
int score = ComputeScore();
if (score >= 0)
{
auto& impl = implementations.emplace_back();
impl.fileName = std::move(fileName);
impl.score = (config.preferredAPI == api) ? std::numeric_limits<int>::max() : score;
}
};
RegisterImpl(RenderAPI::OpenGL, [] { return 50; });
RegisterImpl(RenderAPI::Vulkan, [] { return 100; });
std::sort(implementations.begin(), implementations.end(), [](const auto& lhs, const auto& rhs) { return lhs.score > rhs.score; });
NazaraDebug("Searching for renderer implementation");
DynLib chosenLib;
std::unique_ptr<RendererImpl> chosenImpl;
for (auto&& rendererImpl : implementations)
{
if (!std::filesystem::exists(rendererImpl.fileName))
continue;
std::string fileNameStr = rendererImpl.fileName.generic_u8string();
DynLib implLib;
if (!implLib.Load(rendererImpl.fileName))
{
NazaraWarning("Failed to load " + fileNameStr + ": " + implLib.GetLastError());
continue;
}
CreateRendererImplFunc createRenderer = reinterpret_cast<CreateRendererImplFunc>(implLib.GetSymbol("NazaraRenderer_Instantiate"));
if (!createRenderer)
{
NazaraDebug("Skipped " + fileNameStr + " (symbol not found)");
continue;
}
std::unique_ptr<RendererImpl> impl(createRenderer());
if (!impl || !impl->Prepare({}))
{
NazaraError("Failed to create renderer implementation");
continue;
}
NazaraDebug("Loaded " + fileNameStr);
chosenImpl = std::move(impl); //< Move (and delete previous) implementation before unloading library
chosenLib = std::move(implLib);
break;
}
if (!chosenImpl)
throw std::runtime_error("no renderer found");
m_rendererImpl = std::move(chosenImpl);
m_rendererLib = std::move(chosenLib);
NazaraDebug("Using " + m_rendererImpl->QueryAPIString() + " as renderer");
}
Renderer* Renderer::s_instance = nullptr;
}
<commit_msg>Renderer: Don't ignore non-existent library files<commit_after>// Copyright (C) 2022 Jérôme "Lynix" Leclercq ([email protected])
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <filesystem>
#include <stdexcept>
#include <Nazara/Renderer/Debug.hpp>
#ifdef NAZARA_COMPILER_MSVC
#define NazaraRendererPrefix "./"
#else
#define NazaraRendererPrefix "./lib"
#endif
#ifdef NAZARA_DEBUG
#define NazaraRendererDebugSuffix "-d"
#else
#define NazaraRendererDebugSuffix ""
#endif
namespace Nz
{
Renderer::Renderer(Config config) :
ModuleBase("Renderer", this)
{
LoadBackend(config);
}
Renderer::~Renderer()
{
// reset Renderer impl before unloading library
m_rendererImpl.reset();
}
std::shared_ptr<RenderDevice> Renderer::InstanciateRenderDevice(std::size_t deviceIndex, const RenderDeviceFeatures& enabledFeatures)
{
return m_rendererImpl->InstanciateRenderDevice(deviceIndex, enabledFeatures);
}
RenderAPI Renderer::QueryAPI() const
{
return m_rendererImpl->QueryAPI();
}
std::string Renderer::QueryAPIString() const
{
return m_rendererImpl->QueryAPIString();
}
UInt32 Renderer::QueryAPIVersion() const
{
return m_rendererImpl->QueryAPIVersion();
}
const std::vector<RenderDeviceInfo>& Renderer::QueryRenderDevices() const
{
return m_rendererImpl->QueryRenderDevices();
}
void Renderer::LoadBackend(const Config& config)
{
constexpr std::array<const char*, RenderAPICount> rendererPaths = {
NazaraRendererPrefix "NazaraDirect3DRenderer" NazaraRendererDebugSuffix, // Direct3D
NazaraRendererPrefix "NazaraMantleRenderer" NazaraRendererDebugSuffix, // Mantle
NazaraRendererPrefix "NazaraMetalRenderer" NazaraRendererDebugSuffix, // Metal
NazaraRendererPrefix "NazaraOpenGLRenderer" NazaraRendererDebugSuffix, // OpenGL
NazaraRendererPrefix "NazaraVulkanRenderer" NazaraRendererDebugSuffix, // Vulkan
nullptr // Unknown
};
struct RendererImplementations
{
std::filesystem::path fileName;
int score;
};
std::vector<RendererImplementations> implementations;
auto RegisterImpl = [&](RenderAPI api, auto ComputeScore)
{
const char* rendererName = rendererPaths[UnderlyingCast(api)];
assert(rendererName);
std::filesystem::path fileName(rendererName);
fileName.replace_extension(NAZARA_DYNLIB_EXTENSION);
int score = ComputeScore();
if (score >= 0)
{
auto& impl = implementations.emplace_back();
impl.fileName = std::move(fileName);
impl.score = (config.preferredAPI == api) ? std::numeric_limits<int>::max() : score;
}
};
RegisterImpl(RenderAPI::OpenGL, [] { return 50; });
RegisterImpl(RenderAPI::Vulkan, [] { return 100; });
std::sort(implementations.begin(), implementations.end(), [](const auto& lhs, const auto& rhs) { return lhs.score > rhs.score; });
NazaraDebug("Searching for renderer implementation");
DynLib chosenLib;
std::unique_ptr<RendererImpl> chosenImpl;
for (auto&& rendererImpl : implementations)
{
std::string fileNameStr = rendererImpl.fileName.generic_u8string();
DynLib implLib;
if (!implLib.Load(rendererImpl.fileName))
{
NazaraWarning("Failed to load " + fileNameStr + ": " + implLib.GetLastError());
continue;
}
CreateRendererImplFunc createRenderer = reinterpret_cast<CreateRendererImplFunc>(implLib.GetSymbol("NazaraRenderer_Instantiate"));
if (!createRenderer)
{
NazaraDebug("Skipped " + fileNameStr + " (symbol not found)");
continue;
}
std::unique_ptr<RendererImpl> impl(createRenderer());
if (!impl || !impl->Prepare({}))
{
NazaraError("Failed to create renderer implementation");
continue;
}
NazaraDebug("Loaded " + fileNameStr);
chosenImpl = std::move(impl); //< Move (and delete previous) implementation before unloading library
chosenLib = std::move(implLib);
break;
}
if (!chosenImpl)
throw std::runtime_error("no renderer found");
m_rendererImpl = std::move(chosenImpl);
m_rendererLib = std::move(chosenLib);
NazaraDebug("Using " + m_rendererImpl->QueryAPIString() + " as renderer");
}
Renderer* Renderer::s_instance = nullptr;
}
<|endoftext|> |
<commit_before>#include "PS2VM.h"
#include <boost/filesystem.hpp>
#include "StdStream.h"
#include "StdStreamUtils.h"
#include "Utils.h"
#include "JUnitTestReportWriter.h"
std::vector<std::string> ReadLines(Framework::CStream& inputStream)
{
std::vector<std::string> lines;
lines.push_back(Utils::GetLine(&inputStream));
while(!inputStream.IsEOF())
{
lines.push_back(Utils::GetLine(&inputStream));
}
return lines;
}
TESTRESULT GetTestResult(const boost::filesystem::path& testFilePath)
{
TESTRESULT result;
result.succeeded = false;
try
{
auto resultFilePath = testFilePath;
resultFilePath.replace_extension(".result");
auto expectedFilePath = testFilePath;
expectedFilePath.replace_extension(".expected");
auto resultStream = Framework::CreateInputStdStream(resultFilePath.string());
auto expectedStream = Framework::CreateInputStdStream(expectedFilePath.string());
auto resultLines = ReadLines(resultStream);
auto expectedLines = ReadLines(expectedStream);
if(resultLines.size() != expectedLines.size()) return result;
for(unsigned int i = 0; i < resultLines.size(); i++)
{
if(resultLines[i] != expectedLines[i])
{
LINEDIFF lineDiff;
lineDiff.expected = expectedLines[i];
lineDiff.result = resultLines[i];
result.lineDiffs.push_back(lineDiff);
}
}
result.succeeded = result.lineDiffs.empty();
return result;
}
catch(...)
{
}
return result;
}
void ExecuteTest(const boost::filesystem::path& testFilePath)
{
auto resultFilePath = testFilePath;
resultFilePath.replace_extension(".result");
auto resultStream = new Framework::CStdStream(resultFilePath.string().c_str(), "wb");
bool executionOver = false;
//Setup virtual machine
CPS2VM virtualMachine;
virtualMachine.Initialize();
virtualMachine.Reset();
virtualMachine.m_ee->m_os->OnRequestExit.connect(
[&executionOver] ()
{
executionOver = true;
}
);
virtualMachine.m_ee->m_os->BootFromFile(testFilePath.string().c_str());
virtualMachine.m_iopOs->GetIoman()->SetFileStream(1, resultStream);
virtualMachine.Resume();
while(!executionOver)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
virtualMachine.Pause();
virtualMachine.Destroy();
}
void ScanAndExecuteTests(const boost::filesystem::path& testDirPath, const TestReportWriterPtr& testReportWriter)
{
boost::filesystem::directory_iterator endIterator;
for(auto testPathIterator = boost::filesystem::directory_iterator(testDirPath);
testPathIterator != endIterator; testPathIterator++)
{
auto testPath = testPathIterator->path();
if(boost::filesystem::is_directory(testPath))
{
ScanAndExecuteTests(testPath, testReportWriter);
continue;
}
if(testPath.extension() == ".elf")
{
printf("Testing '%s': ", testPath.string().c_str());
ExecuteTest(testPath);
auto result = GetTestResult(testPath);
printf("%s.\r\n", result.succeeded ? "SUCCEEDED" : "FAILED");
if(testReportWriter)
{
testReportWriter->ReportTestEntry(testPath.string(), result);
}
}
}
}
int main(int argc, const char** argv)
{
if(argc < 2)
{
printf("Usage: AutoTest [options] testDir\r\n");
printf("Options: \r\n");
printf("\t --junitreport <path>\t Writes JUnit format report at <path>.\r\n");
return -1;
}
TestReportWriterPtr testReportWriter;
boost::filesystem::path autoTestRoot;
boost::filesystem::path reportPath;
for(int i = 1; i < argc; i++)
{
if(!strcmp(argv[i], "--junitreport"))
{
if((i + 1) >= argc)
{
printf("Error: Path must be specified for --junitreport option.\r\n");
return -1;
}
testReportWriter = std::make_shared<CJUnitTestReportWriter>();
reportPath = boost::filesystem::path(argv[i + 1]);
i++;
}
else
{
autoTestRoot = argv[i];
break;
}
}
if(autoTestRoot.empty())
{
printf("Error: No test directory specified.\r\n");
return -1;
}
ScanAndExecuteTests(autoTestRoot, testReportWriter);
if(testReportWriter)
{
try
{
testReportWriter->Write(reportPath);
}
catch(const std::exception& exception)
{
printf("Error: Failed to write test report: %s\r\n", exception.what());
return -1;
}
}
return 0;
}
<commit_msg>Use proper enum value for stdout.<commit_after>#include "PS2VM.h"
#include <boost/filesystem.hpp>
#include "StdStream.h"
#include "StdStreamUtils.h"
#include "Utils.h"
#include "JUnitTestReportWriter.h"
std::vector<std::string> ReadLines(Framework::CStream& inputStream)
{
std::vector<std::string> lines;
lines.push_back(Utils::GetLine(&inputStream));
while(!inputStream.IsEOF())
{
lines.push_back(Utils::GetLine(&inputStream));
}
return lines;
}
TESTRESULT GetTestResult(const boost::filesystem::path& testFilePath)
{
TESTRESULT result;
result.succeeded = false;
try
{
auto resultFilePath = testFilePath;
resultFilePath.replace_extension(".result");
auto expectedFilePath = testFilePath;
expectedFilePath.replace_extension(".expected");
auto resultStream = Framework::CreateInputStdStream(resultFilePath.string());
auto expectedStream = Framework::CreateInputStdStream(expectedFilePath.string());
auto resultLines = ReadLines(resultStream);
auto expectedLines = ReadLines(expectedStream);
if(resultLines.size() != expectedLines.size()) return result;
for(unsigned int i = 0; i < resultLines.size(); i++)
{
if(resultLines[i] != expectedLines[i])
{
LINEDIFF lineDiff;
lineDiff.expected = expectedLines[i];
lineDiff.result = resultLines[i];
result.lineDiffs.push_back(lineDiff);
}
}
result.succeeded = result.lineDiffs.empty();
return result;
}
catch(...)
{
}
return result;
}
void ExecuteTest(const boost::filesystem::path& testFilePath)
{
auto resultFilePath = testFilePath;
resultFilePath.replace_extension(".result");
auto resultStream = new Framework::CStdStream(resultFilePath.string().c_str(), "wb");
bool executionOver = false;
//Setup virtual machine
CPS2VM virtualMachine;
virtualMachine.Initialize();
virtualMachine.Reset();
virtualMachine.m_ee->m_os->OnRequestExit.connect(
[&executionOver] ()
{
executionOver = true;
}
);
virtualMachine.m_ee->m_os->BootFromFile(testFilePath.string().c_str());
virtualMachine.m_iopOs->GetIoman()->SetFileStream(Iop::CIoman::FID_STDOUT, resultStream);
virtualMachine.Resume();
while(!executionOver)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
virtualMachine.Pause();
virtualMachine.Destroy();
}
void ScanAndExecuteTests(const boost::filesystem::path& testDirPath, const TestReportWriterPtr& testReportWriter)
{
boost::filesystem::directory_iterator endIterator;
for(auto testPathIterator = boost::filesystem::directory_iterator(testDirPath);
testPathIterator != endIterator; testPathIterator++)
{
auto testPath = testPathIterator->path();
if(boost::filesystem::is_directory(testPath))
{
ScanAndExecuteTests(testPath, testReportWriter);
continue;
}
if(testPath.extension() == ".elf")
{
printf("Testing '%s': ", testPath.string().c_str());
ExecuteTest(testPath);
auto result = GetTestResult(testPath);
printf("%s.\r\n", result.succeeded ? "SUCCEEDED" : "FAILED");
if(testReportWriter)
{
testReportWriter->ReportTestEntry(testPath.string(), result);
}
}
}
}
int main(int argc, const char** argv)
{
if(argc < 2)
{
printf("Usage: AutoTest [options] testDir\r\n");
printf("Options: \r\n");
printf("\t --junitreport <path>\t Writes JUnit format report at <path>.\r\n");
return -1;
}
TestReportWriterPtr testReportWriter;
boost::filesystem::path autoTestRoot;
boost::filesystem::path reportPath;
for(int i = 1; i < argc; i++)
{
if(!strcmp(argv[i], "--junitreport"))
{
if((i + 1) >= argc)
{
printf("Error: Path must be specified for --junitreport option.\r\n");
return -1;
}
testReportWriter = std::make_shared<CJUnitTestReportWriter>();
reportPath = boost::filesystem::path(argv[i + 1]);
i++;
}
else
{
autoTestRoot = argv[i];
break;
}
}
if(autoTestRoot.empty())
{
printf("Error: No test directory specified.\r\n");
return -1;
}
ScanAndExecuteTests(autoTestRoot, testReportWriter);
if(testReportWriter)
{
try
{
testReportWriter->Write(reportPath);
}
catch(const std::exception& exception)
{
printf("Error: Failed to write test report: %s\r\n", exception.what());
return -1;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
*
* Project: integrating laszip into liblas - http://liblas.org -
* Purpose:
* Author: Martin Isenburg
* isenburg at cs.unc.edu
*
******************************************************************************
* Copyright (c) 2010, Martin Isenburg
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
*
* See the COPYING file for more information.
*
****************************************************************************/
/*
===============================================================================
FILE: laszippertest.cpp
CONTENTS:
This tool reads and writes point data in the LAS 1.X format compressed
or uncompressed to test the laszipper and lasunzipper interfaces.
PROGRAMMERS:
martin [email protected]
COPYRIGHT:
copyright (C) 2010 martin [email protected]
This software 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.
CHANGE HISTORY:
13 December 2010 -- created to test the remodularized laszip compressor
===============================================================================
*/
#include "laszipper.hpp"
#include "lasunzipper.hpp"
#ifdef LZ_WIN32_VC6
#include <fstream.h>
#else
#include <istream>
#include <fstream>
using namespace std;
#endif
#include <time.h>
#include <stdio.h>
//#define LASZIP_HAVE_RANGECODER
static double taketime()
{
return (double)(clock())/CLOCKS_PER_SEC;
}
// abstractions for doing I/O, which support VC6 streams, modern streams, and FILE*
struct OStream
{
public:
OStream(bool use_iostream, const char* filename) :
m_use_iostream(use_iostream),
m_filename(filename),
ofile(NULL),
ostream(NULL)
{
if (m_use_iostream)
{
#ifdef LZ_WIN32_VC6
ofb.open(filename, ios::out);
ofb.setmode(filebuf::binary);
ostream = new ostream(&ofb);
#else
ostream = new ofstream();
ostream->open(filename, std::ios::out | std::ios::binary );
#endif
}
else
{
ofile = fopen(filename, "wb");
}
return;
}
~OStream()
{
if (m_use_iostream)
{
delete ostream;
#ifdef LZ_WIN32_VC6
ofb.close();
#endif
}
else
{
if (ofile)
fclose(ofile);
}
}
public:
bool m_use_iostream;
const char* m_filename;
FILE* ofile;
filebuf ofb;
#ifdef LZ_WIN32_VC6
ostream* ostream;
#else
ofstream* ostream;
#endif
};
struct IStream
{
public:
IStream(bool use_iostream, const char* filename) :
m_use_iostream(use_iostream),
m_filename(filename),
ifile(NULL),
istream(NULL)
{
if (m_use_iostream)
{
#ifdef LZ_WIN32_VC6
ifb.open(filename, ios::in);
ifb.setmode(filebuf::binary);
istream = new istream(&ifb);
#else
istream = new ifstream();
istream->open(filename, std::ios::in | std::ios::binary );
#endif
}
else
{
ifile = fopen(filename, "rb");
}
}
~IStream()
{
if (m_use_iostream)
{
delete istream;
#ifdef LZ_WIN32_VC6
ifb.close();
#endif
}
else
{
if (ifile)
fclose(ifile);
}
}
public:
const char* m_filename;
bool m_use_iostream;
FILE* ifile;
filebuf ifb;
#ifdef LZ_WIN32_VC6
istream* istream;
#else
ifstream* istream;
#endif
};
static LASzipper* make_zipper(OStream* ost, unsigned int num_items, LASitem items[], LASzip::Algorithm alg)
{
LASzipper* zipper = new LASzipper();
int stat = 0;
if (ost->m_use_iostream)
stat = zipper->open(*ost->ostream, num_items, items, alg);
else
stat = zipper->open(ost->ofile, num_items, items, alg);
if (stat != 0)
{
fprintf(stderr, "ERROR: could not open laszipper with %s\n", ost->m_filename);
exit(1);
}
return zipper;
}
static LASunzipper* make_unzipper(IStream* ist, unsigned int num_items, LASitem items[], LASzip::Algorithm alg)
{
LASunzipper* unzipper = new LASunzipper();
int stat = 0;
if (ist->m_use_iostream)
stat = unzipper->open(*ist->istream, num_items, items, alg);
else
stat = unzipper->open(ist->ifile, num_items, items, alg);
if (stat != 0)
{
fprintf(stderr, "ERROR: could not open lasunzipper with %s\n", ist->m_filename);
exit(1);
}
return unzipper;
}
static void write_points(LASzipper* zipper, unsigned int num_points,
unsigned int point_size, unsigned char* point_data, unsigned char** point)
{
double start_time, end_time;
unsigned char c;
unsigned int i,j;
start_time = taketime();
c = 0;
for (i = 0; i < num_points; i++)
{
for (j = 0; j < point_size; j++)
{
point_data[j] = c;
c++;
}
zipper->write(point);
}
unsigned int num_bytes = zipper->close();
end_time = taketime();
fprintf(stderr, "laszipper wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time);
return;
}
static void read_points(LASunzipper* unzipper, unsigned int num_points,
unsigned int point_size, unsigned char* point_data, unsigned char** point)
{
unsigned char c;
unsigned int i,j;
unsigned int num_errors, num_bytes;
double start_time, end_time;
start_time = taketime();
num_errors = 0;
c = 0;
for (i = 0; i < num_points; i++)
{
unzipper->read(point);
for (j = 0; j < point_size; j++)
{
if (point_data[j] != c)
{
fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c);
num_errors++;
if (num_errors > 20) break;
}
c++;
}
if (num_errors > 20) break;
}
num_bytes = unzipper->close();
end_time = taketime();
if (num_errors)
{
fprintf(stderr, "ERROR: with lasunzipper %d\n", num_errors);
}
else
{
fprintf(stderr, "SUCCESS: lasunzipper read %d bytes in %g seconds\n", num_bytes, end_time-start_time);
}
return;
}
int main(int argc, char *argv[])
{
unsigned int i;
unsigned int num_points = 100000;
bool use_iostream = false;
// describe the point structure
unsigned int num_items = 5;
LASitem items[5];
items[0].type = LASitem::POINT10;
items[0].size = 20;
items[0].version = 0;
items[1].type = LASitem::GPSTIME11;
items[1].size = 8;
items[1].version = 0;
items[2].type = LASitem::RGB12;
items[2].size = 6;
items[2].version = 0;
items[3].type = LASitem::WAVEPACKET13;
items[3].size = 29;
items[3].version = 0;
items[4].type = LASitem::BYTE;
items[4].size = 7;
items[4].version = 0;
// compute the point size
unsigned int point_size = 0;
for (i = 0; i < num_items; i++) point_size += items[i].size;
// create the point data
unsigned int point_offset = 0;
unsigned char** point = new unsigned char*[num_items];
unsigned char* point_data = new unsigned char[point_size];
for (i = 0; i < num_items; i++)
{
point[i] = &(point_data[point_offset]);
point_offset += items[i].size;
}
OStream* ost1 = new OStream(use_iostream, "test1.lax");
OStream* ost2 = new OStream(use_iostream, "test2.lax");
OStream* ost3 = new OStream(use_iostream, "test3.lax");
LASzipper* laszipper1 = make_zipper(ost1, num_items, items, LASzip::POINT_BY_POINT_RAW);
LASzipper* laszipper2 = make_zipper(ost2, num_items, items, LASzip::POINT_BY_POINT_ARITHMETIC);
#ifdef LASZIP_HAVE_RANGECODER
LASzipper* laszipper3 = make_zipper(ost3, num_items, items, LASzip::POINT_BY_POINT_RANGE);
#else
fprintf(stderr, "(skipping range coder test)\n");
#endif
// write / compress num_points with "random" data
write_points(laszipper1, num_points, point_size, point_data, point);
write_points(laszipper2, num_points, point_size, point_data, point);
#ifdef LASZIP_HAVE_RANGECODER
write_points(laszipper3, num_points, point_size, point_data, point);
#endif
delete laszipper1;
delete laszipper2;
#ifdef LASZIP_HAVE_RANGECODER
delete laszipper3;
#endif
delete ost1;
delete ost2;
delete ost3;
IStream* ist1 = new IStream(use_iostream, "test1.lax");
IStream* ist2 = new IStream(use_iostream, "test2.lax");
IStream* ist3 = new IStream(use_iostream, "test3.lax");
LASunzipper* lasunzipper1 = make_unzipper(ist1, num_items, items, LASzip::POINT_BY_POINT_RAW);
LASunzipper* lasunzipper2 = make_unzipper(ist2, num_items, items, LASzip::POINT_BY_POINT_ARITHMETIC);
#ifdef LASZIP_HAVE_RANGECODER
LASunzipper* lasunzipper3 = make_unzipper(ist3, num_items, items, LASzip::POINT_BY_POINT_RANGE);
#endif
read_points(lasunzipper1, num_points, point_size, point_data, point);
read_points(lasunzipper2, num_points, point_size, point_data, point);
#ifdef LASZIP_HAVE_RANGECODER
read_points(lasunzipper3, num_points, point_size, point_data, point);
#endif
delete lasunzipper1;
delete lasunzipper2;
#ifdef LASZIP_HAVE_RANGECODER
delete lasunzipper3;
#endif
delete ist1;
delete ist2;
delete ist3;
return 0;
}
<commit_msg>consolidate still more, so can add infinite loop<commit_after>/******************************************************************************
*
* Project: integrating laszip into liblas - http://liblas.org -
* Purpose:
* Author: Martin Isenburg
* isenburg at cs.unc.edu
*
******************************************************************************
* Copyright (c) 2010, Martin Isenburg
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
*
* See the COPYING file for more information.
*
****************************************************************************/
/*
===============================================================================
FILE: laszippertest.cpp
CONTENTS:
This tool reads and writes point data in the LAS 1.X format compressed
or uncompressed to test the laszipper and lasunzipper interfaces.
PROGRAMMERS:
martin [email protected]
COPYRIGHT:
copyright (C) 2010 martin [email protected]
This software 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.
CHANGE HISTORY:
13 December 2010 -- created to test the remodularized laszip compressor
===============================================================================
*/
#include "laszipper.hpp"
#include "lasunzipper.hpp"
#ifdef LZ_WIN32_VC6
#include <fstream.h>
#else
#include <istream>
#include <fstream>
using namespace std;
#endif
#include <time.h>
#include <stdio.h>
//#define LASZIP_HAVE_RANGECODER
//---------------------------------------------------------------------------
static double taketime()
{
return (double)(clock())/CLOCKS_PER_SEC;
}
//---------------------------------------------------------------------------
// abstractions for doing I/O, which support VC6 streams, modern streams, and FILE*
struct OStream
{
public:
OStream(bool use_iostream, const char* filename) :
m_use_iostream(use_iostream),
m_filename(filename),
ofile(NULL),
ostream(NULL)
{
if (m_use_iostream)
{
#ifdef LZ_WIN32_VC6
ofb.open(filename, ios::out);
ofb.setmode(filebuf::binary);
ostream = new ostream(&ofb);
#else
ostream = new ofstream();
ostream->open(filename, std::ios::out | std::ios::binary );
#endif
}
else
{
ofile = fopen(filename, "wb");
}
return;
}
~OStream()
{
if (m_use_iostream)
{
delete ostream;
#ifdef LZ_WIN32_VC6
ofb.close();
#endif
}
else
{
if (ofile)
fclose(ofile);
}
}
public:
bool m_use_iostream;
const char* m_filename;
FILE* ofile;
filebuf ofb;
#ifdef LZ_WIN32_VC6
ostream* ostream;
#else
ofstream* ostream;
#endif
};
//---------------------------------------------------------------------------
struct IStream
{
public:
IStream(bool use_iostream, const char* filename) :
m_use_iostream(use_iostream),
m_filename(filename),
ifile(NULL),
istream(NULL)
{
if (m_use_iostream)
{
#ifdef LZ_WIN32_VC6
ifb.open(filename, ios::in);
ifb.setmode(filebuf::binary);
istream = new istream(&ifb);
#else
istream = new ifstream();
istream->open(filename, std::ios::in | std::ios::binary );
#endif
}
else
{
ifile = fopen(filename, "rb");
}
}
~IStream()
{
if (m_use_iostream)
{
delete istream;
#ifdef LZ_WIN32_VC6
ifb.close();
#endif
}
else
{
if (ifile)
fclose(ifile);
}
}
public:
const char* m_filename;
bool m_use_iostream;
FILE* ifile;
filebuf ifb;
#ifdef LZ_WIN32_VC6
istream* istream;
#else
ifstream* istream;
#endif
};
//---------------------------------------------------------------------------
class Data
{
public:
Data(unsigned int num_pts, bool random) :
num_points(num_pts),
use_random(random)
{
items[0].type = LASitem::POINT10;
items[0].size = 20;
items[0].version = 0;
items[1].type = LASitem::GPSTIME11;
items[1].size = 8;
items[1].version = 0;
items[2].type = LASitem::RGB12;
items[2].size = 6;
items[2].version = 0;
items[3].type = LASitem::WAVEPACKET13;
items[3].size = 29;
items[3].version = 0;
items[4].type = LASitem::BYTE;
items[4].size = 7;
items[4].version = 0;
unsigned int i;
// compute the point size
point_size = 0;
for (i = 0; i < num_items; i++) point_size += items[i].size;
// create the point data
unsigned int point_offset = 0;
point = new unsigned char*[num_items];
point_data = new unsigned char[point_size];
for (i = 0; i < num_items; i++)
{
point[i] = &(point_data[point_offset]);
point_offset += items[i].size;
}
return;
}
~Data()
{
delete[] point;
delete[] point_data;
return;
}
static const unsigned int num_items = 5;
LASitem items[num_items];
unsigned int point_size;
unsigned char* point_data;
unsigned char** point;
unsigned num_points;
bool use_random;
};
//---------------------------------------------------------------------------
static LASzipper* make_zipper(OStream* ost, Data& data, LASzip::Algorithm alg)
{
#ifndef LASZIP_HAVE_RANGECODER
if (alg == LASzip::POINT_BY_POINT_RANGE)
{
fprintf(stderr, "(skipping range encoder test)\n");
return NULL;
}
#endif
LASzipper* zipper = new LASzipper();
int stat = 0;
if (ost->m_use_iostream)
stat = zipper->open(*ost->ostream, data.num_items, data.items, alg);
else
stat = zipper->open(ost->ofile, data.num_items, data.items, alg);
if (stat != 0)
{
fprintf(stderr, "ERROR: could not open laszipper with %s\n", ost->m_filename);
exit(1);
}
return zipper;
}
//---------------------------------------------------------------------------
static LASunzipper* make_unzipper(IStream* ist, Data& data, LASzip::Algorithm alg)
{
#ifndef LASZIP_HAVE_RANGECODER
if (alg == LASzip::POINT_BY_POINT_RANGE)
{
return NULL;
}
#endif
LASunzipper* unzipper = new LASunzipper();
int stat = 0;
if (ist->m_use_iostream)
stat = unzipper->open(*ist->istream, data.num_items, data.items, alg);
else
stat = unzipper->open(ist->ifile, data.num_items, data.items, alg);
if (stat != 0)
{
fprintf(stderr, "ERROR: could not open lasunzipper with %s\n", ist->m_filename);
exit(1);
}
return unzipper;
}
//---------------------------------------------------------------------------
static void write_points(LASzipper* zipper, Data& data)
{
if (zipper==NULL) // range coder test
return;
double start_time, end_time;
unsigned char c;
unsigned int i,j;
start_time = taketime();
c = 0;
for (i = 0; i < data.num_points; i++)
{
for (j = 0; j < data.point_size; j++)
{
data.point_data[j] = c;
c++;
}
zipper->write(data.point);
}
unsigned int num_bytes = zipper->close();
end_time = taketime();
fprintf(stderr, "laszipper wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time);
return;
}
//---------------------------------------------------------------------------
static void read_points(LASunzipper* unzipper, Data& data)
{
if (unzipper==NULL) // range coder test
return;
unsigned char c;
unsigned int i,j;
unsigned int num_errors, num_bytes;
double start_time, end_time;
start_time = taketime();
num_errors = 0;
c = 0;
for (i = 0; i < data.num_points; i++)
{
unzipper->read(data.point);
for (j = 0; j < data.point_size; j++)
{
if (data.point_data[j] != c)
{
fprintf(stderr, "%d %d %d != %d\n", i, j, data.point_data[j], c);
num_errors++;
if (num_errors > 20) break;
}
c++;
}
if (num_errors > 20) break;
}
num_bytes = unzipper->close();
end_time = taketime();
if (num_errors)
{
fprintf(stderr, "ERROR: with lasunzipper %d\n", num_errors);
}
else
{
fprintf(stderr, "SUCCESS: lasunzipper read %d bytes in %g seconds\n", num_bytes, end_time-start_time);
}
return;
}
//---------------------------------------------------------------------------
static void run_test(bool use_iostream, const char* filename, Data& data, LASzip::Algorithm alg)
{
OStream* ost = new OStream(use_iostream, filename);
LASzipper* laszipper = make_zipper(ost, data, alg);
write_points(laszipper, data);
delete laszipper;
delete ost;
IStream* ist = new IStream(use_iostream, filename);
LASunzipper* lasunzipper = make_unzipper(ist, data, alg);
read_points(lasunzipper, data);
delete lasunzipper;
delete ist;
return;
}
//---------------------------------------------------------------------------
int main(int argc, char *argv[])
{
unsigned int num_points = 100000;
bool use_iostream = false;
bool forever = false;
bool use_random = true;
do
{
Data data(num_points, use_random);
run_test(use_iostream, "test1.lax", data, LASzip::POINT_BY_POINT_RAW);
run_test(use_iostream, "test2.lax", data, LASzip::POINT_BY_POINT_ARITHMETIC);
run_test(use_iostream, "test3.lax", data, LASzip::POINT_BY_POINT_RANGE);
} while (forever);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef AMGCL_SOLVERS_CG_HPP
#define AMGCL_SOLVERS_CG_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <[email protected]>
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.
*/
/**
* \file amgcl/solver/cg.hpp
* \author Denis Demidov <[email protected]>
* \brief Conjugate Gradient method.
*/
#include <boost/tuple/tuple.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
/// Iterative solvers
namespace solver {
/**
* \defgroup solvers
* \brief Iterative solvers
*
* AMGCL provides several iterative solvers, but it should be easy to use it as
* a preconditioner with a user-provided solver. Each solver in AMGCL is a
* class template. Its single template parameter specifies the backend to use.
* This allows to preallocate necessary resources at class construction.
* Obviously, the solver backend has to coincide with the AMG backend.
*/
/// Conjugate Gradients iterative solver.
/**
* \param Backend Backend for temporary structures allocation.
* \ingroup solvers
* \sa \cite Barrett1994
*/
template <
class Backend,
class InnerProduct = detail::default_inner_product
>
class cg {
public:
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename Backend::params backend_params;
/// Solver parameters.
struct params {
/// Maximum number of iterations.
size_t maxiter;
/// Target residual error.
value_type tol;
params(size_t maxiter = 100, value_type tol = 1e-8)
: maxiter(maxiter), tol(tol)
{}
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
AMGCL_PARAMS_IMPORT_VALUE(p, tol)
{}
};
/// Preallocates necessary data structures
/**
* \param n The system size.
* \param prm Solver parameters.
* \param backend_prm Backend parameters.
*/
cg(
size_t n,
const params &prm = params(),
const backend_params &backend_prm = backend_params(),
const InnerProduct &inner_product = InnerProduct()
) : prm(prm), n(n),
r(Backend::create_vector(n, backend_prm)),
s(Backend::create_vector(n, backend_prm)),
p(Backend::create_vector(n, backend_prm)),
q(Backend::create_vector(n, backend_prm)),
inner_product(inner_product)
{ }
/// Solves the linear system for the given system matrix.
/**
* \param A System matrix.
* \param P Preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*
* The system matrix may differ from the matrix used for the AMG
* preconditioner construction. This may be used for the solution of
* non-stationary problems with slowly changing coefficients. There is
* a strong chance that AMG built for one time step will act as a
* reasonably good preconditioner for several subsequent time steps
* \cite Demidov2012.
*/
template <class Matrix, class Precond, class Vec1, class Vec2>
boost::tuple<size_t, value_type> operator()(
Matrix const &A,
Precond const &P,
Vec1 const &rhs,
Vec2 &x
) const
{
backend::residual(rhs, A, x, *r);
value_type norm_rhs = norm(rhs);
if (norm_rhs < amgcl::detail::eps<value_type>(n)) {
backend::clear(x);
return boost::make_tuple(0, norm_rhs);
}
value_type eps = prm.tol * norm_rhs;
value_type rho1 = 2 * eps * eps, rho2 = 0;
value_type res_norm = norm(*r);
size_t iter = 0;
while(res_norm > eps && iter < prm.maxiter) {
for(bool first = true; iter < prm.maxiter; ++iter) {
P.apply(*r, *s);
rho2 = rho1;
rho1 = inner_product(*r, *s);
if (first) {
backend::copy(*s, *p);
first = false;
} else {
backend::axpby(1, *s, rho1 / rho2, *p);
}
backend::spmv(1, A, *p, 0, *q);
value_type alpha = rho1 / inner_product(*q, *p);
backend::axpby( alpha, *p, 1, x);
backend::axpby(-alpha, *q, 1, *r);
if (rho1 < eps * eps) break;
}
backend::residual(rhs, A, x, *r);
res_norm = norm(*r);
}
return boost::make_tuple(iter, res_norm / norm_rhs);
}
/// Solves the linear system for the same matrix that was used for the AMG preconditioner construction.
/**
* \param P AMG preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*/
template <class Precond, class Vec1, class Vec2>
boost::tuple<size_t, value_type> operator()(
Precond const &P,
Vec1 const &rhs,
Vec2 &x
) const
{
return (*this)(P.top_matrix(), P, rhs, x);
}
private:
params prm;
size_t n;
boost::shared_ptr<vector> r;
boost::shared_ptr<vector> s;
boost::shared_ptr<vector> p;
boost::shared_ptr<vector> q;
InnerProduct inner_product;
template <class Vec>
value_type norm(const Vec &x) const {
return sqrt(inner_product(x, x));
}
};
} // namespace solver
} // namespace amgcl
#endif
<commit_msg>Revert "Fixed a bug in solver::cg"<commit_after>#ifndef AMGCL_SOLVERS_CG_HPP
#define AMGCL_SOLVERS_CG_HPP
/*
The MIT License
Copyright (c) 2012-2014 Denis Demidov <[email protected]>
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.
*/
/**
* \file amgcl/solver/cg.hpp
* \author Denis Demidov <[email protected]>
* \brief Conjugate Gradient method.
*/
#include <boost/tuple/tuple.hpp>
#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>
namespace amgcl {
/// Iterative solvers
namespace solver {
/**
* \defgroup solvers
* \brief Iterative solvers
*
* AMGCL provides several iterative solvers, but it should be easy to use it as
* a preconditioner with a user-provided solver. Each solver in AMGCL is a
* class template. Its single template parameter specifies the backend to use.
* This allows to preallocate necessary resources at class construction.
* Obviously, the solver backend has to coincide with the AMG backend.
*/
/// Conjugate Gradients iterative solver.
/**
* \param Backend Backend for temporary structures allocation.
* \ingroup solvers
* \sa \cite Barrett1994
*/
template <
class Backend,
class InnerProduct = detail::default_inner_product
>
class cg {
public:
typedef typename Backend::vector vector;
typedef typename Backend::value_type value_type;
typedef typename Backend::params backend_params;
/// Solver parameters.
struct params {
/// Maximum number of iterations.
size_t maxiter;
/// Target residual error.
value_type tol;
params(size_t maxiter = 100, value_type tol = 1e-8)
: maxiter(maxiter), tol(tol)
{}
params(const boost::property_tree::ptree &p)
: AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
AMGCL_PARAMS_IMPORT_VALUE(p, tol)
{}
};
/// Preallocates necessary data structures
/**
* \param n The system size.
* \param prm Solver parameters.
* \param backend_prm Backend parameters.
*/
cg(
size_t n,
const params &prm = params(),
const backend_params &backend_prm = backend_params(),
const InnerProduct &inner_product = InnerProduct()
) : prm(prm), n(n),
r(Backend::create_vector(n, backend_prm)),
s(Backend::create_vector(n, backend_prm)),
p(Backend::create_vector(n, backend_prm)),
q(Backend::create_vector(n, backend_prm)),
inner_product(inner_product)
{ }
/// Solves the linear system for the given system matrix.
/**
* \param A System matrix.
* \param P Preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*
* The system matrix may differ from the matrix used for the AMG
* preconditioner construction. This may be used for the solution of
* non-stationary problems with slowly changing coefficients. There is
* a strong chance that AMG built for one time step will act as a
* reasonably good preconditioner for several subsequent time steps
* \cite Demidov2012.
*/
template <class Matrix, class Precond, class Vec1, class Vec2>
boost::tuple<size_t, value_type> operator()(
Matrix const &A,
Precond const &P,
Vec1 const &rhs,
Vec2 &x
) const
{
backend::residual(rhs, A, x, *r);
value_type norm_rhs = norm(rhs);
if (norm_rhs < amgcl::detail::eps<value_type>(n)) {
backend::clear(x);
return boost::make_tuple(0, norm_rhs);
}
value_type eps = prm.tol * norm_rhs;
value_type rho1 = 2 * eps * eps, rho2 = 0;
value_type res_norm = norm(*r);
size_t iter = 0;
while(res_norm > eps && iter < prm.maxiter) {
for(; iter < prm.maxiter; ++iter) {
P.apply(*r, *s);
rho2 = rho1;
rho1 = inner_product(*r, *s);
if (iter)
backend::axpby(1, *s, rho1 / rho2, *p);
else
backend::copy(*s, *p);
backend::spmv(1, A, *p, 0, *q);
value_type alpha = rho1 / inner_product(*q, *p);
backend::axpby( alpha, *p, 1, x);
backend::axpby(-alpha, *q, 1, *r);
if (rho1 < eps * eps) break;
}
backend::residual(rhs, A, x, *r);
res_norm = norm(*r);
}
return boost::make_tuple(iter, res_norm / norm_rhs);
}
/// Solves the linear system for the same matrix that was used for the AMG preconditioner construction.
/**
* \param P AMG preconditioner.
* \param rhs Right-hand side.
* \param x Solution vector.
*/
template <class Precond, class Vec1, class Vec2>
boost::tuple<size_t, value_type> operator()(
Precond const &P,
Vec1 const &rhs,
Vec2 &x
) const
{
return (*this)(P.top_matrix(), P, rhs, x);
}
private:
params prm;
size_t n;
boost::shared_ptr<vector> r;
boost::shared_ptr<vector> s;
boost::shared_ptr<vector> p;
boost::shared_ptr<vector> q;
InnerProduct inner_product;
template <class Vec>
value_type norm(const Vec &x) const {
return sqrt(inner_product(x, x));
}
};
} // namespace solver
} // namespace amgcl
#endif
<|endoftext|> |
<commit_before>// Copyright 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.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This program converts a GPX file to a KML Tour of FlyTo's. Each <trkpt>
// is translated to a <gx:FlyTo>/<LookAt> to the lat/lon of the trkpt and
// all <gx:FlyTo>'s are put in one <gx:Tour>/<gx:Playlist>.
#include <iostream>
#include "kml/base/expat_parser.h"
#include "kml/base/date_time.h"
#include "kml/base/file.h"
#include "kml/base/math_util.h"
#include "kml/base/vec3.h"
#include "kml/base/xml_namespaces.h"
#include "kml/convenience/convenience.h"
#include "kml/convenience/gpx_trk_pt_handler.h"
#include "kml/dom.h"
#include "kml/engine.h"
using kmlbase::AzimuthBetweenPoints;
using kmlbase::DateTime;
using kmlbase::DistanceBetweenPoints;
using kmlbase::ExpatParser;
using kmlbase::GroundDistanceFromRangeAndElevation;
using kmlbase::HeightFromRangeAndElevation;
using kmlbase::Vec3;
using kmlconvenience::CreatePointLatLon;
using kmldom::CameraPtr;
using kmldom::ChangePtr;
using kmldom::ContainerPtr;
using kmldom::DocumentPtr;
using kmldom::GxAnimatedUpdatePtr;
using kmldom::GxFlyToPtr;
using kmldom::GxPlaylistPtr;
using kmldom::GxTourPtr;
using kmldom::GxWaitPtr;
using kmldom::KmlFactory;
using kmldom::KmlPtr;
using kmldom::PlacemarkPtr;
using kmldom::UpdatePtr;
using kmlengine::KmlFile;
using kmlengine::KmlFilePtr;
// Return a <gx:FlyTo> with <Camera> as specified by the lat, lon and heading
// and with a range scaled by speed. The duration is used as the <gx:duration>
// of the <gx:FlyTo>.
static GxFlyToPtr CreateGxFlyTo(double lat, double lon, double heading,
double duration, double speed) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
// Tilt the camera back as speed increases, but clamp max tilt.
double tilt = 0 + speed * 4;
if (tilt > 65.) tilt = 65.;
// The distance along the vector from the gpx point to eyepoint.
double range = 100.0 + tilt * 7;
// The ground distance between the gpx point and the subpoint of where
// we'll place the camera.
double distance = GroundDistanceFromRangeAndElevation(range, 90 - tilt);
// The lat,lon of the camera.
double reverse_heading = fmod(heading + 180.0, 360.0);
Vec3 camera_position =
kmlbase::LatLngOnRadialFromPoint(lat, lon, distance, reverse_heading);
CameraPtr camera = kml_factory->CreateCamera();
camera->set_latitude(camera_position.get_latitude());
camera->set_longitude(camera_position.get_longitude());
camera->set_altitude(HeightFromRangeAndElevation(range, 90 - tilt));
camera->set_heading(heading);
// Nudge the tilt up a little to move the icon towards the bottom of the
// screen.
camera->set_tilt(tilt *= 1.1);
GxFlyToPtr flyto = kml_factory->CreateGxFlyTo();
flyto->set_abstractview(camera);
flyto->set_gx_duration(duration);
// TODO: the first FlyTo in a Playlist often better as bounce
flyto->set_gx_flytomode(kmldom::GX_FLYTOMODE_SMOOTH);
return flyto;
}
static GxAnimatedUpdatePtr CreateAnimatedUpdate(const std::string& target_id,
double lat, double lon,
double duration) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
PlacemarkPtr placemark = kml_factory->CreatePlacemark();
placemark->set_targetid(target_id);
placemark->set_geometry(CreatePointLatLon(lat, lon));
ChangePtr change = kml_factory->CreateChange();
change->add_object(placemark);
UpdatePtr update = kml_factory->CreateUpdate();
update->add_updateoperation(change);
update->set_targethref("");
GxAnimatedUpdatePtr animated_update = kml_factory->CreateGxAnimatedUpdate();
animated_update->set_update(update);
animated_update->set_gx_duration(duration);
return animated_update;
}
// TODO: move to convenience
static GxWaitPtr CreateWait(double duration) {
GxWaitPtr wait = KmlFactory::GetFactory()->CreateGxWait();
wait->set_gx_duration(duration);
return wait;
}
// This specialization of the GpxTrkPtHandler converts each GPX <trkpt> to
// a KML <gx:AnimatedUpdate> + <gx:FlyTo>.
class TourTrkPtHandler : public kmlconvenience::GpxTrkPtHandler {
public:
TourTrkPtHandler(ContainerPtr container)
: placemark_id_("moving-placemark"),
previous_when_(0),
container_(container),
playlist_(KmlFactory::GetFactory()->CreateGxPlaylist()) {
}
// This is called for each <trkpt>.
virtual void HandlePoint(const kmlbase::Vec3& where,
const std::string& when) {
time_t when_timet = DateTime::ToTimeT(when);
if (when_timet == 0) {
std::cerr << "Ignoring point with no time" << std::endl;
return;
}
if (previous_when_ == 0) { // First point
PlacemarkPtr placemark = KmlFactory::GetFactory()->CreatePlacemark();
placemark->set_id(placemark_id_);
placemark->set_geometry(CreatePointLatLon(where.get_latitude(),
where.get_longitude()));
container_->add_feature(placemark);
GxTourPtr tour(KmlFactory::GetFactory()->CreateGxTour());
tour->set_name("Play me!");
tour->set_gx_playlist(playlist_);
container_->add_feature(tour);
} else {
// Convert the GPX <trkpt> to a <gx:AnimatedUpdate> + <gx:FlyTo>.
// Note, it's quite important that the AnimatedUpdate appear _before_
// the FlyTo given that a FlyTo will happen during an AnimatedUpdate
// but an AnimatedUpdate will _not_ start until a FlyTo is done.
const double duration = when_timet - previous_when_;
if (duration < 0) {
std::cerr << "Ignoring point out of time order." << std::endl;
} else {
playlist_->add_gx_tourprimitive(
CreateAnimatedUpdate(placemark_id_, where.get_latitude(),
where.get_longitude(), duration));
const double heading = AzimuthBetweenPoints(
previous_where_.get_latitude(), previous_where_.get_longitude(),
where.get_latitude(), where.get_longitude());
const double speed = DistanceBetweenPoints(
previous_where_.get_latitude(), previous_where_.get_longitude(),
where.get_latitude(), where.get_longitude()) / duration;
playlist_->add_gx_tourprimitive(
CreateGxFlyTo(where.get_latitude(), where.get_longitude(),
heading, duration, speed));
// Wait 0 to create smooth animated update...
playlist_->add_gx_tourprimitive(CreateWait(0));
}
}
previous_when_ = when_timet;
previous_where_ = where;
}
private:
const std::string placemark_id_;
kmlbase::Vec3 previous_where_;
time_t previous_when_;
ContainerPtr container_;
GxPlaylistPtr playlist_;
};
// Parse the gpx file and make a KML tour to save out to the kml file.
static bool CreateGpxTour(const char* gpx_pathname, const char* kml_pathname) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
// Create a <Document> and hand it to the GPX parser.
DocumentPtr document = kml_factory->CreateDocument();
document->set_open(1);
TourTrkPtHandler tour_maker(document);
// Read the GPX file contents.
std::string gpx_data;
if (!kmlbase::File::ReadFileToString(gpx_pathname, &gpx_data)) {
std::cerr << "read failed: " << gpx_pathname << std::endl;
return false;
}
// Parse the GPX data writing a Tour into the <Document>.
std::string errors;
if (!ExpatParser::ParseString(gpx_data, &tour_maker, &errors, false)) {
std::cerr << "parse failed: " << gpx_pathname << std::endl;
return false;
}
// Put the <Document> in a <kml> element and write everything out to the
// supplied pathname.
KmlPtr kml = kml_factory->CreateKml();
kml->set_feature(document);
KmlFilePtr kml_file = KmlFile::CreateFromImport(kml);
// TODO: get rid of this once CreateFromImport discovers namespaces.
kml_file->AddXmlNamespaceById(kmlbase::XMLNS_GX22);
std::string kml_data;
kml_file->SerializeToString(&kml_data);
if (!kmlbase::File::WriteStringToFile(kml_data, kml_pathname)) {
std::cerr << "write failed: " << kml_pathname << std::endl;
return false;
}
return true;
}
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "usage: " << argv[0] << " input.gpx output.kml" << std::endl;
return 1;
}
return CreateGpxTour(argv[1], argv[2]) ? 0 : 1;
}
<commit_msg>CreateWait is in convenience<commit_after>// Copyright 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.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This program converts a GPX file to a KML Tour of FlyTo's. Each <trkpt>
// is translated to a <gx:FlyTo>/<LookAt> to the lat/lon of the trkpt and
// all <gx:FlyTo>'s are put in one <gx:Tour>/<gx:Playlist>.
#include <iostream>
#include "kml/base/expat_parser.h"
#include "kml/base/date_time.h"
#include "kml/base/file.h"
#include "kml/base/math_util.h"
#include "kml/base/vec3.h"
#include "kml/base/xml_namespaces.h"
#include "kml/convenience/convenience.h"
#include "kml/convenience/gpx_trk_pt_handler.h"
#include "kml/dom.h"
#include "kml/engine.h"
using kmlbase::AzimuthBetweenPoints;
using kmlbase::DateTime;
using kmlbase::DistanceBetweenPoints;
using kmlbase::ExpatParser;
using kmlbase::GroundDistanceFromRangeAndElevation;
using kmlbase::HeightFromRangeAndElevation;
using kmlbase::Vec3;
using kmlconvenience::CreatePointLatLon;
using kmldom::CameraPtr;
using kmldom::ChangePtr;
using kmldom::ContainerPtr;
using kmldom::DocumentPtr;
using kmldom::GxAnimatedUpdatePtr;
using kmldom::GxFlyToPtr;
using kmldom::GxPlaylistPtr;
using kmldom::GxTourPtr;
using kmldom::GxWaitPtr;
using kmldom::KmlFactory;
using kmldom::KmlPtr;
using kmldom::PlacemarkPtr;
using kmldom::UpdatePtr;
using kmlengine::KmlFile;
using kmlengine::KmlFilePtr;
// Return a <gx:FlyTo> with <Camera> as specified by the lat, lon and heading
// and with a range scaled by speed. The duration is used as the <gx:duration>
// of the <gx:FlyTo>.
static GxFlyToPtr CreateGxFlyTo(double lat, double lon, double heading,
double duration, double speed) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
// Tilt the camera back as speed increases, but clamp max tilt.
double tilt = 0 + speed * 4;
if (tilt > 65.) tilt = 65.;
// The distance along the vector from the gpx point to eyepoint.
double range = 100.0 + tilt * 7;
// The ground distance between the gpx point and the subpoint of where
// we'll place the camera.
double distance = GroundDistanceFromRangeAndElevation(range, 90 - tilt);
// The lat,lon of the camera.
double reverse_heading = fmod(heading + 180.0, 360.0);
Vec3 camera_position =
kmlbase::LatLngOnRadialFromPoint(lat, lon, distance, reverse_heading);
CameraPtr camera = kml_factory->CreateCamera();
camera->set_latitude(camera_position.get_latitude());
camera->set_longitude(camera_position.get_longitude());
camera->set_altitude(HeightFromRangeAndElevation(range, 90 - tilt));
camera->set_heading(heading);
// Nudge the tilt up a little to move the icon towards the bottom of the
// screen.
camera->set_tilt(tilt *= 1.1);
GxFlyToPtr flyto = kml_factory->CreateGxFlyTo();
flyto->set_abstractview(camera);
flyto->set_gx_duration(duration);
// TODO: the first FlyTo in a Playlist often better as bounce
flyto->set_gx_flytomode(kmldom::GX_FLYTOMODE_SMOOTH);
return flyto;
}
static GxAnimatedUpdatePtr CreateAnimatedUpdate(const std::string& target_id,
double lat, double lon,
double duration) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
PlacemarkPtr placemark = kml_factory->CreatePlacemark();
placemark->set_targetid(target_id);
placemark->set_geometry(CreatePointLatLon(lat, lon));
ChangePtr change = kml_factory->CreateChange();
change->add_object(placemark);
UpdatePtr update = kml_factory->CreateUpdate();
update->add_updateoperation(change);
update->set_targethref("");
GxAnimatedUpdatePtr animated_update = kml_factory->CreateGxAnimatedUpdate();
animated_update->set_update(update);
animated_update->set_gx_duration(duration);
return animated_update;
}
// This specialization of the GpxTrkPtHandler converts each GPX <trkpt> to
// a KML <gx:AnimatedUpdate> + <gx:FlyTo>.
class TourTrkPtHandler : public kmlconvenience::GpxTrkPtHandler {
public:
TourTrkPtHandler(ContainerPtr container)
: placemark_id_("moving-placemark"),
previous_when_(0),
container_(container),
playlist_(KmlFactory::GetFactory()->CreateGxPlaylist()) {
}
// This is called for each <trkpt>.
virtual void HandlePoint(const kmlbase::Vec3& where,
const std::string& when) {
time_t when_timet = DateTime::ToTimeT(when);
if (when_timet == 0) {
std::cerr << "Ignoring point with no time" << std::endl;
return;
}
if (previous_when_ == 0) { // First point
PlacemarkPtr placemark = KmlFactory::GetFactory()->CreatePlacemark();
placemark->set_id(placemark_id_);
placemark->set_geometry(CreatePointLatLon(where.get_latitude(),
where.get_longitude()));
container_->add_feature(placemark);
GxTourPtr tour(KmlFactory::GetFactory()->CreateGxTour());
tour->set_name("Play me!");
tour->set_gx_playlist(playlist_);
container_->add_feature(tour);
} else {
// Convert the GPX <trkpt> to a <gx:AnimatedUpdate> + <gx:FlyTo>.
// Note, it's quite important that the AnimatedUpdate appear _before_
// the FlyTo given that a FlyTo will happen during an AnimatedUpdate
// but an AnimatedUpdate will _not_ start until a FlyTo is done.
const double duration = when_timet - previous_when_;
if (duration < 0) {
std::cerr << "Ignoring point out of time order." << std::endl;
} else {
playlist_->add_gx_tourprimitive(
CreateAnimatedUpdate(placemark_id_, where.get_latitude(),
where.get_longitude(), duration));
const double heading = AzimuthBetweenPoints(
previous_where_.get_latitude(), previous_where_.get_longitude(),
where.get_latitude(), where.get_longitude());
const double speed = DistanceBetweenPoints(
previous_where_.get_latitude(), previous_where_.get_longitude(),
where.get_latitude(), where.get_longitude()) / duration;
playlist_->add_gx_tourprimitive(
CreateGxFlyTo(where.get_latitude(), where.get_longitude(),
heading, duration, speed));
// Wait 0 to create smooth animated update...
playlist_->add_gx_tourprimitive(kmlconvenience::CreateWait(0));
}
}
previous_when_ = when_timet;
previous_where_ = where;
}
private:
const std::string placemark_id_;
kmlbase::Vec3 previous_where_;
time_t previous_when_;
ContainerPtr container_;
GxPlaylistPtr playlist_;
};
// Parse the gpx file and make a KML tour to save out to the kml file.
static bool CreateGpxTour(const char* gpx_pathname, const char* kml_pathname) {
KmlFactory* kml_factory = KmlFactory::GetFactory();
// Create a <Document> and hand it to the GPX parser.
DocumentPtr document = kml_factory->CreateDocument();
document->set_open(1);
TourTrkPtHandler tour_maker(document);
// Read the GPX file contents.
std::string gpx_data;
if (!kmlbase::File::ReadFileToString(gpx_pathname, &gpx_data)) {
std::cerr << "read failed: " << gpx_pathname << std::endl;
return false;
}
// Parse the GPX data writing a Tour into the <Document>.
std::string errors;
if (!ExpatParser::ParseString(gpx_data, &tour_maker, &errors, false)) {
std::cerr << "parse failed: " << gpx_pathname << std::endl;
return false;
}
// Put the <Document> in a <kml> element and write everything out to the
// supplied pathname.
KmlPtr kml = kml_factory->CreateKml();
kml->set_feature(document);
KmlFilePtr kml_file = KmlFile::CreateFromImport(kml);
// TODO: get rid of this once CreateFromImport discovers namespaces.
kml_file->AddXmlNamespaceById(kmlbase::XMLNS_GX22);
std::string kml_data;
kml_file->SerializeToString(&kml_data);
if (!kmlbase::File::WriteStringToFile(kml_data, kml_pathname)) {
std::cerr << "write failed: " << kml_pathname << std::endl;
return false;
}
return true;
}
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "usage: " << argv[0] << " input.gpx output.kml" << std::endl;
return 1;
}
return CreateGpxTour(argv[1], argv[2]) ? 0 : 1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fmtline.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mba $ $Date: 2002-06-10 17:00:58 $
*
* 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 SW_FMTLINE_HXX
#define SW_FMTLINE_HXX
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class IntlWrapper;
class SwFmtLineNumber: public SfxPoolItem
{
ULONG nStartValue :24; //Startwert fuer den Absatz, 0 == kein Startwert
ULONG bCountLines :1; //Zeilen des Absatzes sollen mitgezaehlt werden.
public:
SwFmtLineNumber();
~SwFmtLineNumber();
TYPEINFO();
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;
virtual SvStream& Store(SvStream &, USHORT nIVer) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual USHORT GetVersion( USHORT nFFVer ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
ULONG GetStartValue() const { return nStartValue; }
BOOL IsCount() const { return bCountLines != 0; }
void SetStartValue( ULONG nNew ) { nStartValue = nNew; }
void SetCountLines( BOOL b ) { bCountLines = b; }
};
inline const SwFmtLineNumber &SwAttrSet::GetLineNumber(BOOL bInP) const
{ return (const SwFmtLineNumber&)Get( RES_LINENUMBER,bInP); }
inline const SwFmtLineNumber &SwFmt::GetLineNumber(BOOL bInP) const
{ return aSet.GetLineNumber(bInP); }
#endif
<commit_msg>#101685#,#i6886#: merge OOO_STABLE_1_PORTS (1.2-1.2.20.1) -> HEAD<commit_after>/*************************************************************************
*
* $RCSfile: fmtline.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2002-08-23 13:32:13 $
*
* 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 SW_FMTLINE_HXX
#define SW_FMTLINE_HXX
#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
class IntlWrapper;
class SwFmtLineNumber: public SfxPoolItem
{
ULONG nStartValue :24; //Startwert fuer den Absatz, 0 == kein Startwert
ULONG bCountLines :1; //Zeilen des Absatzes sollen mitgezaehlt werden.
public:
SwFmtLineNumber();
~SwFmtLineNumber();
TYPEINFO();
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;
virtual SvStream& Store(SvStream &, USHORT nIVer) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual USHORT GetVersion( USHORT nFFVer ) const;
virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
ULONG GetStartValue() const { return nStartValue; }
BOOL IsCount() const { return bCountLines != 0; }
void SetStartValue( ULONG nNew ) { nStartValue = nNew; }
void SetCountLines( BOOL b ) { bCountLines = b; }
};
#ifndef MACOSX
// GrP moved to gcc_outl.cxx; revisit with gcc3
inline const SwFmtLineNumber &SwAttrSet::GetLineNumber(BOOL bInP) const
{ return (const SwFmtLineNumber&)Get( RES_LINENUMBER,bInP); }
inline const SwFmtLineNumber &SwFmt::GetLineNumber(BOOL bInP) const
{ return aSet.GetLineNumber(bInP); }
#endif
#endif
<|endoftext|> |
<commit_before>#include <plasp/sas/Description.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <plasp/utils/ParserException.h>
#include <plasp/sas/VariableTransition.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Description::Description()
: m_usesActionCosts{false}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromParser(utils::Parser &&parser)
{
parser.setCaseSensitive(true);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromStream(std::istream &istream)
{
utils::Parser parser;
parser.readStream("std::cin", istream);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromFile(const boost::filesystem::path &path)
{
if (!boost::filesystem::is_regular_file(path))
throw std::runtime_error("File does not exist: \"" + path.string() + "\"");
utils::Parser parser;
parser.readFile(path);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesActionCosts() const
{
return m_usesActionCosts;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Variables &Description::variables() const
{
return m_variables;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const MutexGroups &Description::mutexGroups() const
{
return m_mutexGroups;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const InitialState &Description::initialState() const
{
return *m_initialState;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Goal &Description::goal() const
{
return *m_goal;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Operators &Description::operators() const
{
return m_operators;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const AxiomRules &Description::axiomRules() const
{
return m_axiomRules;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesAxiomRules() const
{
if (!m_axiomRules.empty())
return true;
const auto match = std::find_if(m_variables.cbegin(), m_variables.cend(),
[&](const auto &variable)
{
return variable.axiomLayer() != -1;
});
return match != m_variables.cend();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesConditionalEffects() const
{
const auto match = std::find_if(m_operators.cbegin(), m_operators.cend(),
[&](const auto &operator_)
{
const auto &effects = operator_.effects();
const auto match = std::find_if(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
return !effect.conditions().empty();
});
return match != effects.cend();
});
return match != m_operators.cend();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseContent(utils::Parser &parser)
{
parseVersionSection(parser);
parseMetricSection(parser);
parseVariablesSection(parser);
parseMutexSection(parser);
parseInitialStateSection(parser);
parseGoalSection(parser);
parseOperatorSection(parser);
parseAxiomSection(parser);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVersionSection(utils::Parser &parser) const
{
parser.expect<std::string>("begin_version");
const auto formatVersion = parser.parse<size_t>();
if (formatVersion != 3)
throw utils::ParserException(parser, "Unsupported SAS format version (" + std::to_string(formatVersion) + ")");
parser.expect<std::string>("end_version");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMetricSection(utils::Parser &parser)
{
parser.expect<std::string>("begin_metric");
m_usesActionCosts = parser.parse<bool>();
parser.expect<std::string>("end_metric");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVariablesSection(utils::Parser &parser)
{
const auto numberOfVariables = parser.parse<size_t>();
m_variables.reserve(numberOfVariables);
for (size_t i = 0; i < numberOfVariables; i++)
m_variables.emplace_back(Variable::fromSAS(parser));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMutexSection(utils::Parser &parser)
{
const auto numberOfMutexGroups = parser.parse<size_t>();
m_mutexGroups.reserve(numberOfMutexGroups);
for (size_t i = 0; i < numberOfMutexGroups; i++)
m_mutexGroups.emplace_back(MutexGroup::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseInitialStateSection(utils::Parser &parser)
{
m_initialState = std::make_unique<InitialState>(InitialState::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseGoalSection(utils::Parser &parser)
{
m_goal = std::make_unique<Goal>(Goal::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseOperatorSection(utils::Parser &parser)
{
const auto numberOfOperators = parser.parse<size_t>();
m_operators.reserve(numberOfOperators);
for (size_t i = 0; i < numberOfOperators; i++)
m_operators.emplace_back(Operator::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseAxiomSection(utils::Parser &parser)
{
const auto numberOfAxiomRules = parser.parse<size_t>();
m_axiomRules.reserve(numberOfAxiomRules);
for (size_t i = 0; i < numberOfAxiomRules; i++)
m_axiomRules.emplace_back(AxiomRule::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<commit_msg>Ensuring input to contain only one SAS description.<commit_after>#include <plasp/sas/Description.h>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <plasp/utils/ParserException.h>
#include <plasp/sas/VariableTransition.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Description::Description()
: m_usesActionCosts{false}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromParser(utils::Parser &&parser)
{
parser.setCaseSensitive(true);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromStream(std::istream &istream)
{
utils::Parser parser;
parser.readStream("std::cin", istream);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
Description Description::fromFile(const boost::filesystem::path &path)
{
if (!boost::filesystem::is_regular_file(path))
throw std::runtime_error("File does not exist: \"" + path.string() + "\"");
utils::Parser parser;
parser.readFile(path);
Description description;
description.parseContent(parser);
return description;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesActionCosts() const
{
return m_usesActionCosts;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Variables &Description::variables() const
{
return m_variables;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const MutexGroups &Description::mutexGroups() const
{
return m_mutexGroups;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const InitialState &Description::initialState() const
{
return *m_initialState;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Goal &Description::goal() const
{
return *m_goal;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const Operators &Description::operators() const
{
return m_operators;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const AxiomRules &Description::axiomRules() const
{
return m_axiomRules;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesAxiomRules() const
{
if (!m_axiomRules.empty())
return true;
const auto match = std::find_if(m_variables.cbegin(), m_variables.cend(),
[&](const auto &variable)
{
return variable.axiomLayer() != -1;
});
return match != m_variables.cend();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Description::usesConditionalEffects() const
{
const auto match = std::find_if(m_operators.cbegin(), m_operators.cend(),
[&](const auto &operator_)
{
const auto &effects = operator_.effects();
const auto match = std::find_if(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
return !effect.conditions().empty();
});
return match != effects.cend();
});
return match != m_operators.cend();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseContent(utils::Parser &parser)
{
parseVersionSection(parser);
parseMetricSection(parser);
parseVariablesSection(parser);
parseMutexSection(parser);
parseInitialStateSection(parser);
parseGoalSection(parser);
parseOperatorSection(parser);
parseAxiomSection(parser);
parser.skipWhiteSpace();
if (!parser.atEndOfStream())
throw utils::ParserException(parser, "Expected end of SAS description");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVersionSection(utils::Parser &parser) const
{
parser.expect<std::string>("begin_version");
const auto formatVersion = parser.parse<size_t>();
if (formatVersion != 3)
throw utils::ParserException(parser, "Unsupported SAS format version (" + std::to_string(formatVersion) + ")");
parser.expect<std::string>("end_version");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMetricSection(utils::Parser &parser)
{
parser.expect<std::string>("begin_metric");
m_usesActionCosts = parser.parse<bool>();
parser.expect<std::string>("end_metric");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseVariablesSection(utils::Parser &parser)
{
const auto numberOfVariables = parser.parse<size_t>();
m_variables.reserve(numberOfVariables);
for (size_t i = 0; i < numberOfVariables; i++)
m_variables.emplace_back(Variable::fromSAS(parser));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseMutexSection(utils::Parser &parser)
{
const auto numberOfMutexGroups = parser.parse<size_t>();
m_mutexGroups.reserve(numberOfMutexGroups);
for (size_t i = 0; i < numberOfMutexGroups; i++)
m_mutexGroups.emplace_back(MutexGroup::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseInitialStateSection(utils::Parser &parser)
{
m_initialState = std::make_unique<InitialState>(InitialState::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseGoalSection(utils::Parser &parser)
{
m_goal = std::make_unique<Goal>(Goal::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseOperatorSection(utils::Parser &parser)
{
const auto numberOfOperators = parser.parse<size_t>();
m_operators.reserve(numberOfOperators);
for (size_t i = 0; i < numberOfOperators; i++)
m_operators.emplace_back(Operator::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Description::parseAxiomSection(utils::Parser &parser)
{
const auto numberOfAxiomRules = parser.parse<size_t>();
m_axiomRules.reserve(numberOfAxiomRules);
for (size_t i = 0; i < numberOfAxiomRules; i++)
m_axiomRules.emplace_back(AxiomRule::fromSAS(parser, m_variables));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<|endoftext|> |
<commit_before>void scalar_partition_epi32(uint32_t* array, const uint32_t pivot, int& left, int& right) {
while (left <= right) {
while (array[left] < pivot) {
left += 1;
}
while (array[right] > pivot) {
right -= 1;
}
if (left <= right) {
const uint32_t l = array[left];
const uint32_t r = array[right];
if (l != r) {
array[left] = r;
array[right] = l;
}
left += 1;
right -= 1;
}
}
}
<commit_msg>Revert "AVX512 quicksort: better scalar partition"<commit_after>void scalar_partition_epi32(uint32_t* array, const uint32_t pivot, int& left, int& right) {
while (left <= right) {
while (array[left] < pivot) {
left += 1;
}
while (array[right] > pivot) {
right -= 1;
}
if (left <= right) {
const uint32_t t = array[left];
array[left] = array[right];
array[right] = t;
left += 1;
right -= 1;
}
}
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Base class header file
#include "XPathFunctionTable.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include "FunctionBoolean.hpp"
#include "FunctionCeiling.hpp"
#include "FunctionConcat.hpp"
#include "FunctionContains.hpp"
#include "FunctionCount.hpp"
#include "FunctionFalse.hpp"
#include "FunctionFloor.hpp"
#include "FunctionID.hpp"
#include "FunctionLang.hpp"
#include "FunctionLast.hpp"
#include "FunctionLocalName.hpp"
#include "FunctionName.hpp"
#include "FunctionNamespaceURI.hpp"
#include "FunctionNormalize.hpp"
#include "FunctionNot.hpp"
#include "FunctionNumber.hpp"
#include "FunctionPosition.hpp"
#include "FunctionRound.hpp"
#include "FunctionStartsWith.hpp"
#include "FunctionString.hpp"
#include "FunctionStringLength.hpp"
#include "FunctionSubstring.hpp"
#include "FunctionSubstringAfter.hpp"
#include "FunctionSubstringBefore.hpp"
#include "FunctionSum.hpp"
#include "FunctionTranslate.hpp"
#include "FunctionTrue.hpp"
XPathFunctionTable::XPathFunctionTable() :
m_FunctionCollection()
{
CreateTable();
}
XPathFunctionTable::~XPathFunctionTable()
{
DestroyTable();
}
void
XPathFunctionTable::InstallFunction(
const DOMString& theFunctionName,
const Function& theFunction)
{
assert(length(theFunctionName) != 0);
// Delete the currently installed function, if there is
// one
delete m_FunctionCollection[theFunctionName];
// Clone the function and add it to the collection.
m_FunctionCollection[theFunctionName] = theFunction.clone();
}
void
XPathFunctionTable::CreateTable()
{
try
{
InstallFunction("last",
FunctionLast());
InstallFunction("position",
FunctionPosition());
InstallFunction("count",
FunctionCount());
InstallFunction("id",
FunctionID());
InstallFunction("local-name",
FunctionLocalName());
InstallFunction("namespace-uri",
FunctionNamespaceURI());
InstallFunction("name",
FunctionName());
InstallFunction("string",
FunctionString());
InstallFunction("concat",
FunctionConcat());
InstallFunction("starts-with",
FunctionStartsWith());
InstallFunction("contains",
FunctionContains());
InstallFunction("substring-before",
FunctionSubstringBefore());
InstallFunction("substring-after",
FunctionSubstringAfter());
InstallFunction("substring",
FunctionSubstring());
InstallFunction("string-length",
FunctionStringLength());
InstallFunction("normalize-space",
FunctionNormalizeSpace());
InstallFunction("translate",
FunctionTranslate());
InstallFunction("boolean",
FunctionBoolean());
InstallFunction("not",
FunctionNot());
InstallFunction("true",
FunctionTrue());
InstallFunction("false",
FunctionFalse());
InstallFunction("lang",
FunctionLang());
InstallFunction("number",
FunctionNumber());
InstallFunction("sum",
FunctionSum());
InstallFunction("floor",
FunctionFloor());
InstallFunction("ceiling",
FunctionCeiling());
InstallFunction("round",
FunctionRound());
}
catch(...)
{
DestroyTable();
throw;
}
}
void
XPathFunctionTable::DestroyTable()
{
try
{
std::for_each(m_FunctionCollection.begin(),
m_FunctionCollection.end(),
DeleteFunctorType());
}
catch(...)
{
}
}
XPathFunctionTableException::XPathFunctionTableException(const DOMString& theMessage) :
XPathException(theMessage)
{
}
XPathFunctionTableException::~XPathFunctionTableException()
{
}
XPathFunctionTableInvalidFunctionException::XPathFunctionTableInvalidFunctionException(const DOMString& theFunctionName) :
XPathFunctionTableException(FormatMessage(theFunctionName))
{
}
XPathFunctionTableInvalidFunctionException::~XPathFunctionTableInvalidFunctionException()
{
}
DOMString
XPathFunctionTableInvalidFunctionException::FormatMessage(const DOMString& theFunctionName)
{
const char* theMessage =
"Invalid function name detected: ";
return DOMString(theMessage) + theFunctionName;
}
<commit_msg>New static string initialization.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Base class header file
#include "XPathFunctionTable.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include "FunctionBoolean.hpp"
#include "FunctionCeiling.hpp"
#include "FunctionConcat.hpp"
#include "FunctionContains.hpp"
#include "FunctionCount.hpp"
#include "FunctionFalse.hpp"
#include "FunctionFloor.hpp"
#include "FunctionID.hpp"
#include "FunctionLang.hpp"
#include "FunctionLast.hpp"
#include "FunctionLocalName.hpp"
#include "FunctionName.hpp"
#include "FunctionNamespaceURI.hpp"
#include "FunctionNormalize.hpp"
#include "FunctionNot.hpp"
#include "FunctionNumber.hpp"
#include "FunctionPosition.hpp"
#include "FunctionRound.hpp"
#include "FunctionStartsWith.hpp"
#include "FunctionString.hpp"
#include "FunctionStringLength.hpp"
#include "FunctionSubstring.hpp"
#include "FunctionSubstringAfter.hpp"
#include "FunctionSubstringBefore.hpp"
#include "FunctionSum.hpp"
#include "FunctionTranslate.hpp"
#include "FunctionTrue.hpp"
XPathFunctionTable::XPathFunctionTable() :
m_FunctionCollection()
{
CreateTable();
}
XPathFunctionTable::~XPathFunctionTable()
{
DestroyTable();
}
void
XPathFunctionTable::InstallFunction(
const DOMString& theFunctionName,
const Function& theFunction)
{
assert(length(theFunctionName) != 0);
// Delete the currently installed function, if there is
// one
delete m_FunctionCollection[theFunctionName];
// Clone the function and add it to the collection.
m_FunctionCollection[theFunctionName] = theFunction.clone();
}
void
XPathFunctionTable::CreateTable()
{
try
{
InstallFunction(XALAN_STATIC_UCODE_STRING("last"),
FunctionLast());
InstallFunction(XALAN_STATIC_UCODE_STRING("position"),
FunctionPosition());
InstallFunction(XALAN_STATIC_UCODE_STRING("count"),
FunctionCount());
InstallFunction(XALAN_STATIC_UCODE_STRING("id"),
FunctionID());
InstallFunction(XALAN_STATIC_UCODE_STRING("local-name"),
FunctionLocalName());
InstallFunction(XALAN_STATIC_UCODE_STRING("namespace-uri"),
FunctionNamespaceURI());
InstallFunction(XALAN_STATIC_UCODE_STRING("name"),
FunctionName());
InstallFunction(XALAN_STATIC_UCODE_STRING("string"),
FunctionString());
InstallFunction(XALAN_STATIC_UCODE_STRING("concat"),
FunctionConcat());
InstallFunction(XALAN_STATIC_UCODE_STRING("starts-with"),
FunctionStartsWith());
InstallFunction(XALAN_STATIC_UCODE_STRING("contains"),
FunctionContains());
InstallFunction(XALAN_STATIC_UCODE_STRING("substring-before"),
FunctionSubstringBefore());
InstallFunction(XALAN_STATIC_UCODE_STRING("substring-after"),
FunctionSubstringAfter());
InstallFunction(XALAN_STATIC_UCODE_STRING("substring"),
FunctionSubstring());
InstallFunction(XALAN_STATIC_UCODE_STRING("string-length"),
FunctionStringLength());
InstallFunction(XALAN_STATIC_UCODE_STRING("normalize-space"),
FunctionNormalizeSpace());
InstallFunction(XALAN_STATIC_UCODE_STRING("translate"),
FunctionTranslate());
InstallFunction(XALAN_STATIC_UCODE_STRING("boolean"),
FunctionBoolean());
InstallFunction(XALAN_STATIC_UCODE_STRING("not"),
FunctionNot());
InstallFunction(XALAN_STATIC_UCODE_STRING("true"),
FunctionTrue());
InstallFunction(XALAN_STATIC_UCODE_STRING("false"),
FunctionFalse());
InstallFunction(XALAN_STATIC_UCODE_STRING("lang"),
FunctionLang());
InstallFunction(XALAN_STATIC_UCODE_STRING("number"),
FunctionNumber());
InstallFunction(XALAN_STATIC_UCODE_STRING("sum"),
FunctionSum());
InstallFunction(XALAN_STATIC_UCODE_STRING("floor"),
FunctionFloor());
InstallFunction(XALAN_STATIC_UCODE_STRING("ceiling"),
FunctionCeiling());
InstallFunction(XALAN_STATIC_UCODE_STRING("round"),
FunctionRound());
}
catch(...)
{
DestroyTable();
throw;
}
}
void
XPathFunctionTable::DestroyTable()
{
try
{
std::for_each(m_FunctionCollection.begin(),
m_FunctionCollection.end(),
DeleteFunctorType());
}
catch(...)
{
}
}
XPathFunctionTableException::XPathFunctionTableException(const DOMString& theMessage) :
XPathException(theMessage)
{
}
XPathFunctionTableException::~XPathFunctionTableException()
{
}
XPathFunctionTableInvalidFunctionException::XPathFunctionTableInvalidFunctionException(const DOMString& theFunctionName) :
XPathFunctionTableException(FormatMessage(theFunctionName))
{
}
XPathFunctionTableInvalidFunctionException::~XPathFunctionTableInvalidFunctionException()
{
}
DOMString
XPathFunctionTableInvalidFunctionException::FormatMessage(const DOMString& theFunctionName)
{
const char* theMessage =
"Invalid function name detected: ";
return DOMString(theMessage) + theFunctionName;
}
<|endoftext|> |
<commit_before>/* XMMS2 - X Music Multiplexer System
* Copyright (C) 2003-2008 XMMS2 Team
*
* PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!
*
* 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.
*/
/**
* @file gme decoder.
* @url http://wiki.xmms2.xmms.se/index.php/Notes_from_developing_an_xform_plugin
*/
#include <glib.h>
#include <stdlib.h>
#include "xmms/xmms_xformplugin.h"
#include "xmms/xmms_sample.h"
#include "xmms/xmms_log.h"
#include "xmms/xmms_medialib.h"
#include "gme/gme.h"
#define GME_DEFAULT_SAMPLE_RATE 44100
#define GME_DEFAULT_SONG_LENGTH 300
#define GME_DEFAULT_SONG_LOOPS 2
extern "C" {
/*
* Persistent data
*
*/
typedef struct xmms_gme_data_St {
Music_Emu *emu; /* An emulation instance for the GME library */
int samplerate; /* The sample rate, set by the user */
} xmms_gme_data_t;
/*
* Function prototypes
*/
static gboolean xmms_gme_plugin_setup (xmms_xform_plugin_t *xform_plugin);
static gint xmms_gme_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err);
static gboolean xmms_gme_init (xmms_xform_t *decoder);
static void xmms_gme_destroy (xmms_xform_t *decoder);
static gint64 xmms_gme_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err);
/*
* Plugin header
*/
XMMS_XFORM_PLUGIN ("gme",
"Game Music decoder", XMMS_VERSION,
"Game Music Emulator music decoder",
xmms_gme_plugin_setup);
static gboolean
xmms_gme_plugin_setup (xmms_xform_plugin_t *xform_plugin)
{
xmms_xform_methods_t methods;
XMMS_XFORM_METHODS_INIT (methods);
methods.init = xmms_gme_init;
methods.destroy = xmms_gme_destroy;
methods.read = xmms_gme_read;
methods.seek = xmms_gme_seek;
xmms_xform_plugin_methods_set (xform_plugin, &methods);
xmms_xform_plugin_config_property_register (xform_plugin, "loops", G_STRINGIFY (GME_DEFAULT_SONG_LOOPS), NULL, NULL);
xmms_xform_plugin_config_property_register (xform_plugin, "maxlength", G_STRINGIFY (GME_DEFAULT_SONG_LENGTH), NULL, NULL);
xmms_xform_plugin_config_property_register (xform_plugin, "samplerate", G_STRINGIFY (GME_DEFAULT_SAMPLE_RATE), NULL, NULL);
/* todo: add other mime types */
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-spc",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-nsf",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-gbs",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-gym",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-vgm",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-sap",
NULL);
/* todo: add other magic */
xmms_magic_add ("SPC700 save state",
"application/x-spc",
"0 string SNES-SPC700 Sound File Data",
NULL);
xmms_magic_add ("NSF file",
"application/x-nsf",
"0 string NESM",
NULL);
xmms_magic_add ("GBS file",
"application/x-gbs",
"0 string GBS",
NULL);
xmms_magic_add ("GYM file",
"application/x-gym",
"0 string GYMX",
NULL);
xmms_magic_add ("VGM file",
"application/x-vgm",
"0 string Vgm",
NULL);
xmms_magic_add ("SAP file",
"application/x-sap",
"0 string SAP",
NULL);
/* todo: add other file extensions */
xmms_magic_extension_add ("application/x-spc", "*.spc");
xmms_magic_extension_add ("application/x-nsf", "*.nsf");
xmms_magic_extension_add ("application/x-gbs", "*.gbs");
xmms_magic_extension_add ("application/x-gym", "*.gym");
xmms_magic_extension_add ("application/x-vgm", "*.vgm");
xmms_magic_extension_add ("application/x-sap", "*.sap");
return TRUE;
}
static gboolean
xmms_gme_init (xmms_xform_t *xform)
{
xmms_gme_data_t *data;
gme_err_t init_error;
GString *file_contents; /* The raw data from the file. */
track_info_t metadata;
xmms_config_property_t *val;
int loops;
int maxlength;
const char *subtune_str;
int subtune = 0;
long fadelen = -1;
int samplerate;
g_return_val_if_fail (xform, FALSE);
data = g_new0 (xmms_gme_data_t, 1);
xmms_xform_private_data_set (xform, data);
val = xmms_xform_config_lookup (xform, "samplerate");
samplerate = xmms_config_property_get_int (val);
if (samplerate < 1)
samplerate = GME_DEFAULT_SAMPLE_RATE;
data->samplerate = samplerate;
xmms_xform_outdata_type_add (xform,
XMMS_STREAM_TYPE_MIMETYPE,
"audio/pcm", /* PCM samples */
XMMS_STREAM_TYPE_FMT_FORMAT,
XMMS_SAMPLE_FORMAT_S16, /* 16-bit signed */
XMMS_STREAM_TYPE_FMT_CHANNELS,
2, /* stereo */
XMMS_STREAM_TYPE_FMT_SAMPLERATE,
samplerate,
XMMS_STREAM_TYPE_END);
file_contents = g_string_new ("");
for (;;) {
xmms_error_t error;
gchar buf[4096];
gint ret;
ret = xmms_xform_read (xform, buf, sizeof (buf), &error);
if (ret == -1) {
XMMS_DBG ("Error reading emulated music data");
return FALSE;
}
if (ret == 0) {
break;
}
g_string_append_len (file_contents, buf, ret);
}
init_error = gme_open_data (file_contents->str, file_contents->len, &data->emu, samplerate);
if (init_error) {
XMMS_DBG ("gme_open_data returned an error: %s", init_error);
return FALSE;
}
if (xmms_xform_metadata_get_str (xform, "subtune", &subtune_str)) {
subtune = strtol (subtune_str, NULL, 10);
XMMS_DBG ("Setting subtune to %d", subtune);
if ((subtune < 0 || subtune > gme_track_count (data->emu))) {
XMMS_DBG ("Invalid subtune index");
return FALSE;
}
} else {
xmms_xform_metadata_set_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_SUBTUNES, gme_track_count (data->emu));
}
/*
* Get metadata here
*/
init_error = gme_track_info (data->emu, &metadata, subtune);
if (init_error) {
XMMS_DBG ("Couldn't get GME track info: %s", init_error);
init_error = "";
} else {
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE, metadata.song);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_ARTIST, metadata.author);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_ALBUM, metadata.game);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_COMMENT, metadata.comment);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR, metadata.copyright);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_GENRE, metadata.system); /* I mapped genre to the system type */
val = xmms_xform_config_lookup (xform, "loops");
loops = xmms_config_property_get_int (val);
XMMS_DBG ("intro_length = %ld, loops = %d, loop_length = %ld", metadata.intro_length, loops, metadata.loop_length);
if (metadata.intro_length > 0) {
if ((loops > 0) && (metadata.loop_length > 0)) {
fadelen = metadata.intro_length + loops * metadata.loop_length;
XMMS_DBG ("fadelen now = %ld", fadelen);
} else {
fadelen = metadata.length;
XMMS_DBG ("fadelen now = %ld", fadelen);
}
}
}
val = xmms_xform_config_lookup (xform, "maxlength");
maxlength = xmms_config_property_get_int (val);
XMMS_DBG ("maxlength = %d seconds", maxlength);
if (maxlength > 0 && (fadelen < 0 || (maxlength * 1000L < fadelen))) {
fadelen = maxlength * 1000L;
XMMS_DBG ("fadelen now = %ld", fadelen);
}
XMMS_DBG ("gme.fadelen = %ld", fadelen);
init_error = gme_start_track (data->emu, subtune);
if (init_error) {
XMMS_DBG ("gme_start_track returned an error: %s", init_error);
return FALSE;
}
if (fadelen > 0) {
XMMS_DBG ("Setting song length and fade length...");
xmms_xform_metadata_set_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION, fadelen);
gme_set_fade (data->emu, fadelen);
}
g_string_free (file_contents, TRUE);
return TRUE;
}
static void
xmms_gme_destroy (xmms_xform_t *xform)
{
xmms_gme_data_t *data;
g_return_if_fail (xform);
data = (xmms_gme_data_t *)xmms_xform_private_data_get (xform);
g_return_if_fail (data);
if (data->emu)
gme_delete (data->emu);
g_free (data);
}
/* Read some data */
static gint
xmms_gme_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err)
{
xmms_gme_data_t *data;
gme_err_t play_error;
g_return_val_if_fail (xform, -1);
data = (xmms_gme_data_t *)xmms_xform_private_data_get (xform);
g_return_val_if_fail (data, -1);
if (gme_track_ended (data->emu))
return 0;
play_error = gme_play (data->emu, len/2, (short int *)buf);
if (play_error) {
XMMS_DBG ("gme_play returned an error: %s", play_error);
xmms_error_set (err, XMMS_ERROR_GENERIC, play_error);
return -1;
}
return len;
}
static gint64
xmms_gme_seek (xmms_xform_t *xform, gint64 samples,
xmms_xform_seek_mode_t whence, xmms_error_t *err)
{
xmms_gme_data_t *data;
gint64 target_time;
gint duration;
int samplerate;
g_return_val_if_fail (whence == XMMS_XFORM_SEEK_SET, -1);
g_return_val_if_fail (xform, -1);
data = (xmms_gme_data_t *) xmms_xform_private_data_get (xform);
g_return_val_if_fail (data, -1);
samplerate = data->samplerate;
if (samples < 0) {
xmms_error_set (err, XMMS_ERROR_INVAL,
"Trying to seek before start of stream");
return -1;
}
target_time = (samples / samplerate) * 1000;
xmms_xform_metadata_get_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION, &duration);
if (target_time > duration) {
xmms_error_set (err, XMMS_ERROR_INVAL,
"Trying to seek past end of stream");
return -1;
}
gme_seek (data->emu, target_time);
return (gme_tell (data->emu) / 1000) * samplerate;
}
}
<commit_msg>OTHER: Added AY magic to GME plugin<commit_after>/* XMMS2 - X Music Multiplexer System
* Copyright (C) 2003-2008 XMMS2 Team
*
* PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!
*
* 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.
*/
/**
* @file gme decoder.
* @url http://wiki.xmms2.xmms.se/index.php/Notes_from_developing_an_xform_plugin
*/
#include <glib.h>
#include <stdlib.h>
#include "xmms/xmms_xformplugin.h"
#include "xmms/xmms_sample.h"
#include "xmms/xmms_log.h"
#include "xmms/xmms_medialib.h"
#include "gme/gme.h"
#define GME_DEFAULT_SAMPLE_RATE 44100
#define GME_DEFAULT_SONG_LENGTH 300
#define GME_DEFAULT_SONG_LOOPS 2
extern "C" {
/*
* Persistent data
*
*/
typedef struct xmms_gme_data_St {
Music_Emu *emu; /* An emulation instance for the GME library */
int samplerate; /* The sample rate, set by the user */
} xmms_gme_data_t;
/*
* Function prototypes
*/
static gboolean xmms_gme_plugin_setup (xmms_xform_plugin_t *xform_plugin);
static gint xmms_gme_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err);
static gboolean xmms_gme_init (xmms_xform_t *decoder);
static void xmms_gme_destroy (xmms_xform_t *decoder);
static gint64 xmms_gme_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err);
/*
* Plugin header
*/
XMMS_XFORM_PLUGIN ("gme",
"Game Music decoder", XMMS_VERSION,
"Game Music Emulator music decoder",
xmms_gme_plugin_setup);
static gboolean
xmms_gme_plugin_setup (xmms_xform_plugin_t *xform_plugin)
{
xmms_xform_methods_t methods;
XMMS_XFORM_METHODS_INIT (methods);
methods.init = xmms_gme_init;
methods.destroy = xmms_gme_destroy;
methods.read = xmms_gme_read;
methods.seek = xmms_gme_seek;
xmms_xform_plugin_methods_set (xform_plugin, &methods);
xmms_xform_plugin_config_property_register (xform_plugin, "loops", G_STRINGIFY (GME_DEFAULT_SONG_LOOPS), NULL, NULL);
xmms_xform_plugin_config_property_register (xform_plugin, "maxlength", G_STRINGIFY (GME_DEFAULT_SONG_LENGTH), NULL, NULL);
xmms_xform_plugin_config_property_register (xform_plugin, "samplerate", G_STRINGIFY (GME_DEFAULT_SAMPLE_RATE), NULL, NULL);
/* todo: add other mime types */
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-spc",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-nsf",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-gbs",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-gym",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-vgm",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-sap",
NULL);
xmms_xform_plugin_indata_add (xform_plugin,
XMMS_STREAM_TYPE_MIMETYPE,
"application/x-ay",
NULL);
/* todo: add other magic */
xmms_magic_add ("SPC700 save state",
"application/x-spc",
"0 string SNES-SPC700 Sound File Data",
NULL);
xmms_magic_add ("NSF file",
"application/x-nsf",
"0 string NESM",
NULL);
xmms_magic_add ("GBS file",
"application/x-gbs",
"0 string GBS",
NULL);
xmms_magic_add ("GYM file",
"application/x-gym",
"0 string GYMX",
NULL);
xmms_magic_add ("VGM file",
"application/x-vgm",
"0 string Vgm",
NULL);
xmms_magic_add ("SAP file",
"application/x-sap",
"0 string SAP",
NULL);
xmms_magic_add ("AY file",
"application/x-ay",
"0 string ZXAYEMU",
NULL);
/* todo: add other file extensions */
xmms_magic_extension_add ("application/x-spc", "*.spc");
xmms_magic_extension_add ("application/x-nsf", "*.nsf");
xmms_magic_extension_add ("application/x-gbs", "*.gbs");
xmms_magic_extension_add ("application/x-gym", "*.gym");
xmms_magic_extension_add ("application/x-vgm", "*.vgm");
xmms_magic_extension_add ("application/x-sap", "*.sap");
xmms_magic_extension_add ("application/x-ay", "*.ay");
return TRUE;
}
static gboolean
xmms_gme_init (xmms_xform_t *xform)
{
xmms_gme_data_t *data;
gme_err_t init_error;
GString *file_contents; /* The raw data from the file. */
track_info_t metadata;
xmms_config_property_t *val;
int loops;
int maxlength;
const char *subtune_str;
int subtune = 0;
long fadelen = -1;
int samplerate;
g_return_val_if_fail (xform, FALSE);
data = g_new0 (xmms_gme_data_t, 1);
xmms_xform_private_data_set (xform, data);
val = xmms_xform_config_lookup (xform, "samplerate");
samplerate = xmms_config_property_get_int (val);
if (samplerate < 1)
samplerate = GME_DEFAULT_SAMPLE_RATE;
data->samplerate = samplerate;
xmms_xform_outdata_type_add (xform,
XMMS_STREAM_TYPE_MIMETYPE,
"audio/pcm", /* PCM samples */
XMMS_STREAM_TYPE_FMT_FORMAT,
XMMS_SAMPLE_FORMAT_S16, /* 16-bit signed */
XMMS_STREAM_TYPE_FMT_CHANNELS,
2, /* stereo */
XMMS_STREAM_TYPE_FMT_SAMPLERATE,
samplerate,
XMMS_STREAM_TYPE_END);
file_contents = g_string_new ("");
for (;;) {
xmms_error_t error;
gchar buf[4096];
gint ret;
ret = xmms_xform_read (xform, buf, sizeof (buf), &error);
if (ret == -1) {
XMMS_DBG ("Error reading emulated music data");
return FALSE;
}
if (ret == 0) {
break;
}
g_string_append_len (file_contents, buf, ret);
}
init_error = gme_open_data (file_contents->str, file_contents->len, &data->emu, samplerate);
if (init_error) {
XMMS_DBG ("gme_open_data returned an error: %s", init_error);
return FALSE;
}
if (xmms_xform_metadata_get_str (xform, "subtune", &subtune_str)) {
subtune = strtol (subtune_str, NULL, 10);
XMMS_DBG ("Setting subtune to %d", subtune);
if ((subtune < 0 || subtune > gme_track_count (data->emu))) {
XMMS_DBG ("Invalid subtune index");
return FALSE;
}
} else {
xmms_xform_metadata_set_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_SUBTUNES, gme_track_count (data->emu));
}
/*
* Get metadata here
*/
init_error = gme_track_info (data->emu, &metadata, subtune);
if (init_error) {
XMMS_DBG ("Couldn't get GME track info: %s", init_error);
init_error = "";
} else {
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE, metadata.song);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_ARTIST, metadata.author);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_ALBUM, metadata.game);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_COMMENT, metadata.comment);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR, metadata.copyright);
xmms_xform_metadata_set_str (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_GENRE, metadata.system); /* I mapped genre to the system type */
val = xmms_xform_config_lookup (xform, "loops");
loops = xmms_config_property_get_int (val);
XMMS_DBG ("intro_length = %ld, loops = %d, loop_length = %ld", metadata.intro_length, loops, metadata.loop_length);
if (metadata.intro_length > 0) {
if ((loops > 0) && (metadata.loop_length > 0)) {
fadelen = metadata.intro_length + loops * metadata.loop_length;
XMMS_DBG ("fadelen now = %ld", fadelen);
} else {
fadelen = metadata.length;
XMMS_DBG ("fadelen now = %ld", fadelen);
}
}
}
val = xmms_xform_config_lookup (xform, "maxlength");
maxlength = xmms_config_property_get_int (val);
XMMS_DBG ("maxlength = %d seconds", maxlength);
if (maxlength > 0 && (fadelen < 0 || (maxlength * 1000L < fadelen))) {
fadelen = maxlength * 1000L;
XMMS_DBG ("fadelen now = %ld", fadelen);
}
XMMS_DBG ("gme.fadelen = %ld", fadelen);
init_error = gme_start_track (data->emu, subtune);
if (init_error) {
XMMS_DBG ("gme_start_track returned an error: %s", init_error);
return FALSE;
}
if (fadelen > 0) {
XMMS_DBG ("Setting song length and fade length...");
xmms_xform_metadata_set_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION, fadelen);
gme_set_fade (data->emu, fadelen);
}
g_string_free (file_contents, TRUE);
return TRUE;
}
static void
xmms_gme_destroy (xmms_xform_t *xform)
{
xmms_gme_data_t *data;
g_return_if_fail (xform);
data = (xmms_gme_data_t *)xmms_xform_private_data_get (xform);
g_return_if_fail (data);
if (data->emu)
gme_delete (data->emu);
g_free (data);
}
/* Read some data */
static gint
xmms_gme_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err)
{
xmms_gme_data_t *data;
gme_err_t play_error;
g_return_val_if_fail (xform, -1);
data = (xmms_gme_data_t *)xmms_xform_private_data_get (xform);
g_return_val_if_fail (data, -1);
if (gme_track_ended (data->emu))
return 0;
play_error = gme_play (data->emu, len/2, (short int *)buf);
if (play_error) {
XMMS_DBG ("gme_play returned an error: %s", play_error);
xmms_error_set (err, XMMS_ERROR_GENERIC, play_error);
return -1;
}
return len;
}
static gint64
xmms_gme_seek (xmms_xform_t *xform, gint64 samples,
xmms_xform_seek_mode_t whence, xmms_error_t *err)
{
xmms_gme_data_t *data;
gint64 target_time;
gint duration;
int samplerate;
g_return_val_if_fail (whence == XMMS_XFORM_SEEK_SET, -1);
g_return_val_if_fail (xform, -1);
data = (xmms_gme_data_t *) xmms_xform_private_data_get (xform);
g_return_val_if_fail (data, -1);
samplerate = data->samplerate;
if (samples < 0) {
xmms_error_set (err, XMMS_ERROR_INVAL,
"Trying to seek before start of stream");
return -1;
}
target_time = (samples / samplerate) * 1000;
xmms_xform_metadata_get_int (xform, XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION, &duration);
if (target_time > duration) {
xmms_error_set (err, XMMS_ERROR_INVAL,
"Trying to seek past end of stream");
return -1;
}
gme_seek (data->emu, target_time);
return (gme_tell (data->emu) / 1000) * samplerate;
}
}
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief Write key sets using yaml-cpp
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "write.hpp"
#include "yaml-cpp/yaml.h"
#include <kdbassert.h>
#include <kdbease.h>
#include <kdblogger.h>
#include <kdbplugin.h>
#include <fstream>
using namespace std;
using namespace kdb;
namespace
{
using KeySetPair = pair<KeySet, KeySet>;
/**
* @brief This function checks if `element` is an array element of `parent`.
*
* @pre The key `child` must be below `parent`.
*
* @param parent This parameter specifies a parent key.
* @param keys This variable stores a direct or indirect child of `parent`.
*
* @retval true If `element` is an array element
* @retval false Otherwise
*/
bool isArrayElementOf (Key const & parent, Key const & child)
{
char const * relative = elektraKeyGetRelativeName (*child, *parent);
auto offsetIndex = ckdb::elektraArrayValidateBaseNameString (relative);
if (offsetIndex <= 0) return false;
// Skip `#`, underscores and digits
relative += 2 * offsetIndex;
// The next character has to be the separation char (`/`) or end of string
if (relative[0] != '\0' && relative[0] != '/') return false;
return true;
}
/**
* @brief This function determines if the given key is an array parent.
*
* @param parent This parameter specifies a possible array parent.
* @param keys This variable stores the key set of `parent`.
*
* @retval true If `parent` is the parent key of an array
* @retval false Otherwise
*/
bool isArrayParent (Key const & parent, KeySet const & keys)
{
for (auto const & key : keys)
{
if (!key.isBelow (parent)) continue;
if (!isArrayElementOf (parent, key)) return false;
}
return true;
}
/**
* @brief Split `keys` into two key sets, one for array parents and one for all other keys.
*
* @param keys This parameter contains the key set this function splits.
*
* @return A pair of key sets, where the first key set contains all array parents and the second key set contains all other keys
*/
KeySetPair splitArrayParentsOther (KeySet const & keys)
{
KeySet arrayParents;
KeySet others;
keys.rewind ();
Key previous;
for (previous = keys.next (); keys.next (); previous = keys.current ())
{
bool const previousIsArray =
previous.hasMeta ("array") ||
(keys.current ().isBelow (previous) && keys.current ().getBaseName ()[0] == '#' && isArrayParent (previous, keys));
(previousIsArray ? arrayParents : others).append (previous);
}
(previous.hasMeta ("array") ? arrayParents : others).append (previous);
ELEKTRA_ASSERT (arrayParents.size () + others.size () == keys.size (),
"Number of keys in split key sets: %zu ≠ number in given key set %zu", arrayParents.size () + others.size (),
keys.size ());
return make_pair (arrayParents, others);
}
/**
* @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys.
*
* @param arrayParents This key set contains a (copy) of all array parents of `keys`.
* @param keys This parameter contains the key set this function splits.
*
* @return A pair of key sets, where the first key set contains all array parents and elements,
* and the second key set contains all other keys
*/
KeySetPair splitArrayOther (KeySet const & arrayParents, KeySet const & keys)
{
KeySet others = keys.dup ();
KeySet arrays;
for (auto parent : arrayParents)
{
arrays.append (others.cut (parent));
}
return make_pair (arrays, others);
}
/**
* @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`.
*
* @pre The parameter `key` must be a child of `parent`.
*
* @param key This is the key for which this function returns a relative iterator.
* @param parent This key specifies the part of the name iterator that will not be part of the return value of this function.
*
* @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`.
*/
NameIterator relativeKeyIterator (Key const & key, Key const & parent)
{
auto parentIterator = parent.begin ();
auto keyIterator = key.begin ();
while (parentIterator != parent.end () && keyIterator != key.end ())
{
parentIterator++;
keyIterator++;
}
return keyIterator;
}
/**
* @brief This function checks if a key name specifies an array key.
*
* If the key name contains a valid array index that is smaller than `unsigned long long`, then the function will also return this index.
*
* @param nameIterator This iterator specifies the name of the key.
*
* @retval (true, arrayIndex) if `name` specifies an array key, where `arrayIndex` specifies the index stored in the array key.
* @retval (false, 0) otherwise
*/
std::pair<bool, unsigned long long> isArrayIndex (NameIterator const & nameIterator)
{
string const name = *nameIterator;
auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ());
auto const isArrayElement = offsetIndex >= 1;
return { isArrayElement, isArrayElement ? stoull (name.substr (offsetIndex)) : 0 };
}
/**
* @brief This function creates a YAML node representing a key value.
*
* @param key This key specifies the data that should be saved in the YAML node returned by this function.
*
* @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string
* `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP.
*
* @returns A new YAML node containing the data specified in `key`
*/
YAML::Node createMetaDataNode (Key const & key)
{
return key.hasMeta ("array") ?
YAML::Node (YAML::NodeType::Sequence) :
key.getBinarySize () == 0 ? YAML::Node (YAML::NodeType::Null) :
YAML::Node (key.isBinary () ? "Unsupported binary value!" : key.getString ());
}
/**
* @brief This function creates a YAML Node containing a key value and optionally metadata.
*
* @param key This key specifies the data that should be saved in the YAML node returned by this function.
*
* @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string
* `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP.
*
* @returns A new YAML node containing the data and metadata specified in `key`
*/
YAML::Node createLeafNode (Key & key)
{
YAML::Node metaNode{ YAML::Node (YAML::NodeType::Map) };
YAML::Node dataNode = createMetaDataNode (key);
key.rewindMeta ();
while (Key meta = key.nextMeta ())
{
if (meta.getName () == "array" || meta.getName () == "binary") continue;
if (meta.getName () == "type" && meta.getString () == "binary")
{
dataNode.SetTag ("tag:yaml.org,2002:binary");
continue;
}
metaNode[meta.getName ()] = meta.getString ();
ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ());
}
if (metaNode.size () <= 0)
{
ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”",
dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ());
return dataNode;
}
YAML::Node node{ YAML::Node (YAML::NodeType::Sequence) };
node.SetTag ("!elektra/meta");
node.push_back (dataNode);
node.push_back (metaNode);
#ifdef HAVE_LOGGER
ostringstream data;
data << node;
ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ());
#endif
return node;
}
/**
* @brief This function adds `null` elements to the given YAML collection.
*
* @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements.
* @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`.
*/
void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements)
{
ELEKTRA_LOG_DEBUG ("Add %lld empty array elements", numberOfElements);
for (auto missingFields = numberOfElements; missingFields > 0; missingFields--)
{
sequence.push_back ({});
}
}
/**
* @brief This function adds a key to a YAML node.
*
* @param data This node stores the data specified via `keyIterator`.
* @param keyIterator This iterator specifies the current part of the key name this function adds to `data`.
* @param key This parameter specifies the key that should be added to `data`.
*/
void addKeyArray (YAML::Node & data, NameIterator & keyIterator, Key & key)
{
auto const isArrayAndIndex = isArrayIndex (keyIterator);
auto const isArrayElement = isArrayAndIndex.first;
auto const arrayIndex = isArrayAndIndex.second;
if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined);
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Add key part “%s” to node “%s”", (*keyIterator).c_str (), output.str ().c_str ());
#endif
if (keyIterator == key.end ())
{
ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ());
data = createLeafNode (key);
return;
}
if (keyIterator == --key.end ())
{
if (isArrayElement)
{
addEmptyArrayElements (data, arrayIndex - data.size ());
data.push_back (createLeafNode (key));
}
else
{
data[*keyIterator] = createLeafNode (key);
}
return;
}
YAML::Node node;
if (isArrayElement)
{
node = (data[arrayIndex] && !data[arrayIndex].IsScalar ()) ? data[arrayIndex] : YAML::Node ();
data[arrayIndex] = node;
}
else
{
node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node ();
data[*keyIterator] = node;
}
addKeyArray (node, ++keyIterator, key);
}
/**
* @brief This function adds a key to a YAML node.
*
* @param data This node stores the data specified via `keyIterator`.
* @param keyIterator This iterator specifies the current part of the key name this function adds to `data`.
* @param key This parameter specifies the key that should be added to `data`.
*/
void addKeyNoArray (YAML::Node & data, NameIterator & keyIterator, Key & key)
{
if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined);
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Add key part “%s” to node “%s”", (*keyIterator).c_str (), output.str ().c_str ());
#endif
if (keyIterator == key.end ())
{
ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ());
data = createLeafNode (key);
return;
}
if (keyIterator == --key.end ())
{
data[*keyIterator] = createLeafNode (key);
return;
}
YAML::Node node;
node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node ();
data[*keyIterator] = node;
addKeyNoArray (node, ++keyIterator, key);
}
/**
* @brief This function adds a key set to a YAML node.
*
* @param data This node stores the data specified via `mappings`.
* @param mappings This keyset specifies all keys and values this function adds to `data`.
* @param parent This key is the root of all keys stored in `mappings`.
*/
void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent, bool const isArray = false)
{
for (auto key : mappings)
{
ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (),
key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!");
NameIterator keyIterator = relativeKeyIterator (key, parent);
if (isArray)
{
addKeyArray (data, keyIterator, key);
}
else
{
addKeyNoArray (data, keyIterator, key);
}
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Converted Data:");
ELEKTRA_LOG_DEBUG ("__________");
istringstream stream (output.str ());
for (string line; std::getline (stream, line);)
{
ELEKTRA_LOG_DEBUG ("%s", line.c_str ());
}
ELEKTRA_LOG_DEBUG ("__________");
#endif
}
}
} // end namespace
/**
* @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`.
*
* @param mappings This key set stores the mappings that should be saved as YAML data.
* @param parent This key specifies the path to the YAML data file that should be written.
*/
void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent)
{
ofstream output (parent.getString ());
auto data = YAML::Node ();
KeySet arrayParents;
KeySet arrays;
KeySet nonArrays;
tie (arrayParents, std::ignore) = splitArrayParentsOther (mappings);
tie (arrays, nonArrays) = splitArrayOther (arrayParents, mappings);
addKeys (data, arrays, parent, true);
addKeys (data, nonArrays, parent);
#ifdef HAVE_LOGGER
ELEKTRA_LOG_DEBUG ("Write Data:");
ELEKTRA_LOG_DEBUG ("__________");
ostringstream outputString;
outputString << data;
istringstream stream (outputString.str ());
for (string line; std::getline (stream, line);)
{
ELEKTRA_LOG_DEBUG ("%s", line.c_str ());
}
ELEKTRA_LOG_DEBUG ("__________");
#endif
output << data;
}
<commit_msg>YAML CPP: Reorder function definitions<commit_after>/**
* @file
*
* @brief Write key sets using yaml-cpp
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "write.hpp"
#include "yaml-cpp/yaml.h"
#include <kdbassert.h>
#include <kdbease.h>
#include <kdblogger.h>
#include <kdbplugin.h>
#include <fstream>
using namespace std;
using namespace kdb;
namespace
{
using KeySetPair = pair<KeySet, KeySet>;
/**
* @brief This function checks if `element` is an array element of `parent`.
*
* @pre The key `child` must be below `parent`.
*
* @param parent This parameter specifies a parent key.
* @param keys This variable stores a direct or indirect child of `parent`.
*
* @retval true If `element` is an array element
* @retval false Otherwise
*/
bool isArrayElementOf (Key const & parent, Key const & child)
{
char const * relative = elektraKeyGetRelativeName (*child, *parent);
auto offsetIndex = ckdb::elektraArrayValidateBaseNameString (relative);
if (offsetIndex <= 0) return false;
// Skip `#`, underscores and digits
relative += 2 * offsetIndex;
// The next character has to be the separation char (`/`) or end of string
if (relative[0] != '\0' && relative[0] != '/') return false;
return true;
}
/**
* @brief This function determines if the given key is an array parent.
*
* @param parent This parameter specifies a possible array parent.
* @param keys This variable stores the key set of `parent`.
*
* @retval true If `parent` is the parent key of an array
* @retval false Otherwise
*/
bool isArrayParent (Key const & parent, KeySet const & keys)
{
for (auto const & key : keys)
{
if (!key.isBelow (parent)) continue;
if (!isArrayElementOf (parent, key)) return false;
}
return true;
}
/**
* @brief Split `keys` into two key sets, one for array parents and one for all other keys.
*
* @param keys This parameter contains the key set this function splits.
*
* @return A pair of key sets, where the first key set contains all array parents and the second key set contains all other keys
*/
KeySetPair splitArrayParentsOther (KeySet const & keys)
{
KeySet arrayParents;
KeySet others;
keys.rewind ();
Key previous;
for (previous = keys.next (); keys.next (); previous = keys.current ())
{
bool const previousIsArray =
previous.hasMeta ("array") ||
(keys.current ().isBelow (previous) && keys.current ().getBaseName ()[0] == '#' && isArrayParent (previous, keys));
(previousIsArray ? arrayParents : others).append (previous);
}
(previous.hasMeta ("array") ? arrayParents : others).append (previous);
ELEKTRA_ASSERT (arrayParents.size () + others.size () == keys.size (),
"Number of keys in split key sets: %zu ≠ number in given key set %zu", arrayParents.size () + others.size (),
keys.size ());
return make_pair (arrayParents, others);
}
/**
* @brief This function splits `keys` into two key sets, one for array parents and elements, and the other one for all other keys.
*
* @param arrayParents This key set contains a (copy) of all array parents of `keys`.
* @param keys This parameter contains the key set this function splits.
*
* @return A pair of key sets, where the first key set contains all array parents and elements,
* and the second key set contains all other keys
*/
KeySetPair splitArrayOther (KeySet const & arrayParents, KeySet const & keys)
{
KeySet others = keys.dup ();
KeySet arrays;
for (auto parent : arrayParents)
{
arrays.append (others.cut (parent));
}
return make_pair (arrays, others);
}
/**
* @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`.
*
* @pre The parameter `key` must be a child of `parent`.
*
* @param key This is the key for which this function returns a relative iterator.
* @param parent This key specifies the part of the name iterator that will not be part of the return value of this function.
*
* @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`.
*/
NameIterator relativeKeyIterator (Key const & key, Key const & parent)
{
auto parentIterator = parent.begin ();
auto keyIterator = key.begin ();
while (parentIterator != parent.end () && keyIterator != key.end ())
{
parentIterator++;
keyIterator++;
}
return keyIterator;
}
/**
* @brief This function checks if a key name specifies an array key.
*
* If the key name contains a valid array index that is smaller than `unsigned long long`, then the function will also return this index.
*
* @param nameIterator This iterator specifies the name of the key.
*
* @retval (true, arrayIndex) if `name` specifies an array key, where `arrayIndex` specifies the index stored in the array key.
* @retval (false, 0) otherwise
*/
std::pair<bool, unsigned long long> isArrayIndex (NameIterator const & nameIterator)
{
string const name = *nameIterator;
auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ());
auto const isArrayElement = offsetIndex >= 1;
return { isArrayElement, isArrayElement ? stoull (name.substr (offsetIndex)) : 0 };
}
/**
* @brief This function creates a YAML node representing a key value.
*
* @param key This key specifies the data that should be saved in the YAML node returned by this function.
*
* @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string
* `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP.
*
* @returns A new YAML node containing the data specified in `key`
*/
YAML::Node createMetaDataNode (Key const & key)
{
return key.hasMeta ("array") ?
YAML::Node (YAML::NodeType::Sequence) :
key.getBinarySize () == 0 ? YAML::Node (YAML::NodeType::Null) :
YAML::Node (key.isBinary () ? "Unsupported binary value!" : key.getString ());
}
/**
* @brief This function creates a YAML Node containing a key value and optionally metadata.
*
* @param key This key specifies the data that should be saved in the YAML node returned by this function.
*
* @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string
* `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP.
*
* @returns A new YAML node containing the data and metadata specified in `key`
*/
YAML::Node createLeafNode (Key & key)
{
YAML::Node metaNode{ YAML::Node (YAML::NodeType::Map) };
YAML::Node dataNode = createMetaDataNode (key);
key.rewindMeta ();
while (Key meta = key.nextMeta ())
{
if (meta.getName () == "array" || meta.getName () == "binary") continue;
if (meta.getName () == "type" && meta.getString () == "binary")
{
dataNode.SetTag ("tag:yaml.org,2002:binary");
continue;
}
metaNode[meta.getName ()] = meta.getString ();
ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ());
}
if (metaNode.size () <= 0)
{
ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”",
dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ());
return dataNode;
}
YAML::Node node{ YAML::Node (YAML::NodeType::Sequence) };
node.SetTag ("!elektra/meta");
node.push_back (dataNode);
node.push_back (metaNode);
#ifdef HAVE_LOGGER
ostringstream data;
data << node;
ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ());
#endif
return node;
}
/**
* @brief This function adds `null` elements to the given YAML collection.
*
* @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements.
* @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`.
*/
void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements)
{
ELEKTRA_LOG_DEBUG ("Add %lld empty array elements", numberOfElements);
for (auto missingFields = numberOfElements; missingFields > 0; missingFields--)
{
sequence.push_back ({});
}
}
/**
* @brief This function adds a key to a YAML node.
*
* @param data This node stores the data specified via `keyIterator`.
* @param keyIterator This iterator specifies the current part of the key name this function adds to `data`.
* @param key This parameter specifies the key that should be added to `data`.
*/
void addKeyNoArray (YAML::Node & data, NameIterator & keyIterator, Key & key)
{
if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined);
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Add key part “%s” to node “%s”", (*keyIterator).c_str (), output.str ().c_str ());
#endif
if (keyIterator == key.end ())
{
ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ());
data = createLeafNode (key);
return;
}
if (keyIterator == --key.end ())
{
data[*keyIterator] = createLeafNode (key);
return;
}
YAML::Node node;
node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node ();
data[*keyIterator] = node;
addKeyNoArray (node, ++keyIterator, key);
}
/**
* @brief This function adds a key to a YAML node.
*
* @param data This node stores the data specified via `keyIterator`.
* @param keyIterator This iterator specifies the current part of the key name this function adds to `data`.
* @param key This parameter specifies the key that should be added to `data`.
*/
void addKeyArray (YAML::Node & data, NameIterator & keyIterator, Key & key)
{
auto const isArrayAndIndex = isArrayIndex (keyIterator);
auto const isArrayElement = isArrayAndIndex.first;
auto const arrayIndex = isArrayAndIndex.second;
if (data.IsScalar ()) data = YAML::Node (YAML::NodeType::Undefined);
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Add key part “%s” to node “%s”", (*keyIterator).c_str (), output.str ().c_str ());
#endif
if (keyIterator == key.end ())
{
ELEKTRA_LOG_DEBUG ("Create leaf node for key “%s”", key.getName ().c_str ());
data = createLeafNode (key);
return;
}
if (keyIterator == --key.end ())
{
if (isArrayElement)
{
addEmptyArrayElements (data, arrayIndex - data.size ());
data.push_back (createLeafNode (key));
}
else
{
data[*keyIterator] = createLeafNode (key);
}
return;
}
YAML::Node node;
if (isArrayElement)
{
node = (data[arrayIndex] && !data[arrayIndex].IsScalar ()) ? data[arrayIndex] : YAML::Node ();
data[arrayIndex] = node;
}
else
{
node = (data[*keyIterator] && !data[*keyIterator].IsScalar ()) ? data[*keyIterator] : YAML::Node ();
data[*keyIterator] = node;
}
addKeyArray (node, ++keyIterator, key);
}
/**
* @brief This function adds a key set to a YAML node.
*
* @param data This node stores the data specified via `mappings`.
* @param mappings This keyset specifies all keys and values this function adds to `data`.
* @param parent This key is the root of all keys stored in `mappings`.
*/
void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent, bool const isArray = false)
{
for (auto key : mappings)
{
ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (),
key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!");
NameIterator keyIterator = relativeKeyIterator (key, parent);
if (isArray)
{
addKeyArray (data, keyIterator, key);
}
else
{
addKeyNoArray (data, keyIterator, key);
}
#ifdef HAVE_LOGGER
ostringstream output;
output << data;
ELEKTRA_LOG_DEBUG ("Converted Data:");
ELEKTRA_LOG_DEBUG ("__________");
istringstream stream (output.str ());
for (string line; std::getline (stream, line);)
{
ELEKTRA_LOG_DEBUG ("%s", line.c_str ());
}
ELEKTRA_LOG_DEBUG ("__________");
#endif
}
}
} // end namespace
/**
* @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`.
*
* @param mappings This key set stores the mappings that should be saved as YAML data.
* @param parent This key specifies the path to the YAML data file that should be written.
*/
void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent)
{
ofstream output (parent.getString ());
auto data = YAML::Node ();
KeySet arrayParents;
KeySet arrays;
KeySet nonArrays;
tie (arrayParents, std::ignore) = splitArrayParentsOther (mappings);
tie (arrays, nonArrays) = splitArrayOther (arrayParents, mappings);
addKeys (data, arrays, parent, true);
addKeys (data, nonArrays, parent);
#ifdef HAVE_LOGGER
ELEKTRA_LOG_DEBUG ("Write Data:");
ELEKTRA_LOG_DEBUG ("__________");
ostringstream outputString;
outputString << data;
istringstream stream (outputString.str ());
for (string line; std::getline (stream, line);)
{
ELEKTRA_LOG_DEBUG ("%s", line.c_str ());
}
ELEKTRA_LOG_DEBUG ("__________");
#endif
output << data;
}
<|endoftext|> |
<commit_before>#include "chainerx/routines/type_util.h"
#include <vector>
#include <gtest/gtest.h>
#include "chainerx/array.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/routines/creation.h"
#include "chainerx/shape.h"
#include "chainerx/testing/context_session.h"
namespace chainerx {
namespace {
// Declares necessary variables and runs a set of checks.
#define CHECK_RESULT_TYPE_IMPL(check_body) \
{ \
testing::ContextSession context_session; \
Array Ab = Empty({2, 3}, Dtype::kBool); \
Array Au8 = Empty({2, 3}, Dtype::kUInt8); \
Array Ai8 = Empty({2, 3}, Dtype::kInt8); \
Array Ai16 = Empty({2, 3}, Dtype::kInt16); \
Array Ai32 = Empty({2, 3}, Dtype::kInt32); \
Array Ai64 = Empty({2, 3}, Dtype::kInt64); \
Array Af16 = Empty({2, 3}, Dtype::kFloat16); \
Array Af32 = Empty({2, 3}, Dtype::kFloat32); \
Array Af64 = Empty({2, 3}, Dtype::kFloat64); \
Scalar Sb{1, Dtype::kBool}; \
Scalar Su8{1, Dtype::kUInt8}; \
Scalar Si8{1, Dtype::kInt8}; \
Scalar Si16{1, Dtype::kInt16}; \
Scalar Si32{1, Dtype::kInt32}; \
Scalar Si64{1, Dtype::kInt64}; \
Scalar Sf16{1, Dtype::kFloat16}; \
Scalar Sf32{1, Dtype::kFloat32}; \
Scalar Sf64{1, Dtype::kFloat64}; \
check_body; \
}
// Checks ResultType: static-length 1-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE1(arg1) CHECK_RESULT_TYPE_IMPL({ EXPECT_EQ((arg1).dtype(), chainerx::ResultType(arg1)); })
// Checks ResultType: static-length 2-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE2(expected_dtype, arg1, arg2) \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg1)); \
})
// Checks ResultType: static-length 3-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE3(expected_dtype, arg1, arg2, arg3) \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg2, arg3)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg3, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg1, arg3)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg3, arg1)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg3, arg1, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg3, arg2, arg1)); \
})
// Checks ResultType: 2 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO1(harg1) \
{ \
CHECK_RESULT_TYPE1(A##harg1); \
CHECK_RESULT_TYPE1(S##harg1); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ EXPECT_EQ(A##harg1.dtype(), chainerx::ResultType(std::vector<Array>{A##harg1})); }); \
}
// Checks ResultType: 2 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO2(expected_dtype, harg1, harg2) \
{ \
CHECK_RESULT_TYPE2(expected_dtype, A##harg1, A##harg2); \
CHECK_RESULT_TYPE2(expected_dtype, S##harg1, S##harg2); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg1})); \
}); \
}
// Checks ResultType: 3 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO3(expected_dtype, harg1, harg2, harg3) \
{ \
CHECK_RESULT_TYPE3(expected_dtype, A##harg1, A##harg2, A##harg3); \
CHECK_RESULT_TYPE3(expected_dtype, S##harg1, S##harg2, S##harg3); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg2, A##harg3})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg3, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg1, A##harg3})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg3, A##harg1})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg3, A##harg1, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg3, A##harg2, A##harg1})); \
}); \
}
TEST(ResultTypeTest, NoArgs) {
EXPECT_THROW({ chainerx::ResultType(std::vector<Array>{}); }, ChainerxError);
}
TEST(ResultTypeTest, One) {
CHECK_RESULT_TYPE_HOMO1(b);
CHECK_RESULT_TYPE_HOMO1(f16);
CHECK_RESULT_TYPE_HOMO1(f32);
CHECK_RESULT_TYPE_HOMO1(f64);
CHECK_RESULT_TYPE_HOMO1(i8);
CHECK_RESULT_TYPE_HOMO1(i16);
CHECK_RESULT_TYPE_HOMO1(i32);
CHECK_RESULT_TYPE_HOMO1(i64);
CHECK_RESULT_TYPE_HOMO1(u8);
}
TEST(ResultTypeTest, TwoBool) { CHECK_RESULT_TYPE_HOMO2(Bool, b, b); }
TEST(ResultTypeTest, TwoFloat) {
CHECK_RESULT_TYPE_HOMO2(Float16, f16, f16);
CHECK_RESULT_TYPE_HOMO2(Float32, f32, f32);
CHECK_RESULT_TYPE_HOMO2(Float64, f64, f64);
CHECK_RESULT_TYPE_HOMO2(Float32, f16, f32);
CHECK_RESULT_TYPE_HOMO2(Float64, f16, f64);
CHECK_RESULT_TYPE_HOMO2(Float64, f32, f64);
}
TEST(ResultTypeTest, TwoSignedInt) {
CHECK_RESULT_TYPE_HOMO2(Int8, i8, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, i8, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, i8, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i8, i64);
CHECK_RESULT_TYPE_HOMO2(Int16, i16, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, i32, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i64, i64);
CHECK_RESULT_TYPE_HOMO2(Int32, i16, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i16, i64);
CHECK_RESULT_TYPE_HOMO2(Int64, i32, i64);
}
TEST(ResultTypeTest, TwoUnsignedInt) { CHECK_RESULT_TYPE_HOMO2(UInt8, u8, u8); }
TEST(ResultTypeTest, TwoSignedIntAndUnsignedInt) {
CHECK_RESULT_TYPE_HOMO2(Int16, u8, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, u8, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, u8, i32);
}
TEST(ResultTypeTest, TwoIntAndFloat) {
CHECK_RESULT_TYPE_HOMO2(Float16, i8, f16);
CHECK_RESULT_TYPE_HOMO2(Float16, u8, f16);
CHECK_RESULT_TYPE_HOMO2(Float32, i16, f32);
CHECK_RESULT_TYPE_HOMO2(Float32, i32, f32);
CHECK_RESULT_TYPE_HOMO2(Float32, i64, f32);
}
TEST(ResultTypeTest, TwoBoolAndOther) {
CHECK_RESULT_TYPE_HOMO2(UInt8, b, u8);
CHECK_RESULT_TYPE_HOMO2(Int8, b, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, b, i16);
CHECK_RESULT_TYPE_HOMO2(Float16, b, f16);
CHECK_RESULT_TYPE_HOMO2(Float64, b, f64);
}
TEST(ResultTypeTest, Three) {
// signed ints
CHECK_RESULT_TYPE_HOMO3(Int32, i32, i32, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i8, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i16, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i32, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i32, i32);
// unsigned ints
CHECK_RESULT_TYPE_HOMO3(UInt8, u8, u8, u8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, u8, i8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, i8, i8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, i8, i16);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, u8, i16);
// float and signed int
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i8, i8);
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i32, i64);
CHECK_RESULT_TYPE_HOMO3(Float32, f16, f32, i64);
// float and unsigned int
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i8, u8);
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i16, u8);
CHECK_RESULT_TYPE_HOMO3(Float32, f16, f32, u8);
// bool and other
CHECK_RESULT_TYPE_HOMO3(UInt8, b, u8, u8);
CHECK_RESULT_TYPE_HOMO3(UInt8, b, b, u8);
CHECK_RESULT_TYPE_HOMO3(Int16, b, i8, u8);
CHECK_RESULT_TYPE_HOMO3(Int32, b, b, i32);
CHECK_RESULT_TYPE_HOMO3(Float32, b, f16, f32);
CHECK_RESULT_TYPE_HOMO3(Float64, b, b, f64);
}
TEST(ResultTypeTest, ArraysAndScalars) {
// Arrays take precedence unless Scalar is a wider floating kind.
// same dtype
CHECK_RESULT_TYPE2(Int16, Ai16, Si16);
// narrower vs wider
CHECK_RESULT_TYPE2(Int16, Ai16, Si8);
CHECK_RESULT_TYPE2(Int8, Ai8, Si16);
// float vs int
CHECK_RESULT_TYPE2(Float32, Af32, Si32);
CHECK_RESULT_TYPE2(Float32, Ai32, Sf32);
// 3 arguments
CHECK_RESULT_TYPE3(Int8, Ai8, Si16, Si32);
CHECK_RESULT_TYPE3(Int16, Ai16, Si8, Si32);
CHECK_RESULT_TYPE3(Int16, Ai8, Ai16, Si32);
CHECK_RESULT_TYPE3(Float64, Ai8, Si32, Sf64);
CHECK_RESULT_TYPE3(Float64, Ai8, Sf32, Sf64);
// unsigned
CHECK_RESULT_TYPE3(UInt8, Au8, Si8, Si8);
CHECK_RESULT_TYPE3(UInt8, Au8, Si8, Si16);
CHECK_RESULT_TYPE3(Int16, Au8, Ai8, Si8);
CHECK_RESULT_TYPE3(Float16, Au8, Ai8, Sf16);
CHECK_RESULT_TYPE3(Float16, Au8, Af16, Si8);
CHECK_RESULT_TYPE3(Int8, Ai8, Su8, Si8);
// bool
CHECK_RESULT_TYPE3(Bool, Ab, Sb, Sb);
CHECK_RESULT_TYPE3(Bool, Ab, Si8, Si8);
CHECK_RESULT_TYPE3(Bool, Ab, Sb, Si8);
CHECK_RESULT_TYPE3(Int8, Ai8, Sb, Si8);
CHECK_RESULT_TYPE3(Float32, Af32, Sb, Si8);
CHECK_RESULT_TYPE3(Float32, Af32, Ab, Si8);
CHECK_RESULT_TYPE3(Float16, Ab, Ab, Sf16);
CHECK_RESULT_TYPE3(Float16, Ab, Af16, Sf16);
}
} // namespace
} // namespace chainerx
<commit_msg>Fix duplicated test<commit_after>#include "chainerx/routines/type_util.h"
#include <vector>
#include <gtest/gtest.h>
#include "chainerx/array.h"
#include "chainerx/dtype.h"
#include "chainerx/error.h"
#include "chainerx/routines/creation.h"
#include "chainerx/shape.h"
#include "chainerx/testing/context_session.h"
namespace chainerx {
namespace {
// Declares necessary variables and runs a set of checks.
#define CHECK_RESULT_TYPE_IMPL(check_body) \
{ \
testing::ContextSession context_session; \
Array Ab = Empty({2, 3}, Dtype::kBool); \
Array Au8 = Empty({2, 3}, Dtype::kUInt8); \
Array Ai8 = Empty({2, 3}, Dtype::kInt8); \
Array Ai16 = Empty({2, 3}, Dtype::kInt16); \
Array Ai32 = Empty({2, 3}, Dtype::kInt32); \
Array Ai64 = Empty({2, 3}, Dtype::kInt64); \
Array Af16 = Empty({2, 3}, Dtype::kFloat16); \
Array Af32 = Empty({2, 3}, Dtype::kFloat32); \
Array Af64 = Empty({2, 3}, Dtype::kFloat64); \
Scalar Sb{1, Dtype::kBool}; \
Scalar Su8{1, Dtype::kUInt8}; \
Scalar Si8{1, Dtype::kInt8}; \
Scalar Si16{1, Dtype::kInt16}; \
Scalar Si32{1, Dtype::kInt32}; \
Scalar Si64{1, Dtype::kInt64}; \
Scalar Sf16{1, Dtype::kFloat16}; \
Scalar Sf32{1, Dtype::kFloat32}; \
Scalar Sf64{1, Dtype::kFloat64}; \
check_body; \
}
// Checks ResultType: static-length 1-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE1(arg1) CHECK_RESULT_TYPE_IMPL({ EXPECT_EQ((arg1).dtype(), chainerx::ResultType(arg1)); })
// Checks ResultType: static-length 2-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE2(expected_dtype, arg1, arg2) \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg1)); \
})
// Checks ResultType: static-length 3-arg call
// args are Ai8, Sf32, etc.
#define CHECK_RESULT_TYPE3(expected_dtype, arg1, arg2, arg3) \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg2, arg3)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg1, arg3, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg1, arg3)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg2, arg3, arg1)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg3, arg1, arg2)); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(arg3, arg2, arg1)); \
})
// Checks ResultType: 2 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO1(harg1) \
{ \
CHECK_RESULT_TYPE1(A##harg1); \
CHECK_RESULT_TYPE1(S##harg1); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ EXPECT_EQ(A##harg1.dtype(), chainerx::ResultType(std::vector<Array>{A##harg1})); }); \
}
// Checks ResultType: 2 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO2(expected_dtype, harg1, harg2) \
{ \
CHECK_RESULT_TYPE2(expected_dtype, A##harg1, A##harg2); \
CHECK_RESULT_TYPE2(expected_dtype, S##harg1, S##harg2); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg1})); \
}); \
}
// Checks ResultType: 3 homogeneous-type arguments
// hargs are i8, f32, etc.
#define CHECK_RESULT_TYPE_HOMO3(expected_dtype, harg1, harg2, harg3) \
{ \
CHECK_RESULT_TYPE3(expected_dtype, A##harg1, A##harg2, A##harg3); \
CHECK_RESULT_TYPE3(expected_dtype, S##harg1, S##harg2, S##harg3); \
/* Dynamic-length arrays */ \
CHECK_RESULT_TYPE_IMPL({ \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg2, A##harg3})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg1, A##harg3, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg1, A##harg3})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg2, A##harg3, A##harg1})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg3, A##harg1, A##harg2})); \
EXPECT_EQ(Dtype::k##expected_dtype, chainerx::ResultType(std::vector<Array>{A##harg3, A##harg2, A##harg1})); \
}); \
}
TEST(ResultTypeTest, NoArgs) {
EXPECT_THROW({ chainerx::ResultType(std::vector<Array>{}); }, ChainerxError);
}
TEST(ResultTypeTest, One) {
CHECK_RESULT_TYPE_HOMO1(b);
CHECK_RESULT_TYPE_HOMO1(f16);
CHECK_RESULT_TYPE_HOMO1(f32);
CHECK_RESULT_TYPE_HOMO1(f64);
CHECK_RESULT_TYPE_HOMO1(i8);
CHECK_RESULT_TYPE_HOMO1(i16);
CHECK_RESULT_TYPE_HOMO1(i32);
CHECK_RESULT_TYPE_HOMO1(i64);
CHECK_RESULT_TYPE_HOMO1(u8);
}
TEST(ResultTypeTest, TwoBool) { CHECK_RESULT_TYPE_HOMO2(Bool, b, b); }
TEST(ResultTypeTest, TwoFloat) {
CHECK_RESULT_TYPE_HOMO2(Float16, f16, f16);
CHECK_RESULT_TYPE_HOMO2(Float32, f32, f32);
CHECK_RESULT_TYPE_HOMO2(Float64, f64, f64);
CHECK_RESULT_TYPE_HOMO2(Float32, f16, f32);
CHECK_RESULT_TYPE_HOMO2(Float64, f16, f64);
CHECK_RESULT_TYPE_HOMO2(Float64, f32, f64);
}
TEST(ResultTypeTest, TwoSignedInt) {
CHECK_RESULT_TYPE_HOMO2(Int8, i8, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, i8, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, i8, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i8, i64);
CHECK_RESULT_TYPE_HOMO2(Int16, i16, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, i32, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i64, i64);
CHECK_RESULT_TYPE_HOMO2(Int32, i16, i32);
CHECK_RESULT_TYPE_HOMO2(Int64, i16, i64);
CHECK_RESULT_TYPE_HOMO2(Int64, i32, i64);
}
TEST(ResultTypeTest, TwoUnsignedInt) { CHECK_RESULT_TYPE_HOMO2(UInt8, u8, u8); }
TEST(ResultTypeTest, TwoSignedIntAndUnsignedInt) {
CHECK_RESULT_TYPE_HOMO2(Int16, u8, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, u8, i16);
CHECK_RESULT_TYPE_HOMO2(Int32, u8, i32);
}
TEST(ResultTypeTest, TwoIntAndFloat) {
CHECK_RESULT_TYPE_HOMO2(Float16, i8, f16);
CHECK_RESULT_TYPE_HOMO2(Float16, u8, f16);
CHECK_RESULT_TYPE_HOMO2(Float32, i16, f32);
CHECK_RESULT_TYPE_HOMO2(Float32, i32, f32);
CHECK_RESULT_TYPE_HOMO2(Float32, i64, f32);
}
TEST(ResultTypeTest, TwoBoolAndOther) {
CHECK_RESULT_TYPE_HOMO2(UInt8, b, u8);
CHECK_RESULT_TYPE_HOMO2(Int8, b, i8);
CHECK_RESULT_TYPE_HOMO2(Int16, b, i16);
CHECK_RESULT_TYPE_HOMO2(Float16, b, f16);
CHECK_RESULT_TYPE_HOMO2(Float64, b, f64);
}
TEST(ResultTypeTest, Three) {
// signed ints
CHECK_RESULT_TYPE_HOMO3(Int32, i32, i32, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i8, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i16, i32);
CHECK_RESULT_TYPE_HOMO3(Int32, i8, i32, i32);
CHECK_RESULT_TYPE_HOMO3(Int64, i8, i64, i32);
// unsigned ints
CHECK_RESULT_TYPE_HOMO3(UInt8, u8, u8, u8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, u8, i8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, i8, i8);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, i8, i16);
CHECK_RESULT_TYPE_HOMO3(Int16, u8, u8, i16);
// float and signed int
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i8, i8);
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i32, i64);
CHECK_RESULT_TYPE_HOMO3(Float32, f16, f32, i64);
// float and unsigned int
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i8, u8);
CHECK_RESULT_TYPE_HOMO3(Float16, f16, i16, u8);
CHECK_RESULT_TYPE_HOMO3(Float32, f16, f32, u8);
// bool and other
CHECK_RESULT_TYPE_HOMO3(UInt8, b, u8, u8);
CHECK_RESULT_TYPE_HOMO3(UInt8, b, b, u8);
CHECK_RESULT_TYPE_HOMO3(Int16, b, i8, u8);
CHECK_RESULT_TYPE_HOMO3(Int32, b, b, i32);
CHECK_RESULT_TYPE_HOMO3(Float32, b, f16, f32);
CHECK_RESULT_TYPE_HOMO3(Float64, b, b, f64);
}
TEST(ResultTypeTest, ArraysAndScalars) {
// Arrays take precedence unless Scalar is a wider floating kind.
// same dtype
CHECK_RESULT_TYPE2(Int16, Ai16, Si16);
// narrower vs wider
CHECK_RESULT_TYPE2(Int16, Ai16, Si8);
CHECK_RESULT_TYPE2(Int8, Ai8, Si16);
// float vs int
CHECK_RESULT_TYPE2(Float32, Af32, Si32);
CHECK_RESULT_TYPE2(Float32, Ai32, Sf32);
// 3 arguments
CHECK_RESULT_TYPE3(Int8, Ai8, Si16, Si32);
CHECK_RESULT_TYPE3(Int16, Ai16, Si8, Si32);
CHECK_RESULT_TYPE3(Int16, Ai8, Ai16, Si32);
CHECK_RESULT_TYPE3(Float64, Ai8, Si32, Sf64);
CHECK_RESULT_TYPE3(Float64, Ai8, Sf32, Sf64);
// unsigned
CHECK_RESULT_TYPE3(UInt8, Au8, Si8, Si8);
CHECK_RESULT_TYPE3(UInt8, Au8, Si8, Si16);
CHECK_RESULT_TYPE3(Int16, Au8, Ai8, Si8);
CHECK_RESULT_TYPE3(Float16, Au8, Ai8, Sf16);
CHECK_RESULT_TYPE3(Float16, Au8, Af16, Si8);
CHECK_RESULT_TYPE3(Int8, Ai8, Su8, Si8);
// bool
CHECK_RESULT_TYPE3(Bool, Ab, Sb, Sb);
CHECK_RESULT_TYPE3(Bool, Ab, Si8, Si8);
CHECK_RESULT_TYPE3(Bool, Ab, Sb, Si8);
CHECK_RESULT_TYPE3(Int8, Ai8, Sb, Si8);
CHECK_RESULT_TYPE3(Float32, Af32, Sb, Si8);
CHECK_RESULT_TYPE3(Float32, Af32, Ab, Si8);
CHECK_RESULT_TYPE3(Float16, Ab, Ab, Sf16);
CHECK_RESULT_TYPE3(Float16, Ab, Af16, Sf16);
}
} // namespace
} // namespace chainerx
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_v7
///
/// \macro_code
///
/// \date 2015-03-22
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/// \author Axel Naumann <[email protected]>
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RHist.hxx"
#include "ROOT/RFit.hxx"
#include "ROOT/RFile.hxx"
void simple()
{
using namespace ROOT;
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
Experimental::RAxisConfig xAxis(100, 0., 1.);
Experimental::RAxisConfig yAxis({0., 1., 2., 3., 10.});
Experimental::RH2D histFromVars(xAxis, yAxis);
// Or the short in-place version:
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
Experimental::RH2D hist({100, 0., 1.}, {{0., 1., 2., 3., 10.}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist.Fill({0.01, 1.02});
// Fit the histogram.
Experimental::TFunction<2> func([](const std::array<double, 2> &x, const std::span<double> par) {
return par[0] * x[0] * x[0] + (par[1] - x[1]) * x[1];
});
auto fitResult = Experimental::FitTo(hist, func, {{0., 1.}});
auto file = Experimental::RFile::Recreate("hist.root");
file->Write("TheHist", hist);
}
<commit_msg>v7: using ROOT::Experimental in tutorials/v7/simple.cxx<commit_after>/// \file
/// \ingroup tutorial_v7
///
/// \macro_code
///
/// \date 2015-03-22
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/// \author Axel Naumann <[email protected]>
/*************************************************************************
* Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RHist.hxx"
#include "ROOT/RFit.hxx"
#include "ROOT/RFile.hxx"
void simple()
{
using namespace ROOT::Experimental;
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
RAxisConfig xAxis(100, 0., 1.);
RAxisConfig yAxis({0., 1., 2., 3., 10.});
RH2D histFromVars(xAxis, yAxis);
// Or the short in-place version:
// Create a 2D histogram with an X axis with equidistant bins, and a y axis
// with irregular binning.
RH2D hist({100, 0., 1.}, {{0., 1., 2., 3., 10.}});
// Fill weight 1. at the coordinate 0.01, 1.02.
hist.Fill({0.01, 1.02});
// Fit the histogram.
RFunction<2> func([](const std::array<double, 2> &x, const std::span<double> par) {
return par[0] * x[0] * x[0] + (par[1] - x[1]) * x[1];
});
auto fitResult = FitTo(hist, func, {{0., 1.}});
auto file = RFile::Recreate("hist.root");
file->Write("TheHist", hist);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "app/keyboard_code_conversion.h"
#include "base/basictypes.h"
#include "base/ref_counted.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/net/predictor_api.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
class AutoFillTest : public InProcessBrowserTest {
protected:
AutoFillTest() {
set_show_window(true);
EnableDOMAutomation();
}
void SetUpProfile() {
autofill_test::DisableSystemServices(browser()->profile());
AutoFillProfile profile(string16(), 0);
autofill_test::SetProfileInfo(
&profile, "Office Space", "Milton", "C.", "Waddams",
"[email protected]", "Initech", "4120 Freidrich Lane",
"Basement", "Austin", "Texas", "78744", "United States", "5125551234",
"5125550000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
std::vector<AutoFillProfile> profiles(1, profile);
personal_data_manager->SetProfiles(&profiles);
}
void ExpectFieldValue(const std::wstring& field_name,
const std::string& expected_value) {
std::string value;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.getElementById('" + field_name + L"').value);", &value));
EXPECT_EQ(expected_value, value);
}
};
// Test that basic form fill is working.
// FAILS on windows: http://crbug.com/57962
#if defined(OS_WIN)
#define MAYBE_BasicFormFill DISABLED_BasicFormFill
#else
#define MAYBE_BasicFormFill BasicFormFill
#endif
IN_PROC_BROWSER_TEST_F(AutoFillTest, MAYBE_BasicFormFill) {
SetUpProfile();
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
browser(), GURL("data:text/html;charset=utf-8,"
"<form action=\"http://www.google.com/\" method=\"POST\">"
"<label for=\"firstname\">First name:</label>"
" <input type=\"text\" id=\"firstname\" /><br />"
"<label for=\"lastname\">Last name:</label>"
" <input type=\"text\" id=\"lastname\" /><br />"
"<label for=\"address1\">Address line 1:</label>"
" <input type=\"text\" id=\"address1\" /><br />"
"<label for=\"address2\">Address line 2:</label>"
" <input type=\"text\" id=\"address2\" /><br />"
"<label for=\"city\">City:</label>"
" <input type=\"text\" id=\"city\" /><br />"
"<label for=\"state\">State:</label>"
" <select id=\"state\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br />"
"<label for=\"zip\">ZIP code:</label>"
" <input type=\"text\" id=\"zip\" /><br />"
"<label for=\"country\">Country:</label>"
" <select id=\"country\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br />"
"<label for=\"phone\">Phone number:</label>"
" <input type=\"text\" id=\"phone\" /><br />"
"</form>")));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
RenderViewHost* render_view_host =
browser()->GetSelectedTabContents()->render_view_host();
ASSERT_TRUE(ui_test_utils::ExecuteJavaScript(
render_view_host, L"", L"document.getElementById('firstname').focus();"));
// Start filling the first name field with "M" and wait for the popup to be
// shown.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_M, false, true, false, false,
NotificationType::AUTOFILL_DID_SHOW_SUGGESTIONS,
Source<RenderViewHost>(render_view_host)));
// Press the down arrow to select the suggestion and preview the autofilled
// form.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_DOWN, false, false, false, false,
NotificationType::AUTOFILL_DID_FILL_FORM_DATA,
Source<RenderViewHost>(render_view_host)));
// The previewed values should not be accessible to JavaScript.
ExpectFieldValue(L"firstname", "M");
ExpectFieldValue(L"lastname", "");
ExpectFieldValue(L"address1", "");
ExpectFieldValue(L"address2", "");
ExpectFieldValue(L"city", "");
ExpectFieldValue(L"state", "");
ExpectFieldValue(L"zip", "");
ExpectFieldValue(L"country", "");
ExpectFieldValue(L"phone", "");
// TODO(isherman): It would be nice to test that the previewed values are
// displayed: http://crbug.com/57220
// Press Enter to accept the autofill suggestions.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_RETURN, false, false, false, false,
NotificationType::AUTOFILL_DID_FILL_FORM_DATA,
Source<RenderViewHost>(render_view_host)));
// The form should be filled.
ExpectFieldValue(L"firstname", "Milton");
ExpectFieldValue(L"lastname", "Waddams");
ExpectFieldValue(L"address1", "4120 Freidrich Lane");
ExpectFieldValue(L"address2", "Basement");
ExpectFieldValue(L"city", "Austin");
ExpectFieldValue(L"state", "TX");
ExpectFieldValue(L"zip", "78744");
ExpectFieldValue(L"country", "US");
ExpectFieldValue(L"phone", "5125551234");
}
<commit_msg>(Hopefully) fix flakiness for AutoFillTest.BasicFormFill<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "app/keyboard_code_conversion.h"
#include "base/basictypes.h"
#include "base/ref_counted.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/net/predictor_api.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
class AutoFillTest : public InProcessBrowserTest {
protected:
AutoFillTest() {
set_show_window(true);
EnableDOMAutomation();
}
void SetUpProfile() {
autofill_test::DisableSystemServices(browser()->profile());
AutoFillProfile profile(string16(), 0);
autofill_test::SetProfileInfo(
&profile, "Office Space", "Milton", "C.", "Waddams",
"[email protected]", "Initech", "4120 Freidrich Lane",
"Basement", "Austin", "Texas", "78744", "United States", "5125551234",
"5125550000");
PersonalDataManager* personal_data_manager =
browser()->profile()->GetPersonalDataManager();
ASSERT_TRUE(personal_data_manager);
std::vector<AutoFillProfile> profiles(1, profile);
personal_data_manager->SetProfiles(&profiles);
}
void ExpectFieldValue(const std::wstring& field_name,
const std::string& expected_value) {
std::string value;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.getElementById('" + field_name + L"').value);", &value));
EXPECT_EQ(expected_value, value);
}
};
// Test that basic form fill is working.
IN_PROC_BROWSER_TEST_F(AutoFillTest, BasicFormFill) {
SetUpProfile();
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
browser(), GURL("data:text/html;charset=utf-8,"
"<form action=\"http://www.google.com/\" method=\"POST\">"
"<label for=\"firstname\">First name:</label>"
" <input type=\"text\" id=\"firstname\""
" onFocus=\"domAutomationController.send(true)\""
" /><br />"
"<label for=\"lastname\">Last name:</label>"
" <input type=\"text\" id=\"lastname\" /><br />"
"<label for=\"address1\">Address line 1:</label>"
" <input type=\"text\" id=\"address1\" /><br />"
"<label for=\"address2\">Address line 2:</label>"
" <input type=\"text\" id=\"address2\" /><br />"
"<label for=\"city\">City:</label>"
" <input type=\"text\" id=\"city\" /><br />"
"<label for=\"state\">State:</label>"
" <select id=\"state\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">California</option>"
" <option value=\"TX\">Texas</option>"
" </select><br />"
"<label for=\"zip\">ZIP code:</label>"
" <input type=\"text\" id=\"zip\" /><br />"
"<label for=\"country\">Country:</label>"
" <select id=\"country\">"
" <option value=\"\" selected=\"yes\">--</option>"
" <option value=\"CA\">Canada</option>"
" <option value=\"US\">United States</option>"
" </select><br />"
"<label for=\"phone\">Phone number:</label>"
" <input type=\"text\" id=\"phone\" /><br />"
"</form>")));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_TAB_CONTAINER));
ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
RenderViewHost* render_view_host =
browser()->GetSelectedTabContents()->render_view_host();
bool result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
render_view_host, L"", L"document.getElementById('firstname').focus();",
&result));
ASSERT_TRUE(result);
// Start filling the first name field with "M" and wait for the popup to be
// shown.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_M, false, true, false, false,
NotificationType::AUTOFILL_DID_SHOW_SUGGESTIONS,
Source<RenderViewHost>(render_view_host)));
// Press the down arrow to select the suggestion and preview the autofilled
// form.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_DOWN, false, false, false, false,
NotificationType::AUTOFILL_DID_FILL_FORM_DATA,
Source<RenderViewHost>(render_view_host)));
// The previewed values should not be accessible to JavaScript.
ExpectFieldValue(L"firstname", "M");
ExpectFieldValue(L"lastname", "");
ExpectFieldValue(L"address1", "");
ExpectFieldValue(L"address2", "");
ExpectFieldValue(L"city", "");
ExpectFieldValue(L"state", "");
ExpectFieldValue(L"zip", "");
ExpectFieldValue(L"country", "");
ExpectFieldValue(L"phone", "");
// TODO(isherman): It would be nice to test that the previewed values are
// displayed: http://crbug.com/57220
// Press Enter to accept the autofill suggestions.
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), app::VKEY_RETURN, false, false, false, false,
NotificationType::AUTOFILL_DID_FILL_FORM_DATA,
Source<RenderViewHost>(render_view_host)));
// The form should be filled.
ExpectFieldValue(L"firstname", "Milton");
ExpectFieldValue(L"lastname", "Waddams");
ExpectFieldValue(L"address1", "4120 Freidrich Lane");
ExpectFieldValue(L"address2", "Basement");
ExpectFieldValue(L"city", "Austin");
ExpectFieldValue(L"state", "TX");
ExpectFieldValue(L"zip", "78744");
ExpectFieldValue(L"country", "US");
ExpectFieldValue(L"phone", "5125551234");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/network_library.h"
#include <algorithm>
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "net/url_request/url_request_job.h"
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
template <>
struct RunnableMethodTraits<chromeos::NetworkLibrary> {
void RetainCallee(chromeos::NetworkLibrary* obj) {}
void ReleaseCallee(chromeos::NetworkLibrary* obj) {}
};
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
// static
const int NetworkLibrary::kNetworkTrafficeTimerSecs = 1;
NetworkLibrary::NetworkLibrary()
: traffic_type_(0),
network_devices_(0),
offline_mode_(false) {
if (CrosLibrary::EnsureLoaded()) {
Init();
}
g_url_request_job_tracker.AddObserver(this);
}
NetworkLibrary::~NetworkLibrary() {
if (CrosLibrary::EnsureLoaded()) {
chromeos::DisconnectNetworkStatus(network_status_connection_);
}
g_url_request_job_tracker.RemoveObserver(this);
}
// static
NetworkLibrary* NetworkLibrary::Get() {
return Singleton<NetworkLibrary>::get();
}
// static
bool NetworkLibrary::EnsureLoaded() {
return CrosLibrary::EnsureLoaded();
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary, URLRequestJobTracker::JobObserver implementation:
void NetworkLibrary::OnJobAdded(URLRequestJob* job) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobRemoved(URLRequestJob* job) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobDone(URLRequestJob* job,
const URLRequestStatus& status) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobRedirect(URLRequestJob* job, const GURL& location,
int status_code) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnBytesRead(URLRequestJob* job, int byte_count) {
CheckNetworkTraffic(true);
}
void NetworkLibrary::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void NetworkLibrary::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
static const char* GetEncryptionString(chromeos::EncryptionType encryption) {
switch (encryption) {
case chromeos::NONE:
return "none";
case chromeos::RSN:
return "rsn";
case chromeos::WEP:
return "wep";
case chromeos::WPA:
return "wpa";
}
return "none";
}
void NetworkLibrary::ConnectToWifiNetwork(WifiNetwork network,
const string16& password) {
if (CrosLibrary::EnsureLoaded()) {
// This call kicks off a request to connect to this network, the results of
// which we'll hear about through the monitoring we've set up in Init();
chromeos::ConnectToWifiNetwork(
network.ssid.c_str(),
password.empty() ? NULL : UTF16ToUTF8(password).c_str(),
GetEncryptionString(network.encryption));
}
}
void NetworkLibrary::ConnectToCellularNetwork(CellularNetwork network) {
if (CrosLibrary::EnsureLoaded()) {
// This call kicks off a request to connect to this network, the results of
// which we'll hear about through the monitoring we've set up in Init();
chromeos::ConnectToWifiNetwork(network.name.c_str(), NULL, NULL);
}
}
void NetworkLibrary::EnableEthernetNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_ETHERNET, enable);
}
void NetworkLibrary::EnableWifiNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_WIFI, enable);
}
void NetworkLibrary::EnableCellularNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_CELLULAR, enable);
}
void NetworkLibrary::EnableOfflineMode(bool enable) {
if (!CrosLibrary::EnsureLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
LOG(INFO) << "Trying to enable offline mode when it's already enabled. ";
return;
}
if (!enable && !offline_mode_) {
LOG(INFO) << "Trying to disable offline mode when it's already disabled. ";
return;
}
if (chromeos::SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
NetworkIPConfigVector NetworkLibrary::GetIPConfigs(
const std::string& device_path) {
NetworkIPConfigVector ipconfig_vector;
if (!device_path.empty()) {
chromeos::IPConfigStatus* ipconfig_status =
chromeos::ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
chromeos::IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
chromeos::FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
return ipconfig_vector;
}
// static
void NetworkLibrary::NetworkStatusChangedHandler(void* object,
const chromeos::ServiceStatus& service_status) {
NetworkLibrary* network = static_cast<NetworkLibrary*>(object);
EthernetNetwork ethernet;
WifiNetworkVector wifi_networks;
CellularNetworkVector cellular_networks;
ParseNetworks(service_status, ðernet, &wifi_networks, &cellular_networks);
network->UpdateNetworkStatus(ethernet, wifi_networks, cellular_networks);
}
// static
void NetworkLibrary::ParseNetworks(
const chromeos::ServiceStatus& service_status, EthernetNetwork* ethernet,
WifiNetworkVector* wifi_networks,
CellularNetworkVector* cellular_networks) {
DLOG(INFO) << "ParseNetworks:";
for (int i = 0; i < service_status.size; i++) {
const chromeos::ServiceInfo& service = service_status.services[i];
DLOG(INFO) << " (" << service.type <<
") " << service.ssid <<
" sta=" << service.state <<
" pas=" << service.needs_passphrase <<
" enc=" << service.encryption <<
" sig=" << service.signal_strength;
bool connecting = service.state == chromeos::STATE_ASSOCIATION ||
service.state == chromeos::STATE_CONFIGURATION ||
service.state == chromeos::STATE_CARRIER;
bool connected = service.state == chromeos::STATE_READY;
// if connected, get ip config
std::string ip_address;
if (connected) {
chromeos::IPConfigStatus* ipconfig_status =
chromeos::ListIPConfigs(service.device_path);
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
chromeos::IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0)
ip_address = ipconfig.address;
DLOG(INFO) << " ipconfig: " <<
" type=" << ipconfig.type <<
" address=" << ipconfig.address <<
" mtu=" << ipconfig.mtu <<
" netmask=" << ipconfig.netmask <<
" broadcast=" << ipconfig.broadcast <<
" peer_address=" << ipconfig.peer_address <<
" gateway=" << ipconfig.gateway <<
" domainname=" << ipconfig.domainname <<
" name_servers=" << ipconfig.name_servers;
}
chromeos::FreeIPConfigStatus(ipconfig_status);
}
}
if (service.type == chromeos::TYPE_ETHERNET) {
ethernet->connecting = connecting;
ethernet->connected = connected;
ethernet->device_path = service.device_path;
ethernet->ip_address = ip_address;
} else if (service.type == chromeos::TYPE_WIFI) {
wifi_networks->push_back(WifiNetwork(service.device_path,
service.ssid,
service.needs_passphrase,
service.encryption,
service.signal_strength,
connecting,
connected,
ip_address));
} else if (service.type == chromeos::TYPE_CELLULAR) {
cellular_networks->push_back(CellularNetwork(service.device_path,
service.ssid,
service.signal_strength,
connecting,
connected,
ip_address));
}
}
}
void NetworkLibrary::Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
chromeos::ServiceStatus* service_status = chromeos::GetAvailableNetworks();
if (service_status) {
LOG(INFO) << "Getting initial CrOS network info.";
EthernetNetwork ethernet;
WifiNetworkVector wifi_networks;
CellularNetworkVector cellular_networks;
ParseNetworks(*service_status, ðernet, &wifi_networks,
&cellular_networks);
UpdateNetworkStatus(ethernet, wifi_networks, cellular_networks);
chromeos::FreeServiceStatus(service_status);
}
LOG(INFO) << "Registering for network status updates.";
// Now, register to receive updates on network status.
network_status_connection_ = chromeos::MonitorNetworkStatus(
&NetworkStatusChangedHandler, this);
// Get the enabled network devices bit flag. If we get a -1, then that means
// offline mode is on. So all devices are disabled. This happens when offline
// mode is persisted during a reboot and Chrome starts up with it on.
network_devices_ = chromeos::GetEnabledNetworkDevices();
if (network_devices_ == -1) {
offline_mode_ = true;
network_devices_ = 0;
}
}
void NetworkLibrary::EnableNetworkDevice(chromeos::ConnectionType device,
bool enable) {
if (!CrosLibrary::EnsureLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (network_devices_ & device)) {
LOG(INFO) << "Trying to enable a network device that's already enabled: "
<< device;
return;
}
if (!enable && !(network_devices_ & device)) {
LOG(INFO) << "Trying to disable a network device that's already disabled: "
<< device;
return;
}
if (chromeos::EnableNetworkDevice(device, enable)) {
if (enable)
network_devices_ |= device;
else
network_devices_ &= ~device;
}
}
void NetworkLibrary::UpdateNetworkStatus(const EthernetNetwork& ethernet,
const WifiNetworkVector& wifi_networks,
const CellularNetworkVector& cellular_networks) {
// Make sure we run on UI thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(this,
&NetworkLibrary::UpdateNetworkStatus, ethernet, wifi_networks,
cellular_networks));
return;
}
ethernet_ = ethernet;
wifi_networks_ = wifi_networks;
// Sort the list of wifi networks by ssid.
std::sort(wifi_networks_.begin(), wifi_networks_.end());
wifi_ = WifiNetwork();
for (size_t i = 0; i < wifi_networks_.size(); i++) {
if (wifi_networks_[i].connecting || wifi_networks_[i].connected) {
wifi_ = wifi_networks_[i];
break; // There is only one connected or connecting wifi network.
}
}
cellular_networks_ = cellular_networks;
std::sort(cellular_networks_.begin(), cellular_networks_.end());
cellular_ = CellularNetwork();
for (size_t i = 0; i < cellular_networks_.size(); i++) {
if (cellular_networks_[i].connecting || cellular_networks_[i].connected) {
cellular_ = cellular_networks_[i];
break; // There is only one connected or connecting cellular network.
}
}
FOR_EACH_OBSERVER(Observer, observers_, NetworkChanged(this));
}
void NetworkLibrary::CheckNetworkTraffic(bool download) {
// If we already have a pending upload and download notification, then
// shortcut and return.
if (traffic_type_ == (Observer::TRAFFIC_DOWNLOAD | Observer::TRAFFIC_UPLOAD))
return;
// Figure out if we are uploading and/or downloading. We are downloading
// if download == true. We are uploading if we have upload progress.
if (download)
traffic_type_ |= Observer::TRAFFIC_DOWNLOAD;
if ((traffic_type_ & Observer::TRAFFIC_UPLOAD) == 0) {
URLRequestJobTracker::JobIterator it;
for (it = g_url_request_job_tracker.begin();
it != g_url_request_job_tracker.end();
++it) {
URLRequestJob* job = *it;
if (job->GetUploadProgress() > 0) {
traffic_type_ |= Observer::TRAFFIC_UPLOAD;
break;
}
}
}
// If we have new traffic data to send out and the timer is not currently
// running, then start a new timer.
if (traffic_type_ && !timer_.IsRunning()) {
timer_.Start(base::TimeDelta::FromSeconds(kNetworkTrafficeTimerSecs), this,
&NetworkLibrary::NetworkTrafficTimerFired);
}
}
void NetworkLibrary:: NetworkTrafficTimerFired() {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(this, &NetworkLibrary::NotifyNetworkTraffic,
traffic_type_));
// Reset traffic type so that we don't send the same data next time.
traffic_type_ = 0;
}
void NetworkLibrary::NotifyNetworkTraffic(int traffic_type) {
FOR_EACH_OBSERVER(Observer, observers_, NetworkTraffic(this, traffic_type));
}
bool NetworkLibrary::Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool NetworkLibrary::Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& NetworkLibrary::IPAddress() const {
// Returns highest priority IP address.
if (ethernet_connected())
return ethernet_.ip_address;
if (wifi_connected())
return wifi_.ip_address;
if (cellular_connected())
return cellular_.ip_address;
return ethernet_.ip_address;
}
} // namespace chromeos
<commit_msg>Fix ChromeOS crash when device_path is NULL. TEST=None BUG=1698 Review URL: http://codereview.chromium.org/661230<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/network_library.h"
#include <algorithm>
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "net/url_request/url_request_job.h"
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
template <>
struct RunnableMethodTraits<chromeos::NetworkLibrary> {
void RetainCallee(chromeos::NetworkLibrary* obj) {}
void ReleaseCallee(chromeos::NetworkLibrary* obj) {}
};
namespace chromeos {
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary
// static
const int NetworkLibrary::kNetworkTrafficeTimerSecs = 1;
NetworkLibrary::NetworkLibrary()
: traffic_type_(0),
network_devices_(0),
offline_mode_(false) {
if (CrosLibrary::EnsureLoaded()) {
Init();
}
g_url_request_job_tracker.AddObserver(this);
}
NetworkLibrary::~NetworkLibrary() {
if (CrosLibrary::EnsureLoaded()) {
chromeos::DisconnectNetworkStatus(network_status_connection_);
}
g_url_request_job_tracker.RemoveObserver(this);
}
// static
NetworkLibrary* NetworkLibrary::Get() {
return Singleton<NetworkLibrary>::get();
}
// static
bool NetworkLibrary::EnsureLoaded() {
return CrosLibrary::EnsureLoaded();
}
////////////////////////////////////////////////////////////////////////////////
// NetworkLibrary, URLRequestJobTracker::JobObserver implementation:
void NetworkLibrary::OnJobAdded(URLRequestJob* job) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobRemoved(URLRequestJob* job) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobDone(URLRequestJob* job,
const URLRequestStatus& status) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnJobRedirect(URLRequestJob* job, const GURL& location,
int status_code) {
CheckNetworkTraffic(false);
}
void NetworkLibrary::OnBytesRead(URLRequestJob* job, int byte_count) {
CheckNetworkTraffic(true);
}
void NetworkLibrary::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void NetworkLibrary::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
static const char* GetEncryptionString(chromeos::EncryptionType encryption) {
switch (encryption) {
case chromeos::NONE:
return "none";
case chromeos::RSN:
return "rsn";
case chromeos::WEP:
return "wep";
case chromeos::WPA:
return "wpa";
}
return "none";
}
void NetworkLibrary::ConnectToWifiNetwork(WifiNetwork network,
const string16& password) {
if (CrosLibrary::EnsureLoaded()) {
// This call kicks off a request to connect to this network, the results of
// which we'll hear about through the monitoring we've set up in Init();
chromeos::ConnectToWifiNetwork(
network.ssid.c_str(),
password.empty() ? NULL : UTF16ToUTF8(password).c_str(),
GetEncryptionString(network.encryption));
}
}
void NetworkLibrary::ConnectToCellularNetwork(CellularNetwork network) {
if (CrosLibrary::EnsureLoaded()) {
// This call kicks off a request to connect to this network, the results of
// which we'll hear about through the monitoring we've set up in Init();
chromeos::ConnectToWifiNetwork(network.name.c_str(), NULL, NULL);
}
}
void NetworkLibrary::EnableEthernetNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_ETHERNET, enable);
}
void NetworkLibrary::EnableWifiNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_WIFI, enable);
}
void NetworkLibrary::EnableCellularNetworkDevice(bool enable) {
EnableNetworkDevice(chromeos::TYPE_CELLULAR, enable);
}
void NetworkLibrary::EnableOfflineMode(bool enable) {
if (!CrosLibrary::EnsureLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && offline_mode_) {
LOG(INFO) << "Trying to enable offline mode when it's already enabled. ";
return;
}
if (!enable && !offline_mode_) {
LOG(INFO) << "Trying to disable offline mode when it's already disabled. ";
return;
}
if (chromeos::SetOfflineMode(enable)) {
offline_mode_ = enable;
}
}
NetworkIPConfigVector NetworkLibrary::GetIPConfigs(
const std::string& device_path) {
NetworkIPConfigVector ipconfig_vector;
if (!device_path.empty()) {
chromeos::IPConfigStatus* ipconfig_status =
chromeos::ListIPConfigs(device_path.c_str());
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
chromeos::IPConfig ipconfig = ipconfig_status->ips[i];
ipconfig_vector.push_back(
NetworkIPConfig(device_path, ipconfig.type, ipconfig.address,
ipconfig.netmask, ipconfig.gateway,
ipconfig.name_servers));
}
chromeos::FreeIPConfigStatus(ipconfig_status);
// Sort the list of ip configs by type.
std::sort(ipconfig_vector.begin(), ipconfig_vector.end());
}
}
return ipconfig_vector;
}
// static
void NetworkLibrary::NetworkStatusChangedHandler(void* object,
const chromeos::ServiceStatus& service_status) {
NetworkLibrary* network = static_cast<NetworkLibrary*>(object);
EthernetNetwork ethernet;
WifiNetworkVector wifi_networks;
CellularNetworkVector cellular_networks;
ParseNetworks(service_status, ðernet, &wifi_networks, &cellular_networks);
network->UpdateNetworkStatus(ethernet, wifi_networks, cellular_networks);
}
// static
void NetworkLibrary::ParseNetworks(
const chromeos::ServiceStatus& service_status, EthernetNetwork* ethernet,
WifiNetworkVector* wifi_networks,
CellularNetworkVector* cellular_networks) {
DLOG(INFO) << "ParseNetworks:";
for (int i = 0; i < service_status.size; i++) {
const chromeos::ServiceInfo& service = service_status.services[i];
DLOG(INFO) << " (" << service.type <<
") " << service.ssid <<
" sta=" << service.state <<
" pas=" << service.needs_passphrase <<
" enc=" << service.encryption <<
" sig=" << service.signal_strength;
bool connecting = service.state == chromeos::STATE_ASSOCIATION ||
service.state == chromeos::STATE_CONFIGURATION ||
service.state == chromeos::STATE_CARRIER;
bool connected = service.state == chromeos::STATE_READY;
// if connected, get ip config
std::string ip_address;
if (connected && service.device_path) {
chromeos::IPConfigStatus* ipconfig_status =
chromeos::ListIPConfigs(service.device_path);
if (ipconfig_status) {
for (int i = 0; i < ipconfig_status->size; i++) {
chromeos::IPConfig ipconfig = ipconfig_status->ips[i];
if (strlen(ipconfig.address) > 0)
ip_address = ipconfig.address;
DLOG(INFO) << " ipconfig: " <<
" type=" << ipconfig.type <<
" address=" << ipconfig.address <<
" mtu=" << ipconfig.mtu <<
" netmask=" << ipconfig.netmask <<
" broadcast=" << ipconfig.broadcast <<
" peer_address=" << ipconfig.peer_address <<
" gateway=" << ipconfig.gateway <<
" domainname=" << ipconfig.domainname <<
" name_servers=" << ipconfig.name_servers;
}
chromeos::FreeIPConfigStatus(ipconfig_status);
}
}
if (service.type == chromeos::TYPE_ETHERNET) {
ethernet->connecting = connecting;
ethernet->connected = connected;
ethernet->device_path = service.device_path ? service.device_path :
std::string();
ethernet->ip_address = ip_address;
} else if (service.type == chromeos::TYPE_WIFI) {
wifi_networks->push_back(WifiNetwork(service.device_path ?
service.device_path :
std::string(),
service.ssid,
service.needs_passphrase,
service.encryption,
service.signal_strength,
connecting,
connected,
ip_address));
} else if (service.type == chromeos::TYPE_CELLULAR) {
cellular_networks->push_back(CellularNetwork(service.device_path ?
service.device_path :
std::string(),
service.ssid,
service.signal_strength,
connecting,
connected,
ip_address));
}
}
}
void NetworkLibrary::Init() {
// First, get the currently available networks. This data is cached
// on the connman side, so the call should be quick.
chromeos::ServiceStatus* service_status = chromeos::GetAvailableNetworks();
if (service_status) {
LOG(INFO) << "Getting initial CrOS network info.";
EthernetNetwork ethernet;
WifiNetworkVector wifi_networks;
CellularNetworkVector cellular_networks;
ParseNetworks(*service_status, ðernet, &wifi_networks,
&cellular_networks);
UpdateNetworkStatus(ethernet, wifi_networks, cellular_networks);
chromeos::FreeServiceStatus(service_status);
}
LOG(INFO) << "Registering for network status updates.";
// Now, register to receive updates on network status.
network_status_connection_ = chromeos::MonitorNetworkStatus(
&NetworkStatusChangedHandler, this);
// Get the enabled network devices bit flag. If we get a -1, then that means
// offline mode is on. So all devices are disabled. This happens when offline
// mode is persisted during a reboot and Chrome starts up with it on.
network_devices_ = chromeos::GetEnabledNetworkDevices();
if (network_devices_ == -1) {
offline_mode_ = true;
network_devices_ = 0;
}
}
void NetworkLibrary::EnableNetworkDevice(chromeos::ConnectionType device,
bool enable) {
if (!CrosLibrary::EnsureLoaded())
return;
// If network device is already enabled/disabled, then don't do anything.
if (enable && (network_devices_ & device)) {
LOG(INFO) << "Trying to enable a network device that's already enabled: "
<< device;
return;
}
if (!enable && !(network_devices_ & device)) {
LOG(INFO) << "Trying to disable a network device that's already disabled: "
<< device;
return;
}
if (chromeos::EnableNetworkDevice(device, enable)) {
if (enable)
network_devices_ |= device;
else
network_devices_ &= ~device;
}
}
void NetworkLibrary::UpdateNetworkStatus(const EthernetNetwork& ethernet,
const WifiNetworkVector& wifi_networks,
const CellularNetworkVector& cellular_networks) {
// Make sure we run on UI thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(this,
&NetworkLibrary::UpdateNetworkStatus, ethernet, wifi_networks,
cellular_networks));
return;
}
ethernet_ = ethernet;
wifi_networks_ = wifi_networks;
// Sort the list of wifi networks by ssid.
std::sort(wifi_networks_.begin(), wifi_networks_.end());
wifi_ = WifiNetwork();
for (size_t i = 0; i < wifi_networks_.size(); i++) {
if (wifi_networks_[i].connecting || wifi_networks_[i].connected) {
wifi_ = wifi_networks_[i];
break; // There is only one connected or connecting wifi network.
}
}
cellular_networks_ = cellular_networks;
std::sort(cellular_networks_.begin(), cellular_networks_.end());
cellular_ = CellularNetwork();
for (size_t i = 0; i < cellular_networks_.size(); i++) {
if (cellular_networks_[i].connecting || cellular_networks_[i].connected) {
cellular_ = cellular_networks_[i];
break; // There is only one connected or connecting cellular network.
}
}
FOR_EACH_OBSERVER(Observer, observers_, NetworkChanged(this));
}
void NetworkLibrary::CheckNetworkTraffic(bool download) {
// If we already have a pending upload and download notification, then
// shortcut and return.
if (traffic_type_ == (Observer::TRAFFIC_DOWNLOAD | Observer::TRAFFIC_UPLOAD))
return;
// Figure out if we are uploading and/or downloading. We are downloading
// if download == true. We are uploading if we have upload progress.
if (download)
traffic_type_ |= Observer::TRAFFIC_DOWNLOAD;
if ((traffic_type_ & Observer::TRAFFIC_UPLOAD) == 0) {
URLRequestJobTracker::JobIterator it;
for (it = g_url_request_job_tracker.begin();
it != g_url_request_job_tracker.end();
++it) {
URLRequestJob* job = *it;
if (job->GetUploadProgress() > 0) {
traffic_type_ |= Observer::TRAFFIC_UPLOAD;
break;
}
}
}
// If we have new traffic data to send out and the timer is not currently
// running, then start a new timer.
if (traffic_type_ && !timer_.IsRunning()) {
timer_.Start(base::TimeDelta::FromSeconds(kNetworkTrafficeTimerSecs), this,
&NetworkLibrary::NetworkTrafficTimerFired);
}
}
void NetworkLibrary:: NetworkTrafficTimerFired() {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(this, &NetworkLibrary::NotifyNetworkTraffic,
traffic_type_));
// Reset traffic type so that we don't send the same data next time.
traffic_type_ = 0;
}
void NetworkLibrary::NotifyNetworkTraffic(int traffic_type) {
FOR_EACH_OBSERVER(Observer, observers_, NetworkTraffic(this, traffic_type));
}
bool NetworkLibrary::Connected() const {
return ethernet_connected() || wifi_connected() || cellular_connected();
}
bool NetworkLibrary::Connecting() const {
return ethernet_connecting() || wifi_connecting() || cellular_connecting();
}
const std::string& NetworkLibrary::IPAddress() const {
// Returns highest priority IP address.
if (ethernet_connected())
return ethernet_.ip_address;
if (wifi_connected())
return wifi_.ip_address;
if (cellular_connected())
return cellular_.ip_address;
return ethernet_.ip_address;
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/analyserexternalvariable.h"
#include "libcellml/component.h"
#include "analyserexternalvariable_p.h"
#include "utilities.h"
namespace libcellml {
AnalyserExternalVariable::AnalyserExternalVariableImpl::AnalyserExternalVariableImpl(const VariablePtr &variable)
: mVariable(variable)
{
}
std::vector<VariablePtr>::iterator AnalyserExternalVariable::AnalyserExternalVariableImpl::findDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName)
{
return std::find_if(mDependencies.begin(), mDependencies.end(), [=](const VariablePtr &v) {
return (owningModel(v) == model) && (owningComponent(v)->name() == componentName) && (v->name() == variableName);
});
}
std::vector<VariablePtr>::iterator AnalyserExternalVariable::AnalyserExternalVariableImpl::findDependency(const VariablePtr &variable)
{
return std::find_if(mDependencies.begin(), mDependencies.end(), [=](const VariablePtr &v) {
return v == variable;
});
}
AnalyserExternalVariable::AnalyserExternalVariable(const VariablePtr &variable)
: mPimpl(new AnalyserExternalVariableImpl(variable))
{
}
AnalyserExternalVariable::~AnalyserExternalVariable()
{
delete mPimpl;
}
AnalyserExternalVariablePtr AnalyserExternalVariable::create(const VariablePtr &variable) noexcept
{
return std::shared_ptr<AnalyserExternalVariable> {new AnalyserExternalVariable {variable}};
}
VariablePtr AnalyserExternalVariable::variable() const
{
return mPimpl->mVariable;
}
bool AnalyserExternalVariable::addDependency(const VariablePtr &variable)
{
if (!isSameOrEquivalentVariable(variable, mPimpl->mVariable)
&& (owningModel(variable) == owningModel(mPimpl->mVariable))
&& std::find(mPimpl->mDependencies.begin(), mPimpl->mDependencies.end(), variable) == mPimpl->mDependencies.end()) {
mPimpl->mDependencies.push_back(variable);
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(size_t index)
{
if (index < mPimpl->mDependencies.size()) {
mPimpl->mDependencies.erase(mPimpl->mDependencies.begin() + int64_t(index));
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName)
{
auto result = mPimpl->findDependency(model, componentName, variableName);
if (result != mPimpl->mDependencies.end()) {
mPimpl->mDependencies.erase(result);
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(const VariablePtr &variable)
{
auto result = mPimpl->findDependency(variable);
if (result != mPimpl->mDependencies.end()) {
mPimpl->mDependencies.erase(result);
return true;
}
return false;
}
void AnalyserExternalVariable::removeAllDependencies()
{
mPimpl->mDependencies.clear();
}
bool AnalyserExternalVariable::containsDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
return mPimpl->findDependency(model, componentName, variableName) != mPimpl->mDependencies.end();
}
bool AnalyserExternalVariable::containsDependency(const VariablePtr &variable) const
{
return mPimpl->findDependency(variable) != mPimpl->mDependencies.end();
}
VariablePtr AnalyserExternalVariable::dependency(size_t index) const
{
if (index < mPimpl->mDependencies.size()) {
return mPimpl->mDependencies.at(index);
}
return nullptr;
}
VariablePtr AnalyserExternalVariable::dependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
auto result = mPimpl->findDependency(model, componentName, variableName);
if (result != mPimpl->mDependencies.end()) {
return *result;
}
return nullptr;
}
std::vector<VariablePtr> AnalyserExternalVariable::dependencies() const
{
return mPimpl->mDependencies;
}
size_t AnalyserExternalVariable::dependencyCount() const
{
return mPimpl->mDependencies.size();
}
} // namespace libcellml
<commit_msg>Revert "Address a coverage issue."<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/analyserexternalvariable.h"
#include "libcellml/component.h"
#include "analyserexternalvariable_p.h"
#include "utilities.h"
namespace libcellml {
AnalyserExternalVariable::AnalyserExternalVariableImpl::AnalyserExternalVariableImpl(const VariablePtr &variable)
: mVariable(variable)
{
}
std::vector<VariablePtr>::iterator AnalyserExternalVariable::AnalyserExternalVariableImpl::findDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName)
{
return std::find_if(mDependencies.begin(), mDependencies.end(), [=](const VariablePtr &v) {
return (owningModel(v) == model)
&& (owningComponent(v)->name() == componentName)
&& (v->name() == variableName);
});
}
std::vector<VariablePtr>::iterator AnalyserExternalVariable::AnalyserExternalVariableImpl::findDependency(const VariablePtr &variable)
{
return std::find_if(mDependencies.begin(), mDependencies.end(), [=](const VariablePtr &v) {
return v == variable;
});
}
AnalyserExternalVariable::AnalyserExternalVariable(const VariablePtr &variable)
: mPimpl(new AnalyserExternalVariableImpl(variable))
{
}
AnalyserExternalVariable::~AnalyserExternalVariable()
{
delete mPimpl;
}
AnalyserExternalVariablePtr AnalyserExternalVariable::create(const VariablePtr &variable) noexcept
{
return std::shared_ptr<AnalyserExternalVariable> {new AnalyserExternalVariable {variable}};
}
VariablePtr AnalyserExternalVariable::variable() const
{
return mPimpl->mVariable;
}
bool AnalyserExternalVariable::addDependency(const VariablePtr &variable)
{
if (!isSameOrEquivalentVariable(variable, mPimpl->mVariable)
&& (owningModel(variable) == owningModel(mPimpl->mVariable))
&& std::find(mPimpl->mDependencies.begin(), mPimpl->mDependencies.end(), variable) == mPimpl->mDependencies.end()) {
mPimpl->mDependencies.push_back(variable);
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(size_t index)
{
if (index < mPimpl->mDependencies.size()) {
mPimpl->mDependencies.erase(mPimpl->mDependencies.begin() + int64_t(index));
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName)
{
auto result = mPimpl->findDependency(model, componentName, variableName);
if (result != mPimpl->mDependencies.end()) {
mPimpl->mDependencies.erase(result);
return true;
}
return false;
}
bool AnalyserExternalVariable::removeDependency(const VariablePtr &variable)
{
auto result = mPimpl->findDependency(variable);
if (result != mPimpl->mDependencies.end()) {
mPimpl->mDependencies.erase(result);
return true;
}
return false;
}
void AnalyserExternalVariable::removeAllDependencies()
{
mPimpl->mDependencies.clear();
}
bool AnalyserExternalVariable::containsDependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
return mPimpl->findDependency(model, componentName, variableName) != mPimpl->mDependencies.end();
}
bool AnalyserExternalVariable::containsDependency(const VariablePtr &variable) const
{
return mPimpl->findDependency(variable) != mPimpl->mDependencies.end();
}
VariablePtr AnalyserExternalVariable::dependency(size_t index) const
{
if (index < mPimpl->mDependencies.size()) {
return mPimpl->mDependencies.at(index);
}
return nullptr;
}
VariablePtr AnalyserExternalVariable::dependency(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
auto result = mPimpl->findDependency(model, componentName, variableName);
if (result != mPimpl->mDependencies.end()) {
return *result;
}
return nullptr;
}
std::vector<VariablePtr> AnalyserExternalVariable::dependencies() const
{
return mPimpl->mDependencies;
}
size_t AnalyserExternalVariable::dependencyCount() const
{
return mPimpl->mDependencies.size();
}
} // namespace libcellml
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/menuitem/menuitem.h"
#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/menu/menu.h"
namespace api {
void MenuItem::Create(const base::DictionaryValue& option) {
std::string type;
option.GetString("type", &type);
if (type == "separator") {
menu_item_ = gtk_separator_menu_item_new();
} else {
if (type == "checkbox") {
menu_item_ = gtk_check_menu_item_new();
bool checked;
if (option.GetBoolean("checked", &checked))
SetChecked(checked);
} else {
menu_item_ = gtk_image_menu_item_new();
std::string icon;
if (option.GetString("icon", &icon))
SetIcon(icon);
}
bool enabled;
if (option.GetBoolean("enabled", &enabled))
SetEnabled(enabled);
std::string label;
if (option.GetString("label", &label))
SetLabel(label);
std::string tooltip;
if (option.GetString("tooltip", &tooltip))
SetTooltip(tooltip);
int menu_id;
if (option.GetInteger("submenu", &menu_id))
SetSubmenu(dispatcher_host()->GetObject<Menu>(menu_id));
block_active_ = false;
g_signal_connect(menu_item_, "activate",
G_CALLBACK(OnClickThunk), this);
}
gtk_widget_show(menu_item_);
g_object_ref_sink(G_OBJECT(menu_item_));
}
void MenuItem::Destroy() {
gtk_widget_destroy(menu_item_);
g_object_unref(G_OBJECT(menu_item_));
}
void MenuItem::SetLabel(const std::string& label) {
gtk_menu_item_set_label(GTK_MENU_ITEM(menu_item_), label.c_str());
}
void MenuItem::SetIcon(const std::string& icon) {
if (icon.empty())
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item_), NULL);
else {
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item_),
gtk_image_new_from_file(icon.c_str()));
gtk_image_menu_item_set_always_show_image(GTK_IMAGE_MENU_ITEM(menu_item_),
TRUE);
}
}
void MenuItem::SetTooltip(const std::string& tooltip) {
gtk_widget_set_tooltip_text(menu_item_, tooltip.c_str());
}
void MenuItem::SetEnabled(bool enabled) {
gtk_widget_set_sensitive(menu_item_, enabled);
}
void MenuItem::SetChecked(bool checked) {
// Set active will cause 'activate' to be emitted, so block here
block_active_ = true;
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menu_item_), checked);
block_active_ = false;
}
void MenuItem::SetSubmenu(Menu* sub_menu) {
if (sub_menu == NULL)
gtk_menu_item_remove_submenu(GTK_MENU_ITEM(menu_item_));
else
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item_), sub_menu->menu_);
}
void MenuItem::OnClick(GtkWidget* widget) {
if (block_active_)
return;
base::ListValue args;
dispatcher_host()->SendEvent(this, "click", args);
}
} // namespace api
<commit_msg>[GTK]Fix code style<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/menuitem/menuitem.h"
#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/menu/menu.h"
namespace api {
void MenuItem::Create(const base::DictionaryValue& option) {
std::string type;
option.GetString("type", &type);
if (type == "separator") {
menu_item_ = gtk_separator_menu_item_new();
} else {
if (type == "checkbox") {
menu_item_ = gtk_check_menu_item_new();
bool checked;
if (option.GetBoolean("checked", &checked))
SetChecked(checked);
} else {
menu_item_ = gtk_image_menu_item_new();
std::string icon;
if (option.GetString("icon", &icon))
SetIcon(icon);
}
bool enabled;
if (option.GetBoolean("enabled", &enabled))
SetEnabled(enabled);
std::string label;
if (option.GetString("label", &label))
SetLabel(label);
std::string tooltip;
if (option.GetString("tooltip", &tooltip))
SetTooltip(tooltip);
int menu_id;
if (option.GetInteger("submenu", &menu_id))
SetSubmenu(dispatcher_host()->GetObject<Menu>(menu_id));
block_active_ = false;
g_signal_connect(menu_item_, "activate",
G_CALLBACK(OnClickThunk), this);
}
gtk_widget_show(menu_item_);
g_object_ref_sink(G_OBJECT(menu_item_));
}
void MenuItem::Destroy() {
gtk_widget_destroy(menu_item_);
g_object_unref(G_OBJECT(menu_item_));
}
void MenuItem::SetLabel(const std::string& label) {
gtk_menu_item_set_label(GTK_MENU_ITEM(menu_item_), label.c_str());
}
void MenuItem::SetIcon(const std::string& icon) {
if (icon.empty()) {
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item_), NULL);
}
else {
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item_),
gtk_image_new_from_file(icon.c_str()));
gtk_image_menu_item_set_always_show_image(GTK_IMAGE_MENU_ITEM(menu_item_),
TRUE);
}
}
void MenuItem::SetTooltip(const std::string& tooltip) {
gtk_widget_set_tooltip_text(menu_item_, tooltip.c_str());
}
void MenuItem::SetEnabled(bool enabled) {
gtk_widget_set_sensitive(menu_item_, enabled);
}
void MenuItem::SetChecked(bool checked) {
// Set active will cause 'activate' to be emitted, so block here
block_active_ = true;
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menu_item_), checked);
block_active_ = false;
}
void MenuItem::SetSubmenu(Menu* sub_menu) {
if (sub_menu == NULL)
gtk_menu_item_remove_submenu(GTK_MENU_ITEM(menu_item_));
else
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item_), sub_menu->menu_);
}
void MenuItem::OnClick(GtkWidget* widget) {
if (block_active_)
return;
base::ListValue args;
dispatcher_host()->SendEvent(this, "click", args);
}
} // namespace api
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/platform_thread.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "base/test/multiprocess_test.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
static const int kNumThreads = 5;
static const int kNumTasks = 5;
namespace base {
namespace {
// Each thread will open the shared memory. Each thread will take a different 4
// byte int pointer, and keep changing it, with some small pauses in between.
// Verify that each thread's value in the shared memory is always correct.
class MultipleThreadMain : public PlatformThread::Delegate {
public:
explicit MultipleThreadMain(int16 id) : id_(id) {}
~MultipleThreadMain() {}
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
// PlatformThread::Delegate interface.
void ThreadMain() {
mac::ScopedNSAutoreleasePool pool; // noop if not OSX
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memory.memory()) + id_;
EXPECT_EQ(*ptr, 0);
for (int idx = 0; idx < 100; idx++) {
*ptr = idx;
PlatformThread::Sleep(1); // Short wait.
EXPECT_EQ(*ptr, idx);
}
memory.Close();
}
private:
int16 id_;
static const char* const s_test_name_;
DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain);
};
const char* const MultipleThreadMain::s_test_name_ =
"SharedMemoryOpenThreadTest";
// TODO(port):
// This test requires the ability to pass file descriptors between processes.
// We haven't done that yet in Chrome for POSIX.
#if defined(OS_WIN)
// Each thread will open the shared memory. Each thread will take the memory,
// and keep changing it while trying to lock it, with some small pauses in
// between. Verify that each thread's value in the shared memory is always
// correct.
class MultipleLockThread : public PlatformThread::Delegate {
public:
explicit MultipleLockThread(int id) : id_(id) {}
~MultipleLockThread() {}
// PlatformThread::Delegate interface.
void ThreadMain() {
const uint32 kDataSize = sizeof(int);
SharedMemoryHandle handle = NULL;
{
SharedMemory memory1;
EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest",
true, kDataSize));
EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle));
// TODO(paulg): Implement this once we have a posix version of
// SharedMemory::ShareToProcess.
EXPECT_TRUE(true);
}
SharedMemory memory2(handle, false);
EXPECT_TRUE(memory2.Map(kDataSize));
volatile int* const ptr = static_cast<int*>(memory2.memory());
for (int idx = 0; idx < 20; idx++) {
memory2.Lock();
int i = (id_ << 16) + idx;
*ptr = i;
PlatformThread::Sleep(1); // Short wait.
EXPECT_EQ(*ptr, i);
memory2.Unlock();
}
memory2.Close();
}
private:
int id_;
DISALLOW_COPY_AND_ASSIGN(MultipleLockThread);
};
#endif
} // namespace
TEST(SharedMemoryTest, OpenClose) {
const uint32 kDataSize = 1024;
std::string test_name = "SharedMemoryOpenCloseTest";
// Open two handles to a memory segment, confirm that they are mapped
// separately yet point to the same space.
SharedMemory memory1;
bool rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Open(test_name, false);
EXPECT_FALSE(rv);
rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
SharedMemory memory2;
rv = memory2.Open(test_name, false);
EXPECT_TRUE(rv);
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers.
// Make sure we don't segfault. (it actually happened!)
ASSERT_NE(memory1.memory(), static_cast<void*>(NULL));
ASSERT_NE(memory2.memory(), static_cast<void*>(NULL));
// Write data to the first memory segment, verify contents of second.
memset(memory1.memory(), '1', kDataSize);
EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0);
// Close the first memory segment, and verify the second has the right data.
memory1.Close();
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++)
EXPECT_EQ(*ptr, '1');
// Close the second memory segment.
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory2.Delete(test_name);
EXPECT_TRUE(rv);
}
TEST(SharedMemoryTest, OpenExclusive) {
const uint32 kDataSize = 1024;
const uint32 kDataSize2 = 2048;
std::ostringstream test_name_stream;
test_name_stream << "SharedMemoryOpenExclusiveTest."
<< Time::Now().ToDoubleT();
std::string test_name = test_name_stream.str();
// Open two handles to a memory segment and check that open_existing works
// as expected.
SharedMemory memory1;
bool rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
// Memory1 knows it's size because it created it.
EXPECT_EQ(memory1.created_size(), kDataSize);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
memset(memory1.memory(), 'G', kDataSize);
SharedMemory memory2;
// Should not be able to create if openExisting is false.
rv = memory2.CreateNamed(test_name, false, kDataSize2);
EXPECT_FALSE(rv);
// Should be able to create with openExisting true.
rv = memory2.CreateNamed(test_name, true, kDataSize2);
EXPECT_TRUE(rv);
// Memory2 shouldn't know the size because we didn't create it.
EXPECT_EQ(memory2.created_size(), 0U);
// We should be able to map the original size.
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
// Verify that opening memory2 didn't truncate or delete memory 1.
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++) {
EXPECT_EQ(*ptr, 'G');
}
memory1.Close();
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
}
// Create a set of N threads to each open a shared memory segment and write to
// it. Verify that they are always reading/writing consistent data.
TEST(SharedMemoryTest, MultipleThreads) {
MultipleThreadMain::CleanUp();
// On POSIX we have a problem when 2 threads try to create the shmem
// (a file) at exactly the same time, since create both creates the
// file and zerofills it. We solve the problem for this unit test
// (make it not flaky) by starting with 1 thread, then
// intentionally don't clean up its shmem before running with
// kNumThreads.
int threadcounts[] = { 1, kNumThreads };
for (size_t i = 0; i < sizeof(threadcounts) / sizeof(threadcounts); i++) {
int numthreads = threadcounts[i];
scoped_array<PlatformThreadHandle> thread_handles;
scoped_array<MultipleThreadMain*> thread_delegates;
thread_handles.reset(new PlatformThreadHandle[numthreads]);
thread_delegates.reset(new MultipleThreadMain*[numthreads]);
// Spawn the threads.
for (int16 index = 0; index < numthreads; index++) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleThreadMain(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < numthreads; index++) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
MultipleThreadMain::CleanUp();
}
// TODO(port): this test requires the MultipleLockThread class
// (defined above), which requires the ability to pass file
// descriptors between processes. We haven't done that yet in Chrome
// for POSIX.
#if defined(OS_WIN)
// Create a set of threads to each open a shared memory segment and write to it
// with the lock held. Verify that they are always reading/writing consistent
// data.
TEST(SharedMemoryTest, Lock) {
PlatformThreadHandle thread_handles[kNumThreads];
MultipleLockThread* thread_delegates[kNumThreads];
// Spawn the threads.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleLockThread(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
#endif
// Allocate private (unique) shared memory with an empty string for a
// name. Make sure several of them don't point to the same thing as
// we might expect if the names are equal.
TEST(SharedMemoryTest, AnonymousPrivate) {
int i, j;
int count = 4;
bool rv;
const uint32 kDataSize = 8192;
scoped_array<SharedMemory> memories(new SharedMemory[count]);
scoped_array<int*> pointers(new int*[count]);
ASSERT_TRUE(memories.get());
ASSERT_TRUE(pointers.get());
for (i = 0; i < count; i++) {
rv = memories[i].CreateAndMapAnonymous(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memories[i].memory());
EXPECT_TRUE(ptr);
pointers[i] = ptr;
}
for (i = 0; i < count; i++) {
// zero out the first int in each except for i; for that one, make it 100.
for (j = 0; j < count; j++) {
if (i == j)
pointers[j][0] = 100;
else
pointers[j][0] = 0;
}
// make sure there is no bleeding of the 100 into the other pointers
for (j = 0; j < count; j++) {
if (i == j)
EXPECT_EQ(100, pointers[j][0]);
else
EXPECT_EQ(0, pointers[j][0]);
}
}
for (int i = 0; i < count; i++) {
memories[i].Close();
}
}
// On POSIX it is especially important we test shmem across processes,
// not just across threads. But the test is enabled on all platforms.
class SharedMemoryProcessTest : public base::MultiProcessTest {
public:
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
static int TaskTestMain() {
int errors = 0;
mac::ScopedNSAutoreleasePool pool; // noop if not OSX
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
int *ptr = static_cast<int*>(memory.memory());
for (int idx = 0; idx < 20; idx++) {
memory.Lock();
int i = (1 << 16) + idx;
*ptr = i;
PlatformThread::Sleep(10); // Short wait.
if (*ptr != i)
errors++;
memory.Unlock();
}
memory.Close();
return errors;
}
private:
static const char* const s_test_name_;
};
const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem";
TEST_F(SharedMemoryProcessTest, Tasks) {
SharedMemoryProcessTest::CleanUp();
base::ProcessHandle handles[kNumTasks];
for (int index = 0; index < kNumTasks; ++index) {
handles[index] = SpawnChild("SharedMemoryTestMain", false);
}
int exit_code = 0;
for (int index = 0; index < kNumTasks; ++index) {
EXPECT_TRUE(base::WaitForExitCode(handles[index], &exit_code));
EXPECT_TRUE(exit_code == 0);
}
SharedMemoryProcessTest::CleanUp();
}
MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) {
return SharedMemoryProcessTest::TaskTestMain();
}
} // namespace base
<commit_msg>Mark SharedMemoryProcessTest.Tasks as flaky on Mac.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/platform_thread.h"
#include "base/shared_memory.h"
#include "base/scoped_ptr.h"
#include "base/test/multiprocess_test.h"
#include "base/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
static const int kNumThreads = 5;
static const int kNumTasks = 5;
namespace base {
namespace {
// Each thread will open the shared memory. Each thread will take a different 4
// byte int pointer, and keep changing it, with some small pauses in between.
// Verify that each thread's value in the shared memory is always correct.
class MultipleThreadMain : public PlatformThread::Delegate {
public:
explicit MultipleThreadMain(int16 id) : id_(id) {}
~MultipleThreadMain() {}
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
// PlatformThread::Delegate interface.
void ThreadMain() {
mac::ScopedNSAutoreleasePool pool; // noop if not OSX
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memory.memory()) + id_;
EXPECT_EQ(*ptr, 0);
for (int idx = 0; idx < 100; idx++) {
*ptr = idx;
PlatformThread::Sleep(1); // Short wait.
EXPECT_EQ(*ptr, idx);
}
memory.Close();
}
private:
int16 id_;
static const char* const s_test_name_;
DISALLOW_COPY_AND_ASSIGN(MultipleThreadMain);
};
const char* const MultipleThreadMain::s_test_name_ =
"SharedMemoryOpenThreadTest";
// TODO(port):
// This test requires the ability to pass file descriptors between processes.
// We haven't done that yet in Chrome for POSIX.
#if defined(OS_WIN)
// Each thread will open the shared memory. Each thread will take the memory,
// and keep changing it while trying to lock it, with some small pauses in
// between. Verify that each thread's value in the shared memory is always
// correct.
class MultipleLockThread : public PlatformThread::Delegate {
public:
explicit MultipleLockThread(int id) : id_(id) {}
~MultipleLockThread() {}
// PlatformThread::Delegate interface.
void ThreadMain() {
const uint32 kDataSize = sizeof(int);
SharedMemoryHandle handle = NULL;
{
SharedMemory memory1;
EXPECT_TRUE(memory1.CreateNamed("SharedMemoryMultipleLockThreadTest",
true, kDataSize));
EXPECT_TRUE(memory1.ShareToProcess(GetCurrentProcess(), &handle));
// TODO(paulg): Implement this once we have a posix version of
// SharedMemory::ShareToProcess.
EXPECT_TRUE(true);
}
SharedMemory memory2(handle, false);
EXPECT_TRUE(memory2.Map(kDataSize));
volatile int* const ptr = static_cast<int*>(memory2.memory());
for (int idx = 0; idx < 20; idx++) {
memory2.Lock();
int i = (id_ << 16) + idx;
*ptr = i;
PlatformThread::Sleep(1); // Short wait.
EXPECT_EQ(*ptr, i);
memory2.Unlock();
}
memory2.Close();
}
private:
int id_;
DISALLOW_COPY_AND_ASSIGN(MultipleLockThread);
};
#endif
} // namespace
TEST(SharedMemoryTest, OpenClose) {
const uint32 kDataSize = 1024;
std::string test_name = "SharedMemoryOpenCloseTest";
// Open two handles to a memory segment, confirm that they are mapped
// separately yet point to the same space.
SharedMemory memory1;
bool rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory1.Open(test_name, false);
EXPECT_FALSE(rv);
rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
SharedMemory memory2;
rv = memory2.Open(test_name, false);
EXPECT_TRUE(rv);
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
EXPECT_NE(memory1.memory(), memory2.memory()); // Compare the pointers.
// Make sure we don't segfault. (it actually happened!)
ASSERT_NE(memory1.memory(), static_cast<void*>(NULL));
ASSERT_NE(memory2.memory(), static_cast<void*>(NULL));
// Write data to the first memory segment, verify contents of second.
memset(memory1.memory(), '1', kDataSize);
EXPECT_EQ(memcmp(memory1.memory(), memory2.memory(), kDataSize), 0);
// Close the first memory segment, and verify the second has the right data.
memory1.Close();
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++)
EXPECT_EQ(*ptr, '1');
// Close the second memory segment.
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
rv = memory2.Delete(test_name);
EXPECT_TRUE(rv);
}
TEST(SharedMemoryTest, OpenExclusive) {
const uint32 kDataSize = 1024;
const uint32 kDataSize2 = 2048;
std::ostringstream test_name_stream;
test_name_stream << "SharedMemoryOpenExclusiveTest."
<< Time::Now().ToDoubleT();
std::string test_name = test_name_stream.str();
// Open two handles to a memory segment and check that open_existing works
// as expected.
SharedMemory memory1;
bool rv = memory1.CreateNamed(test_name, false, kDataSize);
EXPECT_TRUE(rv);
// Memory1 knows it's size because it created it.
EXPECT_EQ(memory1.created_size(), kDataSize);
rv = memory1.Map(kDataSize);
EXPECT_TRUE(rv);
memset(memory1.memory(), 'G', kDataSize);
SharedMemory memory2;
// Should not be able to create if openExisting is false.
rv = memory2.CreateNamed(test_name, false, kDataSize2);
EXPECT_FALSE(rv);
// Should be able to create with openExisting true.
rv = memory2.CreateNamed(test_name, true, kDataSize2);
EXPECT_TRUE(rv);
// Memory2 shouldn't know the size because we didn't create it.
EXPECT_EQ(memory2.created_size(), 0U);
// We should be able to map the original size.
rv = memory2.Map(kDataSize);
EXPECT_TRUE(rv);
// Verify that opening memory2 didn't truncate or delete memory 1.
char *start_ptr = static_cast<char *>(memory2.memory());
char *end_ptr = start_ptr + kDataSize;
for (char* ptr = start_ptr; ptr < end_ptr; ptr++) {
EXPECT_EQ(*ptr, 'G');
}
memory1.Close();
memory2.Close();
rv = memory1.Delete(test_name);
EXPECT_TRUE(rv);
}
// Create a set of N threads to each open a shared memory segment and write to
// it. Verify that they are always reading/writing consistent data.
TEST(SharedMemoryTest, MultipleThreads) {
MultipleThreadMain::CleanUp();
// On POSIX we have a problem when 2 threads try to create the shmem
// (a file) at exactly the same time, since create both creates the
// file and zerofills it. We solve the problem for this unit test
// (make it not flaky) by starting with 1 thread, then
// intentionally don't clean up its shmem before running with
// kNumThreads.
int threadcounts[] = { 1, kNumThreads };
for (size_t i = 0; i < sizeof(threadcounts) / sizeof(threadcounts); i++) {
int numthreads = threadcounts[i];
scoped_array<PlatformThreadHandle> thread_handles;
scoped_array<MultipleThreadMain*> thread_delegates;
thread_handles.reset(new PlatformThreadHandle[numthreads]);
thread_delegates.reset(new MultipleThreadMain*[numthreads]);
// Spawn the threads.
for (int16 index = 0; index < numthreads; index++) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleThreadMain(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < numthreads; index++) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
MultipleThreadMain::CleanUp();
}
// TODO(port): this test requires the MultipleLockThread class
// (defined above), which requires the ability to pass file
// descriptors between processes. We haven't done that yet in Chrome
// for POSIX.
#if defined(OS_WIN)
// Create a set of threads to each open a shared memory segment and write to it
// with the lock held. Verify that they are always reading/writing consistent
// data.
TEST(SharedMemoryTest, Lock) {
PlatformThreadHandle thread_handles[kNumThreads];
MultipleLockThread* thread_delegates[kNumThreads];
// Spawn the threads.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThreadHandle pth;
thread_delegates[index] = new MultipleLockThread(index);
EXPECT_TRUE(PlatformThread::Create(0, thread_delegates[index], &pth));
thread_handles[index] = pth;
}
// Wait for the threads to finish.
for (int index = 0; index < kNumThreads; ++index) {
PlatformThread::Join(thread_handles[index]);
delete thread_delegates[index];
}
}
#endif
// Allocate private (unique) shared memory with an empty string for a
// name. Make sure several of them don't point to the same thing as
// we might expect if the names are equal.
TEST(SharedMemoryTest, AnonymousPrivate) {
int i, j;
int count = 4;
bool rv;
const uint32 kDataSize = 8192;
scoped_array<SharedMemory> memories(new SharedMemory[count]);
scoped_array<int*> pointers(new int*[count]);
ASSERT_TRUE(memories.get());
ASSERT_TRUE(pointers.get());
for (i = 0; i < count; i++) {
rv = memories[i].CreateAndMapAnonymous(kDataSize);
EXPECT_TRUE(rv);
int *ptr = static_cast<int*>(memories[i].memory());
EXPECT_TRUE(ptr);
pointers[i] = ptr;
}
for (i = 0; i < count; i++) {
// zero out the first int in each except for i; for that one, make it 100.
for (j = 0; j < count; j++) {
if (i == j)
pointers[j][0] = 100;
else
pointers[j][0] = 0;
}
// make sure there is no bleeding of the 100 into the other pointers
for (j = 0; j < count; j++) {
if (i == j)
EXPECT_EQ(100, pointers[j][0]);
else
EXPECT_EQ(0, pointers[j][0]);
}
}
for (int i = 0; i < count; i++) {
memories[i].Close();
}
}
// On POSIX it is especially important we test shmem across processes,
// not just across threads. But the test is enabled on all platforms.
class SharedMemoryProcessTest : public base::MultiProcessTest {
public:
static void CleanUp() {
SharedMemory memory;
memory.Delete(s_test_name_);
}
static int TaskTestMain() {
int errors = 0;
mac::ScopedNSAutoreleasePool pool; // noop if not OSX
const uint32 kDataSize = 1024;
SharedMemory memory;
bool rv = memory.CreateNamed(s_test_name_, true, kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
rv = memory.Map(kDataSize);
EXPECT_TRUE(rv);
if (rv != true)
errors++;
int *ptr = static_cast<int*>(memory.memory());
for (int idx = 0; idx < 20; idx++) {
memory.Lock();
int i = (1 << 16) + idx;
*ptr = i;
PlatformThread::Sleep(10); // Short wait.
if (*ptr != i)
errors++;
memory.Unlock();
}
memory.Close();
return errors;
}
private:
static const char* const s_test_name_;
};
const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem";
#if defined(OS_MACOSX)
#define MAYBE_Tasks FLAKY_Tasks
#else
#define MAYBE_Tasks Tasks
#endif
TEST_F(SharedMemoryProcessTest, MAYBE_Tasks) {
SharedMemoryProcessTest::CleanUp();
base::ProcessHandle handles[kNumTasks];
for (int index = 0; index < kNumTasks; ++index) {
handles[index] = SpawnChild("SharedMemoryTestMain", false);
}
int exit_code = 0;
for (int index = 0; index < kNumTasks; ++index) {
EXPECT_TRUE(base::WaitForExitCode(handles[index], &exit_code));
EXPECT_TRUE(exit_code == 0);
}
SharedMemoryProcessTest::CleanUp();
}
MULTIPROCESS_TEST_MAIN(SharedMemoryTestMain) {
return SharedMemoryProcessTest::TaskTestMain();
}
} // namespace base
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QPainter>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if(sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if(fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax, QString("%1 %2").arg(val).arg(units));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
foreach(float f, vSamplesIn) {
if(f > tmax) tmax = f;
}
foreach(float f, vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<commit_msg>Qt: Network-Traffic-Graph: make some distance between line and text<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QPainter>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int sampleCount = samples.size(), x = XMARGIN + w, y;
if(sampleCount > 0) {
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if(fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
const float yMarginText = 2.0;
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
foreach(float f, vSamplesIn) {
if(f > tmax) tmax = f;
}
foreach(float f, vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
<|endoftext|> |
<commit_before>// compare speed of attribute access, using various implementations
#define NUM_ATTRIBUTES 30
#define NUM_TRIALS (3000000 / NUM_ATTRIBUTES)
#include <map>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/python.hpp>
#if BOOST_VERSION >= 13600
#include <boost/unordered/unordered_map.hpp>
#endif
//! Create random string.
std::string random_string(int len) {
std::string ret;
for (int i=0; i < len; ++i) {
int num;
num = rand()%122;
if (48 > num)
num += 48;
if ((57 < num) && (65 > num))
num += 7;
if ((90 < num) && (97 > num))
num += 6;
ret += (char)num;
}
return ret;
}
void impl_map(const std::vector<std::string> & names) {
std::map<std::string, int> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#if BOOST_VERSION >= 13600
void impl_hash_map(const std::vector<std::string> & names) {
boost::unordered_map<std::string, int> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#endif
void impl_python_dict(const std::vector<std::string> & names) {
boost::python::dict dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
class Test {};
void impl_python_class(const std::vector<std::string> & names) {
boost::python::object dict1 = boost::python::class_<Test>("Test");
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1.attr(name.c_str()) = i;
};
};
};
int main(void) {
Py_Initialize();
clock_t t;
std::vector<std::string> names;
for (int j=0; j < NUM_ATTRIBUTES; j++) {
std::string name = random_string(10);
//std::cout << name << std::endl;
names.push_back(name);
};
t = clock();
impl_map(names);
std::cout << "map: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds"<< std::endl;
#if BOOST_VERSION >= 13600
t = clock();
impl_hash_map(names);
std::cout << "hash map: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
#endif
t = clock();
impl_python_dict(names);
std::cout << "python dict: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
t = clock();
impl_python_class(names);
std::cout << "python class: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
};
<commit_msg>cpp: more map hash algorithm tests<commit_after>// compare speed of attribute access, using various implementations
#define NUM_ATTRIBUTES 30
#define NUM_TRIALS (3000000 / NUM_ATTRIBUTES)
#include <map>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/python.hpp>
#include <boost/version.hpp>
#if (BOOST_VERSION >= 103600)
#include <boost/unordered/unordered_map.hpp>
#endif
//! Create random string.
std::string random_string(int len) {
std::string ret;
for (int i=0; i < len; ++i) {
int num;
num = rand()%122;
if (48 > num)
num += 48;
if ((57 < num) && (65 > num))
num += 7;
if ((90 < num) && (97 > num))
num += 6;
ret += (char)num;
}
return ret;
}
void impl_map(const std::vector<std::string> & names) {
std::map<std::string, int> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#if (BOOST_VERSION >= 103600)
void impl_hash_map(const std::vector<std::string> & names) {
boost::unordered_map<std::string, int> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#endif
#if (BOOST_VERSION >= 103600)
struct name_hash2 : std::unary_function<std::string, std::size_t> {
std::size_t operator()(std::string const & name) const {
std::size_t seed = 0;
try {
boost::hash_combine(seed, name.at(0));
boost::hash_combine(seed, name.at(2));
boost::hash_combine(seed, name.at(8));
//boost::hash_combine(seed, name.at(32));
//boost::hash_combine(seed, name.at(64));
} catch (const std::out_of_range &) {
// pass the exception
};
return seed;
}
};
void impl_hash_map2(const std::vector<std::string> & names) {
boost::unordered_map<std::string, int, name_hash2> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#endif
#if (BOOST_VERSION >= 103600)
struct name_hash3 : std::unary_function<std::string, std::size_t> {
std::size_t operator()(std::string const & name) const {
std::size_t seed = 0;
try {
seed ^= name.at(0);
seed ^= name.at(2);
seed ^= name.at(8);
} catch (const std::out_of_range &) {
// pass the exception
};
return seed;
}
};
void impl_hash_map3(const std::vector<std::string> & names) {
boost::unordered_map<std::string, int, name_hash2> dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
#endif
void impl_python_dict(const std::vector<std::string> & names) {
boost::python::dict dict1;
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1[name] = i;
};
};
};
class Test {};
void impl_python_class(const std::vector<std::string> & names) {
boost::python::object dict1 = boost::python::class_<Test>("Test");
for (int i=0; i < NUM_TRIALS; i++) {
BOOST_FOREACH(const std::string & name, names) {
dict1.attr(name.c_str()) = i;
};
};
};
int main(void) {
Py_Initialize();
clock_t t;
std::vector<std::string> names;
for (int j=0; j < NUM_ATTRIBUTES; j++) {
std::string name = random_string(10);
//std::cout << name << std::endl;
names.push_back(name);
};
t = clock();
impl_map(names);
std::cout << "map: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds"<< std::endl;
#if (BOOST_VERSION >= 103600)
t = clock();
impl_hash_map(names);
std::cout << "hash map: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
t = clock();
impl_hash_map2(names);
std::cout << "hash map 2: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
t = clock();
impl_hash_map3(names);
std::cout << "hash map 3: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
#endif
t = clock();
impl_python_dict(names);
std::cout << "python dict: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
t = clock();
impl_python_class(names);
std::cout << "python class: " << float(clock() - t) / CLOCKS_PER_SEC << " seconds" << std::endl;
};
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project 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 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.
*/
#include <stdlib.h>
#ifdef WIN32
#include <conio.h>
#include <winsock2.h>
#include <process.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/times.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>
#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "worldgen/mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"
#include "furnaceManager.h"
#ifdef WIN32
static bool quit = false;
#endif
int setnonblock(int fd)
{
#ifdef WIN32
u_long iMode = 1;
ioctlsocket(fd, FIONBIO, &iMode);
#else
int flags;
flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
#endif
return 1;
}
//Handle signals
void sighandler(int sig_num)
{
Mineserver::get().stop();
}
int main(int argc, char *argv[])
{
signal(SIGTERM, sighandler);
signal(SIGINT, sighandler);
srand(time(NULL));
return Mineserver::get().run(argc, argv);
}
Mineserver::Mineserver()
{
}
event_base *Mineserver::getEventBase()
{
return m_eventBase;
}
int Mineserver::run(int argc, char *argv[])
{
uint32 starttime = (uint32)time(0);
uint32 tick = (uint32)time(0);
initConstants();
std::string file_config;
file_config.assign(CONFIG_FILE);
std::string file_commands;
file_commands.assign(COMMANDS_FILE);
if (argc > 1)
file_config.assign(argv[1]);
// Initialize conf
Conf::get()->load(file_config);
Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX);
// Write PID to file
std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str());
if (!pid_out.fail())
#ifdef WIN32
pid_out << _getpid();
#else
pid_out << getpid();
#endif
pid_out.close();
// Load admin, banned and whitelisted users
Conf::get()->loadRoles();
Conf::get()->loadBanned();
Conf::get()->loadWhitelist();
// Load MOTD
Chat::get()->checkMotd(Conf::get()->sValue("motd_file"));
// Set physics enable state according to config
Physics::get()->enabled = (Conf::get()->bValue("liquid_physics"));
// Initialize map
Map::get()->init();
if (Conf::get()->bValue("map_generate_spawn"))
{
std::cout << "Generating spawn area...\n";
int size=Conf::get()->iValue("map_generate_spawn_size");
bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress");
#ifdef WIN32
DWORD t_begin,t_end;
#else
clock_t t_begin,t_end;
#endif
for (int x=-size;x<=size;x++)
{
#ifdef WIN32
if(show_progress)
t_begin = timeGetTime();
#else
if(show_progress)
t_begin = clock();
#endif
for (int z=-size;z<=size;z++)
{
Map::get()->loadMap(x, z);
}
if(show_progress)
{
#ifdef WIN32
t_end = timeGetTime ();
std::cout << ((x+size+1)*(size*2+1)) << "/" << (size*2+1)*(size*2+1) << " done. " << (t_end-t_begin)/(size*2+1) << "ms per chunk" << std::endl;
#else
t_end = clock();
std::cout << ((x+size+1)*(size*2+1)) << "/" << (size*2+1)*(size*2+1) << " done. " << ((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1) << "ms per chunk" << std::endl;
#endif
}
}
#ifdef _DEBUG
std::cout << "Spawn area ready!\n";
#endif
}
// Initialize packethandler
PacketHandler::get()->init();
// Load ip from config
std::string ip = Conf::get()->sValue("ip");
// Load port from config
int port = Conf::get()->iValue("port");
// Initialize plugins
Plugin::get()->init();
#ifdef WIN32
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return EXIT_FAILURE;
}
#endif
struct sockaddr_in addresslisten;
int reuse = 1;
m_eventBase = (event_base *)event_init();
#ifdef WIN32
m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif
if(m_socketlisten < 0)
{
std::cerr << "Failed to create listen socket" << std::endl;
return 1;
}
memset(&addresslisten, 0, sizeof(addresslisten));
addresslisten.sin_family = AF_INET;
addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
addresslisten.sin_port = htons(port);
setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
//Bind to port
if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
{
std::cerr << "Failed to bind" << std::endl;
return 1;
}
if(listen(m_socketlisten, 5) < 0)
{
std::cerr << "Failed to listen to socket" << std::endl;
return 1;
}
setnonblock(m_socketlisten);
event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
event_add(&m_listenEvent, NULL);
std::cout <<
" _____ .__ "<<
std::endl<<
" / \\ |__| ____ ____ ______ ______________ __ ___________ "<<
std::endl<<
" / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<<
std::endl<<
"/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<<
std::endl<<
"\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<<
std::endl<<
" \\/ \\/ \\/ \\/ \\/ \\/ "<<
std::endl<<
"Version " << VERSION <<" by The Mineserver Project"<<
std::endl << std::endl;
if(ip == "0.0.0.0")
{
// Print all local IPs
char name[255];
gethostname ( name, sizeof(name));
struct hostent *hostinfo = gethostbyname(name);
std::cout << "Listening on: ";
int ipIndex = 0;
while(hostinfo->h_addr_list[ipIndex]) {
if(ipIndex > 0) { std::cout << ", "; }
char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]);
std::cout << ip << ":" << port;
}
std::cout << std::endl;
}
else
{
std::cout << "Listening on " << ip << ":" << port << std::endl;
}
std::cout << std::endl;
timeval loopTime;
loopTime.tv_sec = 0;
loopTime.tv_usec = 200000; //200ms
m_running=true;
event_base_loopexit(m_eventBase, &loopTime);
User *serverUser = new User(-1, -1);
serverUser->changeNick("[Server]");
while(m_running && event_base_loop(m_eventBase, 0) == 0)
{
// Check for key input from server console (get's triggered when console hits return)
if (kbhit() != 0)
{
// Loop thru all chars up until CRLF
std::string consoleCommand;
char c;
do
{
c = fgetc (stdin);
consoleCommand.push_back(c);
} while (c != '\n');
// Now handle this command as normal
if (consoleCommand[0] == '/' || consoleCommand[0] == '&' || consoleCommand[0] == '%')
{
Chat::get()->handleMsg(serverUser, consoleCommand);
std::cout << "Command sent" << std::endl;
}
}
if(time(0)-starttime > 10)
{
starttime = (uint32)time(0);
//std::cout << "Currently " << User::all().size() << " users in!" << std::endl;
//If users, ping them
if(User::all().size() > 0)
{
//0x00 package
uint8 data = 0;
User::all()[0]->sendAll(&data, 1);
//Send server time
Packet pkt;
pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime;
User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
}
//Try to load release time from config
int map_release_time = Conf::get()->iValue("map_release_time");
//Release chunks not used in <map_release_time> seconds
/* std::vector<uint32> toRelease;
for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin();
it != Map::get()->mapLastused.end();
++it)
{
if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time)
toRelease.push_back(it->first);
}
int x_temp, z_temp;
for(unsigned i = 0; i < toRelease.size(); i++)
{
Map::get()->idToPos(toRelease[i], &x_temp, &z_temp);
Map::get()->releaseMap(x_temp, z_temp);
} */
}
//Every second
if(time(0)-tick > 0)
{
tick = (uint32)time(0);
//Loop users
for(unsigned int i = 0; i < User::all().size(); i++)
{
User::all()[i]->pushMap();
User::all()[i]->popMap();
//Minecart hacks!!
if(User::all()[i]->attachedTo)
{
Packet pkt;
pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0;
//pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0;
User::all()[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen());
}
}
Map::get()->mapTime+=20;
if(Map::get()->mapTime>=24000) Map::get()->mapTime=0;
Map::get()->checkGenTrees();
// Check for Furnace activity
FurnaceManager::get()->update();
}
//Physics simulation every 200ms
Physics::get()->update();
//Underwater check / drowning
for( unsigned int i = 0; i < User::all().size(); i++ )
User::all()[i]->isUnderwater();
// event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
// event_add(&m_listenEvent, NULL);
event_base_loopexit(m_eventBase, &loopTime);
}
#ifdef WIN32
closesocket(m_socketlisten);
#else
close(m_socketlisten);
#endif
// Remove the PID file
#ifdef WIN32
_unlink((Conf::get()->sValue("pid_file")).c_str());
#else
unlink((Conf::get()->sValue("pid_file")).c_str());
#endif
/* Free memory */
PacketHandler::get()->free();
Map::get()->free();
Physics::get()->free();
FurnaceManager::get()->free();
Chat::get()->free();
Conf::get()->free();
Plugin::get()->free();
Logger::get()->free();
MapGen::get()->free();
return EXIT_SUCCESS;
}
bool Mineserver::stop()
{
m_running=false;
return true;
}
<commit_msg>Fixed seg fault with hostname resolving<commit_after>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project 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 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.
*/
#include <stdlib.h>
#ifdef WIN32
#include <conio.h>
#include <winsock2.h>
#include <process.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/times.h>
#endif
#include <sys/types.h>
#include <fcntl.h>
#include <cassert>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
#include <event.h>
#include <ctime>
#include <vector>
#include <zlib.h>
#include <signal.h>
#include "constants.h"
#include "mineserver.h"
#include "logger.h"
#include "sockets.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "worldgen/mapgen.h"
#include "config.h"
#include "nbt.h"
#include "packets.h"
#include "physics.h"
#include "plugin.h"
#include "furnaceManager.h"
#ifdef WIN32
static bool quit = false;
#endif
int setnonblock(int fd)
{
#ifdef WIN32
u_long iMode = 1;
ioctlsocket(fd, FIONBIO, &iMode);
#else
int flags;
flags = fcntl(fd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
#endif
return 1;
}
//Handle signals
void sighandler(int sig_num)
{
Mineserver::get().stop();
}
int main(int argc, char *argv[])
{
signal(SIGTERM, sighandler);
signal(SIGINT, sighandler);
srand(time(NULL));
return Mineserver::get().run(argc, argv);
}
Mineserver::Mineserver()
{
}
event_base *Mineserver::getEventBase()
{
return m_eventBase;
}
int Mineserver::run(int argc, char *argv[])
{
uint32 starttime = (uint32)time(0);
uint32 tick = (uint32)time(0);
initConstants();
std::string file_config;
file_config.assign(CONFIG_FILE);
std::string file_commands;
file_commands.assign(COMMANDS_FILE);
if (argc > 1)
file_config.assign(argv[1]);
// Initialize conf
Conf::get()->load(file_config);
Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX);
// Write PID to file
std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str());
if (!pid_out.fail())
#ifdef WIN32
pid_out << _getpid();
#else
pid_out << getpid();
#endif
pid_out.close();
// Load admin, banned and whitelisted users
Conf::get()->loadRoles();
Conf::get()->loadBanned();
Conf::get()->loadWhitelist();
// Load MOTD
Chat::get()->checkMotd(Conf::get()->sValue("motd_file"));
// Set physics enable state according to config
Physics::get()->enabled = (Conf::get()->bValue("liquid_physics"));
// Initialize map
Map::get()->init();
if (Conf::get()->bValue("map_generate_spawn"))
{
std::cout << "Generating spawn area...\n";
int size=Conf::get()->iValue("map_generate_spawn_size");
bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress");
#ifdef WIN32
DWORD t_begin,t_end;
#else
clock_t t_begin,t_end;
#endif
for (int x=-size;x<=size;x++)
{
#ifdef WIN32
if(show_progress)
t_begin = timeGetTime();
#else
if(show_progress)
t_begin = clock();
#endif
for (int z=-size;z<=size;z++)
{
Map::get()->loadMap(x, z);
}
if(show_progress)
{
#ifdef WIN32
t_end = timeGetTime ();
std::cout << ((x+size+1)*(size*2+1)) << "/" << (size*2+1)*(size*2+1) << " done. " << (t_end-t_begin)/(size*2+1) << "ms per chunk" << std::endl;
#else
t_end = clock();
std::cout << ((x+size+1)*(size*2+1)) << "/" << (size*2+1)*(size*2+1) << " done. " << ((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1) << "ms per chunk" << std::endl;
#endif
}
}
#ifdef _DEBUG
std::cout << "Spawn area ready!\n";
#endif
}
// Initialize packethandler
PacketHandler::get()->init();
// Load ip from config
std::string ip = Conf::get()->sValue("ip");
// Load port from config
int port = Conf::get()->iValue("port");
// Initialize plugins
Plugin::get()->init();
#ifdef WIN32
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return EXIT_FAILURE;
}
#endif
struct sockaddr_in addresslisten;
int reuse = 1;
m_eventBase = (event_base *)event_init();
#ifdef WIN32
m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif
if(m_socketlisten < 0)
{
std::cerr << "Failed to create listen socket" << std::endl;
return 1;
}
memset(&addresslisten, 0, sizeof(addresslisten));
addresslisten.sin_family = AF_INET;
addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
addresslisten.sin_port = htons(port);
setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
//Bind to port
if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
{
std::cerr << "Failed to bind" << std::endl;
return 1;
}
if(listen(m_socketlisten, 5) < 0)
{
std::cerr << "Failed to listen to socket" << std::endl;
return 1;
}
setnonblock(m_socketlisten);
event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
event_add(&m_listenEvent, NULL);
std::cout <<
" _____ .__ "<<
std::endl<<
" / \\ |__| ____ ____ ______ ______________ __ ___________ "<<
std::endl<<
" / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<<
std::endl<<
"/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<<
std::endl<<
"\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<<
std::endl<<
" \\/ \\/ \\/ \\/ \\/ \\/ "<<
std::endl<<
"Version " << VERSION <<" by The Mineserver Project"<<
std::endl << std::endl;
if(ip == "0.0.0.0")
{
// Print all local IPs
char name[255];
gethostname ( name, sizeof(name));
struct hostent *hostinfo = gethostbyname(name);
std::cout << "Listening on: ";
int ipIndex = 0;
while(hostinfo && hostinfo->h_addr_list[ipIndex]) {
if(ipIndex > 0) { std::cout << ", "; }
char *ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[ipIndex++]);
std::cout << ip << ":" << port;
}
std::cout << std::endl;
}
else
{
std::cout << "Listening on " << ip << ":" << port << std::endl;
}
std::cout << std::endl;
timeval loopTime;
loopTime.tv_sec = 0;
loopTime.tv_usec = 200000; //200ms
m_running=true;
event_base_loopexit(m_eventBase, &loopTime);
User *serverUser = new User(-1, -1);
serverUser->changeNick("[Server]");
while(m_running && event_base_loop(m_eventBase, 0) == 0)
{
// Check for key input from server console (get's triggered when console hits return)
if (kbhit() != 0)
{
// Loop thru all chars up until CRLF
std::string consoleCommand;
char c;
do
{
c = fgetc (stdin);
consoleCommand.push_back(c);
} while (c != '\n');
// Now handle this command as normal
if (consoleCommand[0] == '/' || consoleCommand[0] == '&' || consoleCommand[0] == '%')
{
Chat::get()->handleMsg(serverUser, consoleCommand);
std::cout << "Command sent" << std::endl;
}
}
if(time(0)-starttime > 10)
{
starttime = (uint32)time(0);
//std::cout << "Currently " << User::all().size() << " users in!" << std::endl;
//If users, ping them
if(User::all().size() > 0)
{
//0x00 package
uint8 data = 0;
User::all()[0]->sendAll(&data, 1);
//Send server time
Packet pkt;
pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime;
User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
}
//Try to load release time from config
int map_release_time = Conf::get()->iValue("map_release_time");
//Release chunks not used in <map_release_time> seconds
/* std::vector<uint32> toRelease;
for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin();
it != Map::get()->mapLastused.end();
++it)
{
if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time)
toRelease.push_back(it->first);
}
int x_temp, z_temp;
for(unsigned i = 0; i < toRelease.size(); i++)
{
Map::get()->idToPos(toRelease[i], &x_temp, &z_temp);
Map::get()->releaseMap(x_temp, z_temp);
} */
}
//Every second
if(time(0)-tick > 0)
{
tick = (uint32)time(0);
//Loop users
for(unsigned int i = 0; i < User::all().size(); i++)
{
User::all()[i]->pushMap();
User::all()[i]->popMap();
//Minecart hacks!!
if(User::all()[i]->attachedTo)
{
Packet pkt;
pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0;
//pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0;
User::all()[i]->sendAll((uint8 *)pkt.getWrite(), pkt.getWriteLen());
}
}
Map::get()->mapTime+=20;
if(Map::get()->mapTime>=24000) Map::get()->mapTime=0;
Map::get()->checkGenTrees();
// Check for Furnace activity
FurnaceManager::get()->update();
}
//Physics simulation every 200ms
Physics::get()->update();
//Underwater check / drowning
for( unsigned int i = 0; i < User::all().size(); i++ )
User::all()[i]->isUnderwater();
// event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
// event_add(&m_listenEvent, NULL);
event_base_loopexit(m_eventBase, &loopTime);
}
#ifdef WIN32
closesocket(m_socketlisten);
#else
close(m_socketlisten);
#endif
// Remove the PID file
#ifdef WIN32
_unlink((Conf::get()->sValue("pid_file")).c_str());
#else
unlink((Conf::get()->sValue("pid_file")).c_str());
#endif
/* Free memory */
PacketHandler::get()->free();
Map::get()->free();
Physics::get()->free();
FurnaceManager::get()->free();
Chat::get()->free();
Conf::get()->free();
Plugin::get()->free();
Logger::get()->free();
MapGen::get()->free();
return EXIT_SUCCESS;
}
bool Mineserver::stop()
{
m_running=false;
return true;
}
<|endoftext|> |
<commit_before>#include "renderer/frame_buffer.h"
#include "core/json_serializer.h"
#include "core/log.h"
#include "core/string.h"
#include "core/vec.h"
#include <bgfx/bgfx.h>
#include <lua.hpp>
#include <lauxlib.h>
namespace Lumix
{
FrameBuffer::FrameBuffer(const Declaration& decl)
{
m_autodestroy_handle = true;
m_declaration = decl;
bgfx::TextureHandle texture_handles[16];
for (int i = 0; i < decl.m_renderbuffers_count; ++i)
{
const RenderBuffer& renderbuffer = decl.m_renderbuffers[i];
texture_handles[i] = bgfx::createTexture2D((uint16_t)decl.m_width,
(uint16_t)decl.m_height,
1,
renderbuffer.m_format,
BGFX_TEXTURE_RT);
m_declaration.m_renderbuffers[i].m_handle = texture_handles[i];
}
m_window_handle = nullptr;
m_handle = bgfx::createFrameBuffer((uint8_t)decl.m_renderbuffers_count, texture_handles);
}
FrameBuffer::FrameBuffer(const char* name, int width, int height, void* window_handle)
{
m_autodestroy_handle = false;
copyString(m_declaration.m_name, name);
m_declaration.m_width = width;
m_declaration.m_height = height;
m_declaration.m_renderbuffers_count = 0;
m_window_handle = window_handle;
m_handle = bgfx::createFrameBuffer(window_handle, (uint16_t)width, (uint16_t)height);
}
FrameBuffer::~FrameBuffer()
{
if (m_autodestroy_handle)
{
destroyRenderbuffers();
bgfx::destroyFrameBuffer(m_handle);
}
}
void FrameBuffer::destroyRenderbuffers()
{
for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i)
{
bgfx::destroyTexture(m_declaration.m_renderbuffers[i].m_handle);
}
}
void FrameBuffer::resize(int width, int height)
{
if (bgfx::isValid(m_handle))
{
destroyRenderbuffers();
bgfx::destroyFrameBuffer(m_handle);
}
m_declaration.m_width = width;
m_declaration.m_height = height;
if (m_window_handle)
{
m_handle = bgfx::createFrameBuffer(m_window_handle, (uint16_t)width, (uint16_t)height);
}
else
{
bgfx::TextureHandle texture_handles[16];
for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i)
{
const RenderBuffer& renderbuffer = m_declaration.m_renderbuffers[i];
texture_handles[i] =
bgfx::createTexture2D((uint16_t)width, (uint16_t)height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT);
m_declaration.m_renderbuffers[i].m_handle = texture_handles[i];
}
m_window_handle = nullptr;
m_handle = bgfx::createFrameBuffer((uint8_t)m_declaration.m_renderbuffers_count, texture_handles);
}
}
bool FrameBuffer::RenderBuffer::isDepth() const
{
switch(m_format)
{
case bgfx::TextureFormat::D32:
case bgfx::TextureFormat::D24:
return true;
}
return false;
}
static bgfx::TextureFormat::Enum getFormat(const char* name)
{
if (compareString(name, "depth32") == 0)
{
return bgfx::TextureFormat::D32;
}
else if (compareString(name, "depth24") == 0)
{
return bgfx::TextureFormat::D24;
}
else if (compareString(name, "rgba8") == 0)
{
return bgfx::TextureFormat::RGBA8;
}
else if (compareString(name, "r32f") == 0)
{
return bgfx::TextureFormat::R32F;
}
else
{
g_log_error.log("Renderer") << "Uknown texture format " << name;
return bgfx::TextureFormat::RGBA8;
}
}
void FrameBuffer::RenderBuffer::parse(lua_State* L)
{
if (lua_getfield(L, -1, "format") == LUA_TSTRING)
{
m_format = getFormat(lua_tostring(L, -1));
}
else
{
m_format = bgfx::TextureFormat::RGBA8;
}
lua_pop(L, 1);
}
} // ~namespace Lumix
<commit_msg>hdr support<commit_after>#include "renderer/frame_buffer.h"
#include "core/json_serializer.h"
#include "core/log.h"
#include "core/string.h"
#include "core/vec.h"
#include <bgfx/bgfx.h>
#include <lua.hpp>
#include <lauxlib.h>
namespace Lumix
{
FrameBuffer::FrameBuffer(const Declaration& decl)
{
m_autodestroy_handle = true;
m_declaration = decl;
bgfx::TextureHandle texture_handles[16];
for (int i = 0; i < decl.m_renderbuffers_count; ++i)
{
const RenderBuffer& renderbuffer = decl.m_renderbuffers[i];
texture_handles[i] = bgfx::createTexture2D((uint16_t)decl.m_width,
(uint16_t)decl.m_height,
1,
renderbuffer.m_format,
BGFX_TEXTURE_RT);
m_declaration.m_renderbuffers[i].m_handle = texture_handles[i];
}
m_window_handle = nullptr;
m_handle = bgfx::createFrameBuffer((uint8_t)decl.m_renderbuffers_count, texture_handles);
}
FrameBuffer::FrameBuffer(const char* name, int width, int height, void* window_handle)
{
m_autodestroy_handle = false;
copyString(m_declaration.m_name, name);
m_declaration.m_width = width;
m_declaration.m_height = height;
m_declaration.m_renderbuffers_count = 0;
m_window_handle = window_handle;
m_handle = bgfx::createFrameBuffer(window_handle, (uint16_t)width, (uint16_t)height);
}
FrameBuffer::~FrameBuffer()
{
if (m_autodestroy_handle)
{
destroyRenderbuffers();
bgfx::destroyFrameBuffer(m_handle);
}
}
void FrameBuffer::destroyRenderbuffers()
{
for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i)
{
bgfx::destroyTexture(m_declaration.m_renderbuffers[i].m_handle);
}
}
void FrameBuffer::resize(int width, int height)
{
if (bgfx::isValid(m_handle))
{
destroyRenderbuffers();
bgfx::destroyFrameBuffer(m_handle);
}
m_declaration.m_width = width;
m_declaration.m_height = height;
if (m_window_handle)
{
m_handle = bgfx::createFrameBuffer(m_window_handle, (uint16_t)width, (uint16_t)height);
}
else
{
bgfx::TextureHandle texture_handles[16];
for (int i = 0; i < m_declaration.m_renderbuffers_count; ++i)
{
const RenderBuffer& renderbuffer = m_declaration.m_renderbuffers[i];
texture_handles[i] =
bgfx::createTexture2D((uint16_t)width, (uint16_t)height, 1, renderbuffer.m_format, BGFX_TEXTURE_RT);
m_declaration.m_renderbuffers[i].m_handle = texture_handles[i];
}
m_window_handle = nullptr;
m_handle = bgfx::createFrameBuffer((uint8_t)m_declaration.m_renderbuffers_count, texture_handles);
}
}
bool FrameBuffer::RenderBuffer::isDepth() const
{
switch(m_format)
{
case bgfx::TextureFormat::D32:
case bgfx::TextureFormat::D24:
return true;
}
return false;
}
static bgfx::TextureFormat::Enum getFormat(const char* name)
{
if (compareString(name, "depth32") == 0)
{
return bgfx::TextureFormat::D32;
}
else if (compareString(name, "depth24") == 0)
{
return bgfx::TextureFormat::D24;
}
else if (compareString(name, "rgba8") == 0)
{
return bgfx::TextureFormat::RGBA8;
}
else if (compareString(name, "rgba16f") == 0)
{
return bgfx::TextureFormat::RGBA16F;
}
else if (compareString(name, "r32f") == 0)
{
return bgfx::TextureFormat::R32F;
}
else
{
g_log_error.log("Renderer") << "Uknown texture format " << name;
return bgfx::TextureFormat::RGBA8;
}
}
void FrameBuffer::RenderBuffer::parse(lua_State* L)
{
if (lua_getfield(L, -1, "format") == LUA_TSTRING)
{
m_format = getFormat(lua_tostring(L, -1));
}
else
{
m_format = bgfx::TextureFormat::RGBA8;
}
lua_pop(L, 1);
}
} // ~namespace Lumix
<|endoftext|> |
<commit_before>
/**************************************************
* Source Code for the Original Compiler for the
* Programming Language Wake
*
* PrecedenceEnforcer.cpp
*
* Licensed under the MIT license
* See LICENSE.TXT for details
*
* Author: Michael Fairhurst
* Revised By:
*
**************************************************/
#include "PrecedenceEnforcer.h"
void PrecedenceEnforcer::enforceAssociative(Node* tree, int index) {
enforceExact(tree, index, config.getPrec(tree->node_type));
}
void PrecedenceEnforcer::enforceExact(Node* tree, int index, int outer) {
Node* child = tree->node_data.nodes[index];
int type = child->node_type;
if(config.hasPrec(type)) {
if(config.getPrec(type) > outer) {
tree->node_data.nodes[index] = makeOneBranchNode(NT_REQUIRED_PARENS, child, child->loc);
}
enforce(child);
}
}
void PrecedenceEnforcer::enforceNonAssociative(Node* tree, int index) {
enforceExact(tree, index, config.getPrec(tree->node_type) - 1);
}
void PrecedenceEnforcer::enforce(Node* tree) {
switch(tree->node_type) {
case NT_IMPORT:
case NT_IMPORTSET:
case NT_IMPORTTARGET:
case NT_IMPORTPATH:
case NT_ABSTRACT_METHOD:
case NT_TYPE_ARRAY:
case NT_CURRIED:
case NT_CASE:
case NT_DEFAULTCASE:
case NT_INCREMENT:
case NT_DECREMENT:
case NT_SWITCH:
return;
case NT_ANNOTATED_CLASS:
case NT_ANNOTATED_METHOD:
case NT_ANNOTATED_TYPE:
case NT_PROGRAM:
case NT_RETRIEVALS_STATEMENTS:
case NT_BLOCK:
case NT_VALUES:
case NT_CLASSSET:
case NT_EXPRESSIONS:
case NT_INHERITANCESET:
case NT_PROVISIONS:
case NT_CTOR:
case NT_PARENT:
case NT_INJECTION:
case NT_CLASS:
case NT_TRY:
case NT_THROW:
{
int i;
for(i = 0; i < tree->subnodes; i++)
enforce(tree->node_data.nodes[i]);
}
break;
case NT_CATCH:
enforce(tree->node_data.nodes[1]);
break;
case NT_PROVISION:
if(tree->subnodes != 2 && tree->node_data.nodes[1]->node_type == NT_PROVISION_BEHAVIOR) {
enforce(tree->node_data.nodes[1]->node_data.nodes[1]);
}
break;
case NT_CLASSBODY:
{
int i;
for(i = 0; i < tree->subnodes; i++)
if(tree->node_data.nodes[i]->node_type == NT_METHOD_DECLARATION || tree->node_data.nodes[i]->node_type == NT_ANNOTATED_METHOD || tree->node_data.nodes[i]->node_type == NT_PROVISIONS || tree->node_data.nodes[i]->node_type == NT_PROPERTY)
enforce(tree->node_data.nodes[i]);
}
break;
case NT_METHOD_DECLARATION:
{
if(tree->subnodes > 0) enforce(tree->node_data.nodes[0]);
if(tree->subnodes > 1) enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) enforce(tree->node_data.nodes[2]);
if(tree->subnodes > 3) enforce(tree->node_data.nodes[3]);
}
break;
case NT_LAMBDA_DECLARATION:
{
enforce(tree->node_data.nodes[1]);
}
break;
//case NT_METHOD_RETURN_TYPE:
//case NT_METHOD_NAME:
//break;
case NT_METHOD_INVOCATION:
case NT_EARLYBAILOUT_METHOD_INVOCATION:
{
enforce(tree->node_data.nodes[0]);
int i;
for(i = 1; i < tree->node_data.nodes[1]->subnodes; i += 2) {
for(int b = 0; b < tree->node_data.nodes[1]->node_data.nodes[i]->subnodes; b++) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]->node_data.nodes[b]);
}
}
}
break;
case NT_EARLYBAILOUT_MEMBER_ACCESS:
case NT_MEMBER_ACCESS:
{
enforce(tree->node_data.nodes[0]);
}
break;
case NT_RETRIEVAL:
{
enforce(tree->node_data.nodes[2]);
for(int i = 0; i < tree->node_data.nodes[1]->subnodes; i++) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]);
}
}
break;
case NT_PROPERTY:
{
enforce(tree->node_data.nodes[0]->node_data.nodes[1]);
}
break;
case NT_TYPEINFER_DECLARATION:
case NT_DECLARATION:
case NT_ASSIGNMENT:
case NT_VALUED_ASSIGNMENT:
case NT_ADD_ASSIGNMENT:
case NT_SUB_ASSIGNMENT:
case NT_MULT_ASSIGNMENT:
case NT_DIV_ASSIGNMENT:
{
enforce(tree->node_data.nodes[1]);
break;
}
case NT_ARRAY_DECLARATION:
{
int i;
for(i = 0; i < tree->subnodes; i++) {
enforce(tree->node_data.nodes[i]);
}
}
break;
case NT_EXISTS:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) {
enforce(tree->node_data.nodes[2]);
}
break;
case NT_IF_ELSE:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) {
enforce(tree->node_data.nodes[2]);
}
break;
case NT_WHILE:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
break;
case NT_FOR:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
enforce(tree->node_data.nodes[2]);
enforce(tree->node_data.nodes[3]);
break;
case NT_FOREACH:
case NT_FOREACHIN:
case NT_FOREACHAT:
case NT_FOREACHINAT:
{
int index;
if(tree->node_type == NT_FOREACHIN || tree->node_type == NT_FOREACHINAT) {
index = 1;
} else {
index = 0;
}
enforceExact(tree, index, config.getPrec(NT_ARRAY_ACCESS) < config.getPrec(NT_MEMBER_ACCESS) ? config.getPrec(NT_ARRAY_ACCESS) : config.getPrec(NT_MEMBER_ACCESS)); // code generator will generate (iterationVal).length and also (iterationVal)[i]
}
break;
case NT_LAMBDA_INVOCATION:
enforceAssociative(tree, 0);
if(tree->subnodes == 2) {
for(int i = 0; i < tree->node_data.nodes[1]->subnodes; ++i) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]);
}
}
break;
case NT_IF_THEN_ELSE:
if(config.triAssocLeft(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 0);
} else {
enforceNonAssociative(tree, 0);
}
if(config.triAssocMiddle(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 1);
} else {
enforceNonAssociative(tree, 1);
}
if(config.triAssocRight(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 2);
} else {
enforceNonAssociative(tree, 2);
}
break;
case NT_RETURN:
if(tree->subnodes) enforce(tree->node_data.nodes[0]);
break;
// unary ops with child at 1
case NT_CAST:
enforceAssociative(tree, 1);
break;
// unary ops with child at 0
case NT_AUTOBOX:
case NT_INVERT:
case NT_BITNOT:
enforceAssociative(tree, 0);
break;
case NT_DIVIDE:
case NT_MOD:
case NT_MODNATIVE:
case NT_MODALT:
case NT_SUBTRACT:
case NT_BITSHIFTLEFT:
case NT_BITSHIFTRIGHT:
case NT_ARRAY_ACCESS_LVAL:
case NT_TYPESAFE_ARRAY_ACCESS:
case NT_ARRAY_ACCESS:
case NT_MULTIPLY:
case NT_ADD:
case NT_LESSTHAN:
case NT_GREATERTHAN:
case NT_LESSTHANEQUAL:
case NT_GREATERTHANEQUAL:
case NT_EQUALITY:
case NT_INEQUALITY:
case NT_BITAND:
case NT_BITXOR:
case NT_BITOR:
case NT_AND:
case NT_OR:
enforceAssociative(tree, 0);
if(config.binAssoc(tree->node_type)) {
//enforceAssociative(tree, 0);
enforceAssociative(tree, 1);
} else {
//enforceNonAssociative(tree, 0);
enforceNonAssociative(tree, 1);
}
break;
}
}
<commit_msg>Another attempt at properly specifying precedence of provisions<commit_after>
/**************************************************
* Source Code for the Original Compiler for the
* Programming Language Wake
*
* PrecedenceEnforcer.cpp
*
* Licensed under the MIT license
* See LICENSE.TXT for details
*
* Author: Michael Fairhurst
* Revised By:
*
**************************************************/
#include "PrecedenceEnforcer.h"
void PrecedenceEnforcer::enforceAssociative(Node* tree, int index) {
enforceExact(tree, index, config.getPrec(tree->node_type));
}
void PrecedenceEnforcer::enforceExact(Node* tree, int index, int outer) {
Node* child = tree->node_data.nodes[index];
int type = child->node_type;
if(config.hasPrec(type)) {
if(config.getPrec(type) > outer) {
tree->node_data.nodes[index] = makeOneBranchNode(NT_REQUIRED_PARENS, child, child->loc);
}
enforce(child);
}
}
void PrecedenceEnforcer::enforceNonAssociative(Node* tree, int index) {
enforceExact(tree, index, config.getPrec(tree->node_type) - 1);
}
void PrecedenceEnforcer::enforce(Node* tree) {
switch(tree->node_type) {
case NT_IMPORT:
case NT_IMPORTSET:
case NT_IMPORTTARGET:
case NT_IMPORTPATH:
case NT_ABSTRACT_METHOD:
case NT_TYPE_ARRAY:
case NT_CURRIED:
case NT_CASE:
case NT_DEFAULTCASE:
case NT_INCREMENT:
case NT_DECREMENT:
case NT_SWITCH:
return;
case NT_ANNOTATED_CLASS:
case NT_ANNOTATED_METHOD:
case NT_ANNOTATED_TYPE:
case NT_PROGRAM:
case NT_RETRIEVALS_STATEMENTS:
case NT_BLOCK:
case NT_VALUES:
case NT_CLASSSET:
case NT_EXPRESSIONS:
case NT_INHERITANCESET:
case NT_PROVISIONS:
case NT_CTOR:
case NT_PARENT:
case NT_INJECTION:
case NT_CLASS:
case NT_TRY:
case NT_THROW:
{
int i;
for(i = 0; i < tree->subnodes; i++)
enforce(tree->node_data.nodes[i]);
}
break;
case NT_CATCH:
enforce(tree->node_data.nodes[1]);
break;
case NT_PROVISION:
if(tree->subnodes != 2 && tree->node_data.nodes[1]->node_type == NT_PROVISION_BEHAVIOR) {
enforce(tree->node_data.nodes[1]->node_data.nodes[1]);
}
break;
case NT_CLASSBODY:
{
int i;
for(i = 0; i < tree->subnodes; i++)
if(tree->node_data.nodes[i]->node_type == NT_METHOD_DECLARATION || tree->node_data.nodes[i]->node_type == NT_ANNOTATED_METHOD || tree->node_data.nodes[i]->node_type == NT_PROVISIONS || tree->node_data.nodes[i]->node_type == NT_PROPERTY)
enforce(tree->node_data.nodes[i]);
}
break;
case NT_METHOD_DECLARATION:
{
if(tree->subnodes > 0) enforce(tree->node_data.nodes[0]);
if(tree->subnodes > 1) enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) enforce(tree->node_data.nodes[2]);
if(tree->subnodes > 3) enforce(tree->node_data.nodes[3]);
}
break;
case NT_LAMBDA_DECLARATION:
{
enforce(tree->node_data.nodes[1]);
}
break;
//case NT_METHOD_RETURN_TYPE:
//case NT_METHOD_NAME:
//break;
case NT_METHOD_INVOCATION:
case NT_EARLYBAILOUT_METHOD_INVOCATION:
{
enforce(tree->node_data.nodes[0]);
int i;
for(i = 1; i < tree->node_data.nodes[1]->subnodes; i += 2) {
for(int b = 0; b < tree->node_data.nodes[1]->node_data.nodes[i]->subnodes; b++) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]->node_data.nodes[b]);
}
}
}
break;
case NT_EARLYBAILOUT_MEMBER_ACCESS:
case NT_MEMBER_ACCESS:
{
enforce(tree->node_data.nodes[0]);
}
break;
case NT_RETRIEVAL:
{
enforceExact(tree, 2, config.getPrec(NT_METHOD_INVOCATION));
for(int i = 0; i < tree->node_data.nodes[1]->subnodes; i++) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]);
}
}
break;
case NT_PROPERTY:
{
enforce(tree->node_data.nodes[0]->node_data.nodes[1]);
}
break;
case NT_TYPEINFER_DECLARATION:
case NT_DECLARATION:
case NT_ASSIGNMENT:
case NT_VALUED_ASSIGNMENT:
case NT_ADD_ASSIGNMENT:
case NT_SUB_ASSIGNMENT:
case NT_MULT_ASSIGNMENT:
case NT_DIV_ASSIGNMENT:
{
enforce(tree->node_data.nodes[1]);
break;
}
case NT_ARRAY_DECLARATION:
{
int i;
for(i = 0; i < tree->subnodes; i++) {
enforce(tree->node_data.nodes[i]);
}
}
break;
case NT_EXISTS:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) {
enforce(tree->node_data.nodes[2]);
}
break;
case NT_IF_ELSE:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
if(tree->subnodes > 2) {
enforce(tree->node_data.nodes[2]);
}
break;
case NT_WHILE:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
break;
case NT_FOR:
enforce(tree->node_data.nodes[0]);
enforce(tree->node_data.nodes[1]);
enforce(tree->node_data.nodes[2]);
enforce(tree->node_data.nodes[3]);
break;
case NT_FOREACH:
case NT_FOREACHIN:
case NT_FOREACHAT:
case NT_FOREACHINAT:
{
int index;
if(tree->node_type == NT_FOREACHIN || tree->node_type == NT_FOREACHINAT) {
index = 1;
} else {
index = 0;
}
enforceExact(tree, index, config.getPrec(NT_ARRAY_ACCESS) < config.getPrec(NT_MEMBER_ACCESS) ? config.getPrec(NT_ARRAY_ACCESS) : config.getPrec(NT_MEMBER_ACCESS)); // code generator will generate (iterationVal).length and also (iterationVal)[i]
}
break;
case NT_LAMBDA_INVOCATION:
enforceAssociative(tree, 0);
if(tree->subnodes == 2) {
for(int i = 0; i < tree->node_data.nodes[1]->subnodes; ++i) {
enforce(tree->node_data.nodes[1]->node_data.nodes[i]);
}
}
break;
case NT_IF_THEN_ELSE:
if(config.triAssocLeft(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 0);
} else {
enforceNonAssociative(tree, 0);
}
if(config.triAssocMiddle(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 1);
} else {
enforceNonAssociative(tree, 1);
}
if(config.triAssocRight(NT_IF_THEN_ELSE)) {
enforceAssociative(tree, 2);
} else {
enforceNonAssociative(tree, 2);
}
break;
case NT_RETURN:
if(tree->subnodes) enforce(tree->node_data.nodes[0]);
break;
// unary ops with child at 1
case NT_CAST:
enforceAssociative(tree, 1);
break;
// unary ops with child at 0
case NT_AUTOBOX:
case NT_INVERT:
case NT_BITNOT:
enforceAssociative(tree, 0);
break;
case NT_DIVIDE:
case NT_MOD:
case NT_MODNATIVE:
case NT_MODALT:
case NT_SUBTRACT:
case NT_BITSHIFTLEFT:
case NT_BITSHIFTRIGHT:
case NT_ARRAY_ACCESS_LVAL:
case NT_TYPESAFE_ARRAY_ACCESS:
case NT_ARRAY_ACCESS:
case NT_MULTIPLY:
case NT_ADD:
case NT_LESSTHAN:
case NT_GREATERTHAN:
case NT_LESSTHANEQUAL:
case NT_GREATERTHANEQUAL:
case NT_EQUALITY:
case NT_INEQUALITY:
case NT_BITAND:
case NT_BITXOR:
case NT_BITOR:
case NT_AND:
case NT_OR:
enforceAssociative(tree, 0);
if(config.binAssoc(tree->node_type)) {
//enforceAssociative(tree, 0);
enforceAssociative(tree, 1);
} else {
//enforceNonAssociative(tree, 0);
enforceNonAssociative(tree, 1);
}
break;
}
}
<|endoftext|> |
<commit_before>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include "WorldModel.hpp"
#include <QObject>
#include <QString>
#include <vector>
#include <boost/foreach.hpp>
#include <Constants.hpp>
#include <Utils.hpp>
#include "framework/Module.hpp"
//#include "Ball.hpp"
using namespace std;
using namespace Modeling;
using namespace Utils;
// Maximum time to coast a track (keep the track alive with no observations) in microseconds.
const uint64_t MaxCoastTime = 500000;
WorldModel::WorldModel(SystemState *state, ConfigFile::WorldModel& cfg) :
Module("World Model"),
_config(cfg)
{
_state = state;
for(unsigned int i=0 ; i<5 ; i++)
{
_selfRobot[i] = 0;
_oppRobot[i] = 0;
}
}
WorldModel::~WorldModel()
{
for(unsigned int i=0 ; i<5 ; i++)
{
//delete _self[i];
//delete _opp[i];
}
BOOST_FOREACH(RobotMap::value_type p, _robotMap)
{
RobotModel *robot = p.second;
delete robot;
}
}
void WorldModel::run()
{
// Reset errors on all tracks
BOOST_FOREACH(RobotMap::value_type p, _robotMap)
{
RobotModel *robot = p.second;
robot->bestError = -1;
}
ballModel.bestError = -1;
/// ball sensor
BOOST_FOREACH(Packet::LogFrame::Robot& r, _state->self)
{
r.haveBall = r.radioRx.ball;
//if a robot has the ball, we need to make an observation
//using that information and project the ball in front of it
if (r.valid && r.haveBall)
{
Geometry2d::Point offset = Geometry2d::Point::
direction(r.angle * DegreesToRadians) * Constants::Robot::Radius;
ballModel.observation(_state->timestamp, r.pos + offset);
}
}
//printf("--- WorldModel\n");
uint64_t curTime = 0;
BOOST_FOREACH(const Packet::Vision& vision, _state->rawVision)
{
curTime = max(curTime, vision.timestamp);
if (!vision.sync)
{
const std::vector<Packet::Vision::Robot>* self;
const std::vector<Packet::Vision::Robot>* opp;
if (_state->team == Yellow)
{
self = &vision.yellow;
opp = &vision.blue;
} else if (_state->team == Blue)
{
self = &vision.blue;
opp = &vision.yellow;
} else {
continue;
}
BOOST_FOREACH(const Packet::Vision::Robot& r, *self)
{
RobotModel *robot = map_lookup(_robotMap, r.shell);
if (!robot)
{
robot = new RobotModel(_config, r.shell);
_robotMap[r.shell] = robot;
}
robot->observation(vision.timestamp, r.pos, r.angle);
}
BOOST_FOREACH(const Packet::Vision::Robot& r, *opp)
{
RobotModel *robot = map_lookup(_robotMap, r.shell + OppOffset);
if (!robot)
{
robot = new RobotModel(_config, r.shell);
_robotMap[r.shell + OppOffset] = robot;
}
robot->observation(vision.timestamp, r.pos, r.angle);
}
BOOST_FOREACH(const Packet::Vision::Ball &ball, vision.balls)
{
ballModel.observation(vision.timestamp, ball.pos);
}
}
}
// Update/delete robots
vector<RobotModel *> selfUnused;
vector<RobotModel *> oppUnused;
for (RobotMap::iterator i = _robotMap.begin(); i != _robotMap.end();)
{
RobotMap::iterator next = i;
++next;
RobotModel *robot = i->second;
if ((curTime - robot->lastObservedTime) > MaxCoastTime)
{
// This robot is too old, so delete it.
if (robot->report)
{
*robot->report = 0;
}
delete robot;
_robotMap.erase(i);
} else {
if (robot->bestError >= 0)
{
// This robot has a new observation. Update it.
robot->update();
if (!robot->report)
{
if (i->first < OppOffset)
{
selfUnused.push_back(robot);
} else {
oppUnused.push_back(robot);
}
}
}
}
i = next;
}
//FIXME - Sort unused lists
unsigned int nextSelfUnused = 0;
unsigned int nextOppUnused = 0;
for (int i = 0; i < 5; ++i)
{
if (!_selfRobot[i] && nextSelfUnused < selfUnused.size())
{
_selfRobot[i] = selfUnused[nextSelfUnused++];
_selfRobot[i]->report = &_selfRobot[i];
}
if (_selfRobot[i])
{
_state->self[i].valid = true;
_state->self[i].shell = _selfRobot[i]->shell;
_state->self[i].pos = _selfRobot[i]->pos;
_state->self[i].vel = _selfRobot[i]->vel;
_state->self[i].angle = _selfRobot[i]->angle;
_state->self[i].angleVel = _selfRobot[i]->angleVel;
} else {
_state->self[i].valid = false;
}
if (!_oppRobot[i] && nextOppUnused < oppUnused.size())
{
_oppRobot[i] = oppUnused[nextOppUnused++];
_oppRobot[i]->report = &_oppRobot[i];
}
if (_oppRobot[i])
{
_state->opp[i].valid = true;
_state->opp[i].shell = _oppRobot[i]->shell;
_state->opp[i].pos = _oppRobot[i]->pos;
_state->opp[i].vel = _oppRobot[i]->vel;
_state->opp[i].angle = _oppRobot[i]->angle;
_state->opp[i].angleVel = _oppRobot[i]->angleVel;
} else {
_state->opp[i].valid = false;
}
}
ballModel.update();
_state->ball.pos = ballModel.pos;
_state->ball.vel = ballModel.vel;
_state->ball.accel = ballModel.accel;
_state->ball.valid = (curTime - ballModel.lastObservedTime) < MaxCoastTime;
}
<commit_msg>Don't update haveBall for robots that we don't have reverse packets for<commit_after>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include "WorldModel.hpp"
#include <QObject>
#include <QString>
#include <vector>
#include <boost/foreach.hpp>
#include <Constants.hpp>
#include <Utils.hpp>
#include "framework/Module.hpp"
//#include "Ball.hpp"
using namespace std;
using namespace Modeling;
using namespace Utils;
// Maximum time to coast a track (keep the track alive with no observations) in microseconds.
const uint64_t MaxCoastTime = 500000;
WorldModel::WorldModel(SystemState *state, ConfigFile::WorldModel& cfg) :
Module("World Model"),
_config(cfg)
{
_state = state;
for(unsigned int i=0 ; i<5 ; i++)
{
_selfRobot[i] = 0;
_oppRobot[i] = 0;
}
}
WorldModel::~WorldModel()
{
for(unsigned int i=0 ; i<5 ; i++)
{
//delete _self[i];
//delete _opp[i];
}
BOOST_FOREACH(RobotMap::value_type p, _robotMap)
{
RobotModel *robot = p.second;
delete robot;
}
}
void WorldModel::run()
{
// Reset errors on all tracks
BOOST_FOREACH(RobotMap::value_type p, _robotMap)
{
RobotModel *robot = p.second;
robot->bestError = -1;
}
ballModel.bestError = -1;
/// ball sensor
BOOST_FOREACH(Packet::LogFrame::Robot& r, _state->self)
{
if (r.radioRx.updated)
{
r.haveBall = r.radioRx.ball;
}
//if a robot has the ball, we need to make an observation
//using that information and project the ball in front of it
if (r.valid && r.haveBall)
{
Geometry2d::Point offset = Geometry2d::Point::
direction(r.angle * DegreesToRadians) * Constants::Robot::Radius;
ballModel.observation(_state->timestamp, r.pos + offset);
}
}
//printf("--- WorldModel\n");
uint64_t curTime = 0;
BOOST_FOREACH(const Packet::Vision& vision, _state->rawVision)
{
curTime = max(curTime, vision.timestamp);
if (!vision.sync)
{
const std::vector<Packet::Vision::Robot>* self;
const std::vector<Packet::Vision::Robot>* opp;
if (_state->team == Yellow)
{
self = &vision.yellow;
opp = &vision.blue;
} else if (_state->team == Blue)
{
self = &vision.blue;
opp = &vision.yellow;
} else {
continue;
}
BOOST_FOREACH(const Packet::Vision::Robot& r, *self)
{
RobotModel *robot = map_lookup(_robotMap, r.shell);
if (!robot)
{
robot = new RobotModel(_config, r.shell);
_robotMap[r.shell] = robot;
}
robot->observation(vision.timestamp, r.pos, r.angle);
}
BOOST_FOREACH(const Packet::Vision::Robot& r, *opp)
{
RobotModel *robot = map_lookup(_robotMap, r.shell + OppOffset);
if (!robot)
{
robot = new RobotModel(_config, r.shell);
_robotMap[r.shell + OppOffset] = robot;
}
robot->observation(vision.timestamp, r.pos, r.angle);
}
BOOST_FOREACH(const Packet::Vision::Ball &ball, vision.balls)
{
ballModel.observation(vision.timestamp, ball.pos);
}
}
}
// Update/delete robots
vector<RobotModel *> selfUnused;
vector<RobotModel *> oppUnused;
for (RobotMap::iterator i = _robotMap.begin(); i != _robotMap.end();)
{
RobotMap::iterator next = i;
++next;
RobotModel *robot = i->second;
if ((curTime - robot->lastObservedTime) > MaxCoastTime)
{
// This robot is too old, so delete it.
if (robot->report)
{
*robot->report = 0;
}
delete robot;
_robotMap.erase(i);
} else {
if (robot->bestError >= 0)
{
// This robot has a new observation. Update it.
robot->update();
if (!robot->report)
{
if (i->first < OppOffset)
{
selfUnused.push_back(robot);
} else {
oppUnused.push_back(robot);
}
}
}
}
i = next;
}
//FIXME - Sort unused lists
unsigned int nextSelfUnused = 0;
unsigned int nextOppUnused = 0;
for (int i = 0; i < 5; ++i)
{
if (!_selfRobot[i] && nextSelfUnused < selfUnused.size())
{
_selfRobot[i] = selfUnused[nextSelfUnused++];
_selfRobot[i]->report = &_selfRobot[i];
}
if (_selfRobot[i])
{
_state->self[i].valid = true;
_state->self[i].shell = _selfRobot[i]->shell;
_state->self[i].pos = _selfRobot[i]->pos;
_state->self[i].vel = _selfRobot[i]->vel;
_state->self[i].angle = _selfRobot[i]->angle;
_state->self[i].angleVel = _selfRobot[i]->angleVel;
} else {
_state->self[i].valid = false;
}
if (!_oppRobot[i] && nextOppUnused < oppUnused.size())
{
_oppRobot[i] = oppUnused[nextOppUnused++];
_oppRobot[i]->report = &_oppRobot[i];
}
if (_oppRobot[i])
{
_state->opp[i].valid = true;
_state->opp[i].shell = _oppRobot[i]->shell;
_state->opp[i].pos = _oppRobot[i]->pos;
_state->opp[i].vel = _oppRobot[i]->vel;
_state->opp[i].angle = _oppRobot[i]->angle;
_state->opp[i].angleVel = _oppRobot[i]->angleVel;
} else {
_state->opp[i].valid = false;
}
}
ballModel.update();
_state->ball.pos = ballModel.pos;
_state->ball.vel = ballModel.vel;
_state->ball.accel = ballModel.accel;
_state->ball.valid = (curTime - ballModel.lastObservedTime) < MaxCoastTime;
}
<|endoftext|> |
<commit_before>#include <Geometry2d/Util.hpp>
#include <iostream>
#include <time.hpp>
#include <status.h>
#include "PacketConvert.hpp"
void from_robot_tx_proto(const Packet::Robot& proto_packet, rtp::RobotTxMessage* msg) {
Packet::Control control = proto_packet.control();
msg->uid = proto_packet.uid();
msg->message.controlMessage.bodyX = static_cast<int16_t>(
control.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.bodyY = static_cast<int16_t>(
control.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.bodyW = static_cast<int16_t>(
control.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.dribbler =
clamp(static_cast<uint16_t>(control.dvelocity()) * 2, 0, 255);
msg->message.controlMessage.shootMode = control.shootmode();
msg->message.controlMessage.kickStrength = control.kcstrength();
msg->message.controlMessage.triggerMode = control.triggermode();
msg->message.controlMessage.song = control.song();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
}
void convert_tx_proto_to_rtp(const Packet::RadioTx &proto_packet,
rtp::RobotTxMessage *messages) {
from_robot_tx_proto(proto_packet.robots(0), messages);
}
Packet::RadioRx convert_rx_rtp_to_proto(const rtp::RobotStatusMessage &msg) {
Packet::RadioRx packet;
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg.uid);
packet.set_hardware_version(Packet::RJ2015);
packet.set_battery(msg.battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
if (Packet::BallSenseStatus_IsValid(msg.ballSenseStatus)) {
packet.set_ball_sense_status(
Packet::BallSenseStatus(msg.ballSenseStatus));
}
// Using same flags as 2011 robot. See common/status.h
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg.kickStatus ? Kicker_Charged : 0) |
(msg.kickHealthy ? Kicker_Enabled : 0) |
Kicker_I2C_OK);
// Motor errors
for (int i = 0; i < 5; i++) {
bool err = msg.motorErrors & (1 << i);
packet.add_motor_status(err ? Packet::MotorStatus::Hall_Failure
: Packet::MotorStatus::Good);
}
for (std::size_t i = 0; i < 4; i++) {
packet.add_encoders(msg.encDeltas[i]);
}
// FPGA status
if (Packet::FpgaStatus_IsValid(msg.fpgaStatus)) {
packet.set_fpga_status(Packet::FpgaStatus(msg.fpgaStatus));
}
return packet;
}
void fill_header(rtp::Header* header) {
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
}
<commit_msg>Prints for all 14 debug values<commit_after>#include <Geometry2d/Util.hpp>
#include <iostream>
#include <time.hpp>
#include <status.h>
#include "PacketConvert.hpp"
void from_robot_tx_proto(const Packet::Robot& proto_packet, rtp::RobotTxMessage* msg) {
Packet::Control control = proto_packet.control();
msg->uid = proto_packet.uid();
msg->message.controlMessage.bodyX = static_cast<int16_t>(
control.xvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.bodyY = static_cast<int16_t>(
control.yvelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.bodyW = static_cast<int16_t>(
control.avelocity() * rtp::ControlMessage::VELOCITY_SCALE_FACTOR);
msg->message.controlMessage.dribbler =
clamp(static_cast<uint16_t>(control.dvelocity()) * 2, 0, 255);
msg->message.controlMessage.shootMode = control.shootmode();
msg->message.controlMessage.kickStrength = control.kcstrength();
msg->message.controlMessage.triggerMode = control.triggermode();
msg->message.controlMessage.song = control.song();
msg->messageType = rtp::RobotTxMessage::ControlMessageType;
}
void convert_tx_proto_to_rtp(const Packet::RadioTx &proto_packet,
rtp::RobotTxMessage *messages) {
from_robot_tx_proto(proto_packet.robots(0), messages);
}
Packet::RadioRx convert_rx_rtp_to_proto(const rtp::RobotStatusMessage &msg) {
Packet::RadioRx packet;
packet.set_timestamp(RJ::timestamp());
packet.set_robot_id(msg.uid);
packet.set_hardware_version(Packet::RJ2015);
packet.set_battery(msg.battVoltage *
rtp::RobotStatusMessage::BATTERY_SCALE_FACTOR);
if (Packet::BallSenseStatus_IsValid(msg.ballSenseStatus)) {
packet.set_ball_sense_status(
Packet::BallSenseStatus(msg.ballSenseStatus));
}
// Using same flags as 2011 robot. See common/status.h
// Report that everything is good b/c the bot currently has no way of
// detecting kicker issues
packet.set_kicker_status((msg.kickStatus ? Kicker_Charged : 0) |
(msg.kickHealthy ? Kicker_Enabled : 0) |
Kicker_I2C_OK);
// Motor errors
for (int i = 0; i < 5; i++) {
bool err = msg.motorErrors & (1 << i);
packet.add_motor_status(err ? Packet::MotorStatus::Hall_Failure
: Packet::MotorStatus::Good);
}
for (std::size_t i = 0; i < 14; i++) {
packet.add_encoders(msg.encDeltas[i]);
printf("%9.3f,", (float)msg.encDeltas[i] / 1000);
}
printf("\r\n");
// FPGA status
if (Packet::FpgaStatus_IsValid(msg.fpgaStatus)) {
packet.set_fpga_status(Packet::FpgaStatus(msg.fpgaStatus));
}
return packet;
}
void fill_header(rtp::Header* header) {
header->port = rtp::PortType::CONTROL;
header->address = rtp::BROADCAST_ADDRESS;
header->type = rtp::MessageType::CONTROL;
}
<|endoftext|> |
<commit_before>#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageFileReader.h"
#include <itkImageIOBase.h>
#include <itkImageFileReader.h>
namespace itk {
namespace simple {
ImageFileReader& ImageFileReader::SetFilename ( std::string fn ) {
this->m_Filename = fn;
return *this;
}
std::string ImageFileReader::GetFilename() {
return this->m_Filename;
}
Image::Pointer ImageFileReader::Execute () {
Image::Pointer image = NULL;
// todo check if filename does not exits for robust error handling
itk::ImageIOBase::Pointer iobase =
itk::ImageIOFactory::CreateImageIO(this->m_Filename.c_str(),
itk::ImageIOFactory::ReadMode);
if ( iobase.IsNull() )
{
std::cerr << "unable to create ImageIO for \"" << this->m_Filename << "\"" << std::endl;
return image;
}
// Read the image information
iobase->SetFileName( this->m_Filename );
iobase->ReadImageInformation();
// get output information about input image
unsigned int dimension = iobase->GetNumberOfDimensions();
itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();
itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();
unsigned int numberOfComponents = iobase->GetNumberOfComponents();
if (numberOfComponents == 1 &&
( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )
{
switch (dimension)
{
case 2:
image = this->ExecuteInternalReadScalar<2>( componentType );
break;
case 3:
image = this->ExecuteInternalReadScalar<3>( componentType );
break;
}
}
// we try to load anything else into a VectorImage
else if (pixelType == itk::ImageIOBase::RGB ||
pixelType == itk::ImageIOBase::RGBA ||
pixelType == itk::ImageIOBase::VECTOR ||
pixelType == itk::ImageIOBase::COVARIANTVECTOR ||
pixelType == itk::ImageIOBase::FIXEDARRAY ||
pixelType == itk::ImageIOBase::POINT ||
pixelType == itk::ImageIOBase::OFFSET )
{
switch (dimension)
{
case 2:
image = this->ExecuteInternalReadVector<2>( componentType );
break;
case 3:
image = this->ExecuteInternalReadVector<3>( componentType );
break;
}
}
else
{
std::cerr << "Unknown PixelType: " << (int) componentType << std::endl;
}
if ( image.IsNull() )
{
std::cerr << "Unable to load image!" << std::endl;
}
return image;
}
template < unsigned int ImageDimension >
Image::Pointer ImageFileReader::ExecuteInternalReadScalar( itk::ImageIOBase::IOComponentType componentType )
{
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return this->ExecuteInternal< itk::Image<int8_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UCHAR:
return this->ExecuteInternal< itk::Image<uint8_t, ImageDimension> >( );
break;
case itk::ImageIOBase::SHORT:
return this->ExecuteInternal< itk::Image<int16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::USHORT:
return this->ExecuteInternal< itk::Image<uint16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::INT:
return this->ExecuteInternal< itk::Image<int32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UINT:
return this->ExecuteInternal< itk::Image<uint32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::LONG:
return this->ExecuteInternal< itk::Image<long, ImageDimension> >( );
break;
case itk::ImageIOBase::ULONG:
return this->ExecuteInternal< itk::Image<unsigned long, ImageDimension> >( );
break;
case itk::ImageIOBase::FLOAT:
return this->ExecuteInternal< itk::Image<float, ImageDimension> >( );
break;
case itk::ImageIOBase::DOUBLE:
return this->ExecuteInternal< itk::Image<double, ImageDimension> >( );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
// todo error handling
std::cerr << "Unknow pixel component type" << std::endl;
return NULL;
}
}
template < unsigned int ImageDimension >
Image::Pointer ImageFileReader::ExecuteInternalReadVector( itk::ImageIOBase::IOComponentType componentType )
{
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return this->ExecuteInternal< itk::VectorImage<char, ImageDimension> >( );
break;
case itk::ImageIOBase::UCHAR:
return this->ExecuteInternal< itk::VectorImage<unsigned char, ImageDimension> >( );
break;
case itk::ImageIOBase::SHORT:
return this->ExecuteInternal< itk::VectorImage<int16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::USHORT:
return this->ExecuteInternal< itk::VectorImage<uint16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::INT:
return this->ExecuteInternal< itk::VectorImage<int32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UINT:
return this->ExecuteInternal< itk::VectorImage<uint32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::LONG:
return this->ExecuteInternal< itk::VectorImage<long, ImageDimension> >( );
break;
case itk::ImageIOBase::ULONG:
return this->ExecuteInternal< itk::VectorImage<unsigned long, ImageDimension> >( );
break;
case itk::ImageIOBase::FLOAT:
return this->ExecuteInternal< itk::VectorImage<float, ImageDimension> >( );
break;
case itk::ImageIOBase::DOUBLE:
return this->ExecuteInternal< itk::VectorImage<double, ImageDimension> >( );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
// todo error handling
std::cerr << "Unknow pixel component type" << std::endl;
return NULL;
}
}
template <class TImageType>
Image::Pointer ImageFileReader::ExecuteInternal( void ) {
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> Reader;
// do not create an image if it's not in the instatied pixel list
if ( ImageTypeToPixelIDValue<ImageType>::Result == (int)sitkUnknown)
{
std::cerr << "PixelType is not supported!" << std::endl
<< "Refusing to load! " << std::endl
<< typeid( ImageType ).name() << std::endl
<< typeid( typename ImageTypeToPixelID<ImageType>::PixelIDType ).name() << std::endl
<< ImageTypeToPixelIDValue<ImageType>::Result << std::endl;
return NULL;
}
typename Reader::Pointer reader = Reader::New();
reader->SetFileName( this->m_Filename.c_str() );
reader->Update();
typename Image::Pointer image = new Image( reader->GetOutput() );
return image;
}
}
}
<commit_msg>ENH: changes all error conditions to produce exceptions<commit_after>#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageFileReader.h"
#include <itkImageIOBase.h>
#include <itkImageFileReader.h>
namespace itk {
namespace simple {
ImageFileReader& ImageFileReader::SetFilename ( std::string fn ) {
this->m_Filename = fn;
return *this;
}
std::string ImageFileReader::GetFilename() {
return this->m_Filename;
}
Image::Pointer ImageFileReader::Execute () {
Image::Pointer image = NULL;
// todo check if filename does not exits for robust error handling
itk::ImageIOBase::Pointer iobase =
itk::ImageIOFactory::CreateImageIO(this->m_Filename.c_str(),
itk::ImageIOFactory::ReadMode);
if ( iobase.IsNull() )
{
itkGenericExceptionMacro( "Unable to determine ImageIO reader for \"" << this->m_Filename << "\"" );
}
// Read the image information
iobase->SetFileName( this->m_Filename );
iobase->ReadImageInformation();
// get output information about input image
unsigned int dimension = iobase->GetNumberOfDimensions();
itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();
itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();
unsigned int numberOfComponents = iobase->GetNumberOfComponents();
if (numberOfComponents == 1 &&
( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )
{
switch (dimension)
{
case 2:
image = this->ExecuteInternalReadScalar<2>( componentType );
break;
case 3:
image = this->ExecuteInternalReadScalar<3>( componentType );
break;
}
}
// we try to load anything else into a VectorImage
else if (pixelType == itk::ImageIOBase::RGB ||
pixelType == itk::ImageIOBase::RGBA ||
pixelType == itk::ImageIOBase::VECTOR ||
pixelType == itk::ImageIOBase::COVARIANTVECTOR ||
pixelType == itk::ImageIOBase::FIXEDARRAY ||
pixelType == itk::ImageIOBase::POINT ||
pixelType == itk::ImageIOBase::OFFSET )
{
switch (dimension)
{
case 2:
image = this->ExecuteInternalReadVector<2>( componentType );
break;
case 3:
image = this->ExecuteInternalReadVector<3>( componentType );
break;
}
}
else
{
itkGenericExceptionMacro( "Unknown PixelType: " << (int) componentType );
}
if ( image.IsNull() )
{
itkGenericExceptionMacro( "Unable to load image \"" << this->m_Filename << "\"" );
}
return image;
}
template < unsigned int ImageDimension >
Image::Pointer ImageFileReader::ExecuteInternalReadScalar( itk::ImageIOBase::IOComponentType componentType )
{
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return this->ExecuteInternal< itk::Image<int8_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UCHAR:
return this->ExecuteInternal< itk::Image<uint8_t, ImageDimension> >( );
break;
case itk::ImageIOBase::SHORT:
return this->ExecuteInternal< itk::Image<int16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::USHORT:
return this->ExecuteInternal< itk::Image<uint16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::INT:
return this->ExecuteInternal< itk::Image<int32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UINT:
return this->ExecuteInternal< itk::Image<uint32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::LONG:
return this->ExecuteInternal< itk::Image<long, ImageDimension> >( );
break;
case itk::ImageIOBase::ULONG:
return this->ExecuteInternal< itk::Image<unsigned long, ImageDimension> >( );
break;
case itk::ImageIOBase::FLOAT:
return this->ExecuteInternal< itk::Image<float, ImageDimension> >( );
break;
case itk::ImageIOBase::DOUBLE:
return this->ExecuteInternal< itk::Image<double, ImageDimension> >( );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
assert( false ); // should never get here unless we forgot a type
return NULL;
}
}
template < unsigned int ImageDimension >
Image::Pointer ImageFileReader::ExecuteInternalReadVector( itk::ImageIOBase::IOComponentType componentType )
{
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return this->ExecuteInternal< itk::VectorImage<char, ImageDimension> >( );
break;
case itk::ImageIOBase::UCHAR:
return this->ExecuteInternal< itk::VectorImage<unsigned char, ImageDimension> >( );
break;
case itk::ImageIOBase::SHORT:
return this->ExecuteInternal< itk::VectorImage<int16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::USHORT:
return this->ExecuteInternal< itk::VectorImage<uint16_t, ImageDimension> >( );
break;
case itk::ImageIOBase::INT:
return this->ExecuteInternal< itk::VectorImage<int32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::UINT:
return this->ExecuteInternal< itk::VectorImage<uint32_t, ImageDimension> >( );
break;
case itk::ImageIOBase::LONG:
return this->ExecuteInternal< itk::VectorImage<long, ImageDimension> >( );
break;
case itk::ImageIOBase::ULONG:
return this->ExecuteInternal< itk::VectorImage<unsigned long, ImageDimension> >( );
break;
case itk::ImageIOBase::FLOAT:
return this->ExecuteInternal< itk::VectorImage<float, ImageDimension> >( );
break;
case itk::ImageIOBase::DOUBLE:
return this->ExecuteInternal< itk::VectorImage<double, ImageDimension> >( );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
assert( false ); // should never get here unless we forgot a type
return NULL;
}
}
template <class TImageType>
Image::Pointer ImageFileReader::ExecuteInternal( void ) {
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> Reader;
// do not create an image if it's not in the instatied pixel list
if ( ImageTypeToPixelIDValue<ImageType>::Result == (int)sitkUnknown)
{
itkGenericExceptionMacro( << "PixelType is not supported!" << std::endl
<< "Refusing to load! " << std::endl
<< typeid( ImageType ).name() << std::endl
<< typeid( typename ImageTypeToPixelID<ImageType>::PixelIDType ).name() << std::endl
<< ImageTypeToPixelIDValue<ImageType>::Result );
return NULL;
}
typename Reader::Pointer reader = Reader::New();
reader->SetFileName( this->m_Filename.c_str() );
reader->Update();
typename Image::Pointer image = new Image( reader->GetOutput() );
return image;
}
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include "svm_interface.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
struct svm_parameter param; // set by parse_command_line
struct svm_problem prob; // set by read_problem
struct svm_model *model;
struct svm_node *x_space;
void train(const int problemSize, const int dimensions, double dataset[], double labels[]) {
/*
==================
Set all parameters
==================
*/
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0.5;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
/*
==================
Problem definition
==================
*/
//Set the number of training data
prob.l = problemSize;
//Set the array containing the labels of all training data
prob.y = labels;
/*
for (int i = 0; i < prob.l; i++) {
double subset[dimensions];
for (int j = 0; j < dimensions; j++) {
subset[j] = dataset[i*dimensions+j];
}
double maximum = findMaximum();
}*/
svm_node** x = new svm_node*[prob.l];
for (int row = 0; row < prob.l; row++) {
svm_node* x_space = new svm_node[dimensions + 1];
for (int col = 0; col < dimensions; col++) {
x_space[col].index = col;
x_space[col].value = dataset[row*dimensions + col];
}
x_space[dimensions].index = -1; //Each row of properties should be terminated with a -1 according to the readme
x_space[dimensions].value = 0; //Value not important
x[row] = x_space;
}
prob.x = x;
//Train model
svm_model *model = svm_train(&prob, ¶m);
}
double test(const int dimensions, double testData[]) {
svm_node* testnode = new svm_node[dimensions+1];
for (int i = 0; i < dimensions; i++) {
testnode[i].index = i;
testnode[i].value = testData[i];
}
testnode[dimensions].index = -1;
testnode[dimensions].value = 0;
double retval = svm_predict(model, testnode);
svm_destroy_param(¶m);
delete[] prob.y;
delete[] prob.x;
delete[] x_space;
delete[] testnode;
return retval;
}<commit_msg>Corrected local/global variable bug.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include "svm_interface.h"
struct svm_parameter param; // set by parse_command_line
struct svm_problem prob; // set by read_problem
struct svm_model *model;
struct svm_node *x_space;
void train(const int problemSize, const int dimensions, double dataset[], double labels[]) {
/*
==================
Set all parameters
==================
*/
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0.5;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
/*
==================
Problem definition
==================
*/
//Set the number of training data
prob.l = problemSize;
//Set the array containing the labels of all training data
prob.y = labels;
/*
for (int i = 0; i < prob.l; i++) {
double subset[dimensions];
for (int j = 0; j < dimensions; j++) {
subset[j] = dataset[i*dimensions+j];
}
double maximum = findMaximum();
}*/
svm_node** x = new svm_node*[prob.l];
for (int row = 0; row < prob.l; row++) {
svm_node* x_space = new svm_node[dimensions + 1];
for (int col = 0; col < dimensions; col++) {
x_space[col].index = col;
x_space[col].value = dataset[row*dimensions + col];
}
x_space[dimensions].index = -1; //Each row of properties should be terminated with a -1 according to the readme
x_space[dimensions].value = 0; //Value not important
x[row] = x_space;
}
prob.x = x;
//Train model
model = svm_train(&prob, ¶m);
}
double test(const int dimensions, double testData[]) {
svm_node* testnode = new svm_node[dimensions+1];
for (int i = 0; i < dimensions; i++) {
testnode[i].index = i;
testnode[i].value = testData[i];
}
testnode[dimensions].index = -1;
testnode[dimensions].value = 0;
double retval = svm_predict(model, testnode);
svm_destroy_param(¶m);
delete[] prob.y;
delete[] prob.x;
delete[] x_space;
delete[] testnode;
return retval;
}<|endoftext|> |
<commit_before>#include "customermanagementform.hpp"
#include "ui_customermanagementform.h"
#include "../lib/db/connection.hpp"
CustomerManagementForm::CustomerManagementForm(QWidget *parent) :
QDialog(parent),
ui(new Ui::CustomerManagementForm)
{
ui->setupUi(this);
}
CustomerManagementForm::~CustomerManagementForm()
{
delete ui;
}
void CustomerManagementForm::on_btn_search_clicked()
{
QString keyword = ui->txt_keyword->text();
}
void CustomerManagementForm::on_btn_exit_clicked()
{
this->close();
}
<commit_msg>tablewidget back-end written<commit_after>#include "customermanagementform.hpp"
#include "ui_customermanagementform.h"
#include "../lib/db/connection.hpp"
#include "../lib/models/customer.hpp"
#include <QTableWidgetItem>
CustomerManagementForm::CustomerManagementForm(QWidget *parent) :
QDialog(parent),
ui(new Ui::CustomerManagementForm)
{
ui->setupUi(this);
}
CustomerManagementForm::~CustomerManagementForm()
{
delete ui;
}
void CustomerManagementForm::on_btn_search_clicked()
{
QString keyword = ui->txt_keyword->text();
CustomerList customerList = Connection::getConnection()->getCustomers(keyword);
ui->tbl_customers->setColumnCount(7);
ui->tbl_customers->setRowCount(customerList.size());
ui->tbl_customers->setHorizontalHeaderItem(0, new QTableWidgetItem("ID"));
ui->tbl_customers->setHorizontalHeaderItem(1, new QTableWidgetItem("TC"));
ui->tbl_customers->setHorizontalHeaderItem(2, new QTableWidgetItem("İsim"));
ui->tbl_customers->setHorizontalHeaderItem(3, new QTableWidgetItem("Soyisim"));
ui->tbl_customers->setHorizontalHeaderItem(4, new QTableWidgetItem("Telefon"));
ui->tbl_customers->setHorizontalHeaderItem(5, new QTableWidgetItem("Şehir"));
ui->tbl_customers->setHorizontalHeaderItem(6, new QTableWidgetItem("Adres"));
int i = 0;
foreach (Customer *c, customerList) {
ui->tbl_customers->setItem(i, 0, new QTableWidgetItem(QString::number(c->getId())));
ui->tbl_customers->setItem(i, 1, new QTableWidgetItem(c->getTc()));
ui->tbl_customers->setItem(i, 2, new QTableWidgetItem(c->getName()));
ui->tbl_customers->setItem(i, 3, new QTableWidgetItem(c->getSurname()));
ui->tbl_customers->setItem(i, 4, new QTableWidgetItem(c->getPhone()));
ui->tbl_customers->setItem(i, 5, new QTableWidgetItem(c->getCity()->getName()));
ui->tbl_customers->setItem(i, 6, new QTableWidgetItem(c->getAddress()));
i++;
}
}
void CustomerManagementForm::on_btn_exit_clicked()
{
this->close();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _TXTFTN_HXX
#define _TXTFTN_HXX
#include <txatbase.hxx>
class SwNodeIndex;
class SwTxtNode;
class SwNodes;
class SwDoc;
class SwFrm;
class OUString;
// ATT_FTN **********************************************************
class SW_DLLPUBLIC SwTxtFtn : public SwTxtAttr
{
SwNodeIndex * m_pStartNode;
SwTxtNode * m_pTxtNode;
sal_uInt16 m_nSeqNo;
public:
SwTxtFtn( SwFmtFtn& rAttr, xub_StrLen nStart );
virtual ~SwTxtFtn();
inline SwNodeIndex *GetStartNode() const { return m_pStartNode; }
void SetStartNode( const SwNodeIndex *pNode, sal_Bool bDelNodes = sal_True );
void SetNumber( const sal_uInt16 nNumber, const OUString &sNumStr );
void CopyFtn(SwTxtFtn & rDest, SwTxtNode & rDestNode) const;
// Get and set TxtNode pointer.
inline const SwTxtNode& GetTxtNode() const;
void ChgTxtNode( SwTxtNode* pNew ) { m_pTxtNode = pNew; }
// Create a new empty TextSection for this footnote.
void MakeNewTextSection( SwNodes& rNodes );
// Delete the FtnFrame from page.
void DelFrms( const SwFrm* );
// Check conditional paragraph styles.
void CheckCondColl();
// For references to footnotes.
sal_uInt16 SetSeqRefNo();
void SetSeqNo( sal_uInt16 n ) { m_nSeqNo = n; } // For Readers.
sal_uInt16 GetSeqRefNo() const { return m_nSeqNo; }
static void SetUniqueSeqRefNo( SwDoc& rDoc );
};
inline const SwTxtNode& SwTxtFtn::GetTxtNode() const
{
assert( m_pTxtNode );
return *m_pTxtNode;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>declare OUString in rtl namespace<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _TXTFTN_HXX
#define _TXTFTN_HXX
#include <txatbase.hxx>
namespace rtl { class OUString; }
class SwNodeIndex;
class SwTxtNode;
class SwNodes;
class SwDoc;
class SwFrm;
// ATT_FTN **********************************************************
class SW_DLLPUBLIC SwTxtFtn : public SwTxtAttr
{
SwNodeIndex * m_pStartNode;
SwTxtNode * m_pTxtNode;
sal_uInt16 m_nSeqNo;
public:
SwTxtFtn( SwFmtFtn& rAttr, xub_StrLen nStart );
virtual ~SwTxtFtn();
inline SwNodeIndex *GetStartNode() const { return m_pStartNode; }
void SetStartNode( const SwNodeIndex *pNode, sal_Bool bDelNodes = sal_True );
void SetNumber( const sal_uInt16 nNumber, const OUString &sNumStr );
void CopyFtn(SwTxtFtn & rDest, SwTxtNode & rDestNode) const;
// Get and set TxtNode pointer.
inline const SwTxtNode& GetTxtNode() const;
void ChgTxtNode( SwTxtNode* pNew ) { m_pTxtNode = pNew; }
// Create a new empty TextSection for this footnote.
void MakeNewTextSection( SwNodes& rNodes );
// Delete the FtnFrame from page.
void DelFrms( const SwFrm* );
// Check conditional paragraph styles.
void CheckCondColl();
// For references to footnotes.
sal_uInt16 SetSeqRefNo();
void SetSeqNo( sal_uInt16 n ) { m_nSeqNo = n; } // For Readers.
sal_uInt16 GetSeqRefNo() const { return m_nSeqNo; }
static void SetUniqueSeqRefNo( SwDoc& rDoc );
};
inline const SwTxtNode& SwTxtFtn::GetTxtNode() const
{
assert( m_pTxtNode );
return *m_pTxtNode;
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>SWAPLONG -> OSL_SWAPDWORD<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <string>
using namespace std;
typedef struct {
string left;
string right;
int result;
} Record;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
}
}
<commit_msg>p1013 WA<commit_after>#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#define MAX_COIN_NUM 12
using namespace std;
int coins[MAX_COIN_NUM];
int zero[MAX_COIN_NUM];
void set_record(string side, int value)
{
for (int i = 0, idx = 0; i < 4; i++)
{
idx = side[i] - 'A';
if (zero[idx])
{
coins[idx] += value;
}
}
}
int main()
{
int case_num = 0;
cin >> case_num;
for (int i = 0; i < case_num; i++)
{
memset(coins, 0, sizeof(int) * MAX_COIN_NUM);
memset(zero, 1, sizeof(int) * MAX_COIN_NUM);
for (int weighing_num = 0; weighing_num < 3; weighing_num++)
{
string left, right, result;
cin >> left >> right >> result;
int idx;
if (result == "even")
{
for (int i = 0; i < 4; i++)
{
idx = left[i] - 'A';
zero[idx] = 0;
coins[idx] = 0;
}
for (int i = 0; i < 4; i++)
{
idx = right[i] - 'A';
zero[idx] = 0;
coins[idx] = 0;
}
}
else if (result == "up")
{
set_record(left, 1);
set_record(right, -1);
}
else
{
set_record(left, -1);
set_record(right, 1);
}
}
int fake = 0;
int max_time = 0;
for (int j = 0; j < MAX_COIN_NUM; j++)
{
if (abs(coins[j]) > max_time)
{
max_time = abs(coins[j]);
fake = j;
}
}
if (coins[fake] > 0)
{
printf("%c is the counterfeit coin and it is heavy.\n",
(char)(fake + 'A'));
}
else if (coins[fake] < 0)
{
printf("%c is the counterfeit coin and it is light.\n",
(char)(fake + 'A'));
}
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "DispatchQueue.h"
#include "at_exit.h"
#include <assert.h>
using namespace autowiring;
DispatchQueue::DispatchQueue(void) {}
DispatchQueue::DispatchQueue(size_t dispatchCap):
m_dispatchCap(dispatchCap)
{}
DispatchQueue::DispatchQueue(DispatchQueue&& q):
onAborted(std::move(q.onAborted)),
m_dispatchCap(q.m_dispatchCap)
{
if (!onAborted)
*this += std::move(q);
}
DispatchQueue::~DispatchQueue(void) {
// Wipe out each entry in the queue, we can't call any of them because we're in teardown
for (auto cur = m_pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
}
}
bool DispatchQueue::PromoteReadyDispatchersUnsafe(void) {
// Move all ready elements out of the delayed queue and into the dispatch queue:
size_t nInitial = m_delayedQueue.size();
// String together a chain of things that will be made ready:
for (
auto now = std::chrono::steady_clock::now();
!m_delayedQueue.empty() && m_delayedQueue.top().GetReadyTime() < now;
m_delayedQueue.pop()
) {
// Update tail if head is already set, otherwise update head:
auto thunk = m_delayedQueue.top().GetThunk().release();
if (m_pHead)
m_pTail->m_pFlink = thunk;
else
m_pHead = thunk;
m_pTail = thunk;
m_count++;
}
// Something was promoted if the dispatch queue size is different
return nInitial != m_delayedQueue.size();
}
void DispatchQueue::DispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
std::unique_ptr<DispatchThunkBase> thunk(m_pHead);
m_pHead = thunk->m_pFlink;
lk.unlock();
MakeAtExit([&] {
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
}),
(*thunk)();
}
void DispatchQueue::TryDispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
DispatchThunkBase* pThunk = m_pHead;
m_pHead = pThunk->m_pFlink;
lk.unlock();
try { (*pThunk)(); }
catch (...) {
// Failed to execute thunk, put it back
lk.lock();
pThunk->m_pFlink = m_pHead;
m_pHead = pThunk;
throw;
}
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
delete pThunk;
}
void DispatchQueue::Abort(void) {
// Do not permit any more lambdas to be pended to our queue
DispatchThunkBase* pHead;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
onAborted();
m_dispatchCap = 0;
pHead = m_pHead;
m_pHead = nullptr;
m_pTail = nullptr;
}
// Destroy the whole dispatch queue. Do so in an unsynchronized context in order to prevent
// reentrancy.
size_t nTraversed = 0;
for (auto cur = pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
nTraversed++;
}
// Decrement the count by the number of entries we actually traversed. Abort may potentially
// be called from a lambda function, so assigning this value directly to zero would be an error.
m_count -= nTraversed;
// Wake up anyone who is still waiting:
m_queueUpdated.notify_all();
}
bool DispatchQueue::Cancel(void) {
// Holds the cancelled thunk, declared here so that we delete it out of the lock
std::unique_ptr<DispatchThunkBase> thunk;
std::lock_guard<std::mutex> lk(m_dispatchLock);
if(m_pHead) {
// Found a ready thunk, run from here:
thunk.reset(m_pHead);
m_pHead = thunk->m_pFlink;
}
else if (!m_delayedQueue.empty()) {
auto& f = m_delayedQueue.top();
thunk = std::move(f.GetThunk());
m_delayedQueue.pop();
}
else
// Nothing to cancel!
return false;
return true;
}
void DispatchQueue::WakeAllWaitingThreads(void) {
m_version++;
m_queueUpdated.notify_all();
}
void DispatchQueue::WaitForEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
// Unconditional delay:
uint64_t version = m_version;
m_queueUpdated.wait(
lk,
[this, version] {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
return
// We will need to transition out if the delay queue receives any items:
!this->m_delayedQueue.empty() ||
// We also transition out if the dispatch queue has any events:
this->m_pHead ||
// Or, finally, if the versions don't match
version != m_version;
}
);
if (m_pHead) {
// We have an event, we can just hop over to this variant:
DispatchEventUnsafe(lk);
return;
}
if (!m_delayedQueue.empty())
// The delay queue has items but the dispatch queue does not, we need to switch
// to the suggested sleep timeout variant:
WaitForEventUnsafe(lk, m_delayedQueue.top().GetReadyTime());
}
bool DispatchQueue::WaitForEvent(std::chrono::milliseconds milliseconds) {
return WaitForEvent(std::chrono::steady_clock::now() + milliseconds);
}
bool DispatchQueue::WaitForEvent(std::chrono::steady_clock::time_point wakeTime) {
if (wakeTime == std::chrono::steady_clock::time_point::max())
// Maximal wait--we can optimize by using the zero-arguments version
return WaitForEvent(), true;
std::unique_lock<std::mutex> lk(m_dispatchLock);
return WaitForEventUnsafe(lk, wakeTime);
}
bool DispatchQueue::WaitForEventUnsafe(std::unique_lock<std::mutex>& lk, std::chrono::steady_clock::time_point wakeTime) {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
while (!m_pHead) {
// Derive a wakeup time using the high precision timer:
wakeTime = SuggestSoonestWakeupTimeUnsafe(wakeTime);
// Now we wait, either for the timeout to elapse or for the dispatch queue itself to
// transition to the "aborted" state.
std::cv_status status = m_queueUpdated.wait_until(lk, wakeTime);
// Short-circuit if the queue was aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
if (PromoteReadyDispatchersUnsafe())
// Dispatcher is ready to run! Exit our loop and dispatch an event
break;
if (status == std::cv_status::timeout)
// Can't proceed, queue is empty and nobody is ready to be run
return false;
}
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::DispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// If the queue is empty and we fail to promote anything, return here
// Note that, due to short-circuiting, promotion will not take place if the queue is not empty.
// This behavior is by design.
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::TryDispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
TryDispatchEventUnsafe(lk);
return true;
}
int DispatchQueue::DispatchAllEvents(void) {
int retVal = 0;
while(DispatchEvent())
retVal++;
return retVal;
}
void DispatchQueue::PendExisting(std::unique_lock<std::mutex>&& lk, DispatchThunkBase* thunk) {
// Count must be separately maintained:
m_count++;
// Linked list setup:
if (m_pHead)
m_pTail->m_pFlink = thunk;
else {
m_pHead = thunk;
m_queueUpdated.notify_all();
}
m_pTail = thunk;
// Notification as needed:
OnPended(std::move(lk));
}
bool DispatchQueue::Barrier(std::chrono::nanoseconds timeout) {
// Short-circuit if zero is specified as the timeout value
if (!m_count && timeout.count() == 0)
return true;
// Now lock and double-check:
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Short-circuit if dispatching has been aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted before a timed wait was attempted");
// Set up the lambda. Note that the queue size CANNOT be 1, because we just checked to verify
// that it is non-empty. Thus, we do not need to signal the m_queueUpdated condition variable.
auto complete = std::make_shared<bool>(false);
auto lambda = [complete] { *complete = true; };
PendExisting(
std::move(lk),
new DispatchThunk<decltype(lambda)>(std::move(lambda))
);
if (!lk.owns_lock())
lk.lock();
// Wait until our variable is satisfied, which might be right away:
bool rv = m_queueUpdated.wait_for(lk, timeout, [&] { return onAborted || *complete; });
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted during a timed wait");
return rv;
}
void DispatchQueue::Barrier(void) {
// Set up the lambda:
bool complete = false;
*this += [&] { complete = true; };
// Obtain the lock, wait until our variable is satisfied, which might be right away:
std::unique_lock<std::mutex> lk(m_dispatchLock);
m_queueUpdated.wait(lk, [&] { return onAborted || complete; });
if (onAborted)
// At this point, the dispatch queue MUST be completely run down. We have no outstanding references
// to our stack-allocated "complete" variable. Furthermore, after m_aborted is true, no further
// dispatchers are permitted to be run.
throw dispatch_aborted_exception("Dispatch queue was aborted while a barrier was invoked");
}
std::chrono::steady_clock::time_point
DispatchQueue::SuggestSoonestWakeupTimeUnsafe(std::chrono::steady_clock::time_point latestTime) const {
return
m_delayedQueue.empty() ?
// Nothing in the queue, no way to suggest a shorter time
latestTime :
// Return the shorter of the maximum wait time and the time of the queue ready--we don't want to tell the
// caller to wait longer than the limit of their interest.
std::min(
m_delayedQueue.top().GetReadyTime(),
latestTime
);
}
void DispatchQueue::operator+=(DispatchQueue&& rhs) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Append thunks to our queue
if (m_pHead)
m_pTail->m_pFlink = rhs.m_pHead;
else
m_pHead = rhs.m_pHead;
m_pTail = rhs.m_pTail;
m_count += rhs.m_count;
// Clear queue from rhs
rhs.m_pHead = nullptr;
rhs.m_pTail = nullptr;
rhs.m_count = 0;
// Append delayed thunks
while (!rhs.m_delayedQueue.empty()) {
const auto& top = rhs.m_delayedQueue.top();
m_delayedQueue.emplace(top.GetReadyTime(), top.GetThunk().release());
rhs.m_delayedQueue.pop();
}
// Notification as needed:
m_queueUpdated.notify_all();
OnPended(std::move(lk));
}
DispatchQueue::DispatchThunkDelayedExpressionAbs DispatchQueue::operator+=(std::chrono::steady_clock::time_point rhs) {
return{this, rhs};
}
void DispatchQueue::operator+=(DispatchThunkDelayed&& rhs) {
bool shouldNotify;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
m_delayedQueue.push(std::forward<DispatchThunkDelayed>(rhs));
shouldNotify = m_delayedQueue.top().GetReadyTime() == rhs.GetReadyTime() && !m_count;
}
if(shouldNotify)
// We're becoming the new next-to-execute entity, dispatch queue currently empty, trigger wakeup
// so our newly pended delay thunk is eventually processed.
m_queueUpdated.notify_all();
}
<commit_msg>If the timeout is zero, do not acquire any locks whatsoever<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "DispatchQueue.h"
#include "at_exit.h"
#include <assert.h>
using namespace autowiring;
DispatchQueue::DispatchQueue(void) {}
DispatchQueue::DispatchQueue(size_t dispatchCap):
m_dispatchCap(dispatchCap)
{}
DispatchQueue::DispatchQueue(DispatchQueue&& q):
onAborted(std::move(q.onAborted)),
m_dispatchCap(q.m_dispatchCap)
{
if (!onAborted)
*this += std::move(q);
}
DispatchQueue::~DispatchQueue(void) {
// Wipe out each entry in the queue, we can't call any of them because we're in teardown
for (auto cur = m_pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
}
}
bool DispatchQueue::PromoteReadyDispatchersUnsafe(void) {
// Move all ready elements out of the delayed queue and into the dispatch queue:
size_t nInitial = m_delayedQueue.size();
// String together a chain of things that will be made ready:
for (
auto now = std::chrono::steady_clock::now();
!m_delayedQueue.empty() && m_delayedQueue.top().GetReadyTime() < now;
m_delayedQueue.pop()
) {
// Update tail if head is already set, otherwise update head:
auto thunk = m_delayedQueue.top().GetThunk().release();
if (m_pHead)
m_pTail->m_pFlink = thunk;
else
m_pHead = thunk;
m_pTail = thunk;
m_count++;
}
// Something was promoted if the dispatch queue size is different
return nInitial != m_delayedQueue.size();
}
void DispatchQueue::DispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
std::unique_ptr<DispatchThunkBase> thunk(m_pHead);
m_pHead = thunk->m_pFlink;
lk.unlock();
MakeAtExit([&] {
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
}),
(*thunk)();
}
void DispatchQueue::TryDispatchEventUnsafe(std::unique_lock<std::mutex>& lk) {
// Pull the ready thunk off of the front of the queue and pop it while we hold the lock.
// Then, we will excecute the call while the lock has been released so we do not create
// deadlocks.
DispatchThunkBase* pThunk = m_pHead;
m_pHead = pThunk->m_pFlink;
lk.unlock();
try { (*pThunk)(); }
catch (...) {
// Failed to execute thunk, put it back
lk.lock();
pThunk->m_pFlink = m_pHead;
m_pHead = pThunk;
throw;
}
if (!--m_count) {
// Notify that we have hit zero:
std::lock_guard<std::mutex>{ *lk.mutex() };
m_queueUpdated.notify_all();
}
delete pThunk;
}
void DispatchQueue::Abort(void) {
// Do not permit any more lambdas to be pended to our queue
DispatchThunkBase* pHead;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
onAborted();
m_dispatchCap = 0;
pHead = m_pHead;
m_pHead = nullptr;
m_pTail = nullptr;
}
// Destroy the whole dispatch queue. Do so in an unsynchronized context in order to prevent
// reentrancy.
size_t nTraversed = 0;
for (auto cur = pHead; cur;) {
auto next = cur->m_pFlink;
delete cur;
cur = next;
nTraversed++;
}
// Decrement the count by the number of entries we actually traversed. Abort may potentially
// be called from a lambda function, so assigning this value directly to zero would be an error.
m_count -= nTraversed;
// Wake up anyone who is still waiting:
m_queueUpdated.notify_all();
}
bool DispatchQueue::Cancel(void) {
// Holds the cancelled thunk, declared here so that we delete it out of the lock
std::unique_ptr<DispatchThunkBase> thunk;
std::lock_guard<std::mutex> lk(m_dispatchLock);
if(m_pHead) {
// Found a ready thunk, run from here:
thunk.reset(m_pHead);
m_pHead = thunk->m_pFlink;
}
else if (!m_delayedQueue.empty()) {
auto& f = m_delayedQueue.top();
thunk = std::move(f.GetThunk());
m_delayedQueue.pop();
}
else
// Nothing to cancel!
return false;
return true;
}
void DispatchQueue::WakeAllWaitingThreads(void) {
m_version++;
m_queueUpdated.notify_all();
}
void DispatchQueue::WaitForEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
// Unconditional delay:
uint64_t version = m_version;
m_queueUpdated.wait(
lk,
[this, version] {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
return
// We will need to transition out if the delay queue receives any items:
!this->m_delayedQueue.empty() ||
// We also transition out if the dispatch queue has any events:
this->m_pHead ||
// Or, finally, if the versions don't match
version != m_version;
}
);
if (m_pHead) {
// We have an event, we can just hop over to this variant:
DispatchEventUnsafe(lk);
return;
}
if (!m_delayedQueue.empty())
// The delay queue has items but the dispatch queue does not, we need to switch
// to the suggested sleep timeout variant:
WaitForEventUnsafe(lk, m_delayedQueue.top().GetReadyTime());
}
bool DispatchQueue::WaitForEvent(std::chrono::milliseconds milliseconds) {
return WaitForEvent(std::chrono::steady_clock::now() + milliseconds);
}
bool DispatchQueue::WaitForEvent(std::chrono::steady_clock::time_point wakeTime) {
if (wakeTime == std::chrono::steady_clock::time_point::max())
// Maximal wait--we can optimize by using the zero-arguments version
return WaitForEvent(), true;
std::unique_lock<std::mutex> lk(m_dispatchLock);
return WaitForEventUnsafe(lk, wakeTime);
}
bool DispatchQueue::WaitForEventUnsafe(std::unique_lock<std::mutex>& lk, std::chrono::steady_clock::time_point wakeTime) {
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted prior to waiting for an event");
while (!m_pHead) {
// Derive a wakeup time using the high precision timer:
wakeTime = SuggestSoonestWakeupTimeUnsafe(wakeTime);
// Now we wait, either for the timeout to elapse or for the dispatch queue itself to
// transition to the "aborted" state.
std::cv_status status = m_queueUpdated.wait_until(lk, wakeTime);
// Short-circuit if the queue was aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted while waiting for an event");
if (PromoteReadyDispatchersUnsafe())
// Dispatcher is ready to run! Exit our loop and dispatch an event
break;
if (status == std::cv_status::timeout)
// Can't proceed, queue is empty and nobody is ready to be run
return false;
}
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::DispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// If the queue is empty and we fail to promote anything, return here
// Note that, due to short-circuiting, promotion will not take place if the queue is not empty.
// This behavior is by design.
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
DispatchEventUnsafe(lk);
return true;
}
bool DispatchQueue::TryDispatchEvent(void) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
if (!m_pHead && !PromoteReadyDispatchersUnsafe())
return false;
TryDispatchEventUnsafe(lk);
return true;
}
int DispatchQueue::DispatchAllEvents(void) {
int retVal = 0;
while(DispatchEvent())
retVal++;
return retVal;
}
void DispatchQueue::PendExisting(std::unique_lock<std::mutex>&& lk, DispatchThunkBase* thunk) {
// Count must be separately maintained:
m_count++;
// Linked list setup:
if (m_pHead)
m_pTail->m_pFlink = thunk;
else {
m_pHead = thunk;
m_queueUpdated.notify_all();
}
m_pTail = thunk;
// Notification as needed:
OnPended(std::move(lk));
}
bool DispatchQueue::Barrier(std::chrono::nanoseconds timeout) {
// Do not block or lock in the event of a no-wait check
if (timeout.count() == 0)
return m_count == 0;
// Now lock and double-check:
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Short-circuit if dispatching has been aborted
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted before a timed wait was attempted");
// Set up the lambda. Note that the queue size CANNOT be 1, because we just checked to verify
// that it is non-empty. Thus, we do not need to signal the m_queueUpdated condition variable.
auto complete = std::make_shared<bool>(false);
auto lambda = [complete] { *complete = true; };
PendExisting(
std::move(lk),
new DispatchThunk<decltype(lambda)>(std::move(lambda))
);
if (!lk.owns_lock())
lk.lock();
// Wait until our variable is satisfied, which might be right away:
bool rv = m_queueUpdated.wait_for(lk, timeout, [&] { return onAborted || *complete; });
if (onAborted)
throw dispatch_aborted_exception("Dispatch queue was aborted during a timed wait");
return rv;
}
void DispatchQueue::Barrier(void) {
// Set up the lambda:
bool complete = false;
*this += [&] { complete = true; };
// Obtain the lock, wait until our variable is satisfied, which might be right away:
std::unique_lock<std::mutex> lk(m_dispatchLock);
m_queueUpdated.wait(lk, [&] { return onAborted || complete; });
if (onAborted)
// At this point, the dispatch queue MUST be completely run down. We have no outstanding references
// to our stack-allocated "complete" variable. Furthermore, after m_aborted is true, no further
// dispatchers are permitted to be run.
throw dispatch_aborted_exception("Dispatch queue was aborted while a barrier was invoked");
}
std::chrono::steady_clock::time_point
DispatchQueue::SuggestSoonestWakeupTimeUnsafe(std::chrono::steady_clock::time_point latestTime) const {
return
m_delayedQueue.empty() ?
// Nothing in the queue, no way to suggest a shorter time
latestTime :
// Return the shorter of the maximum wait time and the time of the queue ready--we don't want to tell the
// caller to wait longer than the limit of their interest.
std::min(
m_delayedQueue.top().GetReadyTime(),
latestTime
);
}
void DispatchQueue::operator+=(DispatchQueue&& rhs) {
std::unique_lock<std::mutex> lk(m_dispatchLock);
// Append thunks to our queue
if (m_pHead)
m_pTail->m_pFlink = rhs.m_pHead;
else
m_pHead = rhs.m_pHead;
m_pTail = rhs.m_pTail;
m_count += rhs.m_count;
// Clear queue from rhs
rhs.m_pHead = nullptr;
rhs.m_pTail = nullptr;
rhs.m_count = 0;
// Append delayed thunks
while (!rhs.m_delayedQueue.empty()) {
const auto& top = rhs.m_delayedQueue.top();
m_delayedQueue.emplace(top.GetReadyTime(), top.GetThunk().release());
rhs.m_delayedQueue.pop();
}
// Notification as needed:
m_queueUpdated.notify_all();
OnPended(std::move(lk));
}
DispatchQueue::DispatchThunkDelayedExpressionAbs DispatchQueue::operator+=(std::chrono::steady_clock::time_point rhs) {
return{this, rhs};
}
void DispatchQueue::operator+=(DispatchThunkDelayed&& rhs) {
bool shouldNotify;
{
std::lock_guard<std::mutex> lk(m_dispatchLock);
m_delayedQueue.push(std::forward<DispatchThunkDelayed>(rhs));
shouldNotify = m_delayedQueue.top().GetReadyTime() == rhs.GetReadyTime() && !m_count;
}
if(shouldNotify)
// We're becoming the new next-to-execute entity, dispatch queue currently empty, trigger wakeup
// so our newly pended delay thunk is eventually processed.
m_queueUpdated.notify_all();
}
<|endoftext|> |
<commit_before>#include "CoolProp.h"
#include <vector>
#include "CPExceptions.h"
#include "FluidClass.h"
#include "Ethanol.h"
EthanolClass::EthanolClass()
{
double n[]= {0, 5.8200796E-02, 9.4391227E-01, -8.0941908E-01, 5.5359038E-01, -1.4269032E+00, 1.3448717E-01, 4.2671978E-01, -1.1700261E+00, -9.2405872E-01, 3.4891808E-01, -9.1327720E-01, 2.2629481E-02, -1.5513423E-01, 2.1055146E-01, -2.1997690E-01, -6.5857238E-03, 7.5564749E-01, 1.0694110E-01, -6.9533844E-02, -2.4947395E-01, 2.7177891E-02, -9.0539530E-04, -1.2310953E-01, -8.9779710E-02, -3.9512601E-01};
double d[] = {0, 4, 1, 1, 2, 2, 3, 1, 1, 1, 3, 3, 2, 2, 6, 6, 8, 1, 1, 2, 3, 3, 2, 2, 2, 1};
double t[] = {0, 1.00, 1.04, 2.72, 1.174, 1.329, 0.195, 2.43, 1.274, 4.16, 3.30, 4.177, 2.50, 0.81, 2.02, 1.606, 0.86, 2.50, 3.72, 1.19, 3.25, 3.00, 2.00, 2.00, 1.00, 1.00};
double l[] = {0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double alpha[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.075, 0.463, 0.876, 1.108, 0.741, 4.032, 2.453, 2.300, 3.143};
double beta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.207, 0.0895, 0.581, 0.947, 2.356, 27.01, 4.542, 1.287, 3.090};
double gamma[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.194, 1.986, 1.583, 0.756, 0.495, 1.002, 1.077, 1.493, 1.542};
double epsilon[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.779, 0.805, 1.869, 0.694, 1.312, 2.054, 0.441, 0.793, 0.313};
// Critical parameters
crit.rho = 5.93*46.06844;
crit.p = 6268.0;
crit.T = 514.71;
crit.v = 1.0/crit.rho;
// Other fluid parameters
params.molemass = 46.06844;
params.Ttriple = 159.1;
params.ptriple = 7.2e-7;
params.accentricfactor = 0.644;
params.R_u = 8.314472;
// Limits of EOS
limits.Tmin = params.Ttriple;
limits.Tmax = 500.0;
limits.pmax = 100000.0;
limits.rhomax = 1000000.0*params.molemass;
// Residual part
phirlist.push_back(new phir_power(n,d,t,l,1,16,26));
phirlist.push_back(new phir_gaussian(n,d,t,alpha,epsilon,beta,gamma,17,25,26));
// Ideal-gas part
const double a[]={0.0, 3.43069, -12.7531, 9.39094, 2.14326, 5.09206, 6.60138, 5.70777};
const double b[]={0.0, 0, 0, 0, 0.816771, 2.59175, 3.80408, 8.58736};
std::vector<double> a_v(a, a+sizeof(a)/sizeof(double));
std::vector<double> b_v(b, b+sizeof(b)/sizeof(double));
//for (unsigned int i=1;i<v0_v.size();i++) { v0_v[i]/=crit.T; }
phi0list.push_back(new phi0_lead(a[2], a[3]));
phi0list.push_back(new phi0_logtau(a[1]));
phi0list.push_back(new phi0_Planck_Einstein(a_v,b_v,4,7));
EOSReference.assign("Schroeder Idaho Thesis, 2011");
TransportReference.assign("Using ECS");
name.assign("Ethanol");
aliases.push_back(std::string("C2H6O"));
REFPROPname.assign("ETHANOL");
BibTeXKeys.EOS = "Schroeder-MSTHESIS-2011";
BibTeXKeys.VISCOSITY = "Kiselev-IECR-2005";
BibTeXKeys.ECS_LENNARD_JONES = "Kiselev-IECR-2005";
BibTeXKeys.CONDUCTIVITY = "__Kiselev-IECR-2005";
BibTeXKeys.SURFACE_TENSION = "Mulero-JPCRD-2012";
}
double EthanolClass::psat(double T)
{
const double ti[]={0, 1.0, 1.5, 3.4, 3.7};
const double Ni[]={0, -8.94161, 1.61761, -51.1428, 53.1360};
double summer=0,theta;
int i;
theta=1-T/reduce.T;
for (i=1;i<=4;i++)
{
summer=summer+Ni[i]*pow(theta,ti[i]);
}
return reduce.p*exp(reduce.T/T*summer);
}
double EthanolClass::rhosatL(double T)
{
const double ti[] = {0, 0.5, 0.8, 1.1, 1.5, 3.3};
const double Ni[] = {0, 9.00921, -23.1668, 30.9092, -16.5459, 3.64294};
double summer=0;
int i;
double theta;
theta=1-T/reduce.T;
for (i=1;i<=5;i++)
{
summer += Ni[i]*pow(theta,ti[i]);
}
return reduce.rho*(summer+1);
}
double EthanolClass::rhosatV(double T)
{
const double ti[]={0, 0.21, 1.1, 3.4, 10.};
const double Ni[]={0, -1.75362, -10.5323, -37.6407, -129.762};
double summer=0,theta;
int i;
theta=1.0-T/reduce.T;
for (i=1; i<=4; i++)
{
summer=summer+Ni[i]*pow(theta,ti[i]);
}
return reduce.rho*exp(summer);
}
double EthanolClass::viscosity_Trho(double T, double rho)
{
double eta_0 = -1.03116 + 3.48379e-2*T - 6.50264e-6*T*T;
// Rainwater-Friend for initial density dependence
double e_k, sigma;
this->ECSParams(&e_k,&sigma);
double Tstar = T/e_k;
double b[] = {-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158};
double Bstar = b[0]*pow(Tstar,-0.25*0)+b[1]*pow(Tstar,-0.25*1)+b[2]*pow(Tstar,-0.25*2)+b[3]*pow(Tstar,-0.25*3)+b[4]*pow(Tstar,-0.25*4)+b[5]*pow(Tstar,-0.25*5)+b[6]*pow(Tstar,-0.25*6)+b[7]*pow(Tstar,-2.5)+b[8]*pow(Tstar,-5.5);
double N_A = 6.0221415e23;
double B = Bstar*N_A*sigma*sigma*sigma/1e27/1000;
double e[4][3]; // init with zeros
e[2][0] = 0.131194057;
e[2][1] = -0.382240694;
e[2][2] = 0;
e[3][0] = -0.0805700894;
e[3][1] = 0.153811778;
e[3][2] = -0.110578307;
double c1 = 23.7222995, c2 = -3.38264465, c3 = 12.7568864;
double sumresid = 0;
double tau = T/513.9, delta = rho/5.991/46.06844;
for (int j = 2; j<=3; j++)
{
for (int k = 0; k <= 2; k++)
{
sumresid += e[j][k]*pow(delta,j)/pow(tau,k);
}
}
double delta_0 = c2 + c3*sqrt(T/crit.T);
double eta_r = (sumresid + c1*(delta/(delta_0-delta)-delta/delta_0))*1000; // uPa-s
double rhobar = rho/params.molemass; // [mol/L]
return (eta_0*(1+B*rhobar)+eta_r)/1e6;
}
double EthanolClass::surface_tension_T(double T)
{
return 0.05*pow(1-T/reduce.T,0.952);
}<commit_msg>I think ethanol viscosity is working now, but not 100% sure<commit_after>#include "CoolProp.h"
#include <vector>
#include "CPExceptions.h"
#include "FluidClass.h"
#include "Ethanol.h"
EthanolClass::EthanolClass()
{
double n[]= {0, 5.8200796E-02, 9.4391227E-01, -8.0941908E-01, 5.5359038E-01, -1.4269032E+00, 1.3448717E-01, 4.2671978E-01, -1.1700261E+00, -9.2405872E-01, 3.4891808E-01, -9.1327720E-01, 2.2629481E-02, -1.5513423E-01, 2.1055146E-01, -2.1997690E-01, -6.5857238E-03, 7.5564749E-01, 1.0694110E-01, -6.9533844E-02, -2.4947395E-01, 2.7177891E-02, -9.0539530E-04, -1.2310953E-01, -8.9779710E-02, -3.9512601E-01};
double d[] = {0, 4, 1, 1, 2, 2, 3, 1, 1, 1, 3, 3, 2, 2, 6, 6, 8, 1, 1, 2, 3, 3, 2, 2, 2, 1};
double t[] = {0, 1.00, 1.04, 2.72, 1.174, 1.329, 0.195, 2.43, 1.274, 4.16, 3.30, 4.177, 2.50, 0.81, 2.02, 1.606, 0.86, 2.50, 3.72, 1.19, 3.25, 3.00, 2.00, 2.00, 1.00, 1.00};
double l[] = {0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 1, 2, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double alpha[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.075, 0.463, 0.876, 1.108, 0.741, 4.032, 2.453, 2.300, 3.143};
double beta[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.207, 0.0895, 0.581, 0.947, 2.356, 27.01, 4.542, 1.287, 3.090};
double gamma[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.194, 1.986, 1.583, 0.756, 0.495, 1.002, 1.077, 1.493, 1.542};
double epsilon[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.779, 0.805, 1.869, 0.694, 1.312, 2.054, 0.441, 0.793, 0.313};
// Critical parameters
crit.rho = 5.93*46.06844;
crit.p = 6268.0;
crit.T = 514.71;
crit.v = 1.0/crit.rho;
// Other fluid parameters
params.molemass = 46.06844;
params.Ttriple = 159.1;
params.ptriple = 7.2e-7;
params.accentricfactor = 0.644;
params.R_u = 8.314472;
// Limits of EOS
limits.Tmin = params.Ttriple;
limits.Tmax = 500.0;
limits.pmax = 100000.0;
limits.rhomax = 1000000.0*params.molemass;
// Residual part
phirlist.push_back(new phir_power(n,d,t,l,1,16,26));
phirlist.push_back(new phir_gaussian(n,d,t,alpha,epsilon,beta,gamma,17,25,26));
// Ideal-gas part
const double a[]={0.0, 3.43069, -12.7531, 9.39094, 2.14326, 5.09206, 6.60138, 5.70777};
const double b[]={0.0, 0, 0, 0, 0.816771, 2.59175, 3.80408, 8.58736};
std::vector<double> a_v(a, a+sizeof(a)/sizeof(double));
std::vector<double> b_v(b, b+sizeof(b)/sizeof(double));
//for (unsigned int i=1;i<v0_v.size();i++) { v0_v[i]/=crit.T; }
phi0list.push_back(new phi0_lead(a[2], a[3]));
phi0list.push_back(new phi0_logtau(a[1]));
phi0list.push_back(new phi0_Planck_Einstein(a_v,b_v,4,7));
EOSReference.assign("Schroeder Idaho Thesis, 2011");
TransportReference.assign("Using ECS");
name.assign("Ethanol");
aliases.push_back(std::string("C2H6O"));
REFPROPname.assign("ETHANOL");
BibTeXKeys.EOS = "Schroeder-MSTHESIS-2011";
BibTeXKeys.VISCOSITY = "Kiselev-IECR-2005";
BibTeXKeys.ECS_LENNARD_JONES = "Kiselev-IECR-2005";
BibTeXKeys.CONDUCTIVITY = "__Kiselev-IECR-2005";
BibTeXKeys.SURFACE_TENSION = "Mulero-JPCRD-2012";
}
double EthanolClass::psat(double T)
{
const double ti[]={0, 1.0, 1.5, 3.4, 3.7};
const double Ni[]={0, -8.94161, 1.61761, -51.1428, 53.1360};
double summer=0,theta;
int i;
theta=1-T/reduce.T;
for (i=1;i<=4;i++)
{
summer=summer+Ni[i]*pow(theta,ti[i]);
}
return reduce.p*exp(reduce.T/T*summer);
}
double EthanolClass::rhosatL(double T)
{
const double ti[] = {0, 0.5, 0.8, 1.1, 1.5, 3.3};
const double Ni[] = {0, 9.00921, -23.1668, 30.9092, -16.5459, 3.64294};
double summer=0;
int i;
double theta;
theta=1-T/reduce.T;
for (i=1;i<=5;i++)
{
summer += Ni[i]*pow(theta,ti[i]);
}
return reduce.rho*(summer+1);
}
double EthanolClass::rhosatV(double T)
{
const double ti[]={0, 0.21, 1.1, 3.4, 10.};
const double Ni[]={0, -1.75362, -10.5323, -37.6407, -129.762};
double summer=0,theta;
int i;
theta=1.0-T/reduce.T;
for (i=1; i<=4; i++)
{
summer=summer+Ni[i]*pow(theta,ti[i]);
}
return reduce.rho*exp(summer);
}
double EthanolClass::viscosity_Trho(double T, double rho)
{
double eta_0 = -1.03116 + 3.48379e-2*T - 6.50264e-6*T*T; //uPa-s
// Rainwater-Friend for initial density dependence
double e_k, sigma;
this->ECSParams(&e_k,&sigma);
double Tstar = T/e_k;
double b[] = {-19.572881, 219.73999, -1015.3226, 2471.01251, -3375.1717, 2491.6597, -787.26086, 14.085455, -0.34664158};
double Bstar = b[0]*pow(Tstar,-0.25*0)+b[1]*pow(Tstar,-0.25*1)+b[2]*pow(Tstar,-0.25*2)+b[3]*pow(Tstar,-0.25*3)+b[4]*pow(Tstar,-0.25*4)+b[5]*pow(Tstar,-0.25*5)+b[6]*pow(Tstar,-0.25*6)+b[7]*pow(Tstar,-2.5)+b[8]*pow(Tstar,-5.5);
double B = Bstar*0.60221415*sigma*sigma*sigma;
double e[4][3]; // init with zeros
e[2][0] = 0.131194057;
e[2][1] = -0.382240694;
e[2][2] = 0;
e[3][0] = -0.0805700894;
e[3][1] = 0.153811778;
e[3][2] = -0.110578307;
double c1 = 23.7222995, c2 = -3.38264465, c3 = 12.7568864;
double sumresid = 0;
double tau = T/513.9, delta = rho/(5.991*46.06844);
for (int j = 2; j<=3; j++)
{
for (int k = 0; k <= 2; k++)
{
sumresid += e[j][k]*pow(delta,j)/pow(tau,k);
}
}
double delta_0 = c2 + c3*sqrt(T/513.9);
double eta_r = (sumresid + c1*(delta/(delta_0-delta)-delta/delta_0))*1000; // uPa-s
double rhobar = rho/params.molemass; // [mol/L]
return (eta_0*(1+B*rhobar)+eta_r)/1e6;
}
double EthanolClass::surface_tension_T(double T)
{
return 0.05*pow(1-T/reduce.T,0.952);
}<|endoftext|> |
<commit_before>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"
//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif
using namespace MathLib;
class CSysControlLocal : public CSysControl
{
public:
CSysControlLocal();
virtual ~CSysControlLocal();
virtual void Init(); //角色要初始化,着色器要初始化,
virtual void Update(float ifps);
virtual void Shutdown();
virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。
virtual int ClearState(int state);
virtual float GetMouseDX();
virtual float GetMouseDY();
virtual void SetMouseGrab(int g); //设置是否显示鼠标
virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。
virtual void SetControlMode(ControlMode mode); //控制模式
virtual ControlMode GetControlMode() const; //获取控制模式
private:
void Update_Mouse(float ifps);
void Update_Keyboard(float ifps);
void Update_XPad360(float ifps);
CControlsApp *m_pControlsApp; //控制游戏中移动
CControlsXPad360 *m_pControlsXPad360;
ControlMode m_nControlMode; //控制模式
int m_nOldMouseX; //上一个鼠标坐标X
int m_nOldMouseY; //上一个鼠标坐标Y
CObjectGui *m_pTest3DUI;
CWidgetLabel *m_pTestMessageLabel;
};
CSysControlLocal::CSysControlLocal()
{
}
CSysControlLocal::~CSysControlLocal()
{
}
void CSysControlLocal::Init()
{
m_pControlsApp = new CControlsApp;
m_pControlsXPad360 = new CControlsXPad360(0);
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
SetControlMode(CONTROL_KEYBORAD_MOUSE);
m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
m_pTest3DUI->SetMouseShow(0);
m_pTest3DUI->SetBackground(1);
m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));
m_pTest3DUI->SetScreenSize(800, 400);
m_pTest3DUI->SetControlDistance(1000.0f);
m_pTest3DUI->CreateMaterial("gui_base"); //show in game
m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel->SetFontSize(80); //设置字体大小
m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓
m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");
void CSysControlLocal::Update(float ifps)
{
Update_Mouse(ifps);
Update_Keyboard(ifps);
Update_XPad360(ifps);
}
m_nOldMouseX = 0;
m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
delete m_pControlsApp;
m_pControlsApp = NULL;
delete m_pControlsXPad360;
m_pControlsXPad360 = NULL;
delete m_pTestMessageLabel;
m_pTestMessageLabel = NULL;
delete m_pTest3DUI;
m_pTest3DUI = NULL;
}
int CSysControlLocal::GetState(int state)
{
return m_pControlsApp->GetState(state);
}
int CSysControlLocal::ClearState(int state)
{
return m_pControlsApp->ClearState(state);
}
float CSysControlLocal::GetMouseDX()
{
return m_pControlsApp->GetMouseDX();
}
float CSysControlLocal::GetMouseDY()
{
return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
g_Engine.pApp->SetMouseGrab(g);
g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
return g_Engine.pApp->GetMouseGrab();
}
void CSysControlLocal::SetControlMode(ControlMode mode)
{
m_nControlMode = mode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快
float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢
m_pControlsApp->SetMouseDX(dx);
m_pControlsApp->SetMouseDY(dy);
if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
{
g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
}
m_nOldMouseX = g_Engine.pApp->GetMouseX();
m_nOldMouseY = g_Engine.pApp->GetMouseY();
}
void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad
{
if (g_Engine.pInput->IsKeyDown('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
if (g_Engine.pInput->IsKeyDown('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
if (g_Engine.pInput->IsKeyDown('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
if (g_Engine.pInput->IsKeyDown('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
if (g_Engine.pInput->IsKeyUp('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
else if (g_Engine.pInput->IsKeyUp('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
if (g_Engine.pInput->IsKeyUp('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
else if (g_Engine.pInput->IsKeyUp('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
m_pControlsXPad360->UpdateEvents();
CUtilStr strMessage;
strMessage = CUtilStr("测试3D UI\n"),
strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";
strMessage += CUtilStr::Format("\n手柄测试\n");
strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX());
strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY());
strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
strMessage += "\nTriggers:\n";
strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger());
strMessage += CUtilStr::Format("\nButtons:\n");
for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
{
strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
}
m_pTestMessageLabel->SetText(strMessage.Get());
const float fPadThreshold = 0.5f;
if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
else
{
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
}
if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
else
{
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
}
if (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
//update jump
// LT RT
if (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)
{
}
}<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"
//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif
using namespace MathLib;
class CSysControlLocal : public CSysControl
{
public:
CSysControlLocal();
virtual ~CSysControlLocal();
virtual void Init(); //角色要初始化,着色器要初始化,
virtual void Update(float ifps);
virtual void Shutdown();
virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。
virtual int ClearState(int state);
virtual float GetMouseDX();
virtual float GetMouseDY();
virtual void SetMouseGrab(int g); //设置是否显示鼠标
virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。
virtual void SetControlMode(ControlMode mode); //控制模式
virtual ControlMode GetControlMode() const; //获取控制模式
private:
void Update_Mouse(float ifps);
void Update_Keyboard(float ifps);
void Update_XPad360(float ifps);
CControlsApp *m_pControlsApp; //控制游戏中移动
CControlsXPad360 *m_pControlsXPad360;
ControlMode m_nControlMode; //控制模式
int m_nOldMouseX; //上一个鼠标坐标X
int m_nOldMouseY; //上一个鼠标坐标Y
CObjectGui *m_pTest3DUI;
CWidgetLabel *m_pTestMessageLabel;
};
CSysControlLocal::CSysControlLocal()
{
}
CSysControlLocal::~CSysControlLocal()
{
}
void CSysControlLocal::Init()
{
m_pControlsApp = new CControlsApp;
m_pControlsXPad360 = new CControlsXPad360(0);
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
SetControlMode(CONTROL_KEYBORAD_MOUSE);
m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
m_pTest3DUI->SetMouseShow(0);
m_pTest3DUI->SetBackground(1);
m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));
m_pTest3DUI->SetScreenSize(800, 400);
m_pTest3DUI->SetControlDistance(1000.0f);
m_pTest3DUI->CreateMaterial("gui_base"); //show in game
m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签
m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));
m_pTestMessageLabel->SetFontSize(80); //设置字体大小
m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓
m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");
void CSysControlLocal::Update(float ifps)
{
Update_Mouse(ifps);
Update_Keyboard(ifps);
Update_XPad360(ifps);
}
m_nOldMouseX = 0;
m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
g_Engine.pApp->SetMouseGrab(0);
g_Engine.pApp->SetMouseShow(0);
delete m_pControlsApp;
m_pControlsApp = NULL;
delete m_pControlsXPad360;
m_pControlsXPad360 = NULL;
delete m_pTestMessageLabel;
m_pTestMessageLabel = NULL;
delete m_pTest3DUI;
m_pTest3DUI = NULL;
}
int CSysControlLocal::GetState(int state)
{
return m_pControlsApp->GetState(state);
}
int CSysControlLocal::ClearState(int state)
{
return m_pControlsApp->ClearState(state);
}
float CSysControlLocal::GetMouseDX()
{
return m_pControlsApp->GetMouseDX();
}
float CSysControlLocal::GetMouseDY()
{
return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
g_Engine.pApp->SetMouseGrab(g);
g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
return g_Engine.pApp->GetMouseGrab();
}
void CSysControlLocal::SetControlMode(ControlMode mode)
{
m_nControlMode = mode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快
float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢
m_pControlsApp->SetMouseDX(dx);
m_pControlsApp->SetMouseDY(dy);
if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
{
g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
}
m_nOldMouseX = g_Engine.pApp->GetMouseX();
m_nOldMouseY = g_Engine.pApp->GetMouseY();
}
void CSysControlLocal::Update_Keyboard(float ifps) //键盘按键响应wsad
{
if (g_Engine.pInput->IsKeyDown('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
if (g_Engine.pInput->IsKeyDown('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
if (g_Engine.pInput->IsKeyDown('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
if (g_Engine.pInput->IsKeyDown('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
if (g_Engine.pInput->IsKeyUp('w'))
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
else if (g_Engine.pInput->IsKeyUp('s'))
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
if (g_Engine.pInput->IsKeyUp('a'))
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
else if (g_Engine.pInput->IsKeyUp('d'))
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
if (g_Engine.pInput->IsKeyDown(' ')) //空格跳跃
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
m_pControlsXPad360->UpdateEvents();
CUtilStr strMessage;
strMessage = CUtilStr("测试3D UI\n"),
strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";
strMessage += CUtilStr::Format("\n手柄测试\n");
strMessage += CUtilStr::Format("LeftX: %5.2f\n", m_pControlsXPad360->GetLeftX());
strMessage += CUtilStr::Format("LeftY: %5.2f\n", m_pControlsXPad360->GetLeftY());
strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
strMessage += "\nTriggers:\n";
strMessage += CUtilStr::Format("Left: %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
strMessage += CUtilStr::Format("Right: %5.2f\n", m_pControlsXPad360->GetRightTrigger());
strMessage += CUtilStr::Format("\nButtons:\n");
for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
{
strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
}
m_pTestMessageLabel->SetText(strMessage.Get());
const float fPadThreshold = 0.5f;
if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
else
{
m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
}
if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
else
{
m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
}
if (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))
m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
else
m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
//update jump
// LT RT
if (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)
{
m_pControlsApp->SetState(CControls::STATE_FIRE, 1);
}
}<|endoftext|> |
<commit_before>#include <QTimer>
#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"
namespace {
const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec
}
SINGLETON_IMPL(ServerStatusService)
ServerStatusService::ServerStatusService(QObject *parent)
: QObject(parent)
{
refresh_timer_ = new QTimer(this);
refresh_unconnected_timer_ = new QTimer(this);
connect(refresh_timer_, SIGNAL(timeout()),
this, SLOT(refresh()));
connect(refresh_unconnected_timer_, SIGNAL(timeout()),
this, SLOT(refreshUnconnected()));
refresh();
}
void ServerStatusService::start()
{
refresh_timer_->start(kRefreshInterval);
refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}
void ServerStatusService::stop()
{
refresh_timer_->stop();
refresh_unconnected_timer_->stop();
}
void ServerStatusService::refresh(bool only_refresh_unconnected)
{
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (int i = 0; i < accounts.size(); i++) {
const QUrl& url = accounts[i].serverUrl;
if (requests_.contains(url.host())) {
return;
}
if (only_refresh_unconnected && isServerConnected(url)) {
return;
}
pingServer(url);
}
}
void ServerStatusService::pingServer(const QUrl& url)
{
PingServerRequest *req = new PingServerRequest(url);
connect(req, SIGNAL(success()),
this, SLOT(onPingServerSuccess()));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onPingServerFailed()));
req->setIgnoreSslErrors(true);
req->send();
requests_[url.host()] = req;
}
void ServerStatusService::onPingServerSuccess()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), true);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
void ServerStatusService::onPingServerFailed()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), false);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
bool ServerStatusService::allServersConnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (!status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::allServersDisconnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::isServerConnected(const QUrl& url) const
{
return statuses_.value(url.host()).connected;
}
<commit_msg>set initial server statuses to unconnected<commit_after>#include <QTimer>
#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"
namespace {
const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec
}
SINGLETON_IMPL(ServerStatusService)
ServerStatusService::ServerStatusService(QObject *parent)
: QObject(parent)
{
refresh_timer_ = new QTimer(this);
refresh_unconnected_timer_ = new QTimer(this);
connect(refresh_timer_, SIGNAL(timeout()),
this, SLOT(refresh()));
connect(refresh_unconnected_timer_, SIGNAL(timeout()),
this, SLOT(refreshUnconnected()));
refresh();
}
void ServerStatusService::start()
{
refresh_timer_->start(kRefreshInterval);
refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}
void ServerStatusService::stop()
{
refresh_timer_->stop();
refresh_unconnected_timer_->stop();
}
void ServerStatusService::refresh(bool only_refresh_unconnected)
{
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (int i = 0; i < accounts.size(); i++) {
const QUrl& url = accounts[i].serverUrl;
if (requests_.contains(url.host())) {
return;
}
if (!statuses_.contains(url.host())) {
statuses_[url.host()] = ServerStatus(url, false);
}
if (only_refresh_unconnected && isServerConnected(url)) {
return;
}
pingServer(url);
}
}
void ServerStatusService::pingServer(const QUrl& url)
{
PingServerRequest *req = new PingServerRequest(url);
connect(req, SIGNAL(success()),
this, SLOT(onPingServerSuccess()));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onPingServerFailed()));
req->setIgnoreSslErrors(true);
req->send();
requests_[url.host()] = req;
}
void ServerStatusService::onPingServerSuccess()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), true);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
void ServerStatusService::onPingServerFailed()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), false);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
bool ServerStatusService::allServersConnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (!status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::allServersDisconnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::isServerConnected(const QUrl& url) const
{
return statuses_.value(url.host()).connected;
}
<|endoftext|> |
<commit_before>#include "server/api/url_parser.hpp"
#include "engine/polyline_compressor.hpp"
#include <boost/bind.hpp>
#include <boost/spirit/include/qi_char_.hpp>
#include <boost/spirit/include/qi_grammar.hpp>
#include <boost/spirit/include/qi_uint.hpp>
#include <boost/spirit/include/qi_real.hpp>
#include <boost/spirit/include/qi_lit.hpp>
#include <boost/spirit/include/qi_action.hpp>
#include <boost/spirit/include/qi_as_string.hpp>
#include <boost/spirit/include/qi_operator.hpp>
#include <boost/spirit/include/qi_plus.hpp>
namespace osrm
{
namespace server
{
namespace api
{
namespace
{
namespace qi = boost::spirit::qi;
using Iterator = std::string::iterator;
struct URLGrammar : boost::spirit::qi::grammar<Iterator>
{
URLGrammar() : URLGrammar::base_type(url_rule)
{
const auto set_service = [this](std::string &service)
{
parsed_url.service = std::move(service);
};
const auto set_version = [this](const unsigned version)
{
parsed_url.version = version;
};
const auto set_profile = [this](std::string &profile)
{
parsed_url.profile = std::move(profile);
};
const auto set_query = [this](std::string &query)
{
parsed_url.query = std::move(query);
};
alpha_numeral = qi::char_("a-zA-Z0-9");
polyline_chars = qi::char_("a-zA-Z0-9_.--[]{}@?|\\%~`^");
all_chars = polyline_chars | qi::char_("=,;:&().");
service_rule = +alpha_numeral;
version_rule = qi::uint_;
profile_rule = +alpha_numeral;
query_rule = +all_chars;
url_rule = qi::lit('/') >> service_rule[set_service] //
>> qi::lit('/') >> qi::lit('v') >> version_rule[set_version] //
>> qi::lit('/') >> profile_rule[set_profile] //
>> qi::lit('/') >> query_rule[set_query];
}
ParsedURL parsed_url;
qi::rule<Iterator> url_rule;
qi::rule<Iterator, std::string()> service_rule, profile_rule, query_rule;
qi::rule<Iterator, unsigned()> version_rule;
qi::rule<Iterator, char()> alpha_numeral, all_chars, polyline_chars;
};
}
boost::optional<ParsedURL> parseURL(std::string::iterator &iter, const std::string::iterator end)
{
boost::optional<ParsedURL> parsed_url;
URLGrammar grammar;
const auto result = boost::spirit::qi::parse(iter, end, grammar);
if (result && iter == end)
{
parsed_url = std::move(grammar.parsed_url);
}
return parsed_url;
}
}
}
}
<commit_msg>Do not move from references in grammar handlers<commit_after>#include "server/api/url_parser.hpp"
#include "engine/polyline_compressor.hpp"
#include <boost/bind.hpp>
#include <boost/spirit/include/qi_char_.hpp>
#include <boost/spirit/include/qi_grammar.hpp>
#include <boost/spirit/include/qi_uint.hpp>
#include <boost/spirit/include/qi_real.hpp>
#include <boost/spirit/include/qi_lit.hpp>
#include <boost/spirit/include/qi_action.hpp>
#include <boost/spirit/include/qi_as_string.hpp>
#include <boost/spirit/include/qi_operator.hpp>
#include <boost/spirit/include/qi_plus.hpp>
namespace osrm
{
namespace server
{
namespace api
{
namespace
{
namespace qi = boost::spirit::qi;
using Iterator = std::string::iterator;
struct URLGrammar : boost::spirit::qi::grammar<Iterator>
{
URLGrammar() : URLGrammar::base_type(url_rule)
{
const auto set_service = [this](std::string service)
{
parsed_url.service = std::move(service);
};
const auto set_version = [this](const unsigned version)
{
parsed_url.version = version;
};
const auto set_profile = [this](std::string profile)
{
parsed_url.profile = std::move(profile);
};
const auto set_query = [this](std::string query)
{
parsed_url.query = std::move(query);
};
alpha_numeral = qi::char_("a-zA-Z0-9");
polyline_chars = qi::char_("a-zA-Z0-9_.--[]{}@?|\\%~`^");
all_chars = polyline_chars | qi::char_("=,;:&().");
service_rule = +alpha_numeral;
version_rule = qi::uint_;
profile_rule = +alpha_numeral;
query_rule = +all_chars;
url_rule = qi::lit('/') >> service_rule[set_service] //
>> qi::lit('/') >> qi::lit('v') >> version_rule[set_version] //
>> qi::lit('/') >> profile_rule[set_profile] //
>> qi::lit('/') >> query_rule[set_query];
}
ParsedURL parsed_url;
qi::rule<Iterator> url_rule;
qi::rule<Iterator, std::string()> service_rule, profile_rule, query_rule;
qi::rule<Iterator, unsigned()> version_rule;
qi::rule<Iterator, char()> alpha_numeral, all_chars, polyline_chars;
};
}
boost::optional<ParsedURL> parseURL(std::string::iterator &iter, const std::string::iterator end)
{
boost::optional<ParsedURL> parsed_url;
URLGrammar grammar;
const auto result = boost::spirit::qi::parse(iter, end, grammar);
if (result && iter == end)
{
parsed_url = std::move(grammar.parsed_url);
}
return parsed_url;
}
}
}
}
<|endoftext|> |
<commit_before>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "swoole_server.h"
#include "swoole_memory.h"
namespace swoole {
using network::Socket;
static int ReactorProcess_loop(ProcessPool *pool, Worker *worker);
static int ReactorProcess_onPipeRead(Reactor *reactor, Event *event);
static int ReactorProcess_onClose(Reactor *reactor, Event *event);
static void ReactorProcess_onTimeout(Timer *timer, TimerNode *tnode);
#ifdef HAVE_REUSEPORT
static int ReactorProcess_reuse_port(ListenPort *ls);
#endif
static bool Server_is_single(Server *serv) {
return serv->worker_num == 1 && serv->task_worker_num == 0 && serv->max_request == 0 &&
serv->user_worker_list == nullptr;
}
int Server::create_reactor_processes() {
reactor_num = worker_num;
connection_list = (Connection *) sw_calloc(max_connection, sizeof(Connection));
if (connection_list == nullptr) {
swSysWarn("calloc[2](%d) failed", (int) (max_connection * sizeof(Connection)));
return SW_ERR;
}
return SW_OK;
}
void Server::destroy_reactor_processes() {
sw_free(connection_list);
}
int Server::start_reactor_processes() {
single_thread = 1;
// listen TCP
if (have_stream_sock == 1) {
for (auto ls : ports) {
if (ls->is_dgram()) {
continue;
}
#ifdef HAVE_REUSEPORT
if (enable_reuse_port) {
if (::close(ls->socket->fd) < 0) {
swSysWarn("close(%d) failed", ls->socket->fd);
}
delete ls->socket;
ls->socket = nullptr;
continue;
} else
#endif
{
// listen server socket
if (ls->listen() < 0) {
return SW_ERR;
}
}
}
}
ProcessPool *pool = &gs->event_workers;
if (ProcessPool::create(pool, worker_num, 0, SW_IPC_UNIXSOCK) < 0) {
return SW_ERR;
}
pool->set_max_request(max_request, max_request_grace);
/**
* store to ProcessPool object
*/
gs->event_workers.ptr = this;
gs->event_workers.max_wait_time = max_wait_time;
gs->event_workers.use_msgqueue = 0;
gs->event_workers.main_loop = ReactorProcess_loop;
gs->event_workers.onWorkerNotFound = Server::wait_other_worker;
SW_LOOP_N(worker_num) {
gs->event_workers.workers[i].pool = &gs->event_workers;
gs->event_workers.workers[i].id = i;
gs->event_workers.workers[i].type = SW_PROCESS_WORKER;
}
// single worker
if (Server_is_single(this)) {
int retval = ReactorProcess_loop(&gs->event_workers, &gs->event_workers.workers[0]);
if (retval == SW_OK) {
gs->event_workers.destroy();
}
return retval;
}
SW_LOOP_N(worker_num) {
create_worker(&gs->event_workers.workers[i]);
}
// task workers
if (task_worker_num > 0) {
if (create_task_workers() < 0) {
return SW_ERR;
}
if (gs->task_workers.start() < 0) {
return SW_ERR;
}
}
/**
* create user worker process
*/
if (user_worker_list) {
user_workers = (Worker *) sw_shm_calloc(user_worker_num, sizeof(Worker));
if (user_workers == nullptr) {
swSysWarn("gmalloc[server->user_workers] failed");
return SW_ERR;
}
for (auto worker : *user_worker_list) {
/**
* store the pipe object
*/
if (worker->pipe_object) {
store_pipe_fd(worker->pipe_object);
}
spawn_user_worker(worker);
}
}
/**
* manager process is the same as the master process
*/
SwooleG.pid = gs->manager_pid = getpid();
SwooleG.process_type = SW_PROCESS_MANAGER;
/**
* manager process can not use signalfd
*/
SwooleG.use_signalfd = 0;
gs->event_workers.start();
init_signal_handler();
if (onStart) {
swWarn("The onStart event with SWOOLE_BASE is deprecated");
onStart(this);
}
if (onManagerStart) {
onManagerStart(this);
}
gs->event_workers.wait();
gs->event_workers.shutdown();
kill_user_workers();
if (onManagerStop) {
onManagerStop(this);
}
SW_LOOP_N(worker_num) {
destroy_worker(&gs->event_workers.workers[i]);
}
return SW_OK;
}
static int ReactorProcess_onPipeRead(Reactor *reactor, Event *event) {
EventData task;
SendData _send;
Server *serv = (Server *) reactor->ptr;
Factory *factory = serv->factory;
String *output_buffer;
ssize_t retval = read(event->fd, &task, sizeof(task));
if (retval <= 0) {
return SW_ERR;
} else if ((size_t) retval != task.info.len + sizeof(_send.info)) {
swWarn("bad pipeline data");
return SW_OK;
}
switch (task.info.type) {
case SW_SERVER_EVENT_PIPE_MESSAGE:
serv->onPipeMessage(serv, &task);
break;
case SW_SERVER_EVENT_FINISH:
serv->onFinish(serv, &task);
break;
case SW_SERVER_EVENT_SEND_FILE:
_send.info = task.info;
_send.data = task.data;
factory->finish(&_send);
break;
case SW_SERVER_EVENT_PROXY_START:
case SW_SERVER_EVENT_PROXY_END:
if (task.info.reactor_id < 0 || task.info.reactor_id >= serv->get_all_worker_num()) {
swWarn("invalid worker_id=%d", task.info.reactor_id);
return SW_OK;
}
output_buffer = SwooleWG.output_buffer[task.info.reactor_id];
output_buffer->append(task.data, task.info.len);
if (task.info.type == SW_SERVER_EVENT_PROXY_END) {
memcpy(&_send.info, &task.info, sizeof(_send.info));
_send.info.type = SW_SERVER_EVENT_RECV_DATA;
_send.data = output_buffer->str;
_send.info.len = output_buffer->length;
factory->finish(&_send);
output_buffer->clear();
}
break;
default:
break;
}
return SW_OK;
}
static int ReactorProcess_alloc_output_buffer(size_t n_buffer) {
SwooleWG.output_buffer = (String **) sw_malloc(sizeof(String *) * n_buffer);
if (SwooleWG.output_buffer == nullptr) {
swError("malloc for SwooleWG.output_buffer failed");
return SW_ERR;
}
SW_LOOP_N(n_buffer) {
SwooleWG.output_buffer[i] = new String(SW_BUFFER_SIZE_BIG);
if (SwooleWG.output_buffer[i] == nullptr) {
swError("output_buffer init failed");
return SW_ERR;
}
}
return SW_OK;
}
static void ReactorProcess_free_output_buffer(size_t n_buffer) {
SW_LOOP_N(n_buffer) {
delete SwooleWG.output_buffer[i];
}
sw_free(SwooleWG.output_buffer);
}
static int ReactorProcess_loop(ProcessPool *pool, Worker *worker) {
Server *serv = (Server *) pool->ptr;
SwooleG.process_type = SW_PROCESS_WORKER;
SwooleG.pid = getpid();
SwooleG.process_id = worker->id;
if (serv->max_request > 0) {
SwooleWG.run_always = false;
}
SwooleWG.max_request = serv->max_request;
SwooleWG.worker = worker;
SwooleTG.id = 0;
if (worker->id == 0) {
SwooleTG.update_time = 1;
}
serv->init_worker(worker);
// create reactor
if (!SwooleTG.reactor) {
if (swoole_event_init(0) < 0) {
return SW_ERR;
}
}
Reactor *reactor = SwooleTG.reactor;
if (SwooleTG.timer && SwooleTG.timer->get_reactor() == nullptr) {
SwooleTG.timer->reinit(reactor);
}
size_t n_buffer = serv->get_all_worker_num();
if (ReactorProcess_alloc_output_buffer(n_buffer)) {
return SW_ERR;
}
for (auto ls : serv->ports) {
#ifdef HAVE_REUSEPORT
if (ls->is_stream() && serv->enable_reuse_port) {
if (ReactorProcess_reuse_port(ls) < 0) {
ReactorProcess_free_output_buffer(n_buffer);
swoole_event_free();
return SW_ERR;
}
}
#endif
if (reactor->add(ls->socket, SW_EVENT_READ) < 0) {
return SW_ERR;
}
}
reactor->id = worker->id;
reactor->ptr = serv;
#ifdef HAVE_SIGNALFD
if (SwooleG.use_signalfd) {
swSignalfd_setup(SwooleTG.reactor);
}
#endif
reactor->max_socket = serv->get_max_connection();
reactor->close = Server::close_connection;
// set event handler
// connect
reactor->set_handler(SW_FD_STREAM_SERVER, Server::accept_connection);
// close
reactor->default_error_handler = ReactorProcess_onClose;
// pipe
reactor->set_handler(SW_FD_PIPE | SW_EVENT_READ, ReactorProcess_onPipeRead);
serv->store_listen_socket();
if (worker->pipe_worker) {
worker->pipe_worker->set_nonblock();
worker->pipe_master->set_nonblock();
if (reactor->add(worker->pipe_worker, SW_EVENT_READ) < 0) {
return SW_ERR;
}
if (reactor->add(worker->pipe_master, SW_EVENT_READ) < 0) {
return SW_ERR;
}
}
// task workers
if (serv->task_worker_num > 0) {
if (serv->task_ipc_mode == SW_TASK_IPC_UNIXSOCK) {
for (uint32_t i = 0; i < serv->gs->task_workers.worker_num; i++) {
serv->gs->task_workers.workers[i].pipe_master->set_nonblock();
}
}
}
serv->init_reactor(reactor);
// single server trigger onStart event
if (Server_is_single(serv)) {
if (serv->onStart) {
serv->onStart(serv);
}
}
/**
* 1 second timer
*/
if ((serv->master_timer = swoole_timer_add(1000, true, Server::timer_callback, serv)) == nullptr) {
_fail:
ReactorProcess_free_output_buffer(n_buffer);
swoole_event_free();
return SW_ERR;
}
serv->worker_start_callback();
/**
* for heartbeat check
*/
if (serv->heartbeat_check_interval > 0) {
serv->heartbeat_timer =
swoole_timer_add((long) (serv->heartbeat_check_interval * 1000), true, ReactorProcess_onTimeout, reactor);
if (serv->heartbeat_timer == nullptr) {
goto _fail;
}
}
int retval = reactor->wait(nullptr);
/**
* Close all connections
*/
serv->foreach_connection([serv](Connection *conn) { serv->close(conn->session_id, true); });
/**
* call internal serv hooks
*/
if (serv->hooks[Server::HOOK_WORKER_CLOSE]) {
void *hook_args[2];
hook_args[0] = serv;
hook_args[1] = (void *) (uintptr_t) SwooleG.process_id;
serv->call_hook(Server::HOOK_WORKER_CLOSE, hook_args);
}
swoole_event_free();
serv->worker_stop_callback();
ReactorProcess_free_output_buffer(n_buffer);
return retval;
}
static int ReactorProcess_onClose(Reactor *reactor, Event *event) {
int fd = event->fd;
Server *serv = (Server *) reactor->ptr;
Connection *conn = serv->get_connection(fd);
if (conn == nullptr || conn->active == 0) {
return SW_ERR;
}
if (event->socket->removed) {
return Server::close_connection(reactor, event->socket);
}
if (reactor->del(event->socket) == 0) {
if (conn->close_queued) {
return Server::close_connection(reactor, event->socket);
} else {
return serv->notify(conn, SW_SERVER_EVENT_CLOSE) ? SW_OK : SW_ERR;
}
} else {
return SW_ERR;
}
}
static void ReactorProcess_onTimeout(Timer *timer, TimerNode *tnode) {
Reactor *reactor = (Reactor *) tnode->data;
Server *serv = (Server *) reactor->ptr;
Event notify_ev{};
double now = swoole_microtime();
if (now < serv->heartbeat_check_lasttime + 10) {
return;
}
notify_ev.type = SW_FD_SESSION;
int checktime = now - serv->heartbeat_idle_time;
serv->foreach_connection([serv, checktime, reactor, ¬ify_ev](Connection *conn) {
if (conn->protect || conn->last_recv_time > checktime) {
return;
}
#ifdef SW_USE_OPENSSL
if (conn->socket->ssl && conn->socket->ssl_state != SW_SSL_STATE_READY) {
Server::close_connection(reactor, conn->socket);
return;
}
#endif
if (serv->disable_notify || conn->close_force) {
Server::close_connection(reactor, conn->socket);
return;
}
conn->close_force = 1;
notify_ev.fd = conn->fd;
notify_ev.socket = conn->socket;
notify_ev.reactor_id = conn->reactor_id;
ReactorProcess_onClose(reactor, ¬ify_ev);
});
}
#ifdef HAVE_REUSEPORT
static int ReactorProcess_reuse_port(ListenPort *ls) {
ls->socket = swoole::make_socket(
ls->type, ls->is_dgram() ? SW_FD_DGRAM_SERVER : SW_FD_STREAM_SERVER, SW_SOCK_CLOEXEC | SW_SOCK_NONBLOCK);
if (ls->socket->set_reuse_port() < 0) {
ls->socket->free();
return SW_ERR;
}
if (ls->socket->bind(ls->host, &ls->port) < 0) {
ls->socket->free();
return SW_ERR;
}
return ls->listen();
}
#endif
} // namespace swoole
<commit_msg>Warning free<commit_after>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "swoole_server.h"
#include "swoole_memory.h"
namespace swoole {
using network::Socket;
static int ReactorProcess_loop(ProcessPool *pool, Worker *worker);
static int ReactorProcess_onPipeRead(Reactor *reactor, Event *event);
static int ReactorProcess_onClose(Reactor *reactor, Event *event);
static void ReactorProcess_onTimeout(Timer *timer, TimerNode *tnode);
#ifdef HAVE_REUSEPORT
static int ReactorProcess_reuse_port(ListenPort *ls);
#endif
static bool Server_is_single(Server *serv) {
return serv->worker_num == 1 && serv->task_worker_num == 0 && serv->max_request == 0 &&
serv->user_worker_list == nullptr;
}
int Server::create_reactor_processes() {
reactor_num = worker_num;
connection_list = (Connection *) sw_calloc(max_connection, sizeof(Connection));
if (connection_list == nullptr) {
swSysWarn("calloc[2](%d) failed", (int) (max_connection * sizeof(Connection)));
return SW_ERR;
}
return SW_OK;
}
void Server::destroy_reactor_processes() {
sw_free(connection_list);
}
int Server::start_reactor_processes() {
single_thread = 1;
// listen TCP
if (have_stream_sock == 1) {
for (auto ls : ports) {
if (ls->is_dgram()) {
continue;
}
#ifdef HAVE_REUSEPORT
if (enable_reuse_port) {
if (::close(ls->socket->fd) < 0) {
swSysWarn("close(%d) failed", ls->socket->fd);
}
delete ls->socket;
ls->socket = nullptr;
continue;
} else
#endif
{
// listen server socket
if (ls->listen() < 0) {
return SW_ERR;
}
}
}
}
ProcessPool *pool = &gs->event_workers;
if (ProcessPool::create(pool, worker_num, 0, SW_IPC_UNIXSOCK) < 0) {
return SW_ERR;
}
pool->set_max_request(max_request, max_request_grace);
/**
* store to ProcessPool object
*/
gs->event_workers.ptr = this;
gs->event_workers.max_wait_time = max_wait_time;
gs->event_workers.use_msgqueue = 0;
gs->event_workers.main_loop = ReactorProcess_loop;
gs->event_workers.onWorkerNotFound = Server::wait_other_worker;
SW_LOOP_N(worker_num) {
gs->event_workers.workers[i].pool = &gs->event_workers;
gs->event_workers.workers[i].id = i;
gs->event_workers.workers[i].type = SW_PROCESS_WORKER;
}
// single worker
if (Server_is_single(this)) {
int retval = ReactorProcess_loop(&gs->event_workers, &gs->event_workers.workers[0]);
if (retval == SW_OK) {
gs->event_workers.destroy();
}
return retval;
}
SW_LOOP_N(worker_num) {
create_worker(&gs->event_workers.workers[i]);
}
// task workers
if (task_worker_num > 0) {
if (create_task_workers() < 0) {
return SW_ERR;
}
if (gs->task_workers.start() < 0) {
return SW_ERR;
}
}
/**
* create user worker process
*/
if (user_worker_list) {
user_workers = (Worker *) sw_shm_calloc(user_worker_num, sizeof(Worker));
if (user_workers == nullptr) {
swSysWarn("gmalloc[server->user_workers] failed");
return SW_ERR;
}
for (auto worker : *user_worker_list) {
/**
* store the pipe object
*/
if (worker->pipe_object) {
store_pipe_fd(worker->pipe_object);
}
spawn_user_worker(worker);
}
}
/**
* manager process is the same as the master process
*/
SwooleG.pid = gs->manager_pid = getpid();
SwooleG.process_type = SW_PROCESS_MANAGER;
/**
* manager process can not use signalfd
*/
SwooleG.use_signalfd = 0;
gs->event_workers.start();
init_signal_handler();
if (onStart) {
swWarn("The onStart event with SWOOLE_BASE is deprecated");
onStart(this);
}
if (onManagerStart) {
onManagerStart(this);
}
gs->event_workers.wait();
gs->event_workers.shutdown();
kill_user_workers();
if (onManagerStop) {
onManagerStop(this);
}
SW_LOOP_N(worker_num) {
destroy_worker(&gs->event_workers.workers[i]);
}
return SW_OK;
}
static int ReactorProcess_onPipeRead(Reactor *reactor, Event *event) {
EventData task;
SendData _send;
Server *serv = (Server *) reactor->ptr;
Factory *factory = serv->factory;
String *output_buffer;
ssize_t retval = read(event->fd, &task, sizeof(task));
if (retval <= 0) {
return SW_ERR;
} else if ((size_t) retval != task.info.len + sizeof(_send.info)) {
swWarn("bad pipeline data");
return SW_OK;
}
switch (task.info.type) {
case SW_SERVER_EVENT_PIPE_MESSAGE:
serv->onPipeMessage(serv, &task);
break;
case SW_SERVER_EVENT_FINISH:
serv->onFinish(serv, &task);
break;
case SW_SERVER_EVENT_SEND_FILE:
_send.info = task.info;
_send.data = task.data;
factory->finish(&_send);
break;
case SW_SERVER_EVENT_PROXY_START:
case SW_SERVER_EVENT_PROXY_END:
if (task.info.reactor_id < 0 || task.info.reactor_id >= (int16_t) serv->get_all_worker_num()) {
swWarn("invalid worker_id=%d", task.info.reactor_id);
return SW_OK;
}
output_buffer = SwooleWG.output_buffer[task.info.reactor_id];
output_buffer->append(task.data, task.info.len);
if (task.info.type == SW_SERVER_EVENT_PROXY_END) {
memcpy(&_send.info, &task.info, sizeof(_send.info));
_send.info.type = SW_SERVER_EVENT_RECV_DATA;
_send.data = output_buffer->str;
_send.info.len = output_buffer->length;
factory->finish(&_send);
output_buffer->clear();
}
break;
default:
break;
}
return SW_OK;
}
static int ReactorProcess_alloc_output_buffer(size_t n_buffer) {
SwooleWG.output_buffer = (String **) sw_malloc(sizeof(String *) * n_buffer);
if (SwooleWG.output_buffer == nullptr) {
swError("malloc for SwooleWG.output_buffer failed");
return SW_ERR;
}
SW_LOOP_N(n_buffer) {
SwooleWG.output_buffer[i] = new String(SW_BUFFER_SIZE_BIG);
if (SwooleWG.output_buffer[i] == nullptr) {
swError("output_buffer init failed");
return SW_ERR;
}
}
return SW_OK;
}
static void ReactorProcess_free_output_buffer(size_t n_buffer) {
SW_LOOP_N(n_buffer) {
delete SwooleWG.output_buffer[i];
}
sw_free(SwooleWG.output_buffer);
}
static int ReactorProcess_loop(ProcessPool *pool, Worker *worker) {
Server *serv = (Server *) pool->ptr;
SwooleG.process_type = SW_PROCESS_WORKER;
SwooleG.pid = getpid();
SwooleG.process_id = worker->id;
if (serv->max_request > 0) {
SwooleWG.run_always = false;
}
SwooleWG.max_request = serv->max_request;
SwooleWG.worker = worker;
SwooleTG.id = 0;
if (worker->id == 0) {
SwooleTG.update_time = 1;
}
serv->init_worker(worker);
// create reactor
if (!SwooleTG.reactor) {
if (swoole_event_init(0) < 0) {
return SW_ERR;
}
}
Reactor *reactor = SwooleTG.reactor;
if (SwooleTG.timer && SwooleTG.timer->get_reactor() == nullptr) {
SwooleTG.timer->reinit(reactor);
}
size_t n_buffer = serv->get_all_worker_num();
if (ReactorProcess_alloc_output_buffer(n_buffer)) {
return SW_ERR;
}
for (auto ls : serv->ports) {
#ifdef HAVE_REUSEPORT
if (ls->is_stream() && serv->enable_reuse_port) {
if (ReactorProcess_reuse_port(ls) < 0) {
ReactorProcess_free_output_buffer(n_buffer);
swoole_event_free();
return SW_ERR;
}
}
#endif
if (reactor->add(ls->socket, SW_EVENT_READ) < 0) {
return SW_ERR;
}
}
reactor->id = worker->id;
reactor->ptr = serv;
#ifdef HAVE_SIGNALFD
if (SwooleG.use_signalfd) {
swSignalfd_setup(SwooleTG.reactor);
}
#endif
reactor->max_socket = serv->get_max_connection();
reactor->close = Server::close_connection;
// set event handler
// connect
reactor->set_handler(SW_FD_STREAM_SERVER, Server::accept_connection);
// close
reactor->default_error_handler = ReactorProcess_onClose;
// pipe
reactor->set_handler(SW_FD_PIPE | SW_EVENT_READ, ReactorProcess_onPipeRead);
serv->store_listen_socket();
if (worker->pipe_worker) {
worker->pipe_worker->set_nonblock();
worker->pipe_master->set_nonblock();
if (reactor->add(worker->pipe_worker, SW_EVENT_READ) < 0) {
return SW_ERR;
}
if (reactor->add(worker->pipe_master, SW_EVENT_READ) < 0) {
return SW_ERR;
}
}
// task workers
if (serv->task_worker_num > 0) {
if (serv->task_ipc_mode == SW_TASK_IPC_UNIXSOCK) {
for (uint32_t i = 0; i < serv->gs->task_workers.worker_num; i++) {
serv->gs->task_workers.workers[i].pipe_master->set_nonblock();
}
}
}
serv->init_reactor(reactor);
// single server trigger onStart event
if (Server_is_single(serv)) {
if (serv->onStart) {
serv->onStart(serv);
}
}
/**
* 1 second timer
*/
if ((serv->master_timer = swoole_timer_add(1000, true, Server::timer_callback, serv)) == nullptr) {
_fail:
ReactorProcess_free_output_buffer(n_buffer);
swoole_event_free();
return SW_ERR;
}
serv->worker_start_callback();
/**
* for heartbeat check
*/
if (serv->heartbeat_check_interval > 0) {
serv->heartbeat_timer =
swoole_timer_add((long) (serv->heartbeat_check_interval * 1000), true, ReactorProcess_onTimeout, reactor);
if (serv->heartbeat_timer == nullptr) {
goto _fail;
}
}
int retval = reactor->wait(nullptr);
/**
* Close all connections
*/
serv->foreach_connection([serv](Connection *conn) { serv->close(conn->session_id, true); });
/**
* call internal serv hooks
*/
if (serv->hooks[Server::HOOK_WORKER_CLOSE]) {
void *hook_args[2];
hook_args[0] = serv;
hook_args[1] = (void *) (uintptr_t) SwooleG.process_id;
serv->call_hook(Server::HOOK_WORKER_CLOSE, hook_args);
}
swoole_event_free();
serv->worker_stop_callback();
ReactorProcess_free_output_buffer(n_buffer);
return retval;
}
static int ReactorProcess_onClose(Reactor *reactor, Event *event) {
int fd = event->fd;
Server *serv = (Server *) reactor->ptr;
Connection *conn = serv->get_connection(fd);
if (conn == nullptr || conn->active == 0) {
return SW_ERR;
}
if (event->socket->removed) {
return Server::close_connection(reactor, event->socket);
}
if (reactor->del(event->socket) == 0) {
if (conn->close_queued) {
return Server::close_connection(reactor, event->socket);
} else {
return serv->notify(conn, SW_SERVER_EVENT_CLOSE) ? SW_OK : SW_ERR;
}
} else {
return SW_ERR;
}
}
static void ReactorProcess_onTimeout(Timer *timer, TimerNode *tnode) {
Reactor *reactor = (Reactor *) tnode->data;
Server *serv = (Server *) reactor->ptr;
Event notify_ev{};
double now = swoole_microtime();
if (now < serv->heartbeat_check_lasttime + 10) {
return;
}
notify_ev.type = SW_FD_SESSION;
int checktime = now - serv->heartbeat_idle_time;
serv->foreach_connection([serv, checktime, reactor, ¬ify_ev](Connection *conn) {
if (conn->protect || conn->last_recv_time > checktime) {
return;
}
#ifdef SW_USE_OPENSSL
if (conn->socket->ssl && conn->socket->ssl_state != SW_SSL_STATE_READY) {
Server::close_connection(reactor, conn->socket);
return;
}
#endif
if (serv->disable_notify || conn->close_force) {
Server::close_connection(reactor, conn->socket);
return;
}
conn->close_force = 1;
notify_ev.fd = conn->fd;
notify_ev.socket = conn->socket;
notify_ev.reactor_id = conn->reactor_id;
ReactorProcess_onClose(reactor, ¬ify_ev);
});
}
#ifdef HAVE_REUSEPORT
static int ReactorProcess_reuse_port(ListenPort *ls) {
ls->socket = swoole::make_socket(
ls->type, ls->is_dgram() ? SW_FD_DGRAM_SERVER : SW_FD_STREAM_SERVER, SW_SOCK_CLOEXEC | SW_SOCK_NONBLOCK);
if (ls->socket->set_reuse_port() < 0) {
ls->socket->free();
return SW_ERR;
}
if (ls->socket->bind(ls->host, &ls->port) < 0) {
ls->socket->free();
return SW_ERR;
}
return ls->listen();
}
#endif
} // namespace swoole
<|endoftext|> |
<commit_before>
#include "z80.h"
using z80::fast_u8;
using z80::fast_u16;
using z80::least_u8;
class my_emulator : public z80::z80_cpu<my_emulator> {
public:
typedef z80::z80_cpu<my_emulator> base;
my_emulator() {}
void on_set_pc(fast_u16 pc) {
std::printf("pc = 0x%04x\n", static_cast<unsigned>(pc));
base::on_set_pc(pc);
}
fast_u8 on_read(fast_u16 addr) {
assert(addr < z80::address_space_size);
fast_u8 n = memory[addr];
std::printf("read 0x%02x at 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(addr));
return n;
}
void on_write(fast_u16 addr, fast_u8 n) {
assert(addr < z80::address_space_size);
std::printf("write 0x%02x at 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(addr));
memory[addr] = static_cast<least_u8>(n);
}
fast_u8 on_input(fast_u16 port) {
fast_u8 n = 0xfe;
std::printf("input 0x%02x from 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(port));
return n;
}
void on_output(fast_u16 port, fast_u8 n) {
std::printf("output 0x%02x to 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(port));
}
private:
least_u8 memory[z80::address_space_size] = {
0xdb, // in a, (0xfe)
0xee, 0x07, // xor 7
0xd3, // out (0xfe), a
};
};
int main() {
my_emulator e;
e.on_step();
e.on_step();
e.on_step();
}
<commit_msg>[#34] Fix the binary code for the input/output example.<commit_after>
#include "z80.h"
using z80::fast_u8;
using z80::fast_u16;
using z80::least_u8;
class my_emulator : public z80::z80_cpu<my_emulator> {
public:
typedef z80::z80_cpu<my_emulator> base;
my_emulator() {}
void on_set_pc(fast_u16 pc) {
std::printf("pc = 0x%04x\n", static_cast<unsigned>(pc));
base::on_set_pc(pc);
}
fast_u8 on_read(fast_u16 addr) {
assert(addr < z80::address_space_size);
fast_u8 n = memory[addr];
std::printf("read 0x%02x at 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(addr));
return n;
}
void on_write(fast_u16 addr, fast_u8 n) {
assert(addr < z80::address_space_size);
std::printf("write 0x%02x at 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(addr));
memory[addr] = static_cast<least_u8>(n);
}
fast_u8 on_input(fast_u16 port) {
fast_u8 n = 0xfe;
std::printf("input 0x%02x from 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(port));
return n;
}
void on_output(fast_u16 port, fast_u8 n) {
std::printf("output 0x%02x to 0x%04x\n", static_cast<unsigned>(n),
static_cast<unsigned>(port));
}
private:
least_u8 memory[z80::address_space_size] = {
0xdb, 0xfe, // in a, (0xfe)
0xee, 0x07, // xor 7
0xd3, 0xfe, // out (0xfe), a
};
};
int main() {
my_emulator e;
e.on_step();
e.on_step();
e.on_step();
}
<|endoftext|> |
<commit_before>#include "IDatabaseEngine.h"
#include "DBEngineFactory.h"
#include "core/global.h"
#include "dcparser/hashGenerator.h"
#include "dcparser/dcFile.h"
#include "dcparser/dcClass.h"
#include "dcparser/dcField.h"
#include <soci.h>
#include <boost/icl/interval_set.hpp>
using namespace std;
using namespace soci;
typedef boost::icl::discrete_interval<uint32_t> interval_t;
typedef boost::icl::interval_set<uint32_t> set_t;
static ConfigVariable<std::string> engine_type("type", "null");
static ConfigVariable<std::string> database_name("database", "null");
static ConfigVariable<std::string> session_user("username", "null");
static ConfigVariable<std::string> session_passwd("password", "null");
class SociSQLEngine : public IDatabaseEngine
{
public:
SociSQLEngine(DBEngineConfig dbeconfig, uint32_t min_id, uint32_t max_id) :
IDatabaseEngine(dbeconfig, min_id, max_id), m_min_id(min_id), m_max_id(max_id),
m_backend(engine_type.get_rval(dbeconfig)),
m_db_name(database_name.get_rval(dbeconfig)),
m_sess_user(session_user.get_rval(dbeconfig)),
m_sess_passwd(session_passwd.get_rval(dbeconfig))
{
stringstream log_name;
log_name << "Database-" << m_backend << "(Range: [" << min_id << ", " << max_id << "])";
m_log = new LogCategory(m_backend, log_name.str());
connect();
check_tables();
check_classes();
check_ids();
}
uint32_t create_object(const DatabaseObject& dbo)
{
string field_name;
vector<uint8_t> field_value;
DCClass *dcc = g_dcf->get_class(dbo.dc_id);
bool storable = is_storable(dbo.dc_id);
uint32_t do_id = pop_next_id();
if(!do_id)
{
return 0;
}
try {
m_sql.begin(); // Start transaction
m_sql << "INSERT INTO objects VALUES (" << do_id << "," << dbo.dc_id << ");";
if(storable)
{
// TODO: This would probably be a lot faster if it was all one statement.
// Go ahead and simplify to one statement if you see a good way to do so.
m_sql << "INSERT INTO fields_" << dcc->get_name() << " VALUES (:id);", use(do_id);
statement set_field = (m_sql.prepare << "UPDATE fields_" << dcc->get_name()
<< " SET :name=:value WHERE object_id=:id;",
use(field_name), use(field_value), use(do_id));
for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it)
{
field_name = it->first->get_name();
field_value = it->second;
set_field.execute();
}
}
m_sql.commit(); // End transaction
}
catch (const exception &e)
{
m_sql.rollback(); // Revert transaction
return 0;
}
return do_id;
}
void delete_object(uint32_t do_id)
{
bool storable = false;
DCClass* dcc = get_class(do_id);
if(dcc)
{ // Note: needs to be called outside the transaction so it doesn't prevent deletion
// of the object in the `objects` table
storable = is_storable(dcc->get_number());
}
m_log->debug() << "Deleting object with id " << do_id << "..." << endl;
m_sql << "DELETE FROM objects WHERE id=" << do_id;
if(dcc && storable)
{
m_log->spam() << "... object has stored field, also deleted." << endl;
m_sql << "DELETE FROM fields_" << dcc->get_name() << " WHERE object_id=:id;", use(do_id);
}
push_id(do_id);
}
bool get_object(uint32_t do_id, DatabaseObject& dbo)
{
m_log->spam() << "Getting obj-" << do_id << " ..." << std::endl;
// Get class from the objects table
DCClass* dcc = get_class(do_id);
if(!dcc)
{
return false; // Object does not exist
}
dbo.dc_id = dcc->get_number();
bool stored = is_storable(dcc->get_number());
if(stored)
{
get_fields_from_table(do_id, dcc, dbo.fields);
}
return true;
}
DCClass* get_class(uint32_t do_id)
{
uint16_t dc_id;
try
{
m_sql << "SELECT class_id FROM objects WHERE id=:id;", into(dc_id), use(do_id);
}
catch(const exception &e)
{
return NULL;
}
return g_dcf->get_class(dc_id);
}
void del_field(uint32_t do_id, DCField* field)
{
}
void del_fields(uint32_t do_id, const std::vector<DCField*> &fields)
{
}
void set_field(uint32_t do_id, DCField* field, const vector<uint8_t> &value)
{
}
void set_fields(uint32_t do_id, const map<DCField*, vector<uint8_t>> &fields)
{
}
bool set_field_if_empty(uint32_t do_id, DCField* field, vector<uint8_t> &value)
{
return false;
}
bool set_fields_if_empty(uint32_t do_id, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
bool set_field_if_equals(uint32_t do_id, DCField* field, const vector<uint8_t> &equal, vector<uint8_t> &value)
{
return false;
}
bool set_fields_if_equals(uint32_t do_id, const map<DCField*, vector<uint8_t>> &equals, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
bool get_field(uint32_t do_id, const DCField* field, vector<uint8_t> &value)
{
return false;
}
bool get_fields(uint32_t do_id, const std::vector<DCField*> &fields, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
protected:
void connect()
{
// Prepare database, username, password, etc for connection
stringstream connstring;
if(m_backend == "postgresql")
{
connstring << "dbname=" << m_db_name;
}
else if(m_backend == "mysql")
{
connstring << "db=" << m_db_name << " "
<< "user=" << m_sess_user << " "
<< "pass='" << m_sess_passwd << "'";
}
else if(m_backend == "sqlite")
{
connstring << m_db_name;
}
// Connect to database
m_sql.open(m_backend, connstring.str());
}
void check_tables()
{
m_sql << "CREATE TABLE IF NOT EXISTS objects ("
"id INT NOT NULL PRIMARY KEY, class_id INT NOT NULL);";
//"CONSTRAINT check_object CHECK (id BETWEEN " << m_min_id << " AND " << m_max_id << "));";
m_sql << "CREATE TABLE IF NOT EXISTS classes ("
"id INT NOT NULL PRIMARY KEY, hash INT NOT NULL, name VARCHAR(32) NOT NULL,"
"storable BOOLEAN NOT NULL);";//, CONSTRAINT check_class CHECK (id BETWEEN 0 AND "
//<< g_dcf->get_num_classes()-1 << "));";
}
void check_classes()
{
int dc_id;
uint8_t storable;
string dc_name;
unsigned long dc_hash;
// Prepare sql statements
statement get_row_by_id = (m_sql.prepare << "SELECT hash, name FROM classes WHERE id=:id",
into(dc_hash), into(dc_name), use(dc_id));
statement insert_class = (m_sql.prepare << "INSERT INTO classes VALUES (:id,:hash,:name,:stored)",
use(dc_id), use(dc_hash), use(dc_name), use(storable));
// For each class, verify an entry exists and has the correct name and value
for(dc_id = 0; dc_id < g_dcf->get_num_classes(); ++dc_id)
{
get_row_by_id.execute(true);
if(m_sql.got_data())
{
check_class(dc_id, dc_name, dc_hash);
}
else
{
DCClass* dcc = g_dcf->get_class(dc_id);
// Create fields table for the class
storable = create_fields_table(dcc);
// Create class row in classes table
HashGenerator gen;
dcc->generate_hash(gen);
dc_hash = gen.get_hash();
dc_name = dcc->get_name();
insert_class.execute(true);
}
}
}
void check_ids()
{
// Set all ids as free ids
m_free_ids = set_t();
m_free_ids += interval_t::closed(m_min_id, m_max_id);
uint32_t id;
// Get all ids from the database at once
statement st = (m_sql.prepare << "SELECT id FROM objects;", into(id));
st.execute();
// Iterate through the result set, removing used ids from the free ids
while(st.fetch())
{
m_free_ids -= interval_t::closed(id, id);
}
}
uint32_t pop_next_id()
{
// Check to make sure any free ids exist
if(!m_free_ids.size())
{
return INVALID_DO_ID;
}
// Get next available id from m_free_ids set
interval_t first = *m_free_ids.begin();
uint32_t id = first.lower();
if(!(first.bounds().bits() & BOOST_BINARY(10)))
{
id += 1;
}
// Check if its within range
if(id > m_max_id)
{
return INVALID_DO_ID;
}
// Remove it from the free ids
m_free_ids -= interval_t::closed(id, id);
return id;
}
void push_id(uint32_t id)
{
m_free_ids += interval_t::closed(id, id);
}
private:
uint32_t m_min_id, m_max_id;
string m_backend, m_db_name;
string m_sess_user, m_sess_passwd;
session m_sql;
set_t m_free_ids;
LogCategory* m_log;
void check_class(uint16_t id, string name, unsigned long hash)
{
DCClass* dcc = g_dcf->get_class(id);
if(name != dcc->get_name())
{
// TODO: Try and update the database instead of exiting
m_log->fatal() << "Class name '" << dcc->get_name() << "' from DCFile does not match"
" name '" << name << "' in database, for dc_id " << id << std::endl;
m_log->fatal() << "Database must be rebuilt." << std::endl;
exit(1);
}
HashGenerator gen;
dcc->generate_hash(gen);
if(hash != gen.get_hash())
{
// TODO: Try and update the database instead of exiting
m_log->fatal() << "Class hash '" << gen.get_hash() << "' from DCFile does not match"
" hash '" << hash << "' in database, for dc_id " << id << std::endl;
m_log->fatal() << "Database must be rebuilt." << std::endl;
exit(1);
}
// TODO: Check class_fields table exists
}
// returns true if class has db fields
bool create_fields_table(DCClass* dcc)
{
stringstream ss;
ss << "CREATE TABLE IF NOT EXISTS fields_" << dcc->get_name()
<< "(object_id INT NOT NULL PRIMARY KEY";
int db_field_count = 0;
for(int i = 0; i < dcc->get_num_inherited_fields(); ++i)
{
DCField* field = dcc->get_inherited_field(i);
if(field->is_db() && !field->as_molecular_field())
{
db_field_count += 1;
ss << "," << field->get_name() << " "; // column name
DCPackerInterface* packer;
if(field->has_nested_fields() && field->get_num_nested_fields() == 1)
{
packer = field->get_nested_field(0);
}
else
{
packer = field;
}
// TODO: fix this switch, somehow it always reaches defualt
switch(packer->get_pack_type())
{
case PT_int:
case PT_uint:
case PT_int64:
case PT_uint64:
ss << "INT"; //column type
break;
case PT_double:
ss << "FLOAT"; //column type
break;
case PT_string:
// TODO: See if its possible to get the parameter range limits,
// then use VARCHAR(n) for smaller range limits.
ss << "TEXT"; //column type
break;
default:
// TODO: See if its possible to get the parameter range limits,
// then use VARBINARY(n) for smaller range limits.
if(m_backend == "postgresql") { ss << "BYTEA"; }
else { ss << "BLOB"; }
}
}
}
if(db_field_count > 0)
{
ss << ");";
m_sql << ss.str();
return true;
}
return false;
}
bool is_storable(uint16_t dc_id)
{
uint8_t storable;
m_sql << "SELECT storable FROM classes WHERE id=:id", into(storable), use(dc_id);
return storable;
}
void get_fields_from_table(uint32_t id, DCClass* dcc, map<DCField*, vector<uint8_t>> &fields)
{
}
};
DBEngineCreator<SociSQLEngine> mysqlengine_creator("mysql");
DBEngineCreator<SociSQLEngine> postgresqlengine_creator("postgresql");
DBEngineCreator<SociSQLEngine> sqliteengine_creator("sqlite");
<commit_msg>SQL Database: Remove outdated comment.<commit_after>#include "IDatabaseEngine.h"
#include "DBEngineFactory.h"
#include "core/global.h"
#include "dcparser/hashGenerator.h"
#include "dcparser/dcFile.h"
#include "dcparser/dcClass.h"
#include "dcparser/dcField.h"
#include <soci.h>
#include <boost/icl/interval_set.hpp>
using namespace std;
using namespace soci;
typedef boost::icl::discrete_interval<uint32_t> interval_t;
typedef boost::icl::interval_set<uint32_t> set_t;
static ConfigVariable<std::string> engine_type("type", "null");
static ConfigVariable<std::string> database_name("database", "null");
static ConfigVariable<std::string> session_user("username", "null");
static ConfigVariable<std::string> session_passwd("password", "null");
class SociSQLEngine : public IDatabaseEngine
{
public:
SociSQLEngine(DBEngineConfig dbeconfig, uint32_t min_id, uint32_t max_id) :
IDatabaseEngine(dbeconfig, min_id, max_id), m_min_id(min_id), m_max_id(max_id),
m_backend(engine_type.get_rval(dbeconfig)),
m_db_name(database_name.get_rval(dbeconfig)),
m_sess_user(session_user.get_rval(dbeconfig)),
m_sess_passwd(session_passwd.get_rval(dbeconfig))
{
stringstream log_name;
log_name << "Database-" << m_backend << "(Range: [" << min_id << ", " << max_id << "])";
m_log = new LogCategory(m_backend, log_name.str());
connect();
check_tables();
check_classes();
check_ids();
}
uint32_t create_object(const DatabaseObject& dbo)
{
string field_name;
vector<uint8_t> field_value;
DCClass *dcc = g_dcf->get_class(dbo.dc_id);
bool storable = is_storable(dbo.dc_id);
uint32_t do_id = pop_next_id();
if(!do_id)
{
return 0;
}
try {
m_sql.begin(); // Start transaction
m_sql << "INSERT INTO objects VALUES (" << do_id << "," << dbo.dc_id << ");";
if(storable)
{
// TODO: This would probably be a lot faster if it was all one statement.
// Go ahead and simplify to one statement if you see a good way to do so.
m_sql << "INSERT INTO fields_" << dcc->get_name() << " VALUES (:id);", use(do_id);
statement set_field = (m_sql.prepare << "UPDATE fields_" << dcc->get_name()
<< " SET :name=:value WHERE object_id=:id;",
use(field_name), use(field_value), use(do_id));
for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it)
{
field_name = it->first->get_name();
field_value = it->second;
set_field.execute();
}
}
m_sql.commit(); // End transaction
}
catch (const exception &e)
{
m_sql.rollback(); // Revert transaction
return 0;
}
return do_id;
}
void delete_object(uint32_t do_id)
{
bool storable = false;
DCClass* dcc = get_class(do_id);
if(dcc)
{ // Note: needs to be called outside the transaction so it doesn't prevent deletion
// of the object in the `objects` table
storable = is_storable(dcc->get_number());
}
m_log->debug() << "Deleting object with id " << do_id << "..." << endl;
m_sql << "DELETE FROM objects WHERE id=" << do_id;
if(dcc && storable)
{
m_log->spam() << "... object has stored field, also deleted." << endl;
m_sql << "DELETE FROM fields_" << dcc->get_name() << " WHERE object_id=:id;", use(do_id);
}
push_id(do_id);
}
bool get_object(uint32_t do_id, DatabaseObject& dbo)
{
m_log->spam() << "Getting obj-" << do_id << " ..." << std::endl;
// Get class from the objects table
DCClass* dcc = get_class(do_id);
if(!dcc)
{
return false; // Object does not exist
}
dbo.dc_id = dcc->get_number();
bool stored = is_storable(dcc->get_number());
if(stored)
{
get_fields_from_table(do_id, dcc, dbo.fields);
}
return true;
}
DCClass* get_class(uint32_t do_id)
{
uint16_t dc_id;
try
{
m_sql << "SELECT class_id FROM objects WHERE id=:id;", into(dc_id), use(do_id);
}
catch(const exception &e)
{
return NULL;
}
return g_dcf->get_class(dc_id);
}
void del_field(uint32_t do_id, DCField* field)
{
}
void del_fields(uint32_t do_id, const std::vector<DCField*> &fields)
{
}
void set_field(uint32_t do_id, DCField* field, const vector<uint8_t> &value)
{
}
void set_fields(uint32_t do_id, const map<DCField*, vector<uint8_t>> &fields)
{
}
bool set_field_if_empty(uint32_t do_id, DCField* field, vector<uint8_t> &value)
{
return false;
}
bool set_fields_if_empty(uint32_t do_id, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
bool set_field_if_equals(uint32_t do_id, DCField* field, const vector<uint8_t> &equal, vector<uint8_t> &value)
{
return false;
}
bool set_fields_if_equals(uint32_t do_id, const map<DCField*, vector<uint8_t>> &equals, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
bool get_field(uint32_t do_id, const DCField* field, vector<uint8_t> &value)
{
return false;
}
bool get_fields(uint32_t do_id, const std::vector<DCField*> &fields, map<DCField*, vector<uint8_t>> &values)
{
return false;
}
protected:
void connect()
{
// Prepare database, username, password, etc for connection
stringstream connstring;
if(m_backend == "postgresql")
{
connstring << "dbname=" << m_db_name;
}
else if(m_backend == "mysql")
{
connstring << "db=" << m_db_name << " "
<< "user=" << m_sess_user << " "
<< "pass='" << m_sess_passwd << "'";
}
else if(m_backend == "sqlite")
{
connstring << m_db_name;
}
// Connect to database
m_sql.open(m_backend, connstring.str());
}
void check_tables()
{
m_sql << "CREATE TABLE IF NOT EXISTS objects ("
"id INT NOT NULL PRIMARY KEY, class_id INT NOT NULL);";
//"CONSTRAINT check_object CHECK (id BETWEEN " << m_min_id << " AND " << m_max_id << "));";
m_sql << "CREATE TABLE IF NOT EXISTS classes ("
"id INT NOT NULL PRIMARY KEY, hash INT NOT NULL, name VARCHAR(32) NOT NULL,"
"storable BOOLEAN NOT NULL);";//, CONSTRAINT check_class CHECK (id BETWEEN 0 AND "
//<< g_dcf->get_num_classes()-1 << "));";
}
void check_classes()
{
int dc_id;
uint8_t storable;
string dc_name;
unsigned long dc_hash;
// Prepare sql statements
statement get_row_by_id = (m_sql.prepare << "SELECT hash, name FROM classes WHERE id=:id",
into(dc_hash), into(dc_name), use(dc_id));
statement insert_class = (m_sql.prepare << "INSERT INTO classes VALUES (:id,:hash,:name,:stored)",
use(dc_id), use(dc_hash), use(dc_name), use(storable));
// For each class, verify an entry exists and has the correct name and value
for(dc_id = 0; dc_id < g_dcf->get_num_classes(); ++dc_id)
{
get_row_by_id.execute(true);
if(m_sql.got_data())
{
check_class(dc_id, dc_name, dc_hash);
}
else
{
DCClass* dcc = g_dcf->get_class(dc_id);
// Create fields table for the class
storable = create_fields_table(dcc);
// Create class row in classes table
HashGenerator gen;
dcc->generate_hash(gen);
dc_hash = gen.get_hash();
dc_name = dcc->get_name();
insert_class.execute(true);
}
}
}
void check_ids()
{
// Set all ids as free ids
m_free_ids = set_t();
m_free_ids += interval_t::closed(m_min_id, m_max_id);
uint32_t id;
// Get all ids from the database at once
statement st = (m_sql.prepare << "SELECT id FROM objects;", into(id));
st.execute();
// Iterate through the result set, removing used ids from the free ids
while(st.fetch())
{
m_free_ids -= interval_t::closed(id, id);
}
}
uint32_t pop_next_id()
{
// Check to make sure any free ids exist
if(!m_free_ids.size())
{
return INVALID_DO_ID;
}
// Get next available id from m_free_ids set
interval_t first = *m_free_ids.begin();
uint32_t id = first.lower();
if(!(first.bounds().bits() & BOOST_BINARY(10)))
{
id += 1;
}
// Check if its within range
if(id > m_max_id)
{
return INVALID_DO_ID;
}
// Remove it from the free ids
m_free_ids -= interval_t::closed(id, id);
return id;
}
void push_id(uint32_t id)
{
m_free_ids += interval_t::closed(id, id);
}
private:
uint32_t m_min_id, m_max_id;
string m_backend, m_db_name;
string m_sess_user, m_sess_passwd;
session m_sql;
set_t m_free_ids;
LogCategory* m_log;
void check_class(uint16_t id, string name, unsigned long hash)
{
DCClass* dcc = g_dcf->get_class(id);
if(name != dcc->get_name())
{
// TODO: Try and update the database instead of exiting
m_log->fatal() << "Class name '" << dcc->get_name() << "' from DCFile does not match"
" name '" << name << "' in database, for dc_id " << id << std::endl;
m_log->fatal() << "Database must be rebuilt." << std::endl;
exit(1);
}
HashGenerator gen;
dcc->generate_hash(gen);
if(hash != gen.get_hash())
{
// TODO: Try and update the database instead of exiting
m_log->fatal() << "Class hash '" << gen.get_hash() << "' from DCFile does not match"
" hash '" << hash << "' in database, for dc_id " << id << std::endl;
m_log->fatal() << "Database must be rebuilt." << std::endl;
exit(1);
}
// TODO: Check class_fields table exists
}
// returns true if class has db fields
bool create_fields_table(DCClass* dcc)
{
stringstream ss;
ss << "CREATE TABLE IF NOT EXISTS fields_" << dcc->get_name()
<< "(object_id INT NOT NULL PRIMARY KEY";
int db_field_count = 0;
for(int i = 0; i < dcc->get_num_inherited_fields(); ++i)
{
DCField* field = dcc->get_inherited_field(i);
if(field->is_db() && !field->as_molecular_field())
{
db_field_count += 1;
ss << "," << field->get_name() << " "; // column name
DCPackerInterface* packer;
if(field->has_nested_fields() && field->get_num_nested_fields() == 1)
{
packer = field->get_nested_field(0);
}
else
{
packer = field;
}
switch(packer->get_pack_type())
{
case PT_int:
case PT_uint:
case PT_int64:
case PT_uint64:
ss << "INT"; //column type
break;
case PT_double:
ss << "FLOAT"; //column type
break;
case PT_string:
// TODO: See if its possible to get the parameter range limits,
// then use VARCHAR(n) for smaller range limits.
ss << "TEXT"; //column type
break;
default:
// TODO: See if its possible to get the parameter range limits,
// then use VARBINARY(n) for smaller range limits.
if(m_backend == "postgresql") { ss << "BYTEA"; }
else { ss << "BLOB"; }
}
}
}
if(db_field_count > 0)
{
ss << ");";
m_sql << ss.str();
return true;
}
return false;
}
bool is_storable(uint16_t dc_id)
{
uint8_t storable;
m_sql << "SELECT storable FROM classes WHERE id=:id", into(storable), use(dc_id);
return storable;
}
void get_fields_from_table(uint32_t id, DCClass* dcc, map<DCField*, vector<uint8_t>> &fields)
{
}
};
DBEngineCreator<SociSQLEngine> mysqlengine_creator("mysql");
DBEngineCreator<SociSQLEngine> postgresqlengine_creator("postgresql");
DBEngineCreator<SociSQLEngine> sqliteengine_creator("sqlite");
<|endoftext|> |
<commit_before>#include "MessageGetField.h"
#include "MessageSptr.h" // for MessageSptr
#include <LuaIntf/LuaIntf.h>
#include <google/protobuf/descriptor.h> // for Descriptor
#include <google/protobuf/message.h> // for Message
#include "google/protobuf/descriptor.pb.h" // for map_entry()
using namespace LuaIntf;
using namespace google::protobuf;
using namespace std;
namespace {
FieldResult ErrorResult(lua_State* L, const string& sError)
{
return make_tuple(LuaRef(L, nullptr), sError);
}
template <typename T>
FieldResult ValueResult(lua_State* L, const T& value)
{
return make_tuple(LuaRef::fromValue(L, value), "");
}
MessageSptr MakeSharedMessage(const Message& msg)
{
MessageSptr pMsg(msg.New());
pMsg->CopyFrom(msg);
return pMsg;
}
FieldResult MessageResult(lua_State* L, const Message& msg)
{
return ValueResult(L, MakeSharedMessage(msg));
}
// Set lua table element value.
// Use SetTblMessageElement() if element is a Message.
template <typename T>
void SetTblValueElement(LuaRef& rTbl, int index, const T& value)
{
rTbl.set(index, value);
}
// Set lua table element to Message.
// Support map entry message.
void SetTblMessageElement(LuaRef& rTbl, int index, const Message& msg)
{
const Descriptor* pDesc = msg.GetDescriptor();
assert(pDesc);
bool isMap = pDesc->options().map_entry();
if (!isMap)
{
rTbl.set(index, MakeSharedMessage(msg));
return;
}
// XXX
}
// XXX Use RepeatedFieldRef
// Get repeated field element and insert it to lua table.
// Map field is supported.
// Returns empty if success.
string GetRepeatedFieldElement(const Message& msg,
const FieldDescriptor* pField, int index, LuaRef& rTbl)
{
assert(pField);
assert(pField->is_repeated());
assert(index >= 0);
const Reflection* pRefl = msg.GetReflection();
assert(pRefl);
assert(index < pRefl->FieldSize(msg, pField));
using Fd = FieldDescriptor;
Fd::CppType eCppType = pField->cpp_type();
switch (eCppType)
{
case Fd::CPPTYPE_INT32:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedInt32(msg, pField, index));
return "";
case Fd::CPPTYPE_INT64:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedInt64(msg, pField, index));
return "";
case Fd::CPPTYPE_UINT32:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedUInt32(msg, pField, index));
return "";
case Fd::CPPTYPE_UINT64:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedUInt64(msg, pField, index));
return "";
case Fd::CPPTYPE_DOUBLE:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedDouble(msg, pField, index));
return "";
case Fd::CPPTYPE_FLOAT:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedFloat(msg, pField, index));
return "";
case Fd::CPPTYPE_BOOL:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedBool(msg, pField, index));
return "";
case Fd::CPPTYPE_ENUM:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedEnumValue(msg, pField, index));
return "";
case Fd::CPPTYPE_STRING:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedString(msg, pField, index));
return "";
case Fd::CPPTYPE_MESSAGE:
// Support map entry element.
SetTblMessageElement(rTbl, index,
pRefl->GetRepeatedMessage(msg, pField, index));
return "";
default:
break;
}
// Unknown repeated field type CPPTYPE_UNKNOWN of Message.Field
return string("Unknown repeated field type ") +
pField->CppTypeName(eCppType) + " of " +
msg.GetTypeName() + "." + pField->name();
}
// returns (TableRef, "") or (nil, error_string)
// Map is supported.
FieldResult GetRepeatedField(lua_State* L,
const Message& msg, const FieldDescriptor* pField)
{
assert(L);
assert(pField->is_repeated());
const Reflection* pRefl = msg.GetReflection();
assert(pRefl);
LuaRef tbl = LuaRef::createTable(L);
int nFldSize = pRefl->FieldSize(msg, pField);
for (int index = 0; index < nFldSize; ++index)
{
string sError = GetRepeatedFieldElement(msg, pField, index, tbl);
if (!sError.empty())
return ErrorResult(L, sError);
}
return make_tuple(tbl, "");
}
} // namespace
FieldResult MessageGetField(lua_State* L,
const Message& msg, const std::string& sField)
{
assert(L);
const Descriptor* pDesc = msg.GetDescriptor();
assert(pDesc);
const FieldDescriptor* pField = pDesc->FindFieldByName(sField);
if (!pField)
return ErrorResult(L, "Message " + msg.GetTypeName() + " has no field: " + sField);
const Reflection* pRefl = msg.GetReflection();
if (!pRefl)
return ErrorResult(L, "Message has no reflection.");
if (pField->is_repeated())
{
// returns (TableRef, "") or (nil, error_string)
return GetRepeatedField(L, msg, pField);
}
using Fd = FieldDescriptor;
Fd::CppType eCppType = pField->cpp_type();
switch (eCppType)
{
case Fd::CPPTYPE_INT32:
return ValueResult(L, pRefl->GetInt32(msg, pField));
case Fd::CPPTYPE_INT64:
return ValueResult(L, pRefl->GetInt64(msg, pField));
case Fd::CPPTYPE_UINT32:
return ValueResult(L, pRefl->GetUInt32(msg, pField));
case Fd::CPPTYPE_UINT64:
return ValueResult(L, pRefl->GetUInt64(msg, pField));
case Fd::CPPTYPE_DOUBLE:
return ValueResult(L, pRefl->GetDouble(msg, pField));
case Fd::CPPTYPE_FLOAT:
return ValueResult(L, pRefl->GetFloat(msg, pField));
case Fd::CPPTYPE_BOOL:
return ValueResult(L, pRefl->GetBool(msg, pField));
case Fd::CPPTYPE_ENUM:
return ValueResult(L, pRefl->GetEnumValue(msg, pField));
case Fd::CPPTYPE_STRING:
return ValueResult(L, pRefl->GetString(msg, pField));
case Fd::CPPTYPE_MESSAGE:
if (pRefl->HasField(msg, pField))
return MessageResult(L, pRefl->GetMessage(msg, pField));
return ValueResult(L, nullptr);
default:
break;
}
// Unknown field type CPPTYPE_UNKNOWN of Message.Field
return ErrorResult(L, string("Unknown field type ") +
pField->CppTypeName(eCppType) + " of " +
msg.GetTypeName() + "." + sField);
}
<commit_msg>Add comment.<commit_after>#include "MessageGetField.h"
#include "MessageSptr.h" // for MessageSptr
#include <LuaIntf/LuaIntf.h>
#include <google/protobuf/descriptor.h> // for Descriptor
#include <google/protobuf/message.h> // for Message
#include "google/protobuf/descriptor.pb.h" // for map_entry()
using namespace LuaIntf;
using namespace google::protobuf;
using namespace std;
namespace {
FieldResult ErrorResult(lua_State* L, const string& sError)
{
return make_tuple(LuaRef(L, nullptr), sError);
}
template <typename T>
FieldResult ValueResult(lua_State* L, const T& value)
{
return make_tuple(LuaRef::fromValue(L, value), "");
}
MessageSptr MakeSharedMessage(const Message& msg)
{
MessageSptr pMsg(msg.New());
pMsg->CopyFrom(msg);
return pMsg;
}
FieldResult MessageResult(lua_State* L, const Message& msg)
{
return ValueResult(L, MakeSharedMessage(msg));
}
// Set lua table element value.
// Use SetTblMessageElement() if element is a Message.
template <typename T>
void SetTblValueElement(LuaRef& rTbl, int index, const T& value)
{
rTbl.set(index, value);
}
// Set lua table element to Message.
// Support map entry message.
void SetTblMessageElement(LuaRef& rTbl, int index, const Message& msg)
{
const Descriptor* pDesc = msg.GetDescriptor();
assert(pDesc);
bool isMap = pDesc->options().map_entry();
if (!isMap)
{
rTbl.set(index, MakeSharedMessage(msg));
return;
}
// XXX
}
// XXX Use RepeatedFieldRef
// Get repeated field element and insert it to lua table.
// Map field is supported.
// Returns empty if success.
string GetRepeatedFieldElement(const Message& msg,
const FieldDescriptor* pField, int index, LuaRef& rTbl)
{
assert(pField);
assert(pField->is_repeated());
assert(index >= 0);
const Reflection* pRefl = msg.GetReflection();
assert(pRefl);
assert(index < pRefl->FieldSize(msg, pField));
using Fd = FieldDescriptor;
Fd::CppType eCppType = pField->cpp_type();
switch (eCppType)
{
case Fd::CPPTYPE_INT32:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedInt32(msg, pField, index));
return "";
case Fd::CPPTYPE_INT64:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedInt64(msg, pField, index));
return "";
case Fd::CPPTYPE_UINT32:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedUInt32(msg, pField, index));
return "";
case Fd::CPPTYPE_UINT64:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedUInt64(msg, pField, index));
return "";
case Fd::CPPTYPE_DOUBLE:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedDouble(msg, pField, index));
return "";
case Fd::CPPTYPE_FLOAT:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedFloat(msg, pField, index));
return "";
case Fd::CPPTYPE_BOOL:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedBool(msg, pField, index));
return "";
case Fd::CPPTYPE_ENUM:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedEnumValue(msg, pField, index));
return "";
case Fd::CPPTYPE_STRING:
SetTblValueElement(rTbl, index,
pRefl->GetRepeatedString(msg, pField, index));
return "";
case Fd::CPPTYPE_MESSAGE:
// Support map entry element.
SetTblMessageElement(rTbl, index,
pRefl->GetRepeatedMessage(msg, pField, index));
return "";
default:
break;
}
// Unknown repeated field type CPPTYPE_UNKNOWN of Message.Field
return string("Unknown repeated field type ") +
pField->CppTypeName(eCppType) + " of " +
msg.GetTypeName() + "." + pField->name();
}
// returns (TableRef, "") or (nil, error_string)
// Map is supported.
FieldResult GetRepeatedField(lua_State* L,
const Message& msg, const FieldDescriptor* pField)
{
assert(L);
assert(pField->is_repeated());
const Reflection* pRefl = msg.GetReflection();
assert(pRefl);
LuaRef tbl = LuaRef::createTable(L);
int nFldSize = pRefl->FieldSize(msg, pField);
for (int index = 0; index < nFldSize; ++index)
{
string sError = GetRepeatedFieldElement(msg, pField, index, tbl);
if (!sError.empty())
return ErrorResult(L, sError);
}
return make_tuple(tbl, "");
}
} // namespace
FieldResult MessageGetField(lua_State* L,
const Message& msg, const std::string& sField)
{
assert(L);
const Descriptor* pDesc = msg.GetDescriptor();
assert(pDesc);
const FieldDescriptor* pField = pDesc->FindFieldByName(sField);
if (!pField)
return ErrorResult(L, "Message " + msg.GetTypeName() + " has no field: " + sField);
const Reflection* pRefl = msg.GetReflection();
if (!pRefl)
return ErrorResult(L, "Message has no reflection.");
if (pField->is_repeated())
{
// returns (TableRef, "") or (nil, error_string)
return GetRepeatedField(L, msg, pField);
}
using Fd = FieldDescriptor;
Fd::CppType eCppType = pField->cpp_type();
switch (eCppType)
{
// Scalar field always has a default value.
case Fd::CPPTYPE_INT32:
return ValueResult(L, pRefl->GetInt32(msg, pField));
case Fd::CPPTYPE_INT64:
return ValueResult(L, pRefl->GetInt64(msg, pField));
case Fd::CPPTYPE_UINT32:
return ValueResult(L, pRefl->GetUInt32(msg, pField));
case Fd::CPPTYPE_UINT64:
return ValueResult(L, pRefl->GetUInt64(msg, pField));
case Fd::CPPTYPE_DOUBLE:
return ValueResult(L, pRefl->GetDouble(msg, pField));
case Fd::CPPTYPE_FLOAT:
return ValueResult(L, pRefl->GetFloat(msg, pField));
case Fd::CPPTYPE_BOOL:
return ValueResult(L, pRefl->GetBool(msg, pField));
case Fd::CPPTYPE_ENUM:
return ValueResult(L, pRefl->GetEnumValue(msg, pField));
case Fd::CPPTYPE_STRING:
return ValueResult(L, pRefl->GetString(msg, pField));
case Fd::CPPTYPE_MESSAGE:
// For message field, the default value is null.
if (pRefl->HasField(msg, pField))
return MessageResult(L, pRefl->GetMessage(msg, pField));
return ValueResult(L, nullptr);
default:
break;
}
// Unknown field type CPPTYPE_UNKNOWN of Message.Field
return ErrorResult(L, string("Unknown field type ") +
pField->CppTypeName(eCppType) + " of " +
msg.GetTypeName() + "." + sField);
}
<|endoftext|> |
<commit_before>#include "base/basictypes.h"
#include "base/logging.h"
#include "base/timeutil.h"
// For NV time functions. Ugly!
#include "gfx_es2/gl_state.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#include <stdio.h>
static double curtime = 0;
static float curtime_f = 0;
#ifdef _WIN32
LARGE_INTEGER frequency;
double frequencyMult;
LARGE_INTEGER startTime;
double real_time_now() {
if (frequency.QuadPart == 0) {
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&startTime);
curtime = 0.0;
frequencyMult = 1.0 / static_cast<double>(frequency.QuadPart);
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
double elapsed = static_cast<double>(time.QuadPart - startTime.QuadPart);
return elapsed * frequencyMult;
}
#elif defined(BLACKBERRY)
double real_time_now() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time); // Linux must use CLOCK_MONOTONIC_RAW due to time warps
return time.tv_sec + time.tv_nsec / 1.0e9;
}
#else
uint64_t _frequency = 0;
uint64_t _starttime = 0;
double real_time_now() {
#ifdef ANDROID
if (false && gl_extensions.EGL_NV_system_time) {
// This is needed to profile using PerfHUD on Tegra
if (_frequency == 0) {
_frequency = eglGetSystemTimeFrequencyNV();
_starttime = eglGetSystemTimeNV();
}
uint64_t cur = eglGetSystemTimeNV();
int64_t diff = cur - _starttime;
return (double)diff / (double)_frequency;
}
#endif
static time_t start;
struct timeval tv;
gettimeofday(&tv, NULL);
if (start == 0) {
start = tv.tv_sec;
}
tv.tv_sec -= start;
return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
}
#endif
void time_update() {
curtime = real_time_now();
curtime_f = (float)curtime;
//printf("curtime: %f %f\n", curtime, curtime_f);
// also smooth time.
//curtime+=float((double) (time-_starttime) / (double) _frequency);
//curtime*=0.5f;
//curtime+=1.0f/60.0f;
//lastTime=curtime;
//curtime_f = (float)curtime;
}
float time_now() {
return curtime_f;
}
double time_now_d() {
return curtime;
}
int time_now_ms() {
return int(curtime*1000.0);
}
void sleep_ms(int ms) {
#ifdef _WIN32
#ifndef METRO
Sleep(ms);
#endif
#else
usleep(ms * 1000);
#endif
}
LoggingDeadline::LoggingDeadline(const char *name, int ms) : name_(name), endCalled_(false) {
totalTime_ = (double)ms * 0.001;
time_update();
endTime_ = time_now_d() + totalTime_;
}
LoggingDeadline::~LoggingDeadline() {
if (!endCalled_)
End();
}
bool LoggingDeadline::End() {
endCalled_ = true;
time_update();
if (time_now_d() > endTime_) {
double late = (time_now_d() - endTime_);
double totalTime = late + totalTime_;
ELOG("===== %0.2fms DEADLINE PASSED FOR %s at %0.2fms - %0.2fms late =====", totalTime_ * 1000.0, name_, 1000.0 * totalTime, 1000.0 * late);
return false;
}
return true;
}
<commit_msg>clock_gettime(MONOTONIC) seems more appropriate than gettimeofday for our purposes.<commit_after>#include "base/basictypes.h"
#include "base/logging.h"
#include "base/timeutil.h"
// For NV time functions. Ugly!
#include "gfx_es2/gl_state.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#include <stdio.h>
static double curtime = 0;
static float curtime_f = 0;
#ifdef _WIN32
LARGE_INTEGER frequency;
double frequencyMult;
LARGE_INTEGER startTime;
double real_time_now() {
if (frequency.QuadPart == 0) {
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&startTime);
curtime = 0.0;
frequencyMult = 1.0 / static_cast<double>(frequency.QuadPart);
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
double elapsed = static_cast<double>(time.QuadPart - startTime.QuadPart);
return elapsed * frequencyMult;
}
#elif defined(BLACKBERRY)
double real_time_now() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time); // Linux must use CLOCK_MONOTONIC_RAW due to time warps
return time.tv_sec + time.tv_nsec / 1.0e9;
}
#else
uint64_t _frequency = 0;
uint64_t _starttime = 0;
double real_time_now() {
#ifdef ANDROID
if (false && gl_extensions.EGL_NV_system_time) {
// This is needed to profile using PerfHUD on Tegra
if (_frequency == 0) {
_frequency = eglGetSystemTimeFrequencyNV();
_starttime = eglGetSystemTimeNV();
}
uint64_t cur = eglGetSystemTimeNV();
int64_t diff = cur - _starttime;
return (double)diff / (double)_frequency;
}
struct timespec time;
clock_gettime(CLOCK_MONOTONIC_RAW, &time);
return time.tv_sec + time.tv_nsec / 1.0e9;
#else
static time_t start;
struct timeval tv;
gettimeofday(&tv, NULL);
if (start == 0) {
start = tv.tv_sec;
}
tv.tv_sec -= start;
return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
#endif
}
#endif
void time_update() {
curtime = real_time_now();
curtime_f = (float)curtime;
//printf("curtime: %f %f\n", curtime, curtime_f);
// also smooth time.
//curtime+=float((double) (time-_starttime) / (double) _frequency);
//curtime*=0.5f;
//curtime+=1.0f/60.0f;
//lastTime=curtime;
//curtime_f = (float)curtime;
}
float time_now() {
return curtime_f;
}
double time_now_d() {
return curtime;
}
int time_now_ms() {
return int(curtime*1000.0);
}
void sleep_ms(int ms) {
#ifdef _WIN32
#ifndef METRO
Sleep(ms);
#endif
#else
usleep(ms * 1000);
#endif
}
LoggingDeadline::LoggingDeadline(const char *name, int ms) : name_(name), endCalled_(false) {
totalTime_ = (double)ms * 0.001;
time_update();
endTime_ = time_now_d() + totalTime_;
}
LoggingDeadline::~LoggingDeadline() {
if (!endCalled_)
End();
}
bool LoggingDeadline::End() {
endCalled_ = true;
time_update();
if (time_now_d() > endTime_) {
double late = (time_now_d() - endTime_);
double totalTime = late + totalTime_;
ELOG("===== %0.2fms DEADLINE PASSED FOR %s at %0.2fms - %0.2fms late =====", totalTime_ * 1000.0, name_, 1000.0 * totalTime, 1000.0 * late);
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Tim Severeijns
*
* 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.
*/
#pragma once
#include <chrono>
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <typeinfo>
namespace
{
template<typename Type>
struct TypeName
{
// Evaluated at runtime:
static const decltype(typeid(Type).name()) value;
};
template<typename Type>
decltype(typeid(Type).name()) TypeName<Type>::value = typeid(Type).name();
template<>
struct TypeName<std::chrono::nanoseconds>
{
static constexpr auto value = "nanoseconds";
};
template<>
struct TypeName<std::chrono::microseconds>
{
static constexpr auto value = "microseconds";
};
template<>
struct TypeName<std::chrono::milliseconds>
{
static constexpr auto value = "milliseconds";
};
template<>
struct TypeName<std::chrono::seconds>
{
static constexpr auto value = "seconds";
};
template<>
struct TypeName<std::chrono::minutes>
{
static constexpr auto value = "minutes";
};
template<>
struct TypeName<std::chrono::hours>
{
static constexpr auto value = "hours";
};
}
/**
* @brief The Stopwatch class will wrap the callable object to be timed in a timing block, and then,
* based on which constructor was called, pass the resulting timing information to either std::cout or a
* user-defined output stream or function upon completion of timing.
*
* @tparam ChronoType One of the following std::chrono time representations:
* @li std::chrono::nanoseconds
* @li std::chrono::microseconds
* @li std::chrono::milliseconds
* @li std::chrono::seconds
* @li std::chrono::minutes
* @li std::chrono::hours
*/
template<typename ChronoType>
class Stopwatch
{
public:
using CallbackType = std::function<void (ChronoType, std::string)>;
/**
* @brief This Stopwatch constructor executes and times the code encapsulated within the
* callable object.
*
* Once the callable object has completed execution, the timing results and corresponding units
* will be passed to the specified callback function.
*
* @param[in] callable A callable object encapsulating the code to be timed.
* @param[in] callback Callback to handle the timing result.
*/
template<typename CallableType>
Stopwatch(
CallableType&& callable,
const CallbackType& callback)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
if (callback)
{
callback(m_elapsedTime, std::move(TypeName<ChronoType>::value));
}
}
/**
* @brief This Stopwatch constructor will execute and time the code encapsulated within the
* std::function object.
*
* Once the targeted code has completed execution, the timing results will be written out to
* output stream, along with the specified message. Specifically, the message will be written out
* first, followed immediately by the elapsed time and the corresponding units.
*
* @param[in] callable A callable object encapsulating the code to be timed.
* @param[in] message Output message.
* @param[in] outputStream The std::ostream object to pipe the message and time to.
*/
template<typename CallableType>
Stopwatch(
CallableType&& callable,
const char* const message,
std::ostream& outputStream = std::cout)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
outputStream
<< message
<< m_elapsedTime.count()
<< " "
<< TypeName<ChronoType>::value
<< "."
<< std::endl;
}
/**
* @brief This Stopwatch constructor will time the code encapsulated in the std::function object
* and then save the result to a member variable.
*
* In order to retrieve the elapsed time, call GetElapsedTime(). @See GetElapsedTime().
*/
template<typename CallableType>
Stopwatch(CallableType&& callable)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
}
/**
* @returns The elapsed time in ChronoType units.
*/
ChronoType GetElapsedTime()
{
return m_elapsedTime;
}
private:
/**
* @todo Once C++17 arrives: `noexcept(std::is_nothrow_callable_v<CallableType>)`
*/
template<typename CallableType>
void ExecuteAndTime(CallableType&& callable) noexcept(noexcept(callable))
{
const auto start = std::chrono::high_resolution_clock::now();
callable();
const auto end = std::chrono::high_resolution_clock::now();
m_elapsedTime = std::chrono::duration_cast<ChronoType>(end - start);
}
ChronoType m_elapsedTime;
};
#define TIME_IN_NANOSECONDS(code, message) \
Stopwatch<std::chrono::nanoseconds>( \
[&] { code; }, \
message);
#define TIME_IN_MICROSECONDS(code, message) \
Stopwatch<std::chrono::microseconds>( \
[&] { code; }, \
message);
#define TIME_IN_MILLISECONDS(code, message) \
Stopwatch<std::chrono::milliseconds>( \
[&] { code; }, \
message);
#define TIME_IN_SECONDS(code, message) \
Stopwatch<std::chrono::seconds>( \
[&] { code; }, \
message);
#define TIME_IN_MINUTES(code, message) \
Stopwatch<std::chrono::minutes>( \
[&] { code; }, \
message);
#define TIME_IN_HOURS(code, message) \
Stopwatch<std::chrono::hours>( \
[&] { code; }, \
message);
<commit_msg>More Constness and Another Function<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Tim Severeijns
*
* 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.
*/
#pragma once
#include <chrono>
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>
#include <typeinfo>
namespace
{
template<typename Type>
struct TypeName
{
// Evaluated at runtime:
static const decltype(typeid(Type).name()) value;
};
template<typename Type>
decltype(typeid(Type).name()) TypeName<Type>::value = typeid(Type).name();
template<>
struct TypeName<std::chrono::nanoseconds>
{
static constexpr auto value = "nanoseconds";
};
template<>
struct TypeName<std::chrono::microseconds>
{
static constexpr auto value = "microseconds";
};
template<>
struct TypeName<std::chrono::milliseconds>
{
static constexpr auto value = "milliseconds";
};
template<>
struct TypeName<std::chrono::seconds>
{
static constexpr auto value = "seconds";
};
template<>
struct TypeName<std::chrono::minutes>
{
static constexpr auto value = "minutes";
};
template<>
struct TypeName<std::chrono::hours>
{
static constexpr auto value = "hours";
};
}
/**
* @brief The Stopwatch class will wrap the callable object to be timed in a timing block, and then,
* based on which constructor was called, pass the resulting timing information to either std::cout or a
* user-defined output stream or function upon completion of timing.
*
* @tparam ChronoType One of the following std::chrono time representations:
* @li std::chrono::nanoseconds
* @li std::chrono::microseconds
* @li std::chrono::milliseconds
* @li std::chrono::seconds
* @li std::chrono::minutes
* @li std::chrono::hours
*/
template<typename ChronoType>
class Stopwatch
{
public:
using CallbackType = std::function<void(ChronoType, std::string)>;
/**
* @brief This Stopwatch constructor executes and times the code encapsulated within the
* callable object.
*
* Once the callable object has completed execution, the timing results and corresponding units
* will be passed to the specified callback function.
*
* @param[in] callable A callable object encapsulating the code to be timed.
* @param[in] callback Callback to handle the timing result.
*/
template<typename CallableType>
Stopwatch(
CallableType&& callable,
const CallbackType& callback)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
if (callback)
{
callback(m_elapsedTime, std::move(TypeName<ChronoType>::value));
}
}
/**
* @brief This Stopwatch constructor will execute and time the code encapsulated within the
* std::function object.
*
* Once the targeted code has completed execution, the timing results will be written out to
* output stream, along with the specified message. Specifically, the message will be written out
* first, followed immediately by the elapsed time and the corresponding units.
*
* @param[in] callable A callable object encapsulating the code to be timed.
* @param[in] message Output message.
* @param[in] outputStream The std::ostream object to pipe the message and time to.
*/
template<typename CallableType>
Stopwatch(
CallableType&& callable,
const char* const message,
std::ostream& outputStream = std::cout)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
outputStream
<< message
<< m_elapsedTime.count()
<< " "
<< TypeName<ChronoType>::value
<< "."
<< std::endl;
}
/**
* @brief This Stopwatch constructor will time the code encapsulated in the std::function object
* and then save the result to a member variable.
*
* In order to retrieve the elapsed time, call GetElapsedTime(). @See GetElapsedTime().
*/
template<typename CallableType>
Stopwatch(CallableType&& callable)
noexcept(noexcept(ExecuteAndTime(std::forward<CallableType>(callable))))
{
ExecuteAndTime(std::forward<CallableType>(callable));
}
/**
* @returns The elapsed time in ChronoType units.
*/
ChronoType GetElapsedTime() const
{
return m_elapsedTime;
}
/**
* @returns A character array containing the chrono resolution name.
*/
constexpr auto GetUnitsAsString() const
{
return TypeName<ChronoType>::value;
}
private:
/**
* @todo Once C++17 arrives: `noexcept(std::is_nothrow_callable_v<CallableType>)`
*/
template<typename CallableType>
void ExecuteAndTime(CallableType&& callable) noexcept(noexcept(callable))
{
const auto start = std::chrono::high_resolution_clock::now();
callable();
const auto end = std::chrono::high_resolution_clock::now();
m_elapsedTime = std::chrono::duration_cast<ChronoType>(end - start);
}
ChronoType m_elapsedTime;
};
#define TIME_IN_NANOSECONDS(code, message) \
Stopwatch<std::chrono::nanoseconds>( \
[&] { code; }, \
message);
#define TIME_IN_MICROSECONDS(code, message) \
Stopwatch<std::chrono::microseconds>( \
[&] { code; }, \
message);
#define TIME_IN_MILLISECONDS(code, message) \
Stopwatch<std::chrono::milliseconds>( \
[&] { code; }, \
message);
#define TIME_IN_SECONDS(code, message) \
Stopwatch<std::chrono::seconds>( \
[&] { code; }, \
message);
#define TIME_IN_MINUTES(code, message) \
Stopwatch<std::chrono::minutes>( \
[&] { code; }, \
message);
#define TIME_IN_HOURS(code, message) \
Stopwatch<std::chrono::hours>( \
[&] { code; }, \
message);
<|endoftext|> |
<commit_before>//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "mqtt_adapter.hpp"
#include <boost/log/trivial.hpp>
#include <boost/uuid/name_generator_sha1.hpp>
#include <mqtt/async_client.hpp>
#include <mqtt/setup_log.hpp>
#include "configuration/config_options.hpp"
#include "device_model/device.hpp"
#include "pipeline/convert_sample.hpp"
#include "pipeline/deliver.hpp"
#include "pipeline/delta_filter.hpp"
#include "pipeline/duplicate_filter.hpp"
#include "pipeline/message_mapper.hpp"
#include "pipeline/period_filter.hpp"
#include "pipeline/shdr_token_mapper.hpp"
#include "pipeline/shdr_tokenizer.hpp"
#include "pipeline/timestamp_extractor.hpp"
#include "pipeline/topic_mapper.hpp"
#include "pipeline/upcase_value.hpp"
using namespace std;
namespace asio = boost::asio;
namespace mtconnect
{
using namespace observation;
using namespace entity;
using namespace pipeline;
using namespace adapter;
namespace source
{
template <typename... Ts>
using mqtt_client_ptr = decltype(mqtt::make_async_client(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_tls_client_ptr = decltype(mqtt::make_tls_async_client(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_client_ws_ptr = decltype(mqtt::make_async_client_ws(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_tls_client_ws_ptr = decltype(mqtt::make_tls_async_client_ws(std::declval<Ts>()...));
using mqtt_client = mqtt_client_ptr<boost::asio::io_context &, std::string, std::uint16_t,
mqtt::protocol_version>;
using mqtt_tls_client = mqtt_tls_client_ptr<boost::asio::io_context &, std::string,
std::uint16_t, mqtt::protocol_version>;
using mqtt_client_ws = mqtt_client_ws_ptr<boost::asio::io_context &, std::string, std::uint16_t,
std::string, mqtt::protocol_version>;
using mqtt_tls_client_ws =
mqtt_tls_client_ws_ptr<boost::asio::io_context &, std::string, std::uint16_t, std::string,
mqtt::protocol_version>;
template <typename Derived>
class MqttAdapterClientBase : public MqttAdapterImpl
{
public:
MqttAdapterClientBase(boost::asio::io_context &ioContext, const ConfigOptions &options,
MqttPipeline *pipeline)
: MqttAdapterImpl(ioContext),
m_options(options),
m_host(*GetOption<std::string>(options, configuration::Host)),
m_port(GetOption<int>(options, configuration::Port).value_or(1883)),
m_pipeline(pipeline),
m_reconnectTimer(ioContext)
{
std::stringstream url;
url << "mqtt://" << m_host << ':' << m_port;
m_url = url.str();
std::stringstream identity;
identity << '_' << m_host << '_' << m_port;
boost::uuids::detail::sha1 sha1;
sha1.process_bytes(identity.str().c_str(), identity.str().length());
boost::uuids::detail::sha1::digest_type digest;
sha1.get_digest(digest);
identity.str("");
identity << std::hex << digest[0] << digest[1] << digest[2];
m_identity = std::string("_") + (identity.str()).substr(0, 10);
}
~MqttAdapterClientBase() { stop(); }
Derived &derived() { return static_cast<Derived &>(*this); }
bool start() override
{
NAMED_SCOPE("MqttAdapterClient::start");
#ifndef NDEBUG
mqtt::setup_log(mqtt::severity_level::debug);
#else
mqtt::setup_log();
#endif
auto client = derived().getClient();
client->set_connack_handler([this](bool sp, mqtt::connect_return_code connack_return_code) {
if (connack_return_code == mqtt::connect_return_code::accepted)
{
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "CONNECTED"s}, {"source", m_identity}});
m_pipeline->run(entity);
subscribe();
}
else
{
reconnect();
}
return true;
});
client->set_close_handler([this]() {
LOG(info) << "MQTT " << m_url << ": connection closed";
// Queue on a strand
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "DISCONNECTED"s}, {"source", m_identity}});
m_pipeline->run(entity);
reconnect();
});
client->set_suback_handler(
[this](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) {
LOG(debug) << "suback received. packet_id: " << packet_id;
for (auto const &e : results)
{
LOG(debug) << "subscribe result: " << e;
// Do something if the subscription failed...
}
return true;
});
client->set_error_handler([this](mqtt::error_code ec) {
LOG(error) << "error: " << ec.message();
reconnect();
});
client->set_publish_handler([this](mqtt::optional<std::uint16_t> packet_id,
mqtt::publish_options pubopts, mqtt::buffer topic_name,
mqtt::buffer contents) {
if (packet_id)
LOG(debug) << "packet_id: " << *packet_id;
LOG(debug) << "topic_name: " << topic_name;
LOG(debug) << "contents: " << contents;
receive(topic_name, contents);
return true;
});
m_running = true;
connect();
return true;
}
void stop() override
{
m_running = false;
derived().getClient().reset();
}
protected:
void subscribe()
{
NAMED_SCOPE("MqttAdapterImpl::subscribe");
auto topics = GetOption<StringList>(m_options, configuration::Topics);
std::vector<std::tuple<string, mqtt::subscribe_options>> topicList;
if (topics)
{
for (auto &topic : *topics)
{
auto loc = topic.find(':');
if (loc != string::npos)
{
topicList.emplace_back(make_tuple(topic.substr(loc + 1), mqtt::qos::at_least_once));
}
}
}
else
{
LOG(warning) << "No topics specified, subscribing to '#'";
topicList.emplace_back(make_tuple("#"s, mqtt::qos::at_least_once));
}
m_subPid = derived().getClient()->acquire_unique_packet_id();
derived().getClient()->async_subscribe(m_subPid, topicList, [](mqtt::error_code ec) {
if (ec)
{
LOG(error) << "Subscribe failed: " << ec.message();
}
});
}
void connect()
{
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "CONNECTING"s}, {"source", m_identity}});
m_pipeline->run(entity);
derived().getClient()->async_connect();
}
void receive(mqtt::buffer &topic, mqtt::buffer &contents)
{
auto entity =
make_shared<pipeline::Message>("Topic", Properties {{"VALUE", string(contents)},
{"topic", string(topic)},
{"source", m_identity}});
m_pipeline->run(entity);
}
void reconnect()
{
NAMED_SCOPE("MqttAdapterClient::reconnect");
if (!m_running)
return;
LOG(info) << "Start reconnect timer";
// Set an expiry time relative to now.
m_reconnectTimer.expires_after(std::chrono::seconds(5));
m_reconnectTimer.async_wait([this](const boost::system::error_code &error) {
if (error != boost::asio::error::operation_aborted)
{
LOG(info) << "Reconnect now !!";
// Connect
derived().getClient()->async_connect([this](mqtt::error_code ec) {
LOG(info) << "async_connect callback: " << ec.message();
if (ec && ec != boost::asio::error::operation_aborted)
{
reconnect();
}
});
}
});
}
protected:
ConfigOptions m_options;
std::string m_host;
unsigned int m_port;
std::uint16_t m_subPid {0};
bool m_running;
MqttPipeline *m_pipeline;
boost::asio::steady_timer m_reconnectTimer;
};
class MqttAdapterClient : public MqttAdapterClientBase<MqttAdapterClient>
{
public:
using base = MqttAdapterClientBase<MqttAdapterClient>;
using Client = mqtt_client;
using base::base;
auto getClient()
{
if (!m_client)
{
m_client = mqtt::make_async_client(m_ioContext, m_host, m_port);
m_client->set_client_id(m_identity);
m_client->clean_session();
m_client->set_keep_alive_sec(10);
}
return m_client;
}
protected:
Client m_client;
};
class MqttAdapterTlsClient : public MqttAdapterClientBase<MqttAdapterTlsClient>
{
public:
using base = MqttAdapterClientBase<MqttAdapterTlsClient>;
using Client = mqtt_tls_client;
using base::base;
auto &getClient()
{
if (!m_client)
{
m_client = mqtt::make_tls_async_client(m_ioContext, m_host, m_port);
m_client->set_client_id(m_identity);
m_client->clean_session();
m_client->set_keep_alive_sec(10);
auto cacert = GetOption<string>(m_options, configuration::MqttCaCert);
if (cacert)
{
m_client->get_ssl_context().load_verify_file(*cacert);
}
}
return m_client;
}
protected:
Client m_client;
};
//
// class MqttAdapterClientWs : public MqttAdapterClientBase<mqtt_client_ws>
// {
// public:
// using base = MqttAdapterClientBase<mqtt_client_ws>;
// using base::base;
// };
//
// class MqttAdapterNoTlsClientWs : public MqttAdapterClientBase<mqtt_tls_client_ws>
// {
// public:
// using base = MqttAdapterClientBase<mqtt_tls_client_ws>;
// using base::base;
// };
MqttAdapter::MqttAdapter(boost::asio::io_context &context, const ConfigOptions &options,
std::unique_ptr<MqttPipeline> &pipeline)
: Source("MQTT", options),
m_ioContext(context),
m_host(*GetOption<std::string>(options, configuration::Host)),
m_port(GetOption<int>(options, configuration::Port).value_or(1883)),
m_pipeline(std::move(pipeline))
{
if (IsOptionSet(options, configuration::MqttTls))
m_client = make_shared<MqttAdapterTlsClient>(m_ioContext, options, m_pipeline.get());
else
m_client = make_shared<MqttAdapterClient>(m_ioContext, options, m_pipeline.get());
m_name = m_client->getIdentity();
m_options[configuration::AdapterIdentity] = m_name;
m_pipeline->build(m_options);
m_identity = m_client->getIdentity();
m_url = m_client->getUrl();
}
void MqttPipeline::build(const ConfigOptions &options)
{
clear();
m_options = options;
auto identity = GetOption<string>(options, configuration::AdapterIdentity);
StringList devices;
auto list = GetOption<StringList>(options, configuration::AdditionalDevices);
if (list)
devices = *list;
auto device = GetOption<string>(options, configuration::Device);
if (device)
{
devices.emplace_front(*device);
auto dp = m_context->m_contract->findDevice(*device);
if (dp)
{
dp->setOptions(options);
}
}
TransformPtr next;
bind(make_shared<DeliverConnectionStatus>(
m_context, devices, IsOptionSet(options, configuration::AutoAvailable)));
bind(make_shared<DeliverCommand>(m_context, device));
next = bind(make_shared<TopicMapper>(
m_context, GetOption<string>(m_options, configuration::Device).value_or("")));
auto map1 = next->bind(make_shared<JsonMapper>(m_context));
auto map2 = next->bind(make_shared<DataMapper>(m_context));
next = make_shared<NullTransform>(TypeGuard<Observation, asset::Asset>(SKIP));
map1->bind(next);
map2->bind(next);
// Go directly to asset delivery
std::optional<string> assetMetrics;
if (identity)
assetMetrics = *identity + "_asset_update_rate";
next->bind(make_shared<DeliverAsset>(m_context, assetMetrics));
next->bind(make_shared<DeliverAssetCommand>(m_context));
// Uppercase Events
if (IsOptionSet(m_options, configuration::UpcaseDataItemValue))
next = next->bind(make_shared<UpcaseValue>());
// Filter dups, by delta, and by period
next = next->bind(make_shared<DuplicateFilter>(m_context));
next = next->bind(make_shared<DeltaFilter>(m_context));
next = next->bind(make_shared<PeriodFilter>(m_context));
// Convert values
if (IsOptionSet(m_options, configuration::ConversionRequired))
next = next->bind(make_shared<ConvertSample>());
// Deliver
std::optional<string> obsMetrics;
if (identity)
obsMetrics = *identity + "_observation_update_rate";
next->bind(make_shared<DeliverObservation>(m_context, obsMetrics));
}
} // namespace source
} // namespace mtconnect
<commit_msg>cleaned up mqtt derived classes<commit_after>//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "mqtt_adapter.hpp"
#include <boost/log/trivial.hpp>
#include <boost/uuid/name_generator_sha1.hpp>
#include <mqtt/async_client.hpp>
#include <mqtt/setup_log.hpp>
#include "configuration/config_options.hpp"
#include "device_model/device.hpp"
#include "pipeline/convert_sample.hpp"
#include "pipeline/deliver.hpp"
#include "pipeline/delta_filter.hpp"
#include "pipeline/duplicate_filter.hpp"
#include "pipeline/message_mapper.hpp"
#include "pipeline/period_filter.hpp"
#include "pipeline/shdr_token_mapper.hpp"
#include "pipeline/shdr_tokenizer.hpp"
#include "pipeline/timestamp_extractor.hpp"
#include "pipeline/topic_mapper.hpp"
#include "pipeline/upcase_value.hpp"
using namespace std;
namespace asio = boost::asio;
namespace mtconnect
{
using namespace observation;
using namespace entity;
using namespace pipeline;
using namespace adapter;
namespace source
{
template <typename... Ts>
using mqtt_client_ptr = decltype(mqtt::make_async_client(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_tls_client_ptr = decltype(mqtt::make_tls_async_client(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_client_ws_ptr = decltype(mqtt::make_async_client_ws(std::declval<Ts>()...));
template <typename... Ts>
using mqtt_tls_client_ws_ptr = decltype(mqtt::make_tls_async_client_ws(std::declval<Ts>()...));
using mqtt_client = mqtt_client_ptr<boost::asio::io_context &, std::string, std::uint16_t,
mqtt::protocol_version>;
using mqtt_tls_client = mqtt_tls_client_ptr<boost::asio::io_context &, std::string,
std::uint16_t, mqtt::protocol_version>;
using mqtt_client_ws = mqtt_client_ws_ptr<boost::asio::io_context &, std::string, std::uint16_t,
std::string, mqtt::protocol_version>;
using mqtt_tls_client_ws =
mqtt_tls_client_ws_ptr<boost::asio::io_context &, std::string, std::uint16_t, std::string,
mqtt::protocol_version>;
template <typename Derived>
class MqttAdapterClientBase : public MqttAdapterImpl
{
public:
MqttAdapterClientBase(boost::asio::io_context &ioContext, const ConfigOptions &options,
MqttPipeline *pipeline)
: MqttAdapterImpl(ioContext),
m_options(options),
m_host(*GetOption<std::string>(options, configuration::Host)),
m_port(GetOption<int>(options, configuration::Port).value_or(1883)),
m_pipeline(pipeline),
m_reconnectTimer(ioContext)
{
std::stringstream url;
url << "mqtt://" << m_host << ':' << m_port;
m_url = url.str();
std::stringstream identity;
identity << '_' << m_host << '_' << m_port;
boost::uuids::detail::sha1 sha1;
sha1.process_bytes(identity.str().c_str(), identity.str().length());
boost::uuids::detail::sha1::digest_type digest;
sha1.get_digest(digest);
identity.str("");
identity << std::hex << digest[0] << digest[1] << digest[2];
m_identity = std::string("_") + (identity.str()).substr(0, 10);
}
~MqttAdapterClientBase() { stop(); }
Derived &derived() { return static_cast<Derived &>(*this); }
bool start() override
{
NAMED_SCOPE("MqttAdapterClient::start");
#ifndef NDEBUG
mqtt::setup_log(mqtt::severity_level::debug);
#else
mqtt::setup_log();
#endif
auto client = derived().getClient();
client->set_client_id(m_identity);
client->clean_session();
client->set_keep_alive_sec(10);
client->set_connack_handler([this](bool sp, mqtt::connect_return_code connack_return_code) {
if (connack_return_code == mqtt::connect_return_code::accepted)
{
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "CONNECTED"s}, {"source", m_identity}});
m_pipeline->run(entity);
subscribe();
}
else
{
reconnect();
}
return true;
});
client->set_close_handler([this]() {
LOG(info) << "MQTT " << m_url << ": connection closed";
// Queue on a strand
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "DISCONNECTED"s}, {"source", m_identity}});
m_pipeline->run(entity);
reconnect();
});
client->set_suback_handler(
[this](std::uint16_t packet_id, std::vector<mqtt::suback_return_code> results) {
LOG(debug) << "suback received. packet_id: " << packet_id;
for (auto const &e : results)
{
LOG(debug) << "subscribe result: " << e;
// Do something if the subscription failed...
}
return true;
});
client->set_error_handler([this](mqtt::error_code ec) {
LOG(error) << "error: " << ec.message();
reconnect();
});
client->set_publish_handler([this](mqtt::optional<std::uint16_t> packet_id,
mqtt::publish_options pubopts, mqtt::buffer topic_name,
mqtt::buffer contents) {
if (packet_id)
LOG(debug) << "packet_id: " << *packet_id;
LOG(debug) << "topic_name: " << topic_name;
LOG(debug) << "contents: " << contents;
receive(topic_name, contents);
return true;
});
m_running = true;
connect();
return true;
}
void stop() override
{
m_running = false;
derived().getClient().reset();
}
protected:
void subscribe()
{
NAMED_SCOPE("MqttAdapterImpl::subscribe");
auto topics = GetOption<StringList>(m_options, configuration::Topics);
std::vector<std::tuple<string, mqtt::subscribe_options>> topicList;
if (topics)
{
for (auto &topic : *topics)
{
auto loc = topic.find(':');
if (loc != string::npos)
{
topicList.emplace_back(make_tuple(topic.substr(loc + 1), mqtt::qos::at_least_once));
}
}
}
else
{
LOG(warning) << "No topics specified, subscribing to '#'";
topicList.emplace_back(make_tuple("#"s, mqtt::qos::at_least_once));
}
m_subPid = derived().getClient()->acquire_unique_packet_id();
derived().getClient()->async_subscribe(m_subPid, topicList, [](mqtt::error_code ec) {
if (ec)
{
LOG(error) << "Subscribe failed: " << ec.message();
}
});
}
void connect()
{
auto entity = make_shared<Entity>(
"ConnectionStatus", Properties {{"VALUE", "CONNECTING"s}, {"source", m_identity}});
m_pipeline->run(entity);
derived().getClient()->async_connect();
}
void receive(mqtt::buffer &topic, mqtt::buffer &contents)
{
auto entity =
make_shared<pipeline::Message>("Topic", Properties {{"VALUE", string(contents)},
{"topic", string(topic)},
{"source", m_identity}});
m_pipeline->run(entity);
}
void reconnect()
{
NAMED_SCOPE("MqttAdapterClient::reconnect");
if (!m_running)
return;
LOG(info) << "Start reconnect timer";
// Set an expiry time relative to now.
m_reconnectTimer.expires_after(std::chrono::seconds(5));
m_reconnectTimer.async_wait([this](const boost::system::error_code &error) {
if (error != boost::asio::error::operation_aborted)
{
LOG(info) << "Reconnect now !!";
// Connect
derived().getClient()->async_connect([this](mqtt::error_code ec) {
LOG(info) << "async_connect callback: " << ec.message();
if (ec && ec != boost::asio::error::operation_aborted)
{
reconnect();
}
});
}
});
}
protected:
ConfigOptions m_options;
std::string m_host;
unsigned int m_port;
std::uint16_t m_subPid {0};
bool m_running;
MqttPipeline *m_pipeline;
boost::asio::steady_timer m_reconnectTimer;
};
class MqttAdapterClient : public MqttAdapterClientBase<MqttAdapterClient>
{
public:
using base = MqttAdapterClientBase<MqttAdapterClient>;
using Client = mqtt_client;
using base::base;
auto getClient()
{
if (!m_client)
{
m_client = mqtt::make_async_client(m_ioContext, m_host, m_port);
}
return m_client;
}
protected:
Client m_client;
};
class MqttAdapterTlsClient : public MqttAdapterClientBase<MqttAdapterTlsClient>
{
public:
using base = MqttAdapterClientBase<MqttAdapterTlsClient>;
using Client = mqtt_tls_client;
using base::base;
auto &getClient()
{
if (!m_client)
{
m_client = mqtt::make_tls_async_client(m_ioContext, m_host, m_port);
auto cacert = GetOption<string>(m_options, configuration::MqttCaCert);
if (cacert)
{
m_client->get_ssl_context().load_verify_file(*cacert);
}
}
return m_client;
}
protected:
Client m_client;
};
//
// class MqttAdapterClientWs : public MqttAdapterClientBase<mqtt_client_ws>
// {
// public:
// using base = MqttAdapterClientBase<mqtt_client_ws>;
// using base::base;
// };
//
// class MqttAdapterNoTlsClientWs : public MqttAdapterClientBase<mqtt_tls_client_ws>
// {
// public:
// using base = MqttAdapterClientBase<mqtt_tls_client_ws>;
// using base::base;
// };
MqttAdapter::MqttAdapter(boost::asio::io_context &context, const ConfigOptions &options,
std::unique_ptr<MqttPipeline> &pipeline)
: Source("MQTT", options),
m_ioContext(context),
m_host(*GetOption<std::string>(options, configuration::Host)),
m_port(GetOption<int>(options, configuration::Port).value_or(1883)),
m_pipeline(std::move(pipeline))
{
if (IsOptionSet(options, configuration::MqttTls))
m_client = make_shared<MqttAdapterTlsClient>(m_ioContext, options, m_pipeline.get());
else
m_client = make_shared<MqttAdapterClient>(m_ioContext, options, m_pipeline.get());
m_name = m_client->getIdentity();
m_options[configuration::AdapterIdentity] = m_name;
m_pipeline->build(m_options);
m_identity = m_client->getIdentity();
m_url = m_client->getUrl();
}
void MqttPipeline::build(const ConfigOptions &options)
{
clear();
m_options = options;
auto identity = GetOption<string>(options, configuration::AdapterIdentity);
StringList devices;
auto list = GetOption<StringList>(options, configuration::AdditionalDevices);
if (list)
devices = *list;
auto device = GetOption<string>(options, configuration::Device);
if (device)
{
devices.emplace_front(*device);
auto dp = m_context->m_contract->findDevice(*device);
if (dp)
{
dp->setOptions(options);
}
}
TransformPtr next;
bind(make_shared<DeliverConnectionStatus>(
m_context, devices, IsOptionSet(options, configuration::AutoAvailable)));
bind(make_shared<DeliverCommand>(m_context, device));
next = bind(make_shared<TopicMapper>(
m_context, GetOption<string>(m_options, configuration::Device).value_or("")));
auto map1 = next->bind(make_shared<JsonMapper>(m_context));
auto map2 = next->bind(make_shared<DataMapper>(m_context));
next = make_shared<NullTransform>(TypeGuard<Observation, asset::Asset>(SKIP));
map1->bind(next);
map2->bind(next);
// Go directly to asset delivery
std::optional<string> assetMetrics;
if (identity)
assetMetrics = *identity + "_asset_update_rate";
next->bind(make_shared<DeliverAsset>(m_context, assetMetrics));
next->bind(make_shared<DeliverAssetCommand>(m_context));
// Uppercase Events
if (IsOptionSet(m_options, configuration::UpcaseDataItemValue))
next = next->bind(make_shared<UpcaseValue>());
// Filter dups, by delta, and by period
next = next->bind(make_shared<DuplicateFilter>(m_context));
next = next->bind(make_shared<DeltaFilter>(m_context));
next = next->bind(make_shared<PeriodFilter>(m_context));
// Convert values
if (IsOptionSet(m_options, configuration::ConversionRequired))
next = next->bind(make_shared<ConvertSample>());
// Deliver
std::optional<string> obsMetrics;
if (identity)
obsMetrics = *identity + "_observation_update_rate";
next->bind(make_shared<DeliverObservation>(m_context, obsMetrics));
}
} // namespace source
} // namespace mtconnect
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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 <Core/Algorithms/Legacy/Fields/ConvertMeshType/ConvertMeshToTriSurfMesh.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
bool ConvertMeshToTriSurfMeshAlgo::run(FieldHandle input, FieldHandle& output)
{
//! Mark start of algorithm and report that we will not report progress
algo_start("ConvertMeshToTriSurfMesh");
if (input.get_rep() == 0)
{
error("No input field");
algo_end(); return (false);
}
// no precompiled version available, so compile one
// Create information fields and fill them out with the data types of the input
FieldInformation fi(input);
FieldInformation fo(input);
// Ignore non linear cases for now
if (fi.is_nonlinear())
{
error("This function has not yet been defined for non-linear elements");
algo_end(); return (false);
}
// In case it is already a trisurf skip algorithm
if (fi.is_tri_element())
{
output = input;
remark("Input is already a TriSurfMesh; just copying input to output");
algo_end(); return (true);
}
// Only quads we know how to process, return an error for any other type
if (!fi.is_quad_element())
{
error("This function has been defined for quadrilateral elements only");
algo_end(); return (false);
}
// Fill out the output type by altering the mesh type
// Everything else stays the same
fo.make_trisurfmesh();
// Create the output field
output = CreateField(fo);
// If creation fails return an error to the user
if (output.get_rep() == 0)
{
error("Could not create output field");
algo_end(); return (false);
}
// Algorithm starts here
// Get Virtual interface classes:
VMesh* imesh = input->vmesh();
VMesh* omesh = output->vmesh();
VField* ifield = input->vfield();
VField* ofield = output->vfield();
// Get the number of nodes and elements in the input mesh
VMesh::size_type num_nodes = imesh->num_nodes();
VMesh::size_type num_elems = imesh->num_elems();
// Copy all the nodes
for (VMesh::Node::index_type i=0; i<num_nodes; i++)
{
Point p;
imesh->get_center(p,i);
omesh->add_node(p,i);
}
// Record which element index to use for filling out data
std::vector<VMesh::size_type> elemmap(num_elems);
// If it is a structured mesh use an alternating scheme to get a better mesh
if (fi.is_image()|| fi.is_structquadsurf())
{
// Reserve two arrays to split quadrilateral
VMesh::Node::array_type tri1(3), tri2(3);
VMesh::dimension_type dim;
VMesh::Node::array_type nodes;
// Get the structured dimensions, dimension_type has always three elements
// But here only the first two will be filled out
imesh->get_dimensions(dim);
// Loop over each element and split the quadrilaterals in two triangles
for (VMesh::Elem::index_type i=0; i<num_elems; i++)
{
// Get the nodes that make up a quadrilateral.
// Even for degenerate elements for nodes will be returned
imesh->get_nodes(nodes,i);
// Figure out the red-black scheme
int jj = i/dim[1]; int ii = i%dim[1];
if ((ii^jj)&1)
{
// Splitting option 1
tri1[0] = nodes[0]; tri1[1] = nodes[1]; tri1[2] = nodes[2];
tri2[0] = nodes[2]; tri2[1] = nodes[3]; tri2[2] = nodes[0];
}
else
{
// SPlitting option 2
tri1[0] = nodes[1]; tri1[1] = nodes[2]; tri1[2] = nodes[3];
tri2[0] = nodes[3]; tri2[1] = nodes[0]; tri2[2] = nodes[1];
}
elemmap[i] = 2;
// Add the elements to the output mesh
omesh->add_elem(tri1);
omesh->add_elem(tri2);
}
}
else
{
// Alternative scheme: unstructured so we just split each quadrilateral
VMesh::Node::array_type tri1(3), tri2(3);
VMesh::Node::array_type nodes;
for (VMesh::Elem::index_type i=0; i<num_elems; i++)
{
imesh->get_nodes(nodes,i);
tri1[0] = nodes[0]; tri1[1] = nodes[1]; tri1[2] = nodes[2];
tri2[0] = nodes[2]; tri2[1] = nodes[3]; tri2[2] = nodes[0];
// Check for degenerate elements and record how many elements we are adding
if (tri1[0]==tri1[1] || tri1[1]==tri1[2] || tri1[0]==tri1[2])
{
if (!(tri2[0]==tri2[1] || tri2[1]==tri2[2] || tri2[0]==tri2[2]))
{
omesh->add_elem(tri2);
elemmap[i] = 1;
}
else
{
elemmap[i] = 0;
}
}
else if (tri2[0]==tri2[1] || tri2[1]==tri2[2] || tri2[0]==tri2[2])
{
omesh->add_elem(tri1);
elemmap[i] = 1;
}
else
{
omesh->add_elem(tri1);
omesh->add_elem(tri2);
elemmap[i] = 2;
}
}
}
ofield->resize_fdata();
if (ifield->basis_order() == 1)
{
// Copy all the data
ofield->copy_values(ifield);
}
else if (ifield->basis_order() == 0)
{
VMesh::index_type k = 0;
for(VMesh::index_type i=0; i<num_elems; i++)
{
if (elemmap[i] == 1)
{
ofield->copy_value(ifield,i,k); k++;
}
else if (elemmap[i] == 2)
{
ofield->copy_value(ifield,i,k); k++;
ofield->copy_value(ifield,i,k); k++;
}
}
}
// Copy properties in property manager
output->copy_properties(input.get_rep());
// Success:
algo_end(); return (true);
}
<commit_msg>algo compiles<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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 <Core/Algorithms/Legacy/Fields/ConvertMeshType/ConvertMeshToTriSurfMesh.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
bool ConvertMeshToTriSurfMeshAlgo::run(FieldHandle input, FieldHandle& output)
{
ScopedAlgorithmStatusReporter asr(this, "ConvertMeshToTriSurfMesh");
if (!input)
{
error("No input field");
return (false);
}
// Create information fields and fill them out with the data types of the input
FieldInformation fi(input);
FieldInformation fo(input);
// Ignore non linear cases for now
if (fi.is_nonlinear())
{
error("This function has not yet been defined for non-linear elements");
return (false);
}
// In case it is already a trisurf skip algorithm
if (fi.is_tri_element())
{
output = input;
remark("Input is already a TriSurfMesh; just copying input to output");
return (true);
}
// Only quads we know how to process, return an error for any other type
if (!fi.is_quad_element())
{
error("This function has been defined for quadrilateral elements only");
return (false);
}
// Fill out the output type by altering the mesh type
// Everything else stays the same
fo.make_trisurfmesh();
// Create the output field
output = CreateField(fo);
// If creation fails return an error to the user
if (!output)
{
error("Could not create output field");
return (false);
}
// Algorithm starts here
// Get Virtual interface classes:
VMesh* imesh = input->vmesh();
VMesh* omesh = output->vmesh();
VField* ifield = input->vfield();
VField* ofield = output->vfield();
// Get the number of nodes and elements in the input mesh
VMesh::size_type num_nodes = imesh->num_nodes();
VMesh::size_type num_elems = imesh->num_elems();
// Copy all the nodes
for (VMesh::Node::index_type i=0; i<num_nodes; i++)
{
Point p;
imesh->get_center(p,i);
omesh->add_node(p,i);
}
// Record which element index to use for filling out data
std::vector<VMesh::size_type> elemmap(num_elems);
// If it is a structured mesh use an alternating scheme to get a better mesh
if (fi.is_image()|| fi.is_structquadsurf())
{
// Reserve two arrays to split quadrilateral
VMesh::Node::array_type tri1(3), tri2(3);
VMesh::dimension_type dim;
VMesh::Node::array_type nodes;
// Get the structured dimensions, dimension_type has always three elements
// But here only the first two will be filled out
imesh->get_dimensions(dim);
// Loop over each element and split the quadrilaterals in two triangles
for (VMesh::Elem::index_type i=0; i<num_elems; i++)
{
// Get the nodes that make up a quadrilateral.
// Even for degenerate elements for nodes will be returned
imesh->get_nodes(nodes,i);
// Figure out the red-black scheme
auto jj = i/dim[1];
auto ii = i%dim[1];
if ((ii^jj)&1)
{
// Splitting option 1
tri1[0] = nodes[0]; tri1[1] = nodes[1]; tri1[2] = nodes[2];
tri2[0] = nodes[2]; tri2[1] = nodes[3]; tri2[2] = nodes[0];
}
else
{
// SPlitting option 2
tri1[0] = nodes[1]; tri1[1] = nodes[2]; tri1[2] = nodes[3];
tri2[0] = nodes[3]; tri2[1] = nodes[0]; tri2[2] = nodes[1];
}
elemmap[i] = 2;
// Add the elements to the output mesh
omesh->add_elem(tri1);
omesh->add_elem(tri2);
}
}
else
{
// Alternative scheme: unstructured so we just split each quadrilateral
VMesh::Node::array_type tri1(3), tri2(3);
VMesh::Node::array_type nodes;
for (VMesh::Elem::index_type i=0; i<num_elems; i++)
{
imesh->get_nodes(nodes,i);
tri1[0] = nodes[0]; tri1[1] = nodes[1]; tri1[2] = nodes[2];
tri2[0] = nodes[2]; tri2[1] = nodes[3]; tri2[2] = nodes[0];
// Check for degenerate elements and record how many elements we are adding
if (tri1[0]==tri1[1] || tri1[1]==tri1[2] || tri1[0]==tri1[2])
{
if (!(tri2[0]==tri2[1] || tri2[1]==tri2[2] || tri2[0]==tri2[2]))
{
omesh->add_elem(tri2);
elemmap[i] = 1;
}
else
{
elemmap[i] = 0;
}
}
else if (tri2[0]==tri2[1] || tri2[1]==tri2[2] || tri2[0]==tri2[2])
{
omesh->add_elem(tri1);
elemmap[i] = 1;
}
else
{
omesh->add_elem(tri1);
omesh->add_elem(tri2);
elemmap[i] = 2;
}
}
}
ofield->resize_fdata();
if (ifield->basis_order() == 1)
{
// Copy all the data
ofield->copy_values(ifield);
}
else if (ifield->basis_order() == 0)
{
VMesh::index_type k = 0;
for(VMesh::index_type i=0; i<num_elems; i++)
{
if (elemmap[i] == 1)
{
ofield->copy_value(ifield,i,k); k++;
}
else if (elemmap[i] == 2)
{
ofield->copy_value(ifield,i,k); k++;
ofield->copy_value(ifield,i,k); k++;
}
}
}
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
// Copy properties in property manager
output->copy_properties(input);
#endif
// Success:
return (true);
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <thread>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
//thread t1(task1, "Hello");
// Makes the main thread wait for the new thread to finish execution, therefore blocks execution.
//t1.join();
cout << "Currently Programming" << endl;
return 0;
}
<commit_msg>Update #1<commit_after>#include <string>
#include <iostream>
#include <thread>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
//thread coreThread(testTask, "");
//coreThread.join();
cout << "Currently Programming" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/*
* SolveMinNormLeastSqSystem: Select a row or column of a matrix
*
* Written by:
* David Weinstein
* Department of Computer Science
* University of Utah
* June 1999
*
*
* This module computes the minimal norm, least squared solution to a
* nx3 linear system.
* Given four input ColumnMatrices (v0,v1,v2,b),
* find the three coefficients (w0,w1,w2) that minimize:
* | (w0v0 + w1v1 + w2v2) - b |.
* If more than one minimum exisits (the system is under-determined),
* choose the coefficients such that (w0,w1,w2) has minimum norm.
* We output the vector (w0,w1,w2) as a row-matrix,
* and we ouput the ColumnMatrix (called x), which is: | w0v0 + w1v1 + w2v2 |.
*
*/
#include <Core/Math/Mat.h>
#include <Core/Datatypes/ColumnMatrix.h>
#include <Dataflow/Network/Ports/MatrixPort.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/GuiInterface/GuiVar.h>
#include <iostream>
#include <sstream>
#include <math.h>
namespace SCIRun {
class SolveMinNormLeastSqSystem : public Module {
public:
SolveMinNormLeastSqSystem(GuiContext* ctx);
virtual ~SolveMinNormLeastSqSystem();
virtual void execute();
};
DECLARE_MAKER(SolveMinNormLeastSqSystem)
SolveMinNormLeastSqSystem::SolveMinNormLeastSqSystem(GuiContext* ctx)
: Module("SolveMinNormLeastSqSystem", ctx, Filter, "Math", "SCIRun")
{
}
SolveMinNormLeastSqSystem::~SolveMinNormLeastSqSystem()
{
}
void
SolveMinNormLeastSqSystem::execute()
{
int i;
std::vector<MatrixHandle> in(4);
if (!get_input_handle("BasisVec1(Col)", in[0])) return;
if (!get_input_handle("BasisVec2(Col)", in[1])) return;
if (!get_input_handle("BasisVec3(Col)", in[2])) return;
if (!get_input_handle("TargetVec(Col)", in[3])) return;
MatrixHandle tmp;
for (i = 0; i < 4; i++) { tmp = in[i]->column(); in[i] = tmp; }
std::vector<ColumnMatrix *> Ac(4);
for (i = 0; i < 4; i++) {
Ac[i] = in[i]->column();
}
int size = Ac[0]->nrows();
for (i = 1; i < 4; i++) {
if ( Ac[i]->nrows() != size ) {
error("ColumnMatrices are different sizes");
return;
}
}
double *A[3];
for (i=0; i<3; i++) {
A[i]=Ac[i]->get_data_pointer();
}
double *b = Ac[3]->get_data_pointer();
double *bprime = new double[size];
double *x = new double[3];
min_norm_least_sq_3(A, b, x, bprime, size);
ColumnMatrix* w_vec = new ColumnMatrix;
w_vec->set_data(x);
MatrixHandle w_vecH(w_vec);
send_output_handle("WeightVec(Col)", w_vecH);
ColumnMatrix* bprime_vec = new ColumnMatrix;
bprime_vec->set_data(bprime);
MatrixHandle bprime_vecH(bprime_vec);
send_output_handle("ResultVec(Col)", bprime_vecH);
}
} // End namespace SCIRun
<commit_msg>Delete unneeded code<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/*
* SolveMinNormLeastSqSystem: Select a row or column of a matrix
*
* Written by:
* David Weinstein
* Department of Computer Science
* University of Utah
* June 1999
*
*
* This module computes the minimal norm, least squared solution to a
* nx3 linear system.
* Given four input ColumnMatrices (v0,v1,v2,b),
* find the three coefficients (w0,w1,w2) that minimize:
* | (w0v0 + w1v1 + w2v2) - b |.
* If more than one minimum exisits (the system is under-determined),
* choose the coefficients such that (w0,w1,w2) has minimum norm.
* We output the vector (w0,w1,w2) as a row-matrix,
* and we ouput the ColumnMatrix (called x), which is: | w0v0 + w1v1 + w2v2 |.
*
*/
#include <Core/Math/Mat.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
SolveMinNormLeastSqSystem::SolveMinNormLeastSqSystem(GuiContext* ctx)
: Module("SolveMinNormLeastSqSystem", ctx, Filter, "Math", "SCIRun")
{
}
SolveMinNormLeastSqSystem::~SolveMinNormLeastSqSystem()
{
}
void
SolveMinNormLeastSqSystem::execute()
{
int i;
std::vector<MatrixHandle> in(4);
if (!get_input_handle("BasisVec1(Col)", in[0])) return;
if (!get_input_handle("BasisVec2(Col)", in[1])) return;
if (!get_input_handle("BasisVec3(Col)", in[2])) return;
if (!get_input_handle("TargetVec(Col)", in[3])) return;
MatrixHandle tmp;
for (i = 0; i < 4; i++) { tmp = in[i]->column(); in[i] = tmp; }
std::vector<ColumnMatrix *> Ac(4);
for (i = 0; i < 4; i++) {
Ac[i] = in[i]->column();
}
int size = Ac[0]->nrows();
for (i = 1; i < 4; i++) {
if ( Ac[i]->nrows() != size ) {
error("ColumnMatrices are different sizes");
return;
}
}
double *A[3];
for (i=0; i<3; i++) {
A[i]=Ac[i]->get_data_pointer();
}
double *b = Ac[3]->get_data_pointer();
double *bprime = new double[size];
double *x = new double[3];
min_norm_least_sq_3(A, b, x, bprime, size);
ColumnMatrix* w_vec = new ColumnMatrix;
w_vec->set_data(x);
MatrixHandle w_vecH(w_vec);
send_output_handle("WeightVec(Col)", w_vecH);
ColumnMatrix* bprime_vec = new ColumnMatrix;
bprime_vec->set_data(bprime);
MatrixHandle bprime_vecH(bprime_vec);
send_output_handle("ResultVec(Col)", bprime_vecH);
}
} // End namespace SCIRun
<|endoftext|> |
<commit_before>#pragma once
#include "keilo_application.hpp"
#include <memory>
#include <list>
#include <atomic>
#include <mutex>
#include <queue>
#include <boost/asio.hpp>
class keilo_server
{
public:
keilo_server(int port);
~keilo_server();
public: // user accessable functions
void run();
void run_local();
std::string import_file(std::string file_name, bool ps = true);
private: // outupt
void print_output();
void push_output(const std::string message);
std::thread print_thread;
std::queue<std::string> m_outputs;
std::mutex m_output_mutex;
std::atomic<bool> printing = false;
private: // networking
void accept_client();
void process_client(boost::asio::ip::tcp::socket& client);
const std::string process_message(std::string message);
void disconnect_client(boost::asio::ip::tcp::socket client);
std::thread accept_thread;
boost::asio::io_service m_io_service;
int m_port;
boost::asio::ip::tcp::acceptor m_acceptor;
std::list<boost::asio::ip::tcp::socket> m_clients;
std::list<std::thread> m_client_processes;
private: // database processing
std::string create_database(std::string message, size_t pos);
std::string select_database(std::string message, size_t pos);
std::string export_database(std::string message, size_t pos);
std::string import_database(std::string message, size_t pos);
std::string create_table(std::string message, size_t pos);
std::string select_table(std::string message, size_t pos);
std::string join_table(std::string message, size_t pos);
std::string drop_table(std::string message, size_t pos);
std::string select_record(std::string message, size_t pos);
std::string insert_record(std::string message, size_t pos);
std::string update_record(std::string message, size_t pos);
std::string remove_record(std::string message, size_t pos);
private: // commands
const std::string CREATE = "create";
const std::string SELECT = "select";
const std::string JOIN = "join";
const std::string INSERT = "insert";
const std::string UPDATE = "update";
const std::string REMOVE = "remove";
const std::string DROP = "drop";
const std::string EXPORT_FILE = "export";
const std::string IMPORT_FILE = "import";
const std::string CLEAR = "clear";
const std::string DATABASE = "database";
const std::string TABLE = "table";
const std::string RECORD = "record";
private:
std::atomic<bool> running = false;
std::unique_ptr<keilo_application> m_application;
keilo_database* selected_database = nullptr;
keilo_table* selected_table = nullptr;
};<commit_msg>winsock<commit_after>#pragma once
#include "keilo_application.hpp"
#include "keilo_core.hpp"
#include <memory>
#include <list>
#include <atomic>
#include <mutex>
#include <queue>
class keilo_server
{
public:
keilo_server(int port);
~keilo_server();
public: // user accessable functions
void run();
void run_local();
std::string import_file(std::string file_name, bool ps = true);
private: // outupt
void print_output();
void push_output(const std::string message);
std::thread print_thread;
std::queue<std::string> m_outputs;
std::mutex m_output_mutex;
std::atomic<bool> printing = false;
private: // networking
void accept_client();
void process_client(boost::asio::ip::tcp::socket& client);
const std::string process_message(std::string message);
void disconnect_client(boost::asio::ip::tcp::socket client);
std::thread accept_thread;
int m_port;
std::list<client> m_clients;
SOCKET m_socket;
WSADATA m_wsa;
SOCKADDR_IN m_addr;
std::list<std::thread> m_client_processes;
private: // database processing
std::string create_database(std::string message, size_t pos);
std::string select_database(std::string message, size_t pos);
std::string export_database(std::string message, size_t pos);
std::string import_database(std::string message, size_t pos);
std::string create_table(std::string message, size_t pos);
std::string select_table(std::string message, size_t pos);
std::string join_table(std::string message, size_t pos);
std::string drop_table(std::string message, size_t pos);
std::string select_record(std::string message, size_t pos);
std::string insert_record(std::string message, size_t pos);
std::string update_record(std::string message, size_t pos);
std::string remove_record(std::string message, size_t pos);
private: // commands
const std::string CREATE = "create";
const std::string SELECT = "select";
const std::string JOIN = "join";
const std::string INSERT = "insert";
const std::string UPDATE = "update";
const std::string REMOVE = "remove";
const std::string DROP = "drop";
const std::string EXPORT_FILE = "export";
const std::string IMPORT_FILE = "import";
const std::string CLEAR = "clear";
const std::string DATABASE = "database";
const std::string TABLE = "table";
const std::string RECORD = "record";
private:
std::atomic<bool> running = false;
std::unique_ptr<keilo_application> m_application;
};<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680)
#define ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>
#include <PlatformSupport/AttributeVectorEntry.hpp>
class XALAN_PLATFORMSUPPORT_EXPORT AttributeVectorEntryExtended : public AttributeVectorEntry
{
public:
AttributeVectorEntryExtended(
const XMLChVectorType& theName,
const XMLChVectorType& theValue,
const XMLChVectorType& theType,
const XMLChVectorType& theURI = XMLChVectorType(),
const XMLChVectorType& theLocalName = XMLChVectorType()) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(theURI),
m_localName(theLocalName)
{
}
AttributeVectorEntryExtended(
const XMLCh* theName,
const XMLCh* theValue,
const XMLCh* theType,
const XMLCh* theURI,
const XMLCh* theLocalName) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(theURI, theURI + length(theURI) + 1),
m_localName(theLocalName, theLocalName + length(theLocalName) + 1)
{
}
AttributeVectorEntryExtended(
const XMLCh* theName,
const XMLCh* theValue,
const XMLCh* theType) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(0),
m_localName(0)
{
}
AttributeVectorEntryExtended() :
AttributeVectorEntry(),
m_uri(),
m_localName()
{
}
~AttributeVectorEntryExtended()
{
}
void
clear()
{
AttributeVectorEntry::clear();
m_uri.clear();
m_localName.clear();
}
XMLChVectorType m_uri;
XMLChVectorType m_localName;
};
#endif // ATTRIBUTEVECTORENTRY_HEADER_GUARD_1357924680
<commit_msg>Error compiling on AIX.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680)
#define ATTRIBUTEVECTORENTRYEXTENDED_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <PlatformSupport/PlatformSupportDefinitions.hpp>
#include <PlatformSupport/AttributeVectorEntry.hpp>
class XALAN_PLATFORMSUPPORT_EXPORT AttributeVectorEntryExtended : public AttributeVectorEntry
{
public:
AttributeVectorEntryExtended(
const XMLChVectorType& theName,
const XMLChVectorType& theValue,
const XMLChVectorType& theType,
const XMLChVectorType& theURI = XMLChVectorType(),
const XMLChVectorType& theLocalName = XMLChVectorType()) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(theURI),
m_localName(theLocalName)
{
}
AttributeVectorEntryExtended(
const XMLCh* theName,
const XMLCh* theValue,
const XMLCh* theType,
const XMLCh* theURI,
const XMLCh* theLocalName) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(theURI, theURI + length(theURI) + 1),
m_localName(theLocalName, theLocalName + length(theLocalName) + 1)
{
}
AttributeVectorEntryExtended(
const XMLCh* theName,
const XMLCh* theValue,
const XMLCh* theType) :
AttributeVectorEntry(theName, theValue, theType),
m_uri(),
m_localName()
{
}
AttributeVectorEntryExtended() :
AttributeVectorEntry(),
m_uri(),
m_localName()
{
}
~AttributeVectorEntryExtended()
{
}
void
clear()
{
AttributeVectorEntry::clear();
m_uri.clear();
m_localName.clear();
}
XMLChVectorType m_uri;
XMLChVectorType m_localName;
};
#endif // ATTRIBUTEVECTORENTRY_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/math/Math.hpp> //for macro ASSERT_INPUT_ITERATOR
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity) : maxCapacity(maxCapacity) {
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class IteratorT>
SlidingWindow(UInt maxCapacity, IteratorT initialData_begin, IteratorT initialData_end):
SlidingWindow(maxCapacity) {
// Assert that It obeys the STL forward iterator concept
ASSERT_INPUT_ITERATOR(IteratorT);
for(IteratorT it = initialData_begin; it != initialData_end; ++it) {
append(*it);
}
idxNext_ = buffer_.size() % maxCapacity;
}
const UInt maxCapacity;
size_t size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
/** append new value to the end of the buffer and handle the
"overflows"-may pop the oldest element if full.
*/
void append(T newValue) {
if(size() < maxCapacity) {
buffer_.push_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
//the assignment must be out of the [] above, so not [idxNext_++%maxCap],
// because we want to store the value %maxCap, not only ++
idxNext_ = (idxNext_ +1 ) %maxCapacity;
}
/** like append, but return the dropped value if it was dropped.
:param T newValue - new value to append to the sliding window
:param T& - a return pass-by-value with the removed element,
if this function returns false, this value will remain unchanged.
:return bool if some value has been dropped (and updated as
droppedValue)
*/
bool append(T newValue, T& droppedValue) {
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
bool isFull = (buffer_.size()==maxCapacity);
if(isFull) {
droppedValue = buffer_[idxNext_];
}
append(newValue);
return isFull;
}
/**
:return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
This direct access method is fast.
*/
const std::vector<T>& getData() const {
return buffer_;
}
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
:return new linearized vector
*/
std::vector<T> getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
bool operator==(const SlidingWindow& r2) const {
return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) &&
(this->getData()== r2.getData()) && getLinearizedData() == r2.getLinearizedData());
//FIXME review the ==, on my machine it randomly passes/fails the test!
}
bool operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
/** operator[] provides fast access to the elements indexed relatively
to the oldest element. So slidingWindow[0] returns oldest element,
slidingWindow[size()] returns the newest.
:param UInt index - index/offset from the oldest element, values 0..size()
:return T - i-th oldest value in the buffer
:throws 0<=index<=size()
*/
T& operator[](UInt index) {
NTA_ASSERT(index <= size());
NTA_ASSERT(size() > 0);
//get last updated position, "current"+index(offset)
//avoid calling getLinearizeData() as it involves copy()
if (size() == maxCapacity) {
return &buffer_[(idxNext_ + index) % maxCapacity];
} else {
return &buffer_[index];
}
}
const T& operator[](UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
#endif //header
<commit_msg>SlidingWindow: add print support (<<)<commit_after>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <string>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
#include <nupic/math/Math.hpp> //for macro ASSERT_INPUT_ITERATOR
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity, std::string id="SlidingWindow") :
maxCapacity(maxCapacity),
ID(id)
{
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class IteratorT>
SlidingWindow(UInt maxCapacity, IteratorT initialData_begin,
IteratorT initialData_end, std::string id="SlidingWindow"):
SlidingWindow(maxCapacity, id) {
// Assert that It obeys the STL forward iterator concept
ASSERT_INPUT_ITERATOR(IteratorT);
for(IteratorT it = initialData_begin; it != initialData_end; ++it) {
append(*it);
}
idxNext_ = buffer_.size() % maxCapacity; //TODO remove, not needed
}
const UInt maxCapacity;
const std::string ID; //name of this object
size_t size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
/** append new value to the end of the buffer and handle the
"overflows"-may pop the oldest element if full.
*/
void append(T newValue) {
if(size() < maxCapacity) {
buffer_.push_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
//the assignment must be out of the [] above, so not [idxNext_++%maxCap],
// because we want to store the value %maxCap, not only ++
idxNext_ = (idxNext_ +1 ) %maxCapacity;
}
/** like append, but return the dropped value if it was dropped.
:param T newValue - new value to append to the sliding window
:param T& - a return pass-by-value with the removed element,
if this function returns false, this value will remain unchanged.
:return bool if some value has been dropped (and updated as
droppedValue)
*/
bool append(T newValue, T& droppedValue) {
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
bool isFull = (buffer_.size()==maxCapacity);
if(isFull) {
droppedValue = buffer_[idxNext_];
}
append(newValue);
return isFull;
}
/**
:return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
This direct access method is fast.
*/
const std::vector<T>& getData() const {
return buffer_;
}
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
:return new linearized vector
*/
std::vector<T> getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
bool operator==(const SlidingWindow& r2) const {
return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) &&
(this->getData()== r2.getData()) && getLinearizedData() == r2.getLinearizedData());
//FIXME review the ==, on my machine it randomly passes/fails the test!
}
bool operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
/** operator[] provides fast access to the elements indexed relatively
to the oldest element. So slidingWindow[0] returns oldest element,
slidingWindow[size()] returns the newest.
:param UInt index - index/offset from the oldest element, values 0..size()
:return T - i-th oldest value in the buffer
:throws 0<=index<=size()
*/
T& operator[](UInt index) {
NTA_ASSERT(index <= size());
NTA_ASSERT(size() > 0);
//get last updated position, "current"+index(offset)
//avoid calling getLinearizeData() as it involves copy()
if (size() == maxCapacity) {
return &buffer_[(idxNext_ + index) % maxCapacity];
} else {
return &buffer_[index];
}
}
const T& operator[](UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
std::ostream& operator<<(std::ostream& os) {
return os << ID << std::endl;
}
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
#endif //header
<|endoftext|> |
<commit_before><commit_msg>[DRT] Fix subtle TA mistranslation<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, Ford Motor Company
* 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 Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "transport_manager/iap2_emulation/iap2_transport_adapter.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include "utils/threads/thread.h"
#include "utils/file_system.h"
namespace {
static const mode_t mode = 0666;
static const auto in_signals_channel = "iap_signals_in";
static const auto out_signals_channel = "iap_signals_out";
} // namespace
namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "IAP2Emulation");
IAP2BluetoothEmulationTransportAdapter::IAP2BluetoothEmulationTransportAdapter(
const uint16_t port,
resumption::LastState& last_state,
const TransportManagerSettings& settings)
: TcpTransportAdapter(port, last_state, settings) {}
void IAP2BluetoothEmulationTransportAdapter::DeviceSwitched(
const DeviceUID& device_handle) {
LOG4CXX_AUTO_TRACE(logger_);
UNUSED(device_handle);
DCHECK(!"Switching for iAP2 Bluetooth is not supported.");
}
DeviceType IAP2BluetoothEmulationTransportAdapter::GetDeviceType() const {
return IOS_BT;
}
IAP2USBEmulationTransportAdapter::IAP2USBEmulationTransportAdapter(
const uint16_t port,
resumption::LastState& last_state,
const TransportManagerSettings& settings)
: TcpTransportAdapter(port, last_state, settings), out_(0) {
auto delegate = new IAPSignalHandlerDelegate(*this);
signal_handler_ = threads::CreateThread("iAP signal handler", delegate);
signal_handler_->start();
const auto result = mkfifo(out_signals_channel, mode);
LOG4CXX_DEBUG(logger_, "Out signals channel creation result: " << result);
}
IAP2USBEmulationTransportAdapter::~IAP2USBEmulationTransportAdapter() {
signal_handler_->join();
auto delegate = signal_handler_->delegate();
signal_handler_->set_delegate(NULL);
delete delegate;
threads::DeleteThread(signal_handler_);
LOG4CXX_DEBUG(logger_, "Out close result: " << close(out_));
LOG4CXX_DEBUG(logger_, "Out unlink result: " << unlink(out_signals_channel));
}
void IAP2USBEmulationTransportAdapter::DeviceSwitched(
const DeviceUID& device_handle) {
LOG4CXX_AUTO_TRACE(logger_);
UNUSED(device_handle);
const auto switch_signal_ack = std::string("SDL_TRANSPORT_SWITCH_ACK\n");
auto out_ = open(out_signals_channel, O_WRONLY);
LOG4CXX_DEBUG(logger_, "Out channel descriptor: " << out_);
const auto bytes =
write(out_, switch_signal_ack.c_str(), switch_signal_ack.size());
UNUSED(bytes);
LOG4CXX_DEBUG(logger_, "Written bytes to out: " << bytes);
LOG4CXX_DEBUG(logger_, "Switching signal ACK is sent");
LOG4CXX_DEBUG(logger_, "iAP2 USB device is switched with iAP2 Bluetooth");
}
DeviceType IAP2USBEmulationTransportAdapter::GetDeviceType() const {
return IOS_USB;
}
IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::
IAPSignalHandlerDelegate(IAP2USBEmulationTransportAdapter& adapter)
: adapter_(adapter), run_flag_(true), in_(0) {
const auto result = mkfifo(in_signals_channel, mode);
LOG4CXX_DEBUG(logger_, "In signals channel creation result: " << result);
}
void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Signal handling is started");
const auto switch_signal = "SDL_TRANSPORT_SWITCH";
LOG4CXX_DEBUG(logger_, "Waiting for signal: " << switch_signal);
in_ = open(in_signals_channel, O_RDONLY);
LOG4CXX_DEBUG(logger_, "In channel descriptor: " << in_);
const auto size = 32;
while (run_flag_) {
char buffer[size];
auto bytes = read(in_, &buffer, size);
if (0 == bytes) {
continue;
}
if (-1 == bytes) {
LOG4CXX_DEBUG(logger_, "Error during input pipe read");
break;
}
LOG4CXX_DEBUG(logger_, "Read in bytes: " << bytes);
std::string str(buffer);
if (std::string::npos != str.find(switch_signal)) {
LOG4CXX_DEBUG(logger_, "Switch signal received.");
adapter_.DoTransportSwitch();
}
}
LOG4CXX_DEBUG(logger_, "In close result: " << close(in_));
LOG4CXX_DEBUG(logger_, "In unlink result: " << unlink(in_signals_channel));
}
void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::
exitThreadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Stopping signal handling.");
run_flag_ = false;
if (!in_) {
// To stop thread gracefully in case of no one has connected to pipe before
auto in = open(in_signals_channel, O_WRONLY);
UNUSED(in);
}
}
}
} // namespace transport_manager::transport_adapter
<commit_msg>Fixes thread races in transport manager unit tests<commit_after>/*
* Copyright (c) 2017, Ford Motor Company
* 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 Ford Motor Company 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "transport_manager/iap2_emulation/iap2_transport_adapter.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include "utils/threads/thread.h"
#include "utils/file_system.h"
namespace {
static const mode_t mode = 0666;
static const auto in_signals_channel = "iap_signals_in";
static const auto out_signals_channel = "iap_signals_out";
} // namespace
namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "IAP2Emulation");
IAP2BluetoothEmulationTransportAdapter::IAP2BluetoothEmulationTransportAdapter(
const uint16_t port,
resumption::LastState& last_state,
const TransportManagerSettings& settings)
: TcpTransportAdapter(port, last_state, settings) {}
void IAP2BluetoothEmulationTransportAdapter::DeviceSwitched(
const DeviceUID& device_handle) {
LOG4CXX_AUTO_TRACE(logger_);
UNUSED(device_handle);
DCHECK(!"Switching for iAP2 Bluetooth is not supported.");
}
DeviceType IAP2BluetoothEmulationTransportAdapter::GetDeviceType() const {
return IOS_BT;
}
IAP2USBEmulationTransportAdapter::IAP2USBEmulationTransportAdapter(
const uint16_t port,
resumption::LastState& last_state,
const TransportManagerSettings& settings)
: TcpTransportAdapter(port, last_state, settings), out_(0) {
auto delegate = new IAPSignalHandlerDelegate(*this);
signal_handler_ = threads::CreateThread("iAP signal handler", delegate);
signal_handler_->start();
const auto result = mkfifo(out_signals_channel, mode);
LOG4CXX_DEBUG(logger_, "Out signals channel creation result: " << result);
}
IAP2USBEmulationTransportAdapter::~IAP2USBEmulationTransportAdapter() {
signal_handler_->join();
auto delegate = signal_handler_->delegate();
signal_handler_->set_delegate(NULL);
delete delegate;
threads::DeleteThread(signal_handler_);
LOG4CXX_DEBUG(logger_, "Out close result: " << close(out_));
LOG4CXX_DEBUG(logger_, "Out unlink result: " << unlink(out_signals_channel));
}
void IAP2USBEmulationTransportAdapter::DeviceSwitched(
const DeviceUID& device_handle) {
LOG4CXX_AUTO_TRACE(logger_);
UNUSED(device_handle);
const auto switch_signal_ack = std::string("SDL_TRANSPORT_SWITCH_ACK\n");
auto out_ = open(out_signals_channel, O_WRONLY);
LOG4CXX_DEBUG(logger_, "Out channel descriptor: " << out_);
const auto bytes =
write(out_, switch_signal_ack.c_str(), switch_signal_ack.size());
UNUSED(bytes);
LOG4CXX_DEBUG(logger_, "Written bytes to out: " << bytes);
LOG4CXX_DEBUG(logger_, "Switching signal ACK is sent");
LOG4CXX_DEBUG(logger_, "iAP2 USB device is switched with iAP2 Bluetooth");
}
DeviceType IAP2USBEmulationTransportAdapter::GetDeviceType() const {
return IOS_USB;
}
IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::
IAPSignalHandlerDelegate(IAP2USBEmulationTransportAdapter& adapter)
: adapter_(adapter), run_flag_(true), in_(0) {
const auto result = mkfifo(in_signals_channel, mode);
LOG4CXX_DEBUG(logger_, "In signals channel creation result: " << result);
}
void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Signal handling is started");
const auto switch_signal = "SDL_TRANSPORT_SWITCH";
LOG4CXX_DEBUG(logger_, "Waiting for signal: " << switch_signal);
in_ = open(in_signals_channel, O_RDONLY);
LOG4CXX_DEBUG(logger_, "In channel descriptor: " << in_);
const auto size = 32;
while (run_flag_) {
char buffer[size];
auto bytes = read(in_, &buffer, size);
if (0 == bytes) {
continue;
}
if (-1 == bytes) {
LOG4CXX_DEBUG(logger_, "Error during input pipe read");
break;
}
LOG4CXX_DEBUG(logger_, "Read in bytes: " << bytes);
std::string str(buffer);
if (std::string::npos != str.find(switch_signal)) {
LOG4CXX_DEBUG(logger_, "Switch signal received.");
adapter_.DoTransportSwitch();
}
}
LOG4CXX_DEBUG(logger_, "In close result: " << close(in_));
LOG4CXX_DEBUG(logger_, "In unlink result: " << unlink(in_signals_channel));
}
void IAP2USBEmulationTransportAdapter::IAPSignalHandlerDelegate::
exitThreadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Stopping signal handling.");
run_flag_ = false;
ThreadDelegate::exitThreadMain();
}
}
} // namespace transport_manager::transport_adapter
<|endoftext|> |
<commit_before>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/vmstats_impl.h"
#include <sstream>
#include "bin/file.h"
#include "bin/log.h"
#include "bin/platform.h"
#include "bin/socket.h"
#include "bin/thread.h"
#include "bin/utils.h"
#include "include/dart_debugger_api.h"
#include "platform/json.h"
#define BUFSIZE 8192
#define RETRY_PAUSE 100 // milliseconds
static const char* INDEX_HTML = "index.html";
static const char* VMSTATS_HTML = "vmstats.html";
static const char* DEFAULT_HOST = "localhost";
// Global static pointer used to ensure a single instance of the class.
VmStats* VmStats::instance_ = NULL;
dart::Monitor* VmStats::instance_monitor_;
dart::Mutex* VmStatusService::mutex_;
void VmStats::Start(int port, const char* root_dir) {
if (instance_ != NULL) {
FATAL("VmStats already started.");
}
instance_ = new VmStats();
instance_monitor_ = new dart::Monitor();
VmStatusService::InitOnce();
Socket::Initialize();
if (root_dir != NULL) {
instance_->root_directory_ = root_dir;
}
// TODO(tball): allow host to be specified.
char* host = const_cast<char*>(DEFAULT_HOST);
OSError* os_error;
const char* host_ip = Socket::LookupIPv4Address(host, &os_error);
if (host_ip == NULL) {
Log::PrintErr("Failed IP lookup of VmStats host %s: %s\n",
host, os_error->message());
return;
}
const intptr_t BACKLOG = 128; // Default value from HttpServer.dart
int64_t address = ServerSocket::CreateBindListen(host_ip, port, BACKLOG);
if (address < 0) {
Log::PrintErr("Failed binding VmStats socket: %s:%d\n", host, port);
return;
}
instance_->bind_address_ = address;
Log::Print("VmStats URL: http://%s:%"Pd"/\n", host, Socket::GetPort(address));
MonitorLocker ml(instance_monitor_);
instance_->running_ = true;
int err = dart::Thread::Start(WebServer, address);
if (err != 0) {
Log::PrintErr("Failed starting VmStats thread: %d\n", err);
Shutdown();
}
}
void VmStats::Stop() {
ASSERT(instance_ != NULL);
MonitorLocker ml(instance_monitor_);
instance_->running_ = false;
}
void VmStats::Shutdown() {
ASSERT(instance_ != NULL);
MonitorLocker ml(instance_monitor_);
Socket::Close(instance_->bind_address_);
delete instance_;
instance_ = NULL;
}
void VmStats::AddIsolate(IsolateData* isolate_data,
Dart_Isolate isolate) {
if (instance_ != NULL) {
MonitorLocker ml(instance_monitor_);
instance_->isolate_table_[isolate_data] = isolate;
}
}
void VmStats::RemoveIsolate(IsolateData* isolate_data) {
if (instance_ != NULL) {
MonitorLocker ml(instance_monitor_);
instance_->isolate_table_.erase(isolate_data);
}
}
static const char* ContentType(const char* url) {
const char* suffix = strrchr(url, '.');
if (suffix != NULL) {
if (!strcmp(suffix, ".html")) {
return "text/html; charset=UTF-8";
}
if (!strcmp(suffix, ".dart")) {
return "application/dart; charset=UTF-8";
}
if (!strcmp(suffix, ".js")) {
return "application/javascript; charset=UTF-8";
}
if (!strcmp(suffix, ".css")) {
return "text/css; charset=UTF-8";
}
if (!strcmp(suffix, ".gif")) {
return "image/gif";
}
if (!strcmp(suffix, ".png")) {
return "image/png";
}
if (!strcmp(suffix, ".jpg") || !strcmp(suffix, ".jpeg")) {
return "image/jpeg";
}
}
return "text/plain";
}
void VmStats::WebServer(uword bind_address) {
while (true) {
intptr_t socket = ServerSocket::Accept(bind_address);
if (socket == ServerSocket::kTemporaryFailure) {
// Not a real failure, woke up but no connection available.
// Use MonitorLocker.Wait(), since it has finer granularity than sleep().
dart::Monitor m;
MonitorLocker ml(&m);
ml.Wait(RETRY_PAUSE);
continue;
}
if (socket < 0) {
// Stop() closed the socket.
return;
}
// TODO(tball): rewrite this to use STL, so as to eliminate the static
// buffer and support resource URLs that are longer than BUFSIZE.
// Read request.
char buffer[BUFSIZE + 1];
intptr_t len = Socket::Read(socket, buffer, BUFSIZE);
if (len <= 0) {
// Invalid HTTP request, ignore.
continue;
}
intptr_t n;
while ((n = Socket::Read(socket, buffer + len, BUFSIZE - len)) > 0) {
len += n;
}
buffer[len] = '\0';
// Verify it's a GET request.
// TODO(tball): support POST requests.
if (strncmp("GET ", buffer, 4) != 0 && strncmp("get ", buffer, 4) != 0) {
Log::PrintErr("Unsupported HTTP request type");
const char* response = "HTTP/1.1 403 Forbidden\n"
"Content-Length: 120\n"
"Connection: close\n"
"Content-Type: text/html\n\n"
"<html><head>\n<title>403 Forbidden</title>\n</head>"
"<body>\n<h1>Forbidden</h1>\nUnsupported HTTP request type\n</body>"
"</html>\n";
Socket::Write(socket, response, strlen(response));
Socket::Close(socket);
continue;
}
// Extract GET URL, and null-terminate URL in case request line has
// HTTP version.
for (int i = 4; i < len; i++) {
if (buffer[i] == ' ') {
buffer[i] = '\0';
}
}
char* url = &buffer[4];
Log::Print("vmstats: %s requested\n", url);
char* content = NULL;
// Check for VmStats-specific URLs.
if (strcmp(url, "/isolates") == 0) {
content = instance_->IsolatesStatus();
} else {
// Check plug-ins.
content = VmStatusService::GetVmStatus(url);
}
if (content != NULL) {
size_t content_len = strlen(content);
len = snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: application/json; charset=UTF-8\n"
"Content-Length: %"Pu"\n\n",
content_len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, content, content_len);
Socket::Write(socket, "\n", 1);
Socket::Write(socket, buffer, strlen(buffer));
free(content);
} else {
// No status content with this URL, return file or resource content.
std::string path(instance_->root_directory_);
path.append(url);
// Expand directory URLs.
if (strcmp(url, "/") == 0) {
path.append(VMSTATS_HTML);
} else if (url[strlen(url) - 1] == '/') {
path.append(INDEX_HTML);
}
bool success = false;
if (File::Exists(path.c_str())) {
File* f = File::Open(path.c_str(), File::kRead);
if (f != NULL) {
intptr_t len = f->Length();
char* text_buffer = reinterpret_cast<char*>(malloc(len));
if (f->ReadFully(text_buffer, len)) {
const char* content_type = ContentType(path.c_str());
snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: %s\n"
"Content-Length: %"Pu"\n\n",
content_type, len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, text_buffer, len);
Socket::Write(socket, "\n", 1);
success = true;
}
free(text_buffer);
delete f;
}
} else {
// TODO(tball): look up linked in resource.
}
if (!success) {
const char* response = "HTTP/1.1 404 Not Found\n\n";
Socket::Write(socket, response, strlen(response));
}
}
Socket::Close(socket);
}
Shutdown();
}
char* VmStats::IsolatesStatus() {
std::ostringstream stream;
stream << '{' << std::endl;
stream << "\"isolates\": [" << std::endl;
IsolateTable::iterator itr;
bool first = true;
for (itr = isolate_table_.begin(); itr != isolate_table_.end(); ++itr) {
Dart_Isolate isolate = itr->second;
static char request[512];
snprintf(request, sizeof(request),
"/isolate/0x%"Px,
reinterpret_cast<intptr_t>(isolate));
char* status = VmStatusService::GetVmStatus(request);
if (status != NULL) {
stream << status;
if (!first) {
stream << "," << std::endl;
}
first = false;
}
free(status);
}
stream << std::endl << "]";
stream << std::endl << '}' << std::endl;
return strdup(stream.str().c_str());
}
// Global static pointer used to ensure a single instance of the class.
VmStatusService* VmStatusService::instance_ = NULL;
void VmStatusService::InitOnce() {
ASSERT(VmStatusService::instance_ == NULL);
VmStatusService::instance_ = new VmStatusService();
VmStatusService::mutex_ = new dart::Mutex();
// Register built-in status plug-ins. RegisterPlugin is not used because
// this isn't called within an isolate, and because parameter checking
// isn't necessary.
instance_->RegisterPlugin(&Dart_GetVmStatus);
// TODO(tball): dynamically load any additional plug-ins.
}
int VmStatusService::RegisterPlugin(Dart_VmStatusCallback callback) {
MutexLocker ml(mutex_);
if (callback == NULL) {
return -1;
}
VmStatusPlugin* plugin = new VmStatusPlugin(callback);
VmStatusPlugin* list = instance_->registered_plugin_list_;
if (list == NULL) {
instance_->registered_plugin_list_ = plugin;
} else {
list->Append(plugin);
}
return 0;
}
char* VmStatusService::GetVmStatus(const char* request) {
VmStatusPlugin* plugin = instance_->registered_plugin_list_;
while (plugin != NULL) {
char* result = (plugin->callback())(request);
if (result != NULL) {
return result;
}
plugin = plugin->next();
}
return NULL;
}
<commit_msg>Set vmstats socket as blocking. Review URL: https://codereview.chromium.org//12390041<commit_after>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/vmstats_impl.h"
#include <sstream>
#include "bin/file.h"
#include "bin/log.h"
#include "bin/platform.h"
#include "bin/socket.h"
#include "bin/thread.h"
#include "bin/utils.h"
#include "include/dart_debugger_api.h"
#include "platform/json.h"
#define BUFSIZE 8192
#define RETRY_PAUSE 100 // milliseconds
static const char* INDEX_HTML = "index.html";
static const char* VMSTATS_HTML = "vmstats.html";
static const char* DEFAULT_HOST = "localhost";
// Global static pointer used to ensure a single instance of the class.
VmStats* VmStats::instance_ = NULL;
dart::Monitor* VmStats::instance_monitor_;
dart::Mutex* VmStatusService::mutex_;
void VmStats::Start(int port, const char* root_dir) {
if (instance_ != NULL) {
FATAL("VmStats already started.");
}
instance_ = new VmStats();
instance_monitor_ = new dart::Monitor();
VmStatusService::InitOnce();
Socket::Initialize();
if (root_dir != NULL) {
instance_->root_directory_ = root_dir;
}
// TODO(tball): allow host to be specified.
char* host = const_cast<char*>(DEFAULT_HOST);
OSError* os_error;
const char* host_ip = Socket::LookupIPv4Address(host, &os_error);
if (host_ip == NULL) {
Log::PrintErr("Failed IP lookup of VmStats host %s: %s\n",
host, os_error->message());
return;
}
const intptr_t BACKLOG = 128; // Default value from HttpServer.dart
int64_t address = ServerSocket::CreateBindListen(host_ip, port, BACKLOG);
if (address < 0) {
Log::PrintErr("Failed binding VmStats socket: %s:%d\n", host, port);
return;
}
instance_->bind_address_ = address;
Log::Print("VmStats URL: http://%s:%"Pd"/\n", host, Socket::GetPort(address));
MonitorLocker ml(instance_monitor_);
instance_->running_ = true;
int err = dart::Thread::Start(WebServer, address);
if (err != 0) {
Log::PrintErr("Failed starting VmStats thread: %d\n", err);
Shutdown();
}
}
void VmStats::Stop() {
ASSERT(instance_ != NULL);
MonitorLocker ml(instance_monitor_);
instance_->running_ = false;
}
void VmStats::Shutdown() {
ASSERT(instance_ != NULL);
MonitorLocker ml(instance_monitor_);
Socket::Close(instance_->bind_address_);
delete instance_;
instance_ = NULL;
}
void VmStats::AddIsolate(IsolateData* isolate_data,
Dart_Isolate isolate) {
if (instance_ != NULL) {
MonitorLocker ml(instance_monitor_);
instance_->isolate_table_[isolate_data] = isolate;
}
}
void VmStats::RemoveIsolate(IsolateData* isolate_data) {
if (instance_ != NULL) {
MonitorLocker ml(instance_monitor_);
instance_->isolate_table_.erase(isolate_data);
}
}
static const char* ContentType(const char* url) {
const char* suffix = strrchr(url, '.');
if (suffix != NULL) {
if (!strcmp(suffix, ".html")) {
return "text/html; charset=UTF-8";
}
if (!strcmp(suffix, ".dart")) {
return "application/dart; charset=UTF-8";
}
if (!strcmp(suffix, ".js")) {
return "application/javascript; charset=UTF-8";
}
if (!strcmp(suffix, ".css")) {
return "text/css; charset=UTF-8";
}
if (!strcmp(suffix, ".gif")) {
return "image/gif";
}
if (!strcmp(suffix, ".png")) {
return "image/png";
}
if (!strcmp(suffix, ".jpg") || !strcmp(suffix, ".jpeg")) {
return "image/jpeg";
}
}
return "text/plain";
}
void VmStats::WebServer(uword bind_address) {
while (true) {
intptr_t socket = ServerSocket::Accept(bind_address);
if (socket == ServerSocket::kTemporaryFailure) {
// Not a real failure, woke up but no connection available.
// Use MonitorLocker.Wait(), since it has finer granularity than sleep().
dart::Monitor m;
MonitorLocker ml(&m);
ml.Wait(RETRY_PAUSE);
continue;
}
if (socket < 0) {
// Stop() closed the socket.
return;
}
Socket::SetBlocking(socket);
// TODO(tball): rewrite this to use STL, so as to eliminate the static
// buffer and support resource URLs that are longer than BUFSIZE.
// Read request.
char buffer[BUFSIZE + 1];
intptr_t len = Socket::Read(socket, buffer, BUFSIZE);
if (len <= 0) {
// Invalid HTTP request, ignore.
continue;
}
buffer[len] = '\0';
// Verify it's a GET request.
// TODO(tball): support POST requests.
if (strncmp("GET ", buffer, 4) != 0 && strncmp("get ", buffer, 4) != 0) {
Log::PrintErr("Unsupported HTTP request type");
const char* response = "HTTP/1.1 403 Forbidden\n"
"Content-Length: 120\n"
"Connection: close\n"
"Content-Type: text/html\n\n"
"<html><head>\n<title>403 Forbidden</title>\n</head>"
"<body>\n<h1>Forbidden</h1>\nUnsupported HTTP request type\n</body>"
"</html>\n";
Socket::Write(socket, response, strlen(response));
Socket::Close(socket);
continue;
}
// Extract GET URL, and null-terminate URL in case request line has
// HTTP version.
for (int i = 4; i < len; i++) {
if (buffer[i] == ' ') {
buffer[i] = '\0';
}
}
char* url = &buffer[4];
Log::Print("vmstats: %s requested\n", url);
char* content = NULL;
// Check for VmStats-specific URLs.
if (strcmp(url, "/isolates") == 0) {
content = instance_->IsolatesStatus();
} else {
// Check plug-ins.
content = VmStatusService::GetVmStatus(url);
}
if (content != NULL) {
size_t content_len = strlen(content);
len = snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: application/json; charset=UTF-8\n"
"Content-Length: %"Pu"\n\n",
content_len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, content, content_len);
Socket::Write(socket, "\n", 1);
Socket::Write(socket, buffer, strlen(buffer));
free(content);
} else {
// No status content with this URL, return file or resource content.
std::string path(instance_->root_directory_);
path.append(url);
// Expand directory URLs.
if (strcmp(url, "/") == 0) {
path.append(VMSTATS_HTML);
} else if (url[strlen(url) - 1] == '/') {
path.append(INDEX_HTML);
}
bool success = false;
if (File::Exists(path.c_str())) {
File* f = File::Open(path.c_str(), File::kRead);
if (f != NULL) {
intptr_t len = f->Length();
char* text_buffer = reinterpret_cast<char*>(malloc(len));
if (f->ReadFully(text_buffer, len)) {
const char* content_type = ContentType(path.c_str());
snprintf(buffer, BUFSIZE,
"HTTP/1.1 200 OK\nContent-Type: %s\n"
"Content-Length: %"Pu"\n\n",
content_type, len);
Socket::Write(socket, buffer, strlen(buffer));
Socket::Write(socket, text_buffer, len);
Socket::Write(socket, "\n", 1);
success = true;
}
free(text_buffer);
delete f;
}
} else {
// TODO(tball): look up linked in resource.
}
if (!success) {
const char* response = "HTTP/1.1 404 Not Found\n\n";
Socket::Write(socket, response, strlen(response));
}
}
Socket::Close(socket);
}
Shutdown();
}
char* VmStats::IsolatesStatus() {
std::ostringstream stream;
stream << '{' << std::endl;
stream << "\"isolates\": [" << std::endl;
IsolateTable::iterator itr;
bool first = true;
for (itr = isolate_table_.begin(); itr != isolate_table_.end(); ++itr) {
Dart_Isolate isolate = itr->second;
static char request[512];
snprintf(request, sizeof(request),
"/isolate/0x%"Px,
reinterpret_cast<intptr_t>(isolate));
char* status = VmStatusService::GetVmStatus(request);
if (status != NULL) {
stream << status;
if (!first) {
stream << "," << std::endl;
}
first = false;
}
free(status);
}
stream << std::endl << "]";
stream << std::endl << '}' << std::endl;
return strdup(stream.str().c_str());
}
// Global static pointer used to ensure a single instance of the class.
VmStatusService* VmStatusService::instance_ = NULL;
void VmStatusService::InitOnce() {
ASSERT(VmStatusService::instance_ == NULL);
VmStatusService::instance_ = new VmStatusService();
VmStatusService::mutex_ = new dart::Mutex();
// Register built-in status plug-ins. RegisterPlugin is not used because
// this isn't called within an isolate, and because parameter checking
// isn't necessary.
instance_->RegisterPlugin(&Dart_GetVmStatus);
// TODO(tball): dynamically load any additional plug-ins.
}
int VmStatusService::RegisterPlugin(Dart_VmStatusCallback callback) {
MutexLocker ml(mutex_);
if (callback == NULL) {
return -1;
}
VmStatusPlugin* plugin = new VmStatusPlugin(callback);
VmStatusPlugin* list = instance_->registered_plugin_list_;
if (list == NULL) {
instance_->registered_plugin_list_ = plugin;
} else {
list->Append(plugin);
}
return 0;
}
char* VmStatusService::GetVmStatus(const char* request) {
VmStatusPlugin* plugin = instance_->registered_plugin_list_;
while (plugin != NULL) {
char* result = (plugin->callback())(request);
if (result != NULL) {
return result;
}
plugin = plugin->next();
}
return NULL;
}
<|endoftext|> |
<commit_before>#include "game.h"
#include <algorithm>
// Todo: Add gfx2d functionality to draw arbitrary
// polygons. Also specify transformation (rotation)
const uint BG_COLOR = 0x404968ff;
const int PLAYER_BULLET_DAMAGE = 5;
const int PLAYER_HITPOINTS = 10;
const float PLAYER_MOVE_SPEED = 300.0f;
const float PLAYER_BULLET_SPEED = 300.0f;
const float PLAYER_FIRE_TIME = 0.2f;
const int ENEMY_BULLET_DAMAGE = 10;
const int ENEMY_HITPOINTS = 10;
const float ENEMY_BULLET_SPEED = 300.0f;
const float ENEMY_MOVE_SPEED = 100.0f;
const float ENEMY_FIRE_TIME = 2.0f;
// Todo: load these from file
// Make different enemy types have diff params
// Archetypal enemies? copy from
// Todo: Make cooldown timers go down when firing
// charge up when not
struct WorldObject
{
vec2 size;
vec2 position;
vec2 velocity;
vec2 acceleration;
};
struct LivingThing
{
// Parameters
float fire_time;
float move_speed;
float bullet_speed;
int bullet_damage;
// State
float cooldown;
float lifetime;
int hitpoints;
bool dead;
};
struct Enemy
{
// Parameters
float fire_time;
float move_speed;
float bullet_speed;
int bullet_damage;
// State
float cooldown;
int hitpoints;
bool dead;
float lifetime;
WorldObject obj;
};
struct Player
{
// Parameters
float move_speed;
float fire_time;
float bullet_speed;
int bullet_damage;
// State
float cooldown;
int hitpoints;
bool dead;
WorldObject obj;
};
struct Bullet
{
float damage;
bool dead;
WorldObject obj;
};
struct World
{
vector<Bullet> bullets;
vector<Enemy> enemies;
Player player;
};
Font font;
int window_width;
int window_height;
uint tex;
World world;
void new_enemy(vec2 position, vec2 velocity, vec2 acceleration)
{
Enemy e;
e.fire_time = ENEMY_FIRE_TIME;
e.move_speed = ENEMY_MOVE_SPEED;
e.bullet_speed = ENEMY_BULLET_SPEED;
e.cooldown = ENEMY_FIRE_TIME;
e.hitpoints = ENEMY_HITPOINTS;
e.bullet_damage = ENEMY_BULLET_DAMAGE;
e.lifetime = 0.0f;
e.dead = false;
e.obj.size = vec2(32.0f);
e.obj.position = position;
e.obj.velocity = velocity;
e.obj.acceleration = acceleration;
world.enemies.push_back(e);
}
void new_bullet(vec2 position, vec2 velocity, int damage, vec2 acceleration)
{
Bullet b;
b.obj.position = position;
b.obj.velocity = velocity;
b.obj.acceleration = acceleration;
b.obj.size = vec2(2.0f, 8.0f);
b.dead = false;
b.damage = damage;
world.bullets.push_back(b);
}
void init_player(vec2 position, vec2 velocity, vec2 acceleration)
{
world.player.fire_time = PLAYER_FIRE_TIME;
world.player.move_speed = PLAYER_MOVE_SPEED;
world.player.bullet_speed = PLAYER_BULLET_SPEED;
world.player.cooldown = 0.0f;
world.player.hitpoints = PLAYER_HITPOINTS;
world.player.bullet_damage = PLAYER_BULLET_DAMAGE;
world.player.dead = false;
world.player.obj.size = vec2(32.0f);
world.player.obj.position = position;
world.player.obj.velocity = velocity;
world.player.obj.acceleration = acceleration;
}
void update_world_object(WorldObject &obj, float dt)
{
obj.position += obj.velocity * dt;
obj.velocity += obj.acceleration * dt;
}
bool collides(WorldObject &a, WorldObject &b)
{
if (a.position.x > b.position.x + b.size.x ||
a.position.x + a.size.x < b.position.x ||
a.position.y > b.position.y + b.size.y ||
a.position.y + a.size.y < b.position.y)
return false;
return true;
}
void hit_enemy(Enemy &e, float damage)
{
e.hitpoints -= damage;
if (e.hitpoints <= 0)
e.dead = true;
}
void hit_player(Player &p, float damage)
{
p.hitpoints -= damage;
if (p.hitpoints <= 0)
p.dead = true;
}
void update_bullet(Bullet &b, float dt)
{
update_world_object(b.obj, dt);
for (int i = 0; i < world.enemies.size(); i++)
{
if (collides(b.obj, world.enemies[i].obj))
{
hit_enemy(world.enemies[i], b.damage);
b.dead = true;
return;
}
}
if (collides(b.obj, world.player.obj))
{
hit_player(world.player, b.damage);
b.dead = true;
}
}
void clamp_speed(float max_speed, WorldObject &obj)
{
float speed = length(obj.velocity);
if (speed > max_speed)
obj.velocity = normalize(obj.velocity) * max_speed;
}
void update_enemy(Enemy &e, float dt)
{
update_world_object(e.obj, dt);
e.cooldown -= dt;
if (e.cooldown <= 0.0f)
{
vec2 direction = normalize(world.player.obj.position - e.obj.position);
vec2 velocity = direction * e.bullet_speed;
float body_radius = length(e.obj.size * 0.8f);
vec2 spawn_position = e.obj.position + direction * body_radius;
new_bullet(spawn_position, velocity, e.bullet_damage, vec2(0.0f));
// recoil on enemy?
e.cooldown += e.fire_time;
}
clamp_speed(e.move_speed, e.obj);
e.lifetime += dt;
}
void update_player(Player &p, float dt)
{
if (p.cooldown > 0.0f)
p.cooldown -= dt;
if (is_key_down(SDLK_LEFT))
p.obj.velocity.x = -p.move_speed;
else if (is_key_down(SDLK_RIGHT))
p.obj.velocity.x = +p.move_speed;
else
p.obj.velocity.x = 0.0f;
if (is_key_down(SDLK_UP))
p.obj.velocity.y = -p.move_speed;
else if (is_key_down(SDLK_DOWN))
p.obj.velocity.y = +p.move_speed;
else
p.obj.velocity.y = 0.0f;
clamp_speed(p.move_speed, p.obj);
if (is_key_down(SDLK_z) && p.cooldown <= 0.0f)
{
vec2 dir = vec2(0.0f, -1.0f);
vec2 spawn_left = p.obj.position - vec2(0.0f, 16.0f);
vec2 spawn_right = p.obj.position + vec2(p.obj.size.x, 0.0f) - vec2(0.0f, 16.0f);
new_bullet(spawn_left, dir * p.bullet_speed, p.bullet_damage, vec2(0.0f));
new_bullet(spawn_right, dir * p.bullet_speed, p.bullet_damage, vec2(0.0f));
p.cooldown = p.fire_time;
}
update_world_object(p.obj, dt);
}
void render_enemy(Enemy &e)
{
using namespace gfx2d;
draw_rectangle(e.obj.position, e.obj.size, 0xff9944ff);
Text text;
text << int(e.hitpoints);
draw_string(e.obj.position, text.getString());
}
void render_player(Player &p)
{
using namespace gfx2d;
draw_rectangle(p.obj.position, p.obj.size, 0x4499ffff);
Text text;
text << int(p.hitpoints);
draw_string(p.obj.position, text.getString());
}
void render_bullet(Bullet &b)
{
using namespace gfx2d;
draw_fill_rectangle(b.obj.position, b.obj.size, 0xd3baffff);
}
bool load_game(int width, int height)
{
if (!load_font(font, "../data/fonts/proggytinyttsz_8x12.png"))
return false;
window_width = width;
window_height = height;
gfx2d::init(width, height);
gfx2d::use_font(font);
return true;
}
void free_game()
{
}
void init_game()
{
new_enemy(vec2(200.0f, 200.0f), vec2(0.0f, 0.0f), vec2(0.0f, 0.0f));
new_enemy(vec2(90.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f, -10.0f));
new_enemy(vec2(140.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
new_enemy(vec2(180.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
new_enemy(vec2(220.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
init_player(vec2(200.0f, 400.0f), vec2(0.0f), vec2(0.0f));
}
void update_game(float dt)
{
for (int i = 0; i < world.enemies.size(); i++)
{
if (world.enemies[i].dead)
{
world.enemies.erase(world.enemies.begin() + i);
i--;
}
else
{
update_enemy(world.enemies[i], dt);
}
}
for (int i = 0; i < world.bullets.size(); i++)
{
if (world.bullets[i].dead)
{
world.bullets.erase(world.bullets.begin() + i);
i--;
}
else
{
update_bullet(world.bullets[i], dt);
}
}
update_player(world.player, dt);
}
void render_game(float dt)
{
gfx2d::begin();
{
using namespace gfx2d;
clearc(BG_COLOR);
blend_mode(true, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for (int i = 0; i < world.enemies.size(); i++)
render_enemy(world.enemies[i]);
for (int i = 0; i < world.bullets.size(); i++)
render_bullet(world.bullets[i]);
render_player(world.player);
}
gfx2d::end();
}<commit_msg>Added more modular laser system. random enemy spawning.<commit_after>#include "game.h"
#include <algorithm>
// Todo: Add gfx2d functionality to draw arbitrary
// polygons. Also specify transformation (rotation)
const uint BG_COLOR = 0x404968ff;
const int PLAYER_BULLET_DAMAGE = 5;
const int PLAYER_HITPOINTS = 10;
const float PLAYER_MOVE_SPEED = 300.0f;
const float PLAYER_BULLET_SPEED = 300.0f;
const float PLAYER_BULLET_LIFETIME = 5.0f;
const float PLAYER_FIRE_TIME = 0.2f;
const int ENEMY_BULLET_DAMAGE = 10;
const int ENEMY_HITPOINTS = 10;
const float ENEMY_BULLET_SPEED = 300.0f;
const float ENEMY_BULLET_LIFETIME = 5.0f;
const float ENEMY_MOVE_SPEED = 100.0f;
const float ENEMY_FIRE_TIME = 2.0f;
// Todo: Rename Entity to something else
// Make Entity a base class for all game objects
// Todo: load these from file
// Make different enemy types have diff params
// Archetypal enemies? copy from
// Todo: Make cooldown timers go down when firing
// charge up when not
// Todo: Fix GL_INVALID_VALUE when too much stuff to draw
// Todo: Make general weapon thing
// Todo: Move fire_time and bullet stuffs and cooldown in here
// Todo: Add laser body
// Todo: Add parent id
struct Laser
{
uint parent_id;
vec2 attachment_point;
vec2 normal;
float fire_time;
float cooldown;
float bullet_lifetime;
float bullet_speed; // laser != bullet ...
int damage;
};
struct Body
{
vec2 size;
vec2 position;
vec2 velocity;
vec2 acceleration;
};
struct Entity
{
// Parameters
float move_speed;
// State
float lifetime;
int hitpoints;
bool dead;
};
struct Enemy
{
uint id;
Body body;
Entity entity;
Laser laser;
};
struct Player
{
uint id;
Body body;
Entity entity;
vector<Laser> lasers;
};
struct Bullet
{
uint shooter_id;
float lifetime;
float damage;
bool dead;
Body body;
};
struct World
{
uint next_id;
vector<Bullet> bullets;
vector<Enemy> enemies;
Player player;
};
Font font;
int window_width;
int window_height;
uint tex;
World world;
float spawn_timer = 0.0f;
float spawn_period = 1.0f;
void new_enemy(vec2 position, vec2 velocity, vec2 acceleration)
{
Entity entity;
entity.move_speed = ENEMY_MOVE_SPEED;
entity.hitpoints = ENEMY_HITPOINTS;
entity.lifetime = 0.0f;
entity.dead = false;
Body body;
body.size = vec2(32.0f);
body.position = position;
body.velocity = velocity;
body.acceleration = acceleration;
Laser laser;
laser.fire_time = ENEMY_FIRE_TIME;
laser.bullet_speed = ENEMY_BULLET_SPEED;
laser.cooldown = ENEMY_FIRE_TIME;
laser.damage = ENEMY_BULLET_DAMAGE;
laser.bullet_lifetime = ENEMY_BULLET_LIFETIME;
laser.attachment_point = vec2(16.0f, +38.0f);
laser.normal = vec2(0.0f, 1.0f);
laser.parent_id = world.next_id;
Enemy enemy;
enemy.body = body;
enemy.entity = entity;
enemy.laser = laser;
enemy.id = world.next_id++;
world.enemies.push_back(enemy);
}
void new_bullet(uint shooter_id, float lifetime, vec2 position, vec2 velocity, int damage, vec2 acceleration)
{
Body body;
body.position = position;
body.velocity = velocity;
body.acceleration = acceleration;
body.size = vec2(2.0f, 8.0f);
Bullet bullet;
bullet.body = body;
bullet.dead = false;
bullet.damage = damage;
bullet.lifetime = lifetime;
bullet.shooter_id = shooter_id;
world.bullets.push_back(bullet);
}
void init_player(vec2 position, vec2 velocity, vec2 acceleration)
{
Laser laser_l, laser_r;
laser_l.bullet_speed = PLAYER_BULLET_SPEED;
laser_l.bullet_lifetime = PLAYER_BULLET_LIFETIME;
laser_l.fire_time = PLAYER_FIRE_TIME;
laser_l.damage = PLAYER_BULLET_DAMAGE;
laser_l.cooldown = PLAYER_FIRE_TIME;
laser_l.attachment_point = vec2(0.0f, -8.0f);
laser_l.normal = vec2(0.0f, -1.0f);
laser_l.parent_id = world.next_id;
laser_r = laser_l;
laser_r.attachment_point = vec2(32.0f, -8.0f);
vector<Laser> lasers;
lasers.push_back(laser_l);
lasers.push_back(laser_r);
world.player.id = world.next_id++;
world.player.lasers = lasers;
world.player.entity.move_speed = PLAYER_MOVE_SPEED;
world.player.entity.hitpoints = PLAYER_HITPOINTS;
world.player.entity.dead = false;
world.player.body.size = vec2(32.0f);
world.player.body.position = position;
world.player.body.velocity = velocity;
world.player.body.acceleration = acceleration;
}
void update_body(Body &body, float dt)
{
body.position += body.velocity * dt;
body.velocity += body.acceleration * dt;
}
bool collides(Body &a, Body &b)
{
if (a.position.x > b.position.x + b.size.x ||
a.position.x + a.size.x < b.position.x ||
a.position.y > b.position.y + b.size.y ||
a.position.y + a.size.y < b.position.y)
return false;
return true;
}
void hit_entity(Entity &e, float damage)
{
e.hitpoints -= damage;
if (e.hitpoints <= 0)
e.dead = true;
}
void update_bullet(Bullet &b, float dt)
{
update_body(b.body, dt);
b.lifetime -= dt;
if (b.lifetime <= 0.0f)
b.dead = true;
for (int i = 0; i < world.enemies.size(); i++)
{
if (collides(b.body, world.enemies[i].body))
{
hit_entity(world.enemies[i].entity, b.damage);
b.dead = true;
return;
}
}
if (collides(b.body, world.player.body))
{
hit_entity(world.player.entity, b.damage);
b.dead = true;
}
}
void clamp_speed(float max_speed, Body &body)
{
float speed = length(body.velocity);
if (speed > max_speed)
body.velocity = normalize(body.velocity) * max_speed;
}
bool entity_fire_laser(uint id, Laser &laser, Entity &entity, Body &body)
{
if (laser.cooldown <= 0.0f)
{
// Todo: rotations and stuff
vec2 spawn = body.position + laser.attachment_point;
vec2 direction = laser.normal;
new_bullet(id, laser.bullet_lifetime, spawn, direction * laser.bullet_speed, laser.damage, vec2(0.0f));
laser.cooldown += laser.fire_time;
return true;
}
return false;
}
void update_laser(Laser &l, float dt)
{
if (l.cooldown > 0.0f)
l.cooldown -= dt;
}
void update_enemy(Enemy &e, float dt)
{
update_body(e.body, dt);
update_laser(e.laser, dt);
vec2 direction = normalize(world.player.body.position - e.body.position);
if (entity_fire_laser(e.id, e.laser, e.entity, e.body))
{
// something?
// recoil maybe
}
clamp_speed(e.entity.move_speed, e.body);
e.entity.lifetime += dt;
}
void control_entity(Body &body, Entity &entity)
{
if (is_key_down(SDLK_LEFT))
body.velocity.x = -entity.move_speed;
else if (is_key_down(SDLK_RIGHT))
body.velocity.x = +entity.move_speed;
else
body.velocity.x = 0.0f;
if (is_key_down(SDLK_UP))
body.velocity.y = -entity.move_speed;
else if (is_key_down(SDLK_DOWN))
body.velocity.y = +entity.move_speed;
else
body.velocity.y = 0.0f;
clamp_speed(entity.move_speed, body);
}
void update_player(Player &p, float dt)
{
update_body(p.body, dt);
for (int i = 0; i < p.lasers.size(); i++)
update_laser(p.lasers[i], dt);
control_entity(p.body, p.entity);
if (is_key_down(SDLK_z))
{
vec2 direction = vec2(0.0f, -1.0f);
for (int i = 0; i < p.lasers.size(); i++)
entity_fire_laser(p.id, p.lasers[i], p.entity, p.body);
}
}
void render_enemy(Enemy &e)
{
using namespace gfx2d;
draw_rectangle(e.body.position, e.body.size, 0xff9944ff);
Text text;
text << int(e.entity.hitpoints);
draw_string(e.body.position, text.getString());
}
void render_player(Player &p)
{
using namespace gfx2d;
draw_rectangle(p.body.position, p.body.size, 0x4499ffff);
Text text;
text << int(p.entity.hitpoints);
draw_string(p.body.position, text.getString());
}
void render_bullet(Bullet &b)
{
using namespace gfx2d;
draw_fill_rectangle(b.body.position, b.body.size, 0xd3baffff);
}
bool load_game(int width, int height)
{
if (!load_font(font, "../data/fonts/proggytinyttsz_8x12.png"))
return false;
window_width = width;
window_height = height;
gfx2d::init(width, height);
gfx2d::use_font(font);
return true;
}
void free_game()
{
}
void init_game()
{
new_enemy(vec2(200.0f, 200.0f), vec2(0.0f, 0.0f), vec2(0.0f, 0.0f));
new_enemy(vec2(90.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f, -10.0f));
new_enemy(vec2(140.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
new_enemy(vec2(180.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
new_enemy(vec2(220.0f, 30.0f), vec2(50.0f, 10.0f), vec2(0.0f));
init_player(vec2(200.0f, 400.0f), vec2(0.0f), vec2(0.0f));
}
void update_game(float dt)
{
spawn_timer -= dt;
if (spawn_timer <= 0.0f)
{
new_enemy(
vec2(
frand() * window_width,
frand() * window_height * 0.35f
),
vec2(
(-1.0f + 2.0f * frand()) * 100.0f,
frand() * 100.0f
),
vec2(
(-1.0f + 2.0f * frand()) * 100.0f,
(-1.0f + 2.0f * frand()) * 100.0f
)
);
spawn_timer += spawn_period;
}
for (int i = 0; i < world.enemies.size(); i++)
{
if (world.enemies[i].entity.dead)
{
world.enemies.erase(world.enemies.begin() + i);
i--;
}
else
{
update_enemy(world.enemies[i], dt);
}
}
for (int i = 0; i < world.bullets.size(); i++)
{
if (world.bullets[i].dead)
{
world.bullets.erase(world.bullets.begin() + i);
i--;
}
else
{
update_bullet(world.bullets[i], dt);
}
}
update_player(world.player, dt);
}
void render_game(float dt)
{
gfx2d::begin();
{
using namespace gfx2d;
clearc(BG_COLOR);
blend_mode(true, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for (int i = 0; i < world.enemies.size(); i++)
render_enemy(world.enemies[i]);
for (int i = 0; i < world.bullets.size(); i++)
render_bullet(world.bullets[i]);
render_player(world.player);
Text text;
text << "Enemies: " << world.enemies.size() << '\n';
text << "Bullets: " << world.bullets.size() << '\n';
draw_string(5.0f, 5.0f, text.getString());
}
gfx2d::end();
}<|endoftext|> |
<commit_before>#include "gurobi_solver.h"
#include <Eigen/Core>
#include "gurobi_c++.h"
#include "drake/common/drake_assert.h"
#include "drake/solvers/Optimization.h"
namespace drake {
namespace solvers {
namespace {
// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
// Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
// sparseA.makeCompressed();
// error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
// sparseA.InnerIndices(), sparseA.OuterStarts(),
// sparseA.Values(),sense, b.data(), nullptr);
// return(error);
/**
* Adds a constraint of one of the following forms :
* Ax>=b, Ax<=b, or Ax==b,
* where the character variable @p constraint_sense specifies the type.
* x in this case is the full dimensional variable being optimised.
*
* @param[in] constraint_sense a character variable specifying the
* sense on the constraint. The Gurobi macros maybe used to specify the
* constraint sense.
* i.e.
* GRB_LESS_EQUAL : '<'
* GRB_GREATER_EQUAL : '>'
* GRB_EQUAL : '='
*
* @return error as an integer. The full set of error values are
* described here :
* http://www.gurobi.com/documentation/6.5/refman/error_codes.html#sec:ErrorCodes
*/
template <typename DerivedA, typename DerivedB>
int AddConstraints(GRBmodel* model, const Eigen::MatrixBase<DerivedA>& A,
const Eigen::MatrixBase<DerivedB>& b, char constraint_sense,
double sparseness_threshold) {
for (size_t i = 0; i < A.rows(); i++) {
int non_zeros_index = 0;
std::vector<int> constraint_index(A.cols(), 0);
std::vector<double> constraint_value(A.cols(), 0.0);
for (size_t j = 0; j < A.cols(); j++) {
if (std::abs(A(i, j)) > sparseness_threshold) {
constraint_value[non_zeros_index] = A(i, j);
constraint_index[non_zeros_index++] = j;
}
}
int error =
GRBaddconstr(model, non_zeros_index, &constraint_index[0],
&constraint_value[0], constraint_sense, b(i), nullptr);
if (error) return error;
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
/// Splits out the quadratic costs and makes calls to add them individually.
int AddCosts(GRBmodel* model, OptimizationProblem& prog,
double sparseness_threshold) {
int start_row = 0;
for (const auto& binding : prog.quadratic_costs()) {
const auto& constraint = binding.constraint();
const int constraint_variable_dimension = binding.GetNumElements();
Eigen::MatrixXd Q = 0.5 * (constraint->Q());
Eigen::VectorXd b = constraint->b();
// Check for square matrices.
DRAKE_ASSERT(Q.rows() == Q.cols());
// Check for symmetric matrices.
DRAKE_ASSERT(Q.transpose() == Q);
// Check for Quadratic and Linear Cost dimensions.
DRAKE_ASSERT(Q.rows() == constraint_variable_dimension);
DRAKE_ASSERT(b.cols() == 1);
DRAKE_ASSERT(b.rows() == constraint_variable_dimension);
// adding each Q term (only upper triangular).
for (int i = 0; i < constraint_variable_dimension; i++) {
for (int j = i; j < constraint_variable_dimension; j++) {
if (std::abs(Q(i, j)) > sparseness_threshold) {
int row_ind = i + start_row;
int col_ind = j + start_row;
// TODO(naveenoid) : Port to batch addition mode of this function
// by utilising the Upper right (or lower left) triangular matrix.
// The single element addition method used below is recommended
// initially by Gurobi since it has a low cost.
double individual_quadratic_cost_value = Q(i, j);
const int error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
&individual_quadratic_cost_value);
if (error) {
return (error);
}
}
}
}
const int error = GRBsetdblattrarray(
model, "Obj", start_row, constraint_variable_dimension, b.data());
if (error) {
return error;
}
start_row += Q.rows();
// Verify that the start_row does not exceed the total possible
// dimension of the decision variable.
DRAKE_ASSERT(start_row <= prog.num_vars());
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
/// Splits out the equality and inequality constraints and makes call to
/// add any non-inf constraints.
int ProcessConstraints(GRBmodel* model, OptimizationProblem& prog,
double sparseness_threshold) {
// TODO(naveenoid) : needs test coverage.
for (const auto& binding : prog.linear_equality_constraints()) {
const auto& constraint = binding.constraint();
const int error =
AddConstraints(model, constraint->A(), constraint->lower_bound(),
GRB_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
for (const auto& binding : prog.linear_constraints()) {
const auto& constraint = binding.constraint();
if (constraint->lower_bound() !=
-Eigen::MatrixXd::Constant((constraint->lower_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
const int error =
AddConstraints(model, constraint->A(), constraint->lower_bound(),
GRB_GREATER_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
if (constraint->upper_bound() !=
Eigen::MatrixXd::Constant((constraint->upper_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
const int error =
AddConstraints(model, constraint->A(), constraint->upper_bound(),
GRB_LESS_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
} // close namespace
bool GurobiSolver::available() const { return true; }
SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
// We only process quadratic costs and linear / bounding box
// constraints.
GRBenv* env = nullptr;
GRBloadenv(&env, nullptr);
// Corresponds to no console or file logging.
GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);
DRAKE_ASSERT(prog.generic_costs().empty());
DRAKE_ASSERT(prog.generic_constraints().empty());
const int num_vars = prog.num_vars();
// bound constraints
std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());
for (const auto& binding : prog.bounding_box_constraints()) {
const auto& constraint = binding.constraint();
const Eigen::VectorXd& lower_bound = constraint->lower_bound();
const Eigen::VectorXd& upper_bound = constraint->upper_bound();
for (const DecisionVariableView& decision_variable_view :
binding.variable_list()) {
for (size_t k = 0; k < decision_variable_view.size(); k++) {
const int idx = decision_variable_view.index() + k;
xlow[idx] = std::max(lower_bound(k), xlow[idx]);
xupp[idx] = std::min(upper_bound(k), xupp[idx]);
}
}
}
GRBmodel* model = nullptr;
GRBnewmodel(env, &model, "QP", num_vars, nullptr, &xlow[0], &xupp[0], nullptr,
nullptr);
int error = 0;
// TODO(naveenoid) : This needs access externally.
double sparseness_threshold = 1e-14;
error = AddCosts(model, prog, sparseness_threshold);
if (!error) {
error = ProcessConstraints(model, prog, sparseness_threshold);
}
SolutionResult result = SolutionResult::kUnknownError;
if (!error) {
error = GRBoptimize(model);
}
// If any error exists so far, its either from invalid input or
// from unknown errors.
// TODO(naveenoid) : Properly handle gurobi specific error.
// message.
if (error) {
// TODO(naveenoid) : log error message using GRBgeterrormsg(env).
result = SolutionResult::kInvalidInput;
} else {
int optimstatus = 0;
GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (optimstatus != GRB_OPTIMAL) {
if (optimstatus == GRB_INF_OR_UNBD) {
result = SolutionResult::kInfeasibleConstraints;
}
} else {
result = SolutionResult::kSolutionFound;
Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);
GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
prog.SetDecisionVariableValues(sol_vector);
}
}
prog.SetSolverResult("Gurobi", error);
GRBfreemodel(model);
GRBfreeenv(env);
return result;
}
} // namespace drake
} // namespace solvers
<commit_msg>cpplint cleanup<commit_after>#include "gurobi_solver.h"
#include <Eigen/Core>
#include "gurobi_c++.h"
#include "drake/common/drake_assert.h"
#include "drake/solvers/Optimization.h"
namespace drake {
namespace solvers {
namespace {
// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
// Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
// sparseA.makeCompressed();
// error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
// sparseA.InnerIndices(), sparseA.OuterStarts(),
// sparseA.Values(),sense, b.data(), nullptr);
// return(error);
/**
* Adds a constraint of one of the following forms :
* Ax>=b, Ax<=b, or Ax==b,
* where the character variable @p constraint_sense specifies the type.
* x in this case is the full dimensional variable being optimised.
*
* @param[in] constraint_sense a character variable specifying the
* sense on the constraint. The Gurobi macros maybe used to specify the
* constraint sense.
* i.e.
* GRB_LESS_EQUAL : '<'
* GRB_GREATER_EQUAL : '>'
* GRB_EQUAL : '='
*
* @return error as an integer. The full set of error values are
* described here :
* http://www.gurobi.com/documentation/6.5/refman/error_codes.html#sec:ErrorCodes
*/
template <typename DerivedA, typename DerivedB>
int AddConstraints(GRBmodel* model, const Eigen::MatrixBase<DerivedA>& A,
const Eigen::MatrixBase<DerivedB>& b, char constraint_sense,
double sparseness_threshold) {
for (size_t i = 0; i < A.rows(); i++) {
int non_zeros_index = 0;
std::vector<int> constraint_index(A.cols(), 0);
std::vector<double> constraint_value(A.cols(), 0.0);
for (size_t j = 0; j < A.cols(); j++) {
if (std::abs(A(i, j)) > sparseness_threshold) {
constraint_value[non_zeros_index] = A(i, j);
constraint_index[non_zeros_index++] = j;
}
}
int error =
GRBaddconstr(model, non_zeros_index, &constraint_index[0],
&constraint_value[0], constraint_sense, b(i), nullptr);
if (error) return error;
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
/// Splits out the quadratic costs and makes calls to add them individually.
int AddCosts(GRBmodel* model, OptimizationProblem& prog,
double sparseness_threshold) {
int start_row = 0;
for (const auto& binding : prog.quadratic_costs()) {
const auto& constraint = binding.constraint();
const int constraint_variable_dimension = binding.GetNumElements();
Eigen::MatrixXd Q = 0.5 * (constraint->Q());
Eigen::VectorXd b = constraint->b();
// Check for square matrices.
DRAKE_ASSERT(Q.rows() == Q.cols());
// Check for symmetric matrices.
DRAKE_ASSERT(Q.transpose() == Q);
// Check for Quadratic and Linear Cost dimensions.
DRAKE_ASSERT(Q.rows() == constraint_variable_dimension);
DRAKE_ASSERT(b.cols() == 1);
DRAKE_ASSERT(b.rows() == constraint_variable_dimension);
// adding each Q term (only upper triangular).
for (int i = 0; i < constraint_variable_dimension; i++) {
for (int j = i; j < constraint_variable_dimension; j++) {
if (std::abs(Q(i, j)) > sparseness_threshold) {
int row_ind = i + start_row;
int col_ind = j + start_row;
// TODO(naveenoid) : Port to batch addition mode of this function
// by utilising the Upper right (or lower left) triangular matrix.
// The single element addition method used below is recommended
// initially by Gurobi since it has a low cost.
double individual_quadratic_cost_value = Q(i, j);
const int error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
&individual_quadratic_cost_value);
if (error) {
return (error);
}
}
}
}
const int error = GRBsetdblattrarray(
model, "Obj", start_row, constraint_variable_dimension, b.data());
if (error) {
return error;
}
start_row += Q.rows();
// Verify that the start_row does not exceed the total possible
// dimension of the decision variable.
DRAKE_ASSERT(start_row <= prog.num_vars());
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
/// Splits out the equality and inequality constraints and makes call to
/// add any non-inf constraints.
int ProcessConstraints(GRBmodel* model, OptimizationProblem& prog,
double sparseness_threshold) {
// TODO(naveenoid) : needs test coverage.
for (const auto& binding : prog.linear_equality_constraints()) {
const auto& constraint = binding.constraint();
const int error =
AddConstraints(model, constraint->A(), constraint->lower_bound(),
GRB_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
for (const auto& binding : prog.linear_constraints()) {
const auto& constraint = binding.constraint();
if (constraint->lower_bound() !=
-Eigen::MatrixXd::Constant((constraint->lower_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
const int error =
AddConstraints(model, constraint->A(), constraint->lower_bound(),
GRB_GREATER_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
if (constraint->upper_bound() !=
Eigen::MatrixXd::Constant((constraint->upper_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
const int error =
AddConstraints(model, constraint->A(), constraint->upper_bound(),
GRB_LESS_EQUAL, sparseness_threshold);
if (error) {
return error;
}
}
}
// If loop completes, no errors exist so the value '0' must be returned.
return 0;
}
} // close namespace
bool GurobiSolver::available() const { return true; }
SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
// We only process quadratic costs and linear / bounding box
// constraints.
GRBenv* env = nullptr;
GRBloadenv(&env, nullptr);
// Corresponds to no console or file logging.
GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);
DRAKE_ASSERT(prog.generic_costs().empty());
DRAKE_ASSERT(prog.generic_constraints().empty());
const int num_vars = prog.num_vars();
// bound constraints
std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());
for (const auto& binding : prog.bounding_box_constraints()) {
const auto& constraint = binding.constraint();
const Eigen::VectorXd& lower_bound = constraint->lower_bound();
const Eigen::VectorXd& upper_bound = constraint->upper_bound();
for (const DecisionVariableView& decision_variable_view :
binding.variable_list()) {
for (size_t k = 0; k < decision_variable_view.size(); k++) {
const int idx = decision_variable_view.index() + k;
xlow[idx] = std::max(lower_bound(k), xlow[idx]);
xupp[idx] = std::min(upper_bound(k), xupp[idx]);
}
}
}
GRBmodel* model = nullptr;
GRBnewmodel(env, &model, "QP", num_vars, nullptr, &xlow[0], &xupp[0], nullptr,
nullptr);
int error = 0;
// TODO(naveenoid) : This needs access externally.
double sparseness_threshold = 1e-14;
error = AddCosts(model, prog, sparseness_threshold);
if (!error) {
error = ProcessConstraints(model, prog, sparseness_threshold);
}
SolutionResult result = SolutionResult::kUnknownError;
if (!error) {
error = GRBoptimize(model);
}
// If any error exists so far, its either from invalid input or
// from unknown errors.
// TODO(naveenoid) : Properly handle gurobi specific error.
// message.
if (error) {
// TODO(naveenoid) : log error message using GRBgeterrormsg(env).
result = SolutionResult::kInvalidInput;
} else {
int optimstatus = 0;
GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (optimstatus != GRB_OPTIMAL) {
if (optimstatus == GRB_INF_OR_UNBD) {
result = SolutionResult::kInfeasibleConstraints;
}
} else {
result = SolutionResult::kSolutionFound;
Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);
GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
prog.SetDecisionVariableValues(sol_vector);
}
}
prog.SetSolverResult("Gurobi", error);
GRBfreemodel(model);
GRBfreeenv(env);
return result;
}
} // namespace drake
} // namespace solvers
<|endoftext|> |
<commit_before>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2009 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <cstdlib>
#include <cstdio>
#include "plugin-runner.h"
#include "factory.h"
static bool
sc(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
void
print_key_value(const char *key,
const char *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n%s\n", strlen(value), value);
}
void
print_key_value(const char *key,
int value_len,
void *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n", value_len);
fwrite(value, value_len, 1, stdout);
printf("\n");
}
static void
print_plugin(const char *type, img_factory *imgf) {
print_key_value("type", type);
print_key_value("display-name", imgf->get_name());
print_key_value("internal-name", imgf->get_description());
printf("\n");
}
void
list_plugins(void) {
void *cookie;
img_factory *imgf;
imgf = get_first_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("filter", imgf);
} while((imgf = get_next_factory(&cookie)));
}
imgf = get_first_codec_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("codec", imgf);
} while((imgf = get_next_factory(&cookie)));
}
}
static img_search *get_plugin(const char *type,
const char *internal_name) {
img_factory *imgf;
if (sc(type, "filter")) {
imgf = find_factory(internal_name);
} else if (sc(type, "codec")) {
imgf = find_codec_factory(internal_name);
} else {
printf("Invalid type\n");
return NULL;
}
if (!imgf) {
return NULL;
}
img_search *search = imgf->create("filter");
search->set_plugin_runner_mode(true);
return search;
}
static void
print_search_config(img_search *search) {
// editable?
print_key_value("is-editable", search->is_editable() ? "true" : "false");
// print blob
print_key_value("blob", search->get_auxiliary_data_length(),
search->get_auxiliary_data());
// print config
if (search->is_editable()) {
char *config;
size_t config_size;
FILE *memfile = open_memstream(&config, &config_size);
search->write_config(memfile, NULL);
fclose(memfile);
print_key_value("config", config_size, config);
free(config);
}
}
struct len_data {
int len;
void *data;
};
static int
expect_token_get_size(char token) {
char *line = NULL;
size_t n;
int result = -1;
int c;
// expect token
c = getchar();
// g_debug("%c", c);
if (c != token) {
goto OUT;
}
c = getchar();
// g_debug("%c", c);
if (c != ' ') {
goto OUT;
}
// read size
if (getline(&line, &n, stdin) == -1) {
goto OUT;
}
result = atoi(line);
// g_debug("size: %d", result);
OUT:
free(line);
return result;
}
static bool
populate_search(img_search *search, GHashTable *user_config) {
return true;
}
static GHashTable *
read_key_value_pairs() {
GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
while(true) {
// read key size
int keysize = expect_token_get_size('K');
if (keysize == -1) {
break;
}
// read key + \n
char *key = (char *) g_malloc(keysize + 1);
if (keysize > 0) {
if (fread(key, keysize + 1, 1, stdin) != 1) {
g_free(key);
break;
}
}
key[keysize] = '\0'; // key is a string
// read value size
int valuesize = expect_token_get_size('V');
if (valuesize == -1) {
g_free(key);
}
// read value + \n
void *value = g_malloc(valuesize);
if (valuesize > 0) {
if (fread(value, valuesize, 1, stdin) != 1) {
g_free(key);
g_free(value);
break;
}
}
getchar(); // value is not null terminated
// add entry
// g_debug("key: %s, valuesize: %d", key, valuesize);
struct len_data *ld = g_new(struct len_data, 1);
ld->len = valuesize;
ld->data = value;
g_hash_table_insert(ht, key, ld);
}
return ht;
}
int
get_plugin_initial_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
print_search_config(search);
return 0;
}
int
edit_plugin_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
if (!search->is_editable()) {
printf("Not editable");
return 1;
}
GHashTable *user_config = read_key_value_pairs();
if (!populate_search(search, user_config)) {
return 1;
}
search->edit_search();
gtk_main();
print_search_config(search);
return 0;
}
<commit_msg>Finished mostly-working read config support, still missing patches<commit_after>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2009 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <cstdlib>
#include <cstdio>
#include "plugin-runner.h"
#include "factory.h"
#include "read_config.h"
static bool
sc(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
void
print_key_value(const char *key,
const char *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n%s\n", strlen(value), value);
}
void
print_key_value(const char *key,
int value_len,
void *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n", value_len);
fwrite(value, value_len, 1, stdout);
printf("\n");
}
static void
print_plugin(const char *type, img_factory *imgf) {
print_key_value("type", type);
print_key_value("display-name", imgf->get_name());
print_key_value("internal-name", imgf->get_description());
printf("\n");
}
void
list_plugins(void) {
void *cookie;
img_factory *imgf;
imgf = get_first_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("filter", imgf);
} while((imgf = get_next_factory(&cookie)));
}
imgf = get_first_codec_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("codec", imgf);
} while((imgf = get_next_factory(&cookie)));
}
}
static img_search *get_plugin(const char *type,
const char *internal_name) {
img_factory *imgf;
if (sc(type, "filter")) {
imgf = find_factory(internal_name);
} else if (sc(type, "codec")) {
imgf = find_codec_factory(internal_name);
} else {
printf("Invalid type\n");
return NULL;
}
if (!imgf) {
return NULL;
}
img_search *search = imgf->create("filter");
search->set_plugin_runner_mode(true);
return search;
}
static void
print_search_config(img_search *search) {
// editable?
print_key_value("is-editable", search->is_editable() ? "true" : "false");
// print blob
print_key_value("blob", search->get_auxiliary_data_length(),
search->get_auxiliary_data());
// print config
if (search->is_editable()) {
char *config;
size_t config_size;
FILE *memfile = open_memstream(&config, &config_size);
search->write_config(memfile, NULL);
fclose(memfile);
print_key_value("config", config_size, config);
free(config);
}
}
struct len_data {
int len;
void *data;
};
static int
expect_token_get_size(char token) {
char *line = NULL;
size_t n;
int result = -1;
int c;
// expect token
c = getchar();
// g_debug("%c", c);
if (c != token) {
goto OUT;
}
c = getchar();
// g_debug("%c", c);
if (c != ' ') {
goto OUT;
}
// read size
if (getline(&line, &n, stdin) == -1) {
goto OUT;
}
result = atoi(line);
// g_debug("size: %d", result);
OUT:
free(line);
return result;
}
static void
populate_search(img_search *search, GHashTable *user_config) {
struct len_data *ld;
// blob
ld = (struct len_data *) g_hash_table_lookup(user_config, "blob");
if (ld) {
search->set_auxiliary_data_length(ld->len);
search->set_auxiliary_data(ld->data);
}
// config
ld = (struct len_data *) g_hash_table_lookup(user_config, "config");
if (ld) {
read_search_config_for_plugin_runner(ld->data, ld->len, search);
}
}
static GHashTable *
read_key_value_pairs() {
GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
while(true) {
// read key size
int keysize = expect_token_get_size('K');
if (keysize == -1) {
break;
}
// read key + \n
char *key = (char *) g_malloc(keysize + 1);
if (keysize > 0) {
if (fread(key, keysize + 1, 1, stdin) != 1) {
g_free(key);
break;
}
}
key[keysize] = '\0'; // key is a string
// read value size
int valuesize = expect_token_get_size('V');
if (valuesize == -1) {
g_free(key);
}
// read value + \n
void *value = g_malloc(valuesize);
if (valuesize > 0) {
if (fread(value, valuesize, 1, stdin) != 1) {
g_free(key);
g_free(value);
break;
}
}
getchar(); // value is not null terminated
// add entry
//fprintf(stderr, "key: %s, valuesize: %d\n", key, valuesize);
struct len_data *ld = g_new(struct len_data, 1);
ld->len = valuesize;
ld->data = value;
g_hash_table_insert(ht, key, ld);
}
return ht;
}
int
get_plugin_initial_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
print_search_config(search);
return 0;
}
int
edit_plugin_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
if (!search->is_editable()) {
printf("Not editable");
return 1;
}
GHashTable *user_config = read_key_value_pairs();
populate_search(search, user_config);
search->edit_search();
gtk_main();
print_search_config(search);
return 0;
}
<|endoftext|> |
<commit_before>#include <sal/net/__bits/platform.hpp>
#if __sal_os_windows
#include <mutex>
#else
#include <fcntl.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
__sal_begin
namespace net {
#if __sal_os_windows
namespace {
struct lib_t
{
lib_t () noexcept
{
setup();
}
~lib_t () noexcept
{
cleanup();
}
static std::error_code setup_result;
static lib_t lib;
static void setup () noexcept;
static void cleanup () noexcept;
};
std::error_code lib_t::setup_result{};
lib_t lib_t::lib;
void internal_setup (std::error_code &result) noexcept
{
WSADATA wsa;
result.assign(
::WSAStartup(MAKEWORD(2, 2), &wsa),
std::system_category()
);
}
void lib_t::setup () noexcept
{
static std::once_flag flag;
std::call_once(flag, &internal_setup, setup_result);
}
void lib_t::cleanup () noexcept
{
::WSACleanup();
}
} // namespace
#endif
const std::error_code &init () noexcept
{
#if __sal_os_windows
lib_t::setup();
return lib_t::setup_result;
#else
static std::error_code result{};
return result;
#endif
}
namespace __bits {
namespace {
inline void get_last (std::error_code &error, bool align_with_posix=true)
noexcept
{
#if __sal_os_windows
auto e = ::WSAGetLastError();
if (align_with_posix && e == WSAENOTSOCK)
{
e = WSAEBADF;
}
error.assign(e, std::system_category());
#else
(void)align_with_posix;
error.assign(errno, std::generic_category());
#endif
}
} // namespace
native_handle_t open (int domain,
int type,
int protocol,
std::error_code &error) noexcept
{
auto handle = ::socket(domain, type, protocol);
// ignore error handling, API doesn't let trigger invalid case
// LCOV_EXCL_START
if (handle == -1)
{
get_last(error, false);
}
// LCOV_EXCL_STOP
return handle;
}
void close (native_handle_t handle,
std::error_code &error) noexcept
{
#if __sal_os_windows
if (::closesocket(handle) == 0)
{
return;
}
#else
for (errno = EINTR; errno == EINTR; /**/)
{
if (::close(handle) == 0)
{
return;
}
}
#endif
get_last(error);
}
void get_opt (native_handle_t handle,
int level,
int name,
void *data,
socklen_t *size,
std::error_code &error) noexcept
{
if (::getsockopt(handle, level, name, reinterpret_cast<char *>(data), size))
{
get_last(error);
}
}
void set_opt (native_handle_t handle,
int level,
int name,
const void *data,
socklen_t size,
std::error_code &error) noexcept
{
if (::setsockopt(handle, level, name, reinterpret_cast<const char *>(data), size))
{
get_last(error);
}
}
bool non_blocking (native_handle_t handle, std::error_code &error) noexcept
{
#if __sal_os_windows
(void)handle;
error.assign(WSAEOPNOTSUPP, std::system_category());
return true;
#else
auto flags = ::fcntl(handle, F_GETFL, 0);
if (flags == -1)
{
get_last(error);
}
// it'll be unusable value
return flags & O_NONBLOCK;
#endif
}
void non_blocking (native_handle_t handle,
bool mode,
std::error_code &error) noexcept
{
#if __sal_os_windows
unsigned long arg = mode ? 1 : 0;
if (::ioctlsocket(handle, FIONBIO, &arg) != SOCKET_ERROR)
{
return;
}
#else
int flags = ::fcntl(handle, F_GETFL, 0);
if (flags >= 0)
{
if (mode)
{
flags |= O_NONBLOCK;
}
else
{
flags &= ~O_NONBLOCK;
}
if (::fcntl(handle, F_SETFL, flags) != -1)
{
return;
}
}
#endif
get_last(error);
}
size_t available (native_handle_t handle, std::error_code &error) noexcept
{
unsigned long value{};
#if __sal_os_windows
if (::ioctlsocket(handle, FIONBIO, &value) != SOCKET_ERROR)
{
return value;
}
#else
if (::ioctl(handle, FIONREAD, &value) != -1)
{
return value;
}
#endif
get_last(error);
return 0U;
}
void bind (native_handle_t handle,
const void *address, size_t address_size,
std::error_code &error) noexcept
{
if (::bind(handle,
static_cast<const sockaddr *>(address),
static_cast<socklen_t>(address_size)) == -1)
{
get_last(error);
}
}
void connect (native_handle_t handle,
const void *address, size_t address_size,
std::error_code &error) noexcept
{
if (::connect(handle,
static_cast<const sockaddr *>(address),
static_cast<socklen_t>(address_size)) == -1)
{
get_last(error);
}
}
void shutdown (native_handle_t handle, int what, std::error_code &error)
noexcept
{
if (::shutdown(handle, what) == -1)
{
get_last(error);
}
}
bool wait (native_handle_t handle, wait_t what, int timeout_ms,
std::error_code &error) noexcept
{
#if __sal_os_darwin
if (handle == invalid_socket)
{
error.assign(EBADF, std::generic_category());
return false;
}
#elif __sal_os_windows
#define poll WSAPoll
#endif
pollfd fd{};
fd.fd = handle;
fd.events = what == wait_t::read ? POLLIN : POLLOUT;
auto event_count = ::poll(&fd, 1, timeout_ms);
if (event_count == 1)
{
return (fd.revents & fd.events) != 0;
}
// LCOV_EXCL_START
// can't reach this case by feeding incorrect parameters
else if (event_count == -1)
{
get_last(error);
}
// LCOV_EXCL_STOP
return false;
}
void local_endpoint (native_handle_t handle,
void *address, size_t *address_size,
std::error_code &error) noexcept
{
auto size = static_cast<socklen_t>(*address_size);
if (::getsockname(handle, static_cast<sockaddr *>(address), &size) != -1)
{
*address_size = size;
}
else
{
get_last(error);
}
}
void remote_endpoint (native_handle_t handle,
void *address, size_t *address_size,
std::error_code &error) noexcept
{
auto size = static_cast<socklen_t>(*address_size);
if (::getpeername(handle, static_cast<sockaddr *>(address), &size) != -1)
{
*address_size = size;
}
else
{
get_last(error);
}
}
} // namespace __bits
} // namespace net
__sal_end
<commit_msg>net/socket: align Linux wait() with Darwin/Windows platforms<commit_after>#include <sal/net/__bits/platform.hpp>
#if __sal_os_windows
#include <mutex>
#else
#include <fcntl.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
__sal_begin
namespace net {
#if __sal_os_windows
namespace {
struct lib_t
{
lib_t () noexcept
{
setup();
}
~lib_t () noexcept
{
cleanup();
}
static std::error_code setup_result;
static lib_t lib;
static void setup () noexcept;
static void cleanup () noexcept;
};
std::error_code lib_t::setup_result{};
lib_t lib_t::lib;
void internal_setup (std::error_code &result) noexcept
{
WSADATA wsa;
result.assign(
::WSAStartup(MAKEWORD(2, 2), &wsa),
std::system_category()
);
}
void lib_t::setup () noexcept
{
static std::once_flag flag;
std::call_once(flag, &internal_setup, setup_result);
}
void lib_t::cleanup () noexcept
{
::WSACleanup();
}
} // namespace
#endif
const std::error_code &init () noexcept
{
#if __sal_os_windows
lib_t::setup();
return lib_t::setup_result;
#else
static std::error_code result{};
return result;
#endif
}
namespace __bits {
namespace {
inline void get_last (std::error_code &error, bool align_with_posix=true)
noexcept
{
#if __sal_os_windows
auto e = ::WSAGetLastError();
if (align_with_posix && e == WSAENOTSOCK)
{
e = WSAEBADF;
}
error.assign(e, std::system_category());
#else
(void)align_with_posix;
error.assign(errno, std::generic_category());
#endif
}
} // namespace
native_handle_t open (int domain,
int type,
int protocol,
std::error_code &error) noexcept
{
auto handle = ::socket(domain, type, protocol);
// ignore error handling, API doesn't let trigger invalid case
// LCOV_EXCL_START
if (handle == -1)
{
get_last(error, false);
}
// LCOV_EXCL_STOP
return handle;
}
void close (native_handle_t handle,
std::error_code &error) noexcept
{
#if __sal_os_windows
if (::closesocket(handle) == 0)
{
return;
}
#else
for (errno = EINTR; errno == EINTR; /**/)
{
if (::close(handle) == 0)
{
return;
}
}
#endif
get_last(error);
}
void get_opt (native_handle_t handle,
int level,
int name,
void *data,
socklen_t *size,
std::error_code &error) noexcept
{
if (::getsockopt(handle, level, name, reinterpret_cast<char *>(data), size))
{
get_last(error);
}
}
void set_opt (native_handle_t handle,
int level,
int name,
const void *data,
socklen_t size,
std::error_code &error) noexcept
{
if (::setsockopt(handle, level, name, reinterpret_cast<const char *>(data), size))
{
get_last(error);
}
}
bool non_blocking (native_handle_t handle, std::error_code &error) noexcept
{
#if __sal_os_windows
(void)handle;
error.assign(WSAEOPNOTSUPP, std::system_category());
return true;
#else
auto flags = ::fcntl(handle, F_GETFL, 0);
if (flags == -1)
{
get_last(error);
}
// it'll be unusable value
return flags & O_NONBLOCK;
#endif
}
void non_blocking (native_handle_t handle,
bool mode,
std::error_code &error) noexcept
{
#if __sal_os_windows
unsigned long arg = mode ? 1 : 0;
if (::ioctlsocket(handle, FIONBIO, &arg) != SOCKET_ERROR)
{
return;
}
#else
int flags = ::fcntl(handle, F_GETFL, 0);
if (flags >= 0)
{
if (mode)
{
flags |= O_NONBLOCK;
}
else
{
flags &= ~O_NONBLOCK;
}
if (::fcntl(handle, F_SETFL, flags) != -1)
{
return;
}
}
#endif
get_last(error);
}
size_t available (native_handle_t handle, std::error_code &error) noexcept
{
unsigned long value{};
#if __sal_os_windows
if (::ioctlsocket(handle, FIONBIO, &value) != SOCKET_ERROR)
{
return value;
}
#else
if (::ioctl(handle, FIONREAD, &value) != -1)
{
return value;
}
#endif
get_last(error);
return 0U;
}
void bind (native_handle_t handle,
const void *address, size_t address_size,
std::error_code &error) noexcept
{
if (::bind(handle,
static_cast<const sockaddr *>(address),
static_cast<socklen_t>(address_size)) == -1)
{
get_last(error);
}
}
void connect (native_handle_t handle,
const void *address, size_t address_size,
std::error_code &error) noexcept
{
if (::connect(handle,
static_cast<const sockaddr *>(address),
static_cast<socklen_t>(address_size)) == -1)
{
get_last(error);
}
}
void shutdown (native_handle_t handle, int what, std::error_code &error)
noexcept
{
if (::shutdown(handle, what) == -1)
{
get_last(error);
}
}
bool wait (native_handle_t handle, wait_t what, int timeout_ms,
std::error_code &error) noexcept
{
#if __sal_os_darwin || __sal_os_linux
if (handle == invalid_socket)
{
error.assign(EBADF, std::generic_category());
return false;
}
#elif __sal_os_windows
#define poll WSAPoll
#endif
pollfd fd{};
fd.fd = handle;
fd.events = what == wait_t::read ? POLLIN : POLLOUT;
auto event_count = ::poll(&fd, 1, timeout_ms);
if (event_count == 1)
{
#if __sal_os_linux
// Linux does the "right thing", setting POLLHUP on non-connected sockets
// unfortunately Darwin & Windows disagree and no way to detect such
// situation, so simply align after their behaviour
if (fd.revents & POLLHUP)
{
return false;
}
#endif
return (fd.revents & fd.events) != 0;
}
// LCOV_EXCL_START
// can't reach this case by feeding incorrect parameters
else if (event_count == -1)
{
get_last(error);
}
// LCOV_EXCL_STOP
return false;
}
void local_endpoint (native_handle_t handle,
void *address, size_t *address_size,
std::error_code &error) noexcept
{
auto size = static_cast<socklen_t>(*address_size);
if (::getsockname(handle, static_cast<sockaddr *>(address), &size) != -1)
{
*address_size = size;
}
else
{
get_last(error);
}
}
void remote_endpoint (native_handle_t handle,
void *address, size_t *address_size,
std::error_code &error) noexcept
{
auto size = static_cast<socklen_t>(*address_size);
if (::getpeername(handle, static_cast<sockaddr *>(address), &size) != -1)
{
*address_size = size;
}
else
{
get_last(error);
}
}
} // namespace __bits
} // namespace net
__sal_end
<|endoftext|> |
<commit_before>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "popcount.h"
#include "PrimeNumberFinder.h"
#include "SieveOfEratosthenes.h"
#include "PrimeSieve.h"
#include "GENERATE.h"
#include "config.h"
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
namespace soe {
const uint_t PrimeNumberFinder::kBitmasks_[7][5] =
{
{ END },
{ 0x06, 0x18, 0xc0, END }, // Twin prime bitmasks, i.e. b00000110, b00011000, b11000000
{ 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplet bitmasks, i.e. b00000111, b00001110, ...
{ 0x1e, END }, // Prime quadruplet bitmasks
{ 0x1f, 0x3e, END }, // Prime quintuplet bitmasks
{ 0x3f, END }, // Prime sextuplet bitmasks
{ 0xfe, END } // Prime septuplet bitmasks
};
PrimeNumberFinder::PrimeNumberFinder(PrimeSieve& ps) :
SieveOfEratosthenes(
std::max<uint64_t>(7, ps.getStart()),
ps.getStop(),
ps.getSieveSize(),
ps.getPreSieve()),
ps_(ps)
{
if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEPTUPLETS))
init_kCounts();
}
/// Calculate the number of twins, triplets, ... (bitmask matches)
/// for each possible byte value 0 - 255.
///
void PrimeNumberFinder::init_kCounts()
{
for (uint_t i = 1; i < ps_.counts_.size(); i++) {
if (ps_.isCount(i)) {
kCounts_[i].resize(256);
for (uint_t j = 0; j < kCounts_[i].size(); j++) {
uint_t bitmaskCount = 0;
for (const uint_t* b = kBitmasks_[i]; *b <= j; b++) {
if ((j & *b) == *b)
bitmaskCount++;
}
kCounts_[i][j] = bitmaskCount;
}
}
}
}
/// Executed after each sieved segment.
/// @see sieveSegment() in SieveOfEratosthenes.cpp
///
void PrimeNumberFinder::segmentProcessed(const uint8_t* sieve, uint_t sieveSize)
{
if (ps_.isCount())
count(sieve, sieveSize);
if (ps_.isGenerate())
generate(sieve, sieveSize);
if (ps_.isStatus())
ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE, /* waitForLock = */ false);
}
/// Count the primes and prime k-tuplets within
/// the current segment.
///
void PrimeNumberFinder::count(const uint8_t* sieve, uint_t sieveSize)
{
std::vector<uint64_t>& counts = ps_.counts_;
// count prime numbers, see popcount.h
if (ps_.isFlag(ps_.COUNT_PRIMES))
counts[0] += popcount_lauradoux(reinterpret_cast<const uint64_t*>(sieve), (sieveSize + 7) / 8);
// count prime k-tuplets (i = 1 twins, i = 2 triplets, ...)
for (uint_t i = 1; i < counts.size(); i++) {
if (ps_.isCount(i)) {
const std::vector<uint_t>& kCounts = kCounts_[i];
uint_t sum0 = 0;
uint_t sum1 = 0;
uint_t sum2 = 0;
uint_t sum3 = 0;
for (uint_t j = 0; j < sieveSize; j += 4) {
sum0 += kCounts[sieve[j+0]];
sum1 += kCounts[sieve[j+1]];
sum2 += kCounts[sieve[j+2]];
sum3 += kCounts[sieve[j+3]];
}
counts[i] += (sum0 + sum1) + (sum2 + sum3);
}
}
}
/// Generate (print and callback) the primes and prime
/// k-tuplets within the current segment.
/// @warning primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeNumberFinder::generate(const uint8_t* sieve, uint_t sieveSize) const
{
// print prime k-tuplets to cout
if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEPTUPLETS)) {
uint_t i = 1; // i = 1 twins, i = 2 triplets, ...
for (; !ps_.isPrint(i); i++)
;
// for more speed see GENERATE.h
for (uint_t j = 0; j < sieveSize; j++) {
for (const uint_t* bitmask = kBitmasks_[i]; *bitmask <= sieve[j]; bitmask++) {
if ((sieve[j] & *bitmask) == *bitmask) {
std::ostringstream kTuplet;
kTuplet << "(";
uint_t bits = *bitmask;
while (bits != 0) {
kTuplet << getNextPrime(j, &bits);
kTuplet << (bits != 0 ? ", " : ")\n");
}
std::cout << kTuplet.str();
}
}
}
}
// callback prime numbers
if (ps_.isFlag(ps_.PRINT_PRIMES)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(print, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK32)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(ps_.callback32_, uint32_t) }
if (ps_.isFlag(ps_.CALLBACK64)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(ps_.callback64_, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK32_OBJ)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(callback32_obj, uint32_t) }
if (ps_.isFlag(ps_.CALLBACK64_OBJ)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(callback64_obj, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK64_INT)) { GENERATE_PRIMES(callback64_int, uint64_t) }
}
void PrimeNumberFinder::print(uint64_t prime)
{
std::cout << prime << '\n';
}
void PrimeNumberFinder::callback32_obj(uint32_t prime) const
{
ps_.callback32_obj_(prime, ps_.obj_);
}
void PrimeNumberFinder::callback64_obj(uint64_t prime) const
{
ps_.callback64_obj_(prime, ps_.obj_);
}
void PrimeNumberFinder::callback64_int(uint64_t prime) const
{
ps_.callback64_int_(prime, ps_.threadNum_);
}
} // namespace soe
<commit_msg>improved code readability<commit_after>//
// Copyright (c) 2012 Kim Walisch, <[email protected]>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "popcount.h"
#include "PrimeNumberFinder.h"
#include "SieveOfEratosthenes.h"
#include "PrimeSieve.h"
#include "GENERATE.h"
#include "config.h"
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
namespace soe {
const uint_t PrimeNumberFinder::kBitmasks_[7][5] =
{
{ END },
{ 0x06, 0x18, 0xc0, END }, // Twin prime bitmasks, i.e. b00000110, b00011000, b11000000
{ 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplet bitmasks, i.e. b00000111, b00001110, ...
{ 0x1e, END }, // Prime quadruplet bitmasks
{ 0x1f, 0x3e, END }, // Prime quintuplet bitmasks
{ 0x3f, END }, // Prime sextuplet bitmasks
{ 0xfe, END } // Prime septuplet bitmasks
};
PrimeNumberFinder::PrimeNumberFinder(PrimeSieve& ps) :
SieveOfEratosthenes(
std::max<uint64_t>(7, ps.getStart()),
ps.getStop(),
ps.getSieveSize(),
ps.getPreSieve()),
ps_(ps)
{
if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEPTUPLETS))
init_kCounts();
}
/// Calculate the number of twins, triplets, ... (bitmask matches)
/// for each possible byte value 0 - 255.
///
void PrimeNumberFinder::init_kCounts()
{
for (uint_t i = 1; i < ps_.counts_.size(); i++) {
if (ps_.isCount(i)) {
kCounts_[i].resize(256);
for (uint_t j = 0; j < kCounts_[i].size(); j++) {
uint_t bitmaskCount = 0;
for (const uint_t* b = kBitmasks_[i]; *b <= j; b++) {
if ((j & *b) == *b)
bitmaskCount++;
}
kCounts_[i][j] = bitmaskCount;
}
}
}
}
/// Executed after each sieved segment.
/// @see sieveSegment() in SieveOfEratosthenes.cpp
///
void PrimeNumberFinder::segmentProcessed(const uint8_t* sieve, uint_t sieveSize)
{
if (ps_.isCount())
count(sieve, sieveSize);
if (ps_.isGenerate())
generate(sieve, sieveSize);
if (ps_.isStatus())
ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE, /* waitForLock = */ false);
}
/// Count the primes and prime k-tuplets within
/// the current segment.
///
void PrimeNumberFinder::count(const uint8_t* sieve, uint_t sieveSize)
{
std::vector<uint64_t>& counts = ps_.counts_;
// count prime numbers, see popcount.h
if (ps_.isFlag(ps_.COUNT_PRIMES))
counts[0] += popcount_lauradoux(reinterpret_cast<const uint64_t*>(sieve), (sieveSize + 7) / 8);
// count prime k-tuplets (i = 1 twins, i = 2 triplets, ...)
for (uint_t i = 1; i < counts.size(); i++) {
if (ps_.isCount(i)) {
const std::vector<uint_t>& kCounts = kCounts_[i];
uint_t sum0 = 0;
uint_t sum1 = 0;
uint_t sum2 = 0;
uint_t sum3 = 0;
for (uint_t j = 0; j < sieveSize; j += 4) {
sum0 += kCounts[sieve[j+0]];
sum1 += kCounts[sieve[j+1]];
sum2 += kCounts[sieve[j+2]];
sum3 += kCounts[sieve[j+3]];
}
counts[i] += (sum0 + sum1) + (sum2 + sum3);
}
}
}
/// Generate (print and callback) the primes and prime
/// k-tuplets within the current segment.
/// @warning primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeNumberFinder::generate(const uint8_t* sieve, uint_t sieveSize) const
{
// print prime k-tuplets to cout
if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEPTUPLETS)) {
uint_t i = 1; // i = 1 twins, i = 2 triplets, ...
for (; !ps_.isPrint(i); i++)
;
// for more speed see GENERATE.h
for (uint_t j = 0; j < sieveSize; j++) {
for (const uint_t* bitmask = kBitmasks_[i]; *bitmask <= sieve[j]; bitmask++) {
if ((sieve[j] & *bitmask) == *bitmask) {
std::ostringstream kTuplet;
kTuplet << "(";
uint_t bits = *bitmask;
while (bits != 0) {
kTuplet << getNextPrime(j, &bits);
kTuplet << ((bits != 0) ? ", " : ")\n");
}
std::cout << kTuplet.str();
}
}
}
}
// callback prime numbers
if (ps_.isFlag(ps_.PRINT_PRIMES)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(print, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK32)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(ps_.callback32_, uint32_t) }
if (ps_.isFlag(ps_.CALLBACK64)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(ps_.callback64_, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK32_OBJ)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(callback32_obj, uint32_t) }
if (ps_.isFlag(ps_.CALLBACK64_OBJ)) { PrimeSieve::LockGuard lock(ps_); GENERATE_PRIMES(callback64_obj, uint64_t) }
if (ps_.isFlag(ps_.CALLBACK64_INT)) { GENERATE_PRIMES(callback64_int, uint64_t) }
}
void PrimeNumberFinder::print(uint64_t prime)
{
std::cout << prime << '\n';
}
void PrimeNumberFinder::callback32_obj(uint32_t prime) const
{
ps_.callback32_obj_(prime, ps_.obj_);
}
void PrimeNumberFinder::callback64_obj(uint64_t prime) const
{
ps_.callback64_obj_(prime, ps_.obj_);
}
void PrimeNumberFinder::callback64_int(uint64_t prime) const
{
ps_.callback64_int_(prime, ps_.threadNum_);
}
} // namespace soe
<|endoftext|> |
<commit_before>#ifdef PLATFORM_WINDOWS_64
#include"platform.h"
#include<Windows.h>
//globals
s_platform_globals g_platform_globals;
void platform_init()
{
//NOTE: May cause unexpected behavior if/when the engine is compiled into a DLL
// keep an eye on this!
g_platform_globals.hInstance = GetModuleHandle(NULL);
}
bool platform_update()
{
// this struct holds Windows event messages
MSG msg;
bool returnval = true;
// wait for the next message in the queue, store the result in 'msg'
if(GetMessage(&msg, NULL, 0, 0))
{
// translate keystroke messages into the right format
TranslateMessage(&msg);
// send the message to the WindowProc function
DispatchMessage(&msg);
}
else
{
returnval = false;
}
return returnval;
}
void platform_exit()
{
exit(0);
}
#endif
<commit_msg>changed to peekmessage<commit_after>#ifdef PLATFORM_WINDOWS_64
#include"platform.h"
#include<Windows.h>
//globals
s_platform_globals g_platform_globals;
void platform_init()
{
//NOTE: May cause unexpected behavior if/when the engine is compiled into a DLL
// keep an eye on this!
g_platform_globals.hInstance = GetModuleHandle(NULL);
}
bool platform_update()
{
// this struct holds Windows event messages
MSG msg;
bool returnval = true;
// wait for the next message in the queue, store the result in 'msg'
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// translate keystroke messages into the right format
TranslateMessage(&msg);
// send the message to the WindowProc function
DispatchMessage(&msg);
}
if(msg.message == WM_QUIT)
{
returnval = false;
}
return returnval;
}
void platform_exit()
{
exit(0);
}
#endif
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file.
#include "XalanSourceTreeParserLiaison.hpp"
#include <algorithm>
#include <sax2/XMLReaderFactory.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
#include "XalanSourceTreeContentHandler.hpp"
#include "XalanSourceTreeDOMSupport.hpp"
#include "XalanSourceTreeDocument.hpp"
// http://xml.org/sax/features/validation
const XalanDOMChar XalanSourceTreeParserLiaison::validationString[] = {
XalanUnicode::charLetter_h,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_p,
XalanUnicode::charColon,
XalanUnicode::charSolidus,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_x,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_l,
XalanUnicode::charFullStop,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_g,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_x,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_s,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_v,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_d,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
0
};
XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison(XalanSourceTreeDOMSupport& /* theSupport */) :
m_documentNumber(0),
m_xercesParserLiaison(),
m_documentMap(),
m_persistentDocumentMap(),
m_poolAllText(true)
{
}
XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison() :
m_xercesParserLiaison(),
m_documentMap(),
m_persistentDocumentMap(),
m_poolAllText(true)
{
}
XalanSourceTreeParserLiaison::~XalanSourceTreeParserLiaison()
{
reset();
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any persistent documents.
for_each(m_persistentDocumentMap.begin(),
m_persistentDocumentMap.end(),
makeMapValueDeleteFunctor(m_persistentDocumentMap));
m_persistentDocumentMap.clear();
}
void
XalanSourceTreeParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any documents.
for_each(m_documentMap.begin(),
m_documentMap.end(),
makeMapValueDeleteFunctor(m_documentMap));
m_documentMap.clear();
m_xercesParserLiaison.reset();
}
ExecutionContext*
XalanSourceTreeParserLiaison::getExecutionContext() const
{
return m_xercesParserLiaison.getExecutionContext();
}
void
XalanSourceTreeParserLiaison::setExecutionContext(ExecutionContext& theContext)
{
m_xercesParserLiaison.setExecutionContext(theContext);
}
void
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& inputSource,
DocumentHandler& handler,
const XalanDOMString& identifier)
{
m_xercesParserLiaison.parseXMLStream(inputSource, handler, identifier);
}
XalanDocument*
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& inputSource,
const XalanDOMString& /* identifier */)
{
XalanSourceTreeContentHandler theContentHandler(createXalanSourceTreeDocument());
XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader());
theReader->setFeature(
validationString,
m_xercesParserLiaison.getUseValidation());
theReader->setContentHandler(&theContentHandler);
theReader->setDTDHandler(&theContentHandler);
theReader->setErrorHandler(&m_xercesParserLiaison);
theReader->setLexicalHandler(&theContentHandler);
theReader->setEntityResolver(getEntityResolver());
theReader->parse(inputSource);
return theContentHandler.getDocument();
}
XalanDocument*
XalanSourceTreeParserLiaison::createDocument()
{
return createXalanSourceTreeDocument();
}
XalanDocument*
XalanSourceTreeParserLiaison::createDOMFactory()
{
return m_xercesParserLiaison.createDocument();
}
void
XalanSourceTreeParserLiaison::destroyDocument(XalanDocument* theDocument)
{
if (mapDocument(theDocument) != 0)
{
m_documentMap.erase(theDocument);
delete theDocument;
}
}
unsigned long
XalanSourceTreeParserLiaison::getDocumentNumber()
{
return m_documentNumber++;
}
int
XalanSourceTreeParserLiaison::getIndent() const
{
return m_xercesParserLiaison.getIndent();
}
void
XalanSourceTreeParserLiaison::setIndent(int i)
{
m_xercesParserLiaison.setIndent(i);
}
bool
XalanSourceTreeParserLiaison::getUseValidation() const
{
return m_xercesParserLiaison.getUseValidation();
}
void
XalanSourceTreeParserLiaison::setUseValidation(bool b)
{
m_xercesParserLiaison.setUseValidation(b);
}
const XalanDOMString
XalanSourceTreeParserLiaison::getParserDescription() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("XalanSourceTree"));
}
void
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& theInputSource,
ContentHandler& theContentHandler,
DTDHandler* theDTDHandler,
LexicalHandler* theLexicalHandler,
const XalanDOMString& /* theIdentifier */)
{
XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader());
theReader->setFeature(
validationString,
m_xercesParserLiaison.getUseValidation());
theReader->setContentHandler(&theContentHandler);
theReader->setDTDHandler(theDTDHandler);
theReader->setErrorHandler(&m_xercesParserLiaison);
theReader->setLexicalHandler(theLexicalHandler);
EntityResolver* const theResolver = getEntityResolver();
if (theResolver != 0)
{
theReader->setEntityResolver(theResolver);
}
theReader->parse(theInputSource);
}
bool
XalanSourceTreeParserLiaison::getIncludeIgnorableWhitespace() const
{
return m_xercesParserLiaison.getIncludeIgnorableWhitespace();
}
void
XalanSourceTreeParserLiaison::setIncludeIgnorableWhitespace(bool include)
{
m_xercesParserLiaison.setIncludeIgnorableWhitespace(include);
}
ErrorHandler*
XalanSourceTreeParserLiaison::getErrorHandler()
{
return m_xercesParserLiaison.getErrorHandler();
}
const ErrorHandler*
XalanSourceTreeParserLiaison::getErrorHandler() const
{
return m_xercesParserLiaison.getErrorHandler();
}
void
XalanSourceTreeParserLiaison::setErrorHandler(ErrorHandler* handler)
{
m_xercesParserLiaison.setErrorHandler(handler);
}
bool
XalanSourceTreeParserLiaison::getDoNamespaces() const
{
return m_xercesParserLiaison.getDoNamespaces();
}
void
XalanSourceTreeParserLiaison::setDoNamespaces(bool newState)
{
m_xercesParserLiaison.setDoNamespaces(newState);
}
bool
XalanSourceTreeParserLiaison::getExitOnFirstFatalError() const
{
return m_xercesParserLiaison.getExitOnFirstFatalError();
}
void
XalanSourceTreeParserLiaison::setExitOnFirstFatalError(bool newState)
{
m_xercesParserLiaison.setExitOnFirstFatalError(newState);
}
EntityResolver*
XalanSourceTreeParserLiaison::getEntityResolver()
{
return m_xercesParserLiaison.getEntityResolver();
}
void
XalanSourceTreeParserLiaison::setEntityResolver(EntityResolver* resolver)
{
m_xercesParserLiaison.setEntityResolver(resolver);
}
XalanSourceTreeDocument*
XalanSourceTreeParserLiaison::mapDocument(const XalanDocument* theDocument) const
{
DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
if (i != m_documentMap.end())
{
return (*i).second;
}
else
{
i = m_persistentDocumentMap.find(theDocument);
if (i != m_persistentDocumentMap.end())
{
return (*i).second;
}
else
{
return 0;
}
}
}
XalanSourceTreeDocument*
XalanSourceTreeParserLiaison::createXalanSourceTreeDocument()
{
XalanSourceTreeDocument* const theNewDocument =
new XalanSourceTreeDocument(m_documentNumber++, m_poolAllText);
m_documentMap[theNewDocument] = theNewDocument;
return theNewDocument;
}
bool
XalanSourceTreeParserLiaison::setPersistent(XalanSourceTreeDocument* theDocument)
{
const DocumentMapType::iterator i =
m_documentMap.find(theDocument);
if (i != m_documentMap.end())
{
return false;
}
else
{
m_persistentDocumentMap[(*i).first] = (*i).second;
m_documentMap.erase(i);
return true;
}
}
bool
XalanSourceTreeParserLiaison::unsetPersistent(XalanSourceTreeDocument* theDocument)
{
const DocumentMapType::iterator i =
m_persistentDocumentMap.find(theDocument);
if (i != m_persistentDocumentMap.end())
{
return false;
}
else
{
m_documentMap[(*i).first] = (*i).second;
m_persistentDocumentMap.erase(i);
return true;
}
}
<commit_msg>Use ErrorHandler if available. Fixes bug 3886.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file.
#include "XalanSourceTreeParserLiaison.hpp"
#include <algorithm>
#include <sax2/XMLReaderFactory.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
#include "XalanSourceTreeContentHandler.hpp"
#include "XalanSourceTreeDOMSupport.hpp"
#include "XalanSourceTreeDocument.hpp"
// http://xml.org/sax/features/validation
const XalanDOMChar XalanSourceTreeParserLiaison::validationString[] = {
XalanUnicode::charLetter_h,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_p,
XalanUnicode::charColon,
XalanUnicode::charSolidus,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_x,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_l,
XalanUnicode::charFullStop,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_g,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_x,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_f,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_s,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_v,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_d,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
0
};
XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison(XalanSourceTreeDOMSupport& /* theSupport */) :
m_documentNumber(0),
m_xercesParserLiaison(),
m_documentMap(),
m_persistentDocumentMap(),
m_poolAllText(true)
{
}
XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison() :
m_xercesParserLiaison(),
m_documentMap(),
m_persistentDocumentMap(),
m_poolAllText(true)
{
}
XalanSourceTreeParserLiaison::~XalanSourceTreeParserLiaison()
{
reset();
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any persistent documents.
for_each(m_persistentDocumentMap.begin(),
m_persistentDocumentMap.end(),
makeMapValueDeleteFunctor(m_persistentDocumentMap));
m_persistentDocumentMap.clear();
}
void
XalanSourceTreeParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any documents.
for_each(m_documentMap.begin(),
m_documentMap.end(),
makeMapValueDeleteFunctor(m_documentMap));
m_documentMap.clear();
m_xercesParserLiaison.reset();
}
ExecutionContext*
XalanSourceTreeParserLiaison::getExecutionContext() const
{
return m_xercesParserLiaison.getExecutionContext();
}
void
XalanSourceTreeParserLiaison::setExecutionContext(ExecutionContext& theContext)
{
m_xercesParserLiaison.setExecutionContext(theContext);
}
void
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& inputSource,
DocumentHandler& handler,
const XalanDOMString& identifier)
{
m_xercesParserLiaison.parseXMLStream(inputSource, handler, identifier);
}
XalanDocument*
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& inputSource,
const XalanDOMString& /* identifier */)
{
XalanSourceTreeContentHandler theContentHandler(createXalanSourceTreeDocument());
XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader());
theReader->setFeature(
validationString,
m_xercesParserLiaison.getUseValidation());
theReader->setContentHandler(&theContentHandler);
theReader->setDTDHandler(&theContentHandler);
ErrorHandler* const theHandler = getErrorHandler();
if (theHandler == 0)
{
theReader->setErrorHandler(&m_xercesParserLiaison);
}
else
{
theReader->setErrorHandler(theHandler);
}
theReader->setLexicalHandler(&theContentHandler);
theReader->setEntityResolver(getEntityResolver());
theReader->parse(inputSource);
return theContentHandler.getDocument();
}
XalanDocument*
XalanSourceTreeParserLiaison::createDocument()
{
return createXalanSourceTreeDocument();
}
XalanDocument*
XalanSourceTreeParserLiaison::createDOMFactory()
{
return m_xercesParserLiaison.createDocument();
}
void
XalanSourceTreeParserLiaison::destroyDocument(XalanDocument* theDocument)
{
if (mapDocument(theDocument) != 0)
{
m_documentMap.erase(theDocument);
delete theDocument;
}
}
unsigned long
XalanSourceTreeParserLiaison::getDocumentNumber()
{
return m_documentNumber++;
}
int
XalanSourceTreeParserLiaison::getIndent() const
{
return m_xercesParserLiaison.getIndent();
}
void
XalanSourceTreeParserLiaison::setIndent(int i)
{
m_xercesParserLiaison.setIndent(i);
}
bool
XalanSourceTreeParserLiaison::getUseValidation() const
{
return m_xercesParserLiaison.getUseValidation();
}
void
XalanSourceTreeParserLiaison::setUseValidation(bool b)
{
m_xercesParserLiaison.setUseValidation(b);
}
const XalanDOMString
XalanSourceTreeParserLiaison::getParserDescription() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("XalanSourceTree"));
}
void
XalanSourceTreeParserLiaison::parseXMLStream(
const InputSource& theInputSource,
ContentHandler& theContentHandler,
DTDHandler* theDTDHandler,
LexicalHandler* theLexicalHandler,
const XalanDOMString& /* theIdentifier */)
{
XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader());
theReader->setFeature(
validationString,
m_xercesParserLiaison.getUseValidation());
theReader->setContentHandler(&theContentHandler);
theReader->setDTDHandler(theDTDHandler);
ErrorHandler* const theHandler = getErrorHandler();
if (theHandler == 0)
{
theReader->setErrorHandler(&m_xercesParserLiaison);
}
else
{
theReader->setErrorHandler(theHandler);
}
theReader->setLexicalHandler(theLexicalHandler);
EntityResolver* const theResolver = getEntityResolver();
if (theResolver != 0)
{
theReader->setEntityResolver(theResolver);
}
theReader->parse(theInputSource);
}
bool
XalanSourceTreeParserLiaison::getIncludeIgnorableWhitespace() const
{
return m_xercesParserLiaison.getIncludeIgnorableWhitespace();
}
void
XalanSourceTreeParserLiaison::setIncludeIgnorableWhitespace(bool include)
{
m_xercesParserLiaison.setIncludeIgnorableWhitespace(include);
}
ErrorHandler*
XalanSourceTreeParserLiaison::getErrorHandler()
{
return m_xercesParserLiaison.getErrorHandler();
}
const ErrorHandler*
XalanSourceTreeParserLiaison::getErrorHandler() const
{
return m_xercesParserLiaison.getErrorHandler();
}
void
XalanSourceTreeParserLiaison::setErrorHandler(ErrorHandler* handler)
{
m_xercesParserLiaison.setErrorHandler(handler);
}
bool
XalanSourceTreeParserLiaison::getDoNamespaces() const
{
return m_xercesParserLiaison.getDoNamespaces();
}
void
XalanSourceTreeParserLiaison::setDoNamespaces(bool newState)
{
m_xercesParserLiaison.setDoNamespaces(newState);
}
bool
XalanSourceTreeParserLiaison::getExitOnFirstFatalError() const
{
return m_xercesParserLiaison.getExitOnFirstFatalError();
}
void
XalanSourceTreeParserLiaison::setExitOnFirstFatalError(bool newState)
{
m_xercesParserLiaison.setExitOnFirstFatalError(newState);
}
EntityResolver*
XalanSourceTreeParserLiaison::getEntityResolver()
{
return m_xercesParserLiaison.getEntityResolver();
}
void
XalanSourceTreeParserLiaison::setEntityResolver(EntityResolver* resolver)
{
m_xercesParserLiaison.setEntityResolver(resolver);
}
XalanSourceTreeDocument*
XalanSourceTreeParserLiaison::mapDocument(const XalanDocument* theDocument) const
{
DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
if (i != m_documentMap.end())
{
return (*i).second;
}
else
{
i = m_persistentDocumentMap.find(theDocument);
if (i != m_persistentDocumentMap.end())
{
return (*i).second;
}
else
{
return 0;
}
}
}
XalanSourceTreeDocument*
XalanSourceTreeParserLiaison::createXalanSourceTreeDocument()
{
XalanSourceTreeDocument* const theNewDocument =
new XalanSourceTreeDocument(m_documentNumber++, m_poolAllText);
m_documentMap[theNewDocument] = theNewDocument;
return theNewDocument;
}
bool
XalanSourceTreeParserLiaison::setPersistent(XalanSourceTreeDocument* theDocument)
{
const DocumentMapType::iterator i =
m_documentMap.find(theDocument);
if (i != m_documentMap.end())
{
return false;
}
else
{
m_persistentDocumentMap[(*i).first] = (*i).second;
m_documentMap.erase(i);
return true;
}
}
bool
XalanSourceTreeParserLiaison::unsetPersistent(XalanSourceTreeDocument* theDocument)
{
const DocumentMapType::iterator i =
m_persistentDocumentMap.find(theDocument);
if (i != m_persistentDocumentMap.end())
{
return false;
}
else
{
m_documentMap[(*i).first] = (*i).second;
m_persistentDocumentMap.erase(i);
return true;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2013, Devin Matthews
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL DEVIN MATTHEWS 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 "ccsd.hpp"
using namespace std;
using namespace aquarius::op;
using namespace aquarius::cc;
using namespace aquarius::input;
using namespace aquarius::tensor;
using namespace aquarius::task;
using namespace aquarius::time;
template <typename U>
CCSD<U>::CCSD(const std::string& name, const Config& config)
: Iterative("ccsd", name, config), diis(config.get("diis"))
{
vector<Requirement> reqs;
reqs.push_back(Requirement("moints", "H"));
addProduct(Product("double", "mp2", reqs));
addProduct(Product("double", "energy", reqs));
addProduct(Product("double", "convergence", reqs));
addProduct(Product("double", "S2", reqs));
addProduct(Product("double", "multiplicity", reqs));
addProduct(Product("ccsd.T", "T", reqs));
addProduct(Product("ccsd.Hbar", "Hbar", reqs));
}
template <typename U>
void CCSD<U>::run(TaskDAG& dag, const Arena& arena)
{
const TwoElectronOperator<U>& H = get<TwoElectronOperator<U> >("H");
const Space& occ = H.occ;
const Space& vrt = H.vrt;
put("T", new ExcitationOperator<U,2>(arena, occ, vrt));
puttmp("Z", new ExcitationOperator<U,2>(arena, occ, vrt));
puttmp("D", new Denominator<U>(H));
puttmp("W", new TwoElectronOperator<U>(const_cast<TwoElectronOperator<U>&>(H),
TwoElectronOperator<U>::AB|
TwoElectronOperator<U>::IJ|
TwoElectronOperator<U>::IA|
TwoElectronOperator<U>::IJKL|
TwoElectronOperator<U>::IJAK|
TwoElectronOperator<U>::AIJK|
TwoElectronOperator<U>::AIBJ));
ExcitationOperator<U,2>& T = get<ExcitationOperator<U,2> >("T");
Denominator<U>& D = gettmp<Denominator<U> >("D");
ExcitationOperator<U,2>& Z = gettmp<ExcitationOperator<U,2> >("Z");
Z(0) = (U)0.0;
T(0) = (U)0.0;
T(1) = H.getAI();
T(2) = H.getABIJ();
T.weight(D);
SpinorbitalTensor<U> Tau(T(2));
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
energy = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
conv = T.norm(00);
Logger::log(arena) << "MP2AA = " << setprecision(15) <<
0.25*real(scalar(H.getABIJ()(vec(2,0),vec(0,2))*T(2)(vec(2,0),vec(0,2)))) << endl;
Logger::log(arena) << "MP2AB = " << setprecision(15) <<
real(scalar(H.getABIJ()(vec(1,0),vec(0,1))*T(2)(vec(1,0),vec(0,1)))) << endl;
Logger::log(arena) << "MP2 energy = " << setprecision(15) << energy << endl;
put("mp2", new Scalar(arena, energy));
Iterative::run(dag, arena);
put("energy", new Scalar(arena, energy));
put("convergence", new Scalar(arena, conv));
/*
if (isUsed("S2") || isUsed("multiplicity"))
{
double s2 = getProjectedS2(occ, vrt, T(1), T(2));
double mult = sqrt(4*s2+1);
put("S2", new Scalar(arena, s2));
put("multiplicity", new Scalar(arena, mult));
}
*/
if (isUsed("Hbar"))
{
put("Hbar", new STTwoElectronOperator<U,2>(H, T, true));
}
}
template <typename U>
void CCSD<U>::iterate()
{
const TwoElectronOperator<U>& H = get<TwoElectronOperator<U> >("H");
ExcitationOperator<U,2>& T = get<ExcitationOperator<U,2> >("T");
Denominator<U>& D = gettmp<Denominator<U> >("D");
ExcitationOperator<U,2>& Z = gettmp<ExcitationOperator<U,2> >("Z");
TwoElectronOperator<U>& W = gettmp<TwoElectronOperator<U> >("W");
STExcitationOperator<U,2>::transform(H, T, Z, W);
Z.weight(D);
T += Z;
SpinorbitalTensor<U> Tau(T(2));
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
energy = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
conv = Z.norm(00);
diis.extrapolate(T, Z);
}
/*
template <typename U>
double CCSD<U>::getProjectedS2(const MOSpace<U>& occ, const MOSpace<U>& vrt,
const SpinorbitalTensor<U>& T1,
const SpinorbitalTensor<U>& T2)
{
const Arena& arena = occ.arena;
int N = occ.nao;
int nI = occ.nalpha;
int ni = occ.nbeta;
int nA = vrt.nalpha;
int na = vrt.nbeta;
vector<int> shapeNN = vec(NS,NS);
vector<int> shapeNNNN = vec(NS,NS,NS,NS);
vector<int> sizeAI = vec(nA,nI);
vector<int> sizeAi = vec(nA,ni);
vector<int> sizeaI = vec(na,nI);
vector<int> sizeai = vec(na,ni);
vector<int> sizeIi = vec(nI,ni);
vector<int> sizeIn = vec(nI,N);
vector<int> sizein = vec(ni,N);
vector<int> sizeAaIi = vec(nA,na,nI,ni);
const CTFTensor<U>& CA = vrt.Calpha;
const CTFTensor<U>& Ca = vrt.Cbeta;
const CTFTensor<U>& CI = occ.Calpha;
const CTFTensor<U>& Ci = occ.Cbeta;
//TODO
CTFTensor<U> S(arena, 2, vec(N,N), shapeNN, true);
CTFTensor<U> DAI(arena, 2, sizeAI, shapeNN, false);
CTFTensor<U> DAi(arena, 2, sizeAi, shapeNN, false);
CTFTensor<U> DaI(arena, 2, sizeaI, shapeNN, false);
CTFTensor<U> Dai(arena, 2, sizeai, shapeNN, false);
CTFTensor<U> DIj(arena, 2, sizeIi, shapeNN, false);
CTFTensor<U> DAbIj(arena, 4, sizeAaIi, shapeNNNN, false);
CTFTensor<U> tmp1(arena, 2, sizeIn, shapeNN, false);
CTFTensor<U> tmp2(arena, 2, sizein, shapeNN, false);
tmp1["Iq"] = CI["pI"]*S["pq"];
DIj["Ij"] = tmp1["Iq"]*Ci["qj"];
DaI["aI"] = tmp1["Iq"]*Ca["qa"];
tmp2["iq"] = Ci["pi"]*S["pq"];
DAi["Ai"] = tmp2["iq"]*CA["qA"];
DAI["AI"] = DAi["Aj"]*DIj["Ij"];
Dai["ai"] = DaI["aJ"]*DIj["Ji"];
DAbIj["AbIj"] = DAi["Aj"]*DaI["bI"];
const CTFTensor<U>& T1A = T1(1,0,0,1);
const CTFTensor<U>& T1B = T1(0,0,0,0);
CTFTensor<U> TauAB(T2(1,0,0,1));
TauAB["AbIj"] += T1A["AI"]*T1B["bj"];
U S2 = (U)0;
U S2T11 = -scalar(DAI*T1A);
U S2T12 = -scalar(Dai*T1B);
U S2T2 = -scalar(DAbIj*TauAB);
return abs(S2+S2T11+S2T12+S2T2);
}
*/
INSTANTIATE_SPECIALIZATIONS(CCSD);
REGISTER_TASK(CCSD<double>,"ccsd");
<commit_msg> Remove testing code<commit_after>/* Copyright (c) 2013, Devin Matthews
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL DEVIN MATTHEWS 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 "ccsd.hpp"
using namespace std;
using namespace aquarius::op;
using namespace aquarius::cc;
using namespace aquarius::input;
using namespace aquarius::tensor;
using namespace aquarius::task;
using namespace aquarius::time;
template <typename U>
CCSD<U>::CCSD(const std::string& name, const Config& config)
: Iterative("ccsd", name, config), diis(config.get("diis"))
{
vector<Requirement> reqs;
reqs.push_back(Requirement("moints", "H"));
addProduct(Product("double", "mp2", reqs));
addProduct(Product("double", "energy", reqs));
addProduct(Product("double", "convergence", reqs));
addProduct(Product("double", "S2", reqs));
addProduct(Product("double", "multiplicity", reqs));
addProduct(Product("ccsd.T", "T", reqs));
addProduct(Product("ccsd.Hbar", "Hbar", reqs));
}
template <typename U>
void CCSD<U>::run(TaskDAG& dag, const Arena& arena)
{
const TwoElectronOperator<U>& H = get<TwoElectronOperator<U> >("H");
const Space& occ = H.occ;
const Space& vrt = H.vrt;
put("T", new ExcitationOperator<U,2>(arena, occ, vrt));
puttmp("Z", new ExcitationOperator<U,2>(arena, occ, vrt));
puttmp("D", new Denominator<U>(H));
puttmp("W", new TwoElectronOperator<U>(const_cast<TwoElectronOperator<U>&>(H),
TwoElectronOperator<U>::AB|
TwoElectronOperator<U>::IJ|
TwoElectronOperator<U>::IA|
TwoElectronOperator<U>::IJKL|
TwoElectronOperator<U>::IJAK|
TwoElectronOperator<U>::AIJK|
TwoElectronOperator<U>::AIBJ));
ExcitationOperator<U,2>& T = get<ExcitationOperator<U,2> >("T");
Denominator<U>& D = gettmp<Denominator<U> >("D");
ExcitationOperator<U,2>& Z = gettmp<ExcitationOperator<U,2> >("Z");
Z(0) = (U)0.0;
T(0) = (U)0.0;
T(1) = H.getAI();
T(2) = H.getABIJ();
T.weight(D);
SpinorbitalTensor<U> Tau(T(2));
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
energy = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
conv = T.norm(00);
Logger::log(arena) << "MP2 energy = " << setprecision(15) << energy << endl;
put("mp2", new Scalar(arena, energy));
Iterative::run(dag, arena);
put("energy", new Scalar(arena, energy));
put("convergence", new Scalar(arena, conv));
/*
if (isUsed("S2") || isUsed("multiplicity"))
{
double s2 = getProjectedS2(occ, vrt, T(1), T(2));
double mult = sqrt(4*s2+1);
put("S2", new Scalar(arena, s2));
put("multiplicity", new Scalar(arena, mult));
}
*/
if (isUsed("Hbar"))
{
put("Hbar", new STTwoElectronOperator<U,2>(H, T, true));
}
}
template <typename U>
void CCSD<U>::iterate()
{
const TwoElectronOperator<U>& H = get<TwoElectronOperator<U> >("H");
ExcitationOperator<U,2>& T = get<ExcitationOperator<U,2> >("T");
Denominator<U>& D = gettmp<Denominator<U> >("D");
ExcitationOperator<U,2>& Z = gettmp<ExcitationOperator<U,2> >("Z");
TwoElectronOperator<U>& W = gettmp<TwoElectronOperator<U> >("W");
STExcitationOperator<U,2>::transform(H, T, Z, W);
Z.weight(D);
T += Z;
SpinorbitalTensor<U> Tau(T(2));
Tau["abij"] += 0.5*T(1)["ai"]*T(1)["bj"];
energy = real(scalar(H.getAI()*T(1))) + 0.25*real(scalar(H.getABIJ()*Tau));
conv = Z.norm(00);
diis.extrapolate(T, Z);
}
/*
template <typename U>
double CCSD<U>::getProjectedS2(const MOSpace<U>& occ, const MOSpace<U>& vrt,
const SpinorbitalTensor<U>& T1,
const SpinorbitalTensor<U>& T2)
{
const Arena& arena = occ.arena;
int N = occ.nao;
int nI = occ.nalpha;
int ni = occ.nbeta;
int nA = vrt.nalpha;
int na = vrt.nbeta;
vector<int> shapeNN = vec(NS,NS);
vector<int> shapeNNNN = vec(NS,NS,NS,NS);
vector<int> sizeAI = vec(nA,nI);
vector<int> sizeAi = vec(nA,ni);
vector<int> sizeaI = vec(na,nI);
vector<int> sizeai = vec(na,ni);
vector<int> sizeIi = vec(nI,ni);
vector<int> sizeIn = vec(nI,N);
vector<int> sizein = vec(ni,N);
vector<int> sizeAaIi = vec(nA,na,nI,ni);
const CTFTensor<U>& CA = vrt.Calpha;
const CTFTensor<U>& Ca = vrt.Cbeta;
const CTFTensor<U>& CI = occ.Calpha;
const CTFTensor<U>& Ci = occ.Cbeta;
//TODO
CTFTensor<U> S(arena, 2, vec(N,N), shapeNN, true);
CTFTensor<U> DAI(arena, 2, sizeAI, shapeNN, false);
CTFTensor<U> DAi(arena, 2, sizeAi, shapeNN, false);
CTFTensor<U> DaI(arena, 2, sizeaI, shapeNN, false);
CTFTensor<U> Dai(arena, 2, sizeai, shapeNN, false);
CTFTensor<U> DIj(arena, 2, sizeIi, shapeNN, false);
CTFTensor<U> DAbIj(arena, 4, sizeAaIi, shapeNNNN, false);
CTFTensor<U> tmp1(arena, 2, sizeIn, shapeNN, false);
CTFTensor<U> tmp2(arena, 2, sizein, shapeNN, false);
tmp1["Iq"] = CI["pI"]*S["pq"];
DIj["Ij"] = tmp1["Iq"]*Ci["qj"];
DaI["aI"] = tmp1["Iq"]*Ca["qa"];
tmp2["iq"] = Ci["pi"]*S["pq"];
DAi["Ai"] = tmp2["iq"]*CA["qA"];
DAI["AI"] = DAi["Aj"]*DIj["Ij"];
Dai["ai"] = DaI["aJ"]*DIj["Ji"];
DAbIj["AbIj"] = DAi["Aj"]*DaI["bI"];
const CTFTensor<U>& T1A = T1(1,0,0,1);
const CTFTensor<U>& T1B = T1(0,0,0,0);
CTFTensor<U> TauAB(T2(1,0,0,1));
TauAB["AbIj"] += T1A["AI"]*T1B["bj"];
U S2 = (U)0;
U S2T11 = -scalar(DAI*T1A);
U S2T12 = -scalar(Dai*T1B);
U S2T2 = -scalar(DAbIj*TauAB);
return abs(S2+S2T11+S2T12+S2T2);
}
*/
INSTANTIATE_SPECIALIZATIONS(CCSD);
REGISTER_TASK(CCSD<double>,"ccsd");
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkImageDecoder.h"
#ifdef SK_BUILD_FOR_WIN
// windows doesn't have roundf
inline float roundf(float x) { return (x-floor(x))>0.5 ? ceil(x) : floor(x); }
#endif
#ifdef SK_DEBUG
static void make_rgn(SkRegion* rgn, int left, int top, int right, int bottom,
size_t count, int32_t runs[]) {
SkIRect r;
r.set(left, top, right, bottom);
rgn->debugSetRuns(runs, count);
SkASSERT(rgn->getBounds() == r);
}
static void test_union_bug_1505668(SkRegion* ra, SkRegion* rb, SkRegion* rc) {
static int32_t dataA[] = {
0x00000001, 0x000001dd,
0x00000001, 0x0000000c, 0x0000000d, 0x00000025,
0x7fffffff, 0x000001de, 0x00000001, 0x00000025,
0x7fffffff, 0x000004b3, 0x00000001, 0x00000026,
0x7fffffff, 0x000004b4, 0x0000000c, 0x00000026,
0x7fffffff, 0x00000579, 0x00000000, 0x0000013a,
0x7fffffff, 0x000005d8, 0x00000000, 0x0000013b,
0x7fffffff, 0x7fffffff
};
make_rgn(ra, 0, 1, 315, 1496, SK_ARRAY_COUNT(dataA), dataA);
static int32_t dataB[] = {
0x000000b6, 0x000000c4,
0x000000a1, 0x000000f0, 0x7fffffff, 0x000000d6,
0x7fffffff, 0x000000e4, 0x00000070, 0x00000079,
0x000000a1, 0x000000b0, 0x7fffffff, 0x000000e6,
0x7fffffff, 0x000000f4, 0x00000070, 0x00000079,
0x000000a1, 0x000000b0, 0x7fffffff, 0x000000f6,
0x7fffffff, 0x00000104, 0x000000a1, 0x000000b0,
0x7fffffff, 0x7fffffff
};
make_rgn(rb, 112, 182, 240, 260, SK_ARRAY_COUNT(dataB), dataB);
rc->op(*ra, *rb, SkRegion::kUnion_Op);
}
#endif
static void scale_rect(SkIRect* dst, const SkIRect& src, float scale) {
dst->fLeft = (int)::roundf(src.fLeft * scale);
dst->fTop = (int)::roundf(src.fTop * scale);
dst->fRight = (int)::roundf(src.fRight * scale);
dst->fBottom = (int)::roundf(src.fBottom * scale);
}
static void scale_rgn(SkRegion* dst, const SkRegion& src, float scale) {
SkRegion tmp;
SkRegion::Iterator iter(src);
for (; !iter.done(); iter.next()) {
SkIRect r;
scale_rect(&r, iter.rect(), scale);
tmp.op(r, SkRegion::kUnion_Op);
}
dst->swap(tmp);
}
static void paint_rgn(SkCanvas* canvas, const SkRegion& rgn,
const SkPaint& paint) {
SkRegion scaled;
scale_rgn(&scaled, rgn, 0.5f);
SkRegion::Iterator iter(rgn);
for (; !iter.done(); iter.next())
{
SkRect r;
r.set(iter.rect());
canvas->drawRect(r, paint);
}
}
class RegionView : public SampleView {
public:
RegionView() {
fBase.set(100, 100, 150, 150);
fRect = fBase;
fRect.inset(5, 5);
fRect.offset(25, 25);
this->setBGColor(0xFFDDDDDD);
}
void build_rgn(SkRegion* rgn, SkRegion::Op op) {
rgn->setRect(fBase);
SkIRect r = fBase;
r.offset(75, 20);
rgn->op(r, SkRegion::kUnion_Op);
rgn->op(fRect, op);
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Regions");
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawOrig(SkCanvas* canvas, bool bg) {
SkRect r;
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
if (bg)
paint.setColor(0xFFBBBBBB);
r.set(fBase);
canvas->drawRect(r, paint);
r.set(fRect);
canvas->drawRect(r, paint);
}
void drawRgnOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {
SkRegion rgn;
this->build_rgn(&rgn, op);
{
SkRegion tmp, tmp2(rgn);
tmp = tmp2;
tmp.translate(5, -3);
{
char buffer[1000];
size_t size = tmp.flatten(NULL);
SkASSERT(size <= sizeof(buffer));
size_t size2 = tmp.flatten(buffer);
SkASSERT(size == size2);
SkRegion tmp3;
size2 = tmp3.unflatten(buffer);
SkASSERT(size == size2);
SkASSERT(tmp3 == tmp);
}
rgn.translate(20, 30, &tmp);
SkASSERT(rgn.isEmpty() || tmp != rgn);
tmp.translate(-20, -30);
SkASSERT(tmp == rgn);
}
this->drawOrig(canvas, true);
SkPaint paint;
paint.setColor((color & ~(0xFF << 24)) | (0x44 << 24));
paint_rgn(canvas, rgn, paint);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(color);
paint_rgn(canvas, rgn, paint);
}
void drawPathOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {
SkRegion rgn;
SkPath path;
this->build_rgn(&rgn, op);
rgn.getBoundaryPath(&path);
this->drawOrig(canvas, true);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setColor((color & ~(0xFF << 24)) | (0x44 << 24));
canvas->drawPath(path, paint);
paint.setColor(color);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawPath(path, paint);
}
virtual void onDrawContent(SkCanvas* canvas) {
#ifdef SK_DEBUG
if (true) {
SkRegion a, b, c;
test_union_bug_1505668(&a, &b, &c);
if (false) { // draw the result of the test
SkPaint paint;
canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
paint.setColor(SK_ColorRED);
paint_rgn(canvas, a, paint);
paint.setColor(0x800000FF);
paint_rgn(canvas, b, paint);
paint.setColor(SK_ColorBLACK);
paint.setStyle(SkPaint::kStroke_Style);
// paint_rgn(canvas, c, paint);
return;
}
}
#endif
static const struct {
SkColor fColor;
const char* fName;
SkRegion::Op fOp;
} gOps[] = {
{ SK_ColorBLACK, "Difference", SkRegion::kDifference_Op },
{ SK_ColorRED, "Intersect", SkRegion::kIntersect_Op },
{ 0xFF008800, "Union", SkRegion::kUnion_Op },
{ SK_ColorBLUE, "XOR", SkRegion::kXOR_Op }
};
SkPaint textPaint;
textPaint.setAntiAlias(true);
textPaint.setTextSize(SK_Scalar1*24);
this->drawOrig(canvas, false);
canvas->save();
canvas->translate(SkIntToScalar(200), 0);
this->drawRgnOped(canvas, SkRegion::kUnion_Op, SK_ColorBLACK);
canvas->restore();
canvas->translate(0, SkIntToScalar(200));
for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); op++) {
canvas->drawText(gOps[op].fName, strlen(gOps[op].fName), SkIntToScalar(75), SkIntToScalar(50), textPaint);
this->drawRgnOped(canvas, gOps[op].fOp, gOps[op].fColor);
canvas->save();
canvas->translate(0, SkIntToScalar(200));
this->drawPathOped(canvas, gOps[op].fOp, gOps[op].fColor);
canvas->restore();
canvas->translate(SkIntToScalar(200), 0);
}
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
return fRect.contains(SkScalarRound(x), SkScalarRound(y)) ? new Click(this) : NULL;
}
virtual bool onClick(Click* click) {
fRect.offset(click->fICurr.fX - click->fIPrev.fX,
click->fICurr.fY - click->fIPrev.fY);
this->inval(NULL);
return true;
}
private:
SkIRect fBase, fRect;
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new RegionView; }
static SkViewRegister reg(MyFactory);
<commit_msg>show contains and intersects predicates in sample<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkImageDecoder.h"
static void test_strokerect(SkCanvas* canvas) {
int width = 100;
int height = 100;
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kA8_Config, width*2, height*2);
bitmap.allocPixels();
bitmap.eraseColor(0);
SkScalar dx = 20;
SkScalar dy = 20;
SkPath path;
path.addRect(0.0f, 0.0f, width, height, SkPath::kCW_Direction);
SkRect r = SkRect::MakeWH(width, height);
SkCanvas c(bitmap);
c.translate(dx, dy);
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(1);
// use the rect
c.clear(0);
c.drawRect(r, paint);
canvas->drawBitmap(bitmap, 0, 0, NULL);
// use the path
c.clear(0);
c.drawPath(path, paint);
canvas->drawBitmap(bitmap, 2*width, 0, NULL);
}
static void drawFadingText(SkCanvas* canvas,
const char* text, size_t len, SkScalar x, SkScalar y,
const SkPaint& paint) {
// Need a bounds for the text
SkRect bounds;
SkPaint::FontMetrics fm;
paint.getFontMetrics(&fm);
bounds.set(x, y + fm.fTop, x + paint.measureText(text, len), y + fm.fBottom);
// may need to outset bounds a little, to account for hinting and/or
// antialiasing
bounds.inset(-SkIntToScalar(2), -SkIntToScalar(2));
canvas->saveLayer(&bounds, NULL);
canvas->drawText(text, len, x, y, paint);
const SkPoint pts[] = {
{ bounds.fLeft, y },
{ bounds.fRight, y }
};
const SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, 0 };
// pos[1] value is where we start to fade, relative to the width
// of our pts[] array.
const SkScalar pos[] = { 0, SkFloatToScalar(0.9), SK_Scalar1 };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos, 3,
SkShader::kClamp_TileMode);
SkPaint p;
p.setShader(s)->unref();
p.setXfermodeMode(SkXfermode::kDstIn_Mode);
canvas->drawRect(bounds, p);
canvas->restore();
}
static void test_text(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(20);
const char* str = "Hamburgefons";
size_t len = strlen(str);
SkScalar x = 20;
SkScalar y = 20;
canvas->drawText(str, len, x, y, paint);
y += 20;
const SkPoint pts[] = { { x, y }, { x + paint.measureText(str, len), y } };
const SkColor colors[] = { SK_ColorBLACK, SK_ColorBLACK, 0 };
const SkScalar pos[] = { 0, 0.9f, 1 };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, pos,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
paint.setShader(s)->unref();
canvas->drawText(str, len, x, y, paint);
y += 20;
paint.setShader(NULL);
drawFadingText(canvas, str, len, x, y, paint);
}
#ifdef SK_BUILD_FOR_WIN
// windows doesn't have roundf
inline float roundf(float x) { return (x-floor(x))>0.5 ? ceil(x) : floor(x); }
#endif
#ifdef SK_DEBUG
static void make_rgn(SkRegion* rgn, int left, int top, int right, int bottom,
size_t count, int32_t runs[]) {
SkIRect r;
r.set(left, top, right, bottom);
rgn->debugSetRuns(runs, count);
SkASSERT(rgn->getBounds() == r);
}
static void test_union_bug_1505668(SkRegion* ra, SkRegion* rb, SkRegion* rc) {
static int32_t dataA[] = {
0x00000001,
0x000001dd, 2, 0x00000001, 0x0000000c, 0x0000000d, 0x00000025, 0x7fffffff,
0x000001de, 1, 0x00000001, 0x00000025, 0x7fffffff,
0x000004b3, 1, 0x00000001, 0x00000026, 0x7fffffff,
0x000004b4, 1, 0x0000000c, 0x00000026, 0x7fffffff,
0x00000579, 1, 0x00000000, 0x0000013a, 0x7fffffff,
0x000005d8, 1, 0x00000000, 0x0000013b, 0x7fffffff,
0x7fffffff
};
make_rgn(ra, 0, 1, 315, 1496, SK_ARRAY_COUNT(dataA), dataA);
static int32_t dataB[] = {
0x000000b6,
0x000000c4, 1, 0x000000a1, 0x000000f0, 0x7fffffff,
0x000000d6, 0, 0x7fffffff,
0x000000e4, 2, 0x00000070, 0x00000079, 0x000000a1, 0x000000b0, 0x7fffffff,
0x000000e6, 0, 0x7fffffff,
0x000000f4, 2, 0x00000070, 0x00000079, 0x000000a1, 0x000000b0, 0x7fffffff,
0x000000f6, 0, 0x7fffffff,
0x00000104, 1, 0x000000a1, 0x000000b0, 0x7fffffff,
0x7fffffff
};
make_rgn(rb, 112, 182, 240, 260, SK_ARRAY_COUNT(dataB), dataB);
rc->op(*ra, *rb, SkRegion::kUnion_Op);
}
#endif
static void scale_rect(SkIRect* dst, const SkIRect& src, float scale) {
dst->fLeft = (int)::roundf(src.fLeft * scale);
dst->fTop = (int)::roundf(src.fTop * scale);
dst->fRight = (int)::roundf(src.fRight * scale);
dst->fBottom = (int)::roundf(src.fBottom * scale);
}
static void scale_rgn(SkRegion* dst, const SkRegion& src, float scale) {
SkRegion tmp;
SkRegion::Iterator iter(src);
for (; !iter.done(); iter.next()) {
SkIRect r;
scale_rect(&r, iter.rect(), scale);
tmp.op(r, SkRegion::kUnion_Op);
}
dst->swap(tmp);
}
static void paint_rgn(SkCanvas* canvas, const SkRegion& rgn,
const SkPaint& paint) {
SkRegion scaled;
scale_rgn(&scaled, rgn, 0.5f);
SkRegion::Iterator iter(rgn);
for (; !iter.done(); iter.next())
{
SkRect r;
r.set(iter.rect());
canvas->drawRect(r, paint);
}
}
class RegionView : public SampleView {
public:
RegionView() {
fBase.set(100, 100, 150, 150);
fRect = fBase;
fRect.inset(5, 5);
fRect.offset(25, 25);
this->setBGColor(0xFFDDDDDD);
}
void build_base_rgn(SkRegion* rgn) {
rgn->setRect(fBase);
SkIRect r = fBase;
r.offset(75, 20);
rgn->op(r, SkRegion::kUnion_Op);
}
void build_rgn(SkRegion* rgn, SkRegion::Op op) {
build_base_rgn(rgn);
rgn->op(fRect, op);
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "Regions");
return true;
}
return this->INHERITED::onQuery(evt);
}
static void drawstr(SkCanvas* canvas, const char text[], const SkPoint& loc,
bool hilite) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setTextSize(SkIntToScalar(20));
paint.setColor(hilite ? SK_ColorRED : 0x40FF0000);
canvas->drawText(text, strlen(text), loc.fX, loc.fY, paint);
}
void drawPredicates(SkCanvas* canvas, const SkPoint pts[]) {
SkRegion rgn;
build_base_rgn(&rgn);
drawstr(canvas, "Intersects", pts[0], rgn.intersects(fRect));
drawstr(canvas, "Contains", pts[1], rgn.contains(fRect));
}
void drawOrig(SkCanvas* canvas, bool bg) {
SkRect r;
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
if (bg)
paint.setColor(0xFFBBBBBB);
SkRegion rgn;
build_base_rgn(&rgn);
paint_rgn(canvas, rgn, paint);
r.set(fRect);
canvas->drawRect(r, paint);
}
void drawRgnOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {
SkRegion rgn;
this->build_rgn(&rgn, op);
{
SkRegion tmp, tmp2(rgn);
tmp = tmp2;
tmp.translate(5, -3);
{
char buffer[1000];
size_t size = tmp.flatten(NULL);
SkASSERT(size <= sizeof(buffer));
size_t size2 = tmp.flatten(buffer);
SkASSERT(size == size2);
SkRegion tmp3;
size2 = tmp3.unflatten(buffer);
SkASSERT(size == size2);
SkASSERT(tmp3 == tmp);
}
rgn.translate(20, 30, &tmp);
SkASSERT(rgn.isEmpty() || tmp != rgn);
tmp.translate(-20, -30);
SkASSERT(tmp == rgn);
}
this->drawOrig(canvas, true);
SkPaint paint;
paint.setColor((color & ~(0xFF << 24)) | (0x44 << 24));
paint_rgn(canvas, rgn, paint);
paint.setStyle(SkPaint::kStroke_Style);
paint.setColor(color);
paint_rgn(canvas, rgn, paint);
}
void drawPathOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {
SkRegion rgn;
SkPath path;
this->build_rgn(&rgn, op);
rgn.getBoundaryPath(&path);
this->drawOrig(canvas, true);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setColor((color & ~(0xFF << 24)) | (0x44 << 24));
canvas->drawPath(path, paint);
paint.setColor(color);
paint.setStyle(SkPaint::kStroke_Style);
canvas->drawPath(path, paint);
}
virtual void onDrawContent(SkCanvas* canvas) {
// test_strokerect(canvas); return;
// test_text(canvas); return;
#ifdef SK_DEBUG
if (true) {
SkRegion a, b, c;
test_union_bug_1505668(&a, &b, &c);
if (false) { // draw the result of the test
SkPaint paint;
canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
paint.setColor(SK_ColorRED);
paint_rgn(canvas, a, paint);
paint.setColor(0x800000FF);
paint_rgn(canvas, b, paint);
paint.setColor(SK_ColorBLACK);
paint.setStyle(SkPaint::kStroke_Style);
// paint_rgn(canvas, c, paint);
return;
}
}
#endif
const SkPoint origins[] = {
{ 30*SK_Scalar1, 50*SK_Scalar1 },
{ 150*SK_Scalar1, 50*SK_Scalar1 },
};
this->drawPredicates(canvas, origins);
static const struct {
SkColor fColor;
const char* fName;
SkRegion::Op fOp;
} gOps[] = {
{ SK_ColorBLACK, "Difference", SkRegion::kDifference_Op },
{ SK_ColorRED, "Intersect", SkRegion::kIntersect_Op },
{ 0xFF008800, "Union", SkRegion::kUnion_Op },
{ SK_ColorBLUE, "XOR", SkRegion::kXOR_Op }
};
SkPaint textPaint;
textPaint.setAntiAlias(true);
textPaint.setTextSize(SK_Scalar1*24);
this->drawOrig(canvas, false);
canvas->save();
canvas->translate(SkIntToScalar(200), 0);
this->drawRgnOped(canvas, SkRegion::kUnion_Op, SK_ColorBLACK);
canvas->restore();
canvas->translate(0, SkIntToScalar(200));
for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); op++) {
canvas->drawText(gOps[op].fName, strlen(gOps[op].fName), SkIntToScalar(75), SkIntToScalar(50), textPaint);
this->drawRgnOped(canvas, gOps[op].fOp, gOps[op].fColor);
canvas->save();
canvas->translate(0, SkIntToScalar(200));
this->drawPathOped(canvas, gOps[op].fOp, gOps[op].fColor);
canvas->restore();
canvas->translate(SkIntToScalar(200), 0);
}
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
return fRect.contains(SkScalarRound(x), SkScalarRound(y)) ? new Click(this) : NULL;
}
virtual bool onClick(Click* click) {
fRect.offset(click->fICurr.fX - click->fIPrev.fX,
click->fICurr.fY - click->fIPrev.fY);
this->inval(NULL);
return true;
}
private:
SkIRect fBase, fRect;
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new RegionView; }
static SkViewRegister reg(MyFactory);
<|endoftext|> |
<commit_before>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <SDL.h>
#include <SDL_opengl.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <timer.h>
#include <glcamera.h>
#include <glfunctions.h>
#include <glshader.h>
#include <glprogram.h>
#include <util.h>
#include <model.h>
#include <material.h>
//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
//Start our window
try {
Window::Init();
}
catch (const std::runtime_error &e){
std::cout << e.what() << std::endl;
}
Input::Init();
//Setup main window to read input
int w = 640, h = 480;
Window window("Main window", w, h);
//Time the loading
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::shared_ptr<Model> model = Util::LoadObj("../res/suzanne.obj");
std::cout << "Model load time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() / 1000.0f
<< std::endl;
//Setup program
GL::Program prog("../res/modelshader.v.glsl", "../res/texturemodel.f.glsl");
//This is a parallel to gluLookAt, see http://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml for
//information on what eye, center and up represent, provides enough info to figure out math/transformations
//needed to make a camera
//Create a camera slightly above the box looking down at it
GL::Camera camera(glm::vec3(0, 0, 1), glm::vec3(0, 0, -5), glm::vec3(0, 1, 0));
glm::mat4 proj = glm::perspective(60.0f, (float)w / (float)h, 0.1f, 100.0f);
//Setup the Uniform buffer object
GLuint uboIdx = GL::GetUniformBlockIndex(prog, "Lighting");
if (uboIdx == GL_INVALID_INDEX)
std::cout << "Invalid UBO Index" << std::endl;
GLint uboSize;
GL::GetActiveUniformBlockiv(prog, uboIdx, GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);
//Make a light @ origin
glm::vec4 lightPos(0.0f, 0.0f, 0.0f, 1.0f);
//TODO: Generic Buffers, templated based on type maybe?? Also need to be able to allocate
//arbitrary size buffer and write data to it instead of forced into passing vect/array/etc
GL::VertexBuffer ubo(lightPos, GL::BUFFER::UNIFORM);
GL::BindBufferBase(GL::BUFFER::UNIFORM, uboIdx, ubo);
uboIdx = GL::GetUniformBlockIndex(prog, "VP");
if (uboIdx == GL_INVALID_INDEX)
std::cout << "Invalid UBO Index" << std::endl;
GL::GetActiveUniformBlockiv(prog, uboIdx, GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);
if (uboSize != sizeof(glm::mat4) * 2)
std::cout << "ubo size isn't right!" << std::endl;
std::array<glm::mat4, 2> matVP = { camera.View(), proj };
GL::VertexBuffer matVPubo(matVP, GL::BUFFER::UNIFORM);
GL::BindBufferBase(GL::BUFFER::UNIFORM, uboIdx, matVPubo);
//Trying to figure out what's wrong with this on Nvidia
const char *names[] = { "v", "p" };
GLuint indices[2];
GL::GetUniformIndices(prog, 2, names, indices);
std::cout << "Indices: " << indices[0] << ", " << indices[1] << std::endl;
Util::CheckError("Post UBO setup");
//now query some info
GLint info[2];
//GL::GetActiveUniformsiv
model->UseProgram(prog);
model->Translate(glm::vec3(0, 0, -5));
//Track if model matrix was be updated
bool mUpdate = false;
//speed for moving things
float speed = 8.0f, rotateSpeed = 50.0f;
Timer delta;
delta.Start();
//For tracking if we want to quit
while (!Input::Quit()){
float dT = delta.Restart() / 1000.0f;
//Event Handling
Input::PollEvents();
if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
Input::Quit(true);
//Cube Controls------------------
//Cube rotation
if (Input::KeyDown(SDL_SCANCODE_D)){
model->Rotate(rotateSpeed * dT, glm::vec3(0, 1, 0));
}
if (Input::KeyDown(SDL_SCANCODE_A)){
model->Rotate(-rotateSpeed * dT, glm::vec3(0, 1, 0));
}
if (Input::KeyDown(SDL_SCANCODE_W)){
model->Rotate(-rotateSpeed * dT, glm::vec3(1, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_S)){
model->Rotate(rotateSpeed * dT, glm::vec3(1, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_Q)){
model->Rotate(rotateSpeed * dT, glm::vec3(0, 0, 1));
}
if (Input::KeyDown(SDL_SCANCODE_E)){
model->Rotate(-rotateSpeed * dT, glm::vec3(0, 0, 1));
}
//Cube translation
if (Input::KeyDown(SDL_SCANCODE_UP)){
model->Translate(glm::vec3(0, speed * dT, 0));
}
if (Input::KeyDown(SDL_SCANCODE_DOWN)){
model->Translate(glm::vec3(0, -speed * dT, 0));
}
if (Input::KeyDown(SDL_SCANCODE_LEFT)){
model->Translate(glm::vec3(-speed * dT, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_RIGHT)){
model->Translate(glm::vec3(speed * dT, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_Z)){
model->Translate(glm::vec3(0, 0, speed * dT));
}
if (Input::KeyDown(SDL_SCANCODE_X)){
model->Translate(glm::vec3(0, 0, -speed * dT));
}
//Camera strafe Left/Right
if (Input::KeyDown(SDL_SCANCODE_H))
camera.Strafe(glm::vec3(-speed * dT, 0, 0));
if (Input::KeyDown(SDL_SCANCODE_L))
camera.Strafe(glm::vec3(speed * dT, 0, 0));
//Strafe forward/back
if (Input::KeyDown(SDL_SCANCODE_I))
camera.Strafe(glm::vec3(0, 0, -speed * dT));
if (Input::KeyDown(SDL_SCANCODE_M))
camera.Strafe(glm::vec3(0, 0, speed * dT));
//Camera yaw and pitch while holding LMB
if (Input::MouseDown(1) && Input::MouseMotion()){
SDL_MouseMotionEvent move = Input::GetMotion();
//We want to damp the motion some, so / 5
camera.Yaw(-move.xrel * rotateSpeed / 5.0f * dT);
camera.Pitch(-move.yrel * rotateSpeed / 5.0f * dT);
}
//Camera roll while holding RMB
if (Input::MouseDown(SDL_BUTTON_RIGHT) && Input::MouseMotion()){
SDL_MouseMotionEvent move = Input::GetMotion();
//We want to damp the motion some, so / 5
camera.Roll(-move.xrel * rotateSpeed / 5.0f * dT);
//Camera zoom in/out
camera.Zoom(move.yrel * speed / 5.0f * dT);
}
if (camera.Changed())
matVPubo.BufferSubData(camera.View(), 0);
//Rendering
window.Clear();
model->Draw(true);
window.Present();
//cap at 60fps
if (delta.Ticks() < 1000 / 60)
SDL_Delay(1000 / 60 - delta.Ticks());
}
window.Close();
Window::Quit();
return 0;
}
<commit_msg>Printing offset information is giving what i'd expect as well, very odd<commit_after>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <SDL.h>
#include <SDL_opengl.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <timer.h>
#include <glcamera.h>
#include <glfunctions.h>
#include <glshader.h>
#include <glprogram.h>
#include <util.h>
#include <model.h>
#include <material.h>
//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
//Start our window
try {
Window::Init();
}
catch (const std::runtime_error &e){
std::cout << e.what() << std::endl;
}
Input::Init();
//Setup main window to read input
int w = 640, h = 480;
Window window("Main window", w, h);
//Time the loading
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::shared_ptr<Model> model = Util::LoadObj("../res/suzanne.obj");
std::cout << "Model load time: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() / 1000.0f
<< std::endl;
//Setup program
GL::Program prog("../res/modelshader.v.glsl", "../res/texturemodel.f.glsl");
//This is a parallel to gluLookAt, see http://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml for
//information on what eye, center and up represent, provides enough info to figure out math/transformations
//needed to make a camera
//Create a camera slightly above the box looking down at it
GL::Camera camera(glm::vec3(0, 0, 1), glm::vec3(0, 0, -5), glm::vec3(0, 1, 0));
glm::mat4 proj = glm::perspective(60.0f, (float)w / (float)h, 0.1f, 100.0f);
//Setup the Uniform buffer object
GLuint uboIdx = GL::GetUniformBlockIndex(prog, "Lighting");
if (uboIdx == GL_INVALID_INDEX)
std::cout << "Invalid UBO Index" << std::endl;
GLint uboSize;
GL::GetActiveUniformBlockiv(prog, uboIdx, GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);
//Make a light @ origin
glm::vec4 lightPos(0.0f, 0.0f, 0.0f, 1.0f);
//TODO: Generic Buffers, templated based on type maybe?? Also need to be able to allocate
//arbitrary size buffer and write data to it instead of forced into passing vect/array/etc
GL::VertexBuffer ubo(lightPos, GL::BUFFER::UNIFORM);
GL::BindBufferBase(GL::BUFFER::UNIFORM, uboIdx, ubo);
uboIdx = GL::GetUniformBlockIndex(prog, "VP");
if (uboIdx == GL_INVALID_INDEX)
std::cout << "Invalid UBO Index" << std::endl;
GL::GetActiveUniformBlockiv(prog, uboIdx, GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);
if (uboSize != sizeof(glm::mat4) * 2)
std::cout << "ubo size isn't right!" << std::endl;
std::array<glm::mat4, 2> matVP = { camera.View(), proj };
GL::VertexBuffer matVPubo(matVP, GL::BUFFER::UNIFORM);
GL::BindBufferBase(GL::BUFFER::UNIFORM, uboIdx, matVPubo);
//Trying to figure out what's wrong with this on Nvidia
const char *names[] = { "v", "p" };
GLuint indices[2];
GL::GetUniformIndices(prog, 2, names, indices);
std::cout << "Indices: " << indices[0] << ", " << indices[1] << std::endl;
//now query some info
GLint info[2];
GL::GetActiveUniformsiv(prog, 2, indices, GL_UNIFORM_OFFSET, info);
std::cout << "Offsets: " << info[0] << ", " << info[1] << std::endl;
model->UseProgram(prog);
model->Translate(glm::vec3(0, 0, -5));
//Track if model matrix was be updated
bool mUpdate = false;
//speed for moving things
float speed = 8.0f, rotateSpeed = 50.0f;
Timer delta;
delta.Start();
//For tracking if we want to quit
while (!Input::Quit()){
float dT = delta.Restart() / 1000.0f;
//Event Handling
Input::PollEvents();
if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
Input::Quit(true);
//Cube Controls------------------
//Cube rotation
if (Input::KeyDown(SDL_SCANCODE_D)){
model->Rotate(rotateSpeed * dT, glm::vec3(0, 1, 0));
}
if (Input::KeyDown(SDL_SCANCODE_A)){
model->Rotate(-rotateSpeed * dT, glm::vec3(0, 1, 0));
}
if (Input::KeyDown(SDL_SCANCODE_W)){
model->Rotate(-rotateSpeed * dT, glm::vec3(1, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_S)){
model->Rotate(rotateSpeed * dT, glm::vec3(1, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_Q)){
model->Rotate(rotateSpeed * dT, glm::vec3(0, 0, 1));
}
if (Input::KeyDown(SDL_SCANCODE_E)){
model->Rotate(-rotateSpeed * dT, glm::vec3(0, 0, 1));
}
//Cube translation
if (Input::KeyDown(SDL_SCANCODE_UP)){
model->Translate(glm::vec3(0, speed * dT, 0));
}
if (Input::KeyDown(SDL_SCANCODE_DOWN)){
model->Translate(glm::vec3(0, -speed * dT, 0));
}
if (Input::KeyDown(SDL_SCANCODE_LEFT)){
model->Translate(glm::vec3(-speed * dT, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_RIGHT)){
model->Translate(glm::vec3(speed * dT, 0, 0));
}
if (Input::KeyDown(SDL_SCANCODE_Z)){
model->Translate(glm::vec3(0, 0, speed * dT));
}
if (Input::KeyDown(SDL_SCANCODE_X)){
model->Translate(glm::vec3(0, 0, -speed * dT));
}
//Camera strafe Left/Right
if (Input::KeyDown(SDL_SCANCODE_H))
camera.Strafe(glm::vec3(-speed * dT, 0, 0));
if (Input::KeyDown(SDL_SCANCODE_L))
camera.Strafe(glm::vec3(speed * dT, 0, 0));
//Strafe forward/back
if (Input::KeyDown(SDL_SCANCODE_I))
camera.Strafe(glm::vec3(0, 0, -speed * dT));
if (Input::KeyDown(SDL_SCANCODE_M))
camera.Strafe(glm::vec3(0, 0, speed * dT));
//Camera yaw and pitch while holding LMB
if (Input::MouseDown(1) && Input::MouseMotion()){
SDL_MouseMotionEvent move = Input::GetMotion();
//We want to damp the motion some, so / 5
camera.Yaw(-move.xrel * rotateSpeed / 5.0f * dT);
camera.Pitch(-move.yrel * rotateSpeed / 5.0f * dT);
}
//Camera roll while holding RMB
if (Input::MouseDown(SDL_BUTTON_RIGHT) && Input::MouseMotion()){
SDL_MouseMotionEvent move = Input::GetMotion();
//We want to damp the motion some, so / 5
camera.Roll(-move.xrel * rotateSpeed / 5.0f * dT);
//Camera zoom in/out
camera.Zoom(move.yrel * speed / 5.0f * dT);
}
if (camera.Changed())
matVPubo.BufferSubData(camera.View(), 0);
//Rendering
window.Clear();
model->Draw(true);
window.Present();
//cap at 60fps
if (delta.Ticks() < 1000 / 60)
SDL_Delay(1000 / 60 - delta.Ticks());
}
window.Close();
Window::Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
patterndisp.cpp
Copyright (c) 2014 Terumasa Tadano
This file is distributed under the terms of the MIT license.
Please see the file 'LICENCE.txt' in the root directory
or http://opensource.org/licenses/mit-license.php for information.
*/
#include <iostream>
#include "patterndisp.h"
#include "memory.h"
#include "error.h"
#include "system.h"
#include "fcs.h"
#include "interaction.h"
#include "symmetry.h"
#include "constants.h"
#include "mathfunctions.h"
using namespace ALM_NS;
Displace::Displace(ALM *alm) : Pointers(alm) {}
Displace::~Displace() {}
void Displace::gen_displacement_pattern()
{
int i, j, m, order;
int maxorder = interaction->maxorder;
std::vector<int> group_tmp;
std::cout << " Generating displacement patterns in ";
if (disp_basis[0] == 'C') {
std::cout << "Cartesian coordinate...";
} else {
std::cout << "fractional coordinate...";
}
memory->allocate(dispset, maxorder);
for (order = 0; order < maxorder; ++order) {
m = 0;
for (i = 0; i < fcs->ndup[order].size(); ++i) {
group_tmp.clear();
for (j = 0; j < order + 1; ++j) {
group_tmp.push_back(fcs->fc_set[order][m].elems[j]);
}
dispset[order].insert(DispAtomSet(group_tmp));
m += fcs->ndup[order][i];
}
}
estimate_best_direction_harmonic(disp_harm);
memory->allocate(pattern_all, maxorder);
generate_pattern_all(maxorder, pattern_all);
std::cout << " done!" << std::endl;
}
void Displace::estimate_best_direction_harmonic(std::vector<DispDirectionHarmonic> &disp_harm)
{
int i, j, k, l;
int nsym_disp, nsym_max;
int ii, jj;
int direc;
int nat = system->nat;
int **flag_disp;
double factor = 1.0e-5;
double dprod, norm1, norm2;
double direc_tmp[3];
double disp_tmp[3], disp_tmp_frac[3], disp_best[3];
double **pos_disp;
std::vector<DirectionVec> directionlist_tmp, direction_new;
memory->allocate(flag_disp, nat, 3);
for (i = 0; i < nat; ++i) {
for (j = 0; j < 3; ++j) {
flag_disp[i][j] = 0;
}
}
for (std::set<DispAtomSet>::iterator it = dispset[0].begin(); it != dispset[0].end(); ++it) {
int index_tmp = (*it).atomset[0];
flag_disp[index_tmp / 3][index_tmp % 3] = 1;
}
for (i = 0; i < nat; ++i) {
directionlist_tmp.clear();
for (j = 0; j < 3; ++j) {
if (flag_disp[i][j] == 1) {
for (k = 0; k < 3; ++k) {
direc_tmp[k] = 0.0;
}
direc_tmp[j] = 1.0;
directionlist_tmp.push_back(direc_tmp);
}
}
if (directionlist_tmp.size() > 0) {
disp_harm.push_back(DispDirectionHarmonic(i, directionlist_tmp));
}
}
memory->deallocate(flag_disp);
memory->allocate(pos_disp, nat, 3);
for (i = 0; i < disp_harm.size(); ++i) {
direction_new.clear();
for (j = 0; j < disp_harm[i].directionlist.size(); ++j) {
for (k = 0; k < 3; ++k) {
disp_tmp[k] = disp_harm[i].directionlist[j].direction[k];
if (std::abs(disp_tmp[k]) > eps) direc = k;
}
rotvec(disp_tmp_frac, disp_tmp, system->rlavec);
for (k = 0; k < nat; ++k) {
for (l = 0; l < 3; ++l) {
pos_disp[k][l] = system->xcoord[k][l];
}
}
for (l = 0; l < 3; ++l) pos_disp[disp_harm[i].atom][l] += factor * disp_tmp_frac[l];
nsym_max = symmetry->numsymop(nat, pos_disp, symmetry->tolerance);
for (k = 0; k < 3; ++k) disp_best[k] = disp_tmp[k];
for (ii = 1; ii >= -1; --ii) {
for (jj = 1; jj >= -1; --jj) {
disp_tmp[direc] = 1.0;
disp_tmp[(direc + 1) % 3] = static_cast<double>(ii);
disp_tmp[(direc + 2) % 3] = static_cast<double>(jj);
rotvec(disp_tmp_frac, disp_tmp, system->rlavec);
for (k = 0; k < nat; ++k) {
for (l = 0; l < 3; ++l) {
pos_disp[k][l] = system->xcoord[k][l];
}
}
for (l = 0; l < 3; ++l) pos_disp[disp_harm[i].atom][l] += factor * disp_tmp_frac[l];
nsym_disp = symmetry->numsymop(nat, pos_disp, symmetry->tolerance);
if (nsym_disp > nsym_max) {
bool isok = true;
for (k = 0; k < direction_new.size(); ++k) {
dprod = 0.0;
norm1 = 0.0;
norm2 = 0.0;
for (l = 0; l < 3; ++l) {
dprod = direction_new[k].direction[l] * disp_tmp[l];
norm1 = std::pow(direction_new[k].direction[l], 2);
norm2 = std::pow(disp_tmp[l], 2);
}
if (std::abs(dprod - std::sqrt(norm1*norm2)) < eps10) {
isok = false;
}
}
if (isok) {
nsym_max = nsym_disp;
for (l = 0; l < 3; ++l) disp_best[l] = disp_tmp[l];
}
}
}
}
direction_new.push_back(disp_best);
}
disp_harm_best.push_back(DispDirectionHarmonic(disp_harm[i].atom, direction_new));
}
memory->deallocate(pos_disp);
std::copy(disp_harm_best.begin(), disp_harm_best.end(), disp_harm.begin());
disp_harm_best.clear();
}
void Displace::generate_pattern_all(const int N, std::vector<AtomWithDirection> *pattern)
{
int i, j;
int order;
int atom_tmp;
double disp_tmp[3];
double norm;
double *direc_tmp;
std::vector<int> atoms;
std::vector<double> directions;
std::vector<std::vector<int> > *sign_prod;
std::vector<int> vec_tmp;
memory->allocate(sign_prod, N);
for (order = 0; order < N; ++order) {
vec_tmp.clear();
generate_signvecs(order + 1, sign_prod[order], vec_tmp);
}
for (order = 0; order < N; ++order) {
pattern[order].clear();
if (order == 0) {
// Special treatment for harmonic terms
for (std::vector<DispDirectionHarmonic>::iterator it = disp_harm.begin();
it != disp_harm.end(); ++it) {
DispDirectionHarmonic disp_now = *it;
atom_tmp = disp_now.atom;
for (std::vector<DirectionVec>::iterator it2 = disp_now.directionlist.begin();
it2 != disp_now.directionlist.end(); ++it2) {
atoms.clear();
directions.clear();
atoms.push_back(disp_now.atom);
for (i = 0; i < 3; ++i) {
disp_tmp[i] = (*it2).direction[i];
}
norm = disp_tmp[0] * disp_tmp[0] + disp_tmp[1] * disp_tmp[1] + disp_tmp[2] * disp_tmp[2];
for (i = 0; i < 3; ++i) disp_tmp[i] /= std::sqrt(norm);
if (disp_basis[0] == 'F') {
rotvec(disp_tmp, disp_tmp, system->rlavec);
for (i = 0; i < 3; ++i) disp_tmp[i] /= 2.0 * pi;
}
for (i = 0; i < sign_prod[0].size(); ++i) {
directions.clear();
for (j = 0; j < 3; ++j) {
directions.push_back(disp_tmp[j] * static_cast<double>(sign_prod[order][i][0]));
}
pattern[order].push_back(AtomWithDirection(atoms, directions));
}
}
}
} else {
// Anharmonic terms
int natom_disp;
std::vector<int>::iterator loc;
std::vector<int> nums;
std::vector<double> directions_copy;
double sign_double;
for (std::set<DispAtomSet>::iterator it = dispset[order].begin(); it != dispset[order].end(); ++it) {
atoms.clear();
directions.clear();
nums.clear();
for (i = 0; i < (*it).atomset.size(); ++i) {
atom_tmp = (*it).atomset[i] / 3;
loc = std::find(nums.begin(), nums.end(), (*it).atomset[i]);
if (loc != nums.end()) continue;
nums.push_back((*it).atomset[i]);
atoms.push_back(atom_tmp);
for (j = 0; j < 3; ++j) {
disp_tmp[j] = 0.0;
}
disp_tmp[(*it).atomset[i] % 3] = 1.0;
if (disp_basis[0] == 'F') {
rotvec(disp_tmp, disp_tmp, system->rlavec);
for (j = 0; j < 3; ++j) disp_tmp[j] /= 2.0 * pi;
}
for (j = 0; j < 3; ++j) directions.push_back(disp_tmp[j]);
}
natom_disp = atoms.size();
directions_copy.clear();
std::copy(directions.begin(), directions.end(), std::back_inserter(directions_copy));
for (std::vector<std::vector<int> >::const_iterator it = sign_prod[natom_disp - 1].begin();
it != sign_prod[natom_disp - 1].end(); ++it) {
directions.clear();
for (i = 0; i < (*it).size(); ++i) {
sign_double = static_cast<double>((*it)[i]);
for (j = 0; j < 3; ++j) {
directions.push_back(directions_copy[3 * i + j] * sign_double);
}
}
pattern[order].push_back(AtomWithDirection(atoms, directions));
}
}
}
}
memory->deallocate(sign_prod);
}
void Displace::generate_signvecs(const int N, std::vector<std::vector<int> > &sign, std::vector<int> vec)
{
// returns the product of signs ('+','-')
if (N == 0) {
sign.push_back(vec);
vec.clear();
} else {
std::vector<int> vec_tmp;
vec_tmp.clear();
std::copy(vec.begin(), vec.end(), std::back_inserter(vec_tmp));
vec_tmp.push_back(1);
generate_signvecs(N - 1, sign, vec_tmp);
vec_tmp.clear();
std::copy(vec.begin(), vec.end(), std::back_inserter(vec_tmp));
vec_tmp.push_back(-1);
generate_signvecs(N - 1, sign, vec_tmp);
}
}<commit_msg>estimate_best_direction is currently unavailable<commit_after>/*
patterndisp.cpp
Copyright (c) 2014 Terumasa Tadano
This file is distributed under the terms of the MIT license.
Please see the file 'LICENCE.txt' in the root directory
or http://opensource.org/licenses/mit-license.php for information.
*/
#include <iostream>
#include "patterndisp.h"
#include "memory.h"
#include "error.h"
#include "system.h"
#include "fcs.h"
#include "interaction.h"
#include "symmetry.h"
#include "constants.h"
#include "mathfunctions.h"
using namespace ALM_NS;
Displace::Displace(ALM *alm) : Pointers(alm) {}
Displace::~Displace() {}
void Displace::gen_displacement_pattern()
{
int i, j, m, order;
int maxorder = interaction->maxorder;
std::vector<int> group_tmp;
std::cout << " Generating displacement patterns in ";
if (disp_basis[0] == 'C') {
std::cout << "Cartesian coordinate...";
} else {
std::cout << "fractional coordinate...";
}
memory->allocate(dispset, maxorder);
for (order = 0; order < maxorder; ++order) {
m = 0;
for (i = 0; i < fcs->ndup[order].size(); ++i) {
group_tmp.clear();
for (j = 0; j < order + 1; ++j) {
group_tmp.push_back(fcs->fc_set[order][m].elems[j]);
}
dispset[order].insert(DispAtomSet(group_tmp));
m += fcs->ndup[order][i];
}
}
// estimate_best_direction_harmonic(disp_harm);
memory->allocate(pattern_all, maxorder);
generate_pattern_all(maxorder, pattern_all);
std::cout << " done!" << std::endl;
}
void Displace::estimate_best_direction_harmonic(std::vector<DispDirectionHarmonic> &disp_harm)
{
int i, j, k, l;
int nsym_disp, nsym_max;
int ii, jj;
int direc;
int nat = system->nat;
int **flag_disp;
double factor = 1.0e-5;
double dprod, norm1, norm2;
double direc_tmp[3];
double disp_tmp[3], disp_tmp_frac[3], disp_best[3];
double **pos_disp;
std::vector<DirectionVec> directionlist_tmp, direction_new;
memory->allocate(flag_disp, nat, 3);
for (i = 0; i < nat; ++i) {
for (j = 0; j < 3; ++j) {
flag_disp[i][j] = 0;
}
}
for (std::set<DispAtomSet>::iterator it = dispset[0].begin(); it != dispset[0].end(); ++it) {
int index_tmp = (*it).atomset[0];
flag_disp[index_tmp / 3][index_tmp % 3] = 1;
}
for (i = 0; i < nat; ++i) {
directionlist_tmp.clear();
for (j = 0; j < 3; ++j) {
if (flag_disp[i][j] == 1) {
for (k = 0; k < 3; ++k) {
direc_tmp[k] = 0.0;
}
direc_tmp[j] = 1.0;
directionlist_tmp.push_back(direc_tmp);
}
}
if (directionlist_tmp.size() > 0) {
disp_harm.push_back(DispDirectionHarmonic(i, directionlist_tmp));
}
}
memory->deallocate(flag_disp);
memory->allocate(pos_disp, nat, 3);
for (i = 0; i < disp_harm.size(); ++i) {
direction_new.clear();
for (j = 0; j < disp_harm[i].directionlist.size(); ++j) {
for (k = 0; k < 3; ++k) {
disp_tmp[k] = disp_harm[i].directionlist[j].direction[k];
if (std::abs(disp_tmp[k]) > eps) direc = k;
}
rotvec(disp_tmp_frac, disp_tmp, system->rlavec);
for (k = 0; k < nat; ++k) {
for (l = 0; l < 3; ++l) {
pos_disp[k][l] = system->xcoord[k][l];
}
}
for (l = 0; l < 3; ++l) pos_disp[disp_harm[i].atom][l] += factor * disp_tmp_frac[l];
nsym_max = symmetry->numsymop(nat, pos_disp, symmetry->tolerance);
for (k = 0; k < 3; ++k) disp_best[k] = disp_tmp[k];
for (ii = 1; ii >= -1; --ii) {
for (jj = 1; jj >= -1; --jj) {
disp_tmp[direc] = 1.0;
disp_tmp[(direc + 1) % 3] = static_cast<double>(ii);
disp_tmp[(direc + 2) % 3] = static_cast<double>(jj);
rotvec(disp_tmp_frac, disp_tmp, system->rlavec);
for (k = 0; k < nat; ++k) {
for (l = 0; l < 3; ++l) {
pos_disp[k][l] = system->xcoord[k][l];
}
}
for (l = 0; l < 3; ++l) pos_disp[disp_harm[i].atom][l] += factor * disp_tmp_frac[l];
nsym_disp = symmetry->numsymop(nat, pos_disp, symmetry->tolerance);
if (nsym_disp > nsym_max) {
bool isok = true;
for (k = 0; k < direction_new.size(); ++k) {
dprod = 0.0;
norm1 = 0.0;
norm2 = 0.0;
for (l = 0; l < 3; ++l) {
dprod = direction_new[k].direction[l] * disp_tmp[l];
norm1 = std::pow(direction_new[k].direction[l], 2);
norm2 = std::pow(disp_tmp[l], 2);
}
if (std::abs(dprod - std::sqrt(norm1*norm2)) < eps10) {
isok = false;
}
}
if (isok) {
nsym_max = nsym_disp;
for (l = 0; l < 3; ++l) disp_best[l] = disp_tmp[l];
}
}
}
}
direction_new.push_back(disp_best);
}
disp_harm_best.push_back(DispDirectionHarmonic(disp_harm[i].atom, direction_new));
}
memory->deallocate(pos_disp);
std::copy(disp_harm_best.begin(), disp_harm_best.end(), disp_harm.begin());
disp_harm_best.clear();
}
void Displace::generate_pattern_all(const int N, std::vector<AtomWithDirection> *pattern)
{
int i, j;
int order;
int atom_tmp;
double disp_tmp[3];
double norm;
double *direc_tmp;
std::vector<int> atoms;
std::vector<double> directions;
std::vector<std::vector<int> > *sign_prod;
std::vector<int> vec_tmp;
memory->allocate(sign_prod, N);
for (order = 0; order < N; ++order) {
vec_tmp.clear();
generate_signvecs(order + 1, sign_prod[order], vec_tmp);
}
for (order = 0; order < N; ++order) {
pattern[order].clear();
// if (order == 0) {
// Special treatment for harmonic terms
// for (std::vector<DispDirectionHarmonic>::iterator it = disp_harm.begin();
// it != disp_harm.end(); ++it) {
// DispDirectionHarmonic disp_now = *it;
//
//
// atom_tmp = disp_now.atom;
//
// for (std::vector<DirectionVec>::iterator it2 = disp_now.directionlist.begin();
// it2 != disp_now.directionlist.end(); ++it2) {
//
// atoms.clear();
// directions.clear();
//
// atoms.push_back(disp_now.atom);
//
// for (i = 0; i < 3; ++i) {
// disp_tmp[i] = (*it2).direction[i];
// }
// norm = disp_tmp[0] * disp_tmp[0] + disp_tmp[1] * disp_tmp[1] + disp_tmp[2] * disp_tmp[2];
// for (i = 0; i < 3; ++i) disp_tmp[i] /= std::sqrt(norm);
//
// if (disp_basis[0] == 'F') {
// rotvec(disp_tmp, disp_tmp, system->rlavec);
// for (i = 0; i < 3; ++i) disp_tmp[i] /= 2.0 * pi;
// }
//
// for (i = 0; i < sign_prod[0].size(); ++i) {
// directions.clear();
//
// for (j = 0; j < 3; ++j) {
// directions.push_back(disp_tmp[j] * static_cast<double>(sign_prod[order][i][0]));
// }
// pattern[order].push_back(AtomWithDirection(atoms, directions));
// }
// }
// }
// } else {
// Anharmonic terms
int natom_disp;
std::vector<int>::iterator loc;
std::vector<int> nums;
std::vector<double> directions_copy;
double sign_double;
for (std::set<DispAtomSet>::iterator it = dispset[order].begin(); it != dispset[order].end(); ++it) {
atoms.clear();
directions.clear();
nums.clear();
for (i = 0; i < (*it).atomset.size(); ++i) {
atom_tmp = (*it).atomset[i] / 3;
loc = std::find(nums.begin(), nums.end(), (*it).atomset[i]);
if (loc != nums.end()) continue;
nums.push_back((*it).atomset[i]);
atoms.push_back(atom_tmp);
for (j = 0; j < 3; ++j) {
disp_tmp[j] = 0.0;
}
disp_tmp[(*it).atomset[i] % 3] = 1.0;
if (disp_basis[0] == 'F') {
rotvec(disp_tmp, disp_tmp, system->rlavec);
for (j = 0; j < 3; ++j) disp_tmp[j] /= 2.0 * pi;
}
for (j = 0; j < 3; ++j) directions.push_back(disp_tmp[j]);
}
natom_disp = atoms.size();
directions_copy.clear();
std::copy(directions.begin(), directions.end(), std::back_inserter(directions_copy));
for (std::vector<std::vector<int> >::const_iterator it = sign_prod[natom_disp - 1].begin();
it != sign_prod[natom_disp - 1].end(); ++it) {
directions.clear();
for (i = 0; i < (*it).size(); ++i) {
sign_double = static_cast<double>((*it)[i]);
for (j = 0; j < 3; ++j) {
directions.push_back(directions_copy[3 * i + j] * sign_double);
}
}
pattern[order].push_back(AtomWithDirection(atoms, directions));
}
}
}
// }
memory->deallocate(sign_prod);
}
void Displace::generate_signvecs(const int N, std::vector<std::vector<int> > &sign, std::vector<int> vec)
{
// returns the product of signs ('+','-')
if (N == 0) {
sign.push_back(vec);
vec.clear();
} else {
std::vector<int> vec_tmp;
vec_tmp.clear();
std::copy(vec.begin(), vec.end(), std::back_inserter(vec_tmp));
vec_tmp.push_back(1);
generate_signvecs(N - 1, sign, vec_tmp);
vec_tmp.clear();
std::copy(vec.begin(), vec.end(), std::back_inserter(vec_tmp));
vec_tmp.push_back(-1);
generate_signvecs(N - 1, sign, vec_tmp);
}
}<|endoftext|> |
<commit_before>//
// Created by Vadim N. on 04/04/2015.
//
//#include <omp.h>
//#include <stdio.h>
//
//int main() {
//#pragma omp parallel
// printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
//}
#include <ostream>
#include "Model"
using namespace ymir;
/**
* \brief Main function of a script for computing generation probabitilies. It has
* a strict order of input arguments in console:
* argv[0] - name of the script (default);
* argv[1] - path to an input file;
* argv[2] - path to a model;
* argv[3] - path to an output file;
* argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file.
* argv[5] - 'n' for nucleotide sequences, 'a' for amino acid sequences.
*/
int main(int argc, char* argv[]) {
std::string in_file_path(argv[1]),
model_path(argv[2]),
out_file_path(argv[3]);
bool recompute_genes = std::stoi(argv[4]);
std::cout << "Input file:\t" << in_file_path << std::endl;
std::cout << "Model path:\t" << model_path << std::endl;
std::cout << "Output file:\t" << out_file_path << std::endl;
std::cout << std::endl;
ProbabilisticAssemblingModel model(model_path);
std::cout << std::endl;
if (model.status()) {
//
// Nucleotide
//
// if (argv[5] == "n") {
ParserNuc parser(new NaiveCDR3NucleotideAligner(model.gene_segments(), VDJAlignerParameters(3)));
ClonesetNuc cloneset;
auto alignment_column_options = AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
AlignmentColumnOptions::OVERWRITE,
AlignmentColumnOptions::REALIGN_PROVIDED);
auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,
VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
AlignmentEventScore(1, -1, 1),
AlignmentEventScore(1, -1, 1)),
VDJAlignmentScoreThreshold(6, 3, 5));
// auto vdj_aligner_parameters_aa = VDJAlignerParameters(3,
// VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
// AlignmentEventScore(1, -1, 1),
// AlignmentEventScore(1, -1, 1)),
// VDJAlignmentScoreThreshold(1, 1, 1));
if (parser.openAndParse(in_file_path,
&cloneset,
model.gene_segments(),
model.recombination(),
alignment_column_options,
vdj_aligner_parameters_nuc))
{
if (recompute_genes) {
std::cout << std::endl;
std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl;
model.updateGeneUsage(cloneset);
}
std::cout << std::endl;
std::vector<prob_t> prob_vec;
std::vector<size_t> noncoding_indices;
std::vector<prob_t> coding_probs;
if (argv[5][0] == 'n') {
prob_vec = model.computeFullProbabilities(cloneset, NO_ERRORS);
} else {
ClonesetAA cloneset_aa;
std::cout << "Converting nucleotide clonotypes to amino acid clonotypes..." << std::endl;
noncoding_indices = CDR3AminoAcidAligner(model.gene_segments(), vdj_aligner_parameters_aa).toAminoAcid(cloneset, &cloneset_aa, true);
std::cout << "Done." << std::endl << std::endl;
coding_probs = model.computeFullProbabilities(cloneset_aa);
}
std::ofstream ofs;
ofs.open(out_file_path);
std::cout << std::endl;
std::cout << "Generation probabilities statistics:" << std::endl;
prob_summary(prob_vec);
if (ofs.is_open()) {
// Write nucleotide probabilities.
if (prob_vec.size()) {
for (auto i = 0; i < prob_vec.size(); ++i) {
ofs << prob_vec[i] << std::endl;
}
}
// Write amino acid probabilities.
else {
size_t k = 0, j = 0;
for (auto i = 0; i < cloneset.size(); ++i) {
if (k != noncoding_indices.size() && i == noncoding_indices[k]) {
ofs << "-1" << std::endl;
++k;
} else {
ofs << coding_probs[j] << std::endl;
++j;
}
}
}
} else {
std::cout << "Problems with the output stream. Terminating..." << std::endl;
}
ofs.close();
} else {
std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
}
// }
//
// Amino acid
//
// else {
// ParserAA parser;
// ClonesetAA cloneset;
//
// if (parser.openAndParse(in_file_path,
// &cloneset,
// model.gene_segments(),
// model.recombination(),
// AlignmentColumnOptions(AlignmentColumnOptions::USE_PROVIDED,
// AlignmentColumnOptions::USE_PROVIDED,
// AlignmentColumnOptions::OVERWRITE))) {
//// if (recompute_genes) {
//// std::cout << std::endl;
//// std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl;
//// model.updateGeneUsage(cloneset);
//// }
//
// std::cout << std::endl;
// auto prob_vec = model.computeFullProbabilities(cloneset);
//
// std::ofstream ofs;
// ofs.open(out_file_path);
//
// std::cout << std::endl;
// std::cout << "Generation probabilities statistics:" << std::endl;
// prob_summary(prob_vec);
//
// if (ofs.is_open()) {
// for (auto i = 0; i < prob_vec.size(); ++i) {
// ofs << prob_vec[i] << std::endl;
// }
// } else {
// std::cout << "Problems with the output stream. Terminating..." << std::endl;
// }
// ofs.close();
// } else {
// std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
// }
// }
} else {
std::cout << "Problems with the model. Terminating..." << std::endl;
}
return 0;
}<commit_msg>change scores a bit<commit_after>//
// Created by Vadim N. on 04/04/2015.
//
//#include <omp.h>
//#include <stdio.h>
//
//int main() {
//#pragma omp parallel
// printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
//}
#include <ostream>
#include "Model"
using namespace ymir;
/**
* \brief Main function of a script for computing generation probabitilies. It has
* a strict order of input arguments in console:
* argv[0] - name of the script (default);
* argv[1] - path to an input file;
* argv[2] - path to a model;
* argv[3] - path to an output file;
* argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file.
* argv[5] - 'n' for nucleotide sequences, 'a' for amino acid sequences.
*/
int main(int argc, char* argv[]) {
std::string in_file_path(argv[1]),
model_path(argv[2]),
out_file_path(argv[3]);
bool recompute_genes = std::stoi(argv[4]);
std::cout << "Input file:\t" << in_file_path << std::endl;
std::cout << "Model path:\t" << model_path << std::endl;
std::cout << "Output file:\t" << out_file_path << std::endl;
std::cout << std::endl;
ProbabilisticAssemblingModel model(model_path);
std::cout << std::endl;
if (model.status()) {
//
// Nucleotide
//
// if (argv[5] == "n") {
ParserNuc parser(new NaiveCDR3NucleotideAligner(model.gene_segments(), VDJAlignerParameters(3)));
ClonesetNuc cloneset;
auto alignment_column_options = AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,
AlignmentColumnOptions::OVERWRITE,
AlignmentColumnOptions::REALIGN_PROVIDED);
auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,
VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
AlignmentEventScore(1, -1, 1),
AlignmentEventScore(1, -1, 1)),
VDJAlignmentScoreThreshold(2, 3, 2));
// auto vdj_aligner_parameters_aa = VDJAlignerParameters(3,
// VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),
// AlignmentEventScore(1, -1, 1),
// AlignmentEventScore(1, -1, 1)),
// VDJAlignmentScoreThreshold(1, 1, 1));
if (parser.openAndParse(in_file_path,
&cloneset,
model.gene_segments(),
model.recombination(),
alignment_column_options,
vdj_aligner_parameters_nuc))
{
if (recompute_genes) {
std::cout << std::endl;
std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl;
model.updateGeneUsage(cloneset);
}
std::cout << std::endl;
std::vector<prob_t> prob_vec;
std::vector<size_t> noncoding_indices;
std::vector<prob_t> coding_probs;
if (argv[5][0] == 'n') {
prob_vec = model.computeFullProbabilities(cloneset, NO_ERRORS);
} else {
ClonesetAA cloneset_aa;
std::cout << "Converting nucleotide clonotypes to amino acid clonotypes..." << std::endl;
noncoding_indices = CDR3AminoAcidAligner(model.gene_segments(), vdj_aligner_parameters_aa).toAminoAcid(cloneset, &cloneset_aa, true);
std::cout << "Done." << std::endl << std::endl;
coding_probs = model.computeFullProbabilities(cloneset_aa);
}
std::ofstream ofs;
ofs.open(out_file_path);
std::cout << std::endl;
std::cout << "Generation probabilities statistics:" << std::endl;
prob_summary(prob_vec);
if (ofs.is_open()) {
// Write nucleotide probabilities.
if (prob_vec.size()) {
for (auto i = 0; i < prob_vec.size(); ++i) {
ofs << prob_vec[i] << std::endl;
}
}
// Write amino acid probabilities.
else {
size_t k = 0, j = 0;
for (auto i = 0; i < cloneset.size(); ++i) {
if (k != noncoding_indices.size() && i == noncoding_indices[k]) {
ofs << "-1" << std::endl;
++k;
} else {
ofs << coding_probs[j] << std::endl;
++j;
}
}
}
} else {
std::cout << "Problems with the output stream. Terminating..." << std::endl;
}
ofs.close();
} else {
std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
}
// }
//
// Amino acid
//
// else {
// ParserAA parser;
// ClonesetAA cloneset;
//
// if (parser.openAndParse(in_file_path,
// &cloneset,
// model.gene_segments(),
// model.recombination(),
// AlignmentColumnOptions(AlignmentColumnOptions::USE_PROVIDED,
// AlignmentColumnOptions::USE_PROVIDED,
// AlignmentColumnOptions::OVERWRITE))) {
//// if (recompute_genes) {
//// std::cout << std::endl;
//// std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl;
//// model.updateGeneUsage(cloneset);
//// }
//
// std::cout << std::endl;
// auto prob_vec = model.computeFullProbabilities(cloneset);
//
// std::ofstream ofs;
// ofs.open(out_file_path);
//
// std::cout << std::endl;
// std::cout << "Generation probabilities statistics:" << std::endl;
// prob_summary(prob_vec);
//
// if (ofs.is_open()) {
// for (auto i = 0; i < prob_vec.size(); ++i) {
// ofs << prob_vec[i] << std::endl;
// }
// } else {
// std::cout << "Problems with the output stream. Terminating..." << std::endl;
// }
// ofs.close();
// } else {
// std::cout << "Problems in parsing the input file. Terminating..." << std::endl;
// }
// }
} else {
std::cout << "Problems with the model. Terminating..." << std::endl;
}
return 0;
}<|endoftext|> |
<commit_before>#include "precompiled.h"
#include "engine/actor/Inventory.h"
namespace engine {
namespace actor {
const std::vector<item::ItemBase*> Inventory::getItemList() {
return itemList;
}
std::vector<item::ItemBase*> Inventory::getItemsByName(const String name) {
std::vector<item::ItemBase*> foundItems;
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getName().compare(name) == 0 ) {
foundItems.push_back( (*iter) );
}
}
return foundItems;
}
item::ItemBase* Inventory::getItemByID(const int id) {
item::ItemBase* returnItem = NULL;
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getId() == id ) {
returnItem = (*iter);
break;
}
}
return returnItem;
}
bool Inventory::addItem(item::ItemBase* item) {
// untracked items cannot be added
if ( item->getId() == -1 ) {
return false;
}
itemList.push_back( item );
item->setInInventory(true);
return true;
}
// TODO
std::vector<item::ItemBase*> Inventory::removeItemsByName(const String name) {
//return itemVector();
return std::vector<item::ItemBase*>();
}
item::ItemBase* Inventory::removeItemByID(const int id) {
if ( id < 0 ) { // ids less than 0 (-1) indicate untracked item, it can't be here anyway
return NULL;
}
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getId() == id ) {
item::ItemBase* item = (*iter);
item->setInInventory(false);
iter = itemList.erase(iter);
return item;
}
}
return NULL;
}
}
}<commit_msg>Implemented Inventory::removeItemsByName.<commit_after>#include "precompiled.h"
#include "engine/actor/Inventory.h"
namespace engine {
namespace actor {
const std::vector<item::ItemBase*> Inventory::getItemList() {
return itemList;
}
std::vector<item::ItemBase*> Inventory::getItemsByName(const String name) {
std::vector<item::ItemBase*> foundItems;
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getName().compare(name) == 0 ) {
foundItems.push_back( (*iter) );
}
}
return foundItems;
}
item::ItemBase* Inventory::getItemByID(const int id) {
item::ItemBase* returnItem = NULL;
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getId() == id ) {
returnItem = (*iter);
break;
}
}
return returnItem;
}
bool Inventory::addItem(item::ItemBase* item) {
// untracked items cannot be added
if ( item->getId() == -1 ) {
return false;
}
itemList.push_back( item );
item->setInInventory(true);
return true;
}
std::vector<item::ItemBase*> Inventory::removeItemsByName(const String name) {
std::vector<item::ItemBase*> foundItems;
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getName().compare(name) == 0 ) {
item::ItemBase* item = (*iter);
item->setInInventory(false);
iter = itemList.erase(iter);
foundItems.push_back( item );
}
}
return foundItems;
}
item::ItemBase* Inventory::removeItemByID(const int id) {
if ( id < 0 ) { // ids less than 0 (-1) indicate untracked item, it can't be here anyway
return NULL;
}
for( auto iter = itemList.begin(); iter != itemList.end(); ++iter ) {
if ( (*iter)->getId() == id ) {
item::ItemBase* item = (*iter);
item->setInInventory(false);
iter = itemList.erase(iter);
return item;
}
}
return NULL;
}
}
}<|endoftext|> |
<commit_before>// @(#)root/base:$Id$
// Author: Fons Rademakers 29/07/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Error handling routines.
This file defines a number of global error handling routines:
Warning(), Error(), SysError() and Fatal(). They all take a
location string (where the error happened) and a printf style format
string plus vararg's. In the end these functions call an
errorhandler function. Initially the MinimalErrorHandler, which is supposed
to be replaced by the proper DefaultErrorHandler()
*/
#include "TError.h"
#include "ThreadLocalStorage.h"
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <string>
// Deprecated
TVirtualMutex *gErrorMutex = nullptr;
Int_t gErrorIgnoreLevel = kUnset;
Int_t gErrorAbortLevel = kSysError+1;
Bool_t gPrintViaErrorHandler = kFALSE;
const char *kAssertMsg = "%s violated at line %d of `%s'";
const char *kCheckMsg = "%s not true at line %d of `%s'";
static ErrorHandlerFunc_t gErrorHandler = ROOT::Internal::MinimalErrorHandler;
static ROOT::Internal::ErrorSystemMsgHandlerFunc_t &GetErrorSystemMsgHandlerRef()
{
static ROOT::Internal::ErrorSystemMsgHandlerFunc_t h;
return h;
}
namespace ROOT {
namespace Internal {
ErrorSystemMsgHandlerFunc_t GetErrorSystemMsgHandler()
{
return GetErrorSystemMsgHandlerRef();
}
ErrorSystemMsgHandlerFunc_t SetErrorSystemMsgHandler(ErrorSystemMsgHandlerFunc_t h)
{
auto oldHandler = GetErrorSystemMsgHandlerRef();
GetErrorSystemMsgHandlerRef() = h;
return oldHandler;
}
/// A very simple error handler that is usually replaced by the TROOT default error handler.
/// The minimal error handler is not serialized across threads, so that output of multi-threaded programs
/// can get scrambled
void MinimalErrorHandler(Int_t level, Bool_t abort_bool, const char *location, const char *msg)
{
if (level < gErrorIgnoreLevel)
return;
if (level >= kBreak)
fprintf(stderr, "\n *** Break *** ");
fprintf(stderr, "<%s>: %s\n", location ? location : "unspecified location", msg);
fflush(stderr);
if (abort_bool) {
fprintf(stderr, "aborting\n");
fflush(stderr);
abort();
}
}
} // namespace Internal
} // namespace ROOT
////////////////////////////////////////////////////////////////////////////////
/// Set an errorhandler function. Returns the old handler.
ErrorHandlerFunc_t SetErrorHandler(ErrorHandlerFunc_t newhandler)
{
ErrorHandlerFunc_t oldhandler = gErrorHandler;
gErrorHandler = newhandler;
return oldhandler;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current error handler function.
ErrorHandlerFunc_t GetErrorHandler()
{
return gErrorHandler;
}
////////////////////////////////////////////////////////////////////////////////
/// General error handler function. It calls the user set error handler.
void ErrorHandler(Int_t level, const char *location, const char *fmt, std::va_list ap)
{
TTHREAD_TLS(Int_t) buf_size(256);
TTHREAD_TLS(char*) buf_storage(nullptr);
char small_buf[256];
char *buf = buf_storage ? buf_storage : small_buf;
std::va_list ap_copy;
va_copy(ap_copy, ap);
if (!fmt)
fmt = "no error message provided";
Int_t n = vsnprintf(buf, buf_size, fmt, ap_copy);
if (n >= buf_size) {
va_end(ap_copy);
buf_size = n + 1;
if (buf != &(small_buf[0]))
delete[] buf;
buf_storage = buf = new char[buf_size];
// Try again with a sufficiently large buffer
va_copy(ap_copy, ap);
vsnprintf(buf, buf_size, fmt, ap_copy);
}
va_end(ap_copy);
std::string bp = buf;
if (level >= kSysError && level < kFatal) {
bp.push_back(' ');
if (GetErrorSystemMsgHandlerRef())
bp += GetErrorSystemMsgHandlerRef()();
else
bp += std::string("(errno: ") + std::to_string(errno) + ")";
}
if (level != kFatal)
gErrorHandler(level, level >= gErrorAbortLevel, location, bp.c_str());
else
gErrorHandler(level, kTRUE, location, bp.c_str());
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in abstract base classes in case one does
/// not want to make the class a "real" (in C++ sense) ABC. If this
/// function is called it will warn the user that the function should
/// have been overridden.
void AbstractMethod(const char *method)
{
Warning(method, "this method must be overridden!");
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in classes that should override a certain
/// function, but in the inherited class the function makes no sense.
void MayNotUse(const char *method)
{
Warning(method, "may not use this method");
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function to declare a function obsolete. Specify as of which version
/// the method is obsolete and as from which version it will be removed.
void Obsolete(const char *function, const char *asOfVers, const char *removedFromVers)
{
Warning(function, "obsolete as of %s and will be removed from %s", asOfVers, removedFromVers);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Error(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kError, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case a system (OS or GUI) related error occurred.
void SysError(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kSysError, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Break(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kBreak, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function for informational messages.
void Info(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kInfo, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in warning situations.
void Warning(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kWarning, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case of a fatal error. It will abort the program.
// Fatal() *might* not abort the program (if gAbortLevel > kFatal) - but for all
// reasonable settings it *will* abort. So let's be reasonable wrt Coverity:
// coverity[+kill]
void Fatal(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kFatal, location, fmt, ap);
va_end(ap);
}
<commit_msg>Use C++11 thread_local in TError.cxx<commit_after>// @(#)root/base:$Id$
// Author: Fons Rademakers 29/07/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Error handling routines.
This file defines a number of global error handling routines:
Warning(), Error(), SysError() and Fatal(). They all take a
location string (where the error happened) and a printf style format
string plus vararg's. In the end these functions call an
errorhandler function. Initially the MinimalErrorHandler, which is supposed
to be replaced by the proper DefaultErrorHandler()
*/
#include "TError.h"
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <string>
// Deprecated
TVirtualMutex *gErrorMutex = nullptr;
Int_t gErrorIgnoreLevel = kUnset;
Int_t gErrorAbortLevel = kSysError+1;
Bool_t gPrintViaErrorHandler = kFALSE;
const char *kAssertMsg = "%s violated at line %d of `%s'";
const char *kCheckMsg = "%s not true at line %d of `%s'";
static ErrorHandlerFunc_t gErrorHandler = ROOT::Internal::MinimalErrorHandler;
static ROOT::Internal::ErrorSystemMsgHandlerFunc_t &GetErrorSystemMsgHandlerRef()
{
static ROOT::Internal::ErrorSystemMsgHandlerFunc_t h;
return h;
}
namespace ROOT {
namespace Internal {
ErrorSystemMsgHandlerFunc_t GetErrorSystemMsgHandler()
{
return GetErrorSystemMsgHandlerRef();
}
ErrorSystemMsgHandlerFunc_t SetErrorSystemMsgHandler(ErrorSystemMsgHandlerFunc_t h)
{
auto oldHandler = GetErrorSystemMsgHandlerRef();
GetErrorSystemMsgHandlerRef() = h;
return oldHandler;
}
/// A very simple error handler that is usually replaced by the TROOT default error handler.
/// The minimal error handler is not serialized across threads, so that output of multi-threaded programs
/// can get scrambled
void MinimalErrorHandler(Int_t level, Bool_t abort_bool, const char *location, const char *msg)
{
if (level < gErrorIgnoreLevel)
return;
if (level >= kBreak)
fprintf(stderr, "\n *** Break *** ");
fprintf(stderr, "<%s>: %s\n", location ? location : "unspecified location", msg);
fflush(stderr);
if (abort_bool) {
fprintf(stderr, "aborting\n");
fflush(stderr);
abort();
}
}
} // namespace Internal
} // namespace ROOT
////////////////////////////////////////////////////////////////////////////////
/// Set an errorhandler function. Returns the old handler.
ErrorHandlerFunc_t SetErrorHandler(ErrorHandlerFunc_t newhandler)
{
ErrorHandlerFunc_t oldhandler = gErrorHandler;
gErrorHandler = newhandler;
return oldhandler;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current error handler function.
ErrorHandlerFunc_t GetErrorHandler()
{
return gErrorHandler;
}
////////////////////////////////////////////////////////////////////////////////
/// General error handler function. It calls the user set error handler.
void ErrorHandler(Int_t level, const char *location, const char *fmt, std::va_list ap)
{
thread_local Int_t buf_size(256);
thread_local char *buf_storage(nullptr);
char small_buf[256];
char *buf = buf_storage ? buf_storage : small_buf;
std::va_list ap_copy;
va_copy(ap_copy, ap);
if (!fmt)
fmt = "no error message provided";
Int_t n = vsnprintf(buf, buf_size, fmt, ap_copy);
if (n >= buf_size) {
va_end(ap_copy);
buf_size = n + 1;
if (buf != &(small_buf[0]))
delete[] buf;
buf_storage = buf = new char[buf_size];
// Try again with a sufficiently large buffer
va_copy(ap_copy, ap);
vsnprintf(buf, buf_size, fmt, ap_copy);
}
va_end(ap_copy);
std::string bp = buf;
if (level >= kSysError && level < kFatal) {
bp.push_back(' ');
if (GetErrorSystemMsgHandlerRef())
bp += GetErrorSystemMsgHandlerRef()();
else
bp += std::string("(errno: ") + std::to_string(errno) + ")";
}
if (level != kFatal)
gErrorHandler(level, level >= gErrorAbortLevel, location, bp.c_str());
else
gErrorHandler(level, kTRUE, location, bp.c_str());
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in abstract base classes in case one does
/// not want to make the class a "real" (in C++ sense) ABC. If this
/// function is called it will warn the user that the function should
/// have been overridden.
void AbstractMethod(const char *method)
{
Warning(method, "this method must be overridden!");
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in classes that should override a certain
/// function, but in the inherited class the function makes no sense.
void MayNotUse(const char *method)
{
Warning(method, "may not use this method");
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function to declare a function obsolete. Specify as of which version
/// the method is obsolete and as from which version it will be removed.
void Obsolete(const char *function, const char *asOfVers, const char *removedFromVers)
{
Warning(function, "obsolete as of %s and will be removed from %s", asOfVers, removedFromVers);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Error(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kError, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case a system (OS or GUI) related error occurred.
void SysError(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kSysError, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Break(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kBreak, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function for informational messages.
void Info(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kInfo, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in warning situations.
void Warning(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kWarning, location, fmt, ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case of a fatal error. It will abort the program.
// Fatal() *might* not abort the program (if gAbortLevel > kFatal) - but for all
// reasonable settings it *will* abort. So let's be reasonable wrt Coverity:
// coverity[+kill]
void Fatal(const char *location, const char *fmt, ...)
{
std::va_list ap;
va_start(ap, fmt);
ErrorHandler(kFatal, location, fmt, ap);
va_end(ap);
}
<|endoftext|> |
<commit_before>// @(#)root/base:$Id$
// Author: Fons Rademakers 29/07/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Error handling routines.
This file defines a number of global error handling routines:
Warning(), Error(), SysError() and Fatal(). They all take a
location string (where the error happened) and a printf style format
string plus vararg's. In the end these functions call an
errorhandler function. By default DefaultErrorHandler() is used.
*/
#ifdef WIN32
#include <windows.h>
#endif
#include <cstdio>
#include <cstdlib>
#include "snprintf.h"
#include "Varargs.h"
#include "TError.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TVirtualMutex.h"
#include "ThreadLocalStorage.h"
#include <cctype> // for tolower
#include <string>
// Mutex for error and error format protection
// (exported to be used for similar cases in other classes)
TVirtualMutex *gErrorMutex = 0;
Int_t gErrorIgnoreLevel = kUnset;
Int_t gErrorAbortLevel = kSysError+1;
Bool_t gPrintViaErrorHandler = kFALSE;
const char *kAssertMsg = "%s violated at line %d of `%s'";
const char *kCheckMsg = "%s not true at line %d of `%s'";
// Integrate with crash reporter.
#ifdef __APPLE__
extern "C" {
static const char *__crashreporter_info__ = 0;
asm(".desc ___crashreporter_info__, 0x10");
}
#endif
static ErrorHandlerFunc_t gErrorHandler = DefaultErrorHandler;
////////////////////////////////////////////////////////////////////////////////
/// Print debugging message to stderr and, on Windows, to the system debugger.
static void DebugPrint(const char *fmt, ...)
{
TTHREAD_TLS(Int_t) buf_size = 2048;
TTHREAD_TLS(char*) buf = 0;
va_list ap;
va_start(ap, fmt);
again:
if (!buf)
buf = new char[buf_size];
Int_t n = vsnprintf(buf, buf_size, fmt, ap);
// old vsnprintf's return -1 if string is truncated new ones return
// total number of characters that would have been written
if (n == -1 || n >= buf_size) {
if (n == -1)
buf_size *= 2;
else
buf_size = n+1;
delete [] buf;
buf = 0;
va_end(ap);
va_start(ap, fmt);
goto again;
}
va_end(ap);
// Serialize the actual printing.
R__LOCKGUARD2(gErrorMutex);
const char *toprint = buf; // Work around for older platform where we use TThreadTLSWrapper
fprintf(stderr, "%s", toprint);
#ifdef WIN32
::OutputDebugString(buf);
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Set an errorhandler function. Returns the old handler.
ErrorHandlerFunc_t SetErrorHandler(ErrorHandlerFunc_t newhandler)
{
ErrorHandlerFunc_t oldhandler = gErrorHandler;
gErrorHandler = newhandler;
return oldhandler;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current error handler function.
ErrorHandlerFunc_t GetErrorHandler()
{
return gErrorHandler;
}
////////////////////////////////////////////////////////////////////////////////
/// The default error handler function. It prints the message on stderr and
/// if abort is set it aborts the application.
void DefaultErrorHandler(Int_t level, Bool_t abort_bool, const char *location, const char *msg)
{
if (gErrorIgnoreLevel == kUnset) {
R__LOCKGUARD2(gErrorMutex);
gErrorIgnoreLevel = 0;
if (gEnv) {
std::string slevel;
auto cstrlevel = gEnv->GetValue("Root.ErrorIgnoreLevel", "Print");
while (cstrlevel && *cstrlevel) {
slevel.push_back(tolower(*cstrlevel));
cstrlevel++;
}
if (slevel == "print")
gErrorIgnoreLevel = kPrint;
else if (slevel == "info")
gErrorIgnoreLevel = kInfo;
else if (slevel == "warning")
gErrorIgnoreLevel = kWarning;
else if (slevel == "error")
gErrorIgnoreLevel = kError;
else if (slevel == "break")
gErrorIgnoreLevel = kBreak;
else if (slevel == "syserror")
gErrorIgnoreLevel = kSysError;
else if (slevel == "fatal")
gErrorIgnoreLevel = kFatal;
}
}
if (level < gErrorIgnoreLevel)
return;
const char *type = 0;
if (level >= kInfo)
type = "Info";
if (level >= kWarning)
type = "Warning";
if (level >= kError)
type = "Error";
if (level >= kBreak)
type = "\n *** Break ***";
if (level >= kSysError)
type = "SysError";
if (level >= kFatal)
type = "Fatal";
if (level >= kPrint && level < kInfo)
DebugPrint("%s\n", msg);
else if (level >= kBreak && level < kSysError)
DebugPrint("%s %s\n", type, msg);
else if (!location || !location[0])
DebugPrint("%s: %s\n", type, msg);
else
DebugPrint("%s in <%s>: %s\n", type, location, msg);
fflush(stderr);
if (abort_bool) {
#ifdef __APPLE__
if (__crashreporter_info__)
delete [] __crashreporter_info__;
__crashreporter_info__ = StrDup(smsg);
#endif
DebugPrint("aborting\n");
fflush(stderr);
if (gSystem) {
gSystem->StackTrace();
gSystem->Abort();
} else
abort();
}
}
////////////////////////////////////////////////////////////////////////////////
/// General error handler function. It calls the user set error handler.
void ErrorHandler(Int_t level, const char *location, const char *fmt, va_list ap)
{
TTHREAD_TLS(Int_t) buf_size(256);
TTHREAD_TLS(char*) buf_storage(0);
char small_buf[256];
char *buf = buf_storage ? buf_storage : small_buf;
int vc = 0;
va_list sap;
R__VA_COPY(sap, ap);
again:
if (!buf) {
buf_storage = buf = new char[buf_size];
}
if (!fmt)
fmt = "no error message provided";
Int_t n = vsnprintf(buf, buf_size, fmt, ap);
// old vsnprintf's return -1 if string is truncated new ones return
// total number of characters that would have been written
if (n == -1 || n >= buf_size) {
if (n == -1)
buf_size *= 2;
else
buf_size = n+1;
if (buf != &(small_buf[0])) delete [] buf;
buf = 0;
va_end(ap);
R__VA_COPY(ap, sap);
vc = 1;
goto again;
}
va_end(sap);
if (vc)
va_end(ap);
char *bp;
if (level >= kSysError && level < kFatal) {
const char *toprint = buf; // Work around for older platform where we use TThreadTLSWrapper
bp = Form("%s (%s)", toprint, gSystem->GetError());
} else
bp = buf;
if (level != kFatal)
gErrorHandler(level, level >= gErrorAbortLevel, location, bp);
else
gErrorHandler(level, kTRUE, location, bp);
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in abstract base classes in case one does
/// not want to make the class a "real" (in C++ sense) ABC. If this
/// function is called it will warn the user that the function should
/// have been overridden.
void AbstractMethod(const char *method)
{
Warning(method, "this method must be overridden!");
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in classes that should override a certain
/// function, but in the inherited class the function makes no sense.
void MayNotUse(const char *method)
{
Warning(method, "may not use this method");
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function to declare a function obsolete. Specify as of which version
/// the method is obsolete and as from which version it will be removed.
void Obsolete(const char *function, const char *asOfVers, const char *removedFromVers)
{
Warning(function, "obsolete as of %s and will be removed from %s", asOfVers, removedFromVers);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Error(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kError, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case a system (OS or GUI) related error occurred.
void SysError(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap, va_(fmt));
ErrorHandler(kSysError, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Break(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kBreak, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function for informational messages.
void Info(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kInfo, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in warning situations.
void Warning(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kWarning, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case of a fatal error. It will abort the program.
// Fatal() *might* not abort the program (if gAbortLevel > kFatal) - but for all
// reasonable settings it *will* abort. So let's be reasonable wrt Coverity:
// coverity[+kill]
void Fatal(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kFatal, location, va_(fmt), ap);
va_end(ap);
}
<commit_msg>fix crashreporter handling<commit_after>// @(#)root/base:$Id$
// Author: Fons Rademakers 29/07/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Error handling routines.
This file defines a number of global error handling routines:
Warning(), Error(), SysError() and Fatal(). They all take a
location string (where the error happened) and a printf style format
string plus vararg's. In the end these functions call an
errorhandler function. By default DefaultErrorHandler() is used.
*/
#ifdef WIN32
#include <windows.h>
#endif
#include <cstdio>
#include <cstdlib>
#include "snprintf.h"
#include "Varargs.h"
#include "TError.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TVirtualMutex.h"
#include "ThreadLocalStorage.h"
#include <cctype> // for tolower
#include <cstring>
#include <string>
// Mutex for error and error format protection
// (exported to be used for similar cases in other classes)
TVirtualMutex *gErrorMutex = 0;
Int_t gErrorIgnoreLevel = kUnset;
Int_t gErrorAbortLevel = kSysError+1;
Bool_t gPrintViaErrorHandler = kFALSE;
const char *kAssertMsg = "%s violated at line %d of `%s'";
const char *kCheckMsg = "%s not true at line %d of `%s'";
// Integrate with crash reporter.
#ifdef __APPLE__
extern "C" {
static const char *__crashreporter_info__ = 0;
asm(".desc ___crashreporter_info__, 0x10");
}
#endif
static ErrorHandlerFunc_t gErrorHandler = DefaultErrorHandler;
////////////////////////////////////////////////////////////////////////////////
/// Print debugging message to stderr and, on Windows, to the system debugger.
static void DebugPrint(const char *fmt, ...)
{
TTHREAD_TLS(Int_t) buf_size = 2048;
TTHREAD_TLS(char*) buf = 0;
va_list ap;
va_start(ap, fmt);
again:
if (!buf)
buf = new char[buf_size];
Int_t n = vsnprintf(buf, buf_size, fmt, ap);
// old vsnprintf's return -1 if string is truncated new ones return
// total number of characters that would have been written
if (n == -1 || n >= buf_size) {
if (n == -1)
buf_size *= 2;
else
buf_size = n+1;
delete [] buf;
buf = 0;
va_end(ap);
va_start(ap, fmt);
goto again;
}
va_end(ap);
// Serialize the actual printing.
R__LOCKGUARD2(gErrorMutex);
const char *toprint = buf; // Work around for older platform where we use TThreadTLSWrapper
fprintf(stderr, "%s", toprint);
#ifdef WIN32
::OutputDebugString(buf);
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Set an errorhandler function. Returns the old handler.
ErrorHandlerFunc_t SetErrorHandler(ErrorHandlerFunc_t newhandler)
{
ErrorHandlerFunc_t oldhandler = gErrorHandler;
gErrorHandler = newhandler;
return oldhandler;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the current error handler function.
ErrorHandlerFunc_t GetErrorHandler()
{
return gErrorHandler;
}
////////////////////////////////////////////////////////////////////////////////
/// The default error handler function. It prints the message on stderr and
/// if abort is set it aborts the application.
void DefaultErrorHandler(Int_t level, Bool_t abort_bool, const char *location, const char *msg)
{
if (gErrorIgnoreLevel == kUnset) {
R__LOCKGUARD2(gErrorMutex);
gErrorIgnoreLevel = 0;
if (gEnv) {
std::string slevel;
auto cstrlevel = gEnv->GetValue("Root.ErrorIgnoreLevel", "Print");
while (cstrlevel && *cstrlevel) {
slevel.push_back(tolower(*cstrlevel));
cstrlevel++;
}
if (slevel == "print")
gErrorIgnoreLevel = kPrint;
else if (slevel == "info")
gErrorIgnoreLevel = kInfo;
else if (slevel == "warning")
gErrorIgnoreLevel = kWarning;
else if (slevel == "error")
gErrorIgnoreLevel = kError;
else if (slevel == "break")
gErrorIgnoreLevel = kBreak;
else if (slevel == "syserror")
gErrorIgnoreLevel = kSysError;
else if (slevel == "fatal")
gErrorIgnoreLevel = kFatal;
}
}
if (level < gErrorIgnoreLevel)
return;
const char *type = 0;
if (level >= kInfo)
type = "Info";
if (level >= kWarning)
type = "Warning";
if (level >= kError)
type = "Error";
if (level >= kBreak)
type = "\n *** Break ***";
if (level >= kSysError)
type = "SysError";
if (level >= kFatal)
type = "Fatal";
std::string smsg;
if (level >= kPrint && level < kInfo)
smsg = msg;
else if (level >= kBreak && level < kSysError)
smsg = std::string(type) + " " + msg;
else if (!location || !location[0])
smsg = std::string(type) + ": " + msg;
else
smsg = std::string(type) + " in <" + location + ">: " + msg;
DebugPrint("%s\n", smsg.c_str());
fflush(stderr);
if (abort_bool) {
#ifdef __APPLE__
if (__crashreporter_info__)
delete [] __crashreporter_info__;
__crashreporter_info__ = strdup(smsg.c_str());
#endif
DebugPrint("aborting\n");
fflush(stderr);
if (gSystem) {
gSystem->StackTrace();
gSystem->Abort();
} else
abort();
}
}
////////////////////////////////////////////////////////////////////////////////
/// General error handler function. It calls the user set error handler.
void ErrorHandler(Int_t level, const char *location, const char *fmt, va_list ap)
{
TTHREAD_TLS(Int_t) buf_size(256);
TTHREAD_TLS(char*) buf_storage(0);
char small_buf[256];
char *buf = buf_storage ? buf_storage : small_buf;
int vc = 0;
va_list sap;
R__VA_COPY(sap, ap);
again:
if (!buf) {
buf_storage = buf = new char[buf_size];
}
if (!fmt)
fmt = "no error message provided";
Int_t n = vsnprintf(buf, buf_size, fmt, ap);
// old vsnprintf's return -1 if string is truncated new ones return
// total number of characters that would have been written
if (n == -1 || n >= buf_size) {
if (n == -1)
buf_size *= 2;
else
buf_size = n+1;
if (buf != &(small_buf[0])) delete [] buf;
buf = 0;
va_end(ap);
R__VA_COPY(ap, sap);
vc = 1;
goto again;
}
va_end(sap);
if (vc)
va_end(ap);
char *bp;
if (level >= kSysError && level < kFatal) {
const char *toprint = buf; // Work around for older platform where we use TThreadTLSWrapper
bp = Form("%s (%s)", toprint, gSystem->GetError());
} else
bp = buf;
if (level != kFatal)
gErrorHandler(level, level >= gErrorAbortLevel, location, bp);
else
gErrorHandler(level, kTRUE, location, bp);
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in abstract base classes in case one does
/// not want to make the class a "real" (in C++ sense) ABC. If this
/// function is called it will warn the user that the function should
/// have been overridden.
void AbstractMethod(const char *method)
{
Warning(method, "this method must be overridden!");
}
////////////////////////////////////////////////////////////////////////////////
/// This function can be used in classes that should override a certain
/// function, but in the inherited class the function makes no sense.
void MayNotUse(const char *method)
{
Warning(method, "may not use this method");
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function to declare a function obsolete. Specify as of which version
/// the method is obsolete and as from which version it will be removed.
void Obsolete(const char *function, const char *asOfVers, const char *removedFromVers)
{
Warning(function, "obsolete as of %s and will be removed from %s", asOfVers, removedFromVers);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Error(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kError, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case a system (OS or GUI) related error occurred.
void SysError(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap, va_(fmt));
ErrorHandler(kSysError, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case an error occurred.
void Break(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kBreak, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function for informational messages.
void Info(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kInfo, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in warning situations.
void Warning(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kWarning, location, va_(fmt), ap);
va_end(ap);
}
////////////////////////////////////////////////////////////////////////////////
/// Use this function in case of a fatal error. It will abort the program.
// Fatal() *might* not abort the program (if gAbortLevel > kFatal) - but for all
// reasonable settings it *will* abort. So let's be reasonable wrt Coverity:
// coverity[+kill]
void Fatal(const char *location, const char *va_(fmt), ...)
{
va_list ap;
va_start(ap,va_(fmt));
ErrorHandler(kFatal, location, va_(fmt), ap);
va_end(ap);
}
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <memory>
#include "pugixml.hpp"
#include "core/angle.hpp"
#include "core/angular_quadrature.hpp"
#include "core/core_mesh.hpp"
#include "core/geom.hpp"
#include "ray.hpp"
namespace mocc { namespace moc {
enum VolumeCorrection {
FLAT,
ANGLE
};
/**
* The \ref RayData class is a collection of \ref Ray objects, organized by
* plane, then by angle. Rays are traced only for the set of
* geometrically-unique planes as determined by the \ref CoreMesh object used
* to construct a \ref RayData object. Since the rays are only intended for
* use in a 2-D MoC sweeper, only the first two octants are treated, with
* octants 3 and 4 being treated by sweeping the rays backwards.
*
* Boundary condition indexing is set up to be conformant with corresponding
* instances of \ref BoundaryCondition objects. The \ref BoundaryCondition
* class handles boundary values on a surface-by-surface basis, and therefore
* \ref Ray ends indexed in such a way to correspond to the appropriate faces
* on the \ref BoundaryBondition. Since the \ref BoundaryCondition stores all
* boundary values for a given angle contiguously in the X_NORM, Y_NORM,
* Z_NORM order, the ray indices should look like this:
*
* \verbatim
+- 4-- 5-- 6-- 7-- 8-- 9--10--11-+
| |
3 3
| |
2 2
| |
1 1
| |
0 0
| |
+- 4-- 5-- 6-- 7-- 8-- 9--10--11-+ \endverbatim
*
*/
class RayData {
/**
* A set of planes of \ref Ray
*/
typedef std::vector< std::vector<Ray> > PlaneRays_t;
typedef std::vector< PlaneRays_t > RaySet_t;
public:
RayData( const pugi::xml_node &input,
const AngularQuadrature &ang_quad,
const CoreMesh &mesh );
/**
* Iterator to the beginning of the ray data (by plane)
*/
RaySet_t::const_iterator begin() const {
return rays_.cbegin();
}
/**
* Iterator to the end of the ray data (by plane)
*/
RaySet_t::const_iterator end() const {
return rays_.cend();
}
/**
* Return a const reference to the angular quadrature.
*
* The internal \ref AngularQuadrature is a modularized form of the one
* passed in at construction time, and it is often necessary to retrieve
* this modularized quadrature.
*/
const AngularQuadrature &ang_quad() const {
return ang_quad_;
}
/**
* Return the number of rays for the given angle index
*/
size_t n_rays( size_t iang ) const {
return Nrays_[iang];
}
/**
* Return the number of rays impingent on the y-normal faces of the
* domain for the given angle
*/
size_t nx( size_t iang ) const {
return Nx_[iang];
}
/**
* Return the number of rays impingent on the x-normal faces of the
* domain for the given angle
*/
size_t ny( size_t iang ) const {
return Ny_[iang];
}
/**
* Return the ray spacing for the given angle
*/
real_t spacing( int iang ) const {
return spacing_[iang];
}
/**
* Return the maximum number of segments spanned by any \ref Ray in the
* collection. This is useful for defining the size of the scratch
* space for MoC.
*/
int max_segments() const {
return max_seg_;
}
/**
* Provide stream insertion support.
*/
friend std::ostream& operator<<( std::ostream &os,
const RayData &rays );
/**
* \brief Return a const reference to the indexed set of plane rays.
*/
const PlaneRays_t& operator[]( size_t id ) const {
return rays_[id];
}
private:
// This starts as a copy of the angular quadrature that is passed in
AngularQuadrature ang_quad_;
// Vector of ray sets. The outer-most vector indexes the
// geometrically-unique planes, the second index addresses the
// individual angles, which span octants 1 and 2, and the last index
// treats all of the rays for the given plane and angle.
RaySet_t rays_;
// Ray spacings for each angle. These vary from those specified due to
// modularization
VecF spacing_;
// Number of rays lying on the y-normal face of the core for each angle
VecI Nx_;
// Number of rays lying on the x-normal face of the core for each angle
VecI Ny_;
// Total number of rays for a given angle
VecI Nrays_;
// Number of planes that we have ray data for. This is copied from
// n_unique_planes() on the CoreMesh used to initialize the ray data.
size_t n_planes_;
// Maximum number of ray segments in a single ray
int max_seg_;
/**
* Perform a volume-correction of the ray segment lengths. This can be
* done in two ways: using an angular integral of the ray volumes, or
* using an angle-wise correction, which ensures that for each angle,
* the ray segment volumes reproduce the region volumes. The first way
* is technically more correct, however the latter is useful for
* debugging purposes sometimes.
*/
void correct_volume( const CoreMesh& mesh, VolumeCorrection type );
};
typedef std::shared_ptr<RayData> SP_RayData_t;
} }
<commit_msg>Fix typo in docs<commit_after>#pragma once
#include <vector>
#include <memory>
#include "pugixml.hpp"
#include "core/angle.hpp"
#include "core/angular_quadrature.hpp"
#include "core/core_mesh.hpp"
#include "core/geom.hpp"
#include "ray.hpp"
namespace mocc { namespace moc {
enum VolumeCorrection {
FLAT,
ANGLE
};
/**
* The \ref RayData class is a collection of \ref Ray objects, organized by
* plane, then by angle. Rays are traced only for the set of
* geometrically-unique planes as determined by the \ref CoreMesh object used
* to construct a \ref RayData object. Since the rays are only intended for
* use in a 2-D MoC sweeper, only the first two octants are treated, with
* octants 3 and 4 being treated by sweeping the rays backwards.
*
* Boundary condition indexing is set up to be conformant with corresponding
* instances of \ref BoundaryCondition objects. The \ref BoundaryCondition
* class handles boundary values on a surface-by-surface basis, and therefore
* \ref Ray ends indexed in such a way to correspond to the appropriate faces
* on the \ref BoundaryCondition. Since the \ref BoundaryCondition stores all
* boundary values for a given angle contiguously in the X_NORM, Y_NORM,
* Z_NORM order, the ray indices should look like this:
*
* \verbatim
+- 4-- 5-- 6-- 7-- 8-- 9--10--11-+
| |
3 3
| |
2 2
| |
1 1
| |
0 0
| |
+- 4-- 5-- 6-- 7-- 8-- 9--10--11-+ \endverbatim
*
*/
class RayData {
/**
* A set of planes of \ref Ray
*/
typedef std::vector< std::vector<Ray> > PlaneRays_t;
typedef std::vector< PlaneRays_t > RaySet_t;
public:
RayData( const pugi::xml_node &input,
const AngularQuadrature &ang_quad,
const CoreMesh &mesh );
/**
* Iterator to the beginning of the ray data (by plane)
*/
RaySet_t::const_iterator begin() const {
return rays_.cbegin();
}
/**
* Iterator to the end of the ray data (by plane)
*/
RaySet_t::const_iterator end() const {
return rays_.cend();
}
/**
* Return a const reference to the angular quadrature.
*
* The internal \ref AngularQuadrature is a modularized form of the one
* passed in at construction time, and it is often necessary to retrieve
* this modularized quadrature.
*/
const AngularQuadrature &ang_quad() const {
return ang_quad_;
}
/**
* Return the number of rays for the given angle index
*/
size_t n_rays( size_t iang ) const {
return Nrays_[iang];
}
/**
* Return the number of rays impingent on the y-normal faces of the
* domain for the given angle
*/
size_t nx( size_t iang ) const {
return Nx_[iang];
}
/**
* Return the number of rays impingent on the x-normal faces of the
* domain for the given angle
*/
size_t ny( size_t iang ) const {
return Ny_[iang];
}
/**
* Return the ray spacing for the given angle
*/
real_t spacing( int iang ) const {
return spacing_[iang];
}
/**
* Return the maximum number of segments spanned by any \ref Ray in the
* collection. This is useful for defining the size of the scratch
* space for MoC.
*/
int max_segments() const {
return max_seg_;
}
/**
* Provide stream insertion support.
*/
friend std::ostream& operator<<( std::ostream &os,
const RayData &rays );
/**
* \brief Return a const reference to the indexed set of plane rays.
*/
const PlaneRays_t& operator[]( size_t id ) const {
return rays_[id];
}
private:
// This starts as a copy of the angular quadrature that is passed in
AngularQuadrature ang_quad_;
// Vector of ray sets. The outer-most vector indexes the
// geometrically-unique planes, the second index addresses the
// individual angles, which span octants 1 and 2, and the last index
// treats all of the rays for the given plane and angle.
RaySet_t rays_;
// Ray spacings for each angle. These vary from those specified due to
// modularization
VecF spacing_;
// Number of rays lying on the y-normal face of the core for each angle
VecI Nx_;
// Number of rays lying on the x-normal face of the core for each angle
VecI Ny_;
// Total number of rays for a given angle
VecI Nrays_;
// Number of planes that we have ray data for. This is copied from
// n_unique_planes() on the CoreMesh used to initialize the ray data.
size_t n_planes_;
// Maximum number of ray segments in a single ray
int max_seg_;
/**
* Perform a volume-correction of the ray segment lengths. This can be
* done in two ways: using an angular integral of the ray volumes, or
* using an angle-wise correction, which ensures that for each angle,
* the ray segment volumes reproduce the region volumes. The first way
* is technically more correct, however the latter is useful for
* debugging purposes sometimes.
*/
void correct_volume( const CoreMesh& mesh, VolumeCorrection type );
};
typedef std::shared_ptr<RayData> SP_RayData_t;
} }
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <coins.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <primitives/transaction.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/rbf.h>
#include <validation.h>
#include <version.h>
#include <cassert>
void initialize()
{
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure&) {
return;
}
bool valid_tx = true;
const CTransaction tx = [&] {
try {
return CTransaction(deserialize, ds);
} catch (const std::ios_base::failure&) {
valid_tx = false;
return CTransaction();
}
}();
bool valid_mutable_tx = true;
CDataStream ds_mtx(buffer, SER_NETWORK, INIT_PROTO_VERSION);
CMutableTransaction mutable_tx;
try {
int nVersion;
ds_mtx >> nVersion;
ds_mtx.SetVersion(nVersion);
ds_mtx >> mutable_tx;
} catch (const std::ios_base::failure&) {
valid_mutable_tx = false;
}
assert(valid_tx == valid_mutable_tx);
if (!valid_tx) {
return;
}
TxValidationState state_with_dupe_check;
(void)CheckTransaction(tx, state_with_dupe_check);
const CFeeRate dust_relay_fee{DUST_RELAY_TX_FEE};
std::string reason;
const bool is_standard_with_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ true, dust_relay_fee, reason);
const bool is_standard_without_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ false, dust_relay_fee, reason);
if (is_standard_without_permit_bare_multisig) {
assert(is_standard_with_permit_bare_multisig);
}
(void)tx.GetHash();
(void)tx.GetTotalSize();
try {
(void)tx.GetValueOut();
} catch (const std::runtime_error&) {
}
(void)tx.GetWitnessHash();
(void)tx.HasWitness();
(void)tx.IsCoinBase();
(void)tx.IsNull();
(void)tx.ToString();
(void)EncodeHexTx(tx);
(void)GetLegacySigOpCount(tx);
(void)GetTransactionWeight(tx);
(void)GetVirtualTransactionSize(tx);
(void)IsFinalTx(tx, /* nBlockHeight= */ 1024, /* nBlockTime= */ 1024);
(void)IsStandardTx(tx, reason);
(void)RecursiveDynamicUsage(tx);
(void)SignalsOptInRBF(tx);
CCoinsView coins_view;
const CCoinsViewCache coins_view_cache(&coins_view);
(void)AreInputsStandard(tx, coins_view_cache);
(void)IsWitnessStandard(tx, coins_view_cache);
UniValue u(UniValue::VOBJ);
// ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min()
bool skip_tx_to_univ = false;
for (const CTxOut& txout : tx.vout) {
if (txout.nValue == std::numeric_limits<int64_t>::min()) {
skip_tx_to_univ = true;
}
}
if (!skip_tx_to_univ) {
TxToUniv(tx, /* hashBlock */ {}, u);
}
}
<commit_msg>tests: Fuzz currently uncovered code path in TxToUniv(...)<commit_after>// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <coins.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <primitives/transaction.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/rbf.h>
#include <validation.h>
#include <version.h>
#include <cassert>
void initialize()
{
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t>& buffer)
{
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure&) {
return;
}
bool valid_tx = true;
const CTransaction tx = [&] {
try {
return CTransaction(deserialize, ds);
} catch (const std::ios_base::failure&) {
valid_tx = false;
return CTransaction();
}
}();
bool valid_mutable_tx = true;
CDataStream ds_mtx(buffer, SER_NETWORK, INIT_PROTO_VERSION);
CMutableTransaction mutable_tx;
try {
int nVersion;
ds_mtx >> nVersion;
ds_mtx.SetVersion(nVersion);
ds_mtx >> mutable_tx;
} catch (const std::ios_base::failure&) {
valid_mutable_tx = false;
}
assert(valid_tx == valid_mutable_tx);
if (!valid_tx) {
return;
}
TxValidationState state_with_dupe_check;
(void)CheckTransaction(tx, state_with_dupe_check);
const CFeeRate dust_relay_fee{DUST_RELAY_TX_FEE};
std::string reason;
const bool is_standard_with_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ true, dust_relay_fee, reason);
const bool is_standard_without_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ false, dust_relay_fee, reason);
if (is_standard_without_permit_bare_multisig) {
assert(is_standard_with_permit_bare_multisig);
}
(void)tx.GetHash();
(void)tx.GetTotalSize();
try {
(void)tx.GetValueOut();
} catch (const std::runtime_error&) {
}
(void)tx.GetWitnessHash();
(void)tx.HasWitness();
(void)tx.IsCoinBase();
(void)tx.IsNull();
(void)tx.ToString();
(void)EncodeHexTx(tx);
(void)GetLegacySigOpCount(tx);
(void)GetTransactionWeight(tx);
(void)GetVirtualTransactionSize(tx);
(void)IsFinalTx(tx, /* nBlockHeight= */ 1024, /* nBlockTime= */ 1024);
(void)IsStandardTx(tx, reason);
(void)RecursiveDynamicUsage(tx);
(void)SignalsOptInRBF(tx);
CCoinsView coins_view;
const CCoinsViewCache coins_view_cache(&coins_view);
(void)AreInputsStandard(tx, coins_view_cache);
(void)IsWitnessStandard(tx, coins_view_cache);
UniValue u(UniValue::VOBJ);
// ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min()
bool skip_tx_to_univ = false;
for (const CTxOut& txout : tx.vout) {
if (txout.nValue == std::numeric_limits<int64_t>::min()) {
skip_tx_to_univ = true;
}
}
if (!skip_tx_to_univ) {
TxToUniv(tx, /* hashBlock */ {}, u);
static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
TxToUniv(tx, u256_max, u);
}
}
<|endoftext|> |
<commit_before>// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
#include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
#include <ostream> // NOLINT
#include <string>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
switch (fields.size()) {
case 0:
return "";
case 1:
return fields[0];
default:
std::string result = "(" + fields[0];
for (size_t i = 1; i < fields.size(); i++) {
result += ", ";
result += fields[i];
}
result += ")";
return result;
}
}
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
std::string result;
char prev_char = '\0';
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
// We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && result != "")
result += ' ';
result += ToLower(*p);
}
}
return result;
}
// This class reports Google Mock failures as Google Test failures. A
// user can define another class in a similar fashion if they intend to
// use Google Mock with a testing framework other than Google Test.
class GoogleTestFailureReporter : public FailureReporterInterface {
public:
void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
file,
line,
message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
}
};
// Returns the global failure reporter. Will create a
// GoogleTestFailureReporter and return it the first time called.
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
// Points to the global failure reporter used by Google Mock. gcc
// guarantees that the following use of failure_reporter is
// thread-safe. We may need to add additional synchronization to
// protect failure_reporter if we port Google Mock to other
// compilers.
static FailureReporterInterface* const failure_reporter =
new GoogleTestFailureReporter();
return failure_reporter;
}
// Protects global resources (stdout in particular) used by Log().
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info.
return true;
} else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
// Always hide it if --gmock_verbose=error.
return false;
} else {
// If --gmock_verbose is neither "info" nor "error", we treat it
// as "warning" (its default value).
return severity == kWarning;
}
}
// Prints the given message to stdout if and only if 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) {
if (!LogIsVisible(severity))
return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
std::cout << "\nGMOCK WARNING:";
}
// Pre-pends a new-line to message if it doesn't start with one.
if (message.empty() || message[0] != '\n') {
std::cout << "\n";
}
std::cout << message;
if (stack_frames_to_skip >= 0) {
#ifdef NDEBUG
// In opt mode, we have to be conservative and skip no stack frame.
const int actual_to_skip = 0;
#else
// In dbg mode, we can do what the caller tell us to do (plus one
// for skipping this function's stack frame).
const int actual_to_skip = stack_frames_to_skip + 1;
#endif // NDEBUG
// Appends a new-line to message if it doesn't end with one.
if (!message.empty() && *message.rbegin() != '\n') {
std::cout << "\n";
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
}
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c ? carry
: UnBase64Impl(c, base64 + 1, carry + 1);
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
const char* const base64) {
return {{UnBase64Impl(I, base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(MakeIndexSequence<256>{}, base64);
}
static constexpr char kBase64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
bool Base64Unescape(const std::string& encoded, std::string* decoded) {
decoded->clear();
size_t encoded_len = encoded.size();
decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
int bit_pos = 0;
char dst = 0;
for (int src : encoded) {
if (std::isspace(src) || src == '=') {
continue;
}
char src_bin = kUnBase64[src];
if (src_bin >= 64) {
decoded->clear();
return false;
}
if (bit_pos == 0) {
dst |= src_bin << 2;
bit_pos = 6;
} else {
dst |= static_cast<char>(src_bin >> (bit_pos - 2));
decoded->push_back(dst);
dst = static_cast<char>(src_bin << (10 - bit_pos));
bit_pos = (bit_pos + 6) % 8;
}
}
return true;
}
} // namespace internal
} // namespace testing
<commit_msg>Googletest export<commit_after>// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
#include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
#include <ostream> // NOLINT
#include <string>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
switch (fields.size()) {
case 0:
return "";
case 1:
return fields[0];
default:
std::string result = "(" + fields[0];
for (size_t i = 1; i < fields.size(); i++) {
result += ", ";
result += fields[i];
}
result += ")";
return result;
}
}
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
std::string result;
char prev_char = '\0';
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
// We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && result != "")
result += ' ';
result += ToLower(*p);
}
}
return result;
}
// This class reports Google Mock failures as Google Test failures. A
// user can define another class in a similar fashion if they intend to
// use Google Mock with a testing framework other than Google Test.
class GoogleTestFailureReporter : public FailureReporterInterface {
public:
void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) override {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
file,
line,
message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
}
};
// Returns the global failure reporter. Will create a
// GoogleTestFailureReporter and return it the first time called.
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
// Points to the global failure reporter used by Google Mock. gcc
// guarantees that the following use of failure_reporter is
// thread-safe. We may need to add additional synchronization to
// protect failure_reporter if we port Google Mock to other
// compilers.
static FailureReporterInterface* const failure_reporter =
new GoogleTestFailureReporter();
return failure_reporter;
}
// Protects global resources (stdout in particular) used by Log().
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
// Returns true if and only if a log with the given severity is visible
// according to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info.
return true;
} else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {
// Always hide it if --gmock_verbose=error.
return false;
} else {
// If --gmock_verbose is neither "info" nor "error", we treat it
// as "warning" (its default value).
return severity == kWarning;
}
}
// Prints the given message to stdout if and only if 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) {
if (!LogIsVisible(severity))
return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
std::cout << "\nGMOCK WARNING:";
}
// Pre-pends a new-line to message if it doesn't start with one.
if (message.empty() || message[0] != '\n') {
std::cout << "\n";
}
std::cout << message;
if (stack_frames_to_skip >= 0) {
#ifdef NDEBUG
// In opt mode, we have to be conservative and skip no stack frame.
const int actual_to_skip = 0;
#else
// In dbg mode, we can do what the caller tell us to do (plus one
// for skipping this function's stack frame).
const int actual_to_skip = stack_frames_to_skip + 1;
#endif // NDEBUG
// Appends a new-line to message if it doesn't end with one.
if (!message.empty() && *message.rbegin() != '\n') {
std::cout << "\n";
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
}
constexpr char UnBase64Impl(char c, const char* const base64, char carry) {
return *base64 == 0 ? static_cast<char>(65)
: *base64 == c ? carry
: UnBase64Impl(c, base64 + 1, carry + 1);
}
template <size_t... I>
constexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,
const char* const base64) {
return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};
}
constexpr std::array<char, 256> UnBase64(const char* const base64) {
return UnBase64Impl(MakeIndexSequence<256>{}, base64);
}
static constexpr char kBase64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);
bool Base64Unescape(const std::string& encoded, std::string* decoded) {
decoded->clear();
size_t encoded_len = encoded.size();
decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));
int bit_pos = 0;
char dst = 0;
for (int src : encoded) {
if (std::isspace(src) || src == '=') {
continue;
}
char src_bin = kUnBase64[static_cast<size_t>(src)];
if (src_bin >= 64) {
decoded->clear();
return false;
}
if (bit_pos == 0) {
dst |= src_bin << 2;
bit_pos = 6;
} else {
dst |= static_cast<char>(src_bin >> (bit_pos - 2));
decoded->push_back(dst);
dst = static_cast<char>(src_bin << (10 - bit_pos));
bit_pos = (bit_pos + 6) % 8;
}
}
return true;
}
} // namespace internal
} // namespace testing
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTED_OPTIONS_HPP
#define ROUTED_OPTIONS_HPP
#include "util/version.hpp"
#include "ini_file.hpp"
#include "osrm_exception.hpp"
#include "simple_logger.hpp"
#include <boost/any.hpp>
#include <boost/program_options.hpp>
#include <unordered_map>
#include <fstream>
#include <string>
const static unsigned INIT_OK_START_ENGINE = 0;
const static unsigned INIT_OK_DO_NOT_START_ENGINE = 1;
const static unsigned INIT_FAILED = -1;
inline void populate_base_path(std::unordered_map<std::string, boost::filesystem::path> &server_paths)
{
// populate the server_path object
auto path_iterator = server_paths.find("base");
// if a base path has been set, we populate it.
if (path_iterator != server_paths.end())
{
const std::string base_string = path_iterator->second.string();
SimpleLogger().Write() << "populating base path: " << base_string;
server_paths["hsgrdata"] = base_string + ".hsgr";
BOOST_ASSERT(server_paths.find("hsgrdata") != server_paths.end());
server_paths["nodesdata"] = base_string + ".nodes";
BOOST_ASSERT(server_paths.find("nodesdata") != server_paths.end());
server_paths["coredata"] = base_string + ".core";
BOOST_ASSERT(server_paths.find("coredata") != server_paths.end());
server_paths["edgesdata"] = base_string + ".edges";
BOOST_ASSERT(server_paths.find("edgesdata") != server_paths.end());
server_paths["geometries"] = base_string + ".geometry";
BOOST_ASSERT(server_paths.find("geometries") != server_paths.end());
server_paths["ramindex"] = base_string + ".ramIndex";
BOOST_ASSERT(server_paths.find("ramindex") != server_paths.end());
server_paths["fileindex"] = base_string + ".fileIndex";
BOOST_ASSERT(server_paths.find("fileindex") != server_paths.end());
server_paths["namesdata"] = base_string + ".names";
BOOST_ASSERT(server_paths.find("namesdata") != server_paths.end());
server_paths["timestamp"] = base_string + ".timestamp";
BOOST_ASSERT(server_paths.find("timestamp") != server_paths.end());
}
// check if files are give and whether they exist at all
path_iterator = server_paths.find("hsgrdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".hsgr not found");
}
path_iterator = server_paths.find("nodesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".nodes not found");
}
path_iterator = server_paths.find("edgesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".edges not found");
}
path_iterator = server_paths.find("geometries");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".geometry not found");
}
path_iterator = server_paths.find("ramindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".ramIndex not found");
}
path_iterator = server_paths.find("fileindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".fileIndex not found");
}
path_iterator = server_paths.find("namesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".namesIndex not found");
}
SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
}
// generate boost::program_options object for the routing part
inline unsigned GenerateServerProgramOptions(const int argc,
const char *argv[],
std::unordered_map<std::string, boost::filesystem::path> &paths,
std::string &ip_address,
int &ip_port,
int &requested_num_threads,
bool &use_shared_memory,
bool &trial,
int &max_locations_distance_table,
int &max_locations_map_matching)
{
// declare a group of options that will be allowed only on command line
boost::program_options::options_description generic_options("Options");
generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")(
"config,c", boost::program_options::value<boost::filesystem::path>(&paths["config"])
->default_value("server.ini"),
"Path to a configuration file")(
"trial", boost::program_options::value<bool>(&trial)->implicit_value(true),
"Quit after initialization");
// declare a group of options that will be allowed both on command line
// as well as in a config file
boost::program_options::options_description config_options("Configuration");
config_options.add_options()(
"hsgrdata", boost::program_options::value<boost::filesystem::path>(&paths["hsgrdata"]),
".hsgr file")("nodesdata",
boost::program_options::value<boost::filesystem::path>(&paths["nodesdata"]),
".nodes file")(
"edgesdata", boost::program_options::value<boost::filesystem::path>(&paths["edgesdata"]),
".edges file")("geometry",
boost::program_options::value<boost::filesystem::path>(&paths["geometries"]),
".geometry file")(
"ramindex", boost::program_options::value<boost::filesystem::path>(&paths["ramindex"]),
".ramIndex file")(
"fileindex", boost::program_options::value<boost::filesystem::path>(&paths["fileindex"]),
"File index file")(
"namesdata", boost::program_options::value<boost::filesystem::path>(&paths["namesdata"]),
".names file")("timestamp",
boost::program_options::value<boost::filesystem::path>(&paths["timestamp"]),
".timestamp file")(
"ip,i", boost::program_options::value<std::string>(&ip_address)->default_value("0.0.0.0"),
"IP address")("port,p", boost::program_options::value<int>(&ip_port)->default_value(5000),
"TCP/IP port")(
"threads,t", boost::program_options::value<int>(&requested_num_threads)->default_value(8),
"Number of threads to use")(
"shared-memory,s",
boost::program_options::value<bool>(&use_shared_memory)->implicit_value(true)->default_value(false),
"Load data from shared memory")(
"max-table-size",
boost::program_options::value<int>(&max_locations_distance_table)->default_value(100),
"Max. locations supported in distance table query")(
"max-matching-size",
boost::program_options::value<int>(&max_locations_map_matching)->default_value(100),
"Max. locations supported in map matching query");
// hidden options, will be allowed both on command line and in config
// file, but will not be shown to the user
boost::program_options::options_description hidden_options("Hidden options");
hidden_options.add_options()(
"base,b", boost::program_options::value<boost::filesystem::path>(&paths["base"]),
"base path to .osrm file");
// positional option
boost::program_options::positional_options_description positional_options;
positional_options.add("base", 1);
// combine above options for parsing
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic_options).add(config_options).add(hidden_options);
boost::program_options::options_description config_file_options;
config_file_options.add(config_options).add(hidden_options);
boost::program_options::options_description visible_options(
boost::filesystem::basename(argv[0]) + " <base.osrm> [<options>]");
visible_options.add(generic_options).add(config_options);
// parse command line options
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(positional_options)
.run(),
option_variables);
if (option_variables.count("version"))
{
SimpleLogger().Write() << OSRM_VERSION;
return INIT_OK_DO_NOT_START_ENGINE;
}
if (option_variables.count("help"))
{
SimpleLogger().Write() << visible_options;
return INIT_OK_DO_NOT_START_ENGINE;
}
boost::program_options::notify(option_variables);
// parse config file
auto path_iterator = paths.find("config");
if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) &&
!option_variables.count("base"))
{
SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string();
std::string ini_file_contents = read_file_lower_content(path_iterator->second);
std::stringstream config_stream(ini_file_contents);
boost::program_options::store(parse_config_file(config_stream, config_file_options),
option_variables);
boost::program_options::notify(option_variables);
return INIT_OK_START_ENGINE;
}
if (1 > requested_num_threads)
{
throw osrm::exception("Number of threads must be a positive number");
}
if (2 > max_locations_distance_table)
{
throw osrm::exception("Max location for distance table must be at least two");
}
if (2 > max_locations_map_matching)
{
throw osrm::exception("Max location for map matching must be at least two");
}
if (!use_shared_memory && option_variables.count("base"))
{
return INIT_OK_START_ENGINE;
}
else if (use_shared_memory && !option_variables.count("base"))
{
return INIT_OK_START_ENGINE;
}
else
{
SimpleLogger().Write(logWARNING) << "Shared memory settings conflict with path settings.";
}
SimpleLogger().Write() << visible_options;
return INIT_OK_DO_NOT_START_ENGINE;
}
#endif // ROUTED_OPTIONS_HPP
<commit_msg>Fix case when not specifing path or sharedmemory to osrm-routed<commit_after>/*
Copyright (c) 2015, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTED_OPTIONS_HPP
#define ROUTED_OPTIONS_HPP
#include "util/version.hpp"
#include "ini_file.hpp"
#include "osrm_exception.hpp"
#include "simple_logger.hpp"
#include <boost/any.hpp>
#include <boost/program_options.hpp>
#include <unordered_map>
#include <fstream>
#include <string>
const static unsigned INIT_OK_START_ENGINE = 0;
const static unsigned INIT_OK_DO_NOT_START_ENGINE = 1;
const static unsigned INIT_FAILED = -1;
inline void populate_base_path(std::unordered_map<std::string, boost::filesystem::path> &server_paths)
{
// populate the server_path object
auto path_iterator = server_paths.find("base");
// if a base path has been set, we populate it.
if (path_iterator != server_paths.end())
{
const std::string base_string = path_iterator->second.string();
SimpleLogger().Write() << "populating base path: " << base_string;
server_paths["hsgrdata"] = base_string + ".hsgr";
BOOST_ASSERT(server_paths.find("hsgrdata") != server_paths.end());
server_paths["nodesdata"] = base_string + ".nodes";
BOOST_ASSERT(server_paths.find("nodesdata") != server_paths.end());
server_paths["coredata"] = base_string + ".core";
BOOST_ASSERT(server_paths.find("coredata") != server_paths.end());
server_paths["edgesdata"] = base_string + ".edges";
BOOST_ASSERT(server_paths.find("edgesdata") != server_paths.end());
server_paths["geometries"] = base_string + ".geometry";
BOOST_ASSERT(server_paths.find("geometries") != server_paths.end());
server_paths["ramindex"] = base_string + ".ramIndex";
BOOST_ASSERT(server_paths.find("ramindex") != server_paths.end());
server_paths["fileindex"] = base_string + ".fileIndex";
BOOST_ASSERT(server_paths.find("fileindex") != server_paths.end());
server_paths["namesdata"] = base_string + ".names";
BOOST_ASSERT(server_paths.find("namesdata") != server_paths.end());
server_paths["timestamp"] = base_string + ".timestamp";
BOOST_ASSERT(server_paths.find("timestamp") != server_paths.end());
}
// check if files are give and whether they exist at all
path_iterator = server_paths.find("hsgrdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".hsgr not found");
}
path_iterator = server_paths.find("nodesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".nodes not found");
}
path_iterator = server_paths.find("edgesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".edges not found");
}
path_iterator = server_paths.find("geometries");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".geometry not found");
}
path_iterator = server_paths.find("ramindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".ramIndex not found");
}
path_iterator = server_paths.find("fileindex");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".fileIndex not found");
}
path_iterator = server_paths.find("namesdata");
if (path_iterator == server_paths.end() ||
!boost::filesystem::is_regular_file(path_iterator->second))
{
throw osrm::exception(".namesIndex not found");
}
SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"];
SimpleLogger().Write(logDEBUG) << "Nodes file:\t" << server_paths["nodesdata"];
SimpleLogger().Write(logDEBUG) << "Edges file:\t" << server_paths["edgesdata"];
SimpleLogger().Write(logDEBUG) << "Geometry file:\t" << server_paths["geometries"];
SimpleLogger().Write(logDEBUG) << "RAM file:\t" << server_paths["ramindex"];
SimpleLogger().Write(logDEBUG) << "Index file:\t" << server_paths["fileindex"];
SimpleLogger().Write(logDEBUG) << "Names file:\t" << server_paths["namesdata"];
SimpleLogger().Write(logDEBUG) << "Timestamp file:\t" << server_paths["timestamp"];
}
// generate boost::program_options object for the routing part
inline unsigned GenerateServerProgramOptions(const int argc,
const char *argv[],
std::unordered_map<std::string, boost::filesystem::path> &paths,
std::string &ip_address,
int &ip_port,
int &requested_num_threads,
bool &use_shared_memory,
bool &trial,
int &max_locations_distance_table,
int &max_locations_map_matching)
{
// declare a group of options that will be allowed only on command line
boost::program_options::options_description generic_options("Options");
generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")(
"config,c", boost::program_options::value<boost::filesystem::path>(&paths["config"])
->default_value("server.ini"),
"Path to a configuration file")(
"trial", boost::program_options::value<bool>(&trial)->implicit_value(true),
"Quit after initialization");
// declare a group of options that will be allowed both on command line
// as well as in a config file
boost::program_options::options_description config_options("Configuration");
config_options.add_options()(
"hsgrdata", boost::program_options::value<boost::filesystem::path>(&paths["hsgrdata"]),
".hsgr file")("nodesdata",
boost::program_options::value<boost::filesystem::path>(&paths["nodesdata"]),
".nodes file")(
"edgesdata", boost::program_options::value<boost::filesystem::path>(&paths["edgesdata"]),
".edges file")("geometry",
boost::program_options::value<boost::filesystem::path>(&paths["geometries"]),
".geometry file")(
"ramindex", boost::program_options::value<boost::filesystem::path>(&paths["ramindex"]),
".ramIndex file")(
"fileindex", boost::program_options::value<boost::filesystem::path>(&paths["fileindex"]),
"File index file")(
"namesdata", boost::program_options::value<boost::filesystem::path>(&paths["namesdata"]),
".names file")("timestamp",
boost::program_options::value<boost::filesystem::path>(&paths["timestamp"]),
".timestamp file")(
"ip,i", boost::program_options::value<std::string>(&ip_address)->default_value("0.0.0.0"),
"IP address")("port,p", boost::program_options::value<int>(&ip_port)->default_value(5000),
"TCP/IP port")(
"threads,t", boost::program_options::value<int>(&requested_num_threads)->default_value(8),
"Number of threads to use")(
"shared-memory,s",
boost::program_options::value<bool>(&use_shared_memory)->implicit_value(true)->default_value(false),
"Load data from shared memory")(
"max-table-size",
boost::program_options::value<int>(&max_locations_distance_table)->default_value(100),
"Max. locations supported in distance table query")(
"max-matching-size",
boost::program_options::value<int>(&max_locations_map_matching)->default_value(100),
"Max. locations supported in map matching query");
// hidden options, will be allowed both on command line and in config
// file, but will not be shown to the user
boost::program_options::options_description hidden_options("Hidden options");
hidden_options.add_options()(
"base,b", boost::program_options::value<boost::filesystem::path>(&paths["base"]),
"base path to .osrm file");
// positional option
boost::program_options::positional_options_description positional_options;
positional_options.add("base", 1);
// combine above options for parsing
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic_options).add(config_options).add(hidden_options);
boost::program_options::options_description config_file_options;
config_file_options.add(config_options).add(hidden_options);
boost::program_options::options_description visible_options(
boost::filesystem::basename(argv[0]) + " <base.osrm> [<options>]");
visible_options.add(generic_options).add(config_options);
// parse command line options
boost::program_options::variables_map option_variables;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
.options(cmdline_options)
.positional(positional_options)
.run(),
option_variables);
if (option_variables.count("version"))
{
SimpleLogger().Write() << OSRM_VERSION;
return INIT_OK_DO_NOT_START_ENGINE;
}
if (option_variables.count("help"))
{
SimpleLogger().Write() << visible_options;
return INIT_OK_DO_NOT_START_ENGINE;
}
boost::program_options::notify(option_variables);
// parse config file
auto path_iterator = paths.find("config");
if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) &&
!option_variables.count("base"))
{
SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string();
std::string ini_file_contents = read_file_lower_content(path_iterator->second);
std::stringstream config_stream(ini_file_contents);
boost::program_options::store(parse_config_file(config_stream, config_file_options),
option_variables);
boost::program_options::notify(option_variables);
return INIT_OK_START_ENGINE;
}
if (1 > requested_num_threads)
{
throw osrm::exception("Number of threads must be a positive number");
}
if (2 > max_locations_distance_table)
{
throw osrm::exception("Max location for distance table must be at least two");
}
if (2 > max_locations_map_matching)
{
throw osrm::exception("Max location for map matching must be at least two");
}
if (!use_shared_memory && option_variables.count("base"))
{
return INIT_OK_START_ENGINE;
}
else if (use_shared_memory && !option_variables.count("base"))
{
return INIT_OK_START_ENGINE;
}
else if (use_shared_memory && option_variables.count("base"))
{
SimpleLogger().Write(logWARNING) << "Shared memory settings conflict with path settings.";
}
SimpleLogger().Write() << visible_options;
return INIT_OK_DO_NOT_START_ENGINE;
}
#endif // ROUTED_OPTIONS_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*/
#include "badgeplugin.h"
#include "badgedelegate.h"
#include "treewidget.h"
#include "treeitem.h"
#include "treerole.h"
#include <QHeaderView>
#include <IrcMessage>
#include <IrcBuffer>
#include <QTimer>
#include <QEvent>
BadgePlugin::BadgePlugin(QObject* parent) : QObject(parent)
{
d.tree = 0;
d.block = false;
}
void BadgePlugin::initialize(TreeWidget* tree)
{
d.tree = tree;
d.tree->setColumnCount(2);
d.tree->setItemDelegateForColumn(1, new BadgeDelegate(this));
d.tree->installEventFilter(this);
QHeaderView* header = tree->header();
header->setStretchLastSection(false);
header->setResizeMode(0, QHeaderView::Stretch);
header->setResizeMode(1, QHeaderView::Fixed);
header->resizeSection(1, tree->fontMetrics().width("999"));
connect(tree, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(onBufferAdded(IrcBuffer*)));
connect(tree, SIGNAL(bufferRemoved(IrcBuffer*)), this, SLOT(onBufferRemoved(IrcBuffer*)));
connect(tree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
}
bool BadgePlugin::eventFilter(QObject* object, QEvent* event)
{
Q_UNUSED(object);
if (event->type() == QEvent::DynamicPropertyChange) {
bool block = d.tree->property("blockItemReset").toBool();
if (d.block != block) {
d.block = block;
QTreeWidgetItem* current = d.tree->currentItem();
if (!block && current)
delayedResetItem(current);
}
}
return false;
}
void BadgePlugin::onBufferAdded(IrcBuffer* buffer)
{
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void BadgePlugin::onBufferRemoved(IrcBuffer* buffer)
{
disconnect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void BadgePlugin::onMessageReceived(IrcMessage* message)
{
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
IrcBuffer* buffer = qobject_cast<IrcBuffer*>(sender());
TreeItem* item = d.tree->bufferItem(buffer);
if (item && item != d.tree->currentItem())
item->setData(1, TreeRole::Badge, item->data(1, TreeRole::Badge).toInt() + 1);
}
}
void BadgePlugin::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (!d.block) {
if (previous)
resetItem(previous);
if (current)
delayedResetItem(current);
}
}
void BadgePlugin::resetItem(QTreeWidgetItem* item)
{
if (!item && !d.items.isEmpty())
item = d.items.dequeue();
if (item)
item->setData(1, TreeRole::Badge, 0);
}
void BadgePlugin::delayedResetItem(QTreeWidgetItem* item)
{
d.items.enqueue(static_cast<TreeItem*>(item));
QTimer::singleShot(500, this, SLOT(resetItem()));
}
#if QT_VERSION < 0x050000
Q_EXPORT_STATIC_PLUGIN(BadgePlugin)
#endif
<commit_msg>BadgePlugin: exclude "playback begin/end" messages<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*/
#include "badgeplugin.h"
#include "badgedelegate.h"
#include "treewidget.h"
#include "treeitem.h"
#include "treerole.h"
#include <QHeaderView>
#include <IrcMessage>
#include <IrcBuffer>
#include <QTimer>
#include <QEvent>
BadgePlugin::BadgePlugin(QObject* parent) : QObject(parent)
{
d.tree = 0;
d.block = false;
}
void BadgePlugin::initialize(TreeWidget* tree)
{
d.tree = tree;
d.tree->setColumnCount(2);
d.tree->setItemDelegateForColumn(1, new BadgeDelegate(this));
d.tree->installEventFilter(this);
QHeaderView* header = tree->header();
header->setStretchLastSection(false);
header->setResizeMode(0, QHeaderView::Stretch);
header->setResizeMode(1, QHeaderView::Fixed);
header->resizeSection(1, tree->fontMetrics().width("999"));
connect(tree, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(onBufferAdded(IrcBuffer*)));
connect(tree, SIGNAL(bufferRemoved(IrcBuffer*)), this, SLOT(onBufferRemoved(IrcBuffer*)));
connect(tree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
this, SLOT(onCurrentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
}
bool BadgePlugin::eventFilter(QObject* object, QEvent* event)
{
Q_UNUSED(object);
if (event->type() == QEvent::DynamicPropertyChange) {
bool block = d.tree->property("blockItemReset").toBool();
if (d.block != block) {
d.block = block;
QTreeWidgetItem* current = d.tree->currentItem();
if (!block && current)
delayedResetItem(current);
}
}
return false;
}
void BadgePlugin::onBufferAdded(IrcBuffer* buffer)
{
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void BadgePlugin::onBufferRemoved(IrcBuffer* buffer)
{
disconnect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(onMessageReceived(IrcMessage*)));
}
void BadgePlugin::onMessageReceived(IrcMessage* message)
{
if (message->type() == IrcMessage::Private || message->type() == IrcMessage::Notice) {
if (message->nick() != QLatin1String("***") || message->ident() != QLatin1String("znc")) {
IrcBuffer* buffer = qobject_cast<IrcBuffer*>(sender());
TreeItem* item = d.tree->bufferItem(buffer);
if (item && item != d.tree->currentItem())
item->setData(1, TreeRole::Badge, item->data(1, TreeRole::Badge).toInt() + 1);
}
}
}
void BadgePlugin::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (!d.block) {
if (previous)
resetItem(previous);
if (current)
delayedResetItem(current);
}
}
void BadgePlugin::resetItem(QTreeWidgetItem* item)
{
if (!item && !d.items.isEmpty())
item = d.items.dequeue();
if (item)
item->setData(1, TreeRole::Badge, 0);
}
void BadgePlugin::delayedResetItem(QTreeWidgetItem* item)
{
d.items.enqueue(static_cast<TreeItem*>(item));
QTimer::singleShot(500, this, SLOT(resetItem()));
}
#if QT_VERSION < 0x050000
Q_EXPORT_STATIC_PLUGIN(BadgePlugin)
#endif
<|endoftext|> |
<commit_before><commit_msg>set the correct url for vba unit test<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <concepts>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include "bytes.hh"
enum class mutable_view { no, yes, };
/// Fragmented buffer
///
/// Concept `FragmentedBuffer` is satisfied by any class that is a range of
/// fragments and provides a method `size_bytes()` which returns the total
/// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt
/// to avoid unnecessary linearisation.
template<typename T>
concept FragmentRange = requires (T range) {
typename T::fragment_type;
requires std::is_same_v<typename T::fragment_type, bytes_view>
|| std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
{ *range.begin() } -> std::convertible_to<const typename T::fragment_type&>;
{ *range.end() } -> std::convertible_to<const typename T::fragment_type&>;
{ range.size_bytes() } -> std::convertible_to<size_t>;
{ range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0.
};
template<typename T, typename = void>
struct is_fragment_range : std::false_type { };
template<typename T>
struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { };
template<typename T>
static constexpr bool is_fragment_range_v = is_fragment_range<T>::value;
/// A non-mutable view of a FragmentRange
///
/// Provide a trivially copyable and movable, non-mutable view on a
/// fragment range. This allows uniform ownership semantics across
/// multi-fragment ranges and the single fragment and empty fragment
/// adaptors below, i.e. it allows treating all fragment ranges
/// uniformly as views.
template <typename T>
requires FragmentRange<T>
class fragment_range_view {
const T* _range;
public:
using fragment_type = typename T::fragment_type;
using iterator = typename T::const_iterator;
using const_iterator = typename T::const_iterator;
public:
explicit fragment_range_view(const T& range) : _range(&range) { }
const_iterator begin() const { return _range->begin(); }
const_iterator end() const { return _range->end(); }
size_t size_bytes() const { return _range->size_bytes(); }
bool empty() const { return _range->empty(); }
};
/// Single-element fragment range
///
/// This is a helper that allows converting a bytes_view into a FragmentRange.
template<mutable_view is_mutable>
class single_fragment_range {
public:
using fragment_type = std::conditional_t<is_mutable == mutable_view::no,
bytes_view, bytes_mutable_view>;
private:
fragment_type _view;
public:
using iterator = const fragment_type*;
using const_iterator = const fragment_type*;
explicit single_fragment_range(fragment_type f) : _view { f } { }
const_iterator begin() const { return &_view; }
const_iterator end() const { return &_view + 1; }
size_t size_bytes() const { return _view.size(); }
bool empty() const { return _view.empty(); }
};
single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>;
single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>;
/// Empty fragment range.
struct empty_fragment_range {
using fragment_type = bytes_view;
using iterator = bytes_view*;
using const_iterator = bytes_view*;
iterator begin() const { return nullptr; }
iterator end() const { return nullptr; }
size_t size_bytes() const { return 0; }
bool empty() const { return true; }
};
static_assert(FragmentRange<empty_fragment_range>);
static_assert(FragmentRange<single_fragment_range<mutable_view::no>>);
static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>);
template<typename FragmentedBuffer>
requires FragmentRange<FragmentedBuffer>
bytes linearized(const FragmentedBuffer& buffer)
{
bytes b(bytes::initialized_later(), buffer.size_bytes());
auto dst = b.begin();
using boost::range::for_each;
for_each(buffer, [&] (bytes_view fragment) {
dst = boost::copy(fragment, dst);
});
return b;
}
template<typename FragmentedBuffer, typename Function>
requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) {
fn(bv);
}
decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn)
{
bytes b;
bytes_view bv;
if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) {
bv = *buffer.begin();
} else if (!buffer.empty()) {
b = linearized(buffer);
bv = b;
}
return fn(bv);
}
template<typename T>
concept FragmentedView = requires (T view, size_t n) {
typename T::fragment_type;
requires std::is_same_v<typename T::fragment_type, bytes_view>
|| std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
// No preconditions.
{ view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>;
// No preconditions.
{ view.size_bytes() } -> std::convertible_to<size_t>;
// Precondition: n <= size_bytes()
{ view.prefix(n) } -> std::same_as<T>;
// Precondition: n <= size_bytes()
view.remove_prefix(n);
// Precondition: size_bytes() > 0
view.remove_current();
};
template<typename T>
concept FragmentedMutableView = requires (T view) {
requires FragmentedView<T>;
requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
};
<commit_msg>utils: fragment_range: add linearized and with_linearized for FragmentedView<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <concepts>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include "bytes.hh"
enum class mutable_view { no, yes, };
/// Fragmented buffer
///
/// Concept `FragmentedBuffer` is satisfied by any class that is a range of
/// fragments and provides a method `size_bytes()` which returns the total
/// size of the buffer. The interfaces accepting `FragmentedBuffer` will attempt
/// to avoid unnecessary linearisation.
template<typename T>
concept FragmentRange = requires (T range) {
typename T::fragment_type;
requires std::is_same_v<typename T::fragment_type, bytes_view>
|| std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
{ *range.begin() } -> std::convertible_to<const typename T::fragment_type&>;
{ *range.end() } -> std::convertible_to<const typename T::fragment_type&>;
{ range.size_bytes() } -> std::convertible_to<size_t>;
{ range.empty() } -> std::same_as<bool>; // returns true iff size_bytes() == 0.
};
template<typename T, typename = void>
struct is_fragment_range : std::false_type { };
template<typename T>
struct is_fragment_range<T, std::void_t<typename T::fragment_type>> : std::true_type { };
template<typename T>
static constexpr bool is_fragment_range_v = is_fragment_range<T>::value;
/// A non-mutable view of a FragmentRange
///
/// Provide a trivially copyable and movable, non-mutable view on a
/// fragment range. This allows uniform ownership semantics across
/// multi-fragment ranges and the single fragment and empty fragment
/// adaptors below, i.e. it allows treating all fragment ranges
/// uniformly as views.
template <typename T>
requires FragmentRange<T>
class fragment_range_view {
const T* _range;
public:
using fragment_type = typename T::fragment_type;
using iterator = typename T::const_iterator;
using const_iterator = typename T::const_iterator;
public:
explicit fragment_range_view(const T& range) : _range(&range) { }
const_iterator begin() const { return _range->begin(); }
const_iterator end() const { return _range->end(); }
size_t size_bytes() const { return _range->size_bytes(); }
bool empty() const { return _range->empty(); }
};
/// Single-element fragment range
///
/// This is a helper that allows converting a bytes_view into a FragmentRange.
template<mutable_view is_mutable>
class single_fragment_range {
public:
using fragment_type = std::conditional_t<is_mutable == mutable_view::no,
bytes_view, bytes_mutable_view>;
private:
fragment_type _view;
public:
using iterator = const fragment_type*;
using const_iterator = const fragment_type*;
explicit single_fragment_range(fragment_type f) : _view { f } { }
const_iterator begin() const { return &_view; }
const_iterator end() const { return &_view + 1; }
size_t size_bytes() const { return _view.size(); }
bool empty() const { return _view.empty(); }
};
single_fragment_range(bytes_view) -> single_fragment_range<mutable_view::no>;
single_fragment_range(bytes_mutable_view) -> single_fragment_range<mutable_view::yes>;
/// Empty fragment range.
struct empty_fragment_range {
using fragment_type = bytes_view;
using iterator = bytes_view*;
using const_iterator = bytes_view*;
iterator begin() const { return nullptr; }
iterator end() const { return nullptr; }
size_t size_bytes() const { return 0; }
bool empty() const { return true; }
};
static_assert(FragmentRange<empty_fragment_range>);
static_assert(FragmentRange<single_fragment_range<mutable_view::no>>);
static_assert(FragmentRange<single_fragment_range<mutable_view::yes>>);
template<typename FragmentedBuffer>
requires FragmentRange<FragmentedBuffer>
bytes linearized(const FragmentedBuffer& buffer)
{
bytes b(bytes::initialized_later(), buffer.size_bytes());
auto dst = b.begin();
using boost::range::for_each;
for_each(buffer, [&] (bytes_view fragment) {
dst = boost::copy(fragment, dst);
});
return b;
}
template<typename FragmentedBuffer, typename Function>
requires FragmentRange<FragmentedBuffer> && requires (Function fn, bytes_view bv) {
fn(bv);
}
decltype(auto) with_linearized(const FragmentedBuffer& buffer, Function&& fn)
{
bytes b;
bytes_view bv;
if (__builtin_expect(!buffer.empty() && std::next(buffer.begin()) == buffer.end(), true)) {
bv = *buffer.begin();
} else if (!buffer.empty()) {
b = linearized(buffer);
bv = b;
}
return fn(bv);
}
template<typename T>
concept FragmentedView = requires (T view, size_t n) {
typename T::fragment_type;
requires std::is_same_v<typename T::fragment_type, bytes_view>
|| std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
// No preconditions.
{ view.current_fragment() } -> std::convertible_to<const typename T::fragment_type&>;
// No preconditions.
{ view.size_bytes() } -> std::convertible_to<size_t>;
// Precondition: n <= size_bytes()
{ view.prefix(n) } -> std::same_as<T>;
// Precondition: n <= size_bytes()
view.remove_prefix(n);
// Precondition: size_bytes() > 0
view.remove_current();
};
template<typename T>
concept FragmentedMutableView = requires (T view) {
requires FragmentedView<T>;
requires std::is_same_v<typename T::fragment_type, bytes_mutable_view>;
};
template<FragmentedView View>
requires (!FragmentRange<View>)
bytes linearized(View v)
{
bytes b(bytes::initialized_later(), v.size_bytes());
auto out = b.begin();
while (v.size_bytes()) {
out = std::copy(v.current_fragment().begin(), v.current_fragment().end(), out);
v.remove_current();
}
return b;
}
template<FragmentedView View, typename Function>
requires (!FragmentRange<View>) && std::invocable<Function, bytes_view>
decltype(auto) with_linearized(const View& v, Function&& fn)
{
if (v.size_bytes() == v.current_fragment().size()) [[likely]] {
return fn(v.current_fragment());
} else {
return fn(linearized(v));
}
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* box_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "box_container.h"
#include "label.h"
#include "margin_container.h"
struct _MinSizeCache {
int min_size;
bool will_stretch;
int final_size;
};
void BoxContainer::_resort() {
/** First pass, determine minimum size AND amount of stretchable elements */
Size2i new_size = get_size();
int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
int children_count = 0;
int stretch_min = 0;
int stretch_avail = 0;
float stretch_ratio_total = 0;
Map<Control *, _MinSizeCache> min_size_cache;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
Size2i size = c->get_combined_minimum_size();
_MinSizeCache msc;
if (vertical) { /* VERTICAL */
stretch_min += size.height;
msc.min_size = size.height;
msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
} else { /* HORIZONTAL */
stretch_min += size.width;
msc.min_size = size.width;
msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND;
}
if (msc.will_stretch) {
stretch_avail += msc.min_size;
stretch_ratio_total += c->get_stretch_ratio();
}
msc.final_size = msc.min_size;
min_size_cache[c] = msc;
children_count++;
}
if (children_count == 0)
return;
int stretch_max = (vertical ? new_size.height : new_size.width) - (children_count - 1) * sep;
int stretch_diff = stretch_max - stretch_min;
if (stretch_diff < 0) {
//avoid negative stretch space
stretch_max = stretch_min;
stretch_diff = 0;
}
stretch_avail += stretch_diff; //available stretch space.
/** Second, pass sucessively to discard elements that can't be stretched, this will run while stretchable
elements exist */
bool has_stretched = false;
while (stretch_ratio_total > 0) { // first of all, don't even be here if no stretchable objects exist
has_stretched = true;
bool refit_successful = true; //assume refit-test will go well
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
ERR_FAIL_COND(!min_size_cache.has(c));
_MinSizeCache &msc = min_size_cache[c];
if (msc.will_stretch) { //wants to stretch
//let's see if it can really stretch
int final_pixel_size = stretch_avail * c->get_stretch_ratio() / stretch_ratio_total;
if (final_pixel_size < msc.min_size) {
//if available stretching area is too small for widget,
//then remove it from stretching area
msc.will_stretch = false;
stretch_ratio_total -= c->get_stretch_ratio();
refit_successful = false;
stretch_avail -= msc.min_size;
msc.final_size = msc.min_size;
break;
} else {
msc.final_size = final_pixel_size;
}
}
}
if (refit_successful) //uf refit went well, break
break;
}
/** Final pass, draw and stretch elements **/
int ofs = 0;
if (!has_stretched) {
switch (align) {
case ALIGN_BEGIN:
break;
case ALIGN_CENTER:
ofs = stretch_diff / 2;
break;
case ALIGN_END:
ofs = stretch_diff;
break;
}
}
first = true;
int idx = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
_MinSizeCache &msc = min_size_cache[c];
if (first)
first = false;
else
ofs += sep;
int from = ofs;
int to = ofs + msc.final_size;
if (msc.will_stretch && idx == children_count - 1) {
//adjust so the last one always fits perfect
//compensating for numerical imprecision
to = vertical ? new_size.height : new_size.width;
}
int size = to - from;
Rect2 rect;
if (vertical) {
rect = Rect2(0, from, new_size.width, size);
} else {
rect = Rect2(from, 0, size, new_size.height);
}
fit_child_in_rect(c, rect);
ofs = to;
idx++;
}
}
Size2 BoxContainer::get_minimum_size() const {
/* Calculate MINIMUM SIZE */
Size2i minimum;
int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
if (!c->is_visible()) {
continue;
}
Size2i size = c->get_combined_minimum_size();
if (vertical) { /* VERTICAL */
if (size.width > minimum.width) {
minimum.width = size.width;
}
minimum.height += size.height + (first ? 0 : sep);
} else { /* HORIZONTAL */
if (size.height > minimum.height) {
minimum.height = size.height;
}
minimum.width += size.width + (first ? 0 : sep);
}
first = false;
}
return minimum;
}
void BoxContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
}
}
void BoxContainer::set_alignment(AlignMode p_align) {
align = p_align;
_resort();
}
BoxContainer::AlignMode BoxContainer::get_alignment() const {
return align;
}
void BoxContainer::add_spacer(bool p_begin) {
Control *c = memnew(Control);
c->set_mouse_filter(MOUSE_FILTER_PASS); //allow spacer to pass mouse events
if (vertical)
c->set_v_size_flags(SIZE_EXPAND_FILL);
else
c->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(c);
if (p_begin)
move_child(c, 0);
}
BoxContainer::BoxContainer(bool p_vertical) {
vertical = p_vertical;
align = ALIGN_BEGIN;
//set_ignore_mouse(true);
set_mouse_filter(MOUSE_FILTER_PASS);
}
void BoxContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_spacer", "begin"), &BoxContainer::add_spacer);
ClassDB::bind_method(D_METHOD("get_alignment"), &BoxContainer::get_alignment);
ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &BoxContainer::set_alignment);
BIND_CONSTANT(ALIGN_BEGIN);
BIND_CONSTANT(ALIGN_CENTER);
BIND_CONSTANT(ALIGN_END);
ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment", "get_alignment");
}
MarginContainer *VBoxContainer::add_margin_child(const String &p_label, Control *p_control, bool p_expand) {
Label *l = memnew(Label);
l->set_text(p_label);
add_child(l);
MarginContainer *mc = memnew(MarginContainer);
mc->add_child(p_control);
add_child(mc);
if (p_expand)
mc->set_v_size_flags(SIZE_EXPAND_FILL);
return mc;
}
<commit_msg>Fit grid with label and component of editor<commit_after>/*************************************************************************/
/* box_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "box_container.h"
#include "label.h"
#include "margin_container.h"
struct _MinSizeCache {
int min_size;
bool will_stretch;
int final_size;
};
void BoxContainer::_resort() {
/** First pass, determine minimum size AND amount of stretchable elements */
Size2i new_size = get_size();
int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
int children_count = 0;
int stretch_min = 0;
int stretch_avail = 0;
float stretch_ratio_total = 0;
Map<Control *, _MinSizeCache> min_size_cache;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
Size2i size = c->get_combined_minimum_size();
_MinSizeCache msc;
if (vertical) { /* VERTICAL */
stretch_min += size.height;
msc.min_size = size.height;
msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
} else { /* HORIZONTAL */
stretch_min += size.width;
msc.min_size = size.width;
msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND;
}
if (msc.will_stretch) {
stretch_avail += msc.min_size;
stretch_ratio_total += c->get_stretch_ratio();
}
msc.final_size = msc.min_size;
min_size_cache[c] = msc;
children_count++;
}
if (children_count == 0)
return;
int stretch_max = (vertical ? new_size.height : new_size.width) - (children_count - 1) * sep;
int stretch_diff = stretch_max - stretch_min;
if (stretch_diff < 0) {
//avoid negative stretch space
stretch_max = stretch_min;
stretch_diff = 0;
}
stretch_avail += stretch_diff; //available stretch space.
/** Second, pass sucessively to discard elements that can't be stretched, this will run while stretchable
elements exist */
bool has_stretched = false;
while (stretch_ratio_total > 0) { // first of all, don't even be here if no stretchable objects exist
has_stretched = true;
bool refit_successful = true; //assume refit-test will go well
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
ERR_FAIL_COND(!min_size_cache.has(c));
_MinSizeCache &msc = min_size_cache[c];
if (msc.will_stretch) { //wants to stretch
//let's see if it can really stretch
int final_pixel_size = stretch_avail * c->get_stretch_ratio() / stretch_ratio_total;
if (final_pixel_size < msc.min_size) {
//if available stretching area is too small for widget,
//then remove it from stretching area
msc.will_stretch = false;
stretch_ratio_total -= c->get_stretch_ratio();
refit_successful = false;
stretch_avail -= msc.min_size;
msc.final_size = msc.min_size;
break;
} else {
msc.final_size = final_pixel_size;
}
}
}
if (refit_successful) //uf refit went well, break
break;
}
/** Final pass, draw and stretch elements **/
int ofs = 0;
if (!has_stretched) {
switch (align) {
case ALIGN_BEGIN:
break;
case ALIGN_CENTER:
ofs = stretch_diff / 2;
break;
case ALIGN_END:
ofs = stretch_diff;
break;
}
}
first = true;
int idx = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
_MinSizeCache &msc = min_size_cache[c];
if (first)
first = false;
else
ofs += sep;
int from = ofs;
int to = ofs + msc.final_size;
if (msc.will_stretch && idx == children_count - 1) {
//adjust so the last one always fits perfect
//compensating for numerical imprecision
to = vertical ? new_size.height : new_size.width;
}
int size = to - from;
Rect2 rect;
if (vertical) {
rect = Rect2(0, from, new_size.width, size);
} else {
rect = Rect2(from, 0, size, new_size.height);
}
fit_child_in_rect(c, rect);
ofs = to;
idx++;
}
}
Size2 BoxContainer::get_minimum_size() const {
/* Calculate MINIMUM SIZE */
Size2i minimum;
int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
bool first = true;
for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
if (!c->is_visible()) {
continue;
}
Size2i size = c->get_combined_minimum_size();
if (vertical) { /* VERTICAL */
if (size.width > minimum.width) {
minimum.width = size.width;
}
minimum.height += size.height + (first ? 0 : sep);
} else { /* HORIZONTAL */
if (size.height > minimum.height) {
minimum.height = size.height;
}
minimum.width += size.width + (first ? 0 : sep);
}
first = false;
}
return minimum;
}
void BoxContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
}
}
void BoxContainer::set_alignment(AlignMode p_align) {
align = p_align;
_resort();
}
BoxContainer::AlignMode BoxContainer::get_alignment() const {
return align;
}
void BoxContainer::add_spacer(bool p_begin) {
Control *c = memnew(Control);
c->set_mouse_filter(MOUSE_FILTER_PASS); //allow spacer to pass mouse events
if (vertical)
c->set_v_size_flags(SIZE_EXPAND_FILL);
else
c->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(c);
if (p_begin)
move_child(c, 0);
}
BoxContainer::BoxContainer(bool p_vertical) {
vertical = p_vertical;
align = ALIGN_BEGIN;
//set_ignore_mouse(true);
set_mouse_filter(MOUSE_FILTER_PASS);
}
void BoxContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_spacer", "begin"), &BoxContainer::add_spacer);
ClassDB::bind_method(D_METHOD("get_alignment"), &BoxContainer::get_alignment);
ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &BoxContainer::set_alignment);
BIND_CONSTANT(ALIGN_BEGIN);
BIND_CONSTANT(ALIGN_CENTER);
BIND_CONSTANT(ALIGN_END);
ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment", "get_alignment");
}
MarginContainer *VBoxContainer::add_margin_child(const String &p_label, Control *p_control, bool p_expand) {
Label *l = memnew(Label);
l->set_text(p_label);
add_child(l);
MarginContainer *mc = memnew(MarginContainer);
mc->add_constant_override("margin_left", 0);
mc->add_child(p_control);
add_child(mc);
if (p_expand)
mc->set_v_size_flags(SIZE_EXPAND_FILL);
return mc;
}
<|endoftext|> |
<commit_before>// Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extension/widget/widget.h"
#include <list>
#include <memory>
#include <map>
#include <vector>
#include "extension/xwalk/XW_Extension.h"
#include "extension/xwalk/XW_Extension_EntryPoints.h"
#include "extension/xwalk/XW_Extension_Permissions.h"
#include "extension/xwalk/XW_Extension_Runtime.h"
#include "extension/xwalk/XW_Extension_SyncMessage.h"
#include "common/logger.h"
#include "extension/widget/picojson.h"
#include "common/app_db.h"
#include "common/application_data.h"
#include "common/string_utils.h"
XW_Extension g_xw_extension = 0;
std::string g_appid;
std::unique_ptr<wrt::ApplicationData> g_appdata;
const XW_CoreInterface* g_core = NULL;
const XW_MessagingInterface* g_messaging = NULL;
const XW_Internal_SyncMessagingInterface* g_sync_messaging = NULL;
const XW_Internal_EntryPointsInterface* g_entry_points = NULL;
const XW_Internal_RuntimeInterface* g_runtime = NULL;
extern const char kSource_widget_api[];
typedef void (*CmdHandler)(const picojson::value& args, picojson::object* out);
static void InitHandler(const picojson::value& args, picojson::object* out);
static void KeyHandler(const picojson::value& args, picojson::object* out);
static void GetItemHandler(const picojson::value& args,
picojson::object* out);
static void LengthHandler(const picojson::value& args,
picojson::object* out);
static void ClearHandler(const picojson::value& args,
picojson::object* out);
static void SetItemHandler(const picojson::value& args,
picojson::object* out);
static void RemoveHandler(const picojson::value& args,
picojson::object* out);
std::map<std::string, CmdHandler> g_handler = {
{"init", InitHandler},
{"key", KeyHandler},
{"length", LengthHandler},
{"clear", ClearHandler},
{"getItem", GetItemHandler},
{"setItem", SetItemHandler},
{"removeItem", RemoveHandler},
};
static void HandleMessage(XW_Instance instance,
const char* message,
bool sync);
extern "C" int32_t XW_Initialize(XW_Extension extension,
XW_GetInterface get_interface) {
g_xw_extension = extension;
g_core = reinterpret_cast<const XW_CoreInterface*>(
get_interface(XW_CORE_INTERFACE));
if (!g_core) {
LOGGER(ERROR)
<< "Can't initialize extension: error getting Core interface.";
return -1;
}
g_messaging = reinterpret_cast<const XW_MessagingInterface*>(
get_interface(XW_MESSAGING_INTERFACE));
if (!g_messaging) {
LOGGER(ERROR)
<< "Can't initialize extension: error getting Messaging interface.";
return -1;
}
g_sync_messaging =
reinterpret_cast<const XW_Internal_SyncMessagingInterface*>(
get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE));
if (!g_sync_messaging) {
LOGGER(ERROR)
<< "Can't initialize extension: "
<< "error getting SyncMessaging interface.";
return -1;
}
g_entry_points = reinterpret_cast<const XW_Internal_EntryPointsInterface*>(
get_interface(XW_INTERNAL_ENTRY_POINTS_INTERFACE));
if (!g_entry_points) {
LOGGER(ERROR)
<< "NOTE: Entry points interface not available in this version "
<< "of Crosswalk, ignoring entry point data for extensions.\n";
return -1;
}
g_runtime = reinterpret_cast<const XW_Internal_RuntimeInterface*>(
get_interface(XW_INTERNAL_RUNTIME_INTERFACE));
if (!g_runtime) {
LOGGER(ERROR)
<< "NOTE: runtime interface not available in this version "
<< "of Crosswalk, ignoring runtime variables for extensions.\n";
return -1;
}
std::vector<char> res(256, 0);
g_runtime->GetRuntimeVariableString(extension, "app_id", &res[0], 256);
g_appid = std::string(res.begin(), res.end());
if (g_appid.at(0) == '"') {
g_appid = g_appid.substr(1, g_appid.size()-2);
}
g_core->RegisterInstanceCallbacks(
g_xw_extension,
[](XW_Instance instance){
if (g_appdata.get() == NULL) {
g_appdata.reset(new wrt::ApplicationData(g_appid));
}
wrt::Widget::GetInstance()->Initialize(g_appdata.get());
},
NULL);
g_messaging->Register(g_xw_extension, [](XW_Instance instance,
const char* message) {
HandleMessage(instance, message, false);
});
g_sync_messaging->Register(g_xw_extension, [](XW_Instance instance,
const char* message) {
HandleMessage(instance, message, true);
});
g_core->SetExtensionName(g_xw_extension, "Widget");
const char* entry_points[] = {"widget", NULL};
g_entry_points->SetExtraJSEntryPoints(g_xw_extension, entry_points);
g_core->SetJavaScriptAPI(g_xw_extension, kSource_widget_api);
}
static void InitHandler(const picojson::value& args, picojson::object* out) {
picojson::value result = picojson::value(picojson::object());
picojson::object& obj = result.get<picojson::object>();
auto widget_info = g_appdata->widget_info();
if (widget_info.get() == NULL) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
// TODO(sngn.lee): should be returned localized string
obj["author"] = picojson::value(widget_info->author());
obj["description"] = picojson::value(widget_info->description());
obj["name"] = picojson::value(widget_info->name());
obj["shortName"] = picojson::value(widget_info->short_name());
obj["version"] = picojson::value(widget_info->version());
obj["id"] = picojson::value(widget_info->id());
obj["authorEmail"] = picojson::value(widget_info->author_email());
obj["authorHref"] = picojson::value(widget_info->author_href());
obj["height"] = picojson::value(static_cast<double>(widget_info->height()));
obj["width"] = picojson::value(static_cast<double>(widget_info->width()));
out->insert(std::make_pair("result", result));
}
static void KeyHandler(const picojson::value& args, picojson::object* out) {
int idx = static_cast<int>(args.get("idx").get<double>());
std::string key;
if (!wrt::Widget::GetInstance()->Key(idx, &key)) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(std::make_pair("result", picojson::value(key)));
}
static void GetItemHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
std::string value;
if (!wrt::Widget::GetInstance()->GetItem(key, &value)) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(std::make_pair("result", picojson::value(value)));
}
static void LengthHandler(const picojson::value& args,
picojson::object* out) {
int length = wrt::Widget::GetInstance()->Length();
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(
std::make_pair("result", picojson::value(static_cast<double>(length))));
}
static void ClearHandler(const picojson::value& args,
picojson::object* out) {
wrt::Widget::GetInstance()->Clear();
out->insert(std::make_pair("status", picojson::value("success")));
}
static void SetItemHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
const std::string& value = args.get("value").get<std::string>();
std::string oldvalue;
if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {
out->insert(std::make_pair("result", picojson::value(oldvalue)));
} else {
out->insert(std::make_pair("result", picojson::value()));
}
wrt::Widget::GetInstance()->SetItem(key, value);
out->insert(std::make_pair("status", picojson::value("success")));
}
static void RemoveHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
std::string oldvalue;
if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {
out->insert(std::make_pair("result", picojson::value(oldvalue)));
} else {
out->insert(std::make_pair("result", picojson::value()));
}
wrt::Widget::GetInstance()->RemoveItem(key);
out->insert(std::make_pair("status", picojson::value("success")));
}
static void HandleMessage(XW_Instance instance,
const char* message,
bool sync) {
picojson::value value;
std::string err;
picojson::parse(value, message, message + strlen(message), &err);
if (!err.empty()) {
LOGGER(ERROR) << "Ignoring message. " << err;
return;
}
if (!value.is<picojson::object>()) {
LOGGER(ERROR) << "Ignoring message. It is not an object.";
return;
}
std::string cmd = value.get("cmd").to_str();
// check for args in JSON message
const picojson::value& args = value.get("args");
picojson::value result = picojson::value(picojson::object());
auto handler = g_handler.find(cmd);
if (handler != g_handler.end()) {
handler->second(args, &result.get<picojson::object>());
} else {
result.get<picojson::object>().insert(
std::make_pair("status", picojson::value("error")));
}
if (sync) {
g_sync_messaging->SetSyncReply(instance, result.serialize().c_str());
}
}
namespace wrt {
namespace {
const char* kDbInitedCheckKey = "__WRT_DB_INITED__";
const char* kDBPublicSection = "public";
const char* kDBPrivateSection = "private";
} // namespace
Widget* Widget::GetInstance() {
static Widget instance;
return &instance;
}
Widget::Widget() {
}
Widget::~Widget() {
}
void Widget::Initialize(const ApplicationData* appdata) {
AppDB* db = AppDB::GetInstance();
if (db->HasKey(kDBPrivateSection, kDbInitedCheckKey))
return;
if (appdata->widget_info() == NULL)
return;
auto preferences = appdata->widget_info()->preferences();
auto it = preferences.begin();
for ( ; it != preferences.end(); ++it) {
db->Set(kDBPublicSection,
(*it)->Name(),
(*it)->Value());
}
db->Set(kDBPrivateSection, kDbInitedCheckKey, "true");
}
int Widget::Length() {
AppDB* db = AppDB::GetInstance();
int count = 0;
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
return list.size();
}
bool Widget::Key(int idx, std::string* key) {
AppDB* db = AppDB::GetInstance();
int count = 0;
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
auto it = list.begin();
for ( ; it != list.end() && idx >= 0; ++it) {
if (idx == 0) {
*key = *it;
return true;
}
idx--;
}
return false;
}
bool Widget::GetItem(const std::string& key, std::string* value) {
AppDB* db = AppDB::GetInstance();
if (!db->HasKey(kDBPublicSection, key))
return false;
*value = db->Get(kDBPublicSection, key);
return true;
}
bool Widget::SetItem(const std::string& key, const std::string& value) {
AppDB* db = AppDB::GetInstance();
db->Set(kDBPublicSection, key, value);
return true;
}
bool Widget::RemoveItem(const std::string& key) {
AppDB* db = AppDB::GetInstance();
if (!db->HasKey(kDBPublicSection, key))
return false;
db->Remove(kDBPublicSection, key);
return true;
}
void Widget::Clear() {
AppDB* db = AppDB::GetInstance();
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
auto it = list.begin();
for ( ; it != list.end(); ++it) {
db->Remove(kDBPublicSection, *it);
}
}
} // namespace wrt
<commit_msg>Fix loading failure of libwidget-plugin.so<commit_after>// Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extension/widget/widget.h"
#include <list>
#include <memory>
#include <map>
#include <vector>
#include "extension/xwalk/XW_Extension.h"
#include "extension/xwalk/XW_Extension_EntryPoints.h"
#include "extension/xwalk/XW_Extension_Permissions.h"
#include "extension/xwalk/XW_Extension_Runtime.h"
#include "extension/xwalk/XW_Extension_SyncMessage.h"
#include "common/logger.h"
#include "extension/widget/picojson.h"
#include "common/app_db.h"
#include "common/application_data.h"
#include "common/string_utils.h"
XW_Extension g_xw_extension = 0;
std::string g_appid;
std::unique_ptr<wrt::ApplicationData> g_appdata;
const XW_CoreInterface* g_core = NULL;
const XW_MessagingInterface* g_messaging = NULL;
const XW_Internal_SyncMessagingInterface* g_sync_messaging = NULL;
const XW_Internal_EntryPointsInterface* g_entry_points = NULL;
const XW_Internal_RuntimeInterface* g_runtime = NULL;
extern const char kSource_widget_api[];
typedef void (*CmdHandler)(const picojson::value& args, picojson::object* out);
static void InitHandler(const picojson::value& args, picojson::object* out);
static void KeyHandler(const picojson::value& args, picojson::object* out);
static void GetItemHandler(const picojson::value& args,
picojson::object* out);
static void LengthHandler(const picojson::value& args,
picojson::object* out);
static void ClearHandler(const picojson::value& args,
picojson::object* out);
static void SetItemHandler(const picojson::value& args,
picojson::object* out);
static void RemoveHandler(const picojson::value& args,
picojson::object* out);
std::map<std::string, CmdHandler> g_handler = {
{"init", InitHandler},
{"key", KeyHandler},
{"length", LengthHandler},
{"clear", ClearHandler},
{"getItem", GetItemHandler},
{"setItem", SetItemHandler},
{"removeItem", RemoveHandler},
};
static void HandleMessage(XW_Instance instance,
const char* message,
bool sync);
extern "C" int32_t XW_Initialize(XW_Extension extension,
XW_GetInterface get_interface) {
g_xw_extension = extension;
g_core = reinterpret_cast<const XW_CoreInterface*>(
get_interface(XW_CORE_INTERFACE));
if (!g_core) {
LOGGER(ERROR)
<< "Can't initialize extension: error getting Core interface.";
return XW_ERROR;
}
g_messaging = reinterpret_cast<const XW_MessagingInterface*>(
get_interface(XW_MESSAGING_INTERFACE));
if (!g_messaging) {
LOGGER(ERROR)
<< "Can't initialize extension: error getting Messaging interface.";
return XW_ERROR;
}
g_sync_messaging =
reinterpret_cast<const XW_Internal_SyncMessagingInterface*>(
get_interface(XW_INTERNAL_SYNC_MESSAGING_INTERFACE));
if (!g_sync_messaging) {
LOGGER(ERROR)
<< "Can't initialize extension: "
<< "error getting SyncMessaging interface.";
return XW_ERROR;
}
g_entry_points = reinterpret_cast<const XW_Internal_EntryPointsInterface*>(
get_interface(XW_INTERNAL_ENTRY_POINTS_INTERFACE));
if (!g_entry_points) {
LOGGER(ERROR)
<< "NOTE: Entry points interface not available in this version "
<< "of Crosswalk, ignoring entry point data for extensions.\n";
return XW_ERROR;
}
g_runtime = reinterpret_cast<const XW_Internal_RuntimeInterface*>(
get_interface(XW_INTERNAL_RUNTIME_INTERFACE));
if (!g_runtime) {
LOGGER(ERROR)
<< "NOTE: runtime interface not available in this version "
<< "of Crosswalk, ignoring runtime variables for extensions.\n";
return XW_ERROR;
}
std::vector<char> res(256, 0);
g_runtime->GetRuntimeVariableString(extension, "app_id", &res[0], 256);
g_appid = std::string(res.begin(), res.end());
if (g_appid.at(0) == '"') {
g_appid = g_appid.substr(1, g_appid.size()-2);
}
g_core->RegisterInstanceCallbacks(
g_xw_extension,
[](XW_Instance /*instance*/){
if (g_appdata.get() == NULL) {
g_appdata.reset(new wrt::ApplicationData(g_appid));
}
wrt::Widget::GetInstance()->Initialize(g_appdata.get());
},
NULL);
g_messaging->Register(g_xw_extension, [](XW_Instance instance,
const char* message) {
HandleMessage(instance, message, false);
});
g_sync_messaging->Register(g_xw_extension, [](XW_Instance instance,
const char* message) {
HandleMessage(instance, message, true);
});
g_core->SetExtensionName(g_xw_extension, "Widget");
const char* entry_points[] = {"widget", NULL};
g_entry_points->SetExtraJSEntryPoints(g_xw_extension, entry_points);
g_core->SetJavaScriptAPI(g_xw_extension, kSource_widget_api);
return XW_OK;
}
static void InitHandler(const picojson::value& /*args*/,
picojson::object* out) {
picojson::value result = picojson::value(picojson::object());
picojson::object& obj = result.get<picojson::object>();
auto widget_info = g_appdata->widget_info();
if (widget_info.get() == NULL) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
// TODO(sngn.lee): should be returned localized string
obj["author"] = picojson::value(widget_info->author());
obj["description"] = picojson::value(widget_info->description());
obj["name"] = picojson::value(widget_info->name());
obj["shortName"] = picojson::value(widget_info->short_name());
obj["version"] = picojson::value(widget_info->version());
obj["id"] = picojson::value(widget_info->id());
obj["authorEmail"] = picojson::value(widget_info->author_email());
obj["authorHref"] = picojson::value(widget_info->author_href());
obj["height"] = picojson::value(static_cast<double>(widget_info->height()));
obj["width"] = picojson::value(static_cast<double>(widget_info->width()));
out->insert(std::make_pair("result", result));
}
static void KeyHandler(const picojson::value& args, picojson::object* out) {
int idx = static_cast<int>(args.get("idx").get<double>());
std::string key;
if (!wrt::Widget::GetInstance()->Key(idx, &key)) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(std::make_pair("result", picojson::value(key)));
}
static void GetItemHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
std::string value;
if (!wrt::Widget::GetInstance()->GetItem(key, &value)) {
out->insert(std::make_pair("status", picojson::value("error")));
return;
}
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(std::make_pair("result", picojson::value(value)));
}
static void LengthHandler(const picojson::value& /*args*/,
picojson::object* out) {
int length = wrt::Widget::GetInstance()->Length();
out->insert(std::make_pair("status", picojson::value("success")));
out->insert(
std::make_pair("result", picojson::value(static_cast<double>(length))));
}
static void ClearHandler(const picojson::value& /*args*/,
picojson::object* out) {
wrt::Widget::GetInstance()->Clear();
out->insert(std::make_pair("status", picojson::value("success")));
}
static void SetItemHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
const std::string& value = args.get("value").get<std::string>();
std::string oldvalue;
if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {
out->insert(std::make_pair("result", picojson::value(oldvalue)));
} else {
out->insert(std::make_pair("result", picojson::value()));
}
wrt::Widget::GetInstance()->SetItem(key, value);
out->insert(std::make_pair("status", picojson::value("success")));
}
static void RemoveHandler(const picojson::value& args,
picojson::object* out) {
const std::string& key = args.get("key").get<std::string>();
std::string oldvalue;
if (wrt::Widget::GetInstance()->GetItem(key, &oldvalue)) {
out->insert(std::make_pair("result", picojson::value(oldvalue)));
} else {
out->insert(std::make_pair("result", picojson::value()));
}
wrt::Widget::GetInstance()->RemoveItem(key);
out->insert(std::make_pair("status", picojson::value("success")));
}
static void HandleMessage(XW_Instance instance,
const char* message,
bool sync) {
picojson::value value;
std::string err;
picojson::parse(value, message, message + strlen(message), &err);
if (!err.empty()) {
LOGGER(ERROR) << "Ignoring message. " << err;
return;
}
if (!value.is<picojson::object>()) {
LOGGER(ERROR) << "Ignoring message. It is not an object.";
return;
}
std::string cmd = value.get("cmd").to_str();
// check for args in JSON message
const picojson::value& args = value.get("args");
picojson::value result = picojson::value(picojson::object());
auto handler = g_handler.find(cmd);
if (handler != g_handler.end()) {
handler->second(args, &result.get<picojson::object>());
} else {
result.get<picojson::object>().insert(
std::make_pair("status", picojson::value("error")));
}
if (sync) {
g_sync_messaging->SetSyncReply(instance, result.serialize().c_str());
}
}
namespace wrt {
namespace {
const char* kDbInitedCheckKey = "__WRT_DB_INITED__";
const char* kDBPublicSection = "public";
const char* kDBPrivateSection = "private";
} // namespace
Widget* Widget::GetInstance() {
static Widget instance;
return &instance;
}
Widget::Widget() {
}
Widget::~Widget() {
}
void Widget::Initialize(const ApplicationData* appdata) {
AppDB* db = AppDB::GetInstance();
if (db->HasKey(kDBPrivateSection, kDbInitedCheckKey))
return;
if (appdata->widget_info() == NULL)
return;
auto preferences = appdata->widget_info()->preferences();
auto it = preferences.begin();
for ( ; it != preferences.end(); ++it) {
db->Set(kDBPublicSection,
(*it)->Name(),
(*it)->Value());
}
db->Set(kDBPrivateSection, kDbInitedCheckKey, "true");
}
int Widget::Length() {
AppDB* db = AppDB::GetInstance();
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
return list.size();
}
bool Widget::Key(int idx, std::string* key) {
AppDB* db = AppDB::GetInstance();
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
auto it = list.begin();
for ( ; it != list.end() && idx >= 0; ++it) {
if (idx == 0) {
*key = *it;
return true;
}
idx--;
}
return false;
}
bool Widget::GetItem(const std::string& key, std::string* value) {
AppDB* db = AppDB::GetInstance();
if (!db->HasKey(kDBPublicSection, key))
return false;
*value = db->Get(kDBPublicSection, key);
return true;
}
bool Widget::SetItem(const std::string& key, const std::string& value) {
AppDB* db = AppDB::GetInstance();
db->Set(kDBPublicSection, key, value);
return true;
}
bool Widget::RemoveItem(const std::string& key) {
AppDB* db = AppDB::GetInstance();
if (!db->HasKey(kDBPublicSection, key))
return false;
db->Remove(kDBPublicSection, key);
return true;
}
void Widget::Clear() {
AppDB* db = AppDB::GetInstance();
std::list<std::string> list;
db->GetKeys(kDBPublicSection, &list);
auto it = list.begin();
for ( ; it != list.end(); ++it) {
db->Remove(kDBPublicSection, *it);
}
}
} // namespace wrt
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "base58.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace json_spirit;
extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL);
extern Value CallRPC(string args);
extern CWallet* pwalletMain;
BOOST_AUTO_TEST_SUITE(rpc_wallet_tests)
BOOST_AUTO_TEST_CASE(rpc_addmultisig)
{
LOCK(pwalletMain->cs_wallet);
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_wallet)
{
// Test RPC calls for various wallet statistics
Value r;
LOCK2(cs_main, pwalletMain->cs_wallet);
CPubKey demoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID()));
Value retValue;
string strAccount = "walletDemoAccount";
string strPurpose = "receive";
BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
account.vchPubKey = demoPubkey;
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose);
walletdb.WriteAccount(strAccount, account);
});
CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID()));
/*********************************
* setaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount"));
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error);
BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error);
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error);
/*********************************
* listunspent
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listunspent"));
BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []"));
BOOST_CHECK(r.get_array().empty());
/*********************************
* listreceivedbyaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error);
/*********************************
* listreceivedbyaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error);
/*********************************
* getrawchangeaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress"));
/*********************************
* getnewaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress"));
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount"));
/*********************************
* getaccountaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\""));
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount));
BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get());
/*********************************
* getaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString()));
/*********************************
* signmessage + verifymessage
*********************************/
BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage"));
BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error);
/* Should throw error because this address is not loaded in the wallet */
BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error);
/* missing arguments */
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error);
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error);
/* Illegal address */
BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error);
/* wrong address */
BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false);
/* Correct address and signature but wrong message */
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false);
/* Correct address, message and signature*/
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true);
/*********************************
* getaddressesbyaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error);
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount));
Array arr = retValue.get_array();
BOOST_CHECK(arr.size() > 0);
BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add simple unittest for `fundrawtransaction` (increase test coverage)<commit_after>// Copyright (c) 2013-2014 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "base58.h"
#include "wallet.h"
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace json_spirit;
extern Array createArgs(int nRequired, const char* address1 = NULL, const char* address2 = NULL);
extern Value CallRPC(string args);
extern CWallet* pwalletMain;
BOOST_AUTO_TEST_SUITE(rpc_wallet_tests)
BOOST_AUTO_TEST_CASE(rpc_addmultisig)
{
LOCK(pwalletMain->cs_wallet);
rpcfn_type addmultisig = tableRPC["addmultisigaddress"]->actor;
// old, 65-byte-long:
const char address1Hex[] = "0434e3e09f49ea168c5bbf53f877ff4206923858aab7c7e1df25bc263978107c95e35065a27ef6f1b27222db0ec97e0e895eaca603d3ee0d4c060ce3d8a00286c8";
// new, compressed:
const char address2Hex[] = "0388c2037017c62240b6b72ac1a2a5f94da790596ebd06177c8572752922165cb4";
Value v;
CBitcoinAddress address;
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(1, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_NO_THROW(v = addmultisig(createArgs(2, address1Hex, address2Hex), false));
address.SetString(v.get_str());
BOOST_CHECK(address.IsValid() && address.IsScript());
BOOST_CHECK_THROW(addmultisig(createArgs(0), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(2, address1Hex), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, ""), false), runtime_error);
BOOST_CHECK_THROW(addmultisig(createArgs(1, "NotAValidPubkey"), false), runtime_error);
string short1(address1Hex, address1Hex + sizeof(address1Hex) - 2); // last byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short1.c_str()), false), runtime_error);
string short2(address1Hex + 1, address1Hex + sizeof(address1Hex)); // first byte missing
BOOST_CHECK_THROW(addmultisig(createArgs(2, short2.c_str()), false), runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_wallet)
{
// Test RPC calls for various wallet statistics
Value r;
LOCK2(cs_main, pwalletMain->cs_wallet);
CPubKey demoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID()));
Value retValue;
string strAccount = "walletDemoAccount";
string strPurpose = "receive";
BOOST_CHECK_NO_THROW({ /*Initialize Wallet with an account */
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
account.vchPubKey = demoPubkey;
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, strPurpose);
walletdb.WriteAccount(strAccount, account);
});
CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey();
CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID()));
/*********************************
* setaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("setaccount " + setaccountDemoAddress.ToString() + " nullaccount"));
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ is not owned by the test wallet. */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ nullaccount"), runtime_error);
BOOST_CHECK_THROW(CallRPC("setaccount"), runtime_error);
/* 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X (33 chars) is an illegal address (should be 34 chars) */
BOOST_CHECK_THROW(CallRPC("setaccount 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X nullaccount"), runtime_error);
/*********************************
* listunspent
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listunspent"));
BOOST_CHECK_THROW(CallRPC("listunspent string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 string"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 not_array"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listunspent 0 1 [] extra"), runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC("listunspent 0 1 []"));
BOOST_CHECK(r.get_array().empty());
/*********************************
* listreceivedbyaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaddress 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaddress 0 true extra"), runtime_error);
/*********************************
* listreceivedbyaccount
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount"));
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 not_bool"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("listreceivedbyaccount 0 true"));
BOOST_CHECK_THROW(CallRPC("listreceivedbyaccount 0 true extra"), runtime_error);
/*********************************
* getrawchangeaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getrawchangeaddress"));
/*********************************
* getnewaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress"));
BOOST_CHECK_NO_THROW(CallRPC("getnewaddress getnewaddress_demoaccount"));
/*********************************
* getaccountaddress
*********************************/
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress \"\""));
BOOST_CHECK_NO_THROW(CallRPC("getaccountaddress accountThatDoesntExists")); // Should generate a new account
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaccountaddress " + strAccount));
BOOST_CHECK(CBitcoinAddress(retValue.get_str()).Get() == demoAddress.Get());
/*********************************
* getaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaccount"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("getaccount " + demoAddress.ToString()));
/*********************************
* signmessage + verifymessage
*********************************/
BOOST_CHECK_NO_THROW(retValue = CallRPC("signmessage " + demoAddress.ToString() + " mymessage"));
BOOST_CHECK_THROW(CallRPC("signmessage"), runtime_error);
/* Should throw error because this address is not loaded in the wallet */
BOOST_CHECK_THROW(CallRPC("signmessage 1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ mymessage"), runtime_error);
/* missing arguments */
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString()), runtime_error);
BOOST_CHECK_THROW(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str()), runtime_error);
/* Illegal address */
BOOST_CHECK_THROW(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4X " + retValue.get_str() + " mymessage"), runtime_error);
/* wrong address */
BOOST_CHECK(CallRPC("verifymessage 1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ " + retValue.get_str() + " mymessage").get_bool() == false);
/* Correct address and signature but wrong message */
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false);
/* Correct address, message and signature*/
BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true);
/*********************************
* getaddressesbyaccount
*********************************/
BOOST_CHECK_THROW(CallRPC("getaddressesbyaccount"), runtime_error);
BOOST_CHECK_NO_THROW(retValue = CallRPC("getaddressesbyaccount " + strAccount));
Array arr = retValue.get_array();
BOOST_CHECK(arr.size() > 0);
BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get());
/*********************************
* fundrawtransaction
*********************************/
BOOST_CHECK_THROW(CallRPC("fundrawtransaction 28z"), runtime_error);
BOOST_CHECK_THROW(CallRPC("fundrawtransaction 01000000000180969800000000001976a91450ce0a4b0ee0ddeb633da85199728b940ac3fe9488ac00000000"), runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#ifndef SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
#define SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
#include "cloner.hpp"
#include <type_traits>
#include <memory>
#include <cassert>
namespace sutil
{
/**
* A value_ptr shall fill the need for a smart pointer that clones the pointee.
* The pointee must provide a clone function or a cloner must be provided.
*/
template <typename T, typename ClonerT = default_clone <T>, typename DeleterT = std::default_delete <T> >
class value_ptr
{
public:
using pointer = T*;
using element_type = T;
using deleter_type = DeleterT;
using cloner_type = ClonerT;
/**
* Creates an invalid value_ptr that has ownership of nothing.
*/
constexpr value_ptr() noexcept
: m_(nullptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates an invalid value_ptr that has ownership of nothing.
*/
constexpr value_ptr(std::nullptr_t) noexcept
: m_(nullptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
*
* @param ptr The pointer to take ownership of.
*/
explicit value_ptr(T* ptr) noexcept
: m_(ptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr, typename std::conditional <std::is_reference <deleter_type>::value,
deleter_type, const deleter_type&>::type d) noexcept
: m_(ptr, cloner_type(), d)
{
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr, typename std::remove_reference <deleter_type>::type&& d) noexcept
: m_(std::move(ptr), cloner_type(), std::move(d))
{
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param c A cloner.
*/
value_ptr(T* ptr, typename std::conditional <std::is_reference <cloner_type>::value,
cloner_type, const cloner_type&>::type c) noexcept
: m_(ptr, c, deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param c A cloner.
*/
value_ptr(T* ptr, typename std::remove_reference <cloner_type>::type&& c) noexcept
: m_(std::move(ptr), std::move(c), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function and a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
* @param c A cloner.
*/
value_ptr(T* ptr,
typename std::conditional <std::is_reference <deleter_type>::value,
deleter_type, const deleter_type&>::type d,
typename std::conditional <std::is_reference <cloner_type>::value,
cloner_type, const cloner_type&>::type c) noexcept
: m_(ptr, c, d)
{
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function and a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr,
typename std::remove_reference <cloner_type>::type&& d,
typename std::remove_reference <cloner_type>::type&& c) noexcept
: m_(std::move(ptr), std::move(c), std::move(d))
{
}
/**
* Moves a value ptr over. destroys previously held pointee.
*/
value_ptr(value_ptr&& v) noexcept
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
}
/**
* Copies the pointee. Cannot be noexcept, because clone may throw.
* The value_ptr remains unaltered if clone throws.
*/
value_ptr(value_ptr const& v)
: m_(clone(v.get()), v.get_cloner(), v.get_deleter())
{
}
/**
* Copies the pointee. Cannot be noexcept, because clone may throw.
* The value_ptr remains unaltered if clone throws.
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr(value_ptr <U, ClonerU, DeleterU> const& v)
: m_(clone(v.get()), v.get_cloner(), v.get_deleter())
{
}
/**
* Move assignment.
*/
value_ptr& operator=(value_ptr&& v)
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
return *this;
}
/**
* Move assignment
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr& operator=(value_ptr <U, ClonerU, DeleterU>&& v)
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
return *this;
}
/**
* "Clone" assignment.
*/
value_ptr& operator=(value_ptr const& v)
{
reset(clone(v.get()));
get_deleter() = v.get_deleter();
get_cloner() = v.get_cloner();
return *this;
}
/**
* "Clone" assignment
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr& operator=(value_ptr <U, ClonerU, DeleterU> const& v)
{
reset(clone(v.get()));
get_deleter() = v.get_deleter();
get_cloner() = v.get_cloner();
return *this;
}
/**
* Convenient dereferencing operator.
*/
typename std::add_lvalue_reference <element_type>::type operator*() const
{
// assert(get() != 0);
return *get();
}
/**
* Convenient arrow operator.
*/
pointer operator->() const
{
return get();
}
/**
* Retrieves the held pointee.
*/
pointer get() const
{
return std::get <0> (m_);
}
/**
* Retrieves a reference to the deleter.
*/
typename std::add_lvalue_reference <deleter_type>::type
get_deleter() noexcept
{
return std::get <2> (m_);
}
/**
* Retrieves a reference to the deleter.
*/
typename std::add_lvalue_reference <typename std::add_const <deleter_type>::type>::type
get_deleter() const noexcept
{
return std::get <2> (m_);
}
typename std::add_lvalue_reference <cloner_type>::type
get_cloner() noexcept
{
return std::get <1> (m_);
}
/**
* Retrieves a reference to the cloner.
*/
typename std::add_lvalue_reference <typename std::add_const <cloner_type>::type>::type
get_cloner() const noexcept
{
return std::get <1> (m_);
}
/**
* Resets the value_ptr with a new object. calls the deleter on the old object.
*/
void reset(pointer p = pointer())
{
if (p != get())
{
get_deleter()(get()); // delete held object.
std::get <0> (m_) = p;
}
}
/**
* Is set? Does it hold something?
*/
explicit operator bool() const
{
return get() == nullptr ? false : true;
}
/**
* Gets the owned object and disengages ownership.
* (I am not responsible for deleting it anymore, do it yourself).
*/
pointer release()
{
pointer p = get();
std::get <0> (m_) = nullptr;
return p;
}
/**
* Swaps the pointee's.
*/
void swap(value_ptr&& v)
{
using std::swap;
swap(m_, v.m_);
}
/**
* Destructor.
*/
~value_ptr()
{
reset();
}
private:
template <typename PtrT>
pointer clone(PtrT p) {
return p ? get_cloner()(p) : nullptr;
}
private:
std::tuple <T*, ClonerT, DeleterT> m_;
};
template <typename T, typename ClonerT = sutil::default_clone <T>, typename DeleterT = std::default_delete <T>, typename... List>
value_ptr <T, ClonerT, DeleterT> make_value(List&&... list)
{
return value_ptr <T, ClonerT, DeleterT> (new T(std::forward <List> (list)...));
}
}
#endif // SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
<commit_msg>Added assignment operator, that augments the reset function.<commit_after>#ifndef SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
#define SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
#include "cloner.hpp"
#include <type_traits>
#include <memory>
#include <cassert>
namespace sutil
{
/**
* A value_ptr shall fill the need for a smart pointer that clones the pointee.
* The pointee must provide a clone function or a cloner must be provided.
*/
template <typename T, typename ClonerT = default_clone <T>, typename DeleterT = std::default_delete <T> >
class value_ptr
{
public:
using pointer = T*;
using element_type = T;
using deleter_type = DeleterT;
using cloner_type = ClonerT;
/**
* Creates an invalid value_ptr that has ownership of nothing.
*/
constexpr value_ptr() noexcept
: m_(nullptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates an invalid value_ptr that has ownership of nothing.
*/
constexpr value_ptr(std::nullptr_t) noexcept
: m_(nullptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
*
* @param ptr The pointer to take ownership of.
*/
explicit value_ptr(T* ptr) noexcept
: m_(ptr, cloner_type(), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr, typename std::conditional <std::is_reference <deleter_type>::value,
deleter_type, const deleter_type&>::type d) noexcept
: m_(ptr, cloner_type(), d)
{
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr, typename std::remove_reference <deleter_type>::type&& d) noexcept
: m_(std::move(ptr), cloner_type(), std::move(d))
{
static_assert(!std::is_pointer<cloner_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param c A cloner.
*/
value_ptr(T* ptr, typename std::conditional <std::is_reference <cloner_type>::value,
cloner_type, const cloner_type&>::type c) noexcept
: m_(ptr, c, deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer deleter");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param c A cloner.
*/
value_ptr(T* ptr, typename std::remove_reference <cloner_type>::type&& c) noexcept
: m_(std::move(ptr), std::move(c), deleter_type())
{
static_assert(!std::is_pointer<deleter_type>::value,
"constructed with null function pointer cloner");
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function and a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
* @param c A cloner.
*/
value_ptr(T* ptr,
typename std::conditional <std::is_reference <deleter_type>::value,
deleter_type, const deleter_type&>::type d,
typename std::conditional <std::is_reference <cloner_type>::value,
cloner_type, const cloner_type&>::type c) noexcept
: m_(ptr, c, d)
{
}
/**
* Creates a new value_ptr from a raw owning pointer and aquires ownership.
* Also sets a deleter function and a cloner function.
*
* @param ptr The pointer to take ownership of.
* @param d A deleter.
*/
value_ptr(T* ptr,
typename std::remove_reference <cloner_type>::type&& d,
typename std::remove_reference <cloner_type>::type&& c) noexcept
: m_(std::move(ptr), std::move(c), std::move(d))
{
}
/**
* Moves a value ptr over. destroys previously held pointee.
*/
value_ptr(value_ptr&& v) noexcept
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
}
/**
* Copies the pointee. Cannot be noexcept, because clone may throw.
* The value_ptr remains unaltered if clone throws.
*/
value_ptr(value_ptr const& v)
: m_(clone(v.get()), v.get_cloner(), v.get_deleter())
{
}
/**
* Copies the pointee. Cannot be noexcept, because clone may throw.
* The value_ptr remains unaltered if clone throws.
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr(value_ptr <U, ClonerU, DeleterU> const& v)
: m_(clone(v.get()), v.get_cloner(), v.get_deleter())
{
}
/**
* Move assignment.
*/
value_ptr& operator=(value_ptr&& v)
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
return *this;
}
/**
* Move assignment
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr& operator=(value_ptr <U, ClonerU, DeleterU>&& v)
{
reset(v.release());
get_deleter() = std::move(v.get_deleter());
get_cloner() = std::move(v.get_cloner());
return *this;
}
/**
* "Clone" assignment.
*/
value_ptr& operator=(value_ptr const& v)
{
reset(clone(v.get()));
get_deleter() = v.get_deleter();
get_cloner() = v.get_cloner();
return *this;
}
/**
* "Clone" assignment
*/
template <typename U, typename ClonerU, typename DeleterU>
value_ptr& operator=(value_ptr <U, ClonerU, DeleterU> const& v)
{
reset(clone(v.get()));
get_deleter() = v.get_deleter();
get_cloner() = v.get_cloner();
return *this;
}
/**
* Replacing assignment, frees previously held object.
* Alternative to reset(ptr).
*/
value_ptr& operator=(T* ptr)
{
reset(ptr);
return *this;
}
/**
* Convenient dereferencing operator.
*/
typename std::add_lvalue_reference <element_type>::type operator*() const
{
// assert(get() != 0);
return *get();
}
/**
* Convenient arrow operator.
*/
pointer operator->() const
{
return get();
}
/**
* Retrieves the held pointee.
*/
pointer get() const
{
return std::get <0> (m_);
}
/**
* Retrieves a reference to the deleter.
*/
typename std::add_lvalue_reference <deleter_type>::type
get_deleter() noexcept
{
return std::get <2> (m_);
}
/**
* Retrieves a reference to the deleter.
*/
typename std::add_lvalue_reference <typename std::add_const <deleter_type>::type>::type
get_deleter() const noexcept
{
return std::get <2> (m_);
}
typename std::add_lvalue_reference <cloner_type>::type
get_cloner() noexcept
{
return std::get <1> (m_);
}
/**
* Retrieves a reference to the cloner.
*/
typename std::add_lvalue_reference <typename std::add_const <cloner_type>::type>::type
get_cloner() const noexcept
{
return std::get <1> (m_);
}
/**
* Resets the value_ptr with a new object. calls the deleter on the old object.
*/
void reset(pointer p = pointer())
{
if (p != get())
{
get_deleter()(get()); // delete held object.
std::get <0> (m_) = p;
}
}
/**
* Is set? Does it hold something?
*/
explicit operator bool() const
{
return get() == nullptr ? false : true;
}
/**
* Gets the owned object and disengages ownership.
* (I am not responsible for deleting it anymore, do it yourself).
*/
pointer release()
{
pointer p = get();
std::get <0> (m_) = nullptr;
return p;
}
/**
* Swaps the pointee's.
*/
void swap(value_ptr&& v)
{
using std::swap;
swap(m_, v.m_);
}
/**
* Destructor.
*/
~value_ptr()
{
reset();
}
private:
template <typename PtrT>
pointer clone(PtrT p) {
return p ? get_cloner()(p) : nullptr;
}
private:
std::tuple <T*, ClonerT, DeleterT> m_;
};
template <typename T, typename ClonerT = sutil::default_clone <T>, typename DeleterT = std::default_delete <T>, typename... List>
value_ptr <T, ClonerT, DeleterT> make_value(List&&... list)
{
return value_ptr <T, ClonerT, DeleterT> (new T(std::forward <List> (list)...));
}
}
#endif // SIMPLE_UTIL_VALUE_PTR_HPP_INCLUDED
<|endoftext|> |
<commit_before>#include <TApplication.h>
#include <TGClient.h>
#include "AliZMQMTviewerGUI.h"
int main(int argc, char **argv) {
TApplication theApp("App", &argc, argv);
AliZMQMTviewerGUI viewer(gClient->GetRoot(), 200, 200, argc, argv);
if (viewer.GetInitStatus()<0) {
printf("%s",viewer.fUSAGE);
return 1;
}
theApp.Run();
return 0;
}
<commit_msg>Don't pass options to TApplication<commit_after>#include <TApplication.h>
#include <TGClient.h>
#include "AliZMQMTviewerGUI.h"
int main(int argc, char **argv) {
TApplication theApp("App", NULL, NULL);
AliZMQMTviewerGUI viewer(gClient->GetRoot(), 200, 200, argc, argv);
if (viewer.GetInitStatus()<0) {
printf("%s",viewer.fUSAGE);
return 1;
}
theApp.Run();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BufferedResourceLoader.hxx"
#include "HttpResponseHandler.hxx"
#include "strmap.hxx"
#include "istream/BufferedIstream.hxx"
#include "istream/UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "pool/LeakDetector.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"
namespace {
class PostponedRequest {
struct pool &pool;
ResourceLoader &next;
const StopwatchPtr parent_stopwatch;
const sticky_hash_t session_sticky;
const char *const cache_tag;
const char *const site_name;
const http_method_t method;
const ResourceAddress &address;
const http_status_t status;
StringMap headers;
const char *const body_etag;
HttpResponseHandler &handler;
CancellablePointer &caller_cancel_ptr;
public:
PostponedRequest(struct pool &_pool, ResourceLoader &_next,
const StopwatchPtr &_parent_stopwatch,
sticky_hash_t _session_sticky,
const char *_cache_tag,
const char *_site_name,
http_method_t _method,
const ResourceAddress &_address,
http_status_t _status, StringMap &&_headers,
const char *_body_etag,
HttpResponseHandler &_handler,
CancellablePointer &_caller_cancel_ptr) noexcept
:pool(_pool),
next(_next), parent_stopwatch(_parent_stopwatch),
session_sticky(_session_sticky),
cache_tag(_cache_tag),
site_name(_site_name),
method(_method), address(_address),
status(_status),
/* copy the headers, because they may come from a
FilterCacheRequest pool which may be freed before
BufferedIstream becomes ready */
headers(pool, _headers),
body_etag(_body_etag),
handler(_handler), caller_cancel_ptr(_caller_cancel_ptr)
{
}
auto &GetPool() const noexcept {
return pool;
}
auto &GetHandler() noexcept {
return handler;
}
void Send(UnusedIstreamPtr body) noexcept {
next.SendRequest(pool, parent_stopwatch,
session_sticky, cache_tag, site_name,
method, address, status, std::move(headers),
std::move(body), body_etag,
handler, caller_cancel_ptr);
}
};
}
class BufferedResourceLoader::Request final
: PoolLeakDetector, Cancellable, BufferedIstreamHandler
{
PostponedRequest postponed_request;
CancellablePointer cancel_ptr;
public:
Request(struct pool &_pool, ResourceLoader &_next,
const StopwatchPtr &_parent_stopwatch,
sticky_hash_t _session_sticky,
const char *_cache_tag,
const char *_site_name,
http_method_t _method, const ResourceAddress &_address,
http_status_t _status, StringMap &&_headers,
const char *_body_etag,
HttpResponseHandler &_handler,
CancellablePointer &caller_cancel_ptr) noexcept
:PoolLeakDetector(_pool),
postponed_request(_pool, _next,
_parent_stopwatch,
_session_sticky,
_cache_tag, _site_name,
_method, _address,
_status, std::move(_headers),
_body_etag, _handler, caller_cancel_ptr)
{
caller_cancel_ptr = *this;
}
auto &GetPool() const noexcept {
return postponed_request.GetPool();
}
void Start(EventLoop &_event_loop, PipeStock *_pipe_stock,
UnusedIstreamPtr &&body) noexcept {
NewBufferedIstream(GetPool(),
_event_loop, _pipe_stock,
*this, std::move(body),
cancel_ptr);
}
private:
void Destroy() noexcept {
DeleteFromPool(GetPool(), this);
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
cancel_ptr.Cancel();
Destroy();
}
/* virtual methods from class BufferedIstreamHandler */
void OnBufferedIstreamReady(UnusedIstreamPtr i) noexcept override {
// TODO: eliminate this reference
const ScopePoolRef _ref(GetPool() TRACE_ARGS);
postponed_request.Send(std::move(i));
// TODO: destruct before invoking next.SendRequest()
Destroy();
}
void OnBufferedIstreamError(std::exception_ptr e) noexcept override {
auto &_handler = postponed_request.GetHandler();
Destroy();
_handler.InvokeError(std::move(e));
}
};
void
BufferedResourceLoader::SendRequest(struct pool &pool,
const StopwatchPtr &parent_stopwatch,
sticky_hash_t session_sticky,
const char *cache_tag,
const char *site_name,
http_method_t method,
const ResourceAddress &address,
http_status_t status, StringMap &&headers,
UnusedIstreamPtr body, const char *body_etag,
HttpResponseHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (body) {
auto *request = NewFromPool<Request>(pool, pool, next, parent_stopwatch,
session_sticky,
cache_tag, site_name,
method, address,
status, std::move(headers),
body_etag, handler, cancel_ptr);
request->Start(event_loop, pipe_stock, std::move(body));
} else {
next.SendRequest(pool, parent_stopwatch,
session_sticky, cache_tag, site_name,
method, address, status, std::move(headers),
std::move(body), body_etag,
handler, cancel_ptr);
}
}
<commit_msg>BufferedResourceLoader: eliminate pool reference<commit_after>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "BufferedResourceLoader.hxx"
#include "HttpResponseHandler.hxx"
#include "strmap.hxx"
#include "istream/BufferedIstream.hxx"
#include "istream/UnusedPtr.hxx"
#include "pool/pool.hxx"
#include "pool/LeakDetector.hxx"
#include "util/Cancellable.hxx"
#include "stopwatch.hxx"
namespace {
class PostponedRequest {
struct pool &pool;
ResourceLoader &next;
const StopwatchPtr parent_stopwatch;
const sticky_hash_t session_sticky;
const char *const cache_tag;
const char *const site_name;
const http_method_t method;
const ResourceAddress &address;
const http_status_t status;
StringMap headers;
const char *const body_etag;
HttpResponseHandler &handler;
CancellablePointer &caller_cancel_ptr;
public:
PostponedRequest(struct pool &_pool, ResourceLoader &_next,
const StopwatchPtr &_parent_stopwatch,
sticky_hash_t _session_sticky,
const char *_cache_tag,
const char *_site_name,
http_method_t _method,
const ResourceAddress &_address,
http_status_t _status, StringMap &&_headers,
const char *_body_etag,
HttpResponseHandler &_handler,
CancellablePointer &_caller_cancel_ptr) noexcept
:pool(_pool),
next(_next), parent_stopwatch(_parent_stopwatch),
session_sticky(_session_sticky),
cache_tag(_cache_tag),
site_name(_site_name),
method(_method), address(_address),
status(_status),
/* copy the headers, because they may come from a
FilterCacheRequest pool which may be freed before
BufferedIstream becomes ready */
headers(pool, _headers),
body_etag(_body_etag),
handler(_handler), caller_cancel_ptr(_caller_cancel_ptr)
{
}
auto &GetPool() const noexcept {
return pool;
}
auto &GetHandler() noexcept {
return handler;
}
void Send(UnusedIstreamPtr body) noexcept {
next.SendRequest(pool, parent_stopwatch,
session_sticky, cache_tag, site_name,
method, address, status, std::move(headers),
std::move(body), body_etag,
handler, caller_cancel_ptr);
}
};
}
class BufferedResourceLoader::Request final
: PoolLeakDetector, Cancellable, BufferedIstreamHandler
{
PostponedRequest postponed_request;
CancellablePointer cancel_ptr;
public:
Request(struct pool &_pool, ResourceLoader &_next,
const StopwatchPtr &_parent_stopwatch,
sticky_hash_t _session_sticky,
const char *_cache_tag,
const char *_site_name,
http_method_t _method, const ResourceAddress &_address,
http_status_t _status, StringMap &&_headers,
const char *_body_etag,
HttpResponseHandler &_handler,
CancellablePointer &caller_cancel_ptr) noexcept
:PoolLeakDetector(_pool),
postponed_request(_pool, _next,
_parent_stopwatch,
_session_sticky,
_cache_tag, _site_name,
_method, _address,
_status, std::move(_headers),
_body_etag, _handler, caller_cancel_ptr)
{
caller_cancel_ptr = *this;
}
auto &GetPool() const noexcept {
return postponed_request.GetPool();
}
void Start(EventLoop &_event_loop, PipeStock *_pipe_stock,
UnusedIstreamPtr &&body) noexcept {
NewBufferedIstream(GetPool(),
_event_loop, _pipe_stock,
*this, std::move(body),
cancel_ptr);
}
private:
void Destroy() noexcept {
DeleteFromPool(GetPool(), this);
}
/* virtual methods from class Cancellable */
void Cancel() noexcept override {
cancel_ptr.Cancel();
Destroy();
}
/* virtual methods from class BufferedIstreamHandler */
void OnBufferedIstreamReady(UnusedIstreamPtr i) noexcept override {
auto _pr = std::move(postponed_request);
Destroy();
_pr.Send(std::move(i));
}
void OnBufferedIstreamError(std::exception_ptr e) noexcept override {
auto &_handler = postponed_request.GetHandler();
Destroy();
_handler.InvokeError(std::move(e));
}
};
void
BufferedResourceLoader::SendRequest(struct pool &pool,
const StopwatchPtr &parent_stopwatch,
sticky_hash_t session_sticky,
const char *cache_tag,
const char *site_name,
http_method_t method,
const ResourceAddress &address,
http_status_t status, StringMap &&headers,
UnusedIstreamPtr body, const char *body_etag,
HttpResponseHandler &handler,
CancellablePointer &cancel_ptr) noexcept
{
if (body) {
auto *request = NewFromPool<Request>(pool, pool, next, parent_stopwatch,
session_sticky,
cache_tag, site_name,
method, address,
status, std::move(headers),
body_etag, handler, cancel_ptr);
request->Start(event_loop, pipe_stock, std::move(body));
} else {
next.SendRequest(pool, parent_stopwatch,
session_sticky, cache_tag, site_name,
method, address, status, std::move(headers),
std::move(body), body_etag,
handler, cancel_ptr);
}
}
<|endoftext|> |
<commit_before>#include "game.hpp"
#include <iostream>
//////////
// Code //
struct PositionEvent : public clibgame::Event {
std::string name;
float x, y;
float w, h;
PositionEvent(std::string name,
float x, float y,
float w, float h) {
this->name = name;
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
std::string getEventType() const { return this->name; }
};
struct Position : public clibgame::Component {
float x, y, w, h;
bool alert;
Position(float x, float y,
float w, float h,
bool alert) {
this->x = x;
this->y = y;
this->w = w;
this->h = h;
this->alert = alert;
}
std::string getName() const { return "position"; }
void translate(float dx, float dy) {
this->x += dx;
this->y += dy;
if (this->alert)
clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),
this->x, this->y,
this->w, this->h));
}
};
struct PlayerController : public clibgame::Component {
float speed, dx, dy;
PlayerController(float speed) {
this->speed = speed;
this->dx = 0;
this->dy = 0;
}
std::string getName() const { return "playerController"; }
void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {
bool my = false,
mx = false;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
this->dy += speed * dt;
my = true;
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
this->dy -= speed * dt;
my = true;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
this->dx -= speed * dt;
mx = true;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
this->dx += speed * dt;
mx = true;
}
if (!my)
this->dy -= this->dy * dt;
if (!mx)
this->dx -= this->dx * dt;
if (dx != 0 || dy != 0) {
Position& p = dynamic_cast<Position&>(this->getOwner().getComponent("position"));
p.translate(dx * dt, dy * dt);
}
}
};
struct PlayerRender : public clibgame::Component,
public clibgame::Listener {
clibgame::Texture* texture;
clibgame::Shader* shader;
GLuint vao, vbo, ebo;
std::vector<GLfloat> generateCoords(float x, float y,
float w, float h) {
std::vector<GLfloat> vertices = {
x , y , 0, 0,
x + w, y , 1, 0,
x + w, y + h, 1, 1,
x , y + h, 0, 1
};
return vertices;
}
void updateVertices(float x, float y, float w, float h) {
auto vVertices = generateCoords(x, y, w, h);
GLfloat aVertices[vVertices.size()];
for (int i = 0; i < vVertices.size(); i++)
aVertices[i] = vVertices.at(i);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);
}
PlayerRender() {
clibgame::ListenerManager::instance().registerListener(this, "position");
texture = nullptr;
shader = nullptr;
vao = 0;
vbo = 0;
ebo = 0;
}
~PlayerRender() {
if (texture != nullptr)
delete texture;
if (shader != nullptr)
delete shader;
glDeleteVertexArrays(1, &this->vao);
glDeleteBuffers(1, &this->vbo);
glDeleteBuffers(1, &this->ebo);
}
std::string getName() const { return "playerRender"; }
void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
texture = new clibgame::Texture(res.getTexture("res/test.png"));
shader = new clibgame::Shader(res.getShader("res/test"));
glGenVertexArrays(1, &this->vao);
glBindVertexArray(this->vao);
glGenBuffers(1, &this->vbo);
this->updateVertices(0, 0, 0.1, 0.1);
glGenBuffers(1, &this->ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
GLuint order[] = {
0, 1, 2,
2, 3, 0
};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
}
void render() const {
glBindVertexArray(this->vao);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
glUseProgram(this->shader->getShaderID());
// Initializing the coordinates.
GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");
glEnableVertexAttribArray(coordAttrib);
glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);
// Initializing the texture.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());
glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
void alert(const clibgame::Event&& e) {
if (e.getEventType() == "position") {
const PositionEvent&& pe = dynamic_cast<const PositionEvent&&>(e);
this->updateVertices(pe.x, pe.y,
pe.w, pe.h);
}
}
};
// A component to perform text rendering.
struct TextRender : public clibgame::Component {
std::unique_ptr<clibgame::Shader> shader;
std::unique_ptr<clibgame::Font> font;
std::string fontName;
GLFWwindow* window;
std::string str;
float x, y;
GLuint ebo;
GLuint vbo;
// Constructing a new text render.
TextRender(std::string fontName, std::string str, float x, float y) {
this->font = nullptr;
this->fontName = fontName;
this->str = str;
this->x = x;
this->y = y;
this->vbo = 0;
this->ebo = 0;
}
// Deleting a text render.
~TextRender() {
if (vbo != 0)
glDeleteBuffers(1, &this->vbo);
if (ebo != 0)
glDeleteBuffers(1, &this->ebo);
}
std::string getName() const { return "textRender"; }
void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
shader = std::unique_ptr<clibgame::Shader>(new clibgame::Shader(res.getShader("res/fontshader")));
font = std::unique_ptr<clibgame::Font>(new clibgame::Font(res.getFont(this->fontName)));
this->window = window;
glGenBuffers(1, &this->vbo);
glGenBuffers(1, &this->ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
GLuint order[] = { 0, 1, 2, 2, 3, 0 };
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
}
void render() const {
FT_Face fontFace = this->font->getFontFace();
glUseProgram(this->shader->getShaderID());
// Getting the window size.
int width, height;
glfwGetWindowSize(window, &width, &height);
glUniform2f(glGetUniformLocation(this->shader->getShaderID(), "in_size"), width, height);
// Setting the text color.
glUniform4f(glGetUniformLocation(this->shader->getShaderID(), "in_color"), 1, 1, 1, 1);
// Loading up the texture.
GLuint tex;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Loading up the VBO.
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
// Loading up the EBO.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
// Setting the vertex coordinate.
GLint posAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
float tx = this->x,
ty = this->y;
FT_GlyphSlot g = fontFace->glyph;
for (const char* ptr = str.c_str(); *ptr; ptr++) {
if (FT_Load_Char(fontFace, *ptr, FT_LOAD_RENDER))
continue;
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
g->bitmap.width,
g->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
g->bitmap.buffer
);
float w = g->bitmap.width,
h = g->bitmap.rows;
GLfloat box[] = {
tx , ty , 0, 1,
tx + w, ty , 1, 1,
tx + w, ty + h, 1, 0,
tx , ty + h, 0, 0
};
glBufferData(GL_ARRAY_BUFFER, sizeof(box), box, GL_DYNAMIC_DRAW);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
tx += g->advance.x >> 6;
ty += g->advance.y >> 6;
}
glDeleteTextures(1, &tex);
GLenum err = glGetError();
if (err != GL_NO_ERROR)
std::cout << static_cast<int>(err) << std::endl;
}
};
// Creating a new game.
Game::Game() {
this->addEntity("player");
this->getEntity("player").addComponent(new Position(0, 0, 0.1, 0.1, true));
this->getEntity("player").addComponent(new PlayerController(1));
this->getEntity("player").addComponent(new PlayerRender());
this->addEntity("sometext");
this->getEntity("sometext").addComponent(new TextRender("res/testfont.ttf", "Testing!", 10, 10));
}
<commit_msg>Removed a glGetError() print.<commit_after>#include "game.hpp"
//////////
// Code //
struct PositionEvent : public clibgame::Event {
std::string name;
float x, y;
float w, h;
PositionEvent(std::string name,
float x, float y,
float w, float h) {
this->name = name;
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
std::string getEventType() const { return this->name; }
};
struct Position : public clibgame::Component {
float x, y, w, h;
bool alert;
Position(float x, float y,
float w, float h,
bool alert) {
this->x = x;
this->y = y;
this->w = w;
this->h = h;
this->alert = alert;
}
std::string getName() const { return "position"; }
void translate(float dx, float dy) {
this->x += dx;
this->y += dy;
if (this->alert)
clibgame::ListenerManager::instance().alert(PositionEvent(this->getName(),
this->x, this->y,
this->w, this->h));
}
};
struct PlayerController : public clibgame::Component {
float speed, dx, dy;
PlayerController(float speed) {
this->speed = speed;
this->dx = 0;
this->dy = 0;
}
std::string getName() const { return "playerController"; }
void update(GLFWwindow* window, const clibgame::ECP& ecp, float dt) {
bool my = false,
mx = false;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
this->dy += speed * dt;
my = true;
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
this->dy -= speed * dt;
my = true;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
this->dx -= speed * dt;
mx = true;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
this->dx += speed * dt;
mx = true;
}
if (!my)
this->dy -= this->dy * dt;
if (!mx)
this->dx -= this->dx * dt;
if (dx != 0 || dy != 0) {
Position& p = dynamic_cast<Position&>(this->getOwner().getComponent("position"));
p.translate(dx * dt, dy * dt);
}
}
};
struct PlayerRender : public clibgame::Component,
public clibgame::Listener {
clibgame::Texture* texture;
clibgame::Shader* shader;
GLuint vao, vbo, ebo;
std::vector<GLfloat> generateCoords(float x, float y,
float w, float h) {
std::vector<GLfloat> vertices = {
x , y , 0, 0,
x + w, y , 1, 0,
x + w, y + h, 1, 1,
x , y + h, 0, 1
};
return vertices;
}
void updateVertices(float x, float y, float w, float h) {
auto vVertices = generateCoords(x, y, w, h);
GLfloat aVertices[vVertices.size()];
for (int i = 0; i < vVertices.size(); i++)
aVertices[i] = vVertices.at(i);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(aVertices), aVertices, GL_DYNAMIC_DRAW);
}
PlayerRender() {
clibgame::ListenerManager::instance().registerListener(this, "position");
texture = nullptr;
shader = nullptr;
vao = 0;
vbo = 0;
ebo = 0;
}
~PlayerRender() {
if (texture != nullptr)
delete texture;
if (shader != nullptr)
delete shader;
glDeleteVertexArrays(1, &this->vao);
glDeleteBuffers(1, &this->vbo);
glDeleteBuffers(1, &this->ebo);
}
std::string getName() const { return "playerRender"; }
void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
texture = new clibgame::Texture(res.getTexture("res/test.png"));
shader = new clibgame::Shader(res.getShader("res/test"));
glGenVertexArrays(1, &this->vao);
glBindVertexArray(this->vao);
glGenBuffers(1, &this->vbo);
this->updateVertices(0, 0, 0.1, 0.1);
glGenBuffers(1, &this->ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
GLuint order[] = {
0, 1, 2,
2, 3, 0
};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
}
void render() const {
glBindVertexArray(this->vao);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
glUseProgram(this->shader->getShaderID());
// Initializing the coordinates.
GLint coordAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");
glEnableVertexAttribArray(coordAttrib);
glVertexAttribPointer(coordAttrib, 4, GL_FLOAT, GL_FALSE, 0, 0);
// Initializing the texture.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture->getTextureID());
glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
void alert(const clibgame::Event&& e) {
if (e.getEventType() == "position") {
const PositionEvent&& pe = dynamic_cast<const PositionEvent&&>(e);
this->updateVertices(pe.x, pe.y,
pe.w, pe.h);
}
}
};
// A component to perform text rendering.
struct TextRender : public clibgame::Component {
std::unique_ptr<clibgame::Shader> shader;
std::unique_ptr<clibgame::Font> font;
std::string fontName;
GLFWwindow* window;
std::string str;
float x, y;
GLuint ebo;
GLuint vbo;
// Constructing a new text render.
TextRender(std::string fontName, std::string str, float x, float y) {
this->font = nullptr;
this->fontName = fontName;
this->str = str;
this->x = x;
this->y = y;
this->vbo = 0;
this->ebo = 0;
}
// Deleting a text render.
~TextRender() {
if (vbo != 0)
glDeleteBuffers(1, &this->vbo);
if (ebo != 0)
glDeleteBuffers(1, &this->ebo);
}
std::string getName() const { return "textRender"; }
void init(GLFWwindow* window, const clibgame::ECP& ecp, const clibgame::Res& res) {
shader = std::unique_ptr<clibgame::Shader>(new clibgame::Shader(res.getShader("res/fontshader")));
font = std::unique_ptr<clibgame::Font>(new clibgame::Font(res.getFont(this->fontName)));
this->window = window;
glGenBuffers(1, &this->vbo);
glGenBuffers(1, &this->ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
GLuint order[] = { 0, 1, 2, 2, 3, 0 };
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(order), order, GL_STATIC_DRAW);
}
void render() const {
FT_Face fontFace = this->font->getFontFace();
glUseProgram(this->shader->getShaderID());
// Getting the window size.
int width, height;
glfwGetWindowSize(window, &width, &height);
glUniform2f(glGetUniformLocation(this->shader->getShaderID(), "in_size"), width, height);
// Setting the text color.
glUniform4f(glGetUniformLocation(this->shader->getShaderID(), "in_color"), 1, 1, 1, 1);
// Loading up the texture.
GLuint tex;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glUniform1i(glGetUniformLocation(this->shader->getShaderID(), "in_tex"), 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Loading up the VBO.
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
// Loading up the EBO.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
// Setting the vertex coordinate.
GLint posAttrib = glGetAttribLocation(this->shader->getShaderID(), "in_coordinates");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
float tx = this->x,
ty = this->y;
FT_GlyphSlot g = fontFace->glyph;
for (const char* ptr = str.c_str(); *ptr; ptr++) {
if (FT_Load_Char(fontFace, *ptr, FT_LOAD_RENDER))
continue;
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
g->bitmap.width,
g->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
g->bitmap.buffer
);
float w = g->bitmap.width,
h = g->bitmap.rows;
GLfloat box[] = {
tx , ty , 0, 1,
tx + w, ty , 1, 1,
tx + w, ty + h, 1, 0,
tx , ty + h, 0, 0
};
glBufferData(GL_ARRAY_BUFFER, sizeof(box), box, GL_DYNAMIC_DRAW);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
tx += g->advance.x >> 6;
ty += g->advance.y >> 6;
}
glDeleteTextures(1, &tex);
}
};
// Creating a new game.
Game::Game() {
this->addEntity("player");
this->getEntity("player").addComponent(new Position(0, 0, 0.1, 0.1, true));
this->getEntity("player").addComponent(new PlayerController(4));
this->getEntity("player").addComponent(new PlayerRender());
this->addEntity("sometext");
this->getEntity("sometext").addComponent(new TextRender("res/testfont.ttf", "Testing!", 10, 10));
}
<|endoftext|> |
<commit_before>// friend class as template parameter
// originally found in package 'zipios'
// typechecking results:
// errors: 0
// warnings: 0
// error: k0069.cc:15:12: internal error: found dependent type `Friend' in non-template
// ERR-MATCH: internal error: found dependent type `.*?' in non-template
template< class Type > struct T {
friend struct Friend ;
};
struct Friend;
typedef T< Friend > T1 ;
<commit_msg>Refine err-match<commit_after>// friend class as template parameter
// originally found in package 'zipios'
// typechecking results:
// errors: 0
// warnings: 0
// error: k0069.cc:15:12: internal error: found dependent type `Friend' in non-template
// ERR-MATCH: internal error: found dependent type `[^(].*?' in non-template
template< class Type > struct T {
friend struct Friend ;
};
struct Friend;
typedef T< Friend > T1 ;
<|endoftext|> |
<commit_before>#ifndef PERMUTE_PERMUTE_HPP
#define PERMUTE_PERMUTE_HPP
#include <cmath>
#include <string>
#include "../base-conversion/base_conversion.hpp"
namespace n {
void permute(int n, int k, void (*f)(const std::string &)) {
int numPermutations = pow(k, n);
std::string configuration;
for (int i = 0; i < numPermutations; i++) {
configuration = convert_base(i, 10, k);
(*f)(std::string(n - configuration.length(), '0').append(configuration));
}
}
} // namespace n
#endif
<commit_msg>Bug fixes<commit_after>#ifndef PERMUTE_PERMUTE_HPP
#define PERMUTE_PERMUTE_HPP
#include <cmath>
#include <string>
#include "base_conversion.hpp"
namespace n {
void permute(int n, int k, void (*f)(const std::string &)) {
int numPermutations = pow(k, n);
std::string configuration;
for (int i = 0; i < numPermutations; i++) {
configuration = convert_base(i, 10, k);
(*f)(std::string(n - configuration.length(), '0').append(configuration));
}
}
} // namespace n
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 BOOST_TEST_MAIN
#define BOOST_TEST_MODULE segmenttype_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/segmenttype.h>
using namespace votca::xtp;
BOOST_AUTO_TEST_SUITE(segmenttype_test)
BOOST_AUTO_TEST_CASE(constructors_test) {
SegmentType segT();
SegmentType segT2(1,"Name","SP","file.orb","coord.xyz",true);
}
BOOST_AUTO_TEST_CASE(getters_test) {
SegmentType segT(1,"Name","SP","file.orb","coord.xyz",true);
BOOST_CHECK_EQUAL(segT.getBasisName(),"SP");
BOOST_CHECK_EQUAL(segT.getOrbitalsFile(),"file.orb");
BOOST_CHECK_EQUAL(segT.getQMCoordsFile(),"coord.xyz");
BOOST_CHECK_EQUAL(segT.canRigidify(),true);
BOOST_CHECK_EQUAL(segT.getId(),1);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test_segmenttype: fix a warning<commit_after>/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 BOOST_TEST_MAIN
#define BOOST_TEST_MODULE segmenttype_test
#include <boost/test/unit_test.hpp>
#include <votca/xtp/segmenttype.h>
using namespace votca::xtp;
BOOST_AUTO_TEST_SUITE(segmenttype_test)
BOOST_AUTO_TEST_CASE(constructors_test) {
SegmentType segT;
SegmentType segT2(1,"Name","SP","file.orb","coord.xyz",true);
}
BOOST_AUTO_TEST_CASE(getters_test) {
SegmentType segT(1,"Name","SP","file.orb","coord.xyz",true);
BOOST_CHECK_EQUAL(segT.getBasisName(),"SP");
BOOST_CHECK_EQUAL(segT.getOrbitalsFile(),"file.orb");
BOOST_CHECK_EQUAL(segT.getQMCoordsFile(),"coord.xyz");
BOOST_CHECK_EQUAL(segT.canRigidify(),true);
BOOST_CHECK_EQUAL(segT.getId(),1);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
/**
* \file logging.hh
* \brief logging
**/
#ifndef DUNE_STUFF_COMMON_LOGGING_HH
#define DUNE_STUFF_COMMON_LOGGING_HH
#include <map>
#include <string>
#include <mutex>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <dune/stuff/common/logstreams.hh>
namespace Dune {
namespace Stuff {
namespace Common {
class Logging;
//! global Logging instance
inline Logging& Logger();
/** \brief handles all logging
**/
class Logging
{
private:
Logging();
//! cleanup stream and flag containers
void deinit();
public:
~Logging();
/** \brief setup loglevel, logfilename
* \param logflags any OR'd combination of flags
* \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant
**/
void create(int logflags = (LOG_FILE | LOG_CONSOLE | LOG_ERROR),
const std::string logfile = "dune_stuff_log",
const std::string datadir = "data",
const std::string _logdir = std::string("log"));
//! \attention This will probably not do wht we want it to!
void setPrefix(std::string prefix);
void setStreamFlags(int streamID, int flags);
int getStreamFlags(int streamID) const;
/** \name forwarded Log functions
* \{
*/
template< class T >
void log(T c, int streamID)
{
getStream(streamID) << c;
} // Log
/** \}
*/
LogStream& getStream(int streamId);
LogStream& error() { return getStream(LOG_ERROR); }
LogStream& info() { return getStream(LOG_INFO); }
LogStream& debug() { return getStream(LOG_DEBUG); }
LogStream& devnull() { return emptyLogStream_; }
//! flush all active streams
void flush();
//! creates a new LogStream with given id
int addStream(int flags);
//! re-enable all logging below given priority level
void resume(LogStream::PriorityType prio = LogStream::default_suspend_priority);
//! (temporarily) disable all logging below given priority level
void suspend(LogStream::PriorityType prio = LogStream::default_suspend_priority);
struct SuspendLocal
{
LogStream::PriorityType prio_;
SuspendLocal(LogStream::PriorityType prio = LogStream::default_suspend_priority)
: prio_(prio) {
Logger().suspend(prio_);
}
~SuspendLocal() {
Logger().resume(prio_);
}
};
struct ResumeLocal
{
LogStream::PriorityType prio_;
ResumeLocal(LogStream::PriorityType prio = LogStream::default_suspend_priority)
: prio_(prio) {
Logger().resume(prio_);
}
~ResumeLocal() {
Logger().suspend(prio_);
}
};
private:
boost::filesystem::path filename_;
boost::filesystem::path filenameWoTime_;
boost::filesystem::ofstream logfile_;
typedef std::map< int, int > FlagMap;
FlagMap flagmap_;
typedef std::map< int, std::unique_ptr< LogStream> > StreamMap;
StreamMap streammap_;
typedef std::vector< int > IdVec;
IdVec streamIDs_;
int logflags_;
EmptyLogStream emptyLogStream_;
friend Logging& Logger();
// satisfy stricter warnings wrt copying
Logging(const Logging&) = delete;
Logging& operator=(const Logging&) = delete;
};
inline Logging& Logger()
{
static Logging log;
return log;
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
#define DSC_LOG Dune::Stuff::Common::Logger()
#define DSC_LOG_INFO DSC_LOG.info()
#define DSC_LOG_DEBUG DSC_LOG.debug()
#define DSC_LOG_ERROR DSC_LOG.error()
#define DSC_LOG_DEVNULL DSC_LOG.devnull()
#define DSC_LOG_INFO_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.info() : DSC_LOG.devnull())
#define DSC_LOG_DEBUG_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.debug() : DSC_LOG.devnull())
#define DSC_LOG_ERROR_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.error() : DSC_LOG.devnull())
#endif // DUNE_STUFF_COMMON_LOGGING_HH
<commit_msg>[common.logging] silence warnings from boost<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
/**
* \file logging.hh
* \brief logging
**/
#ifndef DUNE_STUFF_COMMON_LOGGING_HH
#define DUNE_STUFF_COMMON_LOGGING_HH
#include <map>
#include <string>
#include <mutex>
#include <dune/stuff/common/disable_warnings.hh>
# include <boost/filesystem.hpp>
# include <boost/filesystem/fstream.hpp>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/logstreams.hh>
namespace Dune {
namespace Stuff {
namespace Common {
class Logging;
//! global Logging instance
inline Logging& Logger();
/** \brief handles all logging
**/
class Logging
{
private:
Logging();
//! cleanup stream and flag containers
void deinit();
public:
~Logging();
/** \brief setup loglevel, logfilename
* \param logflags any OR'd combination of flags
* \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant
**/
void create(int logflags = (LOG_FILE | LOG_CONSOLE | LOG_ERROR),
const std::string logfile = "dune_stuff_log",
const std::string datadir = "data",
const std::string _logdir = std::string("log"));
//! \attention This will probably not do wht we want it to!
void setPrefix(std::string prefix);
void setStreamFlags(int streamID, int flags);
int getStreamFlags(int streamID) const;
/** \name forwarded Log functions
* \{
*/
template< class T >
void log(T c, int streamID)
{
getStream(streamID) << c;
} // Log
/** \}
*/
LogStream& getStream(int streamId);
LogStream& error() { return getStream(LOG_ERROR); }
LogStream& info() { return getStream(LOG_INFO); }
LogStream& debug() { return getStream(LOG_DEBUG); }
LogStream& devnull() { return emptyLogStream_; }
//! flush all active streams
void flush();
//! creates a new LogStream with given id
int addStream(int flags);
//! re-enable all logging below given priority level
void resume(LogStream::PriorityType prio = LogStream::default_suspend_priority);
//! (temporarily) disable all logging below given priority level
void suspend(LogStream::PriorityType prio = LogStream::default_suspend_priority);
struct SuspendLocal
{
LogStream::PriorityType prio_;
SuspendLocal(LogStream::PriorityType prio = LogStream::default_suspend_priority)
: prio_(prio) {
Logger().suspend(prio_);
}
~SuspendLocal() {
Logger().resume(prio_);
}
};
struct ResumeLocal
{
LogStream::PriorityType prio_;
ResumeLocal(LogStream::PriorityType prio = LogStream::default_suspend_priority)
: prio_(prio) {
Logger().resume(prio_);
}
~ResumeLocal() {
Logger().suspend(prio_);
}
};
private:
boost::filesystem::path filename_;
boost::filesystem::path filenameWoTime_;
boost::filesystem::ofstream logfile_;
typedef std::map< int, int > FlagMap;
FlagMap flagmap_;
typedef std::map< int, std::unique_ptr< LogStream> > StreamMap;
StreamMap streammap_;
typedef std::vector< int > IdVec;
IdVec streamIDs_;
int logflags_;
EmptyLogStream emptyLogStream_;
friend Logging& Logger();
// satisfy stricter warnings wrt copying
Logging(const Logging&) = delete;
Logging& operator=(const Logging&) = delete;
};
inline Logging& Logger()
{
static Logging log;
return log;
}
} // namespace Common
} // namespace Stuff
} // namespace Dune
#define DSC_LOG Dune::Stuff::Common::Logger()
#define DSC_LOG_INFO DSC_LOG.info()
#define DSC_LOG_DEBUG DSC_LOG.debug()
#define DSC_LOG_ERROR DSC_LOG.error()
#define DSC_LOG_DEVNULL DSC_LOG.devnull()
#define DSC_LOG_INFO_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.info() : DSC_LOG.devnull())
#define DSC_LOG_DEBUG_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.debug() : DSC_LOG.devnull())
#define DSC_LOG_ERROR_0 \
(Dune::MPIHelper::getCollectiveCommunication().rank() == 0 ? DSC_LOG.error() : DSC_LOG.devnull())
#endif // DUNE_STUFF_COMMON_LOGGING_HH
<|endoftext|> |
<commit_before>#include <taichi/visual/gui.h>
#include "../tlang.h"
TLANG_NAMESPACE_BEGIN
bool use_gui = false;
auto volume_renderer = [] {
// CoreState::set_trigger_gdb_when_crash(true);
int depth_limit = 40;
int n = 512;
int grid_resolution = 256;
Vector3 albedo(0.95, 0.95, 0.95);
float32 scale = 724.0;
float32 one_over_four_pi = 0.07957747154;
float32 pi = 3.14159265359;
auto f = fopen("snow_density_256.bin", "rb");
TC_ASSERT_INFO(f, "./snow_density_256.bin not found");
std::vector<float32> density_field(pow<3>(grid_resolution));
std::fread(density_field.data(), sizeof(float32), density_field.size(), f);
std::fclose(f);
Program prog(Arch::gpu);
prog.config.print_ir = true;
Vector buffer(DataType::f32, 3);
Global(density, f32);
layout([&]() {
root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));
root.dense(Indices(0, 1, 2), grid_resolution).place(density);
});
auto point_inside_box = [&](Vector p) {
return Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) && p(1) < 1.0f &&
0.0f <= p(2) && p(2) < 1.0f);
};
// If p is in the density field, return the density, otherwise return 0
auto query_density = [&](Vector p) {
auto inside_box = point_inside_box(p);
auto ret = Var(0.0f);
If(inside_box).Then([&] {
auto i = floor(p(0) * float32(grid_resolution));
auto j = floor(p(1) * float32(grid_resolution));
auto k = floor(p(2) * float32(grid_resolution));
ret = density[i, j, k] * scale;
});
return ret;
};
// Adapted from Mitsuba: include/mitsuba/core/aabb.h#L308
auto box_intersect = [&](Vector o, Vector d, Expr &near_t, Expr &far_t) {
auto result = Var(1);
/* For each pair of AABB planes */
for (int i = 0; i < 3; i++) {
auto origin = o(i);
auto min_val = Var(0.f);
auto max_val = Var(1.f);
auto d_rcp = Var(1.f / d(i));
If(d(i) == 0.f)
.Then([&] {
/* The ray is parallel to the planes */
If(origin < min_val || origin > max_val, [&] { result = 0; });
})
.Else([&] {
/* Calculate intersection distances */
auto t1 = Var((min_val - origin) * d_rcp);
auto t2 = Var((max_val - origin) * d_rcp);
If(t1 > t2, [&] {
auto tmp = Var(t1);
t1 = t2;
t2 = tmp;
});
near_t = max(t1, near_t);
far_t = min(t2, far_t);
If(near_t > far_t, [&] { result = 0; });
});
}
return result;
};
// Adapted from Mitsuba: src/libcore/warp.cpp#L25
auto sample_phase_isotropic = [&]() {
auto z = Var(1.0f - 2.0f * Rand<float32>());
auto r = Var(sqrt(1.0f - z * z));
auto phi = Var(2.0f * pi * Rand<float32>());
auto sin_phi = Var(sin(phi));
auto cos_phi = Var(cos(phi));
return Var(Vector({r * cos_phi, r * sin_phi, z}));
};
auto pdf_phase_isotropic = [&]() { return Var(one_over_four_pi); };
auto eval_phase_isotropic = [&]() { return pdf_phase_isotropic(); };
// Direct sample light
auto sample_light = [&](Vector p, float32 inv_max_density) {
auto Le = Var(Vector({5.0f, 5.0f, 5.0f}));
auto light_p = Var(Vector({0.5f, 1.5f, 0.5f}));
auto dir_to_p = Var(p - light_p);
auto dist_to_p = Var(dir_to_p.norm());
auto inv_dist_to_p = Var(1.f / dist_to_p);
dir_to_p = normalized(dir_to_p);
auto near_t = Var(-std::numeric_limits<float>::max());
auto far_t = Var(std::numeric_limits<float>::max());
auto hit = box_intersect(light_p, dir_to_p, near_t, far_t);
auto interaction = Var(0);
auto transmittance = Var(1.f);
If(hit, [&] {
auto cond = Var(hit);
auto t = Var(near_t);
While(cond, [&] {
t -= log(1.f - Rand<float32>()) * inv_max_density;
p = Var(light_p + t * dir_to_p);
If(t >= dist_to_p || !point_inside_box(p))
.Then([&] { cond = 0; })
.Else([&] {
auto density_at_p = query_density(p);
If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
cond = 0;
transmittance = Var(0.f);
});
});
});
});
return Var(transmittance * Le * inv_dist_to_p * inv_dist_to_p);
};
// Woodcock tracking
auto sample_distance = [&](Vector o, Vector d, float32 inv_max_density,
Expr &dist, Vector &sigma_s, Expr &transmittance,
Vector &p) {
auto near_t = Var(-std::numeric_limits<float>::max());
auto far_t = Var(std::numeric_limits<float>::max());
auto hit = box_intersect(o, d, near_t, far_t);
auto cond = Var(hit);
auto interaction = Var(0);
auto t = Var(near_t);
While(cond, [&] {
t -= log(1.f - Rand<float32>()) * inv_max_density;
p = Var(o + t * d);
If(t >= far_t || !point_inside_box(p)).Then([&] { cond = 0; }).Else([&] {
auto density_at_p = query_density(p);
If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
sigma_s(0) = Var(density_at_p * albedo[0]);
sigma_s(1) = Var(density_at_p * albedo[1]);
sigma_s(2) = Var(density_at_p * albedo[2]);
If(density_at_p != 0.f).Then([&] {
transmittance = 1.f / density_at_p;
});
cond = 0;
interaction = 1;
});
});
});
dist = t - near_t;
return hit && interaction;
};
auto background = [](Vector dir) { return Vector({0.4f, 0.4f, 0.4f}); };
float32 fov = 0.7;
auto max_density =
*std::max_element(density_field.begin(), density_field.end()) * scale;
auto inv_max_density = 0.f;
if (max_density > 0.f) {
inv_max_density = 1.f / max_density;
}
Kernel(main).def([&]() {
For(0, n * n * 2, [&](Expr i) {
auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));
auto c = Var(Vector(
{fov * ((Rand<float32>() + cast<float32>(i / n)) / float32(n / 2) -
2.0f),
fov * ((Rand<float32>() + cast<float32>(i % n)) / float32(n / 2) -
1.0f),
-1.0f}));
c = normalized(c);
auto color = Var(Vector({1.0f, 1.0f, 1.0f}));
auto Li = Var(Vector({0.0f, 0.0f, 0.0f}));
auto throughput = Var(Vector({1.0f, 1.0f, 1.0f}));
auto depth = Var(0);
While(depth < depth_limit, [&] {
auto dist = Var(0.f);
auto transmittance = Var(0.f);
auto sigma_s = Var(Vector({0.f, 0.f, 0.f}));
auto interaction_p = Var(Vector({0.f, 0.f, 0.f}));
auto interaction =
sample_distance(orig, c, inv_max_density, dist, sigma_s,
transmittance, interaction_p);
depth += 1;
If(interaction)
.Then([&] {
throughput =
throughput.element_wise_prod(sigma_s * transmittance);
auto phase_value = eval_phase_isotropic();
auto light_value = sample_light(interaction_p, inv_max_density);
Li += phase_value * throughput.element_wise_prod(light_value);
orig = interaction_p;
c = sample_phase_isotropic();
})
.Else([&] {
Li += throughput.element_wise_prod(background(c));
depth = depth_limit;
});
});
buffer[i] += Li;
});
});
for (int i = 0; i < grid_resolution; i++) {
for (int j = 0; j < grid_resolution; j++) {
for (int k = 0; k < grid_resolution; k++) {
density.val<float32>(i, j, k) =
density_field[i * grid_resolution * grid_resolution +
j * grid_resolution + k];
}
}
}
std::unique_ptr<GUI> gui = nullptr;
if (use_gui) {
gui = std::make_unique<GUI>("Volume Renderer", Vector2i(n * 2, n));
}
Vector2i render_size(n * 2, n);
Array2D<Vector4> render_buffer;
auto tone_map = [](real x) { return x; };
constexpr int N = 100;
for (int frame = 0; frame < 100; frame++) {
for (int i = 0; i < N; i++) {
main();
}
prog.profiler_print();
real scale = 1.0f / ((frame + 1) * N);
render_buffer.initialize(render_size);
std::unique_ptr<Canvas> canvas;
canvas = std::make_unique<Canvas>(render_buffer);
for (int i = 0; i < n * n * 2; i++) {
render_buffer[i / n][i % n] =
Vector4(tone_map(scale * buffer(0).val<float32>(i)),
tone_map(scale * buffer(1).val<float32>(i)),
tone_map(scale * buffer(2).val<float32>(i)), 1);
}
if (use_gui) {
gui->canvas->img = canvas->img;
gui->update();
} else {
canvas->img.write_as_image(
fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, depth_limit));
}
}
};
TC_REGISTER_TASK(volume_renderer);
auto volume_renderer_gui = [] {
use_gui = true;
volume_renderer();
};
TC_REGISTER_TASK(volume_renderer_gui);
TLANG_NAMESPACE_END
<commit_msg>snow parameter tweaks<commit_after>#include <taichi/visual/gui.h>
#include "../tlang.h"
TLANG_NAMESPACE_BEGIN
bool use_gui = false;
auto volume_renderer = [] {
// CoreState::set_trigger_gdb_when_crash(true);
int depth_limit = 5;
int n = 512;
int grid_resolution = 256;
Vector3 albedo(0.9, 0.95, 1);
float32 scale = 724.0;
float32 one_over_four_pi = 0.07957747154f;
float32 pi = 3.14159265359f;
auto f = fopen("snow_density_256.bin", "rb");
TC_ASSERT_INFO(f, "./snow_density_256.bin not found");
std::vector<float32> density_field(pow<3>(grid_resolution));
std::fread(density_field.data(), sizeof(float32), density_field.size(), f);
std::fclose(f);
Program prog(Arch::gpu);
prog.config.print_ir = true;
Vector buffer(DataType::f32, 3);
Global(density, f32);
layout([&]() {
root.dense(Index(0), n * n * 2).place(buffer(0), buffer(1), buffer(2));
root.dense(Indices(0, 1, 2), grid_resolution).place(density);
});
auto point_inside_box = [&](Vector p) {
return Var(0.0f <= p(0) && p(0) < 1.0f && 0.0f <= p(1) && p(1) < 1.0f &&
0.0f <= p(2) && p(2) < 1.0f);
};
// If p is in the density field, return the density, otherwise return 0
auto query_density = [&](Vector p) {
auto inside_box = point_inside_box(p);
auto ret = Var(0.0f);
If(inside_box).Then([&] {
auto i = floor(p(0) * float32(grid_resolution));
auto j = floor(p(1) * float32(grid_resolution));
auto k = floor(p(2) * float32(grid_resolution));
ret = density[i, j, k];
});
return ret;
};
// Adapted from Mitsuba: include/mitsuba/core/aabb.h#L308
auto box_intersect = [&](Vector o, Vector d, Expr &near_t, Expr &far_t) {
auto result = Var(1);
/* For each pair of AABB planes */
for (int i = 0; i < 3; i++) {
auto origin = o(i);
auto min_val = Var(0.f);
auto max_val = Var(1.f);
auto d_rcp = Var(1.f / d(i));
If(d(i) == 0.f)
.Then([&] {
/* The ray is parallel to the planes */
If(origin < min_val || origin > max_val, [&] { result = 0; });
})
.Else([&] {
/* Calculate intersection distances */
auto t1 = Var((min_val - origin) * d_rcp);
auto t2 = Var((max_val - origin) * d_rcp);
If(t1 > t2, [&] {
auto tmp = Var(t1);
t1 = t2;
t2 = tmp;
});
near_t = max(t1, near_t);
far_t = min(t2, far_t);
If(near_t > far_t, [&] { result = 0; });
});
}
return result;
};
// Adapted from Mitsuba: src/libcore/warp.cpp#L25
auto sample_phase_isotropic = [&]() {
auto z = Var(1.0f - 2.0f * Rand<float32>());
auto r = Var(sqrt(1.0f - z * z));
auto phi = Var(2.0f * pi * Rand<float32>());
auto sin_phi = Var(sin(phi));
auto cos_phi = Var(cos(phi));
return Var(Vector({r * cos_phi, r * sin_phi, z}));
};
auto pdf_phase_isotropic = [&]() { return Var(one_over_four_pi); };
auto eval_phase_isotropic = [&]() { return pdf_phase_isotropic(); };
// Direct sample light
auto sample_light = [&](Vector p, float32 inv_max_density) {
auto Le = Var(700.0f * Vector({5.0f, 5.0f, 5.0f}));
auto light_p = Var(10.0f * Vector({2.5f, 1.0f, 0.5f}));
auto dir_to_p = Var(p - light_p);
auto dist_to_p = Var(dir_to_p.norm());
auto inv_dist_to_p = Var(1.f / dist_to_p);
dir_to_p = normalized(dir_to_p);
auto near_t = Var(-std::numeric_limits<float>::max());
auto far_t = Var(std::numeric_limits<float>::max());
auto hit = box_intersect(light_p, dir_to_p, near_t, far_t);
auto interaction = Var(0);
auto transmittance = Var(1.f);
If(hit, [&] {
auto cond = Var(hit);
auto t = Var(near_t);
While(cond, [&] {
t -= log(1.f - Rand<float32>()) * inv_max_density;
p = Var(light_p + t * dir_to_p);
If(t >= dist_to_p || !point_inside_box(p))
.Then([&] { cond = 0; })
.Else([&] {
auto density_at_p = query_density(p);
If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
cond = 0;
transmittance = Var(0.f);
});
});
});
});
return Var(transmittance * Le * inv_dist_to_p * inv_dist_to_p);
};
// Woodcock tracking
auto sample_distance = [&](Vector o, Vector d, float32 inv_max_density,
Expr &dist, Vector &sigma_s, Expr &transmittance,
Vector &p) {
auto near_t = Var(-std::numeric_limits<float>::max());
auto far_t = Var(std::numeric_limits<float>::max());
auto hit = box_intersect(o, d, near_t, far_t);
auto cond = Var(hit);
auto interaction = Var(0);
auto t = Var(near_t);
While(cond, [&] {
t -= log(1.f - Rand<float32>()) * inv_max_density;
p = Var(o + t * d);
If(t >= far_t || !point_inside_box(p)).Then([&] { cond = 0; }).Else([&] {
auto density_at_p = query_density(p);
If(density_at_p * inv_max_density > Rand<float32>()).Then([&] {
sigma_s(0) = Var(density_at_p * albedo[0]);
sigma_s(1) = Var(density_at_p * albedo[1]);
sigma_s(2) = Var(density_at_p * albedo[2]);
If(density_at_p != 0.f).Then([&] {
transmittance = 1.f / density_at_p;
});
cond = 0;
interaction = 1;
});
});
});
dist = t - near_t;
return hit && interaction;
};
auto background = [](Vector dir) { return Vector({0.4f, 0.4f, 0.4f}); };
float32 fov = 0.5;
auto max_density = 0.0f;
for (int i = 0; i < pow<3>(grid_resolution); i++) {
max_density = std::max(max_density, density_field[i]);
}
for (int i = 0; i < pow<3>(grid_resolution); i++) {
density_field[i] /= max_density; // normalize to 1 first
density_field[i] *= scale; // then scale
}
max_density = scale;
auto inv_max_density = 0.f;
if (max_density > 0.f) {
inv_max_density = 1.f / max_density;
}
Kernel(main).def([&]() {
For(0, n * n * 2, [&](Expr i) {
auto orig = Var(Vector({0.5f, 0.3f, 1.5f}));
auto c = Var(Vector(
{fov * ((Rand<float32>() + cast<float32>(i / n)) / float32(n / 2) -
2.0f),
fov * ((Rand<float32>() + cast<float32>(i % n)) / float32(n / 2) -
1.0f),
-1.0f}));
c = normalized(c);
auto color = Var(Vector({1.0f, 1.0f, 1.0f}));
auto Li = Var(Vector({0.0f, 0.0f, 0.0f}));
auto throughput = Var(Vector({1.0f, 1.0f, 1.0f}));
auto depth = Var(0);
While(depth < depth_limit, [&] {
auto dist = Var(0.f);
auto transmittance = Var(0.f);
auto sigma_s = Var(Vector({0.f, 0.f, 0.f}));
auto interaction_p = Var(Vector({0.f, 0.f, 0.f}));
auto interaction =
sample_distance(orig, c, inv_max_density, dist, sigma_s,
transmittance, interaction_p);
depth += 1;
If(interaction)
.Then([&] {
throughput =
throughput.element_wise_prod(sigma_s * transmittance);
auto phase_value = eval_phase_isotropic();
auto light_value = sample_light(interaction_p, inv_max_density);
Li += phase_value * throughput.element_wise_prod(light_value);
orig = interaction_p;
c = sample_phase_isotropic();
})
.Else([&] {
// Li += throughput.element_wise_prod(background(c));
depth = depth_limit;
});
});
buffer[i] += Li;
});
});
for (int i = 0; i < grid_resolution; i++) {
for (int j = 0; j < grid_resolution; j++) {
for (int k = 0; k < grid_resolution; k++) {
density.val<float32>(i, j, k) =
density_field[i * grid_resolution * grid_resolution +
j * grid_resolution + k];
}
}
}
std::unique_ptr<GUI> gui = nullptr;
if (use_gui) {
gui = std::make_unique<GUI>("Volume Renderer", Vector2i(n * 2, n));
}
Vector2i render_size(n * 2, n);
Array2D<Vector4> render_buffer;
auto tone_map = [](real x) { return std::sqrt(x); };
constexpr int N = 10;
for (int frame = 0; frame < 100; frame++) {
for (int i = 0; i < N; i++) {
main();
}
// prog.profiler_print();
real scale = 1.0f / ((frame + 1) * N);
render_buffer.initialize(render_size);
std::unique_ptr<Canvas> canvas;
canvas = std::make_unique<Canvas>(render_buffer);
for (int i = 0; i < n * n * 2; i++) {
render_buffer[i / n][i % n] =
Vector4(tone_map(scale * buffer(0).val<float32>(i)),
tone_map(scale * buffer(1).val<float32>(i)),
tone_map(scale * buffer(2).val<float32>(i)), 1);
}
if (use_gui) {
gui->canvas->img = canvas->img;
gui->update();
} else {
canvas->img.write_as_image(
fmt::format("{:05d}-{:05d}-{:05d}.png", frame, N, depth_limit));
}
}
};
TC_REGISTER_TASK(volume_renderer);
auto volume_renderer_gui = [] {
use_gui = true;
volume_renderer();
};
TC_REGISTER_TASK(volume_renderer_gui);
TLANG_NAMESPACE_END
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//mapnik
#include <mapnik/text/placements/angle.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text/placements/list.hpp>
#include <mapnik/text/placements/dummy.hpp>
namespace
{
using namespace mapnik;
double extract_angle(feature_impl const& feature,
attributes const& vars,
symbolizer_base::value_type const& angle_expression)
{
int angle = util::apply_visitor(extract_value<value_integer>(feature, vars), angle_expression) % 360;
if (angle < 0)
{
angle += 360;
}
return angle * (M_PI / 180.0);
}
symbolizer_base::value_type get_opt(xml_node const& xml, std::string const& name, double default_value = .0)
{
boost::optional<expression_ptr> expression = xml.get_opt_attr<expression_ptr>(name);
return expression ? *expression : static_cast<symbolizer_base::value_type>(default_value);
}
}
namespace mapnik
{
//text_placements_angle class
const box2d<double> text_placements_angle::empty_box;
text_placements_angle::text_placements_angle(text_placements_ptr list_placement,
symbolizer_base::value_type const& angle,
symbolizer_base::value_type const& tolerance,
symbolizer_base::value_type const& step,
boost::optional<expression_ptr> const& anchor_key)
: list_placement_(list_placement),
angle_(angle),
tolerance_(tolerance),
step_(step),
anchor_key_(anchor_key)
{
}
text_placement_info_ptr text_placements_angle::get_placement_info(double scale_factor,
feature_impl const& feature,
attributes const& vars,
symbol_cache const& sc) const
{
text_placement_info_ptr list_placement_info = list_placement_->get_placement_info(scale_factor, feature, vars, sc);
double angle = extract_angle(feature, vars, angle_);
double tolerance = extract_angle(feature, vars, tolerance_);
double step = extract_angle(feature, vars, step_);
if (step == .0)
{
step = default_step;
}
if (anchor_key_)
{
std::string anchor_key = util::apply_visitor(extract_value<std::string>(feature, vars),
static_cast<symbolizer_base::value_type>(*anchor_key_));
if (sc.contains(anchor_key))
{
symbol_cache::symbol const& sym = sc.get(anchor_key);
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, sym.box, list_placement_info);
}
else
{
return std::make_shared<text_placement_info_dummy>(this, scale_factor, 1);
}
}
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, empty_box, list_placement_info);
}
void text_placements_angle::add_expressions(expression_set & output) const
{
list_placement_->add_expressions(output);
if (is_expression(angle_)) output.insert(util::get<expression_ptr>(angle_));
if (is_expression(tolerance_)) output.insert(util::get<expression_ptr>(tolerance_));
if (is_expression(step_)) output.insert(util::get<expression_ptr>(step_));
if (anchor_key_) output.insert(*anchor_key_);
}
text_placements_ptr text_placements_angle::from_xml(xml_node const& xml, fontset_map const& fontsets, bool is_shield)
{
symbolizer_base::value_type angle = get_opt(xml, "angle");
symbolizer_base::value_type tolerance = get_opt(xml, "tolerance");
symbolizer_base::value_type step = get_opt(xml, "step", default_step);
boost::optional<expression_ptr> anchor_key = xml.get_opt_attr<expression_ptr>("anchor-key");
text_placements_ptr list_placement_ptr = text_placements_list::from_xml(xml, fontsets, is_shield);
text_placements_ptr ptr = std::make_shared<text_placements_angle>(list_placement_ptr, angle, tolerance, step, anchor_key);
ptr->defaults.from_xml(xml, fontsets, is_shield);
return ptr;
}
//text_placement_info_angle class
text_placement_info_angle::text_placement_info_angle(text_placements_angle const* parent,
feature_impl const& feature,
attributes const& vars,
double scale_factor,
double angle,
double tolerance,
double step,
box2d<double> const& box,
text_placement_info_ptr list_placement_info)
: text_placement_info(parent, scale_factor),
list_placement_info_(list_placement_info),
feature_(feature),
vars_(vars),
angle_(angle),
box_(box),
dx_(displacement(box.width(), properties.layout_defaults.dx)),
dy_(displacement(box.height(), properties.layout_defaults.dy)),
tolerance_iterator_(tolerance, 0, tolerance_function(step))
{
list_placement_info_->next();
}
void text_placement_info_angle::reset_state()
{
list_placement_info_->reset_state();
list_placement_info_->next();
tolerance_iterator_.reset();
}
bool text_placement_info_angle::try_next_angle() const
{
if (tolerance_iterator_.next())
{
double angle = angle_ + tolerance_iterator_.get();
double dx, dy;
get_point(angle, dx, dy);
properties.layout_defaults.dx = dx;
properties.layout_defaults.dy = dy;
return true;
}
return false;
}
bool text_placement_info_angle::next() const
{
if (try_next_angle())
{
return true;
}
else if (list_placement_info_->next())
{
properties = list_placement_info_->properties;
dx_ = displacement(box_.width(), properties.layout_defaults.dx);
dy_ = displacement(box_.height(), properties.layout_defaults.dy);
tolerance_iterator_.reset();
try_next_angle();
return true;
}
return false;
}
double text_placement_info_angle::displacement(double const& box_size, symbolizer_base::value_type const& displacement) const
{
double d = util::apply_visitor(extract_value<double>(feature_, vars_), displacement);
return box_size / 2.0 + d + .5;
}
void text_placement_info_angle::get_point(double angle, double &x, double &y) const
{
double corner = std::atan(dx_ / dy_);
if ((angle >= 0 && angle <= corner) || (angle >= 2 * M_PI - corner && angle <= 2 * M_PI))
{
x = -dy_ * std::tan(angle);
y = -dy_;
}
else if (angle >= corner && angle <= M_PI - corner)
{
x = -dx_;
y = dx_ * std::tan(angle - M_PI_2);
}
else if (angle >= M_PI_2 * 3 - corner && angle <= M_PI_2 * 3 + corner)
{
x = dx_;
y = dx_ * std::tan(angle - M_PI_2 * 3);
}
else
{
x = dy_ * std::tan(angle - M_PI);
y = dy_;
}
}
}
<commit_msg>text placement angle: fix displacement calculation<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//mapnik
#include <mapnik/text/placements/angle.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text/placements/list.hpp>
#include <mapnik/text/placements/dummy.hpp>
namespace
{
using namespace mapnik;
double extract_angle(feature_impl const& feature,
attributes const& vars,
symbolizer_base::value_type const& angle_expression)
{
int angle = util::apply_visitor(extract_value<value_integer>(feature, vars), angle_expression) % 360;
if (angle < 0)
{
angle += 360;
}
return angle * (M_PI / 180.0);
}
symbolizer_base::value_type get_opt(xml_node const& xml, std::string const& name, double default_value = .0)
{
boost::optional<expression_ptr> expression = xml.get_opt_attr<expression_ptr>(name);
return expression ? *expression : static_cast<symbolizer_base::value_type>(default_value);
}
}
namespace mapnik
{
//text_placements_angle class
const box2d<double> text_placements_angle::empty_box;
text_placements_angle::text_placements_angle(text_placements_ptr list_placement,
symbolizer_base::value_type const& angle,
symbolizer_base::value_type const& tolerance,
symbolizer_base::value_type const& step,
boost::optional<expression_ptr> const& anchor_key)
: list_placement_(list_placement),
angle_(angle),
tolerance_(tolerance),
step_(step),
anchor_key_(anchor_key)
{
}
text_placement_info_ptr text_placements_angle::get_placement_info(double scale_factor,
feature_impl const& feature,
attributes const& vars,
symbol_cache const& sc) const
{
text_placement_info_ptr list_placement_info = list_placement_->get_placement_info(scale_factor, feature, vars, sc);
double angle = extract_angle(feature, vars, angle_);
double tolerance = extract_angle(feature, vars, tolerance_);
double step = extract_angle(feature, vars, step_);
if (step == .0)
{
step = default_step;
}
if (anchor_key_)
{
std::string anchor_key = util::apply_visitor(extract_value<std::string>(feature, vars),
static_cast<symbolizer_base::value_type>(*anchor_key_));
if (sc.contains(anchor_key))
{
symbol_cache::symbol const& sym = sc.get(anchor_key);
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, sym.box, list_placement_info);
}
else
{
return std::make_shared<text_placement_info_dummy>(this, scale_factor, 1);
}
}
return std::make_shared<text_placement_info_angle>(this,
feature, vars, scale_factor, angle, tolerance, step, empty_box, list_placement_info);
}
void text_placements_angle::add_expressions(expression_set & output) const
{
list_placement_->add_expressions(output);
if (is_expression(angle_)) output.insert(util::get<expression_ptr>(angle_));
if (is_expression(tolerance_)) output.insert(util::get<expression_ptr>(tolerance_));
if (is_expression(step_)) output.insert(util::get<expression_ptr>(step_));
if (anchor_key_) output.insert(*anchor_key_);
}
text_placements_ptr text_placements_angle::from_xml(xml_node const& xml, fontset_map const& fontsets, bool is_shield)
{
symbolizer_base::value_type angle = get_opt(xml, "angle");
symbolizer_base::value_type tolerance = get_opt(xml, "tolerance");
symbolizer_base::value_type step = get_opt(xml, "step", default_step);
boost::optional<expression_ptr> anchor_key = xml.get_opt_attr<expression_ptr>("anchor-key");
text_placements_ptr list_placement_ptr = text_placements_list::from_xml(xml, fontsets, is_shield);
text_placements_ptr ptr = std::make_shared<text_placements_angle>(list_placement_ptr, angle, tolerance, step, anchor_key);
ptr->defaults.from_xml(xml, fontsets, is_shield);
return ptr;
}
//text_placement_info_angle class
text_placement_info_angle::text_placement_info_angle(text_placements_angle const* parent,
feature_impl const& feature,
attributes const& vars,
double scale_factor,
double angle,
double tolerance,
double step,
box2d<double> const& box,
text_placement_info_ptr list_placement_info)
: text_placement_info(parent, scale_factor),
list_placement_info_(list_placement_info),
feature_(feature),
vars_(vars),
angle_(angle),
box_(box),
dx_(displacement(box.width(), properties.layout_defaults.dx)),
dy_(displacement(box.height(), properties.layout_defaults.dy)),
tolerance_iterator_(tolerance, 0, tolerance_function(step))
{
list_placement_info_->next();
}
void text_placement_info_angle::reset_state()
{
list_placement_info_->reset_state();
list_placement_info_->next();
tolerance_iterator_.reset();
}
bool text_placement_info_angle::try_next_angle() const
{
if (tolerance_iterator_.next())
{
double angle = angle_ + tolerance_iterator_.get();
double dx, dy;
get_point(angle, dx, dy);
properties.layout_defaults.dx = dx;
properties.layout_defaults.dy = dy;
return true;
}
return false;
}
bool text_placement_info_angle::next() const
{
if (try_next_angle())
{
return true;
}
else if (list_placement_info_->next())
{
properties = list_placement_info_->properties;
dx_ = displacement(box_.width(), properties.layout_defaults.dx);
dy_ = displacement(box_.height(), properties.layout_defaults.dy);
tolerance_iterator_.reset();
try_next_angle();
return true;
}
return false;
}
double text_placement_info_angle::displacement(double const& box_size, symbolizer_base::value_type const& displacement) const
{
double d = util::apply_visitor(extract_value<double>(feature_, vars_), displacement);
return box_size / 2.0 + d + .5;
}
void text_placement_info_angle::get_point(double angle, double &x, double &y) const
{
double corner = std::atan(dx_ / dy_);
if ((angle >= 0 && angle <= corner) || (angle >= 2 * M_PI - corner && angle <= 2 * M_PI))
{
x = -dy_ * std::tan(angle);
y = -dy_;
}
else if (angle >= corner && angle <= M_PI - corner)
{
x = -dx_;
y = dx_ * std::tan(angle - M_PI_2);
}
else if (angle >= M_PI + corner && angle <= 2 * M_PI - corner)
{
x = dx_;
y = -dy_ * std::tan(angle - M_PI_2 * 3);
}
else
{
x = dy_ * std::tan(angle - M_PI);
y = dy_;
}
}
}
<|endoftext|> |
<commit_before>// For stat, getcwd
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
// For bad_alloc
#include <exception>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath)
: path_("/")
{
throw PrimitiveError(SYMBOL(clone),
"`Path' objects cannot be cloned");
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
// C *sucks*
static char buf[PATH_MAX];
char* res = getcwd(buf, PATH_MAX);
if (!res)
throw PrimitiveError(SYMBOL(pwd),
"Current directory name too long.");
return new Path(res);
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
struct stat dummy;
if (!::stat(path_.to_string().c_str(), &dummy))
return true;
handle_hard_error(SYMBOL(exists));
switch (errno)
{
case EACCES:
// Permission denied on one of the parent directory.
case ENOENT:
// No such file or directory.
case ENOTDIR:
// One component isn't a directory
return false;
default:
unhandled_error(SYMBOL(exists));
}
}
struct stat Path::stat(const libport::Symbol& msg)
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
return res;
}
bool Path::is_dir()
{
return stat(SYMBOL(isDir)).st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat(SYMBOL(isReg)).st_mode & S_IFREG;
}
bool Path::readable()
{
int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);
if (fd != -1)
{
close(fd);
return true;
}
else if (errno == EACCES)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// Not handled errors, because neither NOATIME or NONBLOCK is used:
// EPERM: The O_NOATIME flag was specified, but the effective user
// ID of the caller did not match the owner of the file and the
// caller was not privileged (CAP_FOWNER).
// EWOULDBLOCK: The O_NONBLOCK flag was specified, and an
// incompatible lease was held on the file (see fcntl(2)).
}
bool Path::writable()
{
int fd = ::open(path_.to_string().c_str(),
O_WRONLY | O_LARGEFILE | O_APPEND);
if (fd != -1)
{
close(fd);
return true;
}
// EROFS = file is on a read only file system.
else if (errno == EACCES || errno == EROFS)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
handle_perm_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// EPERM and EWOULDBLOCK not handled, see readable().
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (!is_dir())
throw PrimitiveError
(SYMBOL(cd),
str(format("Not a directory: %s.") % path_.to_string()));
chdir(as_string().c_str());
return cwd();
}
rPath Path::concat(rPath other)
{
return new Path(path_ / (*other).path_);
}
std::string Path::dirname()
{
return path_.dirname();
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
throw PrimitiveError
(SYMBOL(open),
str(format("Unsupported file type: '%s'.") % path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("\"%s\"") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_hard_error(const libport::Symbol& msg)
{
switch (errno)
{
case EBADF:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad file descriptor");
case EFAULT:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad address");
case EFBIG:
// Theoretically impossible, since O_LARGEFILE is always used
throw PrimitiveError
(msg,
str(format("Unhandled error: file too big: %s.") % path_));
case EINTR:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: file opening interrupted by a signal");
case ELOOP:
throw PrimitiveError
(msg,
str(format("Too many symbolic link: '%s'.") % path_));
case EMFILE:
throw PrimitiveError
(msg,
str(format("The kernel has reached"
" its maximum opened file limit: '%s'.") % path_));
case ENAMETOOLONG:
throw PrimitiveError
(msg,
str(format("File name too long: '%s'.") % path_));
case ENFILE:
throw PrimitiveError
(msg,
str(format("The system has reached"
" its maximum opened file limit: '%s'.") % path_));
case ENOMEM:
// Out of memory.
throw std::bad_alloc();
case ENOSPC:
throw PrimitiveError
(msg,
str(format("No space left on device: '%s'.") % path_));
default:
// Nothing
break;
}
}
void Path::handle_access_error(const libport::Symbol& msg)
{
switch (errno)
{
case EACCES:
throw PrimitiveError
(msg, str(format("Permission denied "
"for a parent directory: '%s'.")
% path_));
case ENOENT:
case ENOTDIR:
throw PrimitiveError
(msg, str(format("No such file or directory: '%s'.")
% path_));
default:
// Nothing
break;
}
}
void Path::handle_perm_error(const libport::Symbol& msg)
{
switch (errno)
{
case EEXIST:
throw PrimitiveError
(msg, str(format("File already exists: '%s'.")
% path_));
case EISDIR:
throw PrimitiveError
(msg, str(format("File is a directory: '%s'.")
% path_));
case EROFS:
throw PrimitiveError
(msg, str(format("File is on a read only file-system: '%s'.")
% path_));
case ETXTBSY:
throw PrimitiveError
(msg, str(format("File is currently being executed: '%s'.")
% path_));
case ENODEV:
case ENXIO:
throw PrimitiveError
(msg, str(format("File is an unopened FIFO "
"or an orphaned device: '%s'.")
% path_));
default:
// Nothing
break;
}
}
void Path::unhandled_error(const libport::Symbol& msg)
{
throw PrimitiveError
(msg,
str(format("Unhandled errno for stat(2): %i (%s).")
% errno
% strerror(errno)));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), &Path::concat);
bind(SYMBOL(writable), &Path::writable);
}
std::string Path::type_name_get() const
{
return type_name;
}
bool Path::path_added = CxxObject::add<Path>("Path", Path::proto);
const std::string Path::type_name = "Path";
rObject Path::proto;
}
<commit_msg>Portability.<commit_after>// For stat, getcwd
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <fcntl.h>
// For bad_alloc
#include <exception>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath)
: path_("/")
{
throw PrimitiveError(SYMBOL(clone),
"`Path' objects cannot be cloned");
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
// C *sucks*
static char buf[PATH_MAX];
char* res = getcwd(buf, PATH_MAX);
if (!res)
throw PrimitiveError(SYMBOL(pwd),
"Current directory name too long.");
return new Path(res);
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
struct stat dummy;
if (!::stat(path_.to_string().c_str(), &dummy))
return true;
handle_hard_error(SYMBOL(exists));
switch (errno)
{
case EACCES:
// Permission denied on one of the parent directory.
case ENOENT:
// No such file or directory.
case ENOTDIR:
// One component isn't a directory
return false;
default:
unhandled_error(SYMBOL(exists));
}
}
struct stat Path::stat(const libport::Symbol& msg)
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
return res;
}
bool Path::is_dir()
{
return stat(SYMBOL(isDir)).st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat(SYMBOL(isReg)).st_mode & S_IFREG;
}
bool Path::readable()
{
int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);
if (fd != -1)
{
close(fd);
return true;
}
else if (errno == EACCES)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// Not handled errors, because neither NOATIME or NONBLOCK is used:
// EPERM: The O_NOATIME flag was specified, but the effective user
// ID of the caller did not match the owner of the file and the
// caller was not privileged (CAP_FOWNER).
// EWOULDBLOCK: The O_NONBLOCK flag was specified, and an
// incompatible lease was held on the file (see fcntl(2)).
}
bool Path::writable()
{
int fd = ::open(path_.to_string().c_str(),
O_WRONLY | O_LARGEFILE | O_APPEND);
if (fd != -1)
{
close(fd);
return true;
}
// EROFS = file is on a read only file system.
else if (errno == EACCES || errno == EROFS)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
handle_perm_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// EPERM and EWOULDBLOCK not handled, see readable().
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (!is_dir())
throw PrimitiveError
(SYMBOL(cd),
str(format("Not a directory: %s.") % path_.to_string()));
chdir(as_string().c_str());
return cwd();
}
rPath Path::concat(rPath other)
{
return new Path(path_ / (*other).path_);
}
std::string Path::dirname()
{
return path_.dirname();
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
throw PrimitiveError
(SYMBOL(open),
str(format("Unsupported file type: '%s'.") % path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("\"%s\"") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_hard_error(const libport::Symbol& msg)
{
switch (errno)
{
case EBADF:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad file descriptor");
case EFAULT:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad address");
case EFBIG:
// Theoretically impossible, since O_LARGEFILE is always used
throw PrimitiveError
(msg,
str(format("Unhandled error: file too big: %s.") % path_));
case EINTR:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: file opening interrupted by a signal");
case ELOOP:
throw PrimitiveError
(msg,
str(format("Too many symbolic link: '%s'.") % path_));
case EMFILE:
throw PrimitiveError
(msg,
str(format("The kernel has reached"
" its maximum opened file limit: '%s'.") % path_));
case ENAMETOOLONG:
throw PrimitiveError
(msg,
str(format("File name too long: '%s'.") % path_));
case ENFILE:
throw PrimitiveError
(msg,
str(format("The system has reached"
" its maximum opened file limit: '%s'.") % path_));
case ENOMEM:
// Out of memory.
throw std::bad_alloc();
case ENOSPC:
throw PrimitiveError
(msg,
str(format("No space left on device: '%s'.") % path_));
default:
// Nothing
break;
}
}
void Path::handle_access_error(const libport::Symbol& msg)
{
switch (errno)
{
case EACCES:
throw PrimitiveError
(msg, str(format("Permission denied "
"for a parent directory: '%s'.")
% path_));
case ENOENT:
case ENOTDIR:
throw PrimitiveError
(msg, str(format("No such file or directory: '%s'.")
% path_));
default:
// Nothing
break;
}
}
void Path::handle_perm_error(const libport::Symbol& msg)
{
switch (errno)
{
case EEXIST:
throw PrimitiveError
(msg, str(format("File already exists: '%s'.")
% path_));
case EISDIR:
throw PrimitiveError
(msg, str(format("File is a directory: '%s'.")
% path_));
case EROFS:
throw PrimitiveError
(msg, str(format("File is on a read only file-system: '%s'.")
% path_));
case ETXTBSY:
throw PrimitiveError
(msg, str(format("File is currently being executed: '%s'.")
% path_));
case ENODEV:
case ENXIO:
throw PrimitiveError
(msg, str(format("File is an unopened FIFO "
"or an orphaned device: '%s'.")
% path_));
default:
// Nothing
break;
}
}
void Path::unhandled_error(const libport::Symbol& msg)
{
throw PrimitiveError
(msg,
str(format("Unhandled errno for stat(2): %i (%s).")
% errno
% strerror(errno)));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), &Path::concat);
bind(SYMBOL(writable), &Path::writable);
}
std::string Path::type_name_get() const
{
return type_name;
}
bool Path::path_added = CxxObject::add<Path>("Path", Path::proto);
const std::string Path::type_name = "Path";
rObject Path::proto;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/UVar.cc
** \brief Creation of the URBI object UVar.
*/
# include <kernel/userver.hh>
# include <kernel/uvalue-cast.hh>
# include <object/global.hh>
# include <object/list.hh>
# include <object/symbols.hh>
# include <object/urbi-exception.hh>
# include <object/uvar.hh>
# include <runner/runner.hh>
# include <runner/interpreter.hh>
namespace object
{
static inline void
show_exception_message(runner::Runner& r, rObject self, const char* m1,
const char* m2)
{
r.lobby_get()->call(SYMBOL(send),
new object::String(
m1
+ libport::format(
"%s.%s",
self->slot_get(SYMBOL(ownerName))->as<String>()->value_get(),
self->slot_get(SYMBOL(initialName))->as<String>()->value_get()
)
+ m2),
new object::String("error"));
}
static inline void callNotify(runner::Runner& r, rObject self,
libport::Symbol notifyList)
{
rList l =
self->slot_get(notifyList)->slot_get(SYMBOL(values))->as<List>();
objects_type args;
args.push_back(self);
List::value_type& callbacks = l->value_get();
for (List::value_type::iterator i = callbacks.begin();
i != callbacks.end(); )
{
bool failed = true;
try
{
r.apply(*i, SYMBOL(NOTIFY), args);
failed = false;
}
catch(UrbiException& e)
{
show_exception_message(r, self,
"!!! Exception caught while processing notify on ", " :");
runner::Interpreter& in = dynamic_cast<runner::Interpreter&>(r);
in.show_exception(e);
}
catch(sched::exception& e)
{
throw;
}
catch(...)
{
show_exception_message(r, self,
"!!! Unknown exception called while processing notify on ", "");
}
if (failed && self->slot_get(SYMBOL(eraseThrowingCallbacks))->as_bool())
{
// 'value' is just a cache, not the actual storage location.
self->slot_get(notifyList)->call(SYMBOL(remove), *i);
i = callbacks.erase(i);
}
else
++i;
}
}
static rObject
update_bounce(objects_type args)
{
//called with self slotname slotval
check_arg_count(args.size() - 1, 2);
libport::intrusive_ptr<UVar> rvar =
args.front()
->slot_get(libport::Symbol(args[1]->as<String>()->value_get())).value()
.unsafe_cast<UVar>();
rvar->update_(args[2]);
return void_class;
}
UVar::UVar()
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{
protos_set(new List);
proto_add(proto ? proto : Primitive::proto);
}
UVar::UVar(libport::intrusive_ptr<UVar>)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{
protos_set(new List);
proto_add(proto ? proto : Primitive::proto);
}
void
UVar::loopCheck()
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
// Loop if we have both notifychange and notifyaccess callbacs.
// Listeners on the changed event counts as notifychange
if (!looping_
&&
( !slot_get(SYMBOL(change))->call(SYMBOL(empty))->as_bool()
|| slot_get(SYMBOL(changed))->call(SYMBOL(hasSubscribers))->as_bool()
)
&& !slot_get(SYMBOL(access))->call(SYMBOL(empty))->as_bool())
{
looping_ = true;
while (true)
{
accessor();
objects_type args;
args.push_back(global_class);
rObject period = args[0]->call_with_this(SYMBOL(getPeriod), args);
r.yield_until(libport::utime() +
static_cast<libport::utime_t>(period->as<Float>()->value_get()
* 1000000.0));
}
}
}
rObject
UVar::update_(rObject val)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(val), val);
if (slot_get(SYMBOL(owned))->as_bool())
callNotify(r, rObject(this), SYMBOL(changeOwned));
else
{
std::set<void*>::iterator i = inChange_.find(&r);
if (i == inChange_.end())
{
// callNotify does not throw, this is safe.
i = inChange_.insert(&r).first;
callNotify(r, rObject(this), SYMBOL(change));
inChange_.erase(i);
}
slot_get(SYMBOL(changed))->call("emit");
}
return val;
}
rObject
UVar::accessor()
{
return getter(false);
}
rObject
UVar::getter(bool fromCXX)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
if (this == proto.get())
return this;
if (!inAccess_)
{
inAccess_ = true;
callNotify(r, rObject(this), SYMBOL(access));
inAccess_ = false;
}
rObject res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (!fromCXX)
if (object::rUValue bv = res->as<object::UValue>())
return bv->extract();
return res;
}
rObject
UVar::writeOwned(rObject newval)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(valsensor), newval);
callNotify(r, rObject(this), SYMBOL(change));
slot_get(SYMBOL(changed))->call("emit");
return newval;
}
void
UVar::initialize(CxxObject::Binder<UVar>& bind)
{
bind(SYMBOL(writeOwned), &UVar::writeOwned);
bind(SYMBOL(update_), &UVar::update_);
bind(SYMBOL(loopCheck), &UVar::loopCheck);
bind(SYMBOL(accessor), &UVar::accessor);
proto->slot_set(SYMBOL(update_bounce), new Primitive(&update_bounce));
}
rObject
UVar::proto_make()
{
return new UVar();
}
URBI_CXX_OBJECT_REGISTER(UVar);
UValue::UValue()
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
}
UValue::UValue(libport::intrusive_ptr<UValue>)
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
}
UValue::UValue(const urbi::UValue& v, bool bypass)
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
put(v, bypass);
}
UValue::~UValue()
{
}
rObject
UValue::extract()
{
if (cache_)
return cache_;
if (value_.type == urbi::DATA_VOID)
return nil_class;
if (!cache_)
cache_ = object_cast(value_);
return cache_;
}
std::string
UValue::extractAsToplevelPrintable()
{
if (value_.type == urbi::DATA_VOID && cache_)
{ // Someone used put, cache_ is more recent
return cache_->call("asToplevelPrintable")->as<String>()->value_get();
}
std::stringstream s;
value_.print(s);
return s.str();
}
const urbi::UValue&
UValue::value_get()
{
static urbi::UValue dummy;
if (value_.type != urbi::DATA_VOID)
return value_;
if (!cache_ || cache_ == nil_class)
return dummy;
value_ = uvalue_cast(cache_);
alocated_ = true;
return value_;
}
void
UValue::invalidate()
{
if (!alocated_)
value_ = urbi::UValue();
}
void
UValue::put(const urbi::UValue& v, bool bypass)
{
alocated_ = !bypass;
value_.set(v, !bypass);
cache_ = 0;
}
void
UValue::put(rObject r)
{
value_ = urbi::UValue();
cache_ = r;
}
rObject
UValue::proto_make()
{
return new UValue();
}
void
UValue::initialize(CxxObject::Binder<UValue>& bind)
{
bind(SYMBOL(extract), &UValue::extract);
bind(SYMBOL(extractAsToplevelPrintable),
&UValue::extractAsToplevelPrintable);
bind(SYMBOL(invalidate), &UValue::invalidate);
bind(SYMBOL(put), (void (UValue::*)(rObject))&UValue::put);
}
URBI_CXX_OBJECT_REGISTER(UValue);
}
<commit_msg>build: fix.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/UVar.cc
** \brief Creation of the URBI object UVar.
*/
# include <kernel/userver.hh>
# include <kernel/uvalue-cast.hh>
# include <object/global.hh>
# include <object/list.hh>
# include <object/lobby.hh>
# include <object/symbols.hh>
# include <object/urbi-exception.hh>
# include <object/uvar.hh>
# include <runner/runner.hh>
# include <runner/interpreter.hh>
namespace object
{
static inline void
show_exception_message(runner::Runner& r, rObject self, const char* m1,
const char* m2)
{
r.lobby_get()->call(SYMBOL(send),
new object::String(
m1
+ libport::format(
"%s.%s",
self->slot_get(SYMBOL(ownerName))->as<String>()->value_get(),
self->slot_get(SYMBOL(initialName))->as<String>()->value_get()
)
+ m2),
new object::String("error"));
}
static inline void callNotify(runner::Runner& r, rObject self,
libport::Symbol notifyList)
{
rList l =
self->slot_get(notifyList)->slot_get(SYMBOL(values))->as<List>();
objects_type args;
args.push_back(self);
List::value_type& callbacks = l->value_get();
for (List::value_type::iterator i = callbacks.begin();
i != callbacks.end(); )
{
bool failed = true;
try
{
r.apply(*i, SYMBOL(NOTIFY), args);
failed = false;
}
catch(UrbiException& e)
{
show_exception_message(r, self,
"!!! Exception caught while processing notify on ", " :");
runner::Interpreter& in = dynamic_cast<runner::Interpreter&>(r);
in.show_exception(e);
}
catch(sched::exception& e)
{
throw;
}
catch(...)
{
show_exception_message(r, self,
"!!! Unknown exception called while processing notify on ", "");
}
if (failed && self->slot_get(SYMBOL(eraseThrowingCallbacks))->as_bool())
{
// 'value' is just a cache, not the actual storage location.
self->slot_get(notifyList)->call(SYMBOL(remove), *i);
i = callbacks.erase(i);
}
else
++i;
}
}
static rObject
update_bounce(objects_type args)
{
//called with self slotname slotval
check_arg_count(args.size() - 1, 2);
libport::intrusive_ptr<UVar> rvar =
args.front()
->slot_get(libport::Symbol(args[1]->as<String>()->value_get())).value()
.unsafe_cast<UVar>();
rvar->update_(args[2]);
return void_class;
}
UVar::UVar()
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{
protos_set(new List);
proto_add(proto ? proto : Primitive::proto);
}
UVar::UVar(libport::intrusive_ptr<UVar>)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{
protos_set(new List);
proto_add(proto ? proto : Primitive::proto);
}
void
UVar::loopCheck()
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
// Loop if we have both notifychange and notifyaccess callbacs.
// Listeners on the changed event counts as notifychange
if (!looping_
&&
( !slot_get(SYMBOL(change))->call(SYMBOL(empty))->as_bool()
|| slot_get(SYMBOL(changed))->call(SYMBOL(hasSubscribers))->as_bool()
)
&& !slot_get(SYMBOL(access))->call(SYMBOL(empty))->as_bool())
{
looping_ = true;
while (true)
{
accessor();
objects_type args;
args.push_back(global_class);
rObject period = args[0]->call_with_this(SYMBOL(getPeriod), args);
r.yield_until(libport::utime() +
static_cast<libport::utime_t>(period->as<Float>()->value_get()
* 1000000.0));
}
}
}
rObject
UVar::update_(rObject val)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(val), val);
if (slot_get(SYMBOL(owned))->as_bool())
callNotify(r, rObject(this), SYMBOL(changeOwned));
else
{
std::set<void*>::iterator i = inChange_.find(&r);
if (i == inChange_.end())
{
// callNotify does not throw, this is safe.
i = inChange_.insert(&r).first;
callNotify(r, rObject(this), SYMBOL(change));
inChange_.erase(i);
}
slot_get(SYMBOL(changed))->call("emit");
}
return val;
}
rObject
UVar::accessor()
{
return getter(false);
}
rObject
UVar::getter(bool fromCXX)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
if (this == proto.get())
return this;
if (!inAccess_)
{
inAccess_ = true;
callNotify(r, rObject(this), SYMBOL(access));
inAccess_ = false;
}
rObject res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (!fromCXX)
if (object::rUValue bv = res->as<object::UValue>())
return bv->extract();
return res;
}
rObject
UVar::writeOwned(rObject newval)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(valsensor), newval);
callNotify(r, rObject(this), SYMBOL(change));
slot_get(SYMBOL(changed))->call("emit");
return newval;
}
void
UVar::initialize(CxxObject::Binder<UVar>& bind)
{
bind(SYMBOL(writeOwned), &UVar::writeOwned);
bind(SYMBOL(update_), &UVar::update_);
bind(SYMBOL(loopCheck), &UVar::loopCheck);
bind(SYMBOL(accessor), &UVar::accessor);
proto->slot_set(SYMBOL(update_bounce), new Primitive(&update_bounce));
}
rObject
UVar::proto_make()
{
return new UVar();
}
URBI_CXX_OBJECT_REGISTER(UVar);
UValue::UValue()
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
}
UValue::UValue(libport::intrusive_ptr<UValue>)
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
}
UValue::UValue(const urbi::UValue& v, bool bypass)
{
protos_set(new List);
proto_add(proto ? proto : CxxObject::proto);
put(v, bypass);
}
UValue::~UValue()
{
}
rObject
UValue::extract()
{
if (cache_)
return cache_;
if (value_.type == urbi::DATA_VOID)
return nil_class;
if (!cache_)
cache_ = object_cast(value_);
return cache_;
}
std::string
UValue::extractAsToplevelPrintable()
{
if (value_.type == urbi::DATA_VOID && cache_)
{ // Someone used put, cache_ is more recent
return cache_->call("asToplevelPrintable")->as<String>()->value_get();
}
std::stringstream s;
value_.print(s);
return s.str();
}
const urbi::UValue&
UValue::value_get()
{
static urbi::UValue dummy;
if (value_.type != urbi::DATA_VOID)
return value_;
if (!cache_ || cache_ == nil_class)
return dummy;
value_ = uvalue_cast(cache_);
alocated_ = true;
return value_;
}
void
UValue::invalidate()
{
if (!alocated_)
value_ = urbi::UValue();
}
void
UValue::put(const urbi::UValue& v, bool bypass)
{
alocated_ = !bypass;
value_.set(v, !bypass);
cache_ = 0;
}
void
UValue::put(rObject r)
{
value_ = urbi::UValue();
cache_ = r;
}
rObject
UValue::proto_make()
{
return new UValue();
}
void
UValue::initialize(CxxObject::Binder<UValue>& bind)
{
bind(SYMBOL(extract), &UValue::extract);
bind(SYMBOL(extractAsToplevelPrintable),
&UValue::extractAsToplevelPrintable);
bind(SYMBOL(invalidate), &UValue::invalidate);
bind(SYMBOL(put), (void (UValue::*)(rObject))&UValue::put);
}
URBI_CXX_OBJECT_REGISTER(UValue);
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2011-2012, Qualys, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Qualys, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
/**
* @file
*
* @author Ivan Ristic <[email protected]>
*/
#include <iostream>
#include <gtest/gtest.h>
#include <htp/htp.h>
#include "test.h"
class ConnectionParsingTest : public testing::Test {
protected:
virtual void SetUp() {
home = (char *)"./files";
cfg = htp_config_create();
htp_config_set_server_personality(cfg, HTP_SERVER_APACHE_2_2);
}
virtual void TearDown() {
htp_config_destroy(cfg);
}
htp_cfg_t *cfg;
char *home;
};
TEST_F(ConnectionParsingTest, Get) {
htp_connp_t *connp = NULL;
int rc = test_run(home, "01-get.t", cfg, &connp);
if (rc < 0) {
if (connp != NULL) {
htp_connp_destroy_all(connp);
}
FAIL();
}
htp_connp_destroy_all(connp);
SUCCEED();
}
<commit_msg>Improve Get regression test.<commit_after>/***************************************************************************
* Copyright (c) 2011-2012, Qualys, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Qualys, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
/**
* @file
*
* @author Ivan Ristic <[email protected]>
*/
#include <iostream>
#include <gtest/gtest.h>
#include <htp/htp.h>
#include "test.h"
class ConnectionParsingTest : public testing::Test {
protected:
virtual void SetUp() {
home = (char *)"./files";
cfg = htp_config_create();
htp_config_set_server_personality(cfg, HTP_SERVER_APACHE_2_2);
}
virtual void TearDown() {
htp_connp_destroy_all(connp);
htp_config_destroy(cfg);
}
htp_connp_t *connp;
htp_cfg_t *cfg;
char *home;
};
TEST_F(ConnectionParsingTest, Get) {
int rc = test_run(home, "01-get.t", cfg, &connp);
ASSERT_GE(rc, 0);
ASSERT_EQ(list_size(connp->conn->transactions), 1);
htp_tx_t *tx = (htp_tx_t *)list_get(connp->conn->transactions, 0);
if (bstr_cmp_c(tx->request_method, "GET") != 0) {
FAIL();
}
if (bstr_cmp_c(tx->request_uri, "/?p=%20") != 0) {
FAIL();
}
SUCCEED();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.