text
stringlengths 54
60.6k
|
|---|
<commit_before>AliAnalysisTask *AddTaskHFECalSys(int sysID, int TPCclust, int TPCclustPID, int Nits, int ITSstat)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskHFEECal", "No analysis manager found.");
return NULL;
}
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskHFECal", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if (type=="AOD"){
::Error("AddTaskHFECal", "The tasks exits because AODs are in input");
return NULL;
}
Bool_t MCthere=kFALSE;
AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
if(!mcH){
MCthere=kFALSE;
}else{
MCthere=kTRUE;
}
//analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFECalSys.C");
AliAnalysisTaskHFECal *hfetaskCent = ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat);
AliAnalysisTaskHFECal *hfetaskTrig= ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat);
mgr->AddTask(hfetaskCent);
mgr->AddTask(hfetaskTrig);
// Semi-central trigger
hfetaskCent->SelectCollisionCandidates(AliVEvent::kCentral);
TString Output1(TString::Format("HFE_Results_EMCALCentral%d",sysID));
TString containerName = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalCentral%d",sysID));
containerName += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output1, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
mgr->ConnectInput(hfetaskCent, 0, cinput);
mgr->ConnectOutput(hfetaskCent, 1, coutput1);
//L1 gamma trigger
hfetaskTrig->SelectCollisionCandidates(AliVEvent::kEMCEGA);
TString Output2(TString::Format("HFE_Results_EMCalTrigEGA%d",sysID));
TString containerName2 = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalTrigEGA%d",sysID));
containerName2 += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output2, TList::Class(),AliAnalysisManager::kOutputContainer, containerName2.Data());
mgr->ConnectInput(hfetaskTrig, 0, cinput);
mgr->ConnectOutput(hfetaskTrig, 1, coutput1);
//MB trigger
AliAnalysisTaskHFECal *hfetaskMB = ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat);
mgr->AddTask(hfetaskMB);
hfetaskMB->SelectCollisionCandidates(AliVEvent::kMB);
TString Output3(TString::Format("HFE_Results_EMCalMB%d",sysID));
TString containerName3 = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalkMB%d",sysID));
containerName3 += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output3, TList::Class(),AliAnalysisManager::kOutputContainer, containerName3.Data());
mgr->ConnectInput(hfetaskMB, 0, cinput);
mgr->ConnectOutput(hfetaskMB, 1, coutput1);
return NULL;
}
<commit_msg>added flag to select QA hist<commit_after>AliAnalysisTask *AddTaskHFECalSys(int sysID, int TPCclust, int TPCclustPID, int Nits, int ITSstat, int QAhist)
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskHFEECal", "No analysis manager found.");
return NULL;
}
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskHFECal", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
if (type=="AOD"){
::Error("AddTaskHFECal", "The tasks exits because AODs are in input");
return NULL;
}
Bool_t MCthere=kFALSE;
AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
if(!mcH){
MCthere=kFALSE;
}else{
MCthere=kTRUE;
}
//analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFECalSys.C");
AliAnalysisTaskHFECal *hfetaskCent = ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat,QAhist);
AliAnalysisTaskHFECal *hfetaskTrig= ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat,QAhist);
mgr->AddTask(hfetaskCent);
mgr->AddTask(hfetaskTrig);
// Semi-central trigger
hfetaskCent->SelectCollisionCandidates(AliVEvent::kCentral);
TString Output1(TString::Format("HFE_Results_EMCALCentral%d",sysID));
TString containerName = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalCentral%d",sysID));
containerName += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output1, TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
mgr->ConnectInput(hfetaskCent, 0, cinput);
mgr->ConnectOutput(hfetaskCent, 1, coutput1);
//L1 gamma trigger
hfetaskTrig->SelectCollisionCandidates(AliVEvent::kEMCEGA);
TString Output2(TString::Format("HFE_Results_EMCalTrigEGA%d",sysID));
TString containerName2 = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalTrigEGA%d",sysID));
containerName2 += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output2, TList::Class(),AliAnalysisManager::kOutputContainer, containerName2.Data());
mgr->ConnectInput(hfetaskTrig, 0, cinput);
mgr->ConnectOutput(hfetaskTrig, 1, coutput1);
//MB trigger
AliAnalysisTaskHFECal *hfetaskMB = ConfigHFECalSys(MCthere,TPCclust,TPCclustPID,Nits,ITSstat,QAhist);
mgr->AddTask(hfetaskMB);
hfetaskMB->SelectCollisionCandidates(AliVEvent::kMB);
TString Output3(TString::Format("HFE_Results_EMCalMB%d",sysID));
TString containerName3 = mgr->GetCommonFileName();
TString appendix(TString::Format(":PWGHF_hfeCalkMB%d",sysID));
containerName3 += appendix;
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Output3, TList::Class(),AliAnalysisManager::kOutputContainer, containerName3.Data());
mgr->ConnectInput(hfetaskMB, 0, cinput);
mgr->ConnectOutput(hfetaskMB, 1, coutput1);
return NULL;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#pragma once
namespace fakeit {
template<typename TARGET, typename SOURCE>
TARGET union_cast(SOURCE source) {
//static_assert(sizeof(TARGET) == sizeof(SOURCE), "can't convert");
union {
SOURCE source;
TARGET target;
} u;
u.source = source;
return u.target;
}
}
<commit_msg>Disable de-virtualization for GCC to prevent crash when having inline virtual dtor in the mocked class<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#pragma once
namespace fakeit {
template<typename TARGET, typename SOURCE>
[[gnu::optimize("no-devirtualize")]]
TARGET union_cast(SOURCE source) {
//static_assert(sizeof(TARGET) == sizeof(SOURCE), "can't convert");
union {
SOURCE source;
TARGET target;
} u;
u.source = source;
return u.target;
}
}
<|endoftext|>
|
<commit_before>#include "SoundWrapper.h"
SoundWrapper::SoundWrapper()
{
m_soundDevice = NULL;
m_masterVoice = NULL;
m_channelVolumes = NULL;
m_masterVolume = 1.0f; // NOTE: (Johan) Makes no difference if this is changed.
ZeroMemory(&m_details, sizeof(XAUDIO2_DEVICE_DETAILS));
/************************************************************************/
/* XAudio2 2.7 specific call, this is called behind the scene in later */
/* versions of XAudio2. */
/************************************************************************/
CoInitializeEx( NULL, COINIT_MULTITHREADED );
initSoundEngine();
m_soundFactory = new SoundFactory(m_soundDevice);
}
SoundWrapper::~SoundWrapper()
{
for (unsigned int i = 0; i < m_sounds.getSize(); i++)
{
destroySound(i);
}
for (unsigned int i = 0; i <m_activeSounds.size(); i++)
{
delete m_activeSounds[i];
}
m_activeSounds.clear();
for(unsigned int i=0; i<m_soundEffects.size(); i++)
{
if( m_soundEffects[i] )
{
delete m_soundEffects[i];
}
}
m_masterVoice->DestroyVoice();
m_soundDevice->StopEngine();
m_soundDevice->Release();
delete m_soundFactory;
delete m_channelVolumes;
CoUninitialize();
}
void SoundWrapper::initSoundEngine()
{
HRESULT hr = S_OK;
UINT32 flags = 0;
#ifdef _DEBUG
flags |= XAUDIO2_DEBUG_ENGINE;
#endif
if ( FAILED (hr = XAudio2Create(&m_soundDevice,flags)))
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
if( FAILED( hr = m_soundDevice->CreateMasteringVoice(&m_masterVoice)))
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
/************************************************************************/
/* XAudio 2.7 specific variable XAUDIO2_DEVICE_DETAILS */
/* Get all the juicy details about the sound device. */
/************************************************************************/
if ( FAILED( hr = m_soundDevice->GetDeviceDetails( 0, &m_details ) ) )
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
m_destChannels = m_details.OutputFormat.Format.nChannels;
m_channelMask = m_details.OutputFormat.dwChannelMask;
m_channelVolumes = new float[m_destChannels];
init3DSoundSettings();
initListener();
}
void SoundWrapper::updateListener(const SoundOrientation& p_sceneInfo)
{
X3DAUDIO_VECTOR front = {
p_sceneInfo.listenerOrientFront[0],
p_sceneInfo.listenerOrientFront[1],
p_sceneInfo.listenerOrientFront[2],
};
X3DAUDIO_VECTOR top = {
p_sceneInfo.listenerOrientTop[0],
p_sceneInfo.listenerOrientTop[1],
p_sceneInfo.listenerOrientTop[2],
};
X3DAUDIO_VECTOR velocity = {
p_sceneInfo.listenerVelocity[0],
p_sceneInfo.listenerVelocity[1],
p_sceneInfo.listenerVelocity[2],
};
X3DAUDIO_VECTOR pos = {
p_sceneInfo.listenerPos[0],
p_sceneInfo.listenerPos[1],
p_sceneInfo.listenerPos[2],
};
m_listener.OrientFront = front;
m_listener.OrientTop = top;
m_listener.Position = pos;
m_listener.Velocity = velocity;
m_listener.pCone = NULL;
}
/*
int SoundWrapper::createAmbientSound(BasicSoundCreationInfo* p_info)
{
int soundIndex = -1;
Sound* sound = NULL;
if(p_info->loopPlayback)
{
sound = m_soundFactory->createAmbientSound(p_info);
m_activeSounds.push_back(sound);
soundIndex = (int)m_activeSounds.size()-1;
}
else
{
sound = m_soundFactory->createAmbientSoundEffect(p_info,
(int)m_soundEffects.size(), &m_soundEffects);
m_soundEffects.push_back(sound);
sound->resumeOrPlay();
}
return soundIndex;
}
*/
/*
int SoundWrapper::createNewPositionalSound(BasicSoundCreationInfo* p_basicSoundInfo,
PositionalSoundCreationInfo* p_positionalInfo)
{
int soundIndex = -1;
p_positionalInfo->destChannels = m_destChannels;
PositionalSound* positionalSound = NULL;
if(p_basicSoundInfo->loopPlayback)
{
positionalSound = m_soundFactory->createPositionalSound(
p_basicSoundInfo, p_positionalInfo);
m_activeSounds.push_back(positionalSound);
soundIndex = (int)m_activeSounds.size()-1;
}
else
{
positionalSound = m_soundFactory->createPositionalSoundEffect(
p_basicSoundInfo, p_positionalInfo, (int)m_soundEffects.size(),
&m_soundEffects);
m_soundEffects.push_back(positionalSound);
positionalSound->resumeOrPlay();
}
return soundIndex;
}
*/
void SoundWrapper::init3DSoundSettings()
{
/************************************************************************/
/* The number of output channels have to be know before the 3D */
/* calculations can be used. The speed of sound can be altered for */
/* artistic feeling. */
/************************************************************************/
X3DAudioInitialize( m_channelMask, X3DAUDIO_SPEED_OF_SOUND, m_x3DAudioInstance);
}
void SoundWrapper::initListener()
{
SoundOrientation info;
info.listenerOrientFront = AglVector3(1,0,0);
info.listenerOrientTop = AglVector3(0,1,0);
info.listenerPos = AglVector3(0,0,0);
info.listenerVelocity = AglVector3(0,0,0);
updateListener(info);
}
void SoundWrapper::calculate3DSound(int p_index)
{
PositionalSound* sound = static_cast<PositionalSound*>(m_sounds[p_index]);
X3DAudioCalculate(m_x3DAudioInstance, &m_listener, &sound->getEmitter(),
X3DAUDIO_CALCULATE_MATRIX, &sound->getDSPSettings());
sound->getSourceVoice()->SetOutputMatrix(m_masterVoice, SOURCECHANNELS,
m_destChannels, sound->getDSPSettings().pMatrixCoefficients);
}
void SoundWrapper::updateSound( unsigned int p_index,
const AudioHeader::PlayState& p_soundInstruction )
{
switch (p_soundInstruction)
{
case AudioHeader::PlayState::PLAY:
m_sounds[p_index]->resumeOrPlay();
break;
case AudioHeader::PlayState::STOP:
m_sounds[p_index]->stop();
break;
case AudioHeader::PlayState::PAUSE:
m_sounds[p_index]->pause();
break;
case AudioHeader::PlayState::RESTART:
m_sounds[p_index]->restart();
break;
case AudioHeader::PlayState::RESUME:
m_sounds[p_index]->resumeOrPlay();
break;
default:
break;
}
}
float* SoundWrapper::getMasterVolumeRef()
{
return &m_masterVolume;
}
float SoundWrapper::getMasterVolume() const
{
return m_masterVolume;
}
void SoundWrapper::setMasterVolume( const float p_value )
{
m_masterVolume = p_value;
}
void SoundWrapper::updateMasterVolume(){
m_masterVoice->SetVolume(m_masterVolume,0);
}
bool SoundWrapper::isPlaying( const int soundIndex ){
return m_activeSounds[soundIndex]->isPlaying();
}
Sound* SoundWrapper::getSound( int p_index ){
return m_sounds[p_index];
}
unsigned int SoundWrapper::createSoundFromHeader( const AudioHeader* p_audioHeader ){
return m_sounds.add(m_soundFactory->createSoundFromHeader(p_audioHeader));
}
void SoundWrapper::destroySound( unsigned int p_index )
{
delete m_sounds.at(p_index);
m_sounds.removeAt(p_index);
}
<commit_msg>Changed so that always assumes output is stereo sound for master voice.<commit_after>#include "SoundWrapper.h"
SoundWrapper::SoundWrapper()
{
m_soundDevice = NULL;
m_masterVoice = NULL;
m_channelVolumes = NULL;
m_masterVolume = 1.0f; // NOTE: (Johan) Makes no difference if this is changed.
ZeroMemory(&m_details, sizeof(XAUDIO2_DEVICE_DETAILS));
/************************************************************************/
/* XAudio2 2.7 specific call, this is called behind the scene in later */
/* versions of XAudio2. */
/************************************************************************/
CoInitializeEx( NULL, COINIT_MULTITHREADED );
initSoundEngine();
m_soundFactory = new SoundFactory(m_soundDevice);
}
SoundWrapper::~SoundWrapper()
{
for (unsigned int i = 0; i < m_sounds.getSize(); i++)
{
destroySound(i);
}
for (unsigned int i = 0; i <m_activeSounds.size(); i++)
{
delete m_activeSounds[i];
}
m_activeSounds.clear();
for(unsigned int i=0; i<m_soundEffects.size(); i++)
{
if( m_soundEffects[i] )
{
delete m_soundEffects[i];
}
}
m_masterVoice->DestroyVoice();
m_soundDevice->StopEngine();
m_soundDevice->Release();
delete m_soundFactory;
delete m_channelVolumes;
CoUninitialize();
}
void SoundWrapper::initSoundEngine()
{
HRESULT hr = S_OK;
UINT32 flags = 0;
#ifdef _DEBUG
flags |= XAUDIO2_DEBUG_ENGINE;
#endif
if ( FAILED (hr = XAudio2Create(&m_soundDevice,flags)))
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
if( FAILED( hr = m_soundDevice->CreateMasteringVoice(&m_masterVoice)))
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
/************************************************************************/
/* XAudio 2.7 specific variable XAUDIO2_DEVICE_DETAILS */
/* Get all the juicy details about the sound device. */
/************************************************************************/
if ( FAILED( hr = m_soundDevice->GetDeviceDetails( 0, &m_details ) ) )
throw XAudio2Exception(hr,__FILE__,__FUNCTION__,__LINE__);
//m_destChannels = m_details.OutputFormat.Format.nChannels;
//m_channelMask = m_details.OutputFormat.dwChannelMask;
m_destChannels = 2;
m_channelMask = 3;
m_channelVolumes = new float[m_destChannels];
init3DSoundSettings();
initListener();
}
void SoundWrapper::updateListener(const SoundOrientation& p_sceneInfo)
{
X3DAUDIO_VECTOR front = {
p_sceneInfo.listenerOrientFront[0],
p_sceneInfo.listenerOrientFront[1],
p_sceneInfo.listenerOrientFront[2],
};
X3DAUDIO_VECTOR top = {
p_sceneInfo.listenerOrientTop[0],
p_sceneInfo.listenerOrientTop[1],
p_sceneInfo.listenerOrientTop[2],
};
X3DAUDIO_VECTOR velocity = {
p_sceneInfo.listenerVelocity[0],
p_sceneInfo.listenerVelocity[1],
p_sceneInfo.listenerVelocity[2],
};
X3DAUDIO_VECTOR pos = {
p_sceneInfo.listenerPos[0],
p_sceneInfo.listenerPos[1],
p_sceneInfo.listenerPos[2],
};
m_listener.OrientFront = front;
m_listener.OrientTop = top;
m_listener.Position = pos;
m_listener.Velocity = velocity;
m_listener.pCone = NULL;
}
/*
int SoundWrapper::createAmbientSound(BasicSoundCreationInfo* p_info)
{
int soundIndex = -1;
Sound* sound = NULL;
if(p_info->loopPlayback)
{
sound = m_soundFactory->createAmbientSound(p_info);
m_activeSounds.push_back(sound);
soundIndex = (int)m_activeSounds.size()-1;
}
else
{
sound = m_soundFactory->createAmbientSoundEffect(p_info,
(int)m_soundEffects.size(), &m_soundEffects);
m_soundEffects.push_back(sound);
sound->resumeOrPlay();
}
return soundIndex;
}
*/
/*
int SoundWrapper::createNewPositionalSound(BasicSoundCreationInfo* p_basicSoundInfo,
PositionalSoundCreationInfo* p_positionalInfo)
{
int soundIndex = -1;
p_positionalInfo->destChannels = m_destChannels;
PositionalSound* positionalSound = NULL;
if(p_basicSoundInfo->loopPlayback)
{
positionalSound = m_soundFactory->createPositionalSound(
p_basicSoundInfo, p_positionalInfo);
m_activeSounds.push_back(positionalSound);
soundIndex = (int)m_activeSounds.size()-1;
}
else
{
positionalSound = m_soundFactory->createPositionalSoundEffect(
p_basicSoundInfo, p_positionalInfo, (int)m_soundEffects.size(),
&m_soundEffects);
m_soundEffects.push_back(positionalSound);
positionalSound->resumeOrPlay();
}
return soundIndex;
}
*/
void SoundWrapper::init3DSoundSettings()
{
/************************************************************************/
/* The number of output channels have to be know before the 3D */
/* calculations can be used. The speed of sound can be altered for */
/* artistic feeling. */
/************************************************************************/
X3DAudioInitialize( m_channelMask, X3DAUDIO_SPEED_OF_SOUND, m_x3DAudioInstance);
}
void SoundWrapper::initListener()
{
SoundOrientation info;
info.listenerOrientFront = AglVector3(1,0,0);
info.listenerOrientTop = AglVector3(0,1,0);
info.listenerPos = AglVector3(0,0,0);
info.listenerVelocity = AglVector3(0,0,0);
updateListener(info);
}
void SoundWrapper::calculate3DSound(int p_index)
{
PositionalSound* sound = static_cast<PositionalSound*>(m_sounds[p_index]);
X3DAudioCalculate(m_x3DAudioInstance, &m_listener, &sound->getEmitter(),
X3DAUDIO_CALCULATE_MATRIX, &sound->getDSPSettings());
sound->getSourceVoice()->SetOutputMatrix(m_masterVoice, SOURCECHANNELS,
m_destChannels, sound->getDSPSettings().pMatrixCoefficients);
}
void SoundWrapper::updateSound( unsigned int p_index,
const AudioHeader::PlayState& p_soundInstruction )
{
switch (p_soundInstruction)
{
case AudioHeader::PlayState::PLAY:
m_sounds[p_index]->resumeOrPlay();
break;
case AudioHeader::PlayState::STOP:
m_sounds[p_index]->stop();
break;
case AudioHeader::PlayState::PAUSE:
m_sounds[p_index]->pause();
break;
case AudioHeader::PlayState::RESTART:
m_sounds[p_index]->restart();
break;
case AudioHeader::PlayState::RESUME:
m_sounds[p_index]->resumeOrPlay();
break;
default:
break;
}
}
float* SoundWrapper::getMasterVolumeRef()
{
return &m_masterVolume;
}
float SoundWrapper::getMasterVolume() const
{
return m_masterVolume;
}
void SoundWrapper::setMasterVolume( const float p_value )
{
m_masterVolume = p_value;
}
void SoundWrapper::updateMasterVolume(){
m_masterVoice->SetVolume(m_masterVolume,0);
}
bool SoundWrapper::isPlaying( const int soundIndex ){
return m_activeSounds[soundIndex]->isPlaying();
}
Sound* SoundWrapper::getSound( int p_index ){
return m_sounds[p_index];
}
unsigned int SoundWrapper::createSoundFromHeader( const AudioHeader* p_audioHeader ){
return m_sounds.add(m_soundFactory->createSoundFromHeader(p_audioHeader));
}
void SoundWrapper::destroySound( unsigned int p_index )
{
delete m_sounds.at(p_index);
m_sounds.removeAt(p_index);
}
<|endoftext|>
|
<commit_before>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 "Vaca/Layout.h"
#include "Vaca/Debug.h"
#include "Vaca/Widget.h"
using namespace Vaca;
Layout::Layout()
{
m_HDWP = NULL;
}
Layout::~Layout()
{
assert(m_HDWP == NULL);
}
void Layout::beginMovement(const WidgetList& widgets)
{
m_HDWP = BeginDeferWindowPos(widgets.size());
m_relayoutWidgets.clear();
}
void Layout::moveWidget(Widget* widget, const Rect& rc)
{
if (m_HDWP != NULL) {
m_HDWP = DeferWindowPos(m_HDWP, widget->getHandle(), NULL,
rc.x, rc.y, rc.w, rc.h,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE);
}
// if (widget->getBounds() == rc)
m_relayoutWidgets.push_back(widget);
}
void Layout::endMovement()
{
if (m_HDWP != NULL) {
EndDeferWindowPos(m_HDWP);
m_HDWP = NULL;
}
for (WidgetList::iterator it=m_relayoutWidgets.begin();
it!=m_relayoutWidgets.end(); ++it) {
(*it)->layout();
}
m_relayoutWidgets.clear();
}
// Size Layout::minimumSize(Widget* parent, WidgetList& widgets)
// {
// return Size(0, 0);
// }
Size Layout::getPreferredSize(Widget* parent, WidgetList& widgets, const Size& fitIn)
{
return Size(0, 0);
}
// Size Layout::maximumSize(Widget* parent, WidgetList& widgets)
// {
// // TODO use std::numeric_limits<int>::max()
// return Size(INT_MAX, INT_MAX);
// }
<commit_msg>Removed commented code.<commit_after>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// 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 "Vaca/Layout.h"
#include "Vaca/Debug.h"
#include "Vaca/Widget.h"
using namespace Vaca;
Layout::Layout()
{
m_HDWP = NULL;
}
Layout::~Layout()
{
assert(m_HDWP == NULL);
}
void Layout::beginMovement(const WidgetList& widgets)
{
m_HDWP = BeginDeferWindowPos(widgets.size());
m_relayoutWidgets.clear();
}
void Layout::moveWidget(Widget* widget, const Rect& rc)
{
if (m_HDWP != NULL) {
m_HDWP = DeferWindowPos(m_HDWP, widget->getHandle(), NULL,
rc.x, rc.y, rc.w, rc.h,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE);
}
// if (widget->getBounds() == rc)
m_relayoutWidgets.push_back(widget);
}
void Layout::endMovement()
{
if (m_HDWP != NULL) {
EndDeferWindowPos(m_HDWP);
m_HDWP = NULL;
}
for (WidgetList::iterator it=m_relayoutWidgets.begin();
it!=m_relayoutWidgets.end(); ++it) {
(*it)->layout();
}
m_relayoutWidgets.clear();
}
Size Layout::getPreferredSize(Widget* parent, WidgetList& widgets, const Size& fitIn)
{
return Size(0, 0);
}
<|endoftext|>
|
<commit_before>#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/Stencil>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Billboard>
#include <osg/Material>
#include <osgUtil/TransformCallback>
#include <osgUtil/SmoothingVisitor>
#include <osgUtil/UpdateVisitor>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <Producer/Camera>
#include <Producer/CameraConfig>
osg::ref_ptr<Producer::Camera> gPBufferCamera;
osg::ref_ptr<osgProducer::OsgSceneHandler> gPBufferSceneHandler;
// call back which cretes a deformation field to oscilate the model.
class MyGeometryCallback :
public osg::Drawable::UpdateCallback,
public osg::Drawable::AttributeFunctor
{
public:
MyGeometryCallback(const osg::Vec3& o,
const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
double period,double xphase,double amplitude):
_firstCall(true),
_startTime(0.0),
_time(0.0),
_period(period),
_xphase(xphase),
_amplitude(amplitude),
_origin(o),
_xAxis(x),
_yAxis(y),
_zAxis(z) {}
virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
{
const osg::FrameStamp* fs = nv->getFrameStamp();
double referenceTime = fs->getReferenceTime();
if (_firstCall)
{
_firstCall = false;
_startTime = referenceTime;
}
_time = referenceTime-_startTime;
drawable->accept(*this);
drawable->dirtyBound();
osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
if (geometry)
{
osgUtil::SmoothingVisitor::smooth(*geometry);
}
}
virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
{
if (type == osg::Drawable::VERTICES)
{
const float TwoPI=2.0f*osg::PI;
const float phase = -_time/_period;
osg::Vec3* end = begin+count;
for (osg::Vec3* itr=begin;itr<end;++itr)
{
osg::Vec3 dv(*itr-_origin);
osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
local.z() = local.x()*_amplitude*
sinf(TwoPI*(phase+local.x()*_xphase));
(*itr) = _origin +
_xAxis*local.x()+
_yAxis*local.y()+
_zAxis*local.z();
}
}
}
bool _firstCall;
double _startTime;
double _time;
double _period;
double _xphase;
float _amplitude;
osg::Vec3 _origin;
osg::Vec3 _xAxis;
osg::Vec3 _yAxis;
osg::Vec3 _zAxis;
};
// Custom Texture subload callback, just acts the the standard subload modes in osg::Texture right now
// but code be used to define your own style callbacks.
class MyTextureSubloadCallback : public osg::Texture2D::SubloadCallback
{
public:
MyTextureSubloadCallback() {}
virtual void load(const osg::Texture2D& texture,osg::State&) const
{
osg::notify(osg::INFO)<<"doing load"<<std::endl;
glTexImage2D( GL_TEXTURE_2D, 0, texture.getInternalFormat(), texture.getTextureWidth(), texture.getTextureHeight(), 0, GL_RGB, GL_FLOAT, 0 );
}
virtual void subload(const osg::Texture2D& ,osg::State&) const
{
osg::notify(osg::INFO)<<"doing subload"<<std::endl;
gPBufferCamera->getRenderSurface()->bindPBufferToTexture(Producer::RenderSurface::FrontBuffer);
}
};
osg::Node* createTexturedFlag(unsigned int width, unsigned int height)
{
// create the quad to visualize.
osg::Geometry* polyGeom = new osg::Geometry();
polyGeom->setSupportsDisplayList(false);
osg::Vec3 origin(0.0f,0.0f,0.0f);
osg::Vec3 xAxis(1.0f,0.0f,0.0f);
osg::Vec3 yAxis(0.0f,0.0f,1.0f);
osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
float flag_height = 100.0f;
float flag_width = 200.0f;
int noSteps = 20;
osg::Vec3Array* vertices = new osg::Vec3Array;
osg::Vec3 bottom = origin;
osg::Vec3 top = origin; top.z()+= flag_height;
osg::Vec3 dv = xAxis*(flag_width/((float)(noSteps-1)));
osg::Vec2Array* texcoords = new osg::Vec2Array;
osg::Vec2 bottom_texcoord(0.0f,0.0f);
osg::Vec2 top_texcoord(0.0f,1.0f);
osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);
for(int i=0;i<noSteps;++i)
{
vertices->push_back(top);
vertices->push_back(bottom);
top+=dv;
bottom+=dv;
texcoords->push_back(top_texcoord);
texcoords->push_back(bottom_texcoord);
top_texcoord+=dv_texcoord;
bottom_texcoord+=dv_texcoord;
}
// pass the created vertex array to the points geometry object.
polyGeom->setVertexArray(vertices);
polyGeom->setTexCoordArray(0,texcoords);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
polyGeom->setColorArray(colors);
polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
// new we need to add the texture to the Drawable, we do so by creating a
// StateSet to contain the Texture StateAttribute.
osg::StateSet* stateset = new osg::StateSet;
// Dynamic texture filled with data from pbuffer.
osg::Texture2D* texture = new osg::Texture2D;
//texture->setSubloadMode(osg::Texture::IF_DIRTY);
texture->setInternalFormat(GL_RGB);
texture->setTextureSize(width,height);
texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP);
texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP);
texture->setSubloadCallback(new MyTextureSubloadCallback());
stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
polyGeom->setStateSet(stateset);
polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/flag_width,0.2f));
osg::Geode* geode = new osg::Geode();
geode->addDrawable(polyGeom);
osg::Group* parent = new osg::Group;
parent->addChild(geode);
return parent;
}
void InitPBufferCamera(osg::Node* subgraph, unsigned int width, unsigned int height)
{
if (!subgraph) return;
gPBufferCamera = new Producer::Camera;
gPBufferCamera->getRenderSurface()->setDrawableType( Producer::RenderSurface::DrawableType_PBuffer );
gPBufferCamera->getRenderSurface()->setWindowRectangle( 0, 0, width, height );
gPBufferCamera->getRenderSurface()->setRenderToTextureMode(Producer::RenderSurface::RenderToRGBTexture);
gPBufferSceneHandler = new osgProducer::OsgSceneHandler;
gPBufferSceneHandler->getSceneView()->setDefaults();
gPBufferSceneHandler->getSceneView()->setSceneData(subgraph);
gPBufferCamera->setSceneHandler( gPBufferSceneHandler.get());
gPBufferCamera->setClearColor( 0.1f,0.9f,0.3f,1.0f );
const osg::BoundingSphere& bs = subgraph->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<subgraph<<std::endl;
return;
}
float znear = 1.0f*bs.radius();
float zfar = 3.0f*bs.radius();
// 2:1 aspect ratio as per flag geomtry below.
float top = 0.25f*znear;
float right = 0.5f*znear;
znear *= 0.9f;
zfar *= 1.1f;
osg::Vec3 eye(bs.center() + osg::Vec3(0.0f, 2.0f, 0.0f)*bs.radius());
gPBufferCamera->setViewByLookat(
eye.x(), eye.y(), eye.z(),
bs.center().x(), bs.center().y(), bs.center().z(),
0.0f, 0.0f, 1.0f);
gPBufferCamera->setLensFrustum(-right,right,-top,top,znear,zfar);
// The Producer PBuffer example says:
//
// "This line is not necessary on glX pbuffer examples, but Windows
// seems to not like rendering to the back buffer on pbuffers"
//
// but I've found that doing this causes a flickering texture. Everything
// works fine for me (on Windows) if I just comment it out.
//gPBufferSceneHandler->getSceneView()->setDrawBufferValue( GL_FRONT );
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
osg::DisplaySettings::instance()->readCommandLine(arguments);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use pbuffers and render to texture..");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--width <integer>","Set the width of the pbuffer & texture");
arguments.getApplicationUsage()->addCommandLineOption("--height <integer>","Set the height of the pbuffer & texture");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
unsigned int width=1024;
unsigned int height=512;
while (arguments.read("--width",width)) {}
while (arguments.read("--height",height)) {}
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load the nodes from the commandline arguments.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
// write_usage(osg::notify(osg::NOTICE),argv[0]);
return 1;
}
// create a transform to spin the model.
osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
loadedModelTransform->addChild(loadedModel.get());
osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
loadedModelTransform->setUpdateCallback(nc);
osg::Group* rootNode = new osg::Group();
// Create a waving rectangle that will use the pbuffer as a texture.
rootNode->addChild(createTexturedFlag(width,height));
// Set up a camera that will render a view of the model to the pbuffer.
InitPBufferCamera(loadedModelTransform,width, height);
// set the scene to render
viewer.setSceneData(rootNode);
// create the windows and run the threads.
viewer.realize();
#if defined(GLX_VERSION_1_1)
// This determins where Pixel reads occur from. The main Camera will
// set the pBuffer camera's rendersurface as the buffer to read from.
Producer::Camera* camera = viewer.getCamera(0);
camera->getRenderSurface()->setReadDrawable( gPBufferCamera->getRenderSurface());
#endif
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
loadedModelTransform->accept(*viewer.getUpdateVisitor());
viewer.update();
// fire off the cull and draw traversals of the scene.
// first the pbuffer draw
gPBufferCamera->frame();
// then the main view draw.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
gPBufferCamera = 0;
gPBufferSceneHandler = 0;
return 0;
}
<commit_msg>Added destructor to fix Cygwin build problem.<commit_after>#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/Stencil>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Billboard>
#include <osg/Material>
#include <osgUtil/TransformCallback>
#include <osgUtil/SmoothingVisitor>
#include <osgUtil/UpdateVisitor>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <Producer/Camera>
#include <Producer/CameraConfig>
osg::ref_ptr<Producer::Camera> gPBufferCamera;
osg::ref_ptr<osgProducer::OsgSceneHandler> gPBufferSceneHandler;
// call back which cretes a deformation field to oscilate the model.
class MyGeometryCallback :
public osg::Drawable::UpdateCallback,
public osg::Drawable::AttributeFunctor
{
public:
MyGeometryCallback(const osg::Vec3& o,
const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
double period,double xphase,double amplitude):
_firstCall(true),
_startTime(0.0),
_time(0.0),
_period(period),
_xphase(xphase),
_amplitude(amplitude),
_origin(o),
_xAxis(x),
_yAxis(y),
_zAxis(z) {}
virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
{
const osg::FrameStamp* fs = nv->getFrameStamp();
double referenceTime = fs->getReferenceTime();
if (_firstCall)
{
_firstCall = false;
_startTime = referenceTime;
}
_time = referenceTime-_startTime;
drawable->accept(*this);
drawable->dirtyBound();
osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
if (geometry)
{
osgUtil::SmoothingVisitor::smooth(*geometry);
}
}
virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
{
if (type == osg::Drawable::VERTICES)
{
const float TwoPI=2.0f*osg::PI;
const float phase = -_time/_period;
osg::Vec3* end = begin+count;
for (osg::Vec3* itr=begin;itr<end;++itr)
{
osg::Vec3 dv(*itr-_origin);
osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
local.z() = local.x()*_amplitude*
sinf(TwoPI*(phase+local.x()*_xphase));
(*itr) = _origin +
_xAxis*local.x()+
_yAxis*local.y()+
_zAxis*local.z();
}
}
}
bool _firstCall;
double _startTime;
double _time;
double _period;
double _xphase;
float _amplitude;
osg::Vec3 _origin;
osg::Vec3 _xAxis;
osg::Vec3 _yAxis;
osg::Vec3 _zAxis;
};
// Custom Texture subload callback, just acts the the standard subload modes in osg::Texture right now
// but code be used to define your own style callbacks.
class MyTextureSubloadCallback : public osg::Texture2D::SubloadCallback
{
public:
MyTextureSubloadCallback() {}
virtual ~MyTextureSubloadCallback() {}
virtual void load(const osg::Texture2D& texture,osg::State&) const
{
osg::notify(osg::INFO)<<"doing load"<<std::endl;
glTexImage2D( GL_TEXTURE_2D, 0, texture.getInternalFormat(), texture.getTextureWidth(), texture.getTextureHeight(), 0, GL_RGB, GL_FLOAT, 0 );
}
virtual void subload(const osg::Texture2D& ,osg::State&) const
{
osg::notify(osg::INFO)<<"doing subload"<<std::endl;
gPBufferCamera->getRenderSurface()->bindPBufferToTexture(Producer::RenderSurface::FrontBuffer);
}
};
osg::Node* createTexturedFlag(unsigned int width, unsigned int height)
{
// create the quad to visualize.
osg::Geometry* polyGeom = new osg::Geometry();
polyGeom->setSupportsDisplayList(false);
osg::Vec3 origin(0.0f,0.0f,0.0f);
osg::Vec3 xAxis(1.0f,0.0f,0.0f);
osg::Vec3 yAxis(0.0f,0.0f,1.0f);
osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
float flag_height = 100.0f;
float flag_width = 200.0f;
int noSteps = 20;
osg::Vec3Array* vertices = new osg::Vec3Array;
osg::Vec3 bottom = origin;
osg::Vec3 top = origin; top.z()+= flag_height;
osg::Vec3 dv = xAxis*(flag_width/((float)(noSteps-1)));
osg::Vec2Array* texcoords = new osg::Vec2Array;
osg::Vec2 bottom_texcoord(0.0f,0.0f);
osg::Vec2 top_texcoord(0.0f,1.0f);
osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);
for(int i=0;i<noSteps;++i)
{
vertices->push_back(top);
vertices->push_back(bottom);
top+=dv;
bottom+=dv;
texcoords->push_back(top_texcoord);
texcoords->push_back(bottom_texcoord);
top_texcoord+=dv_texcoord;
bottom_texcoord+=dv_texcoord;
}
// pass the created vertex array to the points geometry object.
polyGeom->setVertexArray(vertices);
polyGeom->setTexCoordArray(0,texcoords);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
polyGeom->setColorArray(colors);
polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
// new we need to add the texture to the Drawable, we do so by creating a
// StateSet to contain the Texture StateAttribute.
osg::StateSet* stateset = new osg::StateSet;
// Dynamic texture filled with data from pbuffer.
osg::Texture2D* texture = new osg::Texture2D;
//texture->setSubloadMode(osg::Texture::IF_DIRTY);
texture->setInternalFormat(GL_RGB);
texture->setTextureSize(width,height);
texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP);
texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP);
texture->setSubloadCallback(new MyTextureSubloadCallback());
stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
polyGeom->setStateSet(stateset);
polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/flag_width,0.2f));
osg::Geode* geode = new osg::Geode();
geode->addDrawable(polyGeom);
osg::Group* parent = new osg::Group;
parent->addChild(geode);
return parent;
}
void InitPBufferCamera(osg::Node* subgraph, unsigned int width, unsigned int height)
{
if (!subgraph) return;
gPBufferCamera = new Producer::Camera;
gPBufferCamera->getRenderSurface()->setDrawableType( Producer::RenderSurface::DrawableType_PBuffer );
gPBufferCamera->getRenderSurface()->setWindowRectangle( 0, 0, width, height );
gPBufferCamera->getRenderSurface()->setRenderToTextureMode(Producer::RenderSurface::RenderToRGBTexture);
gPBufferSceneHandler = new osgProducer::OsgSceneHandler;
gPBufferSceneHandler->getSceneView()->setDefaults();
gPBufferSceneHandler->getSceneView()->setSceneData(subgraph);
gPBufferCamera->setSceneHandler( gPBufferSceneHandler.get());
gPBufferCamera->setClearColor( 0.1f,0.9f,0.3f,1.0f );
const osg::BoundingSphere& bs = subgraph->getBound();
if (!bs.valid())
{
osg::notify(osg::WARN) << "bb invalid"<<subgraph<<std::endl;
return;
}
float znear = 1.0f*bs.radius();
float zfar = 3.0f*bs.radius();
// 2:1 aspect ratio as per flag geomtry below.
float top = 0.25f*znear;
float right = 0.5f*znear;
znear *= 0.9f;
zfar *= 1.1f;
osg::Vec3 eye(bs.center() + osg::Vec3(0.0f, 2.0f, 0.0f)*bs.radius());
gPBufferCamera->setViewByLookat(
eye.x(), eye.y(), eye.z(),
bs.center().x(), bs.center().y(), bs.center().z(),
0.0f, 0.0f, 1.0f);
gPBufferCamera->setLensFrustum(-right,right,-top,top,znear,zfar);
// The Producer PBuffer example says:
//
// "This line is not necessary on glX pbuffer examples, but Windows
// seems to not like rendering to the back buffer on pbuffers"
//
// but I've found that doing this causes a flickering texture. Everything
// works fine for me (on Windows) if I just comment it out.
//gPBufferSceneHandler->getSceneView()->setDrawBufferValue( GL_FRONT );
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
osg::DisplaySettings::instance()->readCommandLine(arguments);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use pbuffers and render to texture..");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--width <integer>","Set the width of the pbuffer & texture");
arguments.getApplicationUsage()->addCommandLineOption("--height <integer>","Set the height of the pbuffer & texture");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
unsigned int width=1024;
unsigned int height=512;
while (arguments.read("--width",width)) {}
while (arguments.read("--height",height)) {}
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load the nodes from the commandline arguments.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel)
{
// write_usage(osg::notify(osg::NOTICE),argv[0]);
return 1;
}
// create a transform to spin the model.
osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
loadedModelTransform->addChild(loadedModel.get());
osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
loadedModelTransform->setUpdateCallback(nc);
osg::Group* rootNode = new osg::Group();
// Create a waving rectangle that will use the pbuffer as a texture.
rootNode->addChild(createTexturedFlag(width,height));
// Set up a camera that will render a view of the model to the pbuffer.
InitPBufferCamera(loadedModelTransform,width, height);
// set the scene to render
viewer.setSceneData(rootNode);
// create the windows and run the threads.
viewer.realize();
#if defined(GLX_VERSION_1_1)
// This determins where Pixel reads occur from. The main Camera will
// set the pBuffer camera's rendersurface as the buffer to read from.
Producer::Camera* camera = viewer.getCamera(0);
camera->getRenderSurface()->setReadDrawable( gPBufferCamera->getRenderSurface());
#endif
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
loadedModelTransform->accept(*viewer.getUpdateVisitor());
viewer.update();
// fire off the cull and draw traversals of the scene.
// first the pbuffer draw
gPBufferCamera->frame();
// then the main view draw.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
gPBufferCamera = 0;
gPBufferSceneHandler = 0;
return 0;
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
PLATFORM_ASSERT(end >= start);
char s[100];
for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
}
bool wordIsUUID = false;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.'))
chAttr = SCE_C_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
wordIsUUID = strcmp(s, "uuid") == 0;
}
}
styler.ColourTo(end, chAttr);
return wordIsUUID;
}
static bool isOKBeforeRE(char ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold");
bool foldComment = styler.GetPropertyInt("fold.comment");
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int state = initStyle;
int styleBeforeLineStart = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
char chPrevNonWhite = ' ';
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
styler.StartSegment(startPos);
bool lastWordWasUUID = false;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (atEOL) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (ch == '@' && chNext == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_C_VERBATIM;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (iswordstart(ch) || (ch == '@')) {
styler.ColourTo(i - 1, state);
if (lastWordWasUUID) {
state = SCE_C_UUID;
lastWordWasUUID = false;
} else {
state = SCE_C_IDENTIFIER;
}
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i - 1, state);
if (foldComment)
levelCurrent++;
if (styler.SafeGetCharAt(i + 2) == '*' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
styler.ColourTo(i - 1, state);
if (styler.SafeGetCharAt(i + 2) == '/' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTLINEDOC;
else
state = SCE_C_COMMENTLINE;
} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
styler.ColourTo(i - 1, state);
state = SCE_C_REGEX;
} else if (ch == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i - 1, state);
state = SCE_C_CHARACTER;
} else if (ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
styler.ColourTo(i - 1, state);
state = SCE_C_PREPROCESSOR;
// Skip whitespace between # and preprocessor word
do {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} while (isspacechar(ch) && (i < lengthDoc));
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
if (ch == '/' && chNext == '*') {
if (foldComment)
levelCurrent++;
if (styler.SafeGetCharAt(i + 2) == '*')
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
}
} else {
if (state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (isspacechar(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
} else {
if (atEOL && (chPrev != '\\')) {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(styleBeforeLineStart == SCE_C_COMMENT) &&
(i > styler.GetStartSegment())))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
if (foldComment)
levelCurrent--;
}
}
} else if (state == SCE_C_COMMENTDOC) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(styleBeforeLineStart == SCE_C_COMMENTDOC) &&
(i > styler.GetStartSegment())))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
if (foldComment)
levelCurrent--;
}
}
} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
styler.ColourTo(i - 1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
styler.ColourTo(i - 1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_REGEX) {
if (ch == '\r' || ch == '\n' || ch == '/') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (ch == '\\') {
// Gobble up the quoted character
if (chNext == '\\' || chNext == '/') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
} else if (state == SCE_C_VERBATIM) {
if (ch == '\"') {
if (chNext == '\"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_UUID) {
if (ch == '\r' || ch == '\n' || ch == ')') {
styler.ColourTo(i - 1, state);
if (ch == ')')
styler.ColourTo(i, SCE_C_OPERATOR);
state = SCE_C_DEFAULT;
}
}
}
if (atEOL) {
if (fold) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.ColourTo(i, state);
styler.Flush();
styler.SetLevel(lineCurrent, lev);
styler.StartAt(i + 1);
}
lineCurrent++;
levelPrev = levelCurrent;
}
styleBeforeLineStart = state;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
chPrev = ch;
if (ch != ' ' && ch != '\t')
chPrevNonWhite = ch;
}
styler.ColourTo(lengthDoc - 1, state);
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
if (fold) {
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<commit_msg>Separated folding from lexing.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
PLATFORM_ASSERT(end >= start);
char s[100];
for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
}
bool wordIsUUID = false;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.'))
chAttr = SCE_C_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
wordIsUUID = strcmp(s, "uuid") == 0;
}
}
styler.ColourTo(end, chAttr);
return wordIsUUID;
}
static bool isOKBeforeRE(char ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
// Finished the styling, time for folding
bool fold = styler.GetPropertyInt("fold");
bool foldComment = styler.GetPropertyInt("fold.comment");
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
if (fold) {
for (unsigned int j = startPos; j < lengthDoc; j++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(j + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(j + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
//int lineCurrent = styler.GetLine(startPos);
int state = initStyle;
int styleBeforeLineStart = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
char chPrevNonWhite = ' ';
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
styler.StartSegment(startPos);
bool lastWordWasUUID = false;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (atEOL) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (ch == '@' && chNext == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_C_VERBATIM;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (iswordstart(ch) || (ch == '@')) {
styler.ColourTo(i - 1, state);
if (lastWordWasUUID) {
state = SCE_C_UUID;
lastWordWasUUID = false;
} else {
state = SCE_C_IDENTIFIER;
}
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i - 1, state);
if (styler.SafeGetCharAt(i + 2) == '*' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
styler.ColourTo(i - 1, state);
if (styler.SafeGetCharAt(i + 2) == '/' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTLINEDOC;
else
state = SCE_C_COMMENTLINE;
} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
styler.ColourTo(i - 1, state);
state = SCE_C_REGEX;
} else if (ch == '\"') {
styler.ColourTo(i - 1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i - 1, state);
state = SCE_C_CHARACTER;
} else if (ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
styler.ColourTo(i - 1, state);
state = SCE_C_PREPROCESSOR;
// Skip whitespace between # and preprocessor word
do {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} while (isspacechar(ch) && (i < lengthDoc));
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
if (ch == '/' && chNext == '*') {
if (styler.SafeGetCharAt(i + 2) == '*')
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
}
}
} else {
if (state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (isspacechar(ch)) {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
} else {
if (atEOL && (chPrev != '\\')) {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(styleBeforeLineStart == SCE_C_COMMENT) &&
(i > styler.GetStartSegment())))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTDOC) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(styleBeforeLineStart == SCE_C_COMMENTDOC) &&
(i > styler.GetStartSegment())))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i - 1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
styler.ColourTo(i - 1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
styler.ColourTo(i - 1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_REGEX) {
if (ch == '\r' || ch == '\n' || ch == '/') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (ch == '\\') {
// Gobble up the quoted character
if (chNext == '\\' || chNext == '/') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
} else if (state == SCE_C_VERBATIM) {
if (ch == '\"') {
if (chNext == '\"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_UUID) {
if (ch == '\r' || ch == '\n' || ch == ')') {
styler.ColourTo(i - 1, state);
if (ch == ')')
styler.ColourTo(i, SCE_C_OPERATOR);
state = SCE_C_DEFAULT;
}
}
}
if (atEOL) {
styleBeforeLineStart = state;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
chPrev = ch;
if (ch != ' ' && ch != '\t')
chPrevNonWhite = ch;
}
styler.ColourTo(lengthDoc - 1, state);
styler.Flush();
FoldCppDoc(startPos, length, initStyle, keywordlists, styler);
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
// WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
int noDocChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
noDocChars = 0;
if (sc.Match("/**") || sc.Match("/*!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
else
sc.SetState(SCE_C_COMMENT);
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment");
bool foldCompact = styler.GetPropertyInt("fold.compact", 1);
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
<commit_msg>Added Steve's doc comment keyword states.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
int noDocChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if ((sc.ch == '@' || sc.ch == '\\') && (noDocChars == 0)) {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
} else if (sc.atLineEnd) {
noDocChars = 0;
} else if (!isspace(sc.ch)) {
noDocChars++;
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
noDocChars = -1;
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment");
bool foldCompact = styler.GetPropertyInt("fold.compact", 1);
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc);
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TNamed.h>
#include "AliESDRun.h"
#include "AliESDVertex.h"
#include "AliLog.h"
//-------------------------------------------------------------------------
// Implementation Class AliESDRun
// Run by run data
// for the ESD
// Origin: Christian Klein-Boesing, CERN, Christian.Klein-Boesing@cern.ch
//-------------------------------------------------------------------------
ClassImp(AliESDRun)
//______________________________________________________________________________
AliESDRun::AliESDRun() :
TObject(),
fMagneticField(0),
fPeriodNumber(0),
fRunNumber(0),
fRecoVersion(0),
fTriggerClasses(kNTriggerClasses)
{
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=0.;
fTriggerClasses.SetOwner(kTRUE);
}
//______________________________________________________________________________
AliESDRun::AliESDRun(const AliESDRun &esd) :
TObject(esd),
fMagneticField(esd.fMagneticField),
fPeriodNumber(esd.fPeriodNumber),
fRunNumber(esd.fRunNumber),
fRecoVersion(esd.fRecoVersion),
fTriggerClasses(TObjArray(kNTriggerClasses))
{
// Copy constructor
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
}
//______________________________________________________________________________
AliESDRun& AliESDRun::operator=(const AliESDRun &esd)
{
// assigment operator
if(this!=&esd) {
TObject::operator=(esd);
fRunNumber=esd.fRunNumber;
fPeriodNumber=esd.fPeriodNumber;
fRecoVersion=esd.fRecoVersion;
fMagneticField=esd.fMagneticField;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
fTriggerClasses.Clear();
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
}
return *this;
}
void AliESDRun::Copy(TObject &obj) const{
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliESDRun *robj = dynamic_cast<AliESDRun*>(&obj);
if(!robj)return; // not an aliesdrun
*robj = *this;
}
void AliESDRun::SetDiamond(const AliESDVertex *vertex) {
// set the interaction diamond
fDiamondXY[0]=vertex->GetXv();
fDiamondXY[1]=vertex->GetYv();
Double32_t cov[6];
vertex->GetCovMatrix(cov);
fDiamondCovXY[0]=cov[0];
fDiamondCovXY[1]=cov[1];
fDiamondCovXY[2]=cov[2];
}
//______________________________________________________________________________
void AliESDRun::Print(const Option_t *) const
{
// Print some data members
printf("Mean vertex in RUN %d: X=%.4f Y=%.4f cm\n",
GetRunNumber(),GetDiamondX(),GetDiamondY());
printf("Magnetic field = %f T\n",
GetMagneticField());
printf("Event from reconstruction version %d \n",fRecoVersion);
printf("List of active trigger classes: ");
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
printf("%s ",str->GetName());
}
printf("\n");
}
void AliESDRun::Reset()
{
// reset data members
fRunNumber = 0;
fPeriodNumber = 0;
fRecoVersion = 0;
fMagneticField = 0;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=0.;
fTriggerClasses.Clear();
}
//______________________________________________________________________________
void AliESDRun::SetTriggerClass(const char*name, Int_t index)
{
// Fill the trigger class name
// into the corresponding array
if (index >= kNTriggerClasses || index < 0) {
AliError(Form("Index (%d) is outside the allowed range (0,49)!",index));
return;
}
fTriggerClasses.AddAt(new TNamed(name,NULL),index);
}
//______________________________________________________________________________
const char* AliESDRun::GetTriggerClass(Int_t index) const
{
// Get the trigger class name at
// specified position in the trigger mask
TNamed *trclass = (TNamed *)fTriggerClasses.At(index);
if (trclass)
return trclass->GetName();
else
return "";
}
//______________________________________________________________________________
TString AliESDRun::GetActiveTriggerClasses() const
{
// Construct and return
// the list of trigger classes
// which are present in the run
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
return trclasses;
}
//______________________________________________________________________________
TString AliESDRun::GetFiredTriggerClasses(ULong64_t mask) const
{
// Constructs and returns the
// list of trigger classes that
// have been fired. Uses the trigger
// class mask as an argument.
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
if (mask & (1 << i)) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
}
return trclasses;
}
//______________________________________________________________________________
Bool_t AliESDRun::IsTriggerClassFired(ULong64_t mask, const char *name) const
{
// Checks if the trigger class
// identified by 'name' has been
// fired. Uses the trigger class mask.
TNamed *trclass = (TNamed *)fTriggerClasses.FindObject(name);
if (!trclass) return kFALSE;
Int_t iclass = fTriggerClasses.IndexOf(trclass);
if (iclass < 0) return kFALSE;
if (mask & (1 << iclass))
return kTRUE;
else
return kFALSE;
}
<commit_msg>The default values of the diagonal elements of the interaction diamond covariance should be 3*3 (Andrea)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TNamed.h>
#include "AliESDRun.h"
#include "AliESDVertex.h"
#include "AliLog.h"
//-------------------------------------------------------------------------
// Implementation Class AliESDRun
// Run by run data
// for the ESD
// Origin: Christian Klein-Boesing, CERN, Christian.Klein-Boesing@cern.ch
//-------------------------------------------------------------------------
ClassImp(AliESDRun)
//______________________________________________________________________________
AliESDRun::AliESDRun() :
TObject(),
fMagneticField(0),
fPeriodNumber(0),
fRunNumber(0),
fRecoVersion(0),
fTriggerClasses(kNTriggerClasses)
{
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.SetOwner(kTRUE);
}
//______________________________________________________________________________
AliESDRun::AliESDRun(const AliESDRun &esd) :
TObject(esd),
fMagneticField(esd.fMagneticField),
fPeriodNumber(esd.fPeriodNumber),
fRunNumber(esd.fRunNumber),
fRecoVersion(esd.fRecoVersion),
fTriggerClasses(TObjArray(kNTriggerClasses))
{
// Copy constructor
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
}
//______________________________________________________________________________
AliESDRun& AliESDRun::operator=(const AliESDRun &esd)
{
// assigment operator
if(this!=&esd) {
TObject::operator=(esd);
fRunNumber=esd.fRunNumber;
fPeriodNumber=esd.fPeriodNumber;
fRecoVersion=esd.fRecoVersion;
fMagneticField=esd.fMagneticField;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=esd.fDiamondXY[i];
for (Int_t i=0; i<3; i++) fDiamondCovXY[i]=esd.fDiamondCovXY[i];
fTriggerClasses.Clear();
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((esd.fTriggerClasses).At(i));
if (str) fTriggerClasses.AddAt(new TNamed(*str),i);
}
}
return *this;
}
void AliESDRun::Copy(TObject &obj) const{
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliESDRun *robj = dynamic_cast<AliESDRun*>(&obj);
if(!robj)return; // not an aliesdrun
*robj = *this;
}
void AliESDRun::SetDiamond(const AliESDVertex *vertex) {
// set the interaction diamond
fDiamondXY[0]=vertex->GetXv();
fDiamondXY[1]=vertex->GetYv();
Double32_t cov[6];
vertex->GetCovMatrix(cov);
fDiamondCovXY[0]=cov[0];
fDiamondCovXY[1]=cov[1];
fDiamondCovXY[2]=cov[2];
}
//______________________________________________________________________________
void AliESDRun::Print(const Option_t *) const
{
// Print some data members
printf("Mean vertex in RUN %d: X=%.4f Y=%.4f cm\n",
GetRunNumber(),GetDiamondX(),GetDiamondY());
printf("Magnetic field = %f T\n",
GetMagneticField());
printf("Event from reconstruction version %d \n",fRecoVersion);
printf("List of active trigger classes: ");
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
printf("%s ",str->GetName());
}
printf("\n");
}
void AliESDRun::Reset()
{
// reset data members
fRunNumber = 0;
fPeriodNumber = 0;
fRecoVersion = 0;
fMagneticField = 0;
for (Int_t i=0; i<2; i++) fDiamondXY[i]=0.;
fDiamondCovXY[0]=fDiamondCovXY[2]=3.*3.;
fDiamondCovXY[1]=0.;
fTriggerClasses.Clear();
}
//______________________________________________________________________________
void AliESDRun::SetTriggerClass(const char*name, Int_t index)
{
// Fill the trigger class name
// into the corresponding array
if (index >= kNTriggerClasses || index < 0) {
AliError(Form("Index (%d) is outside the allowed range (0,49)!",index));
return;
}
fTriggerClasses.AddAt(new TNamed(name,NULL),index);
}
//______________________________________________________________________________
const char* AliESDRun::GetTriggerClass(Int_t index) const
{
// Get the trigger class name at
// specified position in the trigger mask
TNamed *trclass = (TNamed *)fTriggerClasses.At(index);
if (trclass)
return trclass->GetName();
else
return "";
}
//______________________________________________________________________________
TString AliESDRun::GetActiveTriggerClasses() const
{
// Construct and return
// the list of trigger classes
// which are present in the run
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
return trclasses;
}
//______________________________________________________________________________
TString AliESDRun::GetFiredTriggerClasses(ULong64_t mask) const
{
// Constructs and returns the
// list of trigger classes that
// have been fired. Uses the trigger
// class mask as an argument.
TString trclasses;
for(Int_t i = 0; i < kNTriggerClasses; i++) {
if (mask & (1 << i)) {
TNamed *str = (TNamed *)((fTriggerClasses).At(i));
if (str) {
trclasses += " ";
trclasses += str->GetName();
trclasses += " ";
}
}
}
return trclasses;
}
//______________________________________________________________________________
Bool_t AliESDRun::IsTriggerClassFired(ULong64_t mask, const char *name) const
{
// Checks if the trigger class
// identified by 'name' has been
// fired. Uses the trigger class mask.
TNamed *trclass = (TNamed *)fTriggerClasses.FindObject(name);
if (!trclass) return kFALSE;
Int_t iclass = fTriggerClasses.IndexOf(trclass);
if (iclass < 0) return kFALSE;
if (mask & (1 << iclass))
return kTRUE;
else
return kFALSE;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemo6accelerometer.h"
const char *maemo6accelerometer::id("maemo6.accelerometer");
bool maemo6accelerometer::m_initDone = false;
maemo6accelerometer::maemo6accelerometer(QSensor *sensor)
: maemo6sensorbase(sensor)
{
setReading<QAccelerometerReading>(&m_reading);
if (!m_initDone) {
qDBusRegisterMetaType<XYZ>();
initSensor<AccelerometerSensorChannelInterface>("accelerometersensor");
if (m_sensorInterface)
QObject::connect(static_cast<AccelerometerSensorChannelInterface*>(m_sensorInterface), SIGNAL(dataAvailable(const XYZ&)), this, SLOT(slotDataAvailable(const XYZ&)));
else
qWarning() << "Unable to initialize accelerometer sensor.";
// adding metadata
addDataRate(100, 100); // 100Hz
//addDataRate(400, 400); // 400Hz
// accuracy - or resolution???
// 2^8 = 256 256/2 - 1 = 127
addOutputRange(-2*GRAVITY_EARTH, 2*GRAVITY_EARTH, 2*GRAVITY_EARTH/127); // 2G
addOutputRange(-8*GRAVITY_EARTH, 8*GRAVITY_EARTH, 8*GRAVITY_EARTH/127); // 8G
setDescription(QLatin1String("Measures x, y, and z axes accelerations in m/s^2"));
m_initDone = true;
}
}
void maemo6accelerometer::slotDataAvailable(const XYZ& data)
{
// Convert from milli-Gs to meters per second per second
// Using 1 G = 9.80665 m/s^2
qreal ax = data.x() * GRAVITY_EARTH_THOUSANDTH;
qreal ay = - data.y() * GRAVITY_EARTH_THOUSANDTH;
qreal az = - data.z() * GRAVITY_EARTH_THOUSANDTH;
m_reading.setX(ax);
m_reading.setY(ay);
m_reading.setZ(az);
//m_reading.setTimestamp(data.timestamp());
m_reading.setTimestamp(createTimestamp()); //TODO: use correct timestamp
newReadingAvailable();
}
<commit_msg>x axis fix<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemo6accelerometer.h"
const char *maemo6accelerometer::id("maemo6.accelerometer");
bool maemo6accelerometer::m_initDone = false;
maemo6accelerometer::maemo6accelerometer(QSensor *sensor)
: maemo6sensorbase(sensor)
{
setReading<QAccelerometerReading>(&m_reading);
if (!m_initDone) {
qDBusRegisterMetaType<XYZ>();
initSensor<AccelerometerSensorChannelInterface>("accelerometersensor");
if (m_sensorInterface)
QObject::connect(static_cast<AccelerometerSensorChannelInterface*>(m_sensorInterface), SIGNAL(dataAvailable(const XYZ&)), this, SLOT(slotDataAvailable(const XYZ&)));
else
qWarning() << "Unable to initialize accelerometer sensor.";
// adding metadata
addDataRate(100, 100); // 100Hz
//addDataRate(400, 400); // 400Hz
// accuracy - or resolution???
// 2^8 = 256 256/2 - 1 = 127
addOutputRange(-2*GRAVITY_EARTH, 2*GRAVITY_EARTH, 2*GRAVITY_EARTH/127); // 2G
addOutputRange(-8*GRAVITY_EARTH, 8*GRAVITY_EARTH, 8*GRAVITY_EARTH/127); // 8G
setDescription(QLatin1String("Measures x, y, and z axes accelerations in m/s^2"));
m_initDone = true;
}
}
void maemo6accelerometer::slotDataAvailable(const XYZ& data)
{
// Convert from milli-Gs to meters per second per second
// Using 1 G = 9.80665 m/s^2
qreal ax = - data.x() * GRAVITY_EARTH_THOUSANDTH;
qreal ay = - data.y() * GRAVITY_EARTH_THOUSANDTH;
qreal az = - data.z() * GRAVITY_EARTH_THOUSANDTH;
m_reading.setX(ax);
m_reading.setY(ay);
m_reading.setZ(az);
//m_reading.setTimestamp(data.timestamp());
m_reading.setTimestamp(createTimestamp()); //TODO: use correct timestamp
newReadingAvailable();
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2002 by Mrten Svanfeldt
Anders Stenberg
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/scf.h"
#include "csutil/cscolor.h"
#include "csgeom/vector2.h"
#include "csgeom/vector3.h"
#include "ivideo/rndbuf.h"
#include "gl_sysbufmgr.h"
#include "gl_varbufmgr.h"
#include "gl_render3d.h"
SCF_IMPLEMENT_IBASE (csVARRenderBuffer)
SCF_IMPLEMENTS_INTERFACE (iRenderBuffer)
SCF_IMPLEMENT_IBASE_END
SCF_IMPLEMENT_IBASE (csVARRenderBufferManager)
SCF_IMPLEMENTS_INTERFACE (iRenderBufferManager)
SCF_IMPLEMENT_IBASE_END
#ifndef max
#define max(a,b) ((a)>(b)?(a):(b))
#endif
int csBuddyAllocator::treeSize(int size)
{
int s=size>>CS_BUDDY_SHIFT; /*get size in blocks*/
if(s<=0) /*sanity check: >0*/
return -1;
while(s>1) /*sanity check: power of two*/
s=s>>1;
if(s!=1)
return -1;
return (2*(size>>CS_BUDDY_SHIFT)-1)*sizeof(char);
}
int csBuddyAllocator::ptoi(void *ptr)
{
int i;
assert(m_Tree&&m_Size>0&&m_Height>0);
assert((((int)ptr)&CS_BUDDY_ADD)==0);
i=((int)ptr)>>CS_BUDDY_SHIFT;
if(i<0||i>=m_Size) /*doesn't fit?*/
return -1;
else
return (i+m_Size-1); /*i is an index now*/
}
void* csBuddyAllocator::itop(int i, char level)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>=0);
assert(level<m_Height);
i-=(1<<m_Height-level-1)-1; /*cryptic conversion i->address*/
return (void*)((i<<level+CS_BUDDY_SHIFT));
}
void csBuddyAllocator::stabilize1(int i)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>0);
while(i>0)
{
i=(i-1)/2; /*go parent*/
m_Tree[i]=max(m_Tree[2*i+1],m_Tree[2*i+2]);
} /*parent=greater of children*/
}
void csBuddyAllocator::stabilize2(int i, char level)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>0);
assert(level<m_Height);
while(i>0)
{
i=(i-1)/2; /*go parent*/
assert(m_Tree[i]<=level+1);
if(m_Tree[2*i+1]>m_Tree[2*i+2])
m_Tree[i]=m_Tree[2*i+1]; /*-use left-*/
else if(m_Tree[2*i+1]<m_Tree[2*i+2])
m_Tree[i]=m_Tree[2*i+2]; /*-use right-*/
else if(m_Tree[2*i+1]==level)
m_Tree[i]=level+1; /*coalesce*/
else
m_Tree[i]=m_Tree[2*i+1]; /*otherwise, use one*/
level++; /*next level*/
}
}
void csBuddyAllocator::traverse(int i, char level)
{
int block_no=(i-((1<<m_Height-level-1)-1))*(1<<level);
void *block_addr=itop(i,level);
int block_sz=1<<level;
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>=0);
assert(level<m_Height);
if(m_Tree[i]==level)
printf("#%6d, at %08x, size %6d, Free\n",block_no,(unsigned)block_addr,block_sz);
else if(m_Tree[i]<0)
printf("#%6d, at %08x, size %6d, Busy\n",block_no,(unsigned)block_addr,block_sz);
else
{
traverse(2*i+1,level-1);
traverse(2*i+2,level-1);
}
}
bool csBuddyAllocator::Initialize(int size)
{
m_Tree=0; /*destroy previous info*/
m_Size=0;
if(treeSize(size)<0) /*sanity check*/
return false;
if(size<0) /*sanity check*/
return false;
m_Tree= new char[treeSize(size)];
m_Size=size=size>>CS_BUDDY_SHIFT; /*remember*/
for(m_Height=1;size>1;m_Height++)
size=size>>1;
{
int i;
assert(m_Tree&&m_Size>0&&m_Height>0);
for(i=0;i<2*m_Size-1;i++)
m_Tree[i]=-1;
m_Freeblk=0;
}
{
int i,j,k;
char level=m_Height-1;
assert(m_Tree&&m_Size>0&&m_Height>0);
for(i=1,j=0;i<=m_Size;level--,i=2*i)
for(k=i;k>0;j++,k--) /*fill line*/
m_Tree[j]=level;
m_Freeblk=m_Size;
}
return true;
}
void* csBuddyAllocator::alloc(int size)
{
int i,found;
char level=m_Height-1;
assert(m_Tree&&m_Size>0&&m_Height>0);
size=(size+CS_BUDDY_ADD)>>CS_BUDDY_SHIFT; /*sz in blocks now*/
if(size<=0||1<<m_Tree[0]<size) /*oops?*/
return 0;
for(found=0,i=0;!found&&2*i+2<2*m_Size-1;level--)
{
assert(m_Tree[i]<=level&&m_Tree[i]>=0);
/**left smaller than right?**/
if(m_Tree[2*i+1]<=m_Tree[2*i+2])
if(1<<m_Tree[2*i+1]>=size) /*...and still large enough?*/
i=2*i+1; /*- go left -*/
else if(1<<m_Tree[2*i+2]>=size)/*at least, right large enough?*/
i=2*i+2; /*- go right -*/
else
found=1; /*none enough, use current*/
else /**right smaller than left**/
if(1<<m_Tree[2*i+2]>=size) /*...and still large enough?*/
i=2*i+2; /*- go right -*/
else if(1<<m_Tree[2*i+1]>=size)/*at least, left large enough?*/
i=2*i+1; /*- go left -*/
else
found=1; /*none enough, use current*/
}
assert(1<<m_Tree[i]>=size);
level=m_Tree[i];
m_Tree[i]=-1; /*mark allocated*/
stabilize1(i); /*correct tree*/
m_Freeblk-=size;
return itop(i,level);
}
bool csBuddyAllocator::free(void *ptr)
{
char level;
int i=ptoi(ptr);
assert(m_Tree&&m_Size>0&&m_Height>0);
if(i<0)
return 0; /*find parent with tree[i]<=0*/
for(level=0;i>=0&&m_Tree[i]>=0;level++)
i=(i-1)/2;
if(i>=0) /*if found, free it*/
{
m_Tree[i]=level;
stabilize2(i,level); /*correct tree*/
m_Freeblk+=1<<level;
return true;
}
else
return false;
}
#define CS_VAR_ALLOC_SIZE (8*1024*1024)
bool csVARRenderBufferManager::Initialize(csGLRender3D* render3d)
{
csVARRenderBufferManager::render3d = render3d;
// Alloc some VAR-memory
// HACK: this should be fetched from config-file.. for now it's hardcoded
if(render3d->ext.wglAllocateMemoryNV)
var_buffer = (unsigned char*) render3d->ext.wglAllocateMemoryNV(CS_VAR_ALLOC_SIZE, 0.0f,0.0f,0.5f);
else
return false;
if(!var_buffer)
return false;
render3d->ext.glVertexArrayRangeNV(CS_VAR_ALLOC_SIZE, var_buffer);
glEnableClientState(GL_VERTEX_ARRAY_RANGE_NV);
myalloc = new csBuddyAllocator();
myalloc->Initialize(CS_VAR_ALLOC_SIZE);
return true;
}
csVARRenderBufferManager::~csVARRenderBufferManager()
{
if(var_buffer)
render3d->ext.wglFreeMemoryNV(var_buffer);
var_buffer = 0;
}
csPtr<iRenderBuffer> csVARRenderBufferManager::GetBuffer(int size, CS_RENDERBUFFER_TYPE location)
{
csVARRenderBuffer* buffer = new csVARRenderBuffer( NULL, size, location, this);
return buffer;
}
csVARRenderBuffer::csVARRenderBuffer(void *buffer, int size, CS_RENDERBUFFER_TYPE type, csVARRenderBufferManager* bm)
{
SCF_CONSTRUCT_IBASE (NULL);
memblock = new csVARMemoryBlock();
/// decide wheter to use VAR or not (some special cases)
if(type == CS_BUF_INDEX)
{
isRealVAR = false;
memblock->buffer = new char[size];
}
else if(type == CS_BUF_STATIC)
{
isRealVAR = true;
memblock->buffer = bm->var_buffer + (int) bm->myalloc->alloc(size);
bm->render3d->ext.glGenFencesNV(1, &memblock->fence_id);
} else
{
isRealVAR = true;
}
csVARRenderBuffer::size = size;
csVARRenderBuffer::type = type;
csVARRenderBuffer::bm = bm;
locked = false;
}
csVARRenderBuffer::~csVARRenderBuffer()
{
if (memblock)
{
bm->render3d->ext.glFinishFenceNV(memblock->fence_id);
delete [] (char *)memblock->buffer;
delete memblock;
}
}
void* csVARRenderBuffer::Lock(CS_BUFFER_LOCK_TYPE lockType)
{
if(locked) return NULL;
if(memblock->buffer)
{
if(lockType != CS_BUF_LOCK_RENDER)
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}
if(type == CS_BUF_STATIC)
{
bm->render3d->ext.glFinishFenceNV(memblock->fence_id); //for now.. lockup until finnished
lastlock = lockType;
locked = true;
return memblock->buffer;
}else if(type == CS_BUF_INDEX)
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}else if(type == CS_BUF_DYNAMIC)
{
if(bm->render3d->ext.glTestFenceNV(memblock->fence_id))
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}
else
return NULL;
}else
return NULL;
}else
{
if(type == CS_BUF_DYNAMIC)
{
//alloc a new VAR buffer..
memblock->buffer = bm->myalloc->alloc(size);
bm->render3d->ext.glGenFencesNV(1, &memblock->fence_id);
lastlock = lockType;
locked = true;
return memblock->buffer;
}else
return NULL;
}
return NULL;
}
void csVARRenderBuffer::Release()
{
if(lastlock == CS_BUF_LOCK_RENDER && isRealVAR)
{
bm->render3d->ext.glSetFenceNV(memblock->fence_id, GL_ALL_COMPLETED_NV);
}
lastlock = CS_BUF_LOCK_NOLOCK;
locked = false;
}
<commit_msg>Fixed a small error in VAR buffer manager<commit_after>/*
Copyright (C) 2002 by Mrten Svanfeldt
Anders Stenberg
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/scf.h"
#include "csutil/cscolor.h"
#include "csgeom/vector2.h"
#include "csgeom/vector3.h"
#include "ivideo/rndbuf.h"
#include "gl_sysbufmgr.h"
#include "gl_varbufmgr.h"
#include "gl_render3d.h"
SCF_IMPLEMENT_IBASE (csVARRenderBuffer)
SCF_IMPLEMENTS_INTERFACE (iRenderBuffer)
SCF_IMPLEMENT_IBASE_END
SCF_IMPLEMENT_IBASE (csVARRenderBufferManager)
SCF_IMPLEMENTS_INTERFACE (iRenderBufferManager)
SCF_IMPLEMENT_IBASE_END
#ifndef max
#define max(a,b) ((a)>(b)?(a):(b))
#endif
int csBuddyAllocator::treeSize(int size)
{
int s=size>>CS_BUDDY_SHIFT; /*get size in blocks*/
if(s<=0) /*sanity check: >0*/
return -1;
while(s>1) /*sanity check: power of two*/
s=s>>1;
if(s!=1)
return -1;
return (2*(size>>CS_BUDDY_SHIFT)-1)*sizeof(char);
}
int csBuddyAllocator::ptoi(void *ptr)
{
int i;
assert(m_Tree&&m_Size>0&&m_Height>0);
assert((((int)ptr)&CS_BUDDY_ADD)==0);
i=((int)ptr)>>CS_BUDDY_SHIFT;
if(i<0||i>=m_Size) /*doesn't fit?*/
return -1;
else
return (i+m_Size-1); /*i is an index now*/
}
void* csBuddyAllocator::itop(int i, char level)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>=0);
assert(level<m_Height);
i-=(1<<m_Height-level-1)-1; /*cryptic conversion i->address*/
return (void*)((i<<level+CS_BUDDY_SHIFT));
}
void csBuddyAllocator::stabilize1(int i)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>0);
while(i>0)
{
i=(i-1)/2; /*go parent*/
m_Tree[i]=max(m_Tree[2*i+1],m_Tree[2*i+2]);
} /*parent=greater of children*/
}
void csBuddyAllocator::stabilize2(int i, char level)
{
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>0);
assert(level<m_Height);
while(i>0)
{
i=(i-1)/2; /*go parent*/
assert(m_Tree[i]<=level+1);
if(m_Tree[2*i+1]>m_Tree[2*i+2])
m_Tree[i]=m_Tree[2*i+1]; /*-use left-*/
else if(m_Tree[2*i+1]<m_Tree[2*i+2])
m_Tree[i]=m_Tree[2*i+2]; /*-use right-*/
else if(m_Tree[2*i+1]==level)
m_Tree[i]=level+1; /*coalesce*/
else
m_Tree[i]=m_Tree[2*i+1]; /*otherwise, use one*/
level++; /*next level*/
}
}
void csBuddyAllocator::traverse(int i, char level)
{
int block_no=(i-((1<<m_Height-level-1)-1))*(1<<level);
void *block_addr=itop(i,level);
int block_sz=1<<level;
assert(m_Tree&&m_Size>0&&m_Height>0);
assert(i<2*m_Size-1&&i>=0);
assert(level<m_Height);
if(m_Tree[i]==level)
printf("#%6d, at %08x, size %6d, Free\n",block_no,(unsigned)block_addr,block_sz);
else if(m_Tree[i]<0)
printf("#%6d, at %08x, size %6d, Busy\n",block_no,(unsigned)block_addr,block_sz);
else
{
traverse(2*i+1,level-1);
traverse(2*i+2,level-1);
}
}
bool csBuddyAllocator::Initialize(int size)
{
m_Tree=0; /*destroy previous info*/
m_Size=0;
if(treeSize(size)<0) /*sanity check*/
return false;
if(size<0) /*sanity check*/
return false;
m_Tree= new char[treeSize(size)];
m_Size=size=size>>CS_BUDDY_SHIFT; /*remember*/
for(m_Height=1;size>1;m_Height++)
size=size>>1;
{
int i;
assert(m_Tree&&m_Size>0&&m_Height>0);
for(i=0;i<2*m_Size-1;i++)
m_Tree[i]=-1;
m_Freeblk=0;
}
{
int i,j,k;
char level=m_Height-1;
assert(m_Tree&&m_Size>0&&m_Height>0);
for(i=1,j=0;i<=m_Size;level--,i=2*i)
for(k=i;k>0;j++,k--) /*fill line*/
m_Tree[j]=level;
m_Freeblk=m_Size;
}
return true;
}
void* csBuddyAllocator::alloc(int size)
{
int i,found;
char level=m_Height-1;
assert(m_Tree&&m_Size>0&&m_Height>0);
size=(size+CS_BUDDY_ADD)>>CS_BUDDY_SHIFT; /*sz in blocks now*/
if(size<=0||1<<m_Tree[0]<size) /*oops?*/
return 0;
for(found=0,i=0;!found&&2*i+2<2*m_Size-1;level--)
{
assert(m_Tree[i]<=level&&m_Tree[i]>=0);
/**left smaller than right?**/
if(m_Tree[2*i+1]<=m_Tree[2*i+2])
if(1<<m_Tree[2*i+1]>=size) /*...and still large enough?*/
i=2*i+1; /*- go left -*/
else if(1<<m_Tree[2*i+2]>=size)/*at least, right large enough?*/
i=2*i+2; /*- go right -*/
else
found=1; /*none enough, use current*/
else /**right smaller than left**/
if(1<<m_Tree[2*i+2]>=size) /*...and still large enough?*/
i=2*i+2; /*- go right -*/
else if(1<<m_Tree[2*i+1]>=size)/*at least, left large enough?*/
i=2*i+1; /*- go left -*/
else
found=1; /*none enough, use current*/
}
assert(1<<m_Tree[i]>=size);
level=m_Tree[i];
m_Tree[i]=-1; /*mark allocated*/
stabilize1(i); /*correct tree*/
m_Freeblk-=size;
return itop(i,level);
}
bool csBuddyAllocator::free(void *ptr)
{
char level;
int i=ptoi(ptr);
assert(m_Tree&&m_Size>0&&m_Height>0);
if(i<0)
return 0; /*find parent with tree[i]<=0*/
for(level=0;i>=0&&m_Tree[i]>=0;level++)
i=(i-1)/2;
if(i>=0) /*if found, free it*/
{
m_Tree[i]=level;
stabilize2(i,level); /*correct tree*/
m_Freeblk+=1<<level;
return true;
}
else
return false;
}
#define CS_VAR_ALLOC_SIZE (8*1024*1024)
bool csVARRenderBufferManager::Initialize(csGLRender3D* render3d)
{
csVARRenderBufferManager::render3d = render3d;
// Alloc some VAR-memory
// HACK: this should be fetched from config-file.. for now it's hardcoded
if(render3d->ext.wglAllocateMemoryNV)
var_buffer = (unsigned char*) render3d->ext.wglAllocateMemoryNV(CS_VAR_ALLOC_SIZE, 0.0f,0.0f,0.5f);
else
return false;
if(!var_buffer)
return false;
render3d->ext.glVertexArrayRangeNV(CS_VAR_ALLOC_SIZE, var_buffer);
glEnableClientState(GL_VERTEX_ARRAY_RANGE_NV);
myalloc = new csBuddyAllocator();
myalloc->Initialize(CS_VAR_ALLOC_SIZE);
return true;
}
csVARRenderBufferManager::~csVARRenderBufferManager()
{
if(var_buffer)
render3d->ext.wglFreeMemoryNV(var_buffer);
var_buffer = 0;
}
csPtr<iRenderBuffer> csVARRenderBufferManager::GetBuffer(int size, CS_RENDERBUFFER_TYPE location)
{
csVARRenderBuffer* buffer = new csVARRenderBuffer( NULL, size, location, this);
return buffer;
}
csVARRenderBuffer::csVARRenderBuffer(void *buffer, int size, CS_RENDERBUFFER_TYPE type, csVARRenderBufferManager* bm)
{
SCF_CONSTRUCT_IBASE (NULL);
memblock = new csVARMemoryBlock();
/// decide wheter to use VAR or not (some special cases)
if(type == CS_BUF_INDEX)
{
isRealVAR = false;
memblock->buffer = new char[size];
}
else if(type == CS_BUF_STATIC)
{
isRealVAR = true;
memblock->buffer = bm->var_buffer + (int) bm->myalloc->alloc(size);
bm->render3d->ext.glGenFencesNV(1, &memblock->fence_id);
} else
{
isRealVAR = true;
}
csVARRenderBuffer::size = size;
csVARRenderBuffer::type = type;
csVARRenderBuffer::bm = bm;
locked = false;
}
csVARRenderBuffer::~csVARRenderBuffer()
{
if (memblock && type != CS_BUF_INDEX)
{
bm->render3d->ext.glFinishFenceNV(memblock->fence_id);
bm->myalloc->free(memblock->buffer);
}else if(memblock && type == CS_BUF_INDEX)
{
delete memblock->buffer;
delete memblock;
}
}
void* csVARRenderBuffer::Lock(CS_BUFFER_LOCK_TYPE lockType)
{
if(locked) return NULL;
if(memblock->buffer)
{
if(lockType != CS_BUF_LOCK_RENDER)
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}
if(type == CS_BUF_STATIC)
{
bm->render3d->ext.glFinishFenceNV(memblock->fence_id); //for now.. lockup until finnished
lastlock = lockType;
locked = true;
return memblock->buffer;
}else if(type == CS_BUF_INDEX)
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}else if(type == CS_BUF_DYNAMIC)
{
if(bm->render3d->ext.glTestFenceNV(memblock->fence_id))
{
lastlock = lockType;
locked = true;
return memblock->buffer;
}
else
return NULL;
}else
return NULL;
}else
{
if(type == CS_BUF_DYNAMIC)
{
//alloc a new VAR buffer..
memblock->buffer = bm->myalloc->alloc(size);
bm->render3d->ext.glGenFencesNV(1, &memblock->fence_id);
lastlock = lockType;
locked = true;
return memblock->buffer;
}else
return NULL;
}
return NULL;
}
void csVARRenderBuffer::Release()
{
if(lastlock == CS_BUF_LOCK_RENDER && isRealVAR)
{
bm->render3d->ext.glSetFenceNV(memblock->fence_id, GL_ALL_COMPLETED_NV);
}
lastlock = CS_BUF_LOCK_NOLOCK;
locked = false;
}
<|endoftext|>
|
<commit_before>#pragma once
namespace usagi::keyboard::glfw3
{
const int glfw3_available_keys[] =
{ 32, 39
, 44, 45, 46, 47, 48, 49
, 50, 51, 52, 53, 54, 55, 56, 57, 59
, 61, 65, 66, 67, 68, 69
, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79
, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89
, 90, 91, 92, 93, 96
, 161, 162
, 256, 257, 258, 259
, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269
, 280, 281, 282, 283, 284
, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299
, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309
, 310, 311, 312, 313, 314
, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329
, 330, 331, 332, 333, 334, 335, 336
, 340, 341, 342, 343, 344, 345, 346, 347, 348
};
const char* glfw3_key_names[] =
// 0 .. 9
{ "", "", "", "", "", "", "", "", "", ""
// 10 .. 19
, "", "", "", "", "", "", "", "", "", ""
// 20 .. 29
, "", "", "", "", "", "", "", "", "", ""
// 30 .. 39
, "", "", "space", "", "", "", "", "", "", "apostrophe"
// 40 .. 49
, "", "", "", "", "comma", "minus", "period", "slash", "0", "1"
// 50 .. 59
, "2", "3", "4", "5", "6", "7", "8", "9", "semicolon"
// 60 .. 69
, "", "equal", "a", "b", "c", "d", "e"
// 70 .. 79
, "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"
// 80 .. 89
, "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"
// 90 .. 99
, "z", "left-bracket", "backslash", "right-bracket", "", "", "grave-accent", "", "", ""
// 100 .. 109
, "", "", "", "", "", "", "", "", "", ""
// 110 .. 119
, "", "", "", "", "", "", "", "", "", ""
// 120 .. 129
, "", "", "", "", "", "", "", "", "", ""
// 130 .. 139
, "", "", "", "", "", "", "", "", "", ""
// 140 .. 149
, "", "", "", "", "", "", "", "", "", ""
// 150 .. 159
, "", "", "", "", "", "", "", "", "", ""
// 160 .. 169
, "", "world-1", "world-2", "", "", "", "", "", "", ""
// 170 .. 179
, "", "", "", "", "", "", "", "", "", ""
// 180 .. 189
, "", "", "", "", "", "", "", "", "", ""
// 190 .. 199
, "", "", "", "", "", "", "", "", "", ""
// 200 .. 209
, "", "", "", "", "", "", "", "", "", ""
// 210 .. 219
, "", "", "", "", "", "", "", "", "", ""
// 220 .. 229
, "", "", "", "", "", "", "", "", "", ""
// 230 .. 239
, "", "", "", "", "", "", "", "", "", ""
// 240 .. 249
, "", "", "", "", "", "", "", "", "", ""
// 250 .. 259
, "", "", "", "", "", "", "escape", "enter", "tab", "backspace"
// 260 .. 269
, "insert", "delete", "right", "left", "down", "up", "page-up", "page-down", "home", "end"
// 270 .. 279
, "", "", "", "", "", "", "", "", "", ""
// 280 .. 289
, "caps-lock", "scroll-lock", "num-lock", "print-screen", "pause"
// 290 .. 299
, "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10"
// 300 .. 309
, "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20"
// 310 .. 319
, "f21", "f22", "f23", "f24", "f25", "", "", "", "", ""
// 320 .. 329
, "keypad-0", "keypad-1", "keypad-2", "keypad-3", "keypad-4", "keypad-5", "keypad-6", "keypad-7", "keypad-8", "keypad-9"
// 330 .. 339
, "keypad-decimal", "keypad-devide", "keypad-multiply", "keypad-subtract", "keypad-add", "keypad-enter", "keypad-equal", "", "", ""
// 340 .. 348 ** Note: 349 is not available! **
, "left-shift", "left-control", "left-alternate", "left-super", "right-shift", "right-control", "right-alternate", "right-super", "menu"
};
}<commit_msg>fix glfw3_key_names table<commit_after>#pragma once
namespace usagi::keyboard::glfw3
{
const int glfw3_available_keys[] =
{ 32, 39
, 44, 45, 46, 47, 48, 49
, 50, 51, 52, 53, 54, 55, 56, 57, 59
, 61, 65, 66, 67, 68, 69
, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79
, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89
, 90, 91, 92, 93, 96
, 161, 162
, 256, 257, 258, 259
, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269
, 280, 281, 282, 283, 284
, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299
, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309
, 310, 311, 312, 313, 314
, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329
, 330, 331, 332, 333, 334, 335, 336
, 340, 341, 342, 343, 344, 345, 346, 347, 348
};
const char* glfw3_key_names[] =
// 0 .. 9
{ "", "", "", "", "", "", "", "", "", ""
// 10 .. 19
, "", "", "", "", "", "", "", "", "", ""
// 20 .. 29
, "", "", "", "", "", "", "", "", "", ""
// 30 .. 39
, "", "", "space", "", "", "", "", "", "", "apostrophe"
// 40 .. 49
, "", "", "", "", "comma", "minus", "period", "slash", "0", "1"
// 50 .. 59
, "2", "3", "4", "5", "6", "7", "8", "9", "", "semicolon"
// 60 .. 69
, "", "equal", "", "", "", "a", "b", "c", "d", "e"
// 70 .. 79
, "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"
// 80 .. 89
, "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"
// 90 .. 99
, "z", "left-bracket", "backslash", "right-bracket", "", "", "grave-accent", "", "", ""
// 100 .. 109
, "", "", "", "", "", "", "", "", "", ""
// 110 .. 119
, "", "", "", "", "", "", "", "", "", ""
// 120 .. 129
, "", "", "", "", "", "", "", "", "", ""
// 130 .. 139
, "", "", "", "", "", "", "", "", "", ""
// 140 .. 149
, "", "", "", "", "", "", "", "", "", ""
// 150 .. 159
, "", "", "", "", "", "", "", "", "", ""
// 160 .. 169
, "", "world-1", "world-2", "", "", "", "", "", "", ""
// 170 .. 179
, "", "", "", "", "", "", "", "", "", ""
// 180 .. 189
, "", "", "", "", "", "", "", "", "", ""
// 190 .. 199
, "", "", "", "", "", "", "", "", "", ""
// 200 .. 209
, "", "", "", "", "", "", "", "", "", ""
// 210 .. 219
, "", "", "", "", "", "", "", "", "", ""
// 220 .. 229
, "", "", "", "", "", "", "", "", "", ""
// 230 .. 239
, "", "", "", "", "", "", "", "", "", ""
// 240 .. 249
, "", "", "", "", "", "", "", "", "", ""
// 250 .. 259
, "", "", "", "", "", "", "escape", "enter", "tab", "backspace"
// 260 .. 269
, "insert", "delete", "right", "left", "down", "up", "page-up", "page-down", "home", "end"
// 270 .. 279
, "", "", "", "", "", "", "", "", "", ""
// 280 .. 289
, "caps-lock", "scroll-lock", "num-lock", "print-screen", "pause", "", "", "", "", ""
// 290 .. 299
, "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10"
// 300 .. 309
, "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20"
// 310 .. 319
, "f21", "f22", "f23", "f24", "f25", "", "", "", "", ""
// 320 .. 329
, "keypad-0", "keypad-1", "keypad-2", "keypad-3", "keypad-4", "keypad-5", "keypad-6", "keypad-7", "keypad-8", "keypad-9"
// 330 .. 339
, "keypad-decimal", "keypad-devide", "keypad-multiply", "keypad-subtract", "keypad-add", "keypad-enter", "keypad-equal", "", "", ""
// 340 .. 348 ** Note: 349 is not available! **
, "left-shift", "left-control", "left-alternate", "left-super", "right-shift", "right-control", "right-alternate", "right-super", "menu"
};
}<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "../fileinputstream.h"
#include "../stringstream.h"
#include "../stringterminatedsubstream.h"
#include "inputstreamtests.h"
#include <iostream>
using namespace std;
using namespace Strigi;
int
StringTerminatedSubStreamTest(int, char*[]) {
founderrors = 0;
StringInputStream sr("abc");
StringTerminatedSubStream sub(&sr, "b");
const char* start;
int64_t nread = sub.read(start, 10, 10);
cout << "read " << nread << endl;
/*
for (int i=0; i<ninputstreamtests; ++i) {
FileInputStream file("a.zip");
StringTerminatedSubStream sub(&file, "THEEND");
charinputstreamtests[i](&sub);
}*/
return founderrors;
}
<commit_msg>Reenable full unit test on stringterminatedsubstream.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "../fileinputstream.h"
#include "../stringstream.h"
#include "../stringterminatedsubstream.h"
#include "inputstreamtests.h"
#include <iostream>
using namespace std;
using namespace Strigi;
int
StringTerminatedSubStreamTest(int, char*[]) {
founderrors = 0;
StringInputStream sr("abc");
StringTerminatedSubStream sub(&sr, "b");
const char* start;
int64_t nread = sub.read(start, 10, 10);
cout << "read " << nread << endl;
for (int i=0; i<ninputstreamtests; ++i) {
FileInputStream file("a.zip");
StringTerminatedSubStream sub(&file, "THEEND");
charinputstreamtests[i](&sub);
}
return founderrors;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
return 0;
}
<commit_msg>Updated cpp template<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main(int argc, char* argv[])
{
return 0;
}
<|endoftext|>
|
<commit_before>#include "search_index_builder.hpp"
#include "feature_utils.hpp"
#include "features_vector.hpp"
#include "search_delimiters.hpp"
#include "search_trie.hpp"
#include "search_string_utils.hpp"
#include "string_file.hpp"
#include "../defines.hpp"
#include "../platform/platform.hpp"
#include "../coding/trie_builder.hpp"
#include "../coding/writer.hpp"
#include "../coding/reader_writer_ops.hpp"
#include "../base/string_utils.hpp"
#include "../base/logging.hpp"
#include "../std/algorithm.hpp"
#include "../std/vector.hpp"
namespace
{
struct FeatureNameInserter
{
StringsFile & m_names;
StringsFile::ValueT m_val;
FeatureNameInserter(StringsFile & names) : m_names(names) {}
void AddToken(signed char lang, strings::UniString const & s) const
{
m_names.AddString(StringsFile::StringT(s, lang, m_val));
}
bool operator()(signed char lang, string const & name) const
{
strings::UniString const uniName = search::NormalizeAndSimplifyString(name);
buffer_vector<strings::UniString, 32> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
if (tokens.size() > 30)
{
LOG(LWARNING, ("Name has too many tokens:", name));
tokens.resize(30);
}
for (size_t i = 0; i < tokens.size(); ++i)
AddToken(lang, tokens[i]);
return true;
}
};
class FeatureInserter
{
StringsFile & m_names;
typedef StringsFile::ValueT ValueT;
typedef search::trie::ValueReader SaverT;
SaverT m_valueSaver;
void MakeValue(FeatureType const & f, feature::TypesHolder const & types,
uint64_t pos, ValueT & value) const
{
SaverT::ValueType v;
v.m_featureId = static_cast<uint32_t>(pos);
// get BEST geometry rect of feature
m2::RectD const rect = f.GetLimitRect(-1);
v.m_pt = rect.Center();
v.m_rank = feature::GetSearchRank(types, v.m_pt, f.GetPopulation());
// write to buffer
PushBackByteSink<ValueT> sink(value);
m_valueSaver.Save(sink, v);
}
public:
FeatureInserter(StringsFile & names, serial::CodingParams const & cp)
: m_names(names), m_valueSaver(cp)
{
}
void operator() (FeatureType const & f, uint64_t pos) const
{
feature::TypesHolder types(f);
// init inserter with serialized value
FeatureNameInserter inserter(m_names);
MakeValue(f, types, pos, inserter.m_val);
// add names of the feature
f.ForEachNameRef(inserter);
// add names of categories of the feature
for (size_t i = 0; i < types.Size(); ++i)
inserter.AddToken(search::CATEGORIES_LANG, search::FeatureTypeToString(types[i]));
}
};
} // unnamed namespace
void indexer::BuildSearchIndex(FeaturesVector const & featuresVector, Writer & writer,
string const & tmpFilePath)
{
{
StringsFile names(tmpFilePath);
serial::CodingParams cp(search::POINT_CODING_BITS,
featuresVector.GetCodingParams().GetBasePointUint64());
featuresVector.ForEachOffset(FeatureInserter(names, cp));
names.EndAdding();
names.OpenForRead();
trie::Build(writer, names.Begin(), names.End(), trie::builder::EmptyEdgeBuilder());
// at this point all readers of StringsFile should be dead
}
FileWriter::DeleteFileX(tmpFilePath);
}
bool indexer::BuildSearchIndexFromDatFile(string const & fName)
{
LOG(LINFO, ("Start building search index ..."));
try
{
Platform & pl = GetPlatform();
string const datFile = pl.WritablePathForFile(fName);
string const tmpFile = pl.WritablePathForFile(fName + ".search_index_2.tmp");
{
FilesContainerR readCont(datFile);
feature::DataHeader header;
header.Load(readCont.GetReader(HEADER_FILE_TAG));
FeaturesVector featuresVector(readCont, header);
FileWriter writer(tmpFile);
BuildSearchIndex(featuresVector, writer, pl.WritablePathForFile(fName + ".search_index_1.tmp"));
}
{
// Write to container in reversed order.
FilesContainerW writeCont(datFile, FileWriter::OP_WRITE_EXISTING);
FileWriter writer = writeCont.GetWriter(SEARCH_INDEX_FILE_TAG);
rw_ops::Reverse(FileReader(tmpFile), writer);
}
FileWriter::DeleteFileX(tmpFile);
}
catch (Reader::Exception const & e)
{
LOG(LERROR, ("Error while reading file: ", e.what()));
return false;
}
catch (Writer::Exception const & e)
{
LOG(LERROR, ("Error writing index file: ", e.what()));
return false;
}
LOG(LINFO, ("End building search index."));
return true;
}
<commit_msg>[search] Skip features without names, that has place-city (town, region) types, in suggestion trie generation.<commit_after>#include "search_index_builder.hpp"
#include "feature_utils.hpp"
#include "features_vector.hpp"
#include "search_delimiters.hpp"
#include "search_trie.hpp"
#include "search_string_utils.hpp"
#include "string_file.hpp"
#include "classificator.hpp"
#include "../defines.hpp"
#include "../platform/platform.hpp"
#include "../coding/trie_builder.hpp"
#include "../coding/writer.hpp"
#include "../coding/reader_writer_ops.hpp"
#include "../base/string_utils.hpp"
#include "../base/logging.hpp"
#include "../std/algorithm.hpp"
#include "../std/vector.hpp"
namespace
{
struct FeatureNameInserter
{
StringsFile & m_names;
StringsFile::ValueT m_val;
FeatureNameInserter(StringsFile & names) : m_names(names) {}
void AddToken(signed char lang, strings::UniString const & s) const
{
m_names.AddString(StringsFile::StringT(s, lang, m_val));
}
bool operator()(signed char lang, string const & name) const
{
strings::UniString const uniName = search::NormalizeAndSimplifyString(name);
buffer_vector<strings::UniString, 32> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
/// @todo MAX_TOKENS = 32, in Query::Search we use 31 + prefix. Why 30 ???
if (tokens.size() > 30)
{
LOG(LWARNING, ("Name has too many tokens:", name));
tokens.resize(30);
}
for (size_t i = 0; i < tokens.size(); ++i)
AddToken(lang, tokens[i]);
return true;
}
};
class FeatureInserter
{
StringsFile & m_names;
typedef StringsFile::ValueT ValueT;
typedef search::trie::ValueReader SaverT;
SaverT m_valueSaver;
void MakeValue(FeatureType const & f, feature::TypesHolder const & types,
uint64_t pos, ValueT & value) const
{
SaverT::ValueType v;
v.m_featureId = static_cast<uint32_t>(pos);
// get BEST geometry rect of feature
m2::RectD const rect = f.GetLimitRect(-1);
v.m_pt = rect.Center();
v.m_rank = feature::GetSearchRank(types, v.m_pt, f.GetPopulation());
// write to buffer
PushBackByteSink<ValueT> sink(value);
m_valueSaver.Save(sink, v);
}
class AvoidEmptyName
{
vector<uint32_t> m_vec;
public:
AvoidEmptyName()
{
char const * arr[][3] = {
{ "place", "city", ""},
{ "place", "city", "capital"},
{ "place", "town", ""},
{ "place", "county", ""},
{ "place", "state", ""},
{ "place", "region", ""}
};
Classificator const & c = classif();
size_t const count = ARRAY_SIZE(arr);
m_vec.reserve(count);
for (size_t i = 0; i < count; ++i)
{
vector<string> v;
v.push_back(arr[i][0]);
v.push_back(arr[i][1]);
if (strlen(arr[i][2]) > 0)
v.push_back(arr[i][2]);
m_vec.push_back(c.GetTypeByPath(v));
}
}
bool IsExist(feature::TypesHolder const & types) const
{
for (size_t i = 0; i < m_vec.size(); ++i)
if (types.Has(m_vec[i]))
return true;
return false;
}
};
public:
FeatureInserter(StringsFile & names, serial::CodingParams const & cp)
: m_names(names), m_valueSaver(cp)
{
}
void operator() (FeatureType const & f, uint64_t pos) const
{
feature::TypesHolder types(f);
// init inserter with serialized value
FeatureNameInserter inserter(m_names);
MakeValue(f, types, pos, inserter.m_val);
// add names of the feature
if (!f.ForEachNameRef(inserter))
{
static AvoidEmptyName check;
if (check.IsExist(types))
{
// Do not add such features without names to suggestion list.
return;
}
}
// add names of categories of the feature
for (size_t i = 0; i < types.Size(); ++i)
inserter.AddToken(search::CATEGORIES_LANG, search::FeatureTypeToString(types[i]));
}
};
} // unnamed namespace
void indexer::BuildSearchIndex(FeaturesVector const & featuresVector, Writer & writer,
string const & tmpFilePath)
{
{
StringsFile names(tmpFilePath);
serial::CodingParams cp(search::POINT_CODING_BITS,
featuresVector.GetCodingParams().GetBasePointUint64());
featuresVector.ForEachOffset(FeatureInserter(names, cp));
names.EndAdding();
names.OpenForRead();
trie::Build(writer, names.Begin(), names.End(), trie::builder::EmptyEdgeBuilder());
// at this point all readers of StringsFile should be dead
}
FileWriter::DeleteFileX(tmpFilePath);
}
bool indexer::BuildSearchIndexFromDatFile(string const & fName)
{
LOG(LINFO, ("Start building search index ..."));
try
{
Platform & pl = GetPlatform();
string const datFile = pl.WritablePathForFile(fName);
string const tmpFile = pl.WritablePathForFile(fName + ".search_index_2.tmp");
{
FilesContainerR readCont(datFile);
feature::DataHeader header;
header.Load(readCont.GetReader(HEADER_FILE_TAG));
FeaturesVector featuresVector(readCont, header);
FileWriter writer(tmpFile);
BuildSearchIndex(featuresVector, writer, pl.WritablePathForFile(fName + ".search_index_1.tmp"));
}
{
// Write to container in reversed order.
FilesContainerW writeCont(datFile, FileWriter::OP_WRITE_EXISTING);
FileWriter writer = writeCont.GetWriter(SEARCH_INDEX_FILE_TAG);
rw_ops::Reverse(FileReader(tmpFile), writer);
}
FileWriter::DeleteFileX(tmpFile);
}
catch (Reader::Exception const & e)
{
LOG(LERROR, ("Error while reading file: ", e.what()));
return false;
}
catch (Writer::Exception const & e)
{
LOG(LERROR, ("Error writing index file: ", e.what()));
return false;
}
LOG(LINFO, ("End building search index."));
return true;
}
<|endoftext|>
|
<commit_before>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#if HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/logging.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
/**
* \brief adds another Dune::ParameterTree
*/
void add(const Dune::ParameterTree& _other, const std::string _subName = "")
{
if (_subName.empty()) {
// copy each key/value pair and append subName
const Dune::ParameterTree::KeyVector& keyVector = _other.getValueKeys();
for (size_t ii = 0; ii < keyVector.size(); ++ii) {
const std::string key = keyVector[ii];
if (BaseType::hasKey(key))
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << key << "' already exists in the follingDune::ParameterTree:\n"
<< reportString(" "));
BaseType::operator[](key) = _other.get< std::string >(key);
}
} else {
if (BaseType::hasKey(_subName))
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _subName << "' already exists in the follingDune::ParameterTree:\n"
<< reportString(" "));
else if (BaseType::hasSub(_subName)) {
ExtendedParameterTree _sub = BaseType::sub(_subName);
_sub.add(_other);
BaseType::sub(_subName) = _sub;
} else
BaseType::sub(_subName) = _other;
}
} // ... add(...)
ExtendedParameterTree sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ExtendedParameterTree(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const char* defaultValue) const
{
return this->get< std::string >(_key, std::string(defaultValue));
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key)) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
}
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
return (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"));
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
Dune::DynamicVector< T > getDynVector(const std::string& _key, const T& def, const size_t minSize) const
{
const std::vector< T > vector = getVector< T >(_key, def, minSize);
Dune::DynamicVector< T > ret(vector.size());
for (size_t ii = 0; ii < vector.size(); ++ii)
ret[ii] = vector[ii];
return ret;
}
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize) const
{
if (!hasKey(_key)) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return std::vector< T >(minSize, def);
} else {
const std::string str = BaseType::get(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str, "")) {
if (minSize > 0) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (0) and has been enlarged to size " << minSize << "!" << std::endl;
}
return std::vector< T >(minSize, def);
} else if (str.size() < 3) {
std::vector< T > ret;
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
if (ret.size() < minSize) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (" << ret.size() << ") and has been enlarged to size " << minSize << "!" << std::endl;
for (auto i = ret.size(); i < minSize; ++i)
ret.push_back(def);
}
return ret;
} else {
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
std::vector< T > ret;
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
std::vector< std::string > tokens;
if (str.size() > 2)
tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (auto i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
Dune::DynamicVector< T > getDynVector(const std::string& _key, const size_t minSize) const
{
const std::vector< T > vector = getVector< T >(_key, minSize);
Dune::DynamicVector< T > ret(vector.size());
for (size_t ii = 0; ii < vector.size(); ++ii)
ret[ii] = vector[ii];
return ret;
}
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int minSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else if (minSize == 1)
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() < minSize)
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " vector '" << _key
<< "' too short (is " << ret.size() << ", should be at least " << minSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
#if HAVE_EIGEN
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key,
const T& def,
const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, def, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key, const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
#endif // HAVE_EIGEN
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\return The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ExtendedParameterTree
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<commit_msg>[common.parameter.tree] added init(filename)<commit_after>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#if HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/common/dynvector.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/logging.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(const std::string filename)
: BaseType(init(filename))
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
/**
* \brief adds another Dune::ParameterTree
*/
void add(const Dune::ParameterTree& _other, const std::string _subName = "")
{
if (_subName.empty()) {
// copy each key/value pair and append subName
const Dune::ParameterTree::KeyVector& keyVector = _other.getValueKeys();
for (size_t ii = 0; ii < keyVector.size(); ++ii) {
const std::string key = keyVector[ii];
if (BaseType::hasKey(key))
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << key << "' already exists in the follingDune::ParameterTree:\n"
<< reportString(" "));
BaseType::operator[](key) = _other.get< std::string >(key);
}
} else {
if (BaseType::hasKey(_subName))
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _subName << "' already exists in the follingDune::ParameterTree:\n"
<< reportString(" "));
else if (BaseType::hasSub(_subName)) {
ExtendedParameterTree _sub = BaseType::sub(_subName);
_sub.add(_other);
BaseType::sub(_subName) = _sub;
} else
BaseType::sub(_subName) = _other;
}
} // ... add(...)
ExtendedParameterTree sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ExtendedParameterTree(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const char* defaultValue) const
{
return this->get< std::string >(_key, std::string(defaultValue));
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key)) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
}
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
return (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"));
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
Dune::DynamicVector< T > getDynVector(const std::string& _key, const T& def, const size_t minSize) const
{
const std::vector< T > vector = getVector< T >(_key, def, minSize);
Dune::DynamicVector< T > ret(vector.size());
for (size_t ii = 0; ii < vector.size(); ++ii)
ret[ii] = vector[ii];
return ret;
}
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize) const
{
if (!hasKey(_key)) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return std::vector< T >(minSize, def);
} else {
const std::string str = BaseType::get(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str, "")) {
if (minSize > 0) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (0) and has been enlarged to size " << minSize << "!" << std::endl;
}
return std::vector< T >(minSize, def);
} else if (str.size() < 3) {
std::vector< T > ret;
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
if (ret.size() < minSize) {
Dune::Stuff::Common::Logger().debug() << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (" << ret.size() << ") and has been enlarged to size " << minSize << "!" << std::endl;
for (auto i = ret.size(); i < minSize; ++i)
ret.push_back(def);
}
return ret;
} else {
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
std::vector< T > ret;
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
std::vector< std::string > tokens;
if (str.size() > 2)
tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (auto i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
Dune::DynamicVector< T > getDynVector(const std::string& _key, const size_t minSize) const
{
const std::vector< T > vector = getVector< T >(_key, minSize);
Dune::DynamicVector< T > ret(vector.size());
for (size_t ii = 0; ii < vector.size(); ++ii)
ret[ii] = vector[ii];
return ret;
}
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int minSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else if (minSize == 1)
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() < minSize)
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " vector '" << _key
<< "' too short (is " << ret.size() << ", should be at least " << minSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
#if HAVE_EIGEN
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key,
const T& def,
const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, def, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key, const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
#endif // HAVE_EIGEN
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\return The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
static ParameterTree init(const std::string filename)
{
Dune::ParameterTree paramTree;
Dune::ParameterTreeParser::readINITree(filename, paramTree);
return paramTree;
} // static ExtendedParameterTree init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ExtendedParameterTree
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<|endoftext|>
|
<commit_before>/*==========================================================================
Portions (c) Copyright 2008-2009 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $HeadURL: http://svn.slicer.org/Slicer4/trunk/Modules/OpenIGTLinkIF/vtkSlicerOpenIGTLinkIFLogic.cxx $
Date: $Date: 2011-06-12 14:55:20 -0400 (Sun, 12 Jun 2011) $
Version: $Revision: 16985 $
==========================================================================*/
#include <algorithm>
// IGTLIO includes
#include "igtlioLogic.h"
#include "igtlioConnector.h"
#include "igtlioSession.h"
#include <vtkObjectFactory.h>
// OpenIGTLinkIF Logic includes
#include <vtkNew.h>
#include <vtkCallbackCommand.h>
#include <vtkImageData.h>
#include <vtkTransform.h>
namespace igtlio
{
//---------------------------------------------------------------------------
void onNewDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
logic->InvokeEvent(Logic::NewDeviceEvent, calldata);
Device* device = reinterpret_cast<Device*>(calldata);
device->AddObserver(Device::CommandReceivedEvent, logic->DeviceEventCallback);
device->AddObserver(Device::CommandResponseReceivedEvent, logic->DeviceEventCallback);
}
//---------------------------------------------------------------------------
void onRemovedDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
logic->InvokeEvent(Logic::RemovedDeviceEvent, calldata);
Device* device = reinterpret_cast<Device*>(calldata);
device->RemoveObserver(logic->DeviceEventCallback);
}
//---------------------------------------------------------------------------
void onDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
if ((eid==Device::CommandReceivedEvent) ||
(eid==Connector::DeviceContentModifiedEvent) ||
(eid==Device::CommandResponseReceivedEvent))
{
logic->InvokeEvent(eid, calldata);
}
}
//---------------------------------------------------------------------------
vtkStandardNewMacro(Logic);
//---------------------------------------------------------------------------
Logic::Logic()
{
NewDeviceCallback = vtkSmartPointer<vtkCallbackCommand>::New();
NewDeviceCallback->SetCallback(onNewDeviceEventFunc);
NewDeviceCallback->SetClientData(this);
RemovedDeviceCallback = vtkSmartPointer<vtkCallbackCommand>::New();
RemovedDeviceCallback->SetCallback(onRemovedDeviceEventFunc);
RemovedDeviceCallback->SetClientData(this);
DeviceEventCallback = vtkSmartPointer<vtkCallbackCommand>::New();
DeviceEventCallback->SetCallback(onDeviceEventFunc);
DeviceEventCallback->SetClientData(this);
}
//---------------------------------------------------------------------------
Logic::~Logic()
{
}
//---------------------------------------------------------------------------
void Logic::PrintSelf(ostream& os, vtkIndent indent)
{
os << indent << "vtkIGTLIOLogic: " << this->GetClassName() << "\n";
}
//---------------------------------------------------------------------------
ConnectorPointer Logic::CreateConnector()
{
ConnectorPointer connector = ConnectorPointer::New();
connector->SetUID(this->CreateUniqueConnectorID());
std::stringstream ss;
ss << "IGTLConnector_" << connector->GetUID();
connector->SetName(ss.str());
Connectors.push_back(connector);
connector->AddObserver(Connector::NewDeviceEvent, NewDeviceCallback);
connector->AddObserver(Connector::DeviceContentModifiedEvent, DeviceEventCallback);
connector->AddObserver(Connector::RemovedDeviceEvent, RemovedDeviceCallback);
this->InvokeEvent(ConnectionAddedEvent, connector.GetPointer());
return connector;
}
//---------------------------------------------------------------------------
int Logic::CreateUniqueConnectorID() const
{
int retval=0;
for (unsigned int i=0; i<Connectors.size(); ++i)
{
retval = std::max<int>(retval, Connectors[i]->GetUID()+1);
}
return retval;
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(unsigned int index)
{
std::vector<ConnectorPointer>::iterator toRemove = Connectors.begin()+index;
return this->RemoveConnector(toRemove);
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(ConnectorPointer connector)
{
std::vector<ConnectorPointer>::iterator toRemove = Connectors.begin();
for(; toRemove != Connectors.end(); ++toRemove)
{
if(connector == (*toRemove))
break;
}
return this->RemoveConnector(toRemove);
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(std::vector<ConnectorPointer>::iterator toRemove)
{
toRemove->GetPointer()->RemoveObserver(NewDeviceCallback);
toRemove->GetPointer()->RemoveObserver(RemovedDeviceCallback);
this->InvokeEvent(ConnectionAboutToBeRemovedEvent, toRemove->GetPointer());
Connectors.erase(toRemove);
return 0;
}
//---------------------------------------------------------------------------
int Logic::GetNumberOfConnectors() const
{
return Connectors.size();
}
//---------------------------------------------------------------------------
ConnectorPointer Logic::GetConnector(unsigned int index)
{
if (index<Connectors.size())
return Connectors[index];
vtkErrorMacro("index " << index << " out of bounds.");
return NULL;
}
SessionPointer Logic::StartServer(int serverPort, igtlio::SYNCHRONIZATION_TYPE sync, double timeout_s)
{
SessionPointer session = SessionPointer::New();
session->SetConnector(this->CreateConnector());
session->StartServer(serverPort, sync, timeout_s);
return session;
}
SessionPointer Logic::ConnectToServer(std::string serverHost, int serverPort, igtlio::SYNCHRONIZATION_TYPE sync, double timeout_s)
{
SessionPointer session = SessionPointer::New();
session->SetConnector(this->CreateConnector());
session->ConnectToServer(serverHost, serverPort, sync, timeout_s);
return session;
}
//---------------------------------------------------------------------------
void Logic::PeriodicProcess()
{
for (unsigned i=0; i<Connectors.size(); ++i)
{
Connectors[i]->PeriodicProcess();
}
}
//---------------------------------------------------------------------------
unsigned int Logic::GetNumberOfDevices() const
{
std::vector<DevicePointer> all = this->CreateDeviceList();
return all.size();
}
//---------------------------------------------------------------------------
void Logic::RemoveDevice(unsigned int index)
{
DevicePointer device = this->GetDevice(index);
for (unsigned i=0; i<Connectors.size(); ++i)
{
for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j)
{
DevicePointer local = Connectors[i]->GetDevice(j);
if (device==local)
Connectors[i]->RemoveDevice(j);
}
}
}
//---------------------------------------------------------------------------
DevicePointer Logic::GetDevice(unsigned int index)
{
// TODO: optimize by caching the vector if necessary
std::vector<DevicePointer> all = this->CreateDeviceList();
if (index<all.size())
return all[index];
vtkErrorMacro("index " << index << " out of bounds.");
return NULL;
}
//---------------------------------------------------------------------------
int Logic::ConnectorIndexFromDevice( DevicePointer d )
{
for( std::vector<ConnectorPointer>::size_type i = 0; i < Connectors.size(); ++i )
if( Connectors[i]->HasDevice(d) )
return i;
return -1;
}
//---------------------------------------------------------------------------
std::vector<DevicePointer> Logic::CreateDeviceList() const
{
std::set<DevicePointer> all;
for (unsigned i=0; i<Connectors.size(); ++i)
{
for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j)
{
all.insert(Connectors[i]->GetDevice(j));
}
}
return std::vector<DevicePointer>(all.begin(), all.end());
}
} // namespace igtlio
<commit_msg>Let Logic::RemoveConnector handle connectors not in the vector. Returns 1 if connector was removed, 0 otherwise.<commit_after>/*==========================================================================
Portions (c) Copyright 2008-2009 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $HeadURL: http://svn.slicer.org/Slicer4/trunk/Modules/OpenIGTLinkIF/vtkSlicerOpenIGTLinkIFLogic.cxx $
Date: $Date: 2011-06-12 14:55:20 -0400 (Sun, 12 Jun 2011) $
Version: $Revision: 16985 $
==========================================================================*/
#include <algorithm>
// IGTLIO includes
#include "igtlioLogic.h"
#include "igtlioConnector.h"
#include "igtlioSession.h"
#include <vtkObjectFactory.h>
// OpenIGTLinkIF Logic includes
#include <vtkNew.h>
#include <vtkCallbackCommand.h>
#include <vtkImageData.h>
#include <vtkTransform.h>
namespace igtlio
{
//---------------------------------------------------------------------------
void onNewDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
logic->InvokeEvent(Logic::NewDeviceEvent, calldata);
Device* device = reinterpret_cast<Device*>(calldata);
device->AddObserver(Device::CommandReceivedEvent, logic->DeviceEventCallback);
device->AddObserver(Device::CommandResponseReceivedEvent, logic->DeviceEventCallback);
}
//---------------------------------------------------------------------------
void onRemovedDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
logic->InvokeEvent(Logic::RemovedDeviceEvent, calldata);
Device* device = reinterpret_cast<Device*>(calldata);
device->RemoveObserver(logic->DeviceEventCallback);
}
//---------------------------------------------------------------------------
void onDeviceEventFunc(vtkObject* caller, unsigned long eid, void* clientdata, void *calldata)
{
Logic* logic = reinterpret_cast<Logic*>(clientdata);
if ((eid==Device::CommandReceivedEvent) ||
(eid==Connector::DeviceContentModifiedEvent) ||
(eid==Device::CommandResponseReceivedEvent))
{
logic->InvokeEvent(eid, calldata);
}
}
//---------------------------------------------------------------------------
vtkStandardNewMacro(Logic);
//---------------------------------------------------------------------------
Logic::Logic()
{
NewDeviceCallback = vtkSmartPointer<vtkCallbackCommand>::New();
NewDeviceCallback->SetCallback(onNewDeviceEventFunc);
NewDeviceCallback->SetClientData(this);
RemovedDeviceCallback = vtkSmartPointer<vtkCallbackCommand>::New();
RemovedDeviceCallback->SetCallback(onRemovedDeviceEventFunc);
RemovedDeviceCallback->SetClientData(this);
DeviceEventCallback = vtkSmartPointer<vtkCallbackCommand>::New();
DeviceEventCallback->SetCallback(onDeviceEventFunc);
DeviceEventCallback->SetClientData(this);
}
//---------------------------------------------------------------------------
Logic::~Logic()
{
}
//---------------------------------------------------------------------------
void Logic::PrintSelf(ostream& os, vtkIndent indent)
{
os << indent << "vtkIGTLIOLogic: " << this->GetClassName() << "\n";
}
//---------------------------------------------------------------------------
ConnectorPointer Logic::CreateConnector()
{
ConnectorPointer connector = ConnectorPointer::New();
connector->SetUID(this->CreateUniqueConnectorID());
std::stringstream ss;
ss << "IGTLConnector_" << connector->GetUID();
connector->SetName(ss.str());
Connectors.push_back(connector);
connector->AddObserver(Connector::NewDeviceEvent, NewDeviceCallback);
connector->AddObserver(Connector::DeviceContentModifiedEvent, DeviceEventCallback);
connector->AddObserver(Connector::RemovedDeviceEvent, RemovedDeviceCallback);
this->InvokeEvent(ConnectionAddedEvent, connector.GetPointer());
return connector;
}
//---------------------------------------------------------------------------
int Logic::CreateUniqueConnectorID() const
{
int retval=0;
for (unsigned int i=0; i<Connectors.size(); ++i)
{
retval = std::max<int>(retval, Connectors[i]->GetUID()+1);
}
return retval;
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(unsigned int index)
{
std::vector<ConnectorPointer>::iterator toRemove = Connectors.begin()+index;
return this->RemoveConnector(toRemove);
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(ConnectorPointer connector)
{
std::vector<ConnectorPointer>::iterator toRemove = Connectors.begin();
for(; toRemove != Connectors.end(); ++toRemove)
{
if(connector == (*toRemove))
break;
}
return this->RemoveConnector(toRemove);
}
//---------------------------------------------------------------------------
int Logic::RemoveConnector(std::vector<ConnectorPointer>::iterator toRemove)
{
if(toRemove == Connectors.end())
return 0;
toRemove->GetPointer()->RemoveObserver(NewDeviceCallback);
toRemove->GetPointer()->RemoveObserver(RemovedDeviceCallback);
this->InvokeEvent(ConnectionAboutToBeRemovedEvent, toRemove->GetPointer());
Connectors.erase(toRemove);
return 1;
}
//---------------------------------------------------------------------------
int Logic::GetNumberOfConnectors() const
{
return Connectors.size();
}
//---------------------------------------------------------------------------
ConnectorPointer Logic::GetConnector(unsigned int index)
{
if (index<Connectors.size())
return Connectors[index];
vtkErrorMacro("index " << index << " out of bounds.");
return NULL;
}
SessionPointer Logic::StartServer(int serverPort, igtlio::SYNCHRONIZATION_TYPE sync, double timeout_s)
{
SessionPointer session = SessionPointer::New();
session->SetConnector(this->CreateConnector());
session->StartServer(serverPort, sync, timeout_s);
return session;
}
SessionPointer Logic::ConnectToServer(std::string serverHost, int serverPort, igtlio::SYNCHRONIZATION_TYPE sync, double timeout_s)
{
SessionPointer session = SessionPointer::New();
session->SetConnector(this->CreateConnector());
session->ConnectToServer(serverHost, serverPort, sync, timeout_s);
return session;
}
//---------------------------------------------------------------------------
void Logic::PeriodicProcess()
{
for (unsigned i=0; i<Connectors.size(); ++i)
{
Connectors[i]->PeriodicProcess();
}
}
//---------------------------------------------------------------------------
unsigned int Logic::GetNumberOfDevices() const
{
std::vector<DevicePointer> all = this->CreateDeviceList();
return all.size();
}
//---------------------------------------------------------------------------
void Logic::RemoveDevice(unsigned int index)
{
DevicePointer device = this->GetDevice(index);
for (unsigned i=0; i<Connectors.size(); ++i)
{
for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j)
{
DevicePointer local = Connectors[i]->GetDevice(j);
if (device==local)
Connectors[i]->RemoveDevice(j);
}
}
}
//---------------------------------------------------------------------------
DevicePointer Logic::GetDevice(unsigned int index)
{
// TODO: optimize by caching the vector if necessary
std::vector<DevicePointer> all = this->CreateDeviceList();
if (index<all.size())
return all[index];
vtkErrorMacro("index " << index << " out of bounds.");
return NULL;
}
//---------------------------------------------------------------------------
int Logic::ConnectorIndexFromDevice( DevicePointer d )
{
for( std::vector<ConnectorPointer>::size_type i = 0; i < Connectors.size(); ++i )
if( Connectors[i]->HasDevice(d) )
return i;
return -1;
}
//---------------------------------------------------------------------------
std::vector<DevicePointer> Logic::CreateDeviceList() const
{
std::set<DevicePointer> all;
for (unsigned i=0; i<Connectors.size(); ++i)
{
for (unsigned j=0; j<Connectors[i]->GetNumberOfDevices(); ++j)
{
all.insert(Connectors[i]->GetDevice(j));
}
}
return std::vector<DevicePointer>(all.begin(), all.end());
}
} // namespace igtlio
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// FILE: FastLogger.cpp
// PROJECT: Micro-Manager
// SUBSYSTEM: MMCore
//-----------------------------------------------------------------------------
// DESCRIPTION: Implementation of the IMMLogger interface
// COPYRIGHT: University of California, San Francisco, 2009
// LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Karl Hoover, karl.hoover@ucsf.edu, 2009 11 11
//
// CVS: $Id$
#include <stdarg.h>
#include <string>
#include <iostream>
#include <fstream>
#include <limits.h>
#include "FastLogger.h"
#include "CoreUtils.h"
#include "../MMDevice/DeviceUtils.h"
#include "boost/thread/thread.hpp"
#include <boost/lexical_cast.hpp>
#include "boost/interprocess/detail/os_thread_functions.hpp"
#include "boost/version.hpp"
#if BOOST_VERSION >= 104800
# define BOOST_IPC_DETAIL boost::interprocess::ipcdetail
#else
# define BOOST_IPC_DETAIL boost::interprocess::detail
#endif
using namespace std;
const char* g_textLogIniFiled = "Logging initialization failed\n";
class LoggerThread : public MMDeviceThreadBase
{
public:
LoggerThread(FastLogger* l) : log_(l), busy_(false), stop_(false) {}
~LoggerThread() {}
int svc (void);
void Stop() {stop_ = true;}
void Start() {stop_ = false; activate();}
private:
FastLogger* log_;
bool busy_;
bool stop_;
};
int LoggerThread::svc(void)
{
do
{
std::string stmp;
{
MMThreadGuard stringGuard(log_->logStringLock_g);
stmp = log_->stringToWrite_g;
log_->stringToWrite_g.clear();
}
if (0 < stmp.length())
{
if( 0 != (log_->flags() & STDERR))
std::cerr << stmp << '\n' << flush;
MMThreadGuard fileGuard(log_->logFileLock_g);
if( NULL != log_->plogFile_g)
*log_->plogFile_g << stmp << '\n' << flush;
}
CDeviceUtils::SleepMs(30);
} while (!stop_ );
return 0;
}
LoggerThread* pLogThread_g = NULL;
FastLogger::FastLogger()
:level_(any)
,fast_log_flags_(any)
,plogFile_(NULL)
,failureReported(false),
plogFile_g(0)
{
}
FastLogger::~FastLogger()
{
if( NULL != pLogThread_g)
{
pLogThread_g->Stop();
pLogThread_g->wait();
delete pLogThread_g;
}
Shutdown();
}
/**
* methods declared in IMMLogger as pure virtual
* Refere to IMMLogger declaration
*/
bool FastLogger::Initialize(std::string logFileName, std::string logInstanceName)throw(IMMLogger::runtime_exception)
{
bool bRet =false;
try
{
failureReported=false;
logInstanceName_=logInstanceName;
{
MMThreadGuard guard(logFileLock_g);
bRet = Open(logFileName);
if(bRet)
{
fast_log_flags_ |= OSTREAM;
}
fast_log_flags_ |= STDERR;
set_flags (fast_log_flags_);
}
if( NULL == pLogThread_g)
{
pLogThread_g = new LoggerThread(this);
pLogThread_g->Start();
}
}
catch(...)
{
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
return bRet;
};
void FastLogger::Shutdown()throw(IMMLogger::runtime_exception)
{
try
{
MMThreadGuard guard(logFileLock_g);
failureReported=false;
if(NULL != plogFile_g)
{
plogFile_g->close();
delete plogFile_g;
plogFile_g = NULL;
}
clr_flags (OSTREAM);
//msg_ostream (0, 0);
}
catch(...)
{
plogFile_g = NULL;
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
}
bool FastLogger::Reset()throw(IMMLogger::runtime_exception)
{
bool bRet =false;
try{
MMThreadGuard guard(logFileLock_g);
failureReported=false;
if(NULL != plogFile_g)
{
if (plogFile_g->is_open())
{
plogFile_g->close();
}
//re-open same file but truncate old log content
plogFile_g->open(logFileName_.c_str(), ios_base::trunc);
bRet = true;
}
}
catch(...)
{
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
return bRet;
};
void FastLogger::SetPriorityLevel(IMMLogger::priority level) throw()
{
level_ = level;
}
bool FastLogger::EnableLogToStderr(bool enable)throw()
{
bool bRet = ( 0 != (fast_log_flags_ | STDERR));
fast_log_flags_ |= OSTREAM;
if (enable)
{
fast_log_flags_ |= STDERR;
}
else
{
fast_log_flags_ &= ~STDERR;
}
pLogThread_g->Stop();
pLogThread_g->wait();
set_flags (fast_log_flags_);
pLogThread_g->Start();
return bRet;
};
void FastLogger::Log(IMMLogger::priority p, const char* format, ...) throw()
{
{
MMThreadGuard guard(logFileLock_g);
if( NULL == plogFile_g)
{
cerr<< " log file is NULL!" << endl;
return;
}
}
try
{
// filter by current priority
if (!(p & level_))
return;
std::string entryPrefix = GetEntryPrefix(p);
const size_t MaxBuf = 32767;
struct BigBuffer { char buffer[MaxBuf]; };
std::auto_ptr<BigBuffer> pB (new BigBuffer());
va_list argp;
va_start(argp, format);
#ifdef WIN32
int n = vsnprintf_s(pB->buffer, MaxBuf, MaxBuf - 1, format, argp);
#else
int n = vsnprintf(pB->buffer, MaxBuf - 1, format, argp);
#endif
va_end(argp, format);
if (n <= -1) {
ReportLogFailure();
return;
}
std::string workingString = entryPrefix + pB->buffer;
// Remove trailing newlines
// TODO Fix: Probably a source of leftover CRs on Windows.
if( '\n' == workingString.at(workingString.length()-1))
workingString.replace(workingString.length()-1,1,"");
{
MMThreadGuard stringGuard(logStringLock_g);
if ( 0 <stringToWrite_g.size())
stringToWrite_g += '\n';
stringToWrite_g += workingString;
}
}
catch(...)
{
ReportLogFailure();
}
};
void FastLogger::ReportLogFailure()throw()
{
if(!failureReported)
{
failureReported=true;
MMThreadGuard guard(logFileLock_g);
try {
std::cerr << g_textLogIniFiled;
}
catch (...) {
}
}
};
std::string FastLogger::GetEntryPrefix(IMMLogger::priority p)
{
// date, pid, tid, and log level
std::string entryPrefix;
entryPrefix.reserve(100);
// Date
boost::posix_time::ptime bt = boost::posix_time::microsec_clock::local_time();
std::string todaysDate = boost::posix_time::to_iso_extended_string(bt);
entryPrefix += todaysDate;
// PID
// XXX Avoid using Boost 'detail' classes!
BOOST_IPC_DETAIL::OS_process_id_t pidd = BOOST_IPC_DETAIL::get_current_process_id();
entryPrefix += " p:";
entryPrefix += boost::lexical_cast<std::string>(pidd);
// TID
entryPrefix += " t:";
// Use the platform thread id where available, so that it can be compared
// with debugger, etc.
#ifdef WIN32
entryPrefix += boost::lexical_cast<std::string>(GetCurrentThreadId());
#else
entryPrefix += boost::lexical_cast<std::string>(pthread_self());
#endif
// Log level
if (p == debug)
entryPrefix += " [dbg]: ";
else
entryPrefix += " [LOG]: ";
return entryPrefix;
}
bool FastLogger::Open(const std::string specifiedFile)
{
bool bRet = false;
try
{
if(NULL == plogFile_g)
{
plogFile_g = new std::ofstream();
}
if (!plogFile_g->is_open())
{
// N.B. we do NOT handle re-opening of the log file on a different path!!
if(logFileName_.length() < 1) // if log file path has not yet been specified:
{
logFileName_ = specifiedFile;
}
// first try to open the specified file without any assumption about the path
plogFile_g->open(logFileName_.c_str(), ios_base::app);
//std::cout << "first attempt to open " << logFileName_.c_str() << (plogFile_g->is_open()?" OK":" FAILED") << std::endl;
// if the open failed, assume that this is because the ordinary user does not have write access to the application / program directory
if (!plogFile_g->is_open())
{
std::string homePath;
#ifdef _WINDOWS
homePath = std::string(getenv("HOMEDRIVE")) + std::string(getenv("HOMEPATH")) + "\\";
#else
homePath = std::string(getenv("HOME")) + "/";
#endif
logFileName_ = homePath + specifiedFile;
plogFile_g->open(logFileName_.c_str(), ios_base::app);
}
}
else
{
;//std::cout << "log file " << logFileName_.c_str() << " was open already" << std::endl;
}
bRet = plogFile_g->is_open();
}
catch(...){}
return bRet;
}
void FastLogger::LogContents(char** ppContents, unsigned long& len)
{
*ppContents = 0;
len = 0;
MMThreadGuard guard(logFileLock_g);
if (plogFile_g->is_open())
{
plogFile_g->close();
}
// open to read, and position at the end of the file
// XXX We simply return NULL if cannot open file or size is too large!
std::ifstream ifile(logFileName_.c_str(), ios::in | ios::binary | ios::ate);
if (ifile.is_open())
{
std::ifstream::pos_type pos = ifile.tellg();
// XXX This is broken (sort of): on 64-bit Windows, we artificially
// limit ourselves to 4 GB. But it is probably okay since we don't
// expect the log contents to be > 4 GB. Fixing would require changing
// the signature of this function.
if (pos < ULONG_MAX)
{
len = static_cast<unsigned long>(pos);
*ppContents = new char[len];
if (0 != *ppContents)
{
ifile.seekg(0, ios::beg);
ifile.read(*ppContents, len);
ifile.close();
}
}
}
// re-open for logging
plogFile_g->open(logFileName_.c_str(), ios_base::app);
return;
}
std::string FastLogger::LogPath(void)
{
return logFileName_;
}
<commit_msg>CoreLog: Fix removal of trailing whitespace.<commit_after>///////////////////////////////////////////////////////////////////////////////
// FILE: FastLogger.cpp
// PROJECT: Micro-Manager
// SUBSYSTEM: MMCore
//-----------------------------------------------------------------------------
// DESCRIPTION: Implementation of the IMMLogger interface
// COPYRIGHT: University of California, San Francisco, 2009
// LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Karl Hoover, karl.hoover@ucsf.edu, 2009 11 11
//
// CVS: $Id$
#include <stdarg.h>
#include <string>
#include <iostream>
#include <fstream>
#include <limits.h>
#include "FastLogger.h"
#include "CoreUtils.h"
#include "../MMDevice/DeviceUtils.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread/thread.hpp>
// TODO Stop relying on Boost internals
#include "boost/interprocess/detail/os_thread_functions.hpp"
#include "boost/version.hpp"
#if BOOST_VERSION >= 104800
# define BOOST_IPC_DETAIL boost::interprocess::ipcdetail
#else
# define BOOST_IPC_DETAIL boost::interprocess::detail
#endif
using namespace std;
const char* g_textLogIniFiled = "Logging initialization failed\n";
class LoggerThread : public MMDeviceThreadBase
{
public:
LoggerThread(FastLogger* l) : log_(l), busy_(false), stop_(false) {}
~LoggerThread() {}
int svc (void);
void Stop() {stop_ = true;}
void Start() {stop_ = false; activate();}
private:
FastLogger* log_;
bool busy_;
bool stop_;
};
int LoggerThread::svc(void)
{
do
{
std::string stmp;
{
MMThreadGuard stringGuard(log_->logStringLock_g);
stmp = log_->stringToWrite_g;
log_->stringToWrite_g.clear();
}
if (0 < stmp.length())
{
if( 0 != (log_->flags() & STDERR))
std::cerr << stmp << '\n' << flush;
MMThreadGuard fileGuard(log_->logFileLock_g);
if( NULL != log_->plogFile_g)
*log_->plogFile_g << stmp << '\n' << flush;
}
CDeviceUtils::SleepMs(30);
} while (!stop_ );
return 0;
}
LoggerThread* pLogThread_g = NULL;
FastLogger::FastLogger()
:level_(any)
,fast_log_flags_(any)
,plogFile_(NULL)
,failureReported(false),
plogFile_g(0)
{
}
FastLogger::~FastLogger()
{
if( NULL != pLogThread_g)
{
pLogThread_g->Stop();
pLogThread_g->wait();
delete pLogThread_g;
}
Shutdown();
}
/**
* methods declared in IMMLogger as pure virtual
* Refere to IMMLogger declaration
*/
bool FastLogger::Initialize(std::string logFileName, std::string logInstanceName)throw(IMMLogger::runtime_exception)
{
bool bRet =false;
try
{
failureReported=false;
logInstanceName_=logInstanceName;
{
MMThreadGuard guard(logFileLock_g);
bRet = Open(logFileName);
if(bRet)
{
fast_log_flags_ |= OSTREAM;
}
fast_log_flags_ |= STDERR;
set_flags (fast_log_flags_);
}
if( NULL == pLogThread_g)
{
pLogThread_g = new LoggerThread(this);
pLogThread_g->Start();
}
}
catch(...)
{
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
return bRet;
};
void FastLogger::Shutdown()throw(IMMLogger::runtime_exception)
{
try
{
MMThreadGuard guard(logFileLock_g);
failureReported=false;
if(NULL != plogFile_g)
{
plogFile_g->close();
delete plogFile_g;
plogFile_g = NULL;
}
clr_flags (OSTREAM);
//msg_ostream (0, 0);
}
catch(...)
{
plogFile_g = NULL;
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
}
bool FastLogger::Reset()throw(IMMLogger::runtime_exception)
{
bool bRet =false;
try{
MMThreadGuard guard(logFileLock_g);
failureReported=false;
if(NULL != plogFile_g)
{
if (plogFile_g->is_open())
{
plogFile_g->close();
}
//re-open same file but truncate old log content
plogFile_g->open(logFileName_.c_str(), ios_base::trunc);
bRet = true;
}
}
catch(...)
{
ReportLogFailure();
throw(IMMLogger::runtime_exception(g_textLogIniFiled));
}
return bRet;
};
void FastLogger::SetPriorityLevel(IMMLogger::priority level) throw()
{
level_ = level;
}
bool FastLogger::EnableLogToStderr(bool enable)throw()
{
bool bRet = ( 0 != (fast_log_flags_ | STDERR));
fast_log_flags_ |= OSTREAM;
if (enable)
{
fast_log_flags_ |= STDERR;
}
else
{
fast_log_flags_ &= ~STDERR;
}
pLogThread_g->Stop();
pLogThread_g->wait();
set_flags (fast_log_flags_);
pLogThread_g->Start();
return bRet;
};
void FastLogger::Log(IMMLogger::priority p, const char* format, ...) throw()
{
{
MMThreadGuard guard(logFileLock_g);
if( NULL == plogFile_g)
{
cerr<< " log file is NULL!" << endl;
return;
}
}
try
{
// filter by current priority
if (!(p & level_))
return;
std::string entryPrefix = GetEntryPrefix(p);
const size_t MaxBuf = 32767;
struct BigBuffer { char buffer[MaxBuf]; };
std::auto_ptr<BigBuffer> pB (new BigBuffer());
va_list argp;
va_start(argp, format);
#ifdef WIN32
int n = vsnprintf_s(pB->buffer, MaxBuf, MaxBuf - 1, format, argp);
#else
int n = vsnprintf(pB->buffer, MaxBuf - 1, format, argp);
#endif
va_end(argp, format);
if (n <= -1) {
ReportLogFailure();
return;
}
std::string entryString = entryPrefix + pB->buffer;
boost::algorithm::trim_right(entryString);
{
MMThreadGuard stringGuard(logStringLock_g);
if ( 0 <stringToWrite_g.size())
stringToWrite_g += '\n';
stringToWrite_g += entryString;
}
}
catch(...)
{
ReportLogFailure();
}
};
void FastLogger::ReportLogFailure()throw()
{
if(!failureReported)
{
failureReported=true;
MMThreadGuard guard(logFileLock_g);
try {
std::cerr << g_textLogIniFiled;
}
catch (...) {
}
}
};
std::string FastLogger::GetEntryPrefix(IMMLogger::priority p)
{
// date, pid, tid, and log level
std::string entryPrefix;
entryPrefix.reserve(100);
// Date
boost::posix_time::ptime bt = boost::posix_time::microsec_clock::local_time();
std::string todaysDate = boost::posix_time::to_iso_extended_string(bt);
entryPrefix += todaysDate;
// PID
// XXX Avoid using Boost 'detail' classes!
BOOST_IPC_DETAIL::OS_process_id_t pidd = BOOST_IPC_DETAIL::get_current_process_id();
entryPrefix += " p:";
entryPrefix += boost::lexical_cast<std::string>(pidd);
// TID
entryPrefix += " t:";
// Use the platform thread id where available, so that it can be compared
// with debugger, etc.
#ifdef WIN32
entryPrefix += boost::lexical_cast<std::string>(GetCurrentThreadId());
#else
entryPrefix += boost::lexical_cast<std::string>(pthread_self());
#endif
// Log level
if (p == debug)
entryPrefix += " [dbg]: ";
else
entryPrefix += " [LOG]: ";
return entryPrefix;
}
bool FastLogger::Open(const std::string specifiedFile)
{
bool bRet = false;
try
{
if(NULL == plogFile_g)
{
plogFile_g = new std::ofstream();
}
if (!plogFile_g->is_open())
{
// N.B. we do NOT handle re-opening of the log file on a different path!!
if(logFileName_.length() < 1) // if log file path has not yet been specified:
{
logFileName_ = specifiedFile;
}
// first try to open the specified file without any assumption about the path
plogFile_g->open(logFileName_.c_str(), ios_base::app);
//std::cout << "first attempt to open " << logFileName_.c_str() << (plogFile_g->is_open()?" OK":" FAILED") << std::endl;
// if the open failed, assume that this is because the ordinary user does not have write access to the application / program directory
if (!plogFile_g->is_open())
{
std::string homePath;
#ifdef _WINDOWS
homePath = std::string(getenv("HOMEDRIVE")) + std::string(getenv("HOMEPATH")) + "\\";
#else
homePath = std::string(getenv("HOME")) + "/";
#endif
logFileName_ = homePath + specifiedFile;
plogFile_g->open(logFileName_.c_str(), ios_base::app);
}
}
else
{
;//std::cout << "log file " << logFileName_.c_str() << " was open already" << std::endl;
}
bRet = plogFile_g->is_open();
}
catch(...){}
return bRet;
}
void FastLogger::LogContents(char** ppContents, unsigned long& len)
{
*ppContents = 0;
len = 0;
MMThreadGuard guard(logFileLock_g);
if (plogFile_g->is_open())
{
plogFile_g->close();
}
// open to read, and position at the end of the file
// XXX We simply return NULL if cannot open file or size is too large!
std::ifstream ifile(logFileName_.c_str(), ios::in | ios::binary | ios::ate);
if (ifile.is_open())
{
std::ifstream::pos_type pos = ifile.tellg();
// XXX This is broken (sort of): on 64-bit Windows, we artificially
// limit ourselves to 4 GB. But it is probably okay since we don't
// expect the log contents to be > 4 GB. Fixing would require changing
// the signature of this function.
if (pos < ULONG_MAX)
{
len = static_cast<unsigned long>(pos);
*ppContents = new char[len];
if (0 != *ppContents)
{
ifile.seekg(0, ios::beg);
ifile.read(*ppContents, len);
ifile.close();
}
}
}
// re-open for logging
plogFile_g->open(logFileName_.c_str(), ios_base::app);
return;
}
std::string FastLogger::LogPath(void)
{
return logFileName_;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: SlsPageCacheManager.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-11-08 16:30:28 $
*
* 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 SD_PAGE_CACHE_MANAGER_HXX
#define SD_PAGE_CACHE_MANAGER_HXX
#include <sal/types.h>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <vector>
class Size;
class SdDrawDocument;
class SdrPage;
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
class PageObjectViewObjectContact;
} } }
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace cache {
class BitmapCache;
/** Provide and manage the preview bitmap caches for all slide sorter
instances. There is one cache per active slide sorter plus a small
number of caches that are no longer in use. The later are kept to speed
up the switching between views.
*/
class PageCacheManager
{
public:
typedef BitmapCache Cache;
typedef ::std::vector< ::std::pair<Size, ::boost::shared_ptr<BitmapCache> > > BestFittingPageCaches;
/** Return the one instance of the PageCacheManager class.
*/
static ::boost::shared_ptr<PageCacheManager> Instance (void);
/** Look up the cache for the given model in which the previews have the
specified size. If no such cache exists, then one is created. When
a new BitmapCache is created its Recycle() method is called with a
sorted list of existing caches from which the new one initialize its
previews.
@return
The returned cache lives as long as somebody keeps a shared
pointer and the ReleaseCache() method has not been called.
*/
::boost::shared_ptr<Cache> GetCache (
SdDrawDocument* pDocument,
const Size& rPreviewSize);
/** Tell the cache manager to release its own reference to the specified
cache. After that the cache will live as long as the caller (and
maybe others) holds its reference.
*/
void ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache);
/** This is an information to the cache manager that the size of preview
bitmaps in the specified cache has changed.
*/
::boost::shared_ptr<Cache> ChangeSize (
const ::boost::shared_ptr<Cache>& rpCache,
const Size& rOldPreviewSize,
const Size& rNewPreviewSize);
/** Invalidate the preview bitmap for one slide that belongs to the
specified document. The bitmaps for this slide in all caches are
marked as out-of-date and will be re-created when they are requested
the next time.
*/
void InvalidatePreviewBitmap (
SdDrawDocument* pDocument,
const SdrPage* pPage);
/** The destructor, like the constructor is, should be private. It can
not because the shared_ptr<> implementation does not allow this.
*/
~PageCacheManager (void);
private:
/** Singleton instance of the cache manager. Note that this is a weak
pointer. The (implementation class of) ViewShellBase holds a
shared_ptr so that the cache manager has the same life time as the
ViewShellBase.
*/
static ::boost::weak_ptr<PageCacheManager> mpInstance;
/// List of active caches.
class PageCacheContainer;
::std::auto_ptr<PageCacheContainer> mpPageCaches;
/// List of inactive, recently used caches.
class RecentlyUsedPageCaches;
::std::auto_ptr<RecentlyUsedPageCaches> mpRecentlyUsedPageCaches;
/** The maximal number of recently used caches that are kept alive after
they have become inactive, i.e. after they are not used anymore by a
slide sorter.
*/
const sal_uInt32 mnMaximalRecentlyCacheCount;
PageCacheManager (void);
::boost::shared_ptr<Cache> GetRecentlyUsedCache(
SdDrawDocument* pDocument,
const Size& rSize);
/** Add the given cache to the list of recently used caches for the
document. There is one such list per document. Each least has at
most mnMaximalRecentlyCacheCount members.
*/
void PutRecentlyUsedCache(
SdDrawDocument* pDocument,
const Size& rPreviewSize,
const ::boost::shared_ptr<Cache>& rpCache);
/** Return a sorted list of the available caches, both active caches and
those recently used, for the given document. The sort order is so
that an exact match of the preview size is at the front. Other
caches follow with the largest size first.
*/
BestFittingPageCaches GetBestFittingCaches (
SdDrawDocument* pDocument,
const Size& rPreviewSize);
/** This method is used internally to initialize a newly created
BitmapCache with already exisiting previews.
*/
void Recycle (
const ::boost::shared_ptr<Cache>& rpCache,
SdDrawDocument* pDocument,
const Size& rPreviewSize);
};
} } } // end of namespace ::sd::slidesorter::cache
#endif
<commit_msg>INTEGRATION: CWS pj42 (1.3.2); FILE MERGED 2005/11/10 21:59:33 pjanik 1.3.2.1: #i57567#: Remove SISSL license.<commit_after>/*************************************************************************
*
* $RCSfile: SlsPageCacheManager.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-11-11 10:48:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_PAGE_CACHE_MANAGER_HXX
#define SD_PAGE_CACHE_MANAGER_HXX
#include <sal/types.h>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <vector>
class Size;
class SdDrawDocument;
class SdrPage;
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
class PageObjectViewObjectContact;
} } }
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace cache {
class BitmapCache;
/** Provide and manage the preview bitmap caches for all slide sorter
instances. There is one cache per active slide sorter plus a small
number of caches that are no longer in use. The later are kept to speed
up the switching between views.
*/
class PageCacheManager
{
public:
typedef BitmapCache Cache;
typedef ::std::vector< ::std::pair<Size, ::boost::shared_ptr<BitmapCache> > > BestFittingPageCaches;
/** Return the one instance of the PageCacheManager class.
*/
static ::boost::shared_ptr<PageCacheManager> Instance (void);
/** Look up the cache for the given model in which the previews have the
specified size. If no such cache exists, then one is created. When
a new BitmapCache is created its Recycle() method is called with a
sorted list of existing caches from which the new one initialize its
previews.
@return
The returned cache lives as long as somebody keeps a shared
pointer and the ReleaseCache() method has not been called.
*/
::boost::shared_ptr<Cache> GetCache (
SdDrawDocument* pDocument,
const Size& rPreviewSize);
/** Tell the cache manager to release its own reference to the specified
cache. After that the cache will live as long as the caller (and
maybe others) holds its reference.
*/
void ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache);
/** This is an information to the cache manager that the size of preview
bitmaps in the specified cache has changed.
*/
::boost::shared_ptr<Cache> ChangeSize (
const ::boost::shared_ptr<Cache>& rpCache,
const Size& rOldPreviewSize,
const Size& rNewPreviewSize);
/** Invalidate the preview bitmap for one slide that belongs to the
specified document. The bitmaps for this slide in all caches are
marked as out-of-date and will be re-created when they are requested
the next time.
*/
void InvalidatePreviewBitmap (
SdDrawDocument* pDocument,
const SdrPage* pPage);
/** The destructor, like the constructor is, should be private. It can
not because the shared_ptr<> implementation does not allow this.
*/
~PageCacheManager (void);
private:
/** Singleton instance of the cache manager. Note that this is a weak
pointer. The (implementation class of) ViewShellBase holds a
shared_ptr so that the cache manager has the same life time as the
ViewShellBase.
*/
static ::boost::weak_ptr<PageCacheManager> mpInstance;
/// List of active caches.
class PageCacheContainer;
::std::auto_ptr<PageCacheContainer> mpPageCaches;
/// List of inactive, recently used caches.
class RecentlyUsedPageCaches;
::std::auto_ptr<RecentlyUsedPageCaches> mpRecentlyUsedPageCaches;
/** The maximal number of recently used caches that are kept alive after
they have become inactive, i.e. after they are not used anymore by a
slide sorter.
*/
const sal_uInt32 mnMaximalRecentlyCacheCount;
PageCacheManager (void);
::boost::shared_ptr<Cache> GetRecentlyUsedCache(
SdDrawDocument* pDocument,
const Size& rSize);
/** Add the given cache to the list of recently used caches for the
document. There is one such list per document. Each least has at
most mnMaximalRecentlyCacheCount members.
*/
void PutRecentlyUsedCache(
SdDrawDocument* pDocument,
const Size& rPreviewSize,
const ::boost::shared_ptr<Cache>& rpCache);
/** Return a sorted list of the available caches, both active caches and
those recently used, for the given document. The sort order is so
that an exact match of the preview size is at the front. Other
caches follow with the largest size first.
*/
BestFittingPageCaches GetBestFittingCaches (
SdDrawDocument* pDocument,
const Size& rPreviewSize);
/** This method is used internally to initialize a newly created
BitmapCache with already exisiting previews.
*/
void Recycle (
const ::boost::shared_ptr<Cache>& rpCache,
SdDrawDocument* pDocument,
const Size& rPreviewSize);
};
} } } // end of namespace ::sd::slidesorter::cache
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: miscopt.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-07-26 08:41:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
#define INCLUDED_SVTOOLS_MISCOPT_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtMiscOptions_Impl;
class Link;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about misc group
@descr -
@implements -
@base -
@ATTENTION This class is partially threadsafe.
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVT_DLLPUBLIC SvtMiscOptions: public svt::detail::Options
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtMiscOptions();
virtual ~SvtMiscOptions();
void AddListener( const Link& rLink );
void RemoveListener( const Link& rLink );
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
sal_Bool UseSystemFileDialog() const;
void SetUseSystemFileDialog( sal_Bool bSet );
sal_Bool IsUseSystemFileDialogReadOnly() const;
sal_Bool IsPluginsEnabled() const;
void SetPluginsEnabled( sal_Bool bEnable );
sal_Bool IsPluginsEnabledReadOnly() const;
sal_Int16 GetSymbolsSize() const;
void SetSymbolsSize( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsSize() const;
bool AreCurrentSymbolsLarge() const;
sal_Bool IsGetSymbolsSizeReadOnly() const;
sal_Int16 GetSymbolsStyle() const;
void SetSymbolsStyle( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsStyle() const;
::rtl::OUString GetCurrentSymbolsStyleName() const;
sal_Bool IsGetSymbolsStyleReadOnly() const;
sal_Int16 GetToolboxStyle() const;
void SetToolboxStyle( sal_Int16 nStyle );
sal_Bool IsGetToolboxStyleReadOnly() const;
sal_Bool IsModifyByPrinting() const;
void SetModifyByPrinting(sal_Bool bSet );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class is partially threadsafe (for de-/initialization only).
All access methods are'nt safe!
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVT_DLLPRIVATE static ::osl::Mutex& GetInitMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtMiscOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtMiscOptions
#endif // #ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
<commit_msg>INTEGRATION: CWS nativeprintdlg01_DEV300 (1.3.110); FILE MERGED 2008/02/21 21:44:14 pl 1.3.110.1: #i86329# add system print dialog property<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: miscopt.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2008-03-05 16:39:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
#define INCLUDED_SVTOOLS_MISCOPT_HXX
//_________________________________________________________________________________________________________________
// includes
//_________________________________________________________________________________________________________________
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif
//_________________________________________________________________________________________________________________
// forward declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short forward declaration to our private date container implementation
@descr We use these class as internal member to support small memory requirements.
You can create the container if it is neccessary. The class which use these mechanism
is faster and smaller then a complete implementation!
*//*-*************************************************************************************************************/
class SvtMiscOptions_Impl;
class Link;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
/*-************************************************************************************************************//**
@short collect informations about misc group
@descr -
@implements -
@base -
@ATTENTION This class is partially threadsafe.
@devstatus ready to use
*//*-*************************************************************************************************************/
class SVT_DLLPUBLIC SvtMiscOptions: public svt::detail::Options
{
//-------------------------------------------------------------------------------------------------------------
// public methods
//-------------------------------------------------------------------------------------------------------------
public:
//---------------------------------------------------------------------------------------------------------
// constructor / destructor
//---------------------------------------------------------------------------------------------------------
/*-****************************************************************************************************//**
@short standard constructor and destructor
@descr This will initialize an instance with default values.
We implement these class with a refcount mechanism! Every instance of this class increase it
at create and decrease it at delete time - but all instances use the same data container!
He is implemented as a static member ...
@seealso member m_nRefCount
@seealso member m_pDataContainer
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
SvtMiscOptions();
virtual ~SvtMiscOptions();
void AddListener( const Link& rLink );
void RemoveListener( const Link& rLink );
//---------------------------------------------------------------------------------------------------------
// interface
//---------------------------------------------------------------------------------------------------------
sal_Bool UseSystemFileDialog() const;
void SetUseSystemFileDialog( sal_Bool bSet );
sal_Bool IsUseSystemFileDialogReadOnly() const;
sal_Bool IsPluginsEnabled() const;
void SetPluginsEnabled( sal_Bool bEnable );
sal_Bool IsPluginsEnabledReadOnly() const;
sal_Int16 GetSymbolsSize() const;
void SetSymbolsSize( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsSize() const;
bool AreCurrentSymbolsLarge() const;
sal_Bool IsGetSymbolsSizeReadOnly() const;
sal_Int16 GetSymbolsStyle() const;
void SetSymbolsStyle( sal_Int16 eSet );
sal_Int16 GetCurrentSymbolsStyle() const;
::rtl::OUString GetCurrentSymbolsStyleName() const;
sal_Bool IsGetSymbolsStyleReadOnly() const;
sal_Int16 GetToolboxStyle() const;
void SetToolboxStyle( sal_Int16 nStyle );
sal_Bool IsGetToolboxStyleReadOnly() const;
sal_Bool IsModifyByPrinting() const;
void SetModifyByPrinting(sal_Bool bSet );
sal_Bool UseSystemPrintDialog() const;
void SetUseSystemPrintDialog( sal_Bool bSet );
//-------------------------------------------------------------------------------------------------------------
// private methods
//-------------------------------------------------------------------------------------------------------------
private:
/*-****************************************************************************************************//**
@short return a reference to a static mutex
@descr These class is partially threadsafe (for de-/initialization only).
All access methods are'nt safe!
We create a static mutex only for one ime and use at different times.
@seealso -
@param -
@return A reference to a static mutex member.
@onerror -
*//*-*****************************************************************************************************/
SVT_DLLPRIVATE static ::osl::Mutex& GetInitMutex();
//-------------------------------------------------------------------------------------------------------------
// private member
//-------------------------------------------------------------------------------------------------------------
private:
/*Attention
Don't initialize these static member in these header!
a) Double dfined symbols will be detected ...
b) and unresolved externals exist at linking time.
Do it in your source only.
*/
static SvtMiscOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements!
static sal_Int32 m_nRefCount ; /// internal ref count mechanism
}; // class SvtMiscOptions
#endif // #ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
<|endoftext|>
|
<commit_before>//! @Alan
//!
//! Exercise 9.50:
//! Write a program to process a vector<string>s whose elements represent integral values.
//! Produce the sum of all the elements in that vector.
//! Change the program so that it sums of strings that represent floating-point values.
//!
#include <iostream>
#include <string>
#include <vector>
int sum(const std::vector<std::string> &v);
float sum_f(const std::vector<std::string> &v);
int main()
{
std::vector<std::string> v = {"1","2","3","4.5"};
std::cout << sum(v)<<"\n";
std::cout << sum_f(v);
return 0;
}
int sum(const std::vector<std::string> &v)
{
int sum=0;
for(auto &s : v)
{
sum += std::stoi(s);
}
return sum;
}
float sum_f(const std::vector<std::string> &v)
{
float sum = 0.0;
for(auto &s : v)
{
sum += std::stof(s);
}
return sum;
}
<commit_msg>Update ex9_50.cpp<commit_after>//! @Yue Wang
//!
//! Exercise 9.50:
//! Write a program to process a vector<string>s whose elements represent integral values.
//! Produce the sum of all the elements in that vector.
//! Change the program so that it sums of strings that represent floating-point values.
//!
#include <iostream>
#include <string>
#include <vector>
int sum_for_int(const std::vector<std::string> const& v)
{
int sum = 0;
for (auto const& s : v)
sum += std::stoi(s);
return sum;
}
float sum_for_float(const std::vector<std::string> const& v)
{
float sum = 0.0;
for (auto const& s : v)
sum += std::stof(s);
return sum;
}
int main()
{
std::vector<std::string> v = { "1", "2", "3", "4.5" };
std::cout << sum_for_int(v) << std::endl;
std::cout << sum_for_float(v) << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>edk/watch/Time: I try to compile the source code and I get and error in Time.cpp.<commit_after><|endoftext|>
|
<commit_before>//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main()
{
map<string, vector<string>> famls;
string lastName, chldName;
//! while(lambda)
cin.clear();
while([&]() ->bool {cout<<"Please enter last name:\n"; return cin>>lastName&&lastName!="@q";}()) //the () used here is to call the lambda, otherwise it does not work
{
cout<<"Please enter children's names:\n";
cin.clear();
while(cin>>chldName&&chldName!="@q")
{
//! add new items into vector
famls[lastName].push_back(chldName);
}
}
//! iterate through the map
for(const auto &e:famls)
{
cout<<e.first<<":\n" ;
//iterate through the vector
for(const auto &c: e.second)
cout<<c<<" ";
cout<<endl;
}
}
<commit_msg>Update ex11_7.cpp<commit_after>//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main()
{
map<string, vector<string>> famls;
string lastName, chldName;
//! while(lambda)
cin.clear();
while([&]() ->bool {cout<<"Please enter last name:\n"; return cin>>lastName&&lastName!="@q";}()) //the () used here is to call the lambda, otherwise it does not work
{
cout<<"Please enter children's names:\n";
cin.clear();
while(cin>>chldName&&chldName!="@q")
{
//! add new items into vector
famls[lastName].push_back(chldName);
}
}
//! iterate through the map
for(const auto &e:famls)
{
cout<<e.first<<":\n" ;
//! iterate through the vector
for(const auto &c: e.second)
cout<<c<<" ";
cout<<endl;
}
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#1158124 Dereference after null check<commit_after><|endoftext|>
|
<commit_before>#include <algorithm>
#include <chrono>
#include <fstream>
#include <vector>
#include <CGAL/ch_graham_andrew.h>
#include "point.h"
#include "bsthull.h"
template<class TFn, class ...TArgs>
double measureAlgo(TFn fn, size_t testsNum, TArgs&&... args)
{
using namespace std::chrono;
const auto tStart = high_resolution_clock::now();
for (size_t test = 0; test < testsNum; ++test)
(void) fn(std::forward<TArgs>(args)...);
const auto tEnd = high_resolution_clock::now();
return duration_cast<duration<double>>(tEnd - tStart).count() / testsNum;
}
int main()
{
std::ifstream fin("in.txt");
std::ofstream fout("out.txt");
std::ofstream("algoNames.txt") << "Graham scan\nNew algorithm";
size_t testsNum;
fin >> testsNum;
for (size_t test = 0; test < testsNum; ++test)
{
int pointsNum;
fin >> pointsNum;
std::vector<Point> points;
points.reserve(pointsNum);
for (int i = 0; i < pointsNum; ++i)
{
double x, y;
fin >> x >> y;
points.emplace_back(x, y);
}
const size_t runsNum = std::max(20, 1'000'000 / pointsNum);
std::vector<Point> result(pointsNum);
// heat up cache for algo
measureAlgo(CGAL::ch_graham_andrew<std::vector<Point>::iterator, std::vector<Point>::iterator>,
runsNum, points.begin(), points.end(), result.begin());
fout << measureAlgo(CGAL::ch_graham_andrew<std::vector<Point>::iterator, std::vector<Point>::iterator>,
runsNum, points.begin(), points.end(), result.begin()) << ' ';
// heat up cache for algo
measureAlgo(algorithms::BstConvexHull::Create, runsNum, points);
fout << measureAlgo(algorithms::BstConvexHull::Create, runsNum, points) << '\n';
}
return 0;
}
<commit_msg>Increase runs number for testing<commit_after>#include <algorithm>
#include <chrono>
#include <fstream>
#include <vector>
#include <CGAL/ch_graham_andrew.h>
#include "point.h"
#include "bsthull.h"
template<class TFn, class ...TArgs>
double measureAlgo(TFn fn, size_t testsNum, TArgs&&... args)
{
using namespace std::chrono;
const auto tStart = high_resolution_clock::now();
for (size_t test = 0; test < testsNum; ++test)
(void) fn(std::forward<TArgs>(args)...);
const auto tEnd = high_resolution_clock::now();
return duration_cast<duration<double>>(tEnd - tStart).count() / testsNum;
}
int main()
{
std::ifstream fin("in.txt");
std::ofstream fout("out.txt");
std::ofstream("algoNames.txt") << "Graham scan\nNew algorithm";
size_t testsNum;
fin >> testsNum;
for (size_t test = 0; test < testsNum; ++test)
{
int pointsNum;
fin >> pointsNum;
std::vector<Point> points;
points.reserve(pointsNum);
for (int i = 0; i < pointsNum; ++i)
{
double x, y;
fin >> x >> y;
points.emplace_back(x, y);
}
const size_t runsNum = std::max(30, 10'000'000 / pointsNum);
std::vector<Point> result(pointsNum);
// heat up cache for algo
measureAlgo(CGAL::ch_graham_andrew<std::vector<Point>::iterator, std::vector<Point>::iterator>,
runsNum, points.begin(), points.end(), result.begin());
fout << measureAlgo(CGAL::ch_graham_andrew<std::vector<Point>::iterator, std::vector<Point>::iterator>,
runsNum, points.begin(), points.end(), result.begin()) << ' ';
// heat up cache for algo
measureAlgo(algorithms::BstConvexHull::Create, runsNum, points);
fout << measureAlgo(algorithms::BstConvexHull::Create, runsNum, points) << '\n';
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>n#821567: Use BitmapURL only if its valid.<commit_after><|endoftext|>
|
<commit_before><commit_msg>SwIndex: clean up Remove duplication<commit_after><|endoftext|>
|
<commit_before><commit_msg>Simplify<commit_after><|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ST7565 LCD ドライバー
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "common/csi_io.hpp"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ST7565 テンプレートクラス
@param[in] CSI_IO CSI(SPI) 制御クラス
@param[in] CTRL デバイス選択、レジスター選択、制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSI_IO>
class ST7565 {
CSI_IO& csi_;
// CTRL ctrl_;
enum class CMD : uint8_t {
DISPLAY_OFF = 0xAE,
DISPLAY_ON = 0xAF,
SET_DISP_START_LINE = 0x40,
SET_PAGE = 0xB0,
SET_COLUMN_UPPER = 0x10,
SET_COLUMN_LOWER = 0x00,
SET_ADC_NORMAL = 0xA0,
SET_ADC_REVERSE = 0xA1,
SET_DISP_NORMAL = 0xA6,
SET_DISP_REVERSE = 0xA7,
SET_ALLPTS_NORMAL = 0xA4,
SET_ALLPTS_ON = 0xA5,
SET_BIAS_9 = 0xA2,
SET_BIAS_7 = 0xA3,
RMW = 0xE0,
RMW_CLEAR = 0xEE,
INTERNAL_RESET = 0xE2,
SET_COM_NORMAL = 0xC0,
SET_COM_REVERSE = 0xC8,
SET_POWER_CONTROL = 0x28,
SET_RESISTOR_RATIO = 0x20,
SET_VOLUME_FIRST = 0x81,
SET_VOLUME_SECOND = 0x00,
SET_STATIC_OFF = 0xAC,
SET_STATIC_ON = 0xAD,
SET_STATIC_REG = 0x00,
SET_BOOSTER_FIRST = 0xF8,
SET_BOOSTER_234 = 0,
SET_BOOSTER_5 = 1,
SET_BOOSTER_6 = 3,
NOP = 0xE3,
TEST = 0xF0,
};
inline void write_(CMD cmd) {
csi_.xchg(static_cast<uint8_t>(cmd));
}
inline void write_(CMD cmd, uint8_t ord) {
csi_.xchg(static_cast<uint8_t>(cmd) | ord);
}
inline void chip_enable_(bool f = true) const {
device::P0.B1 = !f;
}
inline void reg_select_(bool f) const {
device::P0.B0 = f;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ST7565(CSI_IO& csi) : csi_(csi) { }
//-----------------------------------------------------------------//
/*!
@brief ブライトネス設定
@param[in] val ブライトネス値
*/
//-----------------------------------------------------------------//
void set_brightness(uint8_t val)
{
write_(CMD::SET_VOLUME_FIRST);
write_(CMD::SET_VOLUME_SECOND, (val & 0x3f));
}
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] contrast コントラスト
*/
//-----------------------------------------------------------------//
void start(uint8_t contrast)
{
device::PM0.B0 = 0; // (A0) output
device::PM0.B1 = 0; // (/CS) output
reg_select_(0);
chip_enable_(false);
utils::delay::milli_second(100);
init();
write_(CMD::DISPLAY_ON);
write_(CMD::SET_ALLPTS_NORMAL);
set_brightness(contrast);
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init()
{
reg_select_(0);
chip_enable_();
// toggle RST low to reset; CS low so it'll listen to us
// if (cs > 0)
// digitalWrite(cs, LOW);
// digitalWrite(rst, LOW);
// _delay_ms(500);
// digitalWrite(rst, HIGH);
write_(CMD::DISPLAY_OFF);
// LCD bias select
write_(CMD::SET_BIAS_7);
// ADC select
write_(CMD::SET_ADC_NORMAL);
// SHL select
write_(CMD::SET_COM_NORMAL);
// Initial display line
write_(CMD::SET_DISP_START_LINE);
// turn on voltage converter (VC=1, VR=0, VF=0)
write_(CMD::SET_POWER_CONTROL, 0x4);
// wait for 50% rising
utils::delay::milli_second(50);
// turn on voltage regulator (VC=1, VR=1, VF=0)
write_(CMD::SET_POWER_CONTROL, 0x6);
// wait >=50ms
utils::delay::milli_second(50);
// turn on voltage follower (VC=1, VR=1, VF=1)
write_(CMD::SET_POWER_CONTROL, 0x7);
// wait 10ms
utils::delay::milli_second(10);
// set lcd operating voltage (regulator resistor, ref voltage resistor)
write_(CMD::SET_RESISTOR_RATIO, 0x6);
}
//-----------------------------------------------------------------//
/*!
@brief コピー
@param[in] p フレームバッファソース
*/
//-----------------------------------------------------------------//
void copy(const uint8_t* p) {
uint8_t ofs = 0x00;
for(uint8_t page = 0; page < 8; ++page) {
reg_select_(0);
write_(CMD::SET_PAGE, page);
write_(CMD::SET_COLUMN_LOWER, ofs & 0x0f);
write_(CMD::SET_COLUMN_UPPER, ofs >> 4);
write_(CMD::RMW);
reg_select_(1);
for(uint8_t i = 0; i < 128; ++i) {
csi_.xchg(*p);
++p;
}
}
reg_select_(0);
}
};
}
<commit_msg>update CS/A0 ctrl<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ST7565(R) LCD ドライバー
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
#include "G13/port.hpp"
#include "common/csi_io.hpp"
namespace chip {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ST7565 テンプレートクラス
@param[in] CSI_IO CSI(SPI) 制御クラス
@param[in] CS デバイス選択、レジスター選択、制御クラス
@param[in] A0 制御切り替え、レジスター選択、制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class CSI_IO, class CS, class A0>
class ST7565 {
CSI_IO& csi_;
enum class CMD : uint8_t {
DISPLAY_OFF = 0xAE,
DISPLAY_ON = 0xAF,
SET_DISP_START_LINE = 0x40,
SET_PAGE = 0xB0,
SET_COLUMN_UPPER = 0x10,
SET_COLUMN_LOWER = 0x00,
SET_ADC_NORMAL = 0xA0,
SET_ADC_REVERSE = 0xA1,
SET_DISP_NORMAL = 0xA6,
SET_DISP_REVERSE = 0xA7,
SET_ALLPTS_NORMAL = 0xA4,
SET_ALLPTS_ON = 0xA5,
SET_BIAS_9 = 0xA2,
SET_BIAS_7 = 0xA3,
RMW = 0xE0,
RMW_CLEAR = 0xEE,
INTERNAL_RESET = 0xE2,
SET_COM_NORMAL = 0xC0,
SET_COM_REVERSE = 0xC8,
SET_POWER_CONTROL = 0x28,
SET_RESISTOR_RATIO = 0x20,
SET_VOLUME_FIRST = 0x81,
SET_VOLUME_SECOND = 0x00,
SET_STATIC_OFF = 0xAC,
SET_STATIC_ON = 0xAD,
SET_STATIC_REG = 0x00,
SET_BOOSTER_FIRST = 0xF8,
SET_BOOSTER_234 = 0,
SET_BOOSTER_5 = 1,
SET_BOOSTER_6 = 3,
NOP = 0xE3,
TEST = 0xF0,
};
inline void write_(CMD cmd) {
csi_.xchg(static_cast<uint8_t>(cmd));
}
inline void write_(CMD cmd, uint8_t ord) {
csi_.xchg(static_cast<uint8_t>(cmd) | ord);
}
inline void chip_enable_(bool f = true) const {
CS::P = !f;
}
inline void reg_select_(bool f) const {
A0::P = f;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ST7565(CSI_IO& csi) : csi_(csi) { }
//-----------------------------------------------------------------//
/*!
@brief ブライトネス設定
@param[in] val ブライトネス値
*/
//-----------------------------------------------------------------//
void set_brightness(uint8_t val)
{
write_(CMD::SET_VOLUME_FIRST);
write_(CMD::SET_VOLUME_SECOND, (val & 0x3f));
}
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] contrast コントラスト
*/
//-----------------------------------------------------------------//
void start(uint8_t contrast)
{
CS::PMC = 0; // (/CS) output
CS::PM = 0;
A0::PMC = 0; // (A0) output
A0::PM = 0;
reg_select_(0);
chip_enable_(false);
utils::delay::milli_second(100);
init();
write_(CMD::DISPLAY_ON);
write_(CMD::SET_ALLPTS_NORMAL);
set_brightness(contrast);
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void init()
{
reg_select_(0);
chip_enable_();
// toggle RST low to reset; CS low so it'll listen to us
// if (cs > 0)
// digitalWrite(cs, LOW);
// digitalWrite(rst, LOW);
// _delay_ms(500);
// digitalWrite(rst, HIGH);
write_(CMD::DISPLAY_OFF);
// LCD bias select
write_(CMD::SET_BIAS_7);
// ADC select
write_(CMD::SET_ADC_NORMAL);
// SHL select
write_(CMD::SET_COM_NORMAL);
// Initial display line
write_(CMD::SET_DISP_START_LINE);
// turn on voltage converter (VC=1, VR=0, VF=0)
write_(CMD::SET_POWER_CONTROL, 0x4);
// wait for 50% rising
utils::delay::milli_second(50);
// turn on voltage regulator (VC=1, VR=1, VF=0)
write_(CMD::SET_POWER_CONTROL, 0x6);
// wait >=50ms
utils::delay::milli_second(50);
// turn on voltage follower (VC=1, VR=1, VF=1)
write_(CMD::SET_POWER_CONTROL, 0x7);
// wait 10ms
utils::delay::milli_second(10);
// set lcd operating voltage (regulator resistor, ref voltage resistor)
write_(CMD::SET_RESISTOR_RATIO, 0x6);
}
//-----------------------------------------------------------------//
/*!
@brief コピー
@param[in] p フレームバッファソース
*/
//-----------------------------------------------------------------//
void copy(const uint8_t* p) {
uint8_t ofs = 0x00;
for(uint8_t page = 0; page < 8; ++page) {
reg_select_(0);
write_(CMD::SET_PAGE, page);
write_(CMD::SET_COLUMN_LOWER, ofs & 0x0f);
write_(CMD::SET_COLUMN_UPPER, ofs >> 4);
write_(CMD::RMW);
reg_select_(1);
for(uint8_t i = 0; i < 128; ++i) {
csi_.xchg(*p);
++p;
}
}
reg_select_(0);
}
};
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrt_fn.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:51:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _WRT_FN_HXX
#define _WRT_FN_HXX
#include "hintids.hxx" // fuer die Konstanten
// einige Forward-Deklarationen
class SwFmt;
class SwNode;
class SwCntntNode;
class Writer;
class SfxPoolItem;
class SfxItemSet;
/* Funktionspointer auf die Attribut-Write-Funktionen */
typedef Writer& (*FnAttrOut)( Writer&, const SfxPoolItem& );
typedef FnAttrOut SwAttrFnTab[ POOLATTR_END - POOLATTR_BEGIN ];
Writer& Out( const SwAttrFnTab, const SfxPoolItem&, Writer& );
Writer& Out_SfxItemSet( const SwAttrFnTab, Writer&, const SfxItemSet&,
BOOL bDeep, BOOL bTstForDefault = TRUE );
/* Funktionspointer auf die Node-Write-Funktionen */
enum RES_NODE
{
RES_NODE_BEGIN = 0,
RES_TXTNODE = RES_NODE_BEGIN,
RES_GRFNODE,
RES_OLENODE,
RES_NODE_END
};
typedef Writer& (*FnNodeOut)( Writer&, SwCntntNode& );
typedef FnNodeOut SwNodeFnTab[ RES_NODE_END - RES_NODE_BEGIN ];
Writer& Out( const SwNodeFnTab, SwNode&, Writer & rWrt );
#endif // _WRT_FN_HXX
<commit_msg>INTEGRATION: CWS writercorehandoff (1.1.1.1.1324); FILE MERGED 2005/09/13 15:07:54 tra 1.1.1.1.1324.2: RESYNC: (1.1.1.1-1.2); FILE MERGED 2005/06/07 14:14:56 fme 1.1.1.1.1324.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wrt_fn.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:09:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _WRT_FN_HXX
#define _WRT_FN_HXX
#include "hintids.hxx" // fuer die Konstanten
// einige Forward-Deklarationen
class SwNode;
class SwCntntNode;
class Writer;
class SfxPoolItem;
class SfxItemSet;
/* Funktionspointer auf die Attribut-Write-Funktionen */
typedef Writer& (*FnAttrOut)( Writer&, const SfxPoolItem& );
typedef FnAttrOut SwAttrFnTab[ POOLATTR_END - POOLATTR_BEGIN ];
Writer& Out( const SwAttrFnTab, const SfxPoolItem&, Writer& );
Writer& Out_SfxItemSet( const SwAttrFnTab, Writer&, const SfxItemSet&,
BOOL bDeep, BOOL bTstForDefault = TRUE );
/* Funktionspointer auf die Node-Write-Funktionen */
enum RES_NODE
{
RES_NODE_BEGIN = 0,
RES_TXTNODE = RES_NODE_BEGIN,
RES_GRFNODE,
RES_OLENODE,
RES_NODE_END
};
typedef Writer& (*FnNodeOut)( Writer&, SwCntntNode& );
typedef FnNodeOut SwNodeFnTab[ RES_NODE_END - RES_NODE_BEGIN ];
Writer& Out( const SwNodeFnTab, SwNode&, Writer & rWrt );
#endif // _WRT_FN_HXX
<|endoftext|>
|
<commit_before><commit_msg>revert hunk that makes sw_ooxmlexport tests fail<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conform.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:24:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SVX_FMGLOB_HXX //autogen
#include <svx/fmglob.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_FMSHELL_HXX //autogen
#include <svx/fmshell.hxx>
#endif
#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "drawbase.hxx"
#include "conform.hxx"
extern BOOL bNoInterrupt; // in mainwn.cxx
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
ConstFormControl::ConstFormControl(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
SwDrawBase(pWrtShell, pEditWin, pSwView)
{
m_bInsForm = TRUE;
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL ConstFormControl::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
SdrView *pSdrView = m_pSh->GetDrawView();
pSdrView->SetOrtho(rMEvt.IsShift());
pSdrView->SetAngleSnapEnabled(rMEvt.IsShift());
if (rMEvt.IsMod2())
{
pSdrView->SetCreate1stPointAsCenter(TRUE);
pSdrView->SetResizeAtCenter(TRUE);
}
else
{
pSdrView->SetCreate1stPointAsCenter(FALSE);
pSdrView->SetResizeAtCenter(FALSE);
}
SdrViewEvent aVEvt;
SdrHitKind eHit = pSdrView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt);
// Nur neues Objekt, wenn nicht im Basismode (bzw reinem Selektionsmode)
if (rMEvt.IsLeft() && !m_pWin->IsDrawAction() &&
(eHit == SDRHIT_UNMARKEDOBJECT || eHit == SDRHIT_NONE || m_pSh->IsDrawCreate()))
{
bNoInterrupt = TRUE;
m_pWin->CaptureMouse();
m_pWin->SetPointer(Pointer(POINTER_DRAW_RECT));
m_aStartPos = m_pWin->PixelToLogic(rMEvt.GetPosPixel());
bReturn = m_pSh->BeginCreate( static_cast< UINT16 >(m_pWin->GetSdrDrawMode()), FmFormInventor, m_aStartPos);
if (bReturn)
m_pWin->SetDrawAction(TRUE);
}
else
bReturn = SwDrawBase::MouseButtonDown(rMEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void ConstFormControl::Activate(const USHORT nSlotId)
{
m_pWin->SetSdrDrawMode( static_cast<SdrObjKind>(nSlotId) );
SwDrawBase::Activate(nSlotId);
m_pSh->GetDrawView()->SetCurrentObj(nSlotId);
m_pWin->SetPointer(Pointer(POINTER_DRAW_RECT));
}
/* -----------------------------19.04.2002 12:42------------------------------
---------------------------------------------------------------------------*/
void ConstFormControl::CreateDefaultObject()
{
Point aStartPos(GetDefaultCenterPos());
Point aEndPos(aStartPos);
aStartPos.X() -= 2 * MM50;
aStartPos.Y() -= MM50;
aEndPos.X() += 2 * MM50;
aEndPos.Y() += MM50;
if(!m_pSh->HasDrawView())
m_pSh->MakeDrawView();
SdrView *pSdrView = m_pSh->GetDrawView();
pSdrView->SetDesignMode(TRUE);
m_pSh->BeginCreate( static_cast< UINT16 >(m_pWin->GetSdrDrawMode()), FmFormInventor, aStartPos);
m_pSh->MoveCreate(aEndPos);
m_pSh->EndCreate(SDRCREATE_FORCEEND);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.9.242); FILE MERGED 2008/04/01 15:59:36 thb 1.9.242.2: #i85898# Stripping all external header guards 2008/03/31 16:59:20 rt 1.9.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conform.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <svx/fmglob.hxx>
#include <svx/svdview.hxx>
#include <svx/fmshell.hxx>
#include "view.hxx"
#include "edtwin.hxx"
#include "wrtsh.hxx"
#include "drawbase.hxx"
#include "conform.hxx"
extern BOOL bNoInterrupt; // in mainwn.cxx
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
ConstFormControl::ConstFormControl(SwWrtShell* pWrtShell, SwEditWin* pEditWin, SwView* pSwView) :
SwDrawBase(pWrtShell, pEditWin, pSwView)
{
m_bInsForm = TRUE;
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL ConstFormControl::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
SdrView *pSdrView = m_pSh->GetDrawView();
pSdrView->SetOrtho(rMEvt.IsShift());
pSdrView->SetAngleSnapEnabled(rMEvt.IsShift());
if (rMEvt.IsMod2())
{
pSdrView->SetCreate1stPointAsCenter(TRUE);
pSdrView->SetResizeAtCenter(TRUE);
}
else
{
pSdrView->SetCreate1stPointAsCenter(FALSE);
pSdrView->SetResizeAtCenter(FALSE);
}
SdrViewEvent aVEvt;
SdrHitKind eHit = pSdrView->PickAnything(rMEvt, SDRMOUSEBUTTONDOWN, aVEvt);
// Nur neues Objekt, wenn nicht im Basismode (bzw reinem Selektionsmode)
if (rMEvt.IsLeft() && !m_pWin->IsDrawAction() &&
(eHit == SDRHIT_UNMARKEDOBJECT || eHit == SDRHIT_NONE || m_pSh->IsDrawCreate()))
{
bNoInterrupt = TRUE;
m_pWin->CaptureMouse();
m_pWin->SetPointer(Pointer(POINTER_DRAW_RECT));
m_aStartPos = m_pWin->PixelToLogic(rMEvt.GetPosPixel());
bReturn = m_pSh->BeginCreate( static_cast< UINT16 >(m_pWin->GetSdrDrawMode()), FmFormInventor, m_aStartPos);
if (bReturn)
m_pWin->SetDrawAction(TRUE);
}
else
bReturn = SwDrawBase::MouseButtonDown(rMEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void ConstFormControl::Activate(const USHORT nSlotId)
{
m_pWin->SetSdrDrawMode( static_cast<SdrObjKind>(nSlotId) );
SwDrawBase::Activate(nSlotId);
m_pSh->GetDrawView()->SetCurrentObj(nSlotId);
m_pWin->SetPointer(Pointer(POINTER_DRAW_RECT));
}
/* -----------------------------19.04.2002 12:42------------------------------
---------------------------------------------------------------------------*/
void ConstFormControl::CreateDefaultObject()
{
Point aStartPos(GetDefaultCenterPos());
Point aEndPos(aStartPos);
aStartPos.X() -= 2 * MM50;
aStartPos.Y() -= MM50;
aEndPos.X() += 2 * MM50;
aEndPos.Y() += MM50;
if(!m_pSh->HasDrawView())
m_pSh->MakeDrawView();
SdrView *pSdrView = m_pSh->GetDrawView();
pSdrView->SetDesignMode(TRUE);
m_pSh->BeginCreate( static_cast< UINT16 >(m_pWin->GetSdrDrawMode()), FmFormInventor, aStartPos);
m_pSh->MoveCreate(aEndPos);
m_pSh->EndCreate(SDRCREATE_FORCEEND);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textidx.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:55:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include <hintids.hxx>
#include <uiparam.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _UIITEMS_HXX
#include <uiitems.hxx>
#endif
#include "viewopt.hxx"
#include "cmdid.h"
#include "view.hxx"
#include "wrtsh.hxx"
#include "swundo.hxx" // fuer Undo-Ids
#include "textsh.hxx"
#include "idxmrk.hxx"
//CHINA001 #include "multmrk.hxx"
#include "cnttab.hxx"
#include "toxmgr.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <index.hrc> //CHINA001
#include <globals.hrc> //CHINA001
// STATIC DATA -----------------------------------------------------------
void SwTextShell::ExecIdx(SfxRequest &rReq)
{
const SfxItemSet *pArgs = rReq.GetArgs();
const SfxPoolItem* pItem = 0;
USHORT nSlot = rReq.GetSlot();
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem );
SfxViewFrame* pVFrame = GetView().GetViewFrame();
Window *pMDI = &pVFrame->GetWindow();
switch( nSlot )
{
case FN_EDIT_AUTH_ENTRY_DLG :
{
//CHINA001 SwAuthMarkModalDlg* pDlg = new SwAuthMarkModalDlg(pMDI, GetShell());
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pDlg = pFact->CreateVclAbstractDialog( pMDI, GetShell(), ResId(DLG_EDIT_AUTHMARK) );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
case FN_INSERT_AUTH_ENTRY_DLG:
{
// no BASIC support
pVFrame->ToggleChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)
pVFrame->GetChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
Invalidate(rReq.GetSlot());
}
break;
case FN_INSERT_IDX_ENTRY_DLG:
{
pVFrame->ToggleChildWindow(FN_INSERT_IDX_ENTRY_DLG);
Invalidate(rReq.GetSlot());
}
break;
case FN_EDIT_IDX_ENTRY_DLG:
{
SwTOXMgr aMgr(GetShellPtr());
USHORT nRet = RET_OK;
if(aMgr.GetTOXMarkCount() > 1)
{ // Mehrere Marken, welche solls denn sein ?
//
//CHINA001 SwMultiTOXMarkDlg* pMultDlg = new SwMultiTOXMarkDlg(pMDI, aMgr);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pMultDlg = pFact->CreateMultiTOXMarkDlg( ResId(DLG_MULTMRK),
pMDI, aMgr);
DBG_ASSERT(pMultDlg, "Dialogdiet fail!");//CHINA001
nRet = pMultDlg->Execute();
delete pMultDlg;
}
if( nRet == RET_OK)
{
//CHINA001 SwIndexMarkModalDlg* pDlg = new SwIndexMarkModalDlg(pMDI, GetShell(), aMgr.GetCurTOXMark());
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pDlg = pFact->CreateIndexMarkModalDlg( ResId(DLG_EDIT_IDXMARK), pMDI, GetShell(), aMgr.GetCurTOXMark() );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
}
case FN_IDX_MARK_TO_IDX:
{
GetShell().GotoTOXMarkBase();
break;
}
case FN_INSERT_MULTI_TOX:
{
SfxItemSet aSet(GetPool(),
RES_COL, RES_COL,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
RES_LR_SPACE, RES_LR_SPACE,
FN_PARAM_TOX_TYPE, FN_PARAM_TOX_TYPE,
0 );
SwWrtShell& rSh = GetShell();
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
const SwTOXBase* pCurTOX = 0;
BOOL bGlobal = FALSE;
if(pItem)
{
pCurTOX = (const SwTOXBase* )((SwPtrItem*)pItem)->GetValue();
bGlobal = TRUE;
}
else
pCurTOX = rSh.GetCurTOX();
if(pCurTOX)
{
const SfxItemSet* pSet = pCurTOX->GetAttrSet();
if(pSet)
aSet.Put(*pSet);
}
//CHINA001 SwMultiTOXTabDialog* pDlg = new SwMultiTOXTabDialog(pMDI, aSet, rSh, (SwTOXBase* )pCurTOX,
//CHINA001 USHRT_MAX, bGlobal);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractMultiTOXTabDialog* pDlg = pFact->CreateMultiTOXTabDialog( ResId(DLG_MULTI_TOX),
pMDI, aSet, rSh, (SwTOXBase* )pCurTOX,
USHRT_MAX, bGlobal);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
case FN_REMOVE_CUR_TOX:
{
SwWrtShell& rSh = GetShell();
const SwTOXBase* pBase = rSh.GetCurTOX();
DBG_ASSERT(pBase, "no TOXBase to remove")
if( pBase )
rSh.DeleteTOX(*pBase, TRUE);
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwTextShell::GetIdxState(SfxItemSet &rSet)
{
SwWrtShell& rSh = GetShell();
SfxViewFrame* pVFrame = GetView().GetViewFrame();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)
pVFrame->GetChildWindow(FN_INSERT_IDX_ENTRY_DLG);
SfxChildWindow* pAuthMark = pVFrame->GetChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
const BOOL bHtmlMode = 0 != ::GetHtmlMode( GetView().GetDocShell() );
const SwTOXBase* pBase = 0;
if( bHtmlMode || 0 != ( pBase = rSh.GetCurTOX()) )
{
USHORT nBase = 0;
if( pBase )
{
if(pBase->IsTOXBaseInReadonly())
{
rSet.DisableItem( FN_INSERT_MULTI_TOX );
}
}
rSet.DisableItem( FN_EDIT_IDX_ENTRY_DLG );
rSet.DisableItem( FN_EDIT_AUTH_ENTRY_DLG );
if(!pIdxMrk)
rSet.DisableItem( FN_INSERT_IDX_ENTRY_DLG );
else
rSet.Put(SfxBoolItem(FN_INSERT_IDX_ENTRY_DLG, TRUE));
if(!pAuthMark)
rSet.DisableItem( FN_INSERT_AUTH_ENTRY_DLG );
else
rSet.Put(SfxBoolItem(FN_INSERT_AUTH_ENTRY_DLG, TRUE));
}
else //if( SFX_ITEM_UNKNOWN != rSet.GetItemState( FN_EDIT_IDX_ENTRY_DLG ))
{
BOOL bEnableEdit = TRUE;
BOOL bInReadonly = rSh.HasReadonlySel();
if( rSh.HasSelection() || bInReadonly)
bEnableEdit = FALSE;
else
{
SwTOXMarks aArr;
rSh.GetCurTOXMarks( aArr );
if( !aArr.Count())
bEnableEdit = FALSE;
}
if(!bEnableEdit)
rSet.DisableItem( FN_EDIT_IDX_ENTRY_DLG );
if(bInReadonly)
{
rSet.DisableItem(FN_INSERT_IDX_ENTRY_DLG);
rSet.DisableItem( FN_INSERT_MULTI_TOX );
}
else
rSet.Put(SfxBoolItem(FN_INSERT_IDX_ENTRY_DLG,
0 != pIdxMrk));
SwField* pField = rSh.GetCurFld();
if(bInReadonly)
rSet.DisableItem(FN_INSERT_AUTH_ENTRY_DLG);
else
rSet.Put(SfxBoolItem(FN_INSERT_AUTH_ENTRY_DLG, 0 != pAuthMark));
if( bInReadonly || !pField ||
pField->GetTyp()->Which() != RES_AUTHORITY)
rSet.DisableItem(FN_EDIT_AUTH_ENTRY_DLG);
rSet.DisableItem(FN_REMOVE_CUR_TOX);
}
}
// -----------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.2); FILE MERGED 2006/09/01 17:53:21 kaib 1.9.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textidx.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:17:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#include <uiparam.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _UIITEMS_HXX
#include <uiitems.hxx>
#endif
#include "viewopt.hxx"
#include "cmdid.h"
#include "view.hxx"
#include "wrtsh.hxx"
#include "swundo.hxx" // fuer Undo-Ids
#include "textsh.hxx"
#include "idxmrk.hxx"
//CHINA001 #include "multmrk.hxx"
#include "cnttab.hxx"
#include "toxmgr.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <index.hrc> //CHINA001
#include <globals.hrc> //CHINA001
// STATIC DATA -----------------------------------------------------------
void SwTextShell::ExecIdx(SfxRequest &rReq)
{
const SfxItemSet *pArgs = rReq.GetArgs();
const SfxPoolItem* pItem = 0;
USHORT nSlot = rReq.GetSlot();
if(pArgs)
pArgs->GetItemState(nSlot, FALSE, &pItem );
SfxViewFrame* pVFrame = GetView().GetViewFrame();
Window *pMDI = &pVFrame->GetWindow();
switch( nSlot )
{
case FN_EDIT_AUTH_ENTRY_DLG :
{
//CHINA001 SwAuthMarkModalDlg* pDlg = new SwAuthMarkModalDlg(pMDI, GetShell());
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pDlg = pFact->CreateVclAbstractDialog( pMDI, GetShell(), ResId(DLG_EDIT_AUTHMARK) );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
case FN_INSERT_AUTH_ENTRY_DLG:
{
// no BASIC support
pVFrame->ToggleChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)
pVFrame->GetChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
Invalidate(rReq.GetSlot());
}
break;
case FN_INSERT_IDX_ENTRY_DLG:
{
pVFrame->ToggleChildWindow(FN_INSERT_IDX_ENTRY_DLG);
Invalidate(rReq.GetSlot());
}
break;
case FN_EDIT_IDX_ENTRY_DLG:
{
SwTOXMgr aMgr(GetShellPtr());
USHORT nRet = RET_OK;
if(aMgr.GetTOXMarkCount() > 1)
{ // Mehrere Marken, welche solls denn sein ?
//
//CHINA001 SwMultiTOXMarkDlg* pMultDlg = new SwMultiTOXMarkDlg(pMDI, aMgr);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pMultDlg = pFact->CreateMultiTOXMarkDlg( ResId(DLG_MULTMRK),
pMDI, aMgr);
DBG_ASSERT(pMultDlg, "Dialogdiet fail!");//CHINA001
nRet = pMultDlg->Execute();
delete pMultDlg;
}
if( nRet == RET_OK)
{
//CHINA001 SwIndexMarkModalDlg* pDlg = new SwIndexMarkModalDlg(pMDI, GetShell(), aMgr.GetCurTOXMark());
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
VclAbstractDialog* pDlg = pFact->CreateIndexMarkModalDlg( ResId(DLG_EDIT_IDXMARK), pMDI, GetShell(), aMgr.GetCurTOXMark() );
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
}
case FN_IDX_MARK_TO_IDX:
{
GetShell().GotoTOXMarkBase();
break;
}
case FN_INSERT_MULTI_TOX:
{
SfxItemSet aSet(GetPool(),
RES_COL, RES_COL,
RES_BACKGROUND, RES_BACKGROUND,
RES_FRM_SIZE, RES_FRM_SIZE,
SID_ATTR_PAGE_SIZE, SID_ATTR_PAGE_SIZE,
RES_LR_SPACE, RES_LR_SPACE,
FN_PARAM_TOX_TYPE, FN_PARAM_TOX_TYPE,
0 );
SwWrtShell& rSh = GetShell();
SwRect aRect;
rSh.CalcBoundRect(aRect, FLY_IN_CNTNT);
long nWidth = aRect.Width();
aSet.Put(SwFmtFrmSize(ATT_VAR_SIZE, nWidth));
// Hoehe=Breite fuer konsistentere Vorschau (analog zu Bereich bearbeiten)
aSet.Put(SvxSizeItem(SID_ATTR_PAGE_SIZE, Size(nWidth, nWidth)));
const SwTOXBase* pCurTOX = 0;
BOOL bGlobal = FALSE;
if(pItem)
{
pCurTOX = (const SwTOXBase* )((SwPtrItem*)pItem)->GetValue();
bGlobal = TRUE;
}
else
pCurTOX = rSh.GetCurTOX();
if(pCurTOX)
{
const SfxItemSet* pSet = pCurTOX->GetAttrSet();
if(pSet)
aSet.Put(*pSet);
}
//CHINA001 SwMultiTOXTabDialog* pDlg = new SwMultiTOXTabDialog(pMDI, aSet, rSh, (SwTOXBase* )pCurTOX,
//CHINA001 USHRT_MAX, bGlobal);
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
AbstractMultiTOXTabDialog* pDlg = pFact->CreateMultiTOXTabDialog( ResId(DLG_MULTI_TOX),
pMDI, aSet, rSh, (SwTOXBase* )pCurTOX,
USHRT_MAX, bGlobal);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
pDlg->Execute();
delete pDlg;
}
break;
case FN_REMOVE_CUR_TOX:
{
SwWrtShell& rSh = GetShell();
const SwTOXBase* pBase = rSh.GetCurTOX();
DBG_ASSERT(pBase, "no TOXBase to remove")
if( pBase )
rSh.DeleteTOX(*pBase, TRUE);
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwTextShell::GetIdxState(SfxItemSet &rSet)
{
SwWrtShell& rSh = GetShell();
SfxViewFrame* pVFrame = GetView().GetViewFrame();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)
pVFrame->GetChildWindow(FN_INSERT_IDX_ENTRY_DLG);
SfxChildWindow* pAuthMark = pVFrame->GetChildWindow(FN_INSERT_AUTH_ENTRY_DLG);
const BOOL bHtmlMode = 0 != ::GetHtmlMode( GetView().GetDocShell() );
const SwTOXBase* pBase = 0;
if( bHtmlMode || 0 != ( pBase = rSh.GetCurTOX()) )
{
USHORT nBase = 0;
if( pBase )
{
if(pBase->IsTOXBaseInReadonly())
{
rSet.DisableItem( FN_INSERT_MULTI_TOX );
}
}
rSet.DisableItem( FN_EDIT_IDX_ENTRY_DLG );
rSet.DisableItem( FN_EDIT_AUTH_ENTRY_DLG );
if(!pIdxMrk)
rSet.DisableItem( FN_INSERT_IDX_ENTRY_DLG );
else
rSet.Put(SfxBoolItem(FN_INSERT_IDX_ENTRY_DLG, TRUE));
if(!pAuthMark)
rSet.DisableItem( FN_INSERT_AUTH_ENTRY_DLG );
else
rSet.Put(SfxBoolItem(FN_INSERT_AUTH_ENTRY_DLG, TRUE));
}
else //if( SFX_ITEM_UNKNOWN != rSet.GetItemState( FN_EDIT_IDX_ENTRY_DLG ))
{
BOOL bEnableEdit = TRUE;
BOOL bInReadonly = rSh.HasReadonlySel();
if( rSh.HasSelection() || bInReadonly)
bEnableEdit = FALSE;
else
{
SwTOXMarks aArr;
rSh.GetCurTOXMarks( aArr );
if( !aArr.Count())
bEnableEdit = FALSE;
}
if(!bEnableEdit)
rSet.DisableItem( FN_EDIT_IDX_ENTRY_DLG );
if(bInReadonly)
{
rSet.DisableItem(FN_INSERT_IDX_ENTRY_DLG);
rSet.DisableItem( FN_INSERT_MULTI_TOX );
}
else
rSet.Put(SfxBoolItem(FN_INSERT_IDX_ENTRY_DLG,
0 != pIdxMrk));
SwField* pField = rSh.GetCurFld();
if(bInReadonly)
rSet.DisableItem(FN_INSERT_AUTH_ENTRY_DLG);
else
rSet.Put(SfxBoolItem(FN_INSERT_AUTH_ENTRY_DLG, 0 != pAuthMark));
if( bInReadonly || !pField ||
pField->GetTyp()->Which() != RES_AUTHORITY)
rSet.DisableItem(FN_EDIT_AUTH_ENTRY_DLG);
rSet.DisableItem(FN_REMOVE_CUR_TOX);
}
}
// -----------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ZipPackageBuffer.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: mtg $ $Date: 2001-11-15 19:59:47 $
*
* 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): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_BUFFER_HXX
#define _ZIP_PACKAGE_BUFFER_HXX
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX
#include <cppuhelper/implbase3.hxx>
#endif
class ZipPackage;
class ZipPackageBuffer : public ::cppu::WeakImplHelper3
<
com::sun::star::io::XInputStream,
com::sun::star::io::XOutputStream,
com::sun::star::io::XSeekable
>
{
protected:
com::sun::star::uno::Sequence < sal_Int8 > m_aBuffer;
sal_Int64 m_nBufferSize, m_nEnd, m_nCurrent;
sal_Bool m_bMustInitBuffer;
public:
ZipPackageBuffer(sal_Int64 nNewBufferSize);
ZipPackageBuffer( com::sun::star::uno::Sequence < sal_Int8 > &nNewBuffer );
virtual ~ZipPackageBuffer(void);
inline void realloc ( sal_Int32 nSize ) { m_aBuffer.realloc ( nSize ); }
inline const sal_Int8 * getConstArray () const { return m_aBuffer.getConstArray(); }
inline const com::sun::star::uno::Sequence < sal_Int8> & getSequence () const { return m_aBuffer; }
// XInputStream
virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL available( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XOutputStream
virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XSeekable
virtual void SAL_CALL seek( sal_Int64 location )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getPosition( )
throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getLength( )
throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.15.218); FILE MERGED 2005/09/05 18:49:02 rt 1.15.218.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ZipPackageBuffer.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:59:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ZIP_PACKAGE_BUFFER_HXX
#define _ZIP_PACKAGE_BUFFER_HXX
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX
#include <cppuhelper/implbase3.hxx>
#endif
class ZipPackage;
class ZipPackageBuffer : public ::cppu::WeakImplHelper3
<
com::sun::star::io::XInputStream,
com::sun::star::io::XOutputStream,
com::sun::star::io::XSeekable
>
{
protected:
com::sun::star::uno::Sequence < sal_Int8 > m_aBuffer;
sal_Int64 m_nBufferSize, m_nEnd, m_nCurrent;
sal_Bool m_bMustInitBuffer;
public:
ZipPackageBuffer(sal_Int64 nNewBufferSize);
ZipPackageBuffer( com::sun::star::uno::Sequence < sal_Int8 > &nNewBuffer );
virtual ~ZipPackageBuffer(void);
inline void realloc ( sal_Int32 nSize ) { m_aBuffer.realloc ( nSize ); }
inline const sal_Int8 * getConstArray () const { return m_aBuffer.getConstArray(); }
inline const com::sun::star::uno::Sequence < sal_Int8> & getSequence () const { return m_aBuffer; }
// XInputStream
virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL available( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XOutputStream
virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL flush( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeOutput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XSeekable
virtual void SAL_CALL seek( sal_Int64 location )
throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getPosition( )
throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int64 SAL_CALL getLength( )
throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>/*
* cam_ZWO.cpp
* PHD Guiding
*
* Created by Robin Glover.
* Copyright (c) 2014 Robin Glover.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
#ifdef ZWO_ASI
#include "cam_ZWO.h"
#include "cameras/ASICamera2.h"
#ifdef __WINDOWS__
# include <Shlwapi.h>
# include <DelayImp.h>
#endif
Camera_ZWO::Camera_ZWO()
: m_buffer(0),
m_capturing(false)
{
Name = _T("ZWO ASI Camera");
Connected = false;
m_hasGuideOutput = true;
HasSubframes = true;
HasGainControl = true; // workaround: ok to set to false later, but brain dialog will frash if we start false then change to true later when the camera is connected
}
Camera_ZWO::~Camera_ZWO()
{
delete[] m_buffer;
}
inline static int cam_gain(int minval, int maxval, int pct)
{
return minval + pct * (maxval - minval) / 100;
}
inline static int gain_pct(int minval, int maxval, int val)
{
return (val - minval) * 100 / (maxval - minval);
}
#ifdef __WINDOWS__
#define FACILITY_VISUALCPP ((LONG)0x6d)
#define VcppException(sev,err) ((sev) | (FACILITY_VISUALCPP<<16) | err)
static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, wxString *err)
{
LONG lDisposition = EXCEPTION_EXECUTE_HANDLER;
PDelayLoadInfo pdli = PDelayLoadInfo(pExcPointers->ExceptionRecord->ExceptionInformation[0]);
switch (pExcPointers->ExceptionRecord->ExceptionCode)
{
case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): {
// ASICamera2.dll depends on the VC++ 2008 runtime, check for that
HMODULE hm = LoadLibraryEx(_T("MSVCR90.DLL"), NULL, LOAD_LIBRARY_AS_DATAFILE);
if (hm)
{
FreeLibrary(hm);
*err = wxString::Format(_("Could not load DLL %s"), pdli->szDll);
}
else
*err = _("The ASI camera library requires the Microsoft Visual C++ 2008 Redistributable Package (x86), available at http://www.microsoft.com/en-us/download/details.aspx?id=29");
break;
}
case VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND):
if (pdli->dlp.fImportByName)
*err = wxString::Format("Function %s was not found in %s", pdli->dlp.szProcName, pdli->szDll);
else
*err = wxString::Format("Function ordinal %d was not found in %s", pdli->dlp.dwOrdinal, pdli->szDll);
break;
default:
// Exception is not related to delay loading
lDisposition = EXCEPTION_CONTINUE_SEARCH;
break;
}
return lDisposition;
}
static bool TryLoadDll(wxString *err)
{
__try {
ASIGetNumOfConnectedCameras();
return true;
}
__except (DelayLoadDllExceptionFilter(GetExceptionInformation(), err)) {
return false;
}
}
#else // __WINDOWS__
static bool TryLoadDll(wxString *err)
{
return true;
}
#endif // __WINDOWS__
bool Camera_ZWO::Connect()
{
wxString err;
if (!TryLoadDll(&err))
{
wxMessageBox(err, _("Error"), wxOK | wxICON_ERROR);
return true;
}
// Find available cameras
int numCameras = ASIGetNumOfConnectedCameras();
if (numCameras == 0)
{
wxMessageBox(_T("No ZWO cameras detected."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
wxArrayString USBNames;
for (int i = 0; i < numCameras; i++)
{
ASI_CAMERA_INFO info;
if (ASIGetCameraProperty(&info, i) == ASI_SUCCESS)
USBNames.Add(info.Name);
}
int selected = 0;
if (USBNames.Count() > 1)
{
selected = wxGetSingleChoiceIndex(_("Select camera"), _("Camera name"), USBNames);
if (selected == -1)
return true;
}
ASI_CAMERA_INFO info;
if (ASIGetCameraProperty(&info, selected) != ASI_SUCCESS)
{
wxMessageBox(_("Failed to get camera properties for ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if (ASIOpenCamera(selected) != ASI_SUCCESS)
{
wxMessageBox(_("Failed to open ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
m_cameraId = selected;
Connected = true;
Name = info.Name;
FullSize.x = info.MaxWidth;
FullSize.y = info.MaxHeight;
delete[] m_buffer;
m_buffer = new unsigned char[FullSize.x * FullSize.y];
PixelSize = info.PixelSize;
int numControls;
if (ASIGetNumOfControls(m_cameraId, &numControls) != ASI_SUCCESS)
{
Disconnect();
wxMessageBox(_("Failed to get camera properties for ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
HasGainControl = false;
for (int i = 0; i < numControls; i++)
{
ASI_CONTROL_CAPS caps;
if (ASIGetControlCaps(m_cameraId, i, &caps) == ASI_SUCCESS)
{
switch (caps.ControlType)
{
case ASI_GAIN:
if (caps.IsWritable)
{
HasGainControl = true;
m_gainControlId = caps.ControlID;
m_minGain = caps.MinValue;
m_maxGain = caps.MaxVale;
}
break;
case ASI_EXPOSURE:
m_exposureControlId = caps.ControlID;
break;
case ASI_BANDWIDTHOVERLOAD:
ASISetControlValue(m_cameraId, caps.ControlID, caps.MinValue, ASI_FALSE);
break;
default:
break;
}
}
}
m_frame = wxRect(FullSize);
Debug.AddLine("ZWO: frame (%d,%d)+(%d,%d)", m_frame.x, m_frame.y, m_frame.width, m_frame.height);
ASISetStartPos(m_cameraId, m_frame.GetLeft(), m_frame.GetTop());
ASISetROIFormat(m_cameraId, m_frame.GetWidth(), m_frame.GetHeight(), 1, ASI_IMG_Y8);
return false;
}
bool Camera_ZWO::Disconnect()
{
ASIStopVideoCapture(m_cameraId);
m_capturing = false;
ASICloseCamera(m_cameraId);
Connected = false;
delete[] m_buffer;
m_buffer = 0;
return false;
}
inline static int round_down(int v, int m)
{
return v & ~(m - 1);
}
inline static int round_up(int v, int m)
{
return round_down(v + m - 1, m);
}
static void flush_buffered_image(int cameraId, usImage& img)
{
// clear buffered image?
ASI_ERROR_CODE status;
do
{
status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned short), 0);
if (status == ASI_SUCCESS)
Debug.AddLine("ZWO: getimagedata clearbuf ret %d", status);
} while (status == ASI_SUCCESS);
}
bool Camera_ZWO::Capture(int duration, usImage& img, wxRect subframe, bool recon)
{
if (img.Init(FullSize))
{
pFrame->Alert(_("Memory allocation error during capture"));
Disconnect();
return true;
}
wxRect frame;
wxPoint subframePos; // position of subframe within frame
bool useSubframe = UseSubframes;
if (subframe.width <= 0 || subframe.height <= 0)
useSubframe = false;
if (useSubframe)
{
// ensure transfer size is a multiple of 1024
// moving the sub-frame or resizing it is somewhat costly (stopCapture / startCapture)
frame.SetLeft(round_down(subframe.GetLeft(), 32));
frame.SetRight(round_up(subframe.GetRight() + 1, 32) - 1);
frame.SetTop(round_down(subframe.GetTop(), 32));
frame.SetBottom(round_up(subframe.GetBottom() + 1, 32) - 1);
subframePos = subframe.GetLeftTop() - frame.GetLeftTop();
}
else
{
frame = wxRect(FullSize);
}
long exposureUS = duration * 1000;
ASI_BOOL tmp;
long cur_exp;
bool exp_change = false;
if (ASIGetControlValue(m_cameraId, m_exposureControlId, &cur_exp, &tmp) == ASI_SUCCESS &&
cur_exp != exposureUS)
{
Debug.AddLine("ZWO: set CONTROL_EXPOSURE %d", exposureUS);
ASISetControlValue(m_cameraId, m_exposureControlId, exposureUS, ASI_FALSE);
exp_change = true;
}
long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain);
long cur_gain;
bool gain_change = false;
if (ASIGetControlValue(m_cameraId, m_gainControlId, &cur_gain, &tmp) == ASI_SUCCESS &&
new_gain != cur_gain)
{
Debug.AddLine("ZWO: set CONTROL_GAIN %d%% %d", GuideCameraGain, new_gain);
ASISetControlValue(m_cameraId, m_gainControlId, new_gain, ASI_FALSE);
gain_change = true;
}
bool size_change = frame.GetSize() != m_frame.GetSize();
bool pos_change = frame.GetLeftTop() != m_frame.GetLeftTop();
if (size_change || pos_change)
{
m_frame = frame;
Debug.AddLine("ZWO: frame (%d,%d)+(%d,%d)", m_frame.x, m_frame.y, m_frame.width, m_frame.height);
}
if (size_change)
{
if (m_capturing)
{
Debug.AddLine("ZWO: stopcapture");
ASIStopVideoCapture(m_cameraId);
m_capturing = false;
}
ASI_ERROR_CODE status = ASISetROIFormat(m_cameraId, frame.GetWidth(), frame.GetHeight(), 1, ASI_IMG_Y8);
if (status != ASI_SUCCESS)
Debug.AddLine("ZWO: setImageFormat(%d,%d) => %d", frame.GetWidth(), frame.GetHeight(), status);
}
if (pos_change)
{
ASI_ERROR_CODE status = ASISetStartPos(m_cameraId, frame.GetLeft(), frame.GetTop());
if (status != ASI_SUCCESS)
Debug.AddLine("ZWO: setStartPos(%d,%d) => %d", frame.GetLeft(), frame.GetTop(), status);
}
// the camera and/or driver will buffer frames and return the oldest frame,
// which could be quite stale. read out all buffered frames so the frame we
// get is current
flush_buffered_image(m_cameraId, img);
if (!m_capturing)
{
Debug.AddLine("ZWO: startcapture");
ASIStartVideoCapture(m_cameraId);
m_capturing = true;
}
int frameSize = frame.GetWidth() * frame.GetHeight();
long timeout = duration * 2 + 15000;
int poll = wxMin(duration, 100);
wxStopWatch timer;
::wxMilliSleep(duration);
ASI_ERROR_CODE status;
do
{
status = ASIGetVideoData(m_cameraId, m_buffer, frameSize, poll);
} while (status != ASI_SUCCESS && timer.Time() <= timeout);
if (status != ASI_SUCCESS)
{
Debug.AddLine("ZWO: getimagedata ret %d", status);
return true;
}
if (useSubframe)
{
img.Subframe = subframe;
// Clear out the image
img.Clear();
for (int y = 0; y < subframe.height; y++)
{
const unsigned char *src = m_buffer + (y + subframePos.y) * frame.width + subframePos.x;
unsigned short *dst = img.ImageData + (y + subframe.y) * FullSize.GetWidth() + subframe.x;
for (int x = 0; x < subframe.width; x++)
*dst++ = *src++;
}
}
else
{
for (int i = 0; i < img.NPixels; i++)
img.ImageData[i] = m_buffer[i];
}
if (recon) SubtractDark(img);
return false;
}
inline static ASI_GUIDE_DIRECTION GetASIDirection(int direction)
{
switch (direction)
{
default:
case NORTH:
return ASI_GUIDE_NORTH;
case EAST:
return ASI_GUIDE_EAST;
case WEST:
return ASI_GUIDE_WEST;
case SOUTH:
return ASI_GUIDE_SOUTH;
}
}
bool Camera_ZWO::ST4PulseGuideScope(int direction, int duration)
{
ASI_GUIDE_DIRECTION d = GetASIDirection(direction);
ASIPulseGuideOn(m_cameraId, d);
wxMilliSleep(duration);
ASIPulseGuideOff(m_cameraId, d);
return false;
}
void Camera_ZWO::ClearGuidePort()
{
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_NORTH);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_SOUTH);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_EAST);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_WEST);
}
#endif // ZWO_ASI
<commit_msg>- fix linux build which uses -Werror=unused-but-set-variable<commit_after>/*
* cam_ZWO.cpp
* PHD Guiding
*
* Created by Robin Glover.
* Copyright (c) 2014 Robin Glover.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
#ifdef ZWO_ASI
#include "cam_ZWO.h"
#include "cameras/ASICamera2.h"
#ifdef __WINDOWS__
# include <Shlwapi.h>
# include <DelayImp.h>
#endif
Camera_ZWO::Camera_ZWO()
: m_buffer(0),
m_capturing(false)
{
Name = _T("ZWO ASI Camera");
Connected = false;
m_hasGuideOutput = true;
HasSubframes = true;
HasGainControl = true; // workaround: ok to set to false later, but brain dialog will frash if we start false then change to true later when the camera is connected
}
Camera_ZWO::~Camera_ZWO()
{
delete[] m_buffer;
}
inline static int cam_gain(int minval, int maxval, int pct)
{
return minval + pct * (maxval - minval) / 100;
}
inline static int gain_pct(int minval, int maxval, int val)
{
return (val - minval) * 100 / (maxval - minval);
}
#ifdef __WINDOWS__
#define FACILITY_VISUALCPP ((LONG)0x6d)
#define VcppException(sev,err) ((sev) | (FACILITY_VISUALCPP<<16) | err)
static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, wxString *err)
{
LONG lDisposition = EXCEPTION_EXECUTE_HANDLER;
PDelayLoadInfo pdli = PDelayLoadInfo(pExcPointers->ExceptionRecord->ExceptionInformation[0]);
switch (pExcPointers->ExceptionRecord->ExceptionCode)
{
case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): {
// ASICamera2.dll depends on the VC++ 2008 runtime, check for that
HMODULE hm = LoadLibraryEx(_T("MSVCR90.DLL"), NULL, LOAD_LIBRARY_AS_DATAFILE);
if (hm)
{
FreeLibrary(hm);
*err = wxString::Format(_("Could not load DLL %s"), pdli->szDll);
}
else
*err = _("The ASI camera library requires the Microsoft Visual C++ 2008 Redistributable Package (x86), available at http://www.microsoft.com/en-us/download/details.aspx?id=29");
break;
}
case VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND):
if (pdli->dlp.fImportByName)
*err = wxString::Format("Function %s was not found in %s", pdli->dlp.szProcName, pdli->szDll);
else
*err = wxString::Format("Function ordinal %d was not found in %s", pdli->dlp.dwOrdinal, pdli->szDll);
break;
default:
// Exception is not related to delay loading
lDisposition = EXCEPTION_CONTINUE_SEARCH;
break;
}
return lDisposition;
}
static bool TryLoadDll(wxString *err)
{
__try {
ASIGetNumOfConnectedCameras();
return true;
}
__except (DelayLoadDllExceptionFilter(GetExceptionInformation(), err)) {
return false;
}
}
#else // __WINDOWS__
static bool TryLoadDll(wxString *err)
{
return true;
}
#endif // __WINDOWS__
bool Camera_ZWO::Connect()
{
wxString err;
if (!TryLoadDll(&err))
{
wxMessageBox(err, _("Error"), wxOK | wxICON_ERROR);
return true;
}
// Find available cameras
int numCameras = ASIGetNumOfConnectedCameras();
if (numCameras == 0)
{
wxMessageBox(_T("No ZWO cameras detected."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
wxArrayString USBNames;
for (int i = 0; i < numCameras; i++)
{
ASI_CAMERA_INFO info;
if (ASIGetCameraProperty(&info, i) == ASI_SUCCESS)
USBNames.Add(info.Name);
}
int selected = 0;
if (USBNames.Count() > 1)
{
selected = wxGetSingleChoiceIndex(_("Select camera"), _("Camera name"), USBNames);
if (selected == -1)
return true;
}
ASI_CAMERA_INFO info;
if (ASIGetCameraProperty(&info, selected) != ASI_SUCCESS)
{
wxMessageBox(_("Failed to get camera properties for ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
if (ASIOpenCamera(selected) != ASI_SUCCESS)
{
wxMessageBox(_("Failed to open ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
m_cameraId = selected;
Connected = true;
Name = info.Name;
FullSize.x = info.MaxWidth;
FullSize.y = info.MaxHeight;
delete[] m_buffer;
m_buffer = new unsigned char[FullSize.x * FullSize.y];
PixelSize = info.PixelSize;
int numControls;
if (ASIGetNumOfControls(m_cameraId, &numControls) != ASI_SUCCESS)
{
Disconnect();
wxMessageBox(_("Failed to get camera properties for ZWO ASI Camera."), _("Error"), wxOK | wxICON_ERROR);
return true;
}
HasGainControl = false;
for (int i = 0; i < numControls; i++)
{
ASI_CONTROL_CAPS caps;
if (ASIGetControlCaps(m_cameraId, i, &caps) == ASI_SUCCESS)
{
switch (caps.ControlType)
{
case ASI_GAIN:
if (caps.IsWritable)
{
HasGainControl = true;
m_gainControlId = caps.ControlID;
m_minGain = caps.MinValue;
m_maxGain = caps.MaxVale;
}
break;
case ASI_EXPOSURE:
m_exposureControlId = caps.ControlID;
break;
case ASI_BANDWIDTHOVERLOAD:
ASISetControlValue(m_cameraId, caps.ControlID, caps.MinValue, ASI_FALSE);
break;
default:
break;
}
}
}
m_frame = wxRect(FullSize);
Debug.AddLine("ZWO: frame (%d,%d)+(%d,%d)", m_frame.x, m_frame.y, m_frame.width, m_frame.height);
ASISetStartPos(m_cameraId, m_frame.GetLeft(), m_frame.GetTop());
ASISetROIFormat(m_cameraId, m_frame.GetWidth(), m_frame.GetHeight(), 1, ASI_IMG_Y8);
return false;
}
bool Camera_ZWO::Disconnect()
{
ASIStopVideoCapture(m_cameraId);
m_capturing = false;
ASICloseCamera(m_cameraId);
Connected = false;
delete[] m_buffer;
m_buffer = 0;
return false;
}
inline static int round_down(int v, int m)
{
return v & ~(m - 1);
}
inline static int round_up(int v, int m)
{
return round_down(v + m - 1, m);
}
static void flush_buffered_image(int cameraId, usImage& img)
{
// clear buffered image?
ASI_ERROR_CODE status;
do
{
status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned short), 0);
if (status == ASI_SUCCESS)
Debug.AddLine("ZWO: getimagedata clearbuf ret %d", status);
} while (status == ASI_SUCCESS);
}
bool Camera_ZWO::Capture(int duration, usImage& img, wxRect subframe, bool recon)
{
if (img.Init(FullSize))
{
pFrame->Alert(_("Memory allocation error during capture"));
Disconnect();
return true;
}
wxRect frame;
wxPoint subframePos; // position of subframe within frame
bool useSubframe = UseSubframes;
if (subframe.width <= 0 || subframe.height <= 0)
useSubframe = false;
if (useSubframe)
{
// ensure transfer size is a multiple of 1024
// moving the sub-frame or resizing it is somewhat costly (stopCapture / startCapture)
frame.SetLeft(round_down(subframe.GetLeft(), 32));
frame.SetRight(round_up(subframe.GetRight() + 1, 32) - 1);
frame.SetTop(round_down(subframe.GetTop(), 32));
frame.SetBottom(round_up(subframe.GetBottom() + 1, 32) - 1);
subframePos = subframe.GetLeftTop() - frame.GetLeftTop();
}
else
{
frame = wxRect(FullSize);
}
long exposureUS = duration * 1000;
ASI_BOOL tmp;
long cur_exp;
// bool exp_change = false;
if (ASIGetControlValue(m_cameraId, m_exposureControlId, &cur_exp, &tmp) == ASI_SUCCESS &&
cur_exp != exposureUS)
{
Debug.AddLine("ZWO: set CONTROL_EXPOSURE %d", exposureUS);
ASISetControlValue(m_cameraId, m_exposureControlId, exposureUS, ASI_FALSE);
// exp_change = true;
}
long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain);
long cur_gain;
// bool gain_change = false;
if (ASIGetControlValue(m_cameraId, m_gainControlId, &cur_gain, &tmp) == ASI_SUCCESS &&
new_gain != cur_gain)
{
Debug.AddLine("ZWO: set CONTROL_GAIN %d%% %d", GuideCameraGain, new_gain);
ASISetControlValue(m_cameraId, m_gainControlId, new_gain, ASI_FALSE);
// gain_change = true;
}
bool size_change = frame.GetSize() != m_frame.GetSize();
bool pos_change = frame.GetLeftTop() != m_frame.GetLeftTop();
if (size_change || pos_change)
{
m_frame = frame;
Debug.AddLine("ZWO: frame (%d,%d)+(%d,%d)", m_frame.x, m_frame.y, m_frame.width, m_frame.height);
}
if (size_change)
{
if (m_capturing)
{
Debug.AddLine("ZWO: stopcapture");
ASIStopVideoCapture(m_cameraId);
m_capturing = false;
}
ASI_ERROR_CODE status = ASISetROIFormat(m_cameraId, frame.GetWidth(), frame.GetHeight(), 1, ASI_IMG_Y8);
if (status != ASI_SUCCESS)
Debug.AddLine("ZWO: setImageFormat(%d,%d) => %d", frame.GetWidth(), frame.GetHeight(), status);
}
if (pos_change)
{
ASI_ERROR_CODE status = ASISetStartPos(m_cameraId, frame.GetLeft(), frame.GetTop());
if (status != ASI_SUCCESS)
Debug.AddLine("ZWO: setStartPos(%d,%d) => %d", frame.GetLeft(), frame.GetTop(), status);
}
// the camera and/or driver will buffer frames and return the oldest frame,
// which could be quite stale. read out all buffered frames so the frame we
// get is current
flush_buffered_image(m_cameraId, img);
if (!m_capturing)
{
Debug.AddLine("ZWO: startcapture");
ASIStartVideoCapture(m_cameraId);
m_capturing = true;
}
int frameSize = frame.GetWidth() * frame.GetHeight();
long timeout = duration * 2 + 15000;
int poll = wxMin(duration, 100);
wxStopWatch timer;
::wxMilliSleep(duration);
ASI_ERROR_CODE status;
do
{
status = ASIGetVideoData(m_cameraId, m_buffer, frameSize, poll);
} while (status != ASI_SUCCESS && timer.Time() <= timeout);
if (status != ASI_SUCCESS)
{
Debug.AddLine("ZWO: getimagedata ret %d", status);
return true;
}
if (useSubframe)
{
img.Subframe = subframe;
// Clear out the image
img.Clear();
for (int y = 0; y < subframe.height; y++)
{
const unsigned char *src = m_buffer + (y + subframePos.y) * frame.width + subframePos.x;
unsigned short *dst = img.ImageData + (y + subframe.y) * FullSize.GetWidth() + subframe.x;
for (int x = 0; x < subframe.width; x++)
*dst++ = *src++;
}
}
else
{
for (int i = 0; i < img.NPixels; i++)
img.ImageData[i] = m_buffer[i];
}
if (recon) SubtractDark(img);
return false;
}
inline static ASI_GUIDE_DIRECTION GetASIDirection(int direction)
{
switch (direction)
{
default:
case NORTH:
return ASI_GUIDE_NORTH;
case EAST:
return ASI_GUIDE_EAST;
case WEST:
return ASI_GUIDE_WEST;
case SOUTH:
return ASI_GUIDE_SOUTH;
}
}
bool Camera_ZWO::ST4PulseGuideScope(int direction, int duration)
{
ASI_GUIDE_DIRECTION d = GetASIDirection(direction);
ASIPulseGuideOn(m_cameraId, d);
wxMilliSleep(duration);
ASIPulseGuideOff(m_cameraId, d);
return false;
}
void Camera_ZWO::ClearGuidePort()
{
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_NORTH);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_SOUTH);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_EAST);
ASIPulseGuideOff(m_cameraId, ASI_GUIDE_WEST);
}
#endif // ZWO_ASI
<|endoftext|>
|
<commit_before>#include "task.h"
#include "lua_moo.h"
#include "objectmanager.h"
#include <QDateTime>
const char *Task::mPrepositionList[] =
{
"with/using",
"at/to",
"in front of",
"in/inside/into",
"on top of/on/onto/upon",
"out of/from inside/from",
"over",
"through",
"under/underneath/beneath",
"behind",
"beside",
"for/about",
"is",
"as",
"off/off of",
"up",
0
};
Task::Task( const QString &pCommand ) : mCommand( pCommand )
{
mProgrammerId = OBJECT_NONE;
mTimeStamp = QDateTime::currentMSecsSinceEpoch();
mPlayer = OBJECT_NONE;
mObject = OBJECT_NONE;
mCaller = OBJECT_NONE;
mDirectObjectId = OBJECT_NONE;
mIndirectObjectId = OBJECT_NONE;
}
Task::Task( const TaskEntry &pEntry )
{
mProgrammerId = pEntry.playerid();
mId = pEntry.id();
mTimeStamp = pEntry.timestamp();
mCommand = pEntry.command();
mPlayer = pEntry.playerid();
mObject = OBJECT_NONE;
mCaller = OBJECT_NONE;
mDirectObjectId = OBJECT_NONE;
mIndirectObjectId = OBJECT_NONE;
}
Task::~Task( void )
{
}
void Task::findObject( const QString &pName, QList<ObjectId> &pId ) const
{
if( pName.isEmpty() )
{
return;
}
if( pName.startsWith( "#" ) )
{
bool ok;
int id = pName.mid( 1 ).toInt( &ok );
if( ok && ObjectManager::instance()->object( id ) != 0 )
{
pId.append( id );
return;
}
return;
}
if( pName == "me" )
{
pId.append( player() );
return;
}
if( pName == "here" )
{
Object *Player;
if( ( Player = ObjectManager::instance()->object( player() ) ) != 0 )
{
pId.append( Player->location() );
}
}
// Otherwise, the server considers all of the objects whose location is either the player
// (i.e., the objects the player is "holding", so to speak)
Object *Player;
if( ( Player = ObjectManager::instance()->object( player() ) ) != 0 )
{
const QList<ObjectId> &Contents = Player->contents();
foreach( ObjectId id, Contents )
{
Object *Object;
if( ( Object = ObjectManager::instance()->object( id ) ) != 0 )
{
if( Object->matchName( pName ) )
{
pId.append( id );
}
}
}
// or the room the player is in (i.e., the objects in the same room as the player);
// it will try to match the object string against the various names for these objects.
Object *Location;
if( ( Location = ObjectManager::instance()->object( Player->location() ) ) != 0 )
{
if( Location->matchName( pName ) )
{
pId.append( Location->id() );
}
const QList<ObjectId> &Contents = Location->contents();
foreach( ObjectId id, Contents )
{
Object *Object;
if( ( Object = ObjectManager::instance()->object( id ) ) != 0 )
{
if( Object->matchName( pName ) )
{
pId.append( id );
}
}
}
}
}
}
int Task::findPreposition( const QStringList &pWords )
{
mPreposition.clear();
for( int i = 0 ; i < pWords.size() && mPreposition.isEmpty() ; i++ )
{
const QString CurWrd = pWords.at( i );
for( const char **p = mPrepositionList ; *p != 0 ; p++ )
{
QString s( *p );
QStringList PrpSet = s.split( '/' );
if( PrpSet.contains( CurWrd ) )
{
mPreposition = CurWrd;
return( i );
}
}
}
return( pWords.size() );
}
void Task::getDirectAndIndirect( const QStringList &pWords, int pPrpIdx )
{
mDirectObjectName.clear();
mIndirectObjectName.clear();
for( int i = 0 ; i < pWords.size() ; i++ )
{
if( i < pPrpIdx )
{
if( !mDirectObjectName.isEmpty() )
{
mDirectObjectName.append( " " );
}
mDirectObjectName.append( pWords.at( i ) );
}
else if( i > pPrpIdx )
{
if( !mIndirectObjectName.isEmpty() )
{
mIndirectObjectName.append( " " );
}
mIndirectObjectName.append( pWords.at( i ) );
}
}
}
<commit_msg>Added support for $object look ups (equivalent to object id in #0.object)<commit_after>#include "task.h"
#include "lua_moo.h"
#include "objectmanager.h"
#include "lua_object.h"
#include <QDateTime>
const char *Task::mPrepositionList[] =
{
"with/using",
"at/to",
"in front of",
"in/inside/into",
"on top of/on/onto/upon",
"out of/from inside/from",
"over",
"through",
"under/underneath/beneath",
"behind",
"beside",
"for/about",
"is",
"as",
"off/off of",
"up",
0
};
Task::Task( const QString &pCommand ) : mCommand( pCommand )
{
mProgrammerId = OBJECT_NONE;
mTimeStamp = QDateTime::currentMSecsSinceEpoch();
mPlayer = OBJECT_NONE;
mObject = OBJECT_NONE;
mCaller = OBJECT_NONE;
mDirectObjectId = OBJECT_NONE;
mIndirectObjectId = OBJECT_NONE;
}
Task::Task( const TaskEntry &pEntry )
{
mProgrammerId = pEntry.playerid();
mId = pEntry.id();
mTimeStamp = pEntry.timestamp();
mCommand = pEntry.command();
mPlayer = pEntry.playerid();
mObject = OBJECT_NONE;
mCaller = OBJECT_NONE;
mDirectObjectId = OBJECT_NONE;
mIndirectObjectId = OBJECT_NONE;
}
Task::~Task( void )
{
}
void Task::findObject( const QString &pName, QList<ObjectId> &pId ) const
{
if( pName.isEmpty() )
{
return;
}
if( pName.startsWith( "#" ) )
{
bool ok;
int id = pName.mid( 1 ).toInt( &ok );
if( ok && ObjectManager::instance()->object( id ) != 0 )
{
pId.append( id );
return;
}
return;
}
if( pName.startsWith( "$" ) )
{
Object *R = ObjectManager::o( 0 );
if( R )
{
Property *P = R->prop( pName.mid( 1 ) );
if( P )
{
ObjectId OID = OBJECT_NONE;
if( P->value().type() == QVariant::Int )
{
OID = P->value().toInt();
}
else
{
lua_object::luaHandle H = P->value().value<lua_object::luaHandle>();
OID = H.O;
}
pId.append( OID );
}
}
return;
}
if( pName == "me" )
{
pId.append( player() );
return;
}
if( pName == "here" )
{
Object *Player;
if( ( Player = ObjectManager::instance()->object( player() ) ) != 0 )
{
pId.append( Player->location() );
}
}
// Otherwise, the server considers all of the objects whose location is either the player
// (i.e., the objects the player is "holding", so to speak)
Object *Player;
if( ( Player = ObjectManager::instance()->object( player() ) ) != 0 )
{
const QList<ObjectId> &Contents = Player->contents();
foreach( ObjectId id, Contents )
{
Object *Object;
if( ( Object = ObjectManager::instance()->object( id ) ) != 0 )
{
if( Object->matchName( pName ) )
{
pId.append( id );
}
}
}
// or the room the player is in (i.e., the objects in the same room as the player);
// it will try to match the object string against the various names for these objects.
Object *Location;
if( ( Location = ObjectManager::instance()->object( Player->location() ) ) != 0 )
{
if( Location->matchName( pName ) )
{
pId.append( Location->id() );
}
const QList<ObjectId> &Contents = Location->contents();
foreach( ObjectId id, Contents )
{
Object *Object;
if( ( Object = ObjectManager::instance()->object( id ) ) != 0 )
{
if( Object->matchName( pName ) )
{
pId.append( id );
}
}
}
}
}
}
int Task::findPreposition( const QStringList &pWords )
{
mPreposition.clear();
for( int i = 0 ; i < pWords.size() && mPreposition.isEmpty() ; i++ )
{
const QString CurWrd = pWords.at( i );
for( const char **p = mPrepositionList ; *p != 0 ; p++ )
{
QString s( *p );
QStringList PrpSet = s.split( '/' );
if( PrpSet.contains( CurWrd ) )
{
mPreposition = CurWrd;
return( i );
}
}
}
return( pWords.size() );
}
void Task::getDirectAndIndirect( const QStringList &pWords, int pPrpIdx )
{
mDirectObjectName.clear();
mIndirectObjectName.clear();
for( int i = 0 ; i < pWords.size() ; i++ )
{
if( i < pPrpIdx )
{
if( !mDirectObjectName.isEmpty() )
{
mDirectObjectName.append( " " );
}
mDirectObjectName.append( pWords.at( i ) );
}
else if( i > pPrpIdx )
{
if( !mIndirectObjectName.isEmpty() )
{
mIndirectObjectName.append( " " );
}
mIndirectObjectName.append( pWords.at( i ) );
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Minor example cleanup<commit_after><|endoftext|>
|
<commit_before><commit_msg>fixing code-style<commit_after><|endoftext|>
|
<commit_before>#include "AsyncWriterThread.h"
#include <fastrtps/rtps/writer/RTPSWriter.h>
#include <boost/thread.hpp>
#include <boost/thread/lock_guard.hpp>
#include <algorithm>
#include <cassert>
using namespace eprosima::fastrtps::rtps;
AsyncWriterThread::AsyncWriterThread() : thread_(nullptr)
{
}
AsyncWriterThread::~AsyncWriterThread()
{
if(thread_ != nullptr)
{
thread_->interrupt();
thread_->join();
delete thread_;
}
}
bool AsyncWriterThread::addWriter(RTPSWriter* writer)
{
bool returnedValue = false;
assert(writer != nullptr);
if(writer->isAsync())
{
boost::lock_guard<boost::mutex> guard(mutex_);
async_writers.push_back(writer);
returnedValue = true;
// If thread not running, start it.
if(thread_ == nullptr)
{
thread_ = new boost::thread(&AsyncWriterThread::run, this);
}
}
return returnedValue;
}
/*!
* @brief This function removes a writer.
* @param writer Asynchronous writer to be removed.
* @return Result of the operation.
*/
bool AsyncWriterThread::removeWriter(RTPSWriter* writer)
{
bool returnedValue = false;
assert(writer != nullptr);
boost::lock_guard<boost::mutex> guard(mutex_);
auto it = std::find(async_writers.begin(), async_writers.end(), writer);
if(it != async_writers.end())
{
async_writers.erase(it);
returnedValue = true;
// If there is not more asynchronous writers, stop the thread.
if(async_writers.empty())
{
thread_->interrupt();
thread_->join();
thread_ = nullptr;
}
}
return returnedValue;
}
void AsyncWriterThread::run()
{
do
{
try
{
// While the thread is in execution, it cannot be interrupted.
{
boost::this_thread::disable_interruption di;
boost::lock_guard<boost::mutex> guard(mutex_);
for(auto it = async_writers.begin(); it != async_writers.end(); ++it)
{
(*it)->unsent_changes_not_empty();
}
}
//TODO Make configurable the time.
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
}
catch(boost::thread_interrupted /*e*/)
{
return;
}
} while(1);
}
<commit_msg>Removed little memory leak<commit_after>#include "AsyncWriterThread.h"
#include <fastrtps/rtps/writer/RTPSWriter.h>
#include <boost/thread.hpp>
#include <boost/thread/lock_guard.hpp>
#include <algorithm>
#include <cassert>
using namespace eprosima::fastrtps::rtps;
AsyncWriterThread::AsyncWriterThread() : thread_(nullptr)
{
}
AsyncWriterThread::~AsyncWriterThread()
{
if(thread_ != nullptr)
{
thread_->interrupt();
thread_->join();
delete thread_;
}
}
bool AsyncWriterThread::addWriter(RTPSWriter* writer)
{
bool returnedValue = false;
assert(writer != nullptr);
if(writer->isAsync())
{
boost::lock_guard<boost::mutex> guard(mutex_);
async_writers.push_back(writer);
returnedValue = true;
// If thread not running, start it.
if(thread_ == nullptr)
{
thread_ = new boost::thread(&AsyncWriterThread::run, this);
}
}
return returnedValue;
}
/*!
* @brief This function removes a writer.
* @param writer Asynchronous writer to be removed.
* @return Result of the operation.
*/
bool AsyncWriterThread::removeWriter(RTPSWriter* writer)
{
bool returnedValue = false;
assert(writer != nullptr);
boost::lock_guard<boost::mutex> guard(mutex_);
auto it = std::find(async_writers.begin(), async_writers.end(), writer);
if(it != async_writers.end())
{
async_writers.erase(it);
returnedValue = true;
// If there is not more asynchronous writers, stop the thread.
if(async_writers.empty())
{
thread_->interrupt();
thread_->join();
delete thread_;
thread_ = nullptr;
}
}
return returnedValue;
}
void AsyncWriterThread::run()
{
do
{
try
{
// While the thread is in execution, it cannot be interrupted.
{
boost::this_thread::disable_interruption di;
boost::lock_guard<boost::mutex> guard(mutex_);
for(auto it = async_writers.begin(); it != async_writers.end(); ++it)
{
(*it)->unsent_changes_not_empty();
}
}
//TODO Make configurable the time.
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
}
catch(boost::thread_interrupted /*e*/)
{
return;
}
} while(1);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file includes unit tests for EncoderStateFeedback.
#include "video_engine/encoder_state_feedback.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "modules/rtp_rtcp/interface/rtp_rtcp_defines.h"
#include "modules/utility/interface/process_thread.h"
#include "system_wrappers/interface/scoped_ptr.h"
#include "video_engine/vie_encoder.h"
namespace webrtc {
// TODO(mflodman) Create a common mock in module utility.
class TestProcessThread : public ProcessThread {
public:
TestProcessThread() {}
~TestProcessThread() {}
virtual WebRtc_Word32 Start() { return 0; }
virtual WebRtc_Word32 Stop() { return 0; }
virtual WebRtc_Word32 RegisterModule(const Module* module) { return 0; }
virtual WebRtc_Word32 DeRegisterModule(const Module* module) { return 0; }
};
class MockVieEncoder : public ViEEncoder {
public:
explicit MockVieEncoder(TestProcessThread* process_thread)
: ViEEncoder(1, 1, 1, *process_thread, NULL) {}
~MockVieEncoder() {}
MOCK_METHOD1(OnReceivedIntraFrameRequest,
void(uint32_t));
MOCK_METHOD2(OnReceivedSLI,
void(uint32_t ssrc, uint8_t picture_id));
MOCK_METHOD2(OnReceivedRPSI,
void(uint32_t ssrc, uint64_t picture_id));
};
class VieKeyRequestTest : public ::testing::Test {
protected:
virtual void SetUp() {
process_thread_.reset(new TestProcessThread());
encoder_state_feedback_.reset(new EncoderStateFeedback());
}
scoped_ptr<TestProcessThread> process_thread_;
scoped_ptr<EncoderStateFeedback> encoder_state_feedback_;
};
TEST_F(VieKeyRequestTest, CreateAndTriggerRequests) {
const int ssrc = 1234;
MockVieEncoder encoder(process_thread_.get());
EXPECT_EQ(true, encoder_state_feedback_->AddEncoder(ssrc, &encoder));
EXPECT_CALL(encoder, OnReceivedIntraFrameRequest(ssrc))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc);
const uint8_t sli_picture_id = 3;
EXPECT_CALL(encoder, OnReceivedSLI(ssrc, sli_picture_id))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc, sli_picture_id);
const uint64_t rpsi_picture_id = 9;
EXPECT_CALL(encoder, OnReceivedRPSI(ssrc, rpsi_picture_id))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc, rpsi_picture_id);
encoder_state_feedback_->RemoveEncoder(ssrc);
}
// Register multiple encoders and make sure the request is relayed to correct
// ViEEncoder.
TEST_F(VieKeyRequestTest, MultipleEncoders) {
const int ssrc_1 = 1234;
const int ssrc_2 = 5678;
MockVieEncoder encoder_1(process_thread_.get());
MockVieEncoder encoder_2(process_thread_.get());
EXPECT_EQ(true, encoder_state_feedback_->AddEncoder(ssrc_1, &encoder_1));
EXPECT_EQ(true, encoder_state_feedback_->AddEncoder(ssrc_2, &encoder_2));
EXPECT_CALL(encoder_1, OnReceivedIntraFrameRequest(ssrc_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedIntraFrameRequest(ssrc_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_2);
const uint8_t sli_pid_1 = 3;
const uint8_t sli_pid_2 = 4;
EXPECT_CALL(encoder_1, OnReceivedSLI(ssrc_1, sli_pid_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedSLI(ssrc_2, sli_pid_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc_1, sli_pid_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc_2, sli_pid_2);
const uint64_t rpsi_pid_1 = 9;
const uint64_t rpsi_pid_2 = 10;
EXPECT_CALL(encoder_1, OnReceivedRPSI(ssrc_1, rpsi_pid_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedRPSI(ssrc_2, rpsi_pid_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc_1, rpsi_pid_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc_2, rpsi_pid_2);
encoder_state_feedback_->RemoveEncoder(ssrc_1);
EXPECT_CALL(encoder_2, OnReceivedIntraFrameRequest(ssrc_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_2);
encoder_state_feedback_->RemoveEncoder(ssrc_2);
}
TEST_F(VieKeyRequestTest, AddTwiceError) {
const int ssrc = 1234;
MockVieEncoder encoder(process_thread_.get());
EXPECT_EQ(true, encoder_state_feedback_->AddEncoder(ssrc, &encoder));
EXPECT_EQ(false, encoder_state_feedback_->AddEncoder(ssrc, &encoder));
encoder_state_feedback_->RemoveEncoder(ssrc);
}
} // namespace webrtc
<commit_msg>Fix gcc 4.6 compilation for video_engine_unittest<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file includes unit tests for EncoderStateFeedback.
#include "video_engine/encoder_state_feedback.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "modules/rtp_rtcp/interface/rtp_rtcp_defines.h"
#include "modules/utility/interface/process_thread.h"
#include "system_wrappers/interface/scoped_ptr.h"
#include "video_engine/vie_encoder.h"
namespace webrtc {
// TODO(mflodman) Create a common mock in module utility.
class TestProcessThread : public ProcessThread {
public:
TestProcessThread() {}
~TestProcessThread() {}
virtual WebRtc_Word32 Start() { return 0; }
virtual WebRtc_Word32 Stop() { return 0; }
virtual WebRtc_Word32 RegisterModule(const Module* module) { return 0; }
virtual WebRtc_Word32 DeRegisterModule(const Module* module) { return 0; }
};
class MockVieEncoder : public ViEEncoder {
public:
explicit MockVieEncoder(TestProcessThread* process_thread)
: ViEEncoder(1, 1, 1, *process_thread, NULL) {}
~MockVieEncoder() {}
MOCK_METHOD1(OnReceivedIntraFrameRequest,
void(uint32_t));
MOCK_METHOD2(OnReceivedSLI,
void(uint32_t ssrc, uint8_t picture_id));
MOCK_METHOD2(OnReceivedRPSI,
void(uint32_t ssrc, uint64_t picture_id));
};
class VieKeyRequestTest : public ::testing::Test {
protected:
virtual void SetUp() {
process_thread_.reset(new TestProcessThread());
encoder_state_feedback_.reset(new EncoderStateFeedback());
}
scoped_ptr<TestProcessThread> process_thread_;
scoped_ptr<EncoderStateFeedback> encoder_state_feedback_;
};
TEST_F(VieKeyRequestTest, CreateAndTriggerRequests) {
const int ssrc = 1234;
MockVieEncoder encoder(process_thread_.get());
EXPECT_TRUE(encoder_state_feedback_->AddEncoder(ssrc, &encoder));
EXPECT_CALL(encoder, OnReceivedIntraFrameRequest(ssrc))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc);
const uint8_t sli_picture_id = 3;
EXPECT_CALL(encoder, OnReceivedSLI(ssrc, sli_picture_id))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc, sli_picture_id);
const uint64_t rpsi_picture_id = 9;
EXPECT_CALL(encoder, OnReceivedRPSI(ssrc, rpsi_picture_id))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc, rpsi_picture_id);
encoder_state_feedback_->RemoveEncoder(ssrc);
}
// Register multiple encoders and make sure the request is relayed to correct
// ViEEncoder.
TEST_F(VieKeyRequestTest, MultipleEncoders) {
const int ssrc_1 = 1234;
const int ssrc_2 = 5678;
MockVieEncoder encoder_1(process_thread_.get());
MockVieEncoder encoder_2(process_thread_.get());
EXPECT_TRUE(encoder_state_feedback_->AddEncoder(ssrc_1, &encoder_1));
EXPECT_TRUE(encoder_state_feedback_->AddEncoder(ssrc_2, &encoder_2));
EXPECT_CALL(encoder_1, OnReceivedIntraFrameRequest(ssrc_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedIntraFrameRequest(ssrc_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_2);
const uint8_t sli_pid_1 = 3;
const uint8_t sli_pid_2 = 4;
EXPECT_CALL(encoder_1, OnReceivedSLI(ssrc_1, sli_pid_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedSLI(ssrc_2, sli_pid_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc_1, sli_pid_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedSLI(
ssrc_2, sli_pid_2);
const uint64_t rpsi_pid_1 = 9;
const uint64_t rpsi_pid_2 = 10;
EXPECT_CALL(encoder_1, OnReceivedRPSI(ssrc_1, rpsi_pid_1))
.Times(1);
EXPECT_CALL(encoder_2, OnReceivedRPSI(ssrc_2, rpsi_pid_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc_1, rpsi_pid_1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->OnReceivedRPSI(
ssrc_2, rpsi_pid_2);
encoder_state_feedback_->RemoveEncoder(ssrc_1);
EXPECT_CALL(encoder_2, OnReceivedIntraFrameRequest(ssrc_2))
.Times(1);
encoder_state_feedback_->GetRtcpIntraFrameObserver()->
OnReceivedIntraFrameRequest(ssrc_2);
encoder_state_feedback_->RemoveEncoder(ssrc_2);
}
TEST_F(VieKeyRequestTest, AddTwiceError) {
const int ssrc = 1234;
MockVieEncoder encoder(process_thread_.get());
EXPECT_TRUE(encoder_state_feedback_->AddEncoder(ssrc, &encoder));
EXPECT_FALSE(encoder_state_feedback_->AddEncoder(ssrc, &encoder));
encoder_state_feedback_->RemoveEncoder(ssrc);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#include <vtkSmoothPolyDataFilter.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include "processing.h"
#include "FiberPostProcessCLP.h"
#include "utils.h"
int main( int argc , char* argv[] )
{
PARSE_ARGS ;
bool attributeFlag = false ;
bool thresholdFlag = false ;
if( !attributeFileName.empty() )
{
attributeFlag = true ;
}
for( int i = 0 ; i < argc ; i++ )
{
if( !strcmp( argv[ i ] , "-t" ) || !strcmp( argv[ i ] , "--threshold" ) )
{
thresholdFlag = true ;
}
}
processing FiberProcessing ;
FiberProcessing.SetInputFileName( inputFiberFileName ) ;
FiberProcessing.SetOutputFileName( outputFiberFileName ) ;
FiberProcessing.SetVisualisation( visualisationFlag ) ;
FiberProcessing.SetAttributeFileName( attributeFileName ) ;
FiberProcessing.SetThreshold( threshold ) ;
FiberProcessing.SetThresholdFlag( thresholdFlag ) ;
FiberProcessing.SetAttributeFlag( attributeFlag ) ;
FiberProcessing.SetMaskFlag( mask ) ;
FiberProcessing.SetCropFlag( crop ) ;
FiberProcessing.SetCleanFlag( clean ) ;
FiberProcessing.SetThresholdMode ( thresholdMode ) ;
FiberProcessing.run() ;
return EXIT_SUCCESS ;
}
<commit_msg>BUG: wrong input parameters were not treated.<commit_after>#include <vtkSmoothPolyDataFilter.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include "processing.h"
#include "FiberPostProcessCLP.h"
#include "utils.h"
int main( int argc , char* argv[] )
{
PARSE_ARGS ;
bool attributeFlag = false ;
bool thresholdFlag = false ;
if( !attributeFileName.empty() )
{
attributeFlag = true ;
}
for( int i = 0 ; i < argc ; i++ )
{
if( !strcmp( argv[ i ] , "-t" ) || !strcmp( argv[ i ] , "--threshold" ) )
{
thresholdFlag = true ;
}
}
processing FiberProcessing ;
if( inp)
if( attributeFlag == false )
{
if( crop == true || clean == true || mask == true )
{
std::cerr << "No attribute file detected. --crop, --clean, --mask requires an attribute file to be used. Please use --attributeFile or -m to input an attribute file or consult the help for more details." << std::endl ;
return EXIT_FAILURE ;
}
}
else if( mask == false )
{
if( clean == true )
{
std::cerr << "--clean requires --mask to be used. Please consult the help for more details." << std::endl ;
return EXIT_FAILURE ;
}
}
FiberProcessing.SetOutputFileName( outputFiberFileName ) ;
FiberProcessing.SetVisualisation( visualisationFlag ) ;
FiberProcessing.SetAttributeFileName( attributeFileName ) ;
FiberProcessing.SetThreshold( threshold ) ;
FiberProcessing.SetThresholdFlag( thresholdFlag ) ;
FiberProcessing.SetAttributeFlag( attributeFlag ) ;
FiberProcessing.SetMaskFlag( mask ) ;
FiberProcessing.SetCropFlag( crop ) ;
FiberProcessing.SetCleanFlag( clean ) ;
FiberProcessing.SetThresholdMode ( thresholdMode ) ;
FiberProcessing.run() ;
return EXIT_SUCCESS ;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "Gaffer/TweakPlug.h"
#include "Gaffer/PlugAlgo.h"
#include "Gaffer/ScriptNode.h"
#include "IECore/DataAlgo.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/StringAlgo.h"
#include "IECore/TypeTraits.h"
#include <unordered_map>
using namespace std;
using namespace IECore;
using namespace Gaffer;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
/// \todo - if these make sense, I guess they should be pushed back to cortex
// IsColorTypedData
template< typename T > struct IsColorTypedData : boost::mpl::and_< TypeTraits::IsTypedData<T>, TypeTraits::IsColor< typename TypeTraits::ValueType<T>::type > > {};
// SupportsArithmeticData
template< typename T > struct SupportsArithData : boost::mpl::or_< TypeTraits::IsNumericSimpleTypedData<T>, TypeTraits::IsVecTypedData<T>, IsColorTypedData<T>> {};
} // namespace
//////////////////////////////////////////////////////////////////////////
// TweakPlug
//////////////////////////////////////////////////////////////////////////
GAFFER_PLUG_DEFINE_TYPE( TweakPlug );
TweakPlug::TweakPlug( const std::string &tweakName, Gaffer::ValuePlugPtr valuePlug, Mode mode, bool enabled )
: TweakPlug( valuePlug, "tweak", In, Default | Dynamic )
{
namePlug()->setValue( tweakName );
modePlug()->setValue( mode );
enabledPlug()->setValue( enabled );
}
TweakPlug::TweakPlug( const std::string &tweakName, const IECore::Data *value, Mode mode, bool enabled )
: TweakPlug( tweakName, PlugAlgo::createPlugFromData( "value", In, Default | Dynamic, value ), mode, enabled )
{
}
TweakPlug::TweakPlug( Gaffer::ValuePlugPtr valuePlug, const std::string &name, Direction direction, unsigned flags )
: ValuePlug( name, direction, flags )
{
addChild( new StringPlug( "name", direction ) );
addChild( new BoolPlug( "enabled", direction, true ) );
addChild( new IntPlug( "mode", direction, Replace, Replace, Create ) );
if( valuePlug )
{
valuePlug->setName( "value" );
addChild( valuePlug );
}
}
Gaffer::StringPlug *TweakPlug::namePlug()
{
return getChild<StringPlug>( 0 );
}
const Gaffer::StringPlug *TweakPlug::namePlug() const
{
return getChild<StringPlug>( 0 );
}
Gaffer::BoolPlug *TweakPlug::enabledPlug()
{
return getChild<BoolPlug>( 1 );
}
const Gaffer::BoolPlug *TweakPlug::enabledPlug() const
{
return getChild<BoolPlug>( 1 );
}
Gaffer::IntPlug *TweakPlug::modePlug()
{
return getChild<IntPlug>( 2 );
}
const Gaffer::IntPlug *TweakPlug::modePlug() const
{
return getChild<IntPlug>( 2 );
}
Gaffer::ValuePlug *TweakPlug::valuePlugInternal()
{
if( children().size() <= 3 )
{
return nullptr;
}
return getChild<ValuePlug>( 3 );
}
const Gaffer::ValuePlug *TweakPlug::valuePlugInternal() const
{
if( children().size() <= 3 )
{
return nullptr;
}
return getChild<ValuePlug>( 3 );
}
bool TweakPlug::acceptsChild( const Gaffer::GraphComponent *potentialChild ) const
{
if( !Plug::acceptsChild( potentialChild ) )
{
return false;
}
if(
potentialChild->isInstanceOf( StringPlug::staticTypeId() ) &&
potentialChild->getName() == "name" &&
!getChild<Plug>( "name" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( BoolPlug::staticTypeId() ) &&
potentialChild->getName() == "enabled" &&
!getChild<Plug>( "enabled" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( IntPlug::staticTypeId() ) &&
potentialChild->getName() == "mode" &&
!getChild<Plug>( "mode" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( ValuePlug::staticTypeId() ) &&
potentialChild->getName() == "value" &&
!getChild<Plug>( "value" )
)
{
return true;
}
return false;
}
Gaffer::PlugPtr TweakPlug::createCounterpart( const std::string &name, Direction direction ) const
{
const Plug *p = valuePlug();
PlugPtr plugCounterpart = p->createCounterpart( p->getName(), direction );
return new TweakPlug( runTimeCast<ValuePlug>( plugCounterpart.get() ), name, direction, getFlags() );
}
bool TweakPlug::applyTweak( IECore::CompoundData *parameters, MissingMode missingMode ) const
{
return applyTweak(
[¶meters]( const std::string &valueName ) { return parameters->member( valueName ); },
[¶meters]( const std::string &valueName, DataPtr newData )
{
if( newData == nullptr )
{
return parameters->writable().erase( valueName ) > 0;
}
parameters->writable()[valueName] = newData;
return true;
},
missingMode
);
}
void TweakPlug::applyNumericTweak(
const IECore::Data *sourceData,
const IECore::Data *tweakData,
IECore::Data *destData,
TweakPlug::Mode mode,
const std::string &tweakName
) const
{
dispatch(
destData,
[&] ( auto data ) {
using DataType = typename std::remove_pointer<decltype( data )>::type;
if constexpr( SupportsArithData<DataType>::value ) {
const DataType *sourceDataCast = runTimeCast<const DataType>( sourceData );
const DataType *tweakDataCast = runTimeCast<const DataType>( tweakData );
switch( mode )
{
case TweakPlug::Add :
data->writable() = sourceDataCast->readable() + tweakDataCast->readable();
break;
case TweakPlug::Subtract :
data->writable() = sourceDataCast->readable() - tweakDataCast->readable();
break;
case TweakPlug::Multiply :
data->writable() = sourceDataCast->readable() * tweakDataCast->readable();
break;
case TweakPlug::Replace :
case TweakPlug::Remove :
case TweakPlug::Create :
// These cases are unused - we handle replace and remove mode outside of numericTweak.
// But the compiler gets unhappy if we don't handle some cases.
assert( false );
break;
}
}
else
{
throw IECore::Exception( boost::str(
boost::format( "Cannot apply tweak with mode %s to \"%s\" : Data type %s not supported." )
% modeToString( mode )
% tweakName
% sourceData->typeName()
)
);
}
}
);
}
const char *TweakPlug::modeToString( Gaffer::TweakPlug::Mode mode )
{
switch( mode )
{
case Gaffer::TweakPlug::Replace :
return "Replace";
case Gaffer::TweakPlug::Add :
return "Add";
case Gaffer::TweakPlug::Subtract :
return "Subtract";
case Gaffer::TweakPlug::Multiply :
return "Multiply";
case Gaffer::TweakPlug::Remove :
return "Remove";
default :
return "Invalid";
}
}
//////////////////////////////////////////////////////////////////////////
// TweaksPlug
//////////////////////////////////////////////////////////////////////////
GAFFER_PLUG_DEFINE_TYPE( TweaksPlug );
TweaksPlug::TweaksPlug( const std::string &name, Direction direction, unsigned flags )
: ValuePlug( name, direction, flags )
{
}
bool TweaksPlug::acceptsChild( const Gaffer::GraphComponent *potentialChild ) const
{
if( !ValuePlug::acceptsChild( potentialChild ) )
{
return false;
}
return runTimeCast<const TweakPlug>( potentialChild );
}
bool TweaksPlug::acceptsInput( const Plug *input ) const
{
if( !ValuePlug::acceptsChild( input ) )
{
return false;
}
if( !input )
{
return true;
}
if( const ScriptNode *s = ancestor<ScriptNode>() )
{
if( s->isExecuting() )
{
// Before TweaksPlug existed, regular Plugs were
// used in its place. If such plugs were ever
// promoted or passed through dots, they will have
// been serialised with just a regular plug type,
// and we need to tolerate connections to them
// on loading.
return true;
}
}
return runTimeCast<const TweaksPlug>( input );
}
Gaffer::PlugPtr TweaksPlug::createCounterpart( const std::string &name, Direction direction ) const
{
PlugPtr result = new TweaksPlug( name, direction, getFlags() );
for( const auto &tweakPlug : TweakPlug::Range( *this ) )
{
result->addChild( tweakPlug->createCounterpart( tweakPlug->getName(), direction ) );
}
return result;
}
bool TweaksPlug::applyTweaks( IECore::CompoundData *parameters, TweakPlug::MissingMode missingMode ) const
{
bool applied = false;
for( const auto &tweak : TweakPlug::Range( *this ) )
{
if( tweak->applyTweak( parameters, missingMode ) )
{
applied = true;
}
}
return applied;
}
<commit_msg>TweakPlug : Handle `Create` mode in `modeToString()`<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, Image Engine Design 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 John Haddon nor the names of
// any other contributors to this software 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 "Gaffer/TweakPlug.h"
#include "Gaffer/PlugAlgo.h"
#include "Gaffer/ScriptNode.h"
#include "IECore/DataAlgo.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/StringAlgo.h"
#include "IECore/TypeTraits.h"
#include <unordered_map>
using namespace std;
using namespace IECore;
using namespace Gaffer;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
/// \todo - if these make sense, I guess they should be pushed back to cortex
// IsColorTypedData
template< typename T > struct IsColorTypedData : boost::mpl::and_< TypeTraits::IsTypedData<T>, TypeTraits::IsColor< typename TypeTraits::ValueType<T>::type > > {};
// SupportsArithmeticData
template< typename T > struct SupportsArithData : boost::mpl::or_< TypeTraits::IsNumericSimpleTypedData<T>, TypeTraits::IsVecTypedData<T>, IsColorTypedData<T>> {};
} // namespace
//////////////////////////////////////////////////////////////////////////
// TweakPlug
//////////////////////////////////////////////////////////////////////////
GAFFER_PLUG_DEFINE_TYPE( TweakPlug );
TweakPlug::TweakPlug( const std::string &tweakName, Gaffer::ValuePlugPtr valuePlug, Mode mode, bool enabled )
: TweakPlug( valuePlug, "tweak", In, Default | Dynamic )
{
namePlug()->setValue( tweakName );
modePlug()->setValue( mode );
enabledPlug()->setValue( enabled );
}
TweakPlug::TweakPlug( const std::string &tweakName, const IECore::Data *value, Mode mode, bool enabled )
: TweakPlug( tweakName, PlugAlgo::createPlugFromData( "value", In, Default | Dynamic, value ), mode, enabled )
{
}
TweakPlug::TweakPlug( Gaffer::ValuePlugPtr valuePlug, const std::string &name, Direction direction, unsigned flags )
: ValuePlug( name, direction, flags )
{
addChild( new StringPlug( "name", direction ) );
addChild( new BoolPlug( "enabled", direction, true ) );
addChild( new IntPlug( "mode", direction, Replace, Replace, Create ) );
if( valuePlug )
{
valuePlug->setName( "value" );
addChild( valuePlug );
}
}
Gaffer::StringPlug *TweakPlug::namePlug()
{
return getChild<StringPlug>( 0 );
}
const Gaffer::StringPlug *TweakPlug::namePlug() const
{
return getChild<StringPlug>( 0 );
}
Gaffer::BoolPlug *TweakPlug::enabledPlug()
{
return getChild<BoolPlug>( 1 );
}
const Gaffer::BoolPlug *TweakPlug::enabledPlug() const
{
return getChild<BoolPlug>( 1 );
}
Gaffer::IntPlug *TweakPlug::modePlug()
{
return getChild<IntPlug>( 2 );
}
const Gaffer::IntPlug *TweakPlug::modePlug() const
{
return getChild<IntPlug>( 2 );
}
Gaffer::ValuePlug *TweakPlug::valuePlugInternal()
{
if( children().size() <= 3 )
{
return nullptr;
}
return getChild<ValuePlug>( 3 );
}
const Gaffer::ValuePlug *TweakPlug::valuePlugInternal() const
{
if( children().size() <= 3 )
{
return nullptr;
}
return getChild<ValuePlug>( 3 );
}
bool TweakPlug::acceptsChild( const Gaffer::GraphComponent *potentialChild ) const
{
if( !Plug::acceptsChild( potentialChild ) )
{
return false;
}
if(
potentialChild->isInstanceOf( StringPlug::staticTypeId() ) &&
potentialChild->getName() == "name" &&
!getChild<Plug>( "name" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( BoolPlug::staticTypeId() ) &&
potentialChild->getName() == "enabled" &&
!getChild<Plug>( "enabled" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( IntPlug::staticTypeId() ) &&
potentialChild->getName() == "mode" &&
!getChild<Plug>( "mode" )
)
{
return true;
}
else if(
potentialChild->isInstanceOf( ValuePlug::staticTypeId() ) &&
potentialChild->getName() == "value" &&
!getChild<Plug>( "value" )
)
{
return true;
}
return false;
}
Gaffer::PlugPtr TweakPlug::createCounterpart( const std::string &name, Direction direction ) const
{
const Plug *p = valuePlug();
PlugPtr plugCounterpart = p->createCounterpart( p->getName(), direction );
return new TweakPlug( runTimeCast<ValuePlug>( plugCounterpart.get() ), name, direction, getFlags() );
}
bool TweakPlug::applyTweak( IECore::CompoundData *parameters, MissingMode missingMode ) const
{
return applyTweak(
[¶meters]( const std::string &valueName ) { return parameters->member( valueName ); },
[¶meters]( const std::string &valueName, DataPtr newData )
{
if( newData == nullptr )
{
return parameters->writable().erase( valueName ) > 0;
}
parameters->writable()[valueName] = newData;
return true;
},
missingMode
);
}
void TweakPlug::applyNumericTweak(
const IECore::Data *sourceData,
const IECore::Data *tweakData,
IECore::Data *destData,
TweakPlug::Mode mode,
const std::string &tweakName
) const
{
dispatch(
destData,
[&] ( auto data ) {
using DataType = typename std::remove_pointer<decltype( data )>::type;
if constexpr( SupportsArithData<DataType>::value ) {
const DataType *sourceDataCast = runTimeCast<const DataType>( sourceData );
const DataType *tweakDataCast = runTimeCast<const DataType>( tweakData );
switch( mode )
{
case TweakPlug::Add :
data->writable() = sourceDataCast->readable() + tweakDataCast->readable();
break;
case TweakPlug::Subtract :
data->writable() = sourceDataCast->readable() - tweakDataCast->readable();
break;
case TweakPlug::Multiply :
data->writable() = sourceDataCast->readable() * tweakDataCast->readable();
break;
case TweakPlug::Replace :
case TweakPlug::Remove :
case TweakPlug::Create :
// These cases are unused - we handle replace and remove mode outside of numericTweak.
// But the compiler gets unhappy if we don't handle some cases.
assert( false );
break;
}
}
else
{
throw IECore::Exception( boost::str(
boost::format( "Cannot apply tweak with mode %s to \"%s\" : Data type %s not supported." )
% modeToString( mode )
% tweakName
% sourceData->typeName()
)
);
}
}
);
}
const char *TweakPlug::modeToString( Gaffer::TweakPlug::Mode mode )
{
switch( mode )
{
case Gaffer::TweakPlug::Replace :
return "Replace";
case Gaffer::TweakPlug::Add :
return "Add";
case Gaffer::TweakPlug::Subtract :
return "Subtract";
case Gaffer::TweakPlug::Multiply :
return "Multiply";
case Gaffer::TweakPlug::Remove :
return "Remove";
case Gaffer::TweakPlug::Create :
return "Create";
}
return "Invalid";
}
//////////////////////////////////////////////////////////////////////////
// TweaksPlug
//////////////////////////////////////////////////////////////////////////
GAFFER_PLUG_DEFINE_TYPE( TweaksPlug );
TweaksPlug::TweaksPlug( const std::string &name, Direction direction, unsigned flags )
: ValuePlug( name, direction, flags )
{
}
bool TweaksPlug::acceptsChild( const Gaffer::GraphComponent *potentialChild ) const
{
if( !ValuePlug::acceptsChild( potentialChild ) )
{
return false;
}
return runTimeCast<const TweakPlug>( potentialChild );
}
bool TweaksPlug::acceptsInput( const Plug *input ) const
{
if( !ValuePlug::acceptsChild( input ) )
{
return false;
}
if( !input )
{
return true;
}
if( const ScriptNode *s = ancestor<ScriptNode>() )
{
if( s->isExecuting() )
{
// Before TweaksPlug existed, regular Plugs were
// used in its place. If such plugs were ever
// promoted or passed through dots, they will have
// been serialised with just a regular plug type,
// and we need to tolerate connections to them
// on loading.
return true;
}
}
return runTimeCast<const TweaksPlug>( input );
}
Gaffer::PlugPtr TweaksPlug::createCounterpart( const std::string &name, Direction direction ) const
{
PlugPtr result = new TweaksPlug( name, direction, getFlags() );
for( const auto &tweakPlug : TweakPlug::Range( *this ) )
{
result->addChild( tweakPlug->createCounterpart( tweakPlug->getName(), direction ) );
}
return result;
}
bool TweaksPlug::applyTweaks( IECore::CompoundData *parameters, TweakPlug::MissingMode missingMode ) const
{
bool applied = false;
for( const auto &tweak : TweakPlug::Range( *this ) )
{
if( tweak->applyTweak( parameters, missingMode ) )
{
applied = true;
}
}
return applied;
}
<|endoftext|>
|
<commit_before>//
// Created by Sam on 9/25/2017.
//
#include <utility>
#include <iostream>
#include "../../../include/Game/Core/Card.h"
#include "../../../include/Game/Core/Player.h"
#include "../../../include/Game/Core/Game.h"
#include "../../../include/Game/Core/Board.h"
#include "../../../include/Network/Client.h"
#include "../../../include/Network/Derived/ChatMessage.h"
#include "../../../include/Network/Derived/PlayCardMessage.h"
void Player::draw()
{
hand->addCard(board->deck->draw());
}
void Player::draw(int count)
{
for (int i = 0; i < count; i++)
{
draw();
}
}
void Player::playCard(const json &rawJSON)
{
if (shared_from_this() == game->activePlayer)
{
PlayCardMessage moveCardMessage(rawJSON);
auto card = hand->findCard(moveCardMessage.cardTag);
if (availableMana.canPay(card->mana))
{
availableMana.payMana(card->mana);
board->playCard(card);
}
}
}
void Player::sendChatMessage(const json &rawJSON)
{
// Format chat message with the sender name before broadcasting it to all players
ChatMessage chatMessage(rawJSON);
chatMessage.rawJSON[Message::DATA_KEY]["text"] = name + ": " + chatMessage.text;
game->writePlayers(chatMessage.getJSON());
}
json Player::getState()
{
json playerJSON;
playerJSON["playerID"] = tag;
playerJSON["hand"] = hand->getJSON();
playerJSON["health"] = health;
playerJSON["deckCount"] = board->deck->count();
playerJSON["mana"] = getManaJSON();
return playerJSON;
}
json Player::getOpponentState()
{
json opponentJSON;
opponentJSON["playerID"] = tag;
opponentJSON["name"] = name;
opponentJSON["tag"] = tag;
opponentJSON["health"] = health;
opponentJSON["handCount"] = hand->count();
opponentJSON["deckCount"] = board->deck->count();
opponentJSON["mana"] = getManaJSON();
return opponentJSON;
}
json Player::getManaJSON()
{
json manaJSON;
manaJSON["available"] = availableMana.getJSON();
manaJSON["total"] = totalMana.getJSON();
return manaJSON;
}
Player::Player(std::shared_ptr<Client> client)
: client(client),
name(client->name),
availableMana(1,1,1,1,1,1),
totalMana(1,1,1,1,1,1),
board(std::make_shared<Board>()),
hand(std::make_shared<Hand>()),
health(30)
{
}
Player::~Player()
= default;
<commit_msg>Removed dupe player tag in from the opponent state<commit_after>//
// Created by Sam on 9/25/2017.
//
#include <utility>
#include <iostream>
#include "../../../include/Game/Core/Card.h"
#include "../../../include/Game/Core/Player.h"
#include "../../../include/Game/Core/Game.h"
#include "../../../include/Game/Core/Board.h"
#include "../../../include/Network/Client.h"
#include "../../../include/Network/Derived/ChatMessage.h"
#include "../../../include/Network/Derived/PlayCardMessage.h"
void Player::draw()
{
hand->addCard(board->deck->draw());
}
void Player::draw(int count)
{
for (int i = 0; i < count; i++)
{
draw();
}
}
void Player::playCard(const json &rawJSON)
{
if (shared_from_this() == game->activePlayer)
{
PlayCardMessage moveCardMessage(rawJSON);
auto card = hand->findCard(moveCardMessage.cardTag);
if (availableMana.canPay(card->mana))
{
availableMana.payMana(card->mana);
board->playCard(card);
}
}
}
void Player::sendChatMessage(const json &rawJSON)
{
// Format chat message with the sender name before broadcasting it to all players
ChatMessage chatMessage(rawJSON);
chatMessage.rawJSON[Message::DATA_KEY]["text"] = name + ": " + chatMessage.text;
game->writePlayers(chatMessage.getJSON());
}
json Player::getState()
{
json playerJSON;
playerJSON["playerID"] = tag;
playerJSON["hand"] = hand->getJSON();
playerJSON["health"] = health;
playerJSON["deckCount"] = board->deck->count();
playerJSON["mana"] = getManaJSON();
return playerJSON;
}
json Player::getOpponentState()
{
json opponentJSON;
opponentJSON["playerID"] = tag;
opponentJSON["name"] = name;
opponentJSON["health"] = health;
opponentJSON["handCount"] = hand->count();
opponentJSON["deckCount"] = board->deck->count();
opponentJSON["mana"] = getManaJSON();
return opponentJSON;
}
json Player::getManaJSON()
{
json manaJSON;
manaJSON["available"] = availableMana.getJSON();
manaJSON["total"] = totalMana.getJSON();
return manaJSON;
}
Player::Player(std::shared_ptr<Client> client)
: client(client),
name(client->name),
availableMana(1,1,1,1,1,1),
totalMana(1,1,1,1,1,1),
board(std::make_shared<Board>()),
hand(std::make_shared<Hand>()),
health(30)
{
}
Player::~Player()
= default;
<|endoftext|>
|
<commit_before>#include "xml.h"
#include <cstring>
#include <iostream>
#include "../leanify.h"
#include "../utils.h"
Xml::Xml(void *p, size_t s /*= 0*/) : Format(p, s), doc(true)
{
unsigned char *q = (unsigned char *)p;
const unsigned char utf8_bom[] = { 0xEF, 0xBB, 0xBF };
// tinyxml2 does not support utf16
/*
const unsigned char utf16be_bom[] = { 0xFE, 0xFF };
const unsigned char utf16le_bom[] = { 0xFF, 0xFE };
*/
// skip utf8 bom
if (!memcmp(q, utf8_bom, sizeof(utf8_bom)))
{
q += sizeof(utf8_bom);
}
/* else if (!memcmp(q, utf16le_bom, sizeof(utf16le_bom)) || !memcmp(q, utf16be_bom, sizeof(utf16be_bom)))
{
q += sizeof(utf16le_bom);
}
*/
// skip spaces
while (isspace(*q) && q < (unsigned char *)p + s)
{
q++;
}
// only parse the file if it starts with '<'
if (*q == '<')
{
is_valid = (doc.Parse(fp, size) == 0);
}
else
{
is_valid = false;
}
}
size_t Xml::Leanify(size_t size_leanified /*= 0*/)
{
const char *root_name = doc.RootElement()->Name();
// if the XML is fb2 file
if (strcmp(root_name, "FictionBook") == 0)
{
if (is_verbose)
{
std::cout << "FB2 detected." << std::endl;
}
if (depth < max_depth)
{
depth++;
// iterate through all binary element
for (auto e = doc.RootElement()->FirstChildElement("binary"); e; e = e->NextSiblingElement("binary"))
{
for (int i = 1; i < depth; i++)
{
std::cout << "-> ";
}
std::cout << e->Attribute("id") << std::endl;
const char *base64_data = e->GetText();
if (base64_data == nullptr)
{
std::cout << "No data found." << std::endl;
continue;
}
size_t base64_len = strlen(base64_data);
// 4 base64 character contains information of 3 bytes
size_t binary_len = 3 * base64_len / 4;
unsigned char *binary_data = new unsigned char[binary_len];
if (Base64Decode(base64_data, base64_len, binary_data, &binary_len))
{
std::cout << "Base64 decode error." << std::endl;
delete[] binary_data;
continue;
}
// Leanify embedded image
binary_len = LeanifyFile(binary_data, binary_len);
// allocate a few more bytes for padding
size_t new_base64_len = 4 * binary_len / 3 + 4;
char *new_base64_data = new char[new_base64_len];
if (Base64Encode(binary_data, binary_len, new_base64_data, new_base64_len))
{
std::cout << "Base64 encode error." << std::endl;
}
else if (strlen(new_base64_data) < base64_len)
{
e->SetText(new_base64_data);
}
delete[] binary_data;
delete[] new_base64_data;
}
depth--;
}
}
else if (strcmp(root_name, "svg") == 0)
{
if (is_verbose)
{
std::cout << "SVG detected." << std::endl;
}
for (auto e = doc.RootElement()->FirstChildElement("metadata"); e; e = e->NextSiblingElement("metadata"))
{
doc.RootElement()->DeleteChild(e);
}
TraverseElements(doc.RootElement(), [](tinyxml2::XMLElement* e)
{
// remove empty attribute
for (auto attr = e->FirstAttribute(); attr; attr = attr->Next())
{
auto value = attr->Value();
if (value == nullptr || *value == 0)
{
e->DeleteAttribute(attr->Name());
}
}
// remove empty text element and container element
auto name = e->Name();
if (e->NoChildren())
{
if (strcmp(name, "text") == 0 ||
strcmp(name, "tspan") == 0 ||
strcmp(name, "a") == 0 ||
strcmp(name, "defs") == 0 ||
strcmp(name, "g") == 0 ||
strcmp(name, "marker") == 0 ||
strcmp(name, "mask") == 0 ||
strcmp(name, "missing-glyph") == 0 ||
strcmp(name, "pattern") == 0 ||
strcmp(name, "switch") == 0 ||
strcmp(name, "symbol") == 0)
{
e->Parent()->DeleteChild(e);
}
}
if (strcmp(name, "tref") == 0 && e->Attribute("xlink:href") == nullptr)
{
e->Parent()->DeleteChild(e);
}
});
}
// print leanified XML to memory
tinyxml2::XMLPrinter printer(0, true);
doc.Print(&printer);
size_t new_size = printer.CStrSize() - 1; // -1 for the \0
fp -= size_leanified;
if (new_size < size)
{
memcpy(fp, printer.CStr(), new_size);
return new_size;
}
else if (size_leanified)
{
memmove(fp, fp + size_leanified, size);
}
return size;
}
void Xml::TraverseElements(tinyxml2::XMLElement *ele, std::function<void(tinyxml2::XMLElement*)> callback)
{
for (auto e = ele->FirstChildElement(); e; e = e->NextSiblingElement())
{
TraverseElements(e, callback);
}
callback(ele);
}
<commit_msg>SVG: support removing metadata anywhere<commit_after>#include "xml.h"
#include <cstring>
#include <iostream>
#include "../leanify.h"
#include "../utils.h"
Xml::Xml(void *p, size_t s /*= 0*/) : Format(p, s), doc(true)
{
unsigned char *q = (unsigned char *)p;
const unsigned char utf8_bom[] = { 0xEF, 0xBB, 0xBF };
// tinyxml2 does not support utf16
/*
const unsigned char utf16be_bom[] = { 0xFE, 0xFF };
const unsigned char utf16le_bom[] = { 0xFF, 0xFE };
*/
// skip utf8 bom
if (!memcmp(q, utf8_bom, sizeof(utf8_bom)))
{
q += sizeof(utf8_bom);
}
/* else if (!memcmp(q, utf16le_bom, sizeof(utf16le_bom)) || !memcmp(q, utf16be_bom, sizeof(utf16be_bom)))
{
q += sizeof(utf16le_bom);
}
*/
// skip spaces
while (isspace(*q) && q < (unsigned char *)p + s)
{
q++;
}
// only parse the file if it starts with '<'
if (*q == '<')
{
is_valid = (doc.Parse(fp, size) == 0);
}
else
{
is_valid = false;
}
}
size_t Xml::Leanify(size_t size_leanified /*= 0*/)
{
const char *root_name = doc.RootElement()->Name();
// if the XML is fb2 file
if (strcmp(root_name, "FictionBook") == 0)
{
if (is_verbose)
{
std::cout << "FB2 detected." << std::endl;
}
if (depth < max_depth)
{
depth++;
// iterate through all binary element
for (auto e = doc.RootElement()->FirstChildElement("binary"); e; e = e->NextSiblingElement("binary"))
{
for (int i = 1; i < depth; i++)
{
std::cout << "-> ";
}
std::cout << e->Attribute("id") << std::endl;
const char *base64_data = e->GetText();
if (base64_data == nullptr)
{
std::cout << "No data found." << std::endl;
continue;
}
size_t base64_len = strlen(base64_data);
// 4 base64 character contains information of 3 bytes
size_t binary_len = 3 * base64_len / 4;
unsigned char *binary_data = new unsigned char[binary_len];
if (Base64Decode(base64_data, base64_len, binary_data, &binary_len))
{
std::cout << "Base64 decode error." << std::endl;
delete[] binary_data;
continue;
}
// Leanify embedded image
binary_len = LeanifyFile(binary_data, binary_len);
// allocate a few more bytes for padding
size_t new_base64_len = 4 * binary_len / 3 + 4;
char *new_base64_data = new char[new_base64_len];
if (Base64Encode(binary_data, binary_len, new_base64_data, new_base64_len))
{
std::cout << "Base64 encode error." << std::endl;
}
else if (strlen(new_base64_data) < base64_len)
{
e->SetText(new_base64_data);
}
delete[] binary_data;
delete[] new_base64_data;
}
depth--;
}
}
else if (strcmp(root_name, "svg") == 0)
{
if (is_verbose)
{
std::cout << "SVG detected." << std::endl;
}
TraverseElements(doc.RootElement(), [](tinyxml2::XMLElement* e)
{
// remove empty attribute
for (auto attr = e->FirstAttribute(); attr; attr = attr->Next())
{
auto value = attr->Value();
if (value == nullptr || *value == 0)
{
e->DeleteAttribute(attr->Name());
}
}
// remove empty text element and container element
auto name = e->Name();
if (e->NoChildren())
{
if (strcmp(name, "text") == 0 ||
strcmp(name, "tspan") == 0 ||
strcmp(name, "a") == 0 ||
strcmp(name, "defs") == 0 ||
strcmp(name, "g") == 0 ||
strcmp(name, "marker") == 0 ||
strcmp(name, "mask") == 0 ||
strcmp(name, "missing-glyph") == 0 ||
strcmp(name, "pattern") == 0 ||
strcmp(name, "switch") == 0 ||
strcmp(name, "symbol") == 0)
{
e->Parent()->DeleteChild(e);
return;
}
}
if (strcmp(name, "tref") == 0 && e->Attribute("xlink:href") == nullptr)
{
e->Parent()->DeleteChild(e);
return;
}
if (strcmp(name, "metadata") == 0)
{
e->Parent()->DeleteChild(e);
return;
}
});
}
// print leanified XML to memory
tinyxml2::XMLPrinter printer(0, true);
doc.Print(&printer);
size_t new_size = printer.CStrSize() - 1; // -1 for the \0
fp -= size_leanified;
if (new_size < size)
{
memcpy(fp, printer.CStr(), new_size);
return new_size;
}
else if (size_leanified)
{
memmove(fp, fp + size_leanified, size);
}
return size;
}
void Xml::TraverseElements(tinyxml2::XMLElement *ele, std::function<void(tinyxml2::XMLElement*)> callback)
{
for (auto e = ele->FirstChildElement(); e; e = e->NextSiblingElement())
{
TraverseElements(e, callback);
}
callback(ele);
}
<|endoftext|>
|
<commit_before>// Neptools.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "PacArchive.h"
using namespace neptools;
using namespace std;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
struct Options
{
wstring game_dir;
wstring out_dir;
};
void print_help(po::options_description desc)
{
cout << "\n\tUsage: neptools.exe <gamedir> <outdir>" << "\n\n";
cout << " <gamedir>\t\tDirectory of the game you want to extract files from." << '\n';
cout << " <outdir>\t\tOutput directory for extracted files." << "\n\n";
cout << desc << endl;
}
//Parse the command line
//
void parse_commandline(int argc, wchar_t** argv, Options options)
{
try
{
po::options_description general("General options");
general.add_options()
("help,h", "Display help message")
;
po::options_description dirs("Input and output directories");
dirs.add_options()
("gamedir", po::wvalue<wstring>(&options.game_dir)->value_name("dir"), "Directory of the game you want to extract files from.")
("outdir", po::wvalue<wstring>(&options.out_dir)->value_name("dir"), "Output directory for extraced files.")
;
po::options_description cmdline_options;
cmdline_options.add(general).add(dirs);
po::positional_options_description pos;
pos.add("gamedir", 1).add("outdir", 1);
po::variables_map vmap;
po::store(po::wcommand_line_parser(argc, argv).options(cmdline_options).positional(pos).run(), vmap);
if (vmap.count("help"))
{
print_help(general);
exit(1);
}
vmap.notify();
if (!vmap.count("gamedir"))
{
throw std::invalid_argument("No input directory set.");
}
if (!vmap.count("outdir"))
{
options.out_dir = fs::absolute(fs::system_complete(argv[0])).generic_wstring();
wcout << L"No outdir set. Using default: " << options.out_dir << endl;
}
}
catch (const exception& e)
{
wcout << e.what() << endl;
exit(1);
}
}
int wmain(int argc, wchar_t* argv[])
{
// initialize char <> wchar_t conversion from system locale
locale::global(locale(""));
// Process command line
Options options{ L"blah", L"blubb" };
parse_commandline(argc, argv, options);
return 0;
}
<commit_msg>Fixed parse_commandline param type.<commit_after>// Neptools.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "PacArchive.h"
using namespace neptools;
using namespace std;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
struct Options
{
wstring game_dir;
wstring out_dir;
};
void print_help(po::options_description desc)
{
cout << "\n\tUsage: neptools.exe <gamedir> <outdir>" << "\n\n";
cout << " <gamedir>\t\tDirectory of the game you want to extract files from." << '\n';
cout << " <outdir>\t\tOutput directory for extracted files." << "\n\n";
cout << desc << endl;
}
//Parse the command line
//
void parse_commandline(int argc, wchar_t** argv, Options& options)
{
try
{
po::options_description general("General options");
general.add_options()
("help,h", "Display help message")
;
po::options_description dirs("Input and output directories");
dirs.add_options()
("gamedir", po::wvalue<wstring>(&options.game_dir)->value_name("dir"), "Directory of the game you want to extract files from.")
("outdir", po::wvalue<wstring>(&options.out_dir)->value_name("dir"), "Output directory for extraced files.")
;
po::options_description cmdline_options;
cmdline_options.add(general).add(dirs);
po::positional_options_description pos;
pos.add("gamedir", 1).add("outdir", 1);
po::variables_map vmap;
po::store(po::wcommand_line_parser(argc, argv).options(cmdline_options).positional(pos).run(), vmap);
if (vmap.count("help"))
{
print_help(general);
exit(1);
}
vmap.notify();
if (!vmap.count("gamedir"))
{
throw std::invalid_argument("No input directory set.");
}
if (!vmap.count("outdir"))
{
options.out_dir = fs::absolute(fs::system_complete(argv[0])).generic_wstring();
wcout << L"No outdir set. Using default: " << options.out_dir << endl;
}
}
catch (const exception& e)
{
wcout << e.what() << endl;
exit(1);
}
}
int wmain(int argc, wchar_t* argv[])
{
// initialize char <> wchar_t conversion from system locale
locale::global(locale(""));
// Process command line
Options options{ L"", L"" };
parse_commandline(argc, argv, options);
wcout << L"Input dir: " << options.game_dir << L'\n';
wcout << L"output dir: " << options.out_dir << L'\n';
return 0;
}
<|endoftext|>
|
<commit_before>#include "zip.h"
#include <algorithm> // std::search
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <miniz/miniz.h>
#include "../leanify.h"
#include "../utils.h"
using std::cerr;
using std::endl;
using std::string;
using std::vector;
const uint8_t Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };
size_t Zip::Leanify(size_t size_leanified /*= 0*/) {
depth++;
uint8_t* fp_r = fp_;
uint8_t* p_read;
uint8_t* p_end = fp_ + size_;
uint8_t* fp_w = fp_ - size_leanified;
uint8_t* p_write = fp_w;
//1. find EOCD
// End of central directory record
const uint8_t eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };
uint8_t* p_searchstart = p_end - 65535 - 22;
if (p_searchstart < fp_r) p_searchstart = fp_r;
uint8_t* p_ecod = std::search(p_searchstart, p_end, eocd_header_magic, eocd_header_magic + sizeof(eocd_header_magic));
if (p_ecod == p_end) {
cerr << "EOCD not found!" << endl;
// abort
goto failure;
}
//2. find CD with EOCD
p_read = p_ecod;
if (p_read + 22 > p_end) {
cerr << "EOF with EOCD!" << endl;
// abort
goto failure;
}
uint16_t cd_parts = *(uint16_t*)(p_read + 4);
uint16_t cd_parts_total = *(uint16_t*)(p_read + 6);
uint16_t cd_count = *(uint16_t*)(p_read + 8);
uint16_t cd_count_total = *(uint16_t*)(p_read + 10);
uint32_t cd_size = *(uint32_t*)(p_read + 12);
uint8_t* cd_off = fp_r + *(uint32_t*)(p_read + 16);
uint16_t cd_comment_len = *(uint16_t*)(p_read + 20);
if (cd_parts > 0 || cd_parts_total > 0 ||
cd_count != cd_count_total) {
cerr << "Neither split split nor spanned archives is supported!" << endl;
// abort
goto failure;
}
if (cd_off + cd_size > p_end) {
cerr << "EOF with central directory!" << endl;
// ignore
}
//3. find all local file headers with CD
vector<uint32_t> local_header_offsets_r;
p_read = cd_off;
const uint8_t cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };
for (int entity = 0; entity < cd_count; ++entity) {
if (p_read + 46 > p_end) {
cerr << "EOF with central directory!" << endl;
// ignore
break;
}
if (memcmp(cd_off, cd_header_magic, sizeof(cd_header_magic))) {
cerr << "Central directory header magic mismatch!" << endl;
// ignore
break;
}
local_header_offsets_r.push_back(*(uint32_t*)(p_read + 42));
p_read += 46 + *(uint16_t*)(p_read + 28) + *(uint16_t*)(p_read + 30) + *(uint16_t*)(p_read + 32);
}
if (p_read - cd_off != cd_size) {
cerr << "Central directory size mismatch!" << endl;
//ignore
}
vector<uint32_t> local_header_offsets_w;
// TODO: check EOF using size_
// Local file header
for (uint32_t local_header_offset : local_header_offsets_r) {
p_read = fp_r + local_header_offset;
local_header_offsets_w.push_back(p_write - fp_w);
uint16_t filename_length = *(uint16_t*)(p_read + 26);
size_t header_size = 30 + filename_length;
// move header
memmove(p_write, p_read, header_size);
// if Extra field length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 28)) {
p_read += *(uint16_t*)(p_write + 28);
*(uint16_t*)(p_write + 28) = 0;
}
uint32_t* crc = (uint32_t*)(p_write + 14);
uint32_t* compressed_size = crc + 1;
uint32_t* uncompressed_size = compressed_size + 1;
uint32_t orig_comp_size = *compressed_size;
uint16_t flag = *(uint16_t*)(p_write + 6);
uint16_t* compression_method = (uint16_t*)(p_write + 8);
string filename(reinterpret_cast<char*>(p_write) + 30, filename_length);
// do not output filename if it is a directory
if ((orig_comp_size || *compression_method || flag & 8) && depth <= max_depth)
PrintFileName(filename);
// From Wikipedia:
// If bit 3 (0x08) of the general-purpose flags field is set,
// then the CRC-32 and file sizes are not known when the header is written.
// The fields in the local header are filled with zero,
// and the CRC-32 and size are appended in a 12-byte structure
// (optionally preceded by a 4-byte signature) immediately after the compressed data
if (flag & 8) {
// set this bit to 0
*(uint16_t*)(p_write + 6) &= ~8;
// data descriptor signature
const uint8_t dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };
// search for signature
uint8_t* dd = p_read + header_size;
do {
dd = std::search(dd + 1, p_end, dd_sign, dd_sign + 4);
if (dd == p_end) {
cerr << "data descriptor signature not found!" << endl;
// abort
// zip does not have 4-byte signature preceded
goto failure;
}
} while (*(uint32_t*)(dd + 8) != dd - p_read - header_size);
*crc = *(uint32_t*)(dd + 4);
*compressed_size = orig_comp_size = *(uint32_t*)(dd + 8);
*uncompressed_size = *(uint32_t*)(dd + 12);
}
// if compression method is not deflate or fast mode
// then only Leanify embedded file if the method is store
// otherwise just memmove the compressed part
if (*compression_method != 8 || (flag & 1) || is_fast) {
if (*compression_method == 0 && depth <= max_depth && !(flag & 1)) {
// method is store
if (orig_comp_size) {
uint32_t new_size = LeanifyFile(p_read + header_size, orig_comp_size, p_read - p_write, filename);
p_read += header_size + orig_comp_size;
*compressed_size = *uncompressed_size = new_size;
*crc = mz_crc32(0, p_write + header_size, new_size);
} else {
p_read += header_size;
}
} else {
// unsupported compression method or encrypted, move it
memmove(p_write + header_size, p_read + header_size, orig_comp_size);
p_read += header_size + orig_comp_size;
}
p_write += header_size + *compressed_size;
} else {
// the method is deflate, uncompress it and recompress with zopfli
p_read += header_size;
p_write += header_size;
if (*uncompressed_size) {
// uncompress
size_t s = 0;
uint8_t* buffer = static_cast<uint8_t*>(tinfl_decompress_mem_to_heap(p_read, orig_comp_size, &s, 0));
if (!buffer || s != *uncompressed_size || *crc != mz_crc32(0, buffer, *uncompressed_size)) {
cerr << "ZIP file corrupted!" << endl;
mz_free(buffer);
memmove(p_write, p_read, orig_comp_size);
p_read += orig_comp_size;
p_write += orig_comp_size;
continue;
}
// Leanify uncompressed file
uint32_t new_uncomp_size = LeanifyFile(buffer, s, 0, filename);
// recompress
uint8_t bp = 0, *out = nullptr;
size_t new_comp_size = 0;
ZopfliDeflate(&zopfli_options_, 2, 1, buffer, new_uncomp_size, &bp, &out, &new_comp_size);
// switch to store if deflate makes file larger
if (new_uncomp_size <= new_comp_size && new_uncomp_size <= orig_comp_size) {
*compression_method = 0;
*crc = mz_crc32(0, buffer, new_uncomp_size);
*compressed_size = new_uncomp_size;
*uncompressed_size = new_uncomp_size;
memcpy(p_write, buffer, new_uncomp_size);
p_write += new_uncomp_size;
} else if (new_comp_size < orig_comp_size) {
*crc = mz_crc32(0, buffer, new_uncomp_size);
*compressed_size = new_comp_size;
*uncompressed_size = new_uncomp_size;
memcpy(p_write, out, new_comp_size);
p_write += new_comp_size;
} else {
memmove(p_write, p_read, orig_comp_size);
p_write += orig_comp_size;
}
p_read += orig_comp_size;
mz_free(buffer);
delete[] out;
} else {
*compression_method = 0;
*compressed_size = 0;
p_read += orig_comp_size;
}
}
// we don't use data descriptor, so that can save more bytes (16 per file)
if (flag & 8)
p_read += 16;
}
uint8_t* central_directory = p_write;
p_read = cd_off;
// TODO: check EOF using size_
for (uint32_t local_header_offset : local_header_offsets_w) {
if (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic))) {
//Already checked before
cerr << "Central directory header magic mismatch!" << endl;
break;
}
if (p_read + 46 > p_end) {
//Already checked before
cerr << "EOF with central directory!" << endl;
break;
}
int header_size = 46 + *(uint16_t*)(p_read + 28);
// move header
memmove(p_write, p_read, header_size);
// set bit 3 of General purpose bit flag to 0
*(uint16_t*)(p_write + 8) &= ~8;
// if Extra field length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 30)) {
p_read += *(uint16_t*)(p_write + 30);
*(uint16_t*)(p_write + 30) = 0;
}
// if File comment length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 32)) {
p_read += *(uint16_t*)(p_write + 32);
*(uint16_t*)(p_write + 32) = 0;
}
uint8_t* local_header = fp_w + local_header_offset;
// copy new CRC-32, Compressed size, Uncompressed size_
// from Local file header to Central directory file header
memcpy(p_write + 16, local_header + 14, 12);
// update compression method
*(uint16_t*)(p_write + 10) = *(uint16_t*)(local_header + 8);
// new Local file header offset
*(uint32_t*)(p_write + 42) = local_header_offset + out_embed_off_;
p_read += header_size;
p_write += header_size;
}
// End of central directory record
p_read = p_ecod;
memmove(p_write, p_read, 12);
// Number of central directory records on this disk, Total number of central directory records
*(uint16_t*)(p_write + 8) = *(uint16_t*)(p_write + 10) = local_header_offsets_w.size();
// central directory size
*(uint32_t*)(p_write + 12) = p_write - central_directory;
// central directory offset
*(uint32_t*)(p_write + 16) = central_directory - fp_w + out_embed_off_;
// set comment length to 0
*(uint16_t*)(p_write + 20) = 0;
// 22 is the length of EOCD
size_ = p_write + 22 - fp_w;
fp_ = fp_w;
return size_;
failure:
return Format::Leanify(size_leanified);
}
<commit_msg>Fix compile error<commit_after>#include "zip.h"
#include <algorithm> // std::search
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
#include <miniz/miniz.h>
#include "../leanify.h"
#include "../utils.h"
using std::cerr;
using std::endl;
using std::string;
using std::vector;
const uint8_t Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };
size_t Zip::Leanify(size_t size_leanified /*= 0*/) {
depth++;
uint8_t* fp_r = fp_;
uint8_t* p_read;
uint8_t* p_end = fp_ + size_;
uint8_t* fp_w = fp_ - size_leanified;
uint8_t* p_write = fp_w;
//1. find EOCD
// End of central directory record
const uint8_t eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };
uint8_t* p_searchstart = p_end - 65535 - 22;
if (p_searchstart < fp_r) p_searchstart = fp_r;
uint8_t* p_ecod = std::search(p_searchstart, p_end, eocd_header_magic, eocd_header_magic + sizeof(eocd_header_magic));
if (p_ecod == p_end) {
cerr << "EOCD not found!" << endl;
// abort
return Format::Leanify(size_leanified);
}
//2. find CD with EOCD
p_read = p_ecod;
if (p_read + 22 > p_end) {
cerr << "EOF with EOCD!" << endl;
// abort
return Format::Leanify(size_leanified);
}
uint16_t cd_parts = *(uint16_t*)(p_read + 4);
uint16_t cd_parts_total = *(uint16_t*)(p_read + 6);
uint16_t cd_count = *(uint16_t*)(p_read + 8);
uint16_t cd_count_total = *(uint16_t*)(p_read + 10);
uint32_t cd_size = *(uint32_t*)(p_read + 12);
uint8_t* cd_off = fp_r + *(uint32_t*)(p_read + 16);
uint16_t cd_comment_len = *(uint16_t*)(p_read + 20);
if (cd_parts > 0 || cd_parts_total > 0 ||
cd_count != cd_count_total) {
cerr << "Neither split split nor spanned archives is supported!" << endl;
// abort
return Format::Leanify(size_leanified);
}
if (cd_off + cd_size > p_end) {
cerr << "EOF with central directory!" << endl;
// ignore
}
//3. find all local file headers with CD
vector<uint32_t> local_header_offsets_r;
p_read = cd_off;
const uint8_t cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };
for (int entity = 0; entity < cd_count; ++entity) {
if (p_read + 46 > p_end) {
cerr << "EOF with central directory!" << endl;
// ignore
break;
}
if (memcmp(cd_off, cd_header_magic, sizeof(cd_header_magic))) {
cerr << "Central directory header magic mismatch!" << endl;
// ignore
break;
}
local_header_offsets_r.push_back(*(uint32_t*)(p_read + 42));
p_read += 46 + *(uint16_t*)(p_read + 28) + *(uint16_t*)(p_read + 30) + *(uint16_t*)(p_read + 32);
}
if (p_read - cd_off != cd_size) {
cerr << "Central directory size mismatch!" << endl;
//ignore
}
vector<uint32_t> local_header_offsets_w;
// TODO: check EOF using size_
// Local file header
for (uint32_t local_header_offset : local_header_offsets_r) {
p_read = fp_r + local_header_offset;
local_header_offsets_w.push_back(p_write - fp_w);
uint16_t filename_length = *(uint16_t*)(p_read + 26);
size_t header_size = 30 + filename_length;
// move header
memmove(p_write, p_read, header_size);
// if Extra field length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 28)) {
p_read += *(uint16_t*)(p_write + 28);
*(uint16_t*)(p_write + 28) = 0;
}
uint32_t* crc = (uint32_t*)(p_write + 14);
uint32_t* compressed_size = crc + 1;
uint32_t* uncompressed_size = compressed_size + 1;
uint32_t orig_comp_size = *compressed_size;
uint16_t flag = *(uint16_t*)(p_write + 6);
uint16_t* compression_method = (uint16_t*)(p_write + 8);
string filename(reinterpret_cast<char*>(p_write) + 30, filename_length);
// do not output filename if it is a directory
if ((orig_comp_size || *compression_method || flag & 8) && depth <= max_depth)
PrintFileName(filename);
// From Wikipedia:
// If bit 3 (0x08) of the general-purpose flags field is set,
// then the CRC-32 and file sizes are not known when the header is written.
// The fields in the local header are filled with zero,
// and the CRC-32 and size are appended in a 12-byte structure
// (optionally preceded by a 4-byte signature) immediately after the compressed data
if (flag & 8) {
// set this bit to 0
*(uint16_t*)(p_write + 6) &= ~8;
// data descriptor signature
const uint8_t dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };
// search for signature
uint8_t* dd = p_read + header_size;
do {
dd = std::search(dd + 1, p_end, dd_sign, dd_sign + 4);
if (dd == p_end) {
cerr << "data descriptor signature not found!" << endl;
// abort
// zip does not have 4-byte signature preceded
return Format::Leanify(size_leanified);
}
} while (*(uint32_t*)(dd + 8) != dd - p_read - header_size);
*crc = *(uint32_t*)(dd + 4);
*compressed_size = orig_comp_size = *(uint32_t*)(dd + 8);
*uncompressed_size = *(uint32_t*)(dd + 12);
}
// if compression method is not deflate or fast mode
// then only Leanify embedded file if the method is store
// otherwise just memmove the compressed part
if (*compression_method != 8 || (flag & 1) || is_fast) {
if (*compression_method == 0 && depth <= max_depth && !(flag & 1)) {
// method is store
if (orig_comp_size) {
uint32_t new_size = LeanifyFile(p_read + header_size, orig_comp_size, p_read - p_write, filename);
p_read += header_size + orig_comp_size;
*compressed_size = *uncompressed_size = new_size;
*crc = mz_crc32(0, p_write + header_size, new_size);
} else {
p_read += header_size;
}
} else {
// unsupported compression method or encrypted, move it
memmove(p_write + header_size, p_read + header_size, orig_comp_size);
p_read += header_size + orig_comp_size;
}
p_write += header_size + *compressed_size;
} else {
// the method is deflate, uncompress it and recompress with zopfli
p_read += header_size;
p_write += header_size;
if (*uncompressed_size) {
// uncompress
size_t s = 0;
uint8_t* buffer = static_cast<uint8_t*>(tinfl_decompress_mem_to_heap(p_read, orig_comp_size, &s, 0));
if (!buffer || s != *uncompressed_size || *crc != mz_crc32(0, buffer, *uncompressed_size)) {
cerr << "ZIP file corrupted!" << endl;
mz_free(buffer);
memmove(p_write, p_read, orig_comp_size);
p_read += orig_comp_size;
p_write += orig_comp_size;
continue;
}
// Leanify uncompressed file
uint32_t new_uncomp_size = LeanifyFile(buffer, s, 0, filename);
// recompress
uint8_t bp = 0, *out = nullptr;
size_t new_comp_size = 0;
ZopfliDeflate(&zopfli_options_, 2, 1, buffer, new_uncomp_size, &bp, &out, &new_comp_size);
// switch to store if deflate makes file larger
if (new_uncomp_size <= new_comp_size && new_uncomp_size <= orig_comp_size) {
*compression_method = 0;
*crc = mz_crc32(0, buffer, new_uncomp_size);
*compressed_size = new_uncomp_size;
*uncompressed_size = new_uncomp_size;
memcpy(p_write, buffer, new_uncomp_size);
p_write += new_uncomp_size;
} else if (new_comp_size < orig_comp_size) {
*crc = mz_crc32(0, buffer, new_uncomp_size);
*compressed_size = new_comp_size;
*uncompressed_size = new_uncomp_size;
memcpy(p_write, out, new_comp_size);
p_write += new_comp_size;
} else {
memmove(p_write, p_read, orig_comp_size);
p_write += orig_comp_size;
}
p_read += orig_comp_size;
mz_free(buffer);
delete[] out;
} else {
*compression_method = 0;
*compressed_size = 0;
p_read += orig_comp_size;
}
}
// we don't use data descriptor, so that can save more bytes (16 per file)
if (flag & 8)
p_read += 16;
}
uint8_t* central_directory = p_write;
p_read = cd_off;
// TODO: check EOF using size_
for (uint32_t local_header_offset : local_header_offsets_w) {
if (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic))) {
//Already checked before
cerr << "Central directory header magic mismatch!" << endl;
break;
}
if (p_read + 46 > p_end) {
//Already checked before
cerr << "EOF with central directory!" << endl;
break;
}
int header_size = 46 + *(uint16_t*)(p_read + 28);
// move header
memmove(p_write, p_read, header_size);
// set bit 3 of General purpose bit flag to 0
*(uint16_t*)(p_write + 8) &= ~8;
// if Extra field length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 30)) {
p_read += *(uint16_t*)(p_write + 30);
*(uint16_t*)(p_write + 30) = 0;
}
// if File comment length is not 0, then skip it and set it to 0
if (*(uint16_t*)(p_write + 32)) {
p_read += *(uint16_t*)(p_write + 32);
*(uint16_t*)(p_write + 32) = 0;
}
uint8_t* local_header = fp_w + local_header_offset;
// copy new CRC-32, Compressed size, Uncompressed size_
// from Local file header to Central directory file header
memcpy(p_write + 16, local_header + 14, 12);
// update compression method
*(uint16_t*)(p_write + 10) = *(uint16_t*)(local_header + 8);
// new Local file header offset
*(uint32_t*)(p_write + 42) = local_header_offset + out_embed_off_;
p_read += header_size;
p_write += header_size;
}
// End of central directory record
p_read = p_ecod;
memmove(p_write, p_read, 12);
// Number of central directory records on this disk, Total number of central directory records
*(uint16_t*)(p_write + 8) = *(uint16_t*)(p_write + 10) = local_header_offsets_w.size();
// central directory size
*(uint32_t*)(p_write + 12) = p_write - central_directory;
// central directory offset
*(uint32_t*)(p_write + 16) = central_directory - fp_w + out_embed_off_;
// set comment length to 0
*(uint16_t*)(p_write + 20) = 0;
// 22 is the length of EOCD
size_ = p_write + 22 - fp_w;
fp_ = fp_w;
return size_;
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include <boost/filesystem.hpp>
#include <gtest/gtest.h>
#include "joynr/Settings.h"
#include "joynr/tests/testProxy.h"
#include "joynr/tests/TestBooleanBroadcastBroadcastFilterParameters.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/OnChangeSubscriptionQos.h"
#include "joynr/MulticastSubscriptionQos.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockTestProvider.h"
#include "tests/mock/MockSubscriptionListener.h"
using namespace ::testing;
using namespace joynr;
class PersistencyCreationTest : public testing::Test
{
public:
PersistencyCreationTest() :
runtime(nullptr),
testProvider(nullptr),
testProxy(nullptr),
domain("PersistencyCreationTest"),
providerParticipantId(),
semaphore(0),
MESSAGINGQOS_TTL(1000)
{
}
void init(const std::string& settings)
{
ccRuntime = JoynrClusterControllerRuntime::create(
std::make_unique<joynr::Settings>(settings));
types::ProviderQos providerQos;
providerQos.setScope(joynr::types::ProviderScope::LOCAL);
testProvider = std::make_shared<MockTestProvider>();
providerParticipantId = ccRuntime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);
// Create a proxy on runtimeAcOFF
auto testProxyBuilder = ccRuntime->createProxyBuilder<tests::testProxy>(domain);
DiscoveryQos discoveryQos;
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(1000);
testProxy = testProxyBuilder->setMessagingQos(MessagingQos(MESSAGINGQOS_TTL))
->setDiscoveryQos(discoveryQos)
->build();
}
void SetUp()
{
// Make sure there are no persisted files from previous test runs.
joynr::test::util::removeFileInCurrentDirectory(".*\\.settings");
joynr::test::util::removeFileInCurrentDirectory(".*\\.persist");
joynr::test::util::removeFileInCurrentDirectory(".*\\.entries");
}
void TearDown()
{
testProxy.reset();
ccRuntime->unregisterProvider(providerParticipantId);
testProvider.reset();
ccRuntime.reset();
// Delete test specific files
joynr::test::util::removeFileInCurrentDirectory(".*\\.settings");
joynr::test::util::removeFileInCurrentDirectory(".*\\.persist");
joynr::test::util::removeFileInCurrentDirectory(".*\\.entries");
}
protected:
std::shared_ptr<JoynrRuntime> runtime;
std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
std::shared_ptr<MockTestProvider> testProvider;
std::shared_ptr<tests::testProxy> testProxy;
std::string domain;
std::string providerParticipantId;
joynr::Semaphore semaphore;
const std::int64_t MESSAGINGQOS_TTL;
};
TEST_F(PersistencyCreationTest, testPersistencyFilesAreNotWrittenWhenDisabled)
{
init("test-resources/persistency-cc-disabled.settings");
std::string hello;
testProxy->sayHello(hello);
joynr::tests::TestBooleanBroadcastBroadcastFilterParameters filterParameters;
testProxy->subscribeToBooleanBroadcastBroadcast(
filterParameters,
std::make_shared<MockSubscriptionListenerOneType<bool>>(),
std::make_shared<OnChangeSubscriptionQos>()
);
testProxy->subscribeToATTRIBUTEWITHCAPITALLETTERS(
std::make_shared<MockSubscriptionListenerOneType<std::int32_t>>(),
std::make_shared<SubscriptionQos>()
);
testProxy->subscribeToLocationUpdateBroadcast(
std::make_shared<MockSubscriptionListenerOneType<joynr::types::Localisation::GpsLocation>>(),
std::make_shared<MulticastSubscriptionQos>()
);
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_MULTICAST_RECEIVER_DIRECTORY_PERSISTENCE_FILENAME()));
}
TEST_F(PersistencyCreationTest, testPersistencyFilesAreWrittenWhenEnabled)
{
init("test-resources/persistency-cc-enabled.settings");
std::string hello;
testProxy->sayHello(hello);
joynr::tests::TestBooleanBroadcastBroadcastFilterParameters filterParameters;
testProxy->subscribeToBooleanBroadcastBroadcast(
filterParameters,
std::make_shared<MockSubscriptionListenerOneType<bool>>(),
std::make_shared<OnChangeSubscriptionQos>()
);
testProxy->subscribeToATTRIBUTEWITHCAPITALLETTERS(
std::make_shared<MockSubscriptionListenerOneType<std::int32_t>>(),
std::make_shared<SubscriptionQos>()
);
testProxy->subscribeToLocationUpdateBroadcast(
std::make_shared<MockSubscriptionListenerOneType<joynr::types::Localisation::GpsLocation>>(),
std::make_shared<MulticastSubscriptionQos>()
);
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_MULTICAST_RECEIVER_DIRECTORY_PERSISTENCE_FILENAME()));
}
<commit_msg>[C++] PersistencyCreationTest waits for runtime destruction before deleting files<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include <boost/filesystem.hpp>
#include <gtest/gtest.h>
#include "joynr/Settings.h"
#include "joynr/tests/testProxy.h"
#include "joynr/tests/TestBooleanBroadcastBroadcastFilterParameters.h"
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/OnChangeSubscriptionQos.h"
#include "joynr/MulticastSubscriptionQos.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockTestProvider.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/utils/PtrUtils.h"
using namespace ::testing;
using namespace joynr;
class PersistencyCreationTest : public testing::Test
{
public:
PersistencyCreationTest() :
runtime(nullptr),
testProvider(nullptr),
testProxy(nullptr),
domain("PersistencyCreationTest"),
providerParticipantId(),
semaphore(0),
MESSAGINGQOS_TTL(1000)
{
}
void init(const std::string& settings)
{
ccRuntime = JoynrClusterControllerRuntime::create(
std::make_unique<joynr::Settings>(settings));
types::ProviderQos providerQos;
providerQos.setScope(joynr::types::ProviderScope::LOCAL);
testProvider = std::make_shared<MockTestProvider>();
providerParticipantId = ccRuntime->registerProvider<tests::testProvider>(domain, testProvider, providerQos);
// Create a proxy on runtimeAcOFF
auto testProxyBuilder = ccRuntime->createProxyBuilder<tests::testProxy>(domain);
DiscoveryQos discoveryQos;
discoveryQos.setDiscoveryScope(types::DiscoveryScope::LOCAL_ONLY);
discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
discoveryQos.setDiscoveryTimeoutMs(1000);
testProxy = testProxyBuilder->setMessagingQos(MessagingQos(MESSAGINGQOS_TTL))
->setDiscoveryQos(discoveryQos)
->build();
}
void SetUp()
{
// Make sure there are no persisted files from previous test runs.
joynr::test::util::removeFileInCurrentDirectory(".*\\.settings");
joynr::test::util::removeFileInCurrentDirectory(".*\\.persist");
joynr::test::util::removeFileInCurrentDirectory(".*\\.entries");
}
void TearDown()
{
testProxy.reset();
ccRuntime->unregisterProvider(providerParticipantId);
test::util::resetAndWaitUntilDestroyed(testProvider);
test::util::resetAndWaitUntilDestroyed(ccRuntime);
// Delete test specific files
joynr::test::util::removeFileInCurrentDirectory(".*\\.settings");
joynr::test::util::removeFileInCurrentDirectory(".*\\.persist");
joynr::test::util::removeFileInCurrentDirectory(".*\\.entries");
}
protected:
std::shared_ptr<JoynrRuntime> runtime;
std::shared_ptr<JoynrClusterControllerRuntime> ccRuntime;
std::shared_ptr<MockTestProvider> testProvider;
std::shared_ptr<tests::testProxy> testProxy;
std::string domain;
std::string providerParticipantId;
joynr::Semaphore semaphore;
const std::int64_t MESSAGINGQOS_TTL;
};
TEST_F(PersistencyCreationTest, testPersistencyFilesAreNotWrittenWhenDisabled)
{
init("test-resources/persistency-cc-disabled.settings");
std::string hello;
testProxy->sayHello(hello);
joynr::tests::TestBooleanBroadcastBroadcastFilterParameters filterParameters;
testProxy->subscribeToBooleanBroadcastBroadcast(
filterParameters,
std::make_shared<MockSubscriptionListenerOneType<bool>>(),
std::make_shared<OnChangeSubscriptionQos>()
);
testProxy->subscribeToATTRIBUTEWITHCAPITALLETTERS(
std::make_shared<MockSubscriptionListenerOneType<std::int32_t>>(),
std::make_shared<SubscriptionQos>()
);
testProxy->subscribeToLocationUpdateBroadcast(
std::make_shared<MockSubscriptionListenerOneType<joynr::types::Localisation::GpsLocation>>(),
std::make_shared<MulticastSubscriptionQos>()
);
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME()));
EXPECT_FALSE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_MULTICAST_RECEIVER_DIRECTORY_PERSISTENCE_FILENAME()));
}
TEST_F(PersistencyCreationTest, testPersistencyFilesAreWrittenWhenEnabled)
{
init("test-resources/persistency-cc-enabled.settings");
std::string hello;
testProxy->sayHello(hello);
joynr::tests::TestBooleanBroadcastBroadcastFilterParameters filterParameters;
testProxy->subscribeToBooleanBroadcastBroadcast(
filterParameters,
std::make_shared<MockSubscriptionListenerOneType<bool>>(),
std::make_shared<OnChangeSubscriptionQos>()
);
testProxy->subscribeToATTRIBUTEWITHCAPITALLETTERS(
std::make_shared<MockSubscriptionListenerOneType<std::int32_t>>(),
std::make_shared<SubscriptionQos>()
);
testProxy->subscribeToLocationUpdateBroadcast(
std::make_shared<MockSubscriptionListenerOneType<joynr::types::Localisation::GpsLocation>>(),
std::make_shared<MulticastSubscriptionQos>()
);
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME()));
EXPECT_TRUE(boost::filesystem::exists(ClusterControllerSettings::DEFAULT_MULTICAST_RECEIVER_DIRECTORY_PERSISTENCE_FILENAME()));
}
<|endoftext|>
|
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "cachingimageprovider.h"
#include "../Common/defines.h"
#include "../QMLExtensions/imagecachingservice.h"
#define RECACHE true
namespace QMLExtensions {
QString prepareUrl(const QString &url) {
QString id;
if (url.contains(QChar('%'))) {
QUrl initialUrl(url);
id = initialUrl.path();
} else {
id = url;
}
return id;
}
QImage CachingImageProvider::requestImage(const QString &url, QSize *size, const QSize &requestedSize) {
Q_ASSERT(!url.isEmpty());
if (url.isEmpty()) { return QImage(); }
const QString id = prepareUrl(url);
QString cachedPath;
bool needsUpdate = false;
if (m_ImageCachingService->tryGetCachedImage(id, requestedSize, cachedPath, needsUpdate)) {
QImage cachedImage(cachedPath);
if (needsUpdate) {
LOG_INFO << "Recaching image" << id;
m_ImageCachingService->cacheImage(id, requestedSize, RECACHE);
}
if (!cachedImage.isNull()) {
*size = cachedImage.size();
return cachedImage;
}
}
LOG_INTEGR_TESTS_OR_DEBUG << "Not found properly cached:" << id;
QImage originalImage(id);
QImage result;
if (requestedSize.isValid()) {
m_ImageCachingService->cacheImage(id, requestedSize);
result = originalImage.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
} else {
LOG_WARNING << "Size is invalid:" << requestedSize.width() << "x" << requestedSize.height();
m_ImageCachingService->cacheImage(id);
result = originalImage.scaled(m_ImageCachingService->getDefaultSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
*size = result.size();
return result;
}
}
<commit_msg>More mitigations for black thumbnails<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "cachingimageprovider.h"
#include "../Common/defines.h"
#include "../QMLExtensions/imagecachingservice.h"
#define RECACHE true
namespace QMLExtensions {
QString prepareUrl(const QString &url) {
QString id;
if (url.contains(QChar('%'))) {
QUrl initialUrl(url);
id = initialUrl.path();
} else {
id = url;
}
return id;
}
QImage CachingImageProvider::requestImage(const QString &url, QSize *size, const QSize &requestedSize) {
Q_ASSERT(!url.isEmpty());
if (url.isEmpty()) { return QImage(); }
const QString id = prepareUrl(url);
QString cachedPath;
bool needsUpdate = false;
if (m_ImageCachingService->tryGetCachedImage(id, requestedSize, cachedPath, needsUpdate)) {
if (needsUpdate) {
LOG_INFO << "Recaching image" << id;
m_ImageCachingService->cacheImage(id, requestedSize, RECACHE);
}
QImage cachedImage;
bool loaded = cachedImage.load(cachedPath);
if (loaded && !cachedImage.isNull()) {
*size = cachedImage.size();
return cachedImage;
}
}
LOG_INTEGR_TESTS_OR_DEBUG << "Not found properly cached:" << id;
QImage originalImage(id);
QImage result;
if (requestedSize.isValid()) {
m_ImageCachingService->cacheImage(id, requestedSize);
result = originalImage.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
} else {
LOG_WARNING << "Size is invalid:" << requestedSize.width() << "x" << requestedSize.height();
m_ImageCachingService->cacheImage(id);
result = originalImage.scaled(m_ImageCachingService->getDefaultSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
*size = result.size();
return result;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/games/dark_hex.h"
#include <memory> // Note where we use it ?
#include <utility> // Note where we use it ?
#include <vector>
#include "./hex.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace dark_hex {
namespace {
// Define the vars needed on the scope 'using' ?
using hex::kCellStates;
using hex::kDefaultBoardSize;
using hex::CellState;
using hex::StateToString;
using hex::PlayerToState;
// Game Facts
const GameType kGameType{
/*short_name=*/"dark_hex",
/*long_name=*/"Dark Hex",
GameType::Dynamics::kSequential,
GameType::ChanceMode::kDeterministic,
GameType::Information::kImperfectInformation,
GameType::Utility::kZeroSum,
GameType::RewardModel::kTerminal,
/*max_num_players=*/2,
/*min_num_players=*/2,
/*provides_information_state_string=*/true,
/*provides_information_state_tensor=*/true,
/*provides_observation_string=*/true,
/*provides_observation_tensor=*/true,
/*parameter_specification=*/
{
{"obstype", GameParameter(static_cast<std::string>(kDefaultObsType))},
{"board_size", GameParameter(hex::kDefaultBoardSize)},
}
};
std::shared_ptr<const Game> Factory(const GameParameters& params){
return std::shared_ptr<const Game>(
new DarkHexGame(params)
);
}
REGISTER_SPIEL_GAME(kGameType, Factory);
}
DarkHexState::DarkHexState(std::shared_ptr<const Game> game, int board_size,
ObservationType obs_type)
: State(game), state_(game, board_size), obs_type_(obs_type) {
std::fill(begin(black_view_), end(black_view_), CellState::kEmpty);
std::fill(begin(white_view_), end(white_view_), CellState::kEmpty);
}
void DarkHexState::DoApplyAction(Action move) {
Player cur_player = CurrentPlayer();//current player
auto& cur_view = (cur_player == Player(0) ? black_view_ : white_view_);
// Either occupied or not
if (state_.BoardAt(move) == CellState::kEmpty) {
state_.ApplyAction(move);
} else {}
SPIEL_CHECK_EQ(cur_view[move], CellState::kEmpty);
cur_view[move] = state_.BoardAt(move);
action_sequence_.push_back(std::pair<int,Action>(cur_player, move));
}
std::vector<Action> DarkHexState::LegalActions() const {
if (IsTerminal()) return {};
std::vector<Action> moves;
const Player player = CurrentPlayer();
const auto& cur_view = (player == Player{0} ? black_view_ : white_view_);
for (Action move = 0; move < kNumOfCells; ++move){
if (cur_view[move] == CellState::kEmpty){
moves.push_back(move);
}
}
return moves;
}
std::string DarkHexState::ViewToString(Player player) const {
const auto& cur_view = (player == Player{0} ? black_view_ : white_view_);
std::string str;
// TODO: ??
// Change here for row & cols after customizing for x, y
int num_rows = kDefaultBoardSize, num_cols = kDefaultBoardSize;
for (int r = 0; r < num_rows; ++r){
for (int c = 0; c < num_cols; ++c){
absl::StrAppend(&str, StateToString(cur_view[r * num_cols + c]));
}
if (r < (num_rows - 1)) absl::StrAppend(&str, "\n");
}
return str;
}
std::string DarkHexState::ActionSequenceToString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
std::string str;
for (const auto& player_with_action: action_sequence_) {
if (player_with_action.first == player) {
str.append(std::to_string(player_with_action.first));
str.push_back(',');
str.append(std::to_string(player_with_action.second));
str.push_back(' ');
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
str.append(std::to_string(player_with_action.first));
str.append(",? ");
} else {
SPIEL_CHECK_EQ(obs_type_, ObservationType::kRevealNothing);
}
}
return str;
}
std::string DarkHexState::InformationStateString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
return ViewToString(player) + "\n"
+ std::to_string(history_.size()) + "\n"
+ ActionSequenceToString(player);
}
void DarkHexState::InformationStateTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
// Didnt write these very carefully check again ??
const auto& player_view = (player == Player{0} ? black_view_ : white_view_);
SPIEL_CHECK_EQ(values.size(), kNumOfCells * kCellStates +
kLongestSequence * (1 + kBitsPerAction));
std::fill(values.begin(), values.end(), 0.);
for (int cell = 0; cell < kNumOfCells; ++cell) {
values[kNumOfCells * static_cast<int>(player_view[cell]) + cell] = 1.0; // what is this line ??
}
// Encoding the sequence
int offset = kNumOfCells * kCellStates;
// check auto& ??
for (const auto& player_with_action: action_sequence_) {
if (player_with_action.first == player) {
values[offset] = player_with_action.first;
values[offset + 1 + player_with_action.second] = 1.0; // Check this lines purpose ??
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
values[offset] = player_with_action.first;
values[offset + 1 + 10] = 1.0; // again ??
} else {
SPIEL_CHECK_EQ(obs_type_, ObservationType::kRevealNothing);
}
offset += (1 + kBitsPerAction);
}
}
std::string DarkHexState::ObservationString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
std::string observation = ViewToString(player);
if (obs_type_ == ObservationType::kRevealNumTurns){
absl::StrAppend(&observation, "\nTotal turns: ", action_sequence_.size());
}
return observation;
}
void DarkHexState::ObservationTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
SPIEL_CHECK_EQ(values.size(), game_->ObservationTensorSize());
std::fill(values.begin(), values.end(), 0.);
const auto& player_view = (player == Player{0} ? black_view_ : white_view_);
for (int cell = 0; cell < kNumOfCells; ++cell) {
values[kNumOfCells * static_cast<int>(player_view[cell]) + cell] = 1.0; // check this static_cast ??
}
if (obs_type_ == ObservationType::kRevealNumTurns) {
values[kNumOfCells * kCellStates + action_sequence_.size()] = 1.0;
}
}
std::unique_ptr<State> DarkHexState::Clone() const {
return std::unique_ptr<State>(new DarkHexState(*this));
}
void DarkHexState::UndoAction(Player player, Action move) {
Action last_move = action_sequence_.back().second;
SPIEL_CHECK_EQ(last_move, move);
if (state_.BoardAt(move) == PlayerToState(player)) {
state_.UndoAction(player, move);
} else { }
auto& player_view = (player == Player{0} ? black_view_ : white_view_);
player_view[move] = CellState::kEmpty;
action_sequence_.pop_back();
history_.pop_back();
}
DarkHexGame::DarkHexGame(const GameParameters& params)
: Game(kGameType, params),
game_(std::static_pointer_cast<const hex::HexGame>(LoadGame("hex"))),
board_size_(ParameterValue<int>("board_size")) {
std::string obs_type = ParameterValue<std::string>("obstype");
if (obs_type == "reveal-nothing") {
obs_type_ = ObservationType::kRevealNothing;
} else if (obs_type == "reveal-numturns") {
obs_type_ = ObservationType::kRevealNumTurns;
} else {
SpielFatalError(absl::StrCat("Unrecognized observation type: ", obs_type));
}
}
std::vector<int> DarkHexGame::InformationStateTensorShape() const {
return {1, kNumOfCells * kCellStates + kLongestSequence * (1 + kBitsPerAction)};
}
std::vector<int> DarkHexGame::ObservationTensorShape() const {
if (obs_type_ == ObservationType::kRevealNothing) {
return {kNumOfCells * kCellStates};
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
return {kNumOfCells * kCellStates + kLongestSequence};
} else {
SpielFatalError("Uknown observation type");
}
}
}
}<commit_msg>dh information state fixed<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/games/dark_hex.h"
#include <memory> // Note where we use it ?
#include <utility> // Note where we use it ?
#include <vector>
#include "./hex.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace dark_hex {
namespace {
// Define the vars needed on the scope 'using' ?
using hex::kCellStates;
using hex::kDefaultBoardSize;
using hex::CellState;
using hex::kMinValueCellState;
using hex::StateToString;
using hex::PlayerToState;
// Game Facts
const GameType kGameType{
/*short_name=*/"dark_hex",
/*long_name=*/"Dark Hex",
GameType::Dynamics::kSequential,
GameType::ChanceMode::kDeterministic,
GameType::Information::kImperfectInformation,
GameType::Utility::kZeroSum,
GameType::RewardModel::kTerminal,
/*max_num_players=*/2,
/*min_num_players=*/2,
/*provides_information_state_string=*/true,
/*provides_information_state_tensor=*/true,
/*provides_observation_string=*/true,
/*provides_observation_tensor=*/true,
/*parameter_specification=*/
{
{"obstype", GameParameter(static_cast<std::string>(kDefaultObsType))},
{"board_size", GameParameter(hex::kDefaultBoardSize)},
}
};
std::shared_ptr<const Game> Factory(const GameParameters& params){
return std::shared_ptr<const Game>(
new DarkHexGame(params)
);
}
REGISTER_SPIEL_GAME(kGameType, Factory);
}
DarkHexState::DarkHexState(std::shared_ptr<const Game> game, int board_size,
ObservationType obs_type)
: State(game), state_(game, board_size), obs_type_(obs_type) {
std::fill(begin(black_view_), end(black_view_), CellState::kEmpty);
std::fill(begin(white_view_), end(white_view_), CellState::kEmpty);
}
void DarkHexState::DoApplyAction(Action move) {
Player cur_player = CurrentPlayer();//current player
auto& cur_view = (cur_player == Player(0) ? black_view_ : white_view_);
// Either occupied or not
if (state_.BoardAt(move) == CellState::kEmpty) {
state_.ApplyAction(move);
} else {}
SPIEL_CHECK_EQ(cur_view[move], CellState::kEmpty);
cur_view[move] = state_.BoardAt(move);
action_sequence_.push_back(std::pair<int,Action>(cur_player, move));
}
std::vector<Action> DarkHexState::LegalActions() const {
if (IsTerminal()) return {};
std::vector<Action> moves;
const Player player = CurrentPlayer();
const auto& cur_view = (player == Player{0} ? black_view_ : white_view_);
for (Action move = 0; move < kNumOfCells; ++move){
if (cur_view[move] == CellState::kEmpty){
moves.push_back(move);
}
}
return moves;
}
std::string DarkHexState::ViewToString(Player player) const {
const auto& cur_view = (player == Player{0} ? black_view_ : white_view_);
std::string str;
// TODO: ??
// Change here for row & cols after customizing for x, y
int num_rows = kDefaultBoardSize, num_cols = kDefaultBoardSize;
for (int r = 0; r < num_rows; ++r){
for (int c = 0; c < num_cols; ++c){
absl::StrAppend(&str, StateToString(cur_view[r * num_cols + c]));
}
if (r < (num_rows - 1)) absl::StrAppend(&str, "\n");
}
return str;
}
std::string DarkHexState::ActionSequenceToString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
std::string str;
for (const auto& player_with_action: action_sequence_) {
if (player_with_action.first == player) {
str.append(std::to_string(player_with_action.first));
str.push_back(',');
str.append(std::to_string(player_with_action.second));
str.push_back(' ');
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
str.append(std::to_string(player_with_action.first));
str.append(",? ");
} else {
SPIEL_CHECK_EQ(obs_type_, ObservationType::kRevealNothing);
}
}
return str;
}
std::string DarkHexState::InformationStateString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
return ViewToString(player) + "\n"
+ std::to_string(history_.size()) + "\n"
+ ActionSequenceToString(player);
}
void DarkHexState::InformationStateTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
// Didnt write these very carefully check again ??
const auto& player_view = (player == Player{0} ? black_view_ : white_view_);
SPIEL_CHECK_EQ(values.size(), kNumOfCells * kCellStates +
kLongestSequence * (1 + kBitsPerAction));
std::fill(values.begin(), values.end(), 0.);
for (int cell = 0; cell < kNumOfCells; ++cell) {
if (values.size() <= kNumOfCells * (static_cast<int>(player_view[cell]) - kMinValueCellState) + cell) {
std::cout << "values full size:\t\t" << values.size() << std::endl;
std::cout << "values indexed here:\t\t" << kNumOfCells << " " << (static_cast<int>(player_view[cell]) - kMinValueCellState) << " " << cell << std::endl;
}
values[kNumOfCells * (static_cast<int>(player_view[cell]) - kMinValueCellState) + cell] = 1.0;
}
// Encoding the sequence
int offset = kNumOfCells * kCellStates;
// check auto& ??
for (const auto& player_with_action: action_sequence_) {
if (player_with_action.first == player) {
// if (values.size() <= offset || values.size() <= offset + 1 + player_with_action.second) {
// std::cout << "CHECK 2" << std::endl;
// std::cout << "values full size:\t\t" << values.size() << std::endl;
// std::cout << "values indexed here:\t\t" << offset << std::endl;
// std::cout << "values indexed here again:\t\t" << offset + 1 + player_with_action.second << std::endl;
// }
values[offset] = player_with_action.first;
values[offset + 1 + player_with_action.second] = 1.0; // Check this lines purpose ??
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
// if (values.size() <= offset || values.size() <= offset + 1 + 10) {
// std::cout << "CHECK 3" << std::endl;
// std::cout << "values full size:\t\t" << values.size() << std::endl;
// std::cout << "values indexed here:\t\t" << offset << std::endl;
// std::cout << "values indexed here again:\t\t" << offset + 1 + 10 << std::endl;
// }
values[offset] = player_with_action.first;
values[offset + 1 + 10] = 1.0; // again ??
} else {
SPIEL_CHECK_EQ(obs_type_, ObservationType::kRevealNothing);
}
offset += (1 + kBitsPerAction);
}
}
std::string DarkHexState::ObservationString(Player player) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
std::string observation = ViewToString(player);
if (obs_type_ == ObservationType::kRevealNumTurns){
absl::StrAppend(&observation, "\nTotal turns: ", action_sequence_.size());
}
return observation;
}
void DarkHexState::ObservationTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
SPIEL_CHECK_EQ(values.size(), game_->ObservationTensorSize());
std::fill(values.begin(), values.end(), 0.);
const auto& player_view = (player == Player{0} ? black_view_ : white_view_);
for (int cell = 0; cell < kNumOfCells; ++cell) {
// if (values.size() <= kNumOfCells * static_cast<int>(player_view[cell]) + cell) {
// std::cout << "values full size:\t\t" << values.size() << std::endl;
// std::cout << "values indexed here:\t\t" << kNumOfCells * static_cast<int>(player_view[cell]) + cell << std::endl;
// }
values[kNumOfCells * (static_cast<int>(player_view[cell]) - kMinValueCellState) + cell] = 1.0; // check this static_cast ??
}
if (obs_type_ == ObservationType::kRevealNumTurns) {
// if (values.size() <= kNumOfCells * kCellStates + action_sequence_.size()) {
// std::cout << "values full size:\t\t" << values.size() << std::endl;
// std::cout << "values indexed here:\t\t" << kNumOfCells * kCellStates + action_sequence_.size() << std::endl;
// }
values[kNumOfCells * kCellStates + action_sequence_.size()] = 1.0;
}
}
std::unique_ptr<State> DarkHexState::Clone() const {
return std::unique_ptr<State>(new DarkHexState(*this));
}
void DarkHexState::UndoAction(Player player, Action move) {
Action last_move = action_sequence_.back().second;
SPIEL_CHECK_EQ(last_move, move);
if (state_.BoardAt(move) == PlayerToState(player)) {
state_.UndoAction(player, move);
} else { }
auto& player_view = (player == Player{0} ? black_view_ : white_view_);
player_view[move] = CellState::kEmpty;
action_sequence_.pop_back();
history_.pop_back();
}
DarkHexGame::DarkHexGame(const GameParameters& params)
: Game(kGameType, params),
game_(std::static_pointer_cast<const hex::HexGame>(LoadGame("hex"))),
board_size_(ParameterValue<int>("board_size")) {
std::string obs_type = ParameterValue<std::string>("obstype");
if (obs_type == "reveal-nothing") {
obs_type_ = ObservationType::kRevealNothing;
} else if (obs_type == "reveal-numturns") {
obs_type_ = ObservationType::kRevealNumTurns;
} else {
SpielFatalError(absl::StrCat("Unrecognized observation type: ", obs_type));
}
}
std::vector<int> DarkHexGame::InformationStateTensorShape() const {
return {1, kNumOfCells * kCellStates + kLongestSequence * (1 + kBitsPerAction)};
}
std::vector<int> DarkHexGame::ObservationTensorShape() const {
if (obs_type_ == ObservationType::kRevealNothing) {
return {kNumOfCells * kCellStates};
} else if (obs_type_ == ObservationType::kRevealNumTurns) {
return {kNumOfCells * kCellStates + kLongestSequence};
} else {
SpielFatalError("Uknown observation type");
}
}
}
}<|endoftext|>
|
<commit_before>/*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include <set>
#include "ParallelConnectedComponents.h"
#include "../structures/Partition.h"
#include "../coarsening/PartitionCoarsening.h"
#include "../auxiliary/Log.h"
namespace NetworKit {
ParallelConnectedComponents::ParallelConnectedComponents(const Graph& G, bool coarsening) : G(G), coarsening(coarsening) {
}
void ParallelConnectedComponents::run() {
if (G.isDirected()) {
throw std::runtime_error("algorithm does not accept directed graphs");
}
// calculate connected components by label propagation
count z = G.upperNodeIdBound();
DEBUG("initializing labels");
component = Partition(z);
component.allToSingletons();
DEBUG("initializing active nodes");
const char INACTIVE = 0;
const char ACTIVE = 1;
std::vector<char> activeNodes(z); // record if node must be processed
std::vector<char> nextActiveNodes(z, ACTIVE); // for next iteration
DEBUG("main loop");
// count numActive = 0; // for debugging purposes only
count numIterations = 0;
bool change = true;
// only 8 iterations when coarsening is on, otherwise till no more changes happened
while (change && (!coarsening || numIterations < 8)) {
// TRACE("label propagation iteration");
activeNodes.swap(nextActiveNodes);
nextActiveNodes.assign(z, INACTIVE);
change = false;
// numActive = 0;
G.balancedParallelForNodes([&](node u) {
if (activeNodes[u] == ACTIVE) {
// ++numActive;
// get smallest
index smallest = component[u];
G.forNeighborsOf(u, [&](node v) {
smallest = std::min(smallest, component[v]);
});
if (component[u] != smallest) {
component.moveToSubset(smallest, u);
change = true;
G.forNeighborsOf(u, [&](node v) {
// only nodes that do not have the smallest component label
// will see a new component label because of the change of u,
// only they need to be activated
if (component[v] != smallest) {
nextActiveNodes[v] = ACTIVE;
}
});
}
}
});
// TRACE("num active: ", numActive);
++numIterations;
}
if (coarsening && numIterations == 8) { // TODO: externalize constant
// coarsen and make recursive call
PartitionCoarsening con;
std::pair<Graph, std::vector<node> > coarse = con.run(G, component);
ParallelConnectedComponents cc(coarse.first);
cc.run();
// apply to current graph
G.parallelForNodes([&](node u) {
component[u] = cc.componentOfNode(coarse.second[u]);
});
}
}
void ParallelConnectedComponents::runSequential() {
if (G.isDirected()) {
throw std::runtime_error("algorithm does not accept directed graphs");
}
// calculate connected components by label propagation
count z = G.upperNodeIdBound();
DEBUG("initializing labels");
component = Partition(z);
component.allToSingletons();
DEBUG("initializing active nodes");
std::vector<bool> activeNodes(z, true); // record if node must be processed
DEBUG("main loop");
// count numActive = 0; // for debugging purposes only
count numIterations = 0;
bool change = true;
// only 8 iterations when coarsening is on, otherwise till no more changes happened
while (change && (!coarsening || numIterations < 8)) {
// TRACE("label propagation iteration");
change = false;
// numActive = 0;
G.forNodes([&](node u) {
if (activeNodes[u]) {
// ++numActive;
// get smallest
index smallest = component[u];
G.forNeighborsOf(u, [&](node v) {
smallest = std::min(smallest, component[v]);
});
if (component[u] != smallest) {
component.moveToSubset(smallest, u);
change = true;
G.forNeighborsOf(u, [&](node v) {
// only nodes that do not have the smallest component label
// will see a new component label because of the change of u,
// only they need to be activated
if (component[v] != smallest) {
activeNodes[v] = true;
}
});
} else {
activeNodes[u] = false; // current node becomes inactive
}
}
});
// TRACE("num active: ", numActive);
++numIterations;
}
if (coarsening && numIterations == 8) { // TODO: externalize constant
// coarsen and make recursive call
PartitionCoarsening con;
std::pair<Graph, std::vector<node> > coarse = con.run(G, component);
ParallelConnectedComponents cc(coarse.first);
cc.run();
// apply to current graph
G.forNodes([&](node u) {
component[u] = cc.componentOfNode(coarse.second[u]);
});
}
}
Partition ParallelConnectedComponents::getPartition() {
return this->component;
}
count ParallelConnectedComponents::numberOfComponents() {
return this->component.numberOfSubsets();
}
count ParallelConnectedComponents::componentOfNode(node u) {
assert (component[u] != none);
return component[u];
}
}
<commit_msg>parallel coarsening in ParallelConnectedComponents<commit_after>/*
* ConnectedComponents.cpp
*
* Created on: Dec 16, 2013
* Author: cls
*/
#include <set>
#include "ParallelConnectedComponents.h"
#include "../structures/Partition.h"
#include "../coarsening/PartitionCoarsening.h"
#include "../auxiliary/Log.h"
namespace NetworKit {
ParallelConnectedComponents::ParallelConnectedComponents(const Graph& G, bool coarsening) : G(G), coarsening(coarsening) {
}
void ParallelConnectedComponents::run() {
if (G.isDirected()) {
throw std::runtime_error("algorithm does not accept directed graphs");
}
// calculate connected components by label propagation
count z = G.upperNodeIdBound();
DEBUG("initializing labels");
component = Partition(z);
component.allToSingletons();
DEBUG("initializing active nodes");
const char INACTIVE = 0;
const char ACTIVE = 1;
std::vector<char> activeNodes(z); // record if node must be processed
std::vector<char> nextActiveNodes(z, ACTIVE); // for next iteration
DEBUG("main loop");
// count numActive = 0; // for debugging purposes only
count numIterations = 0;
bool change = true;
// only 8 iterations when coarsening is on, otherwise till no more changes happened
while (change && (!coarsening || numIterations < 8)) {
// TRACE("label propagation iteration");
activeNodes.swap(nextActiveNodes);
nextActiveNodes.assign(z, INACTIVE);
change = false;
// numActive = 0;
G.balancedParallelForNodes([&](node u) {
if (activeNodes[u] == ACTIVE) {
// ++numActive;
// get smallest
index smallest = component[u];
G.forNeighborsOf(u, [&](node v) {
smallest = std::min(smallest, component[v]);
});
if (component[u] != smallest) {
component.moveToSubset(smallest, u);
change = true;
G.forNeighborsOf(u, [&](node v) {
// only nodes that do not have the smallest component label
// will see a new component label because of the change of u,
// only they need to be activated
if (component[v] != smallest) {
nextActiveNodes[v] = ACTIVE;
}
});
}
}
});
// TRACE("num active: ", numActive);
++numIterations;
}
if (coarsening && numIterations == 8) { // TODO: externalize constant
// coarsen and make recursive call
ParallelPartitionCoarsening con;
std::pair<Graph, std::vector<node> > coarse = con.run(G, component);
ParallelConnectedComponents cc(coarse.first);
cc.run();
// apply to current graph
G.parallelForNodes([&](node u) {
component[u] = cc.componentOfNode(coarse.second[u]);
});
}
}
void ParallelConnectedComponents::runSequential() {
if (G.isDirected()) {
throw std::runtime_error("algorithm does not accept directed graphs");
}
// calculate connected components by label propagation
count z = G.upperNodeIdBound();
DEBUG("initializing labels");
component = Partition(z);
component.allToSingletons();
DEBUG("initializing active nodes");
std::vector<bool> activeNodes(z, true); // record if node must be processed
DEBUG("main loop");
// count numActive = 0; // for debugging purposes only
count numIterations = 0;
bool change = true;
// only 8 iterations when coarsening is on, otherwise till no more changes happened
while (change && (!coarsening || numIterations < 8)) {
// TRACE("label propagation iteration");
change = false;
// numActive = 0;
G.forNodes([&](node u) {
if (activeNodes[u]) {
// ++numActive;
// get smallest
index smallest = component[u];
G.forNeighborsOf(u, [&](node v) {
smallest = std::min(smallest, component[v]);
});
if (component[u] != smallest) {
component.moveToSubset(smallest, u);
change = true;
G.forNeighborsOf(u, [&](node v) {
// only nodes that do not have the smallest component label
// will see a new component label because of the change of u,
// only they need to be activated
if (component[v] != smallest) {
activeNodes[v] = true;
}
});
} else {
activeNodes[u] = false; // current node becomes inactive
}
}
});
// TRACE("num active: ", numActive);
++numIterations;
}
if (coarsening && numIterations == 8) { // TODO: externalize constant
// coarsen and make recursive call
PartitionCoarsening con;
std::pair<Graph, std::vector<node> > coarse = con.run(G, component);
ParallelConnectedComponents cc(coarse.first);
cc.run();
// apply to current graph
G.forNodes([&](node u) {
component[u] = cc.componentOfNode(coarse.second[u]);
});
}
}
Partition ParallelConnectedComponents::getPartition() {
return this->component;
}
count ParallelConnectedComponents::numberOfComponents() {
return this->component.numberOfSubsets();
}
count ParallelConnectedComponents::componentOfNode(node u) {
assert (component[u] != none);
return component[u];
}
}
<|endoftext|>
|
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "../EntropySource.h"
#ifdef TARGET_NRF51822 /* Persistent storage supported on nrf51 platforms */
#include "nrf_soc.h"
#include "nrf_error.h"
#include "mbed.h"
/*
* nRF51 has a TRNG that we can access using SoftDevice.
*/
int eddystoneEntropyPoll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
uint32_t err = 0;
err = sd_rand_application_bytes_available_get((uint8_t*)olen);
if (err != NRF_SUCCESS) {
return(-1);
}
*olen = *olen > len ? len : *olen;
if (*olen)
{
err = sd_rand_application_vector_get(output, *olen);
if (err != NRF_SUCCESS) {
return(-1);
}
}
return( 0 );
}
#endif /* #ifdef TARGET_NRF51822 */<commit_msg>Fix and cleanup nrf entropy source.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* 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 "../EntropySource.h"
#ifdef TARGET_NRF51822 /* Persistent storage supported on nrf51 platforms */
#include "nrf_soc.h"
#include "nrf_error.h"
#include "mbed.h"
#include <mbedtls/entropy.h>
/*
* nRF51 has a TRNG that we can access using SoftDevice.
*/
int eddystoneEntropyPoll(void *data, unsigned char *output, size_t len, size_t *olen)
{
uint8_t bytes_available = 0;
// get the number of random bytes available
if (sd_rand_application_bytes_available_get(&bytes_available) != NRF_SUCCESS) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
// if there is more bytes available that what is requested,
// truncate the number of bytes in output to len, otherwise use the total
// of bytes available.
const uint8_t output_len = bytes_available > len ? len : bytes_available;
if (output_len) {
// transfer "output_len" random bytes to output.
if (sd_rand_application_vector_get(output, output_len) != NRF_SUCCESS) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
}
// Everything went fine, commit the output_len to the output parameter
*olen = output_len;
return 0;
}
#endif /* #ifdef TARGET_NRF51822 */
<|endoftext|>
|
<commit_before>//===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "DYLDRendezvous.h"
using namespace lldb;
using namespace lldb_private;
/// Locates the address of the rendezvous structure. Returns the address on
/// success and LLDB_INVALID_ADDRESS on failure.
static addr_t
ResolveRendezvousAddress(Process *process)
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
addr_t info_location;
addr_t info_addr;
Error error;
if (!process)
{
if (log)
log->Printf ("%s null process provided", __FUNCTION__);
return LLDB_INVALID_ADDRESS;
}
// Try to get it from our process. This might be a remote process and might
// grab it via some remote-specific mechanism.
info_location = process->GetImageInfoAddress();
if (log)
log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);
// If the process fails to return an address, fall back to seeing if the local object file can help us find it.
if (info_location == LLDB_INVALID_ADDRESS)
{
Target *target = &process->GetTarget();
if (target)
{
ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
Address addr = obj_file->GetImageInfoAddress(target);
if (addr.IsValid())
{
info_location = addr.GetLoadAddress(target);
if (log)
log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location);
}
else
{
if (log)
log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__);
}
}
}
if (info_location == LLDB_INVALID_ADDRESS)
{
if (log)
log->Printf ("%s FAILED - invalid info address", __FUNCTION__);
return LLDB_INVALID_ADDRESS;
}
if (log)
log->Printf ("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64, __FUNCTION__, process->GetAddressByteSize(), info_location);
info_addr = process->ReadPointerFromMemory(info_location, error);
if (error.Fail())
{
if (log)
log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ());
return LLDB_INVALID_ADDRESS;
}
if (info_addr == 0)
{
if (log)
log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location);
return LLDB_INVALID_ADDRESS;
}
return info_addr;
}
DYLDRendezvous::DYLDRendezvous(Process *process)
: m_process(process),
m_rendezvous_addr(LLDB_INVALID_ADDRESS),
m_current(),
m_previous(),
m_soentries(),
m_added_soentries(),
m_removed_soentries()
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
m_thread_info.valid = false;
// Cache a copy of the executable path
if (m_process)
{
Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
if (exe_mod)
{
exe_mod->GetFileSpec().GetPath(m_exe_path, PATH_MAX);
if (log)
log->Printf ("DYLDRendezvous::%s exe module executable path set: '%s'", __FUNCTION__, m_exe_path);
}
else
{
if (log)
log->Printf ("DYLDRendezvous::%s cannot cache exe module path: null executable module pointer", __FUNCTION__);
}
}
}
bool
DYLDRendezvous::Resolve()
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
const size_t word_size = 4;
Rendezvous info;
size_t address_size;
size_t padding;
addr_t info_addr;
addr_t cursor;
address_size = m_process->GetAddressByteSize();
padding = address_size - word_size;
if (log)
log->Printf ("DYLDRendezvous::%s address size: %zu, padding %zu", __FUNCTION__, address_size, padding);
if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
cursor = info_addr = ResolveRendezvousAddress(m_process);
else
cursor = info_addr = m_rendezvous_addr;
if (log)
log->Printf ("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);
if (cursor == LLDB_INVALID_ADDRESS)
return false;
if (!(cursor = ReadWord(cursor, &info.version, word_size)))
return false;
if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
return false;
if (!(cursor = ReadPointer(cursor, &info.brk)))
return false;
if (!(cursor = ReadWord(cursor, &info.state, word_size)))
return false;
if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
return false;
// The rendezvous was successfully read. Update our internal state.
m_rendezvous_addr = info_addr;
m_previous = m_current;
m_current = info;
return UpdateSOEntries();
}
bool
DYLDRendezvous::IsValid()
{
return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
}
bool
DYLDRendezvous::UpdateSOEntries()
{
SOEntry entry;
if (m_current.map_addr == 0)
return false;
// When the previous and current states are consistent this is the first
// time we have been asked to update. Just take a snapshot of the currently
// loaded modules.
if (m_previous.state == eConsistent && m_current.state == eConsistent)
return TakeSnapshot(m_soentries);
// If we are about to add or remove a shared object clear out the current
// state and take a snapshot of the currently loaded images.
if (m_current.state == eAdd || m_current.state == eDelete)
{
assert(m_previous.state == eConsistent);
m_soentries.clear();
m_added_soentries.clear();
m_removed_soentries.clear();
return TakeSnapshot(m_soentries);
}
assert(m_current.state == eConsistent);
// Otherwise check the previous state to determine what to expect and update
// accordingly.
if (m_previous.state == eAdd)
return UpdateSOEntriesForAddition();
else if (m_previous.state == eDelete)
return UpdateSOEntriesForDeletion();
return false;
}
bool
DYLDRendezvous::UpdateSOEntriesForAddition()
{
SOEntry entry;
iterator pos;
assert(m_previous.state == eAdd);
if (m_current.map_addr == 0)
return false;
for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
{
if (!ReadSOEntryFromMemory(cursor, entry))
return false;
// Only add shared libraries and not the executable.
// On Linux this is indicated by an empty path in the entry.
// On FreeBSD it is the name of the executable.
if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
continue;
pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
if (pos == m_soentries.end())
{
m_soentries.push_back(entry);
m_added_soentries.push_back(entry);
}
}
return true;
}
bool
DYLDRendezvous::UpdateSOEntriesForDeletion()
{
SOEntryList entry_list;
iterator pos;
assert(m_previous.state == eDelete);
if (!TakeSnapshot(entry_list))
return false;
for (iterator I = begin(); I != end(); ++I)
{
pos = std::find(entry_list.begin(), entry_list.end(), *I);
if (pos == entry_list.end())
m_removed_soentries.push_back(*I);
}
m_soentries = entry_list;
return true;
}
bool
DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list)
{
SOEntry entry;
if (m_current.map_addr == 0)
return false;
for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
{
if (!ReadSOEntryFromMemory(cursor, entry))
return false;
// Only add shared libraries and not the executable.
// On Linux this is indicated by an empty path in the entry.
// On FreeBSD it is the name of the executable.
if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
continue;
entry_list.push_back(entry);
}
return true;
}
addr_t
DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size)
{
Error error;
*dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
if (error.Fail())
return 0;
return addr + size;
}
addr_t
DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst)
{
Error error;
*dst = m_process->ReadPointerFromMemory(addr, error);
if (error.Fail())
return 0;
return addr + m_process->GetAddressByteSize();
}
std::string
DYLDRendezvous::ReadStringFromMemory(addr_t addr)
{
std::string str;
Error error;
if (addr == LLDB_INVALID_ADDRESS)
return std::string();
m_process->ReadCStringFromMemory(addr, str, error);
return str;
}
bool
DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry)
{
entry.clear();
entry.link_addr = addr;
if (!(addr = ReadPointer(addr, &entry.base_addr)))
return false;
// mips adds an extra load offset field to the link map struct on
// FreeBSD and NetBSD (need to validate other OSes).
// http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
if (arch.GetCore() == ArchSpec::eCore_mips64)
{
assert (arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
arch.GetTriple().getOS() == llvm::Triple::NetBSD);
addr_t mips_l_offs;
if (!(addr = ReadPointer(addr, &mips_l_offs)))
return false;
if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
return false;
}
if (!(addr = ReadPointer(addr, &entry.path_addr)))
return false;
if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
return false;
if (!(addr = ReadPointer(addr, &entry.next)))
return false;
if (!(addr = ReadPointer(addr, &entry.prev)))
return false;
entry.path = ReadStringFromMemory(entry.path_addr);
return true;
}
bool
DYLDRendezvous::FindMetadata(const char *name, PThreadField field, uint32_t& value)
{
Target& target = m_process->GetTarget();
SymbolContextList list;
if (!target.GetImages().FindSymbolsWithNameAndType (ConstString(name), eSymbolTypeAny, list))
return false;
Address address = list[0].symbol->GetAddress();
addr_t addr = address.GetLoadAddress (&target);
if (addr == LLDB_INVALID_ADDRESS)
return false;
Error error;
value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(addr + field*sizeof(uint32_t), sizeof(uint32_t), 0, error);
if (error.Fail())
return false;
if (field == eSize)
value /= 8; // convert bits to bytes
return true;
}
const DYLDRendezvous::ThreadInfo&
DYLDRendezvous::GetThreadInfo()
{
if (!m_thread_info.valid)
{
bool ok = true;
ok &= FindMetadata ("_thread_db_pthread_dtvp", eOffset, m_thread_info.dtv_offset);
ok &= FindMetadata ("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
ok &= FindMetadata ("_thread_db_link_map_l_tls_modid", eOffset, m_thread_info.modid_offset);
ok &= FindMetadata ("_thread_db_dtv_t_pointer_val", eOffset, m_thread_info.tls_offset);
if (ok)
m_thread_info.valid = true;
}
return m_thread_info;
}
void
DYLDRendezvous::DumpToLog(Log *log) const
{
int state = GetState();
if (!log)
return;
log->PutCString("DYLDRendezvous:");
log->Printf(" Address: %" PRIx64, GetRendezvousAddress());
log->Printf(" Version: %" PRIu64, GetVersion());
log->Printf(" Link : %" PRIx64, GetLinkMapAddress());
log->Printf(" Break : %" PRIx64, GetBreakAddress());
log->Printf(" LDBase : %" PRIx64, GetLDBase());
log->Printf(" State : %s",
(state == eConsistent) ? "consistent" :
(state == eAdd) ? "add" :
(state == eDelete) ? "delete" : "unknown");
iterator I = begin();
iterator E = end();
if (I != E)
log->PutCString("DYLDRendezvous SOEntries:");
for (int i = 1; I != E; ++I, ++i)
{
log->Printf("\n SOEntry [%d] %s", i, I->path.c_str());
log->Printf(" Base : %" PRIx64, I->base_addr);
log->Printf(" Path : %" PRIx64, I->path_addr);
log->Printf(" Dyn : %" PRIx64, I->dyn_addr);
log->Printf(" Next : %" PRIx64, I->next);
log->Printf(" Prev : %" PRIx64, I->prev);
}
}
<commit_msg>Update assertion in DYLDRendezvous.<commit_after>//===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "DYLDRendezvous.h"
using namespace lldb;
using namespace lldb_private;
/// Locates the address of the rendezvous structure. Returns the address on
/// success and LLDB_INVALID_ADDRESS on failure.
static addr_t
ResolveRendezvousAddress(Process *process)
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
addr_t info_location;
addr_t info_addr;
Error error;
if (!process)
{
if (log)
log->Printf ("%s null process provided", __FUNCTION__);
return LLDB_INVALID_ADDRESS;
}
// Try to get it from our process. This might be a remote process and might
// grab it via some remote-specific mechanism.
info_location = process->GetImageInfoAddress();
if (log)
log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);
// If the process fails to return an address, fall back to seeing if the local object file can help us find it.
if (info_location == LLDB_INVALID_ADDRESS)
{
Target *target = &process->GetTarget();
if (target)
{
ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
Address addr = obj_file->GetImageInfoAddress(target);
if (addr.IsValid())
{
info_location = addr.GetLoadAddress(target);
if (log)
log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location);
}
else
{
if (log)
log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__);
}
}
}
if (info_location == LLDB_INVALID_ADDRESS)
{
if (log)
log->Printf ("%s FAILED - invalid info address", __FUNCTION__);
return LLDB_INVALID_ADDRESS;
}
if (log)
log->Printf ("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64, __FUNCTION__, process->GetAddressByteSize(), info_location);
info_addr = process->ReadPointerFromMemory(info_location, error);
if (error.Fail())
{
if (log)
log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ());
return LLDB_INVALID_ADDRESS;
}
if (info_addr == 0)
{
if (log)
log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location);
return LLDB_INVALID_ADDRESS;
}
return info_addr;
}
DYLDRendezvous::DYLDRendezvous(Process *process)
: m_process(process),
m_rendezvous_addr(LLDB_INVALID_ADDRESS),
m_current(),
m_previous(),
m_soentries(),
m_added_soentries(),
m_removed_soentries()
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
m_thread_info.valid = false;
// Cache a copy of the executable path
if (m_process)
{
Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
if (exe_mod)
{
exe_mod->GetFileSpec().GetPath(m_exe_path, PATH_MAX);
if (log)
log->Printf ("DYLDRendezvous::%s exe module executable path set: '%s'", __FUNCTION__, m_exe_path);
}
else
{
if (log)
log->Printf ("DYLDRendezvous::%s cannot cache exe module path: null executable module pointer", __FUNCTION__);
}
}
}
bool
DYLDRendezvous::Resolve()
{
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
const size_t word_size = 4;
Rendezvous info;
size_t address_size;
size_t padding;
addr_t info_addr;
addr_t cursor;
address_size = m_process->GetAddressByteSize();
padding = address_size - word_size;
if (log)
log->Printf ("DYLDRendezvous::%s address size: %zu, padding %zu", __FUNCTION__, address_size, padding);
if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
cursor = info_addr = ResolveRendezvousAddress(m_process);
else
cursor = info_addr = m_rendezvous_addr;
if (log)
log->Printf ("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);
if (cursor == LLDB_INVALID_ADDRESS)
return false;
if (!(cursor = ReadWord(cursor, &info.version, word_size)))
return false;
if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
return false;
if (!(cursor = ReadPointer(cursor, &info.brk)))
return false;
if (!(cursor = ReadWord(cursor, &info.state, word_size)))
return false;
if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
return false;
// The rendezvous was successfully read. Update our internal state.
m_rendezvous_addr = info_addr;
m_previous = m_current;
m_current = info;
return UpdateSOEntries();
}
bool
DYLDRendezvous::IsValid()
{
return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
}
bool
DYLDRendezvous::UpdateSOEntries()
{
SOEntry entry;
if (m_current.map_addr == 0)
return false;
// When the previous and current states are consistent this is the first
// time we have been asked to update. Just take a snapshot of the currently
// loaded modules.
if (m_previous.state == eConsistent && m_current.state == eConsistent)
return TakeSnapshot(m_soentries);
// If we are about to add or remove a shared object clear out the current
// state and take a snapshot of the currently loaded images.
if (m_current.state == eAdd || m_current.state == eDelete)
{
assert(m_previous.state == eConsistent || (m_previous.state == eAdd && m_current.state == eDelete));
m_soentries.clear();
m_added_soentries.clear();
m_removed_soentries.clear();
return TakeSnapshot(m_soentries);
}
assert(m_current.state == eConsistent);
// Otherwise check the previous state to determine what to expect and update
// accordingly.
if (m_previous.state == eAdd)
return UpdateSOEntriesForAddition();
else if (m_previous.state == eDelete)
return UpdateSOEntriesForDeletion();
return false;
}
bool
DYLDRendezvous::UpdateSOEntriesForAddition()
{
SOEntry entry;
iterator pos;
assert(m_previous.state == eAdd);
if (m_current.map_addr == 0)
return false;
for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
{
if (!ReadSOEntryFromMemory(cursor, entry))
return false;
// Only add shared libraries and not the executable.
// On Linux this is indicated by an empty path in the entry.
// On FreeBSD it is the name of the executable.
if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
continue;
pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
if (pos == m_soentries.end())
{
m_soentries.push_back(entry);
m_added_soentries.push_back(entry);
}
}
return true;
}
bool
DYLDRendezvous::UpdateSOEntriesForDeletion()
{
SOEntryList entry_list;
iterator pos;
assert(m_previous.state == eDelete);
if (!TakeSnapshot(entry_list))
return false;
for (iterator I = begin(); I != end(); ++I)
{
pos = std::find(entry_list.begin(), entry_list.end(), *I);
if (pos == entry_list.end())
m_removed_soentries.push_back(*I);
}
m_soentries = entry_list;
return true;
}
bool
DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list)
{
SOEntry entry;
if (m_current.map_addr == 0)
return false;
for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
{
if (!ReadSOEntryFromMemory(cursor, entry))
return false;
// Only add shared libraries and not the executable.
// On Linux this is indicated by an empty path in the entry.
// On FreeBSD it is the name of the executable.
if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
continue;
entry_list.push_back(entry);
}
return true;
}
addr_t
DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size)
{
Error error;
*dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
if (error.Fail())
return 0;
return addr + size;
}
addr_t
DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst)
{
Error error;
*dst = m_process->ReadPointerFromMemory(addr, error);
if (error.Fail())
return 0;
return addr + m_process->GetAddressByteSize();
}
std::string
DYLDRendezvous::ReadStringFromMemory(addr_t addr)
{
std::string str;
Error error;
if (addr == LLDB_INVALID_ADDRESS)
return std::string();
m_process->ReadCStringFromMemory(addr, str, error);
return str;
}
bool
DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry)
{
entry.clear();
entry.link_addr = addr;
if (!(addr = ReadPointer(addr, &entry.base_addr)))
return false;
// mips adds an extra load offset field to the link map struct on
// FreeBSD and NetBSD (need to validate other OSes).
// http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
if (arch.GetCore() == ArchSpec::eCore_mips64)
{
assert (arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
arch.GetTriple().getOS() == llvm::Triple::NetBSD);
addr_t mips_l_offs;
if (!(addr = ReadPointer(addr, &mips_l_offs)))
return false;
if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
return false;
}
if (!(addr = ReadPointer(addr, &entry.path_addr)))
return false;
if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
return false;
if (!(addr = ReadPointer(addr, &entry.next)))
return false;
if (!(addr = ReadPointer(addr, &entry.prev)))
return false;
entry.path = ReadStringFromMemory(entry.path_addr);
return true;
}
bool
DYLDRendezvous::FindMetadata(const char *name, PThreadField field, uint32_t& value)
{
Target& target = m_process->GetTarget();
SymbolContextList list;
if (!target.GetImages().FindSymbolsWithNameAndType (ConstString(name), eSymbolTypeAny, list))
return false;
Address address = list[0].symbol->GetAddress();
addr_t addr = address.GetLoadAddress (&target);
if (addr == LLDB_INVALID_ADDRESS)
return false;
Error error;
value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(addr + field*sizeof(uint32_t), sizeof(uint32_t), 0, error);
if (error.Fail())
return false;
if (field == eSize)
value /= 8; // convert bits to bytes
return true;
}
const DYLDRendezvous::ThreadInfo&
DYLDRendezvous::GetThreadInfo()
{
if (!m_thread_info.valid)
{
bool ok = true;
ok &= FindMetadata ("_thread_db_pthread_dtvp", eOffset, m_thread_info.dtv_offset);
ok &= FindMetadata ("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
ok &= FindMetadata ("_thread_db_link_map_l_tls_modid", eOffset, m_thread_info.modid_offset);
ok &= FindMetadata ("_thread_db_dtv_t_pointer_val", eOffset, m_thread_info.tls_offset);
if (ok)
m_thread_info.valid = true;
}
return m_thread_info;
}
void
DYLDRendezvous::DumpToLog(Log *log) const
{
int state = GetState();
if (!log)
return;
log->PutCString("DYLDRendezvous:");
log->Printf(" Address: %" PRIx64, GetRendezvousAddress());
log->Printf(" Version: %" PRIu64, GetVersion());
log->Printf(" Link : %" PRIx64, GetLinkMapAddress());
log->Printf(" Break : %" PRIx64, GetBreakAddress());
log->Printf(" LDBase : %" PRIx64, GetLDBase());
log->Printf(" State : %s",
(state == eConsistent) ? "consistent" :
(state == eAdd) ? "add" :
(state == eDelete) ? "delete" : "unknown");
iterator I = begin();
iterator E = end();
if (I != E)
log->PutCString("DYLDRendezvous SOEntries:");
for (int i = 1; I != E; ++I, ++i)
{
log->Printf("\n SOEntry [%d] %s", i, I->path.c_str());
log->Printf(" Base : %" PRIx64, I->base_addr);
log->Printf(" Path : %" PRIx64, I->path_addr);
log->Printf(" Dyn : %" PRIx64, I->dyn_addr);
log->Printf(" Next : %" PRIx64, I->next);
log->Printf(" Prev : %" PRIx64, I->prev);
}
}
<|endoftext|>
|
<commit_before>/* chronos - a crude substitution for POSIX `time` command line utility
on Windows.
Aggregates and reports user and kernel times for process and its children.
Attempts to mimic output format used on Linux
Copyright (c) 2016, Grigory Rechistov
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <windows.h>
/* Get a human-readable description of the last error.
Kinda like POSIX's strerror() */
std::wstring GetLastErrorDescription() {
DWORD errcode = GetLastError();
if (errcode == 0) return std::wstring();
LPWSTR buf = NULL;
size_t bufSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, errcode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&buf, 0, NULL);
std::wstring message(buf, bufSize);
LocalFree(buf);
return message;
}
void UsageAndExit(wchar_t *argv[]) {
std::wcerr <<
"chronos - report wallclock, user and system times of process\n"
"Copyright (c) 2016, Grigory Rechistov\n\n"
"Usage: " << argv[0] << " [-v] [-o file] [--] program [options]\n"
"\n"
"Run program and report its resources usage\n"
" --verbose, -v produce results in verbose format\n"
" --output, -o filename write result to filename instead of stdout\n"
" program program name to start\n"
" options the program's own arguments\n" << std::endl;
exit(1);
}
/* Discovered command line options */
struct CliParams {
bool verbose; /* true if verbose output */
std::wstring outputFileName; /* file name to write results, or empty string */
std::wstring cmdLine; /* The rest of command line options combined in a string */
std::wstring progName; /* Isolated program name to create */
};
/* Returns true on success, false if parsing failed */
/* BUG: may not handle quoted arguments and spaces in them as a whole */
bool ParseArgv(int argc, wchar_t *argv[], CliParams &result) {
assert(argc >= 1);
argv++;
argc--;
std::vector<std::wstring> arguments(argc);
/* We start counting from 1 to omit program name */
for (int i = 0; i < argc; i++) {
arguments[i] = std::wstring(argv[i]);
}
int argNo = 0;
bool consumeNextPositionalArgument = false;
std::wstring posArg(L"");
while (argNo < argc) {
std::wstring &curWord = arguments[argNo];
if (consumeNextPositionalArgument) {
posArg = curWord;
consumeNextPositionalArgument = false;
argNo++;
continue;
}
if (!curWord.compare(L"--")) {
/* Optional separator of flags and positional arguments */
argNo++; /* skip the "--" itself */
break;
}
/* Look for matches for supported options */
if (curWord.find(L"-o") == 0) {
curWord = curWord.substr(2); /* remove the '-o' part */
if (curWord.empty()) { /* must be the next word */
consumeNextPositionalArgument = true;
} else { /* argument is attached to the flag */
posArg = curWord;
}
} else if (curWord.find(L"--output") == 0) {
curWord = curWord.substr(8);
if (curWord.empty()) {
consumeNextPositionalArgument = true;
} else {
posArg = curWord;
}
} else if (!curWord.compare(L"-v")
|| !curWord.compare(L"--verbose")) {
result.verbose = true;
} else if (!curWord.compare(L"-h")
|| !curWord.compare(L"--help")) {
/* Help asked */
return false;
} else if (curWord.find(L"-") == 0) { /* Unknown option */
std::wcerr << "Unknown option " << curWord << std::endl;
return false;
break;
} else { /* Non positional arguments have started */
break;
}
argNo++;
}
if (!posArg.compare(L"--")) {
std::wcerr << "Missing positional argument" << std::endl;
return false;
}
if (posArg.length() != 0) {
result.outputFileName = posArg;
}
/* Check if there is at least one positional parameter left */
if (argNo == argc) {
std::wcerr << "Missing program name" << std::endl;
return false;
}
result.progName = arguments[argNo];
result.cmdLine = result.progName;
/* Concatenate all arguments into one line */
for (int i = argNo + 1; i < argc; i++) {
result.cmdLine += L" " + arguments[i];
}
/* For BAT files, the program name should be "cmd.exe /c",
otherwise it might not work correctly */
// TODO
return true;
}
int wmain(int argc, wchar_t* argv[]) {
const double timeUnit = 1.0e-7; /* 100 nanoseconds time resolution unit */
int ret = 0;
/* Parse command line arguments */
CliParams params = { 0 };
if (!ParseArgv(argc, argv, params)) {
UsageAndExit(argv);
}
/* Prepare to start application */
STARTUPINFO startUp;
GetStartupInfo(&startUp);
/* Start program in paused state */
PROCESS_INFORMATION procInfo;
if (!CreateProcess(params.progName.c_str(), const_cast<LPWSTR>(params.cmdLine.c_str()), NULL, NULL, TRUE,
CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS, NULL, NULL, &startUp, &procInfo)) {
std::wcerr << L"Unable to start the process: "
<< GetLastErrorDescription() << std::endl;
return 127;
}
HANDLE hProcess = procInfo.hProcess;
/* Create job object and attach the process to it */
HANDLE hJob = CreateJobObject(NULL, NULL); // XXX no security attributes passed
assert(hJob != NULL);
ret = AssignProcessToJobObject(hJob, hProcess);
assert(ret);
/* Now run the process and allow it to spawn children */
ResumeThread(procInfo.hThread);
/* Block until the process terminates */
if (WaitForSingleObject(hProcess, INFINITE) != WAIT_OBJECT_0) {
std::wcerr << L"Failed waiting for process termination: "
<< GetLastErrorDescription() << std::endl;
return 127;
}
DWORD exitCode = 0;
ret = GetExitCodeProcess(hProcess, &exitCode);
assert(ret);
/* Calculate wallclock time in hundreds of nanoseconds.
Ignore user and kernel times (third and fourth return parameters) */
FILETIME createTime, exitTime, unusedTime;
ret = GetProcessTimes(hProcess, &createTime, &exitTime, &unusedTime, &unusedTime);
assert(ret);
LONGLONG createTime100Ns = (LONGLONG)createTime.dwHighDateTime << 32 | createTime.dwLowDateTime;
LONGLONG exitTime100Ns = (LONGLONG)exitTime.dwHighDateTime << 32 | exitTime.dwLowDateTime;
LONGLONG wallclockTime100Ns = exitTime100Ns - createTime100Ns;
/* Get total user and kernel times for all processes of the job object */
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION jobInfo;
ret = QueryInformationJobObject(hJob, JobObjectBasicAccountingInformation,
&jobInfo, sizeof(jobInfo), NULL);
assert(ret);
/* Close unused handlers */
CloseHandle(hProcess);
CloseHandle(hJob);
if (jobInfo.ActiveProcesses != 0) {
std::cerr << "Warning: there are still "
<< jobInfo.ActiveProcesses
<< " alive children processes" << std::endl;
/* We may kill survived processes, if desired */
//std::cerr << "Killing them" << std::endl;
//TerminateJobObject(hJob, 127);
}
/* Get kernel and user times in hundreds of nanoseconds */
LONGLONG kernelTime100Ns = jobInfo.TotalKernelTime.QuadPart;
LONGLONG userTime100Ns = jobInfo.TotalUserTime.QuadPart;
DWORD pageFaults = jobInfo.TotalPageFaultCount; /* Also available, why not report it as well */
/* Choose where to print results - to a file or stdout */
std::wstreambuf *buf;
std::wofstream of;
if (!params.outputFileName.empty()) {
of.open(params.outputFileName);
buf = of.rdbuf();
} else {
buf = std::wcout.rdbuf();
}
std::wostream out(buf);
/* Print floats with two digits after the dot */
out << std::fixed << std::setprecision(2);
out << std::endl;
if (params.verbose) {
out << L"Command being timed: " << L"\"" << params.cmdLine << L"\"" << std::endl;
out << "Elapsed (wall clock) time (seconds): " << timeUnit * wallclockTime100Ns << std::endl;
out << "User time (seconds): " << timeUnit * userTime100Ns << std::endl;
out << "System time (seconds): " << timeUnit * kernelTime100Ns << std::endl;
out << "Page faults: " << pageFaults << std::endl;
out << "Exit status: " << exitCode << std::endl;
} else {
/* Match POSIX time output */
out << "real" << "\t" << timeUnit * wallclockTime100Ns << "s"<< std::endl;
out << "user" << "\t" << timeUnit * userTime100Ns << "s" << std::endl;
out << "sys" << "\t" << timeUnit * kernelTime100Ns << "s" << std::endl;
}
if (of.is_open()) {
of.close();
}
return exitCode;
}
<commit_msg>Attempt to fix the problem with running BAT vs EXE<commit_after>/* chronos - a crude substitution for POSIX `time` command line utility
on Windows.
Aggregates and reports user and kernel times for process and its children.
Attempts to mimic output format used on Linux
Copyright (c) 2016, Grigory Rechistov
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <windows.h>
/* Get a human-readable description of the last error.
Kinda like POSIX's strerror() */
static std::wstring GetLastErrorDescription() {
DWORD errcode = GetLastError();
if (errcode == 0) return std::wstring();
LPWSTR buf = NULL;
size_t bufSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, errcode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&buf, 0, NULL);
std::wstring message(buf, bufSize);
LocalFree(buf);
return message;
}
/* Return true if s contains path to BAT file */
static bool IsBatFile(const std::wstring &s) {
// XXX I cannot seem to invent a proper way to decide
// if the file is a batch script. Use a name heuristic
if (s.rfind(L".bat") == s.length() - 4)
return true;
return false;
}
static void UsageAndExit(wchar_t *argv[]) {
std::wcerr <<
"chronos - report wallclock, user and system times of process\n"
"Copyright (c) 2016, Grigory Rechistov\n\n"
"Usage: " << argv[0] << " [-v] [-o file] [--] program [options]\n"
"\n"
"Run program and report its resources usage\n"
" --verbose, -v produce results in verbose format\n"
" --output, -o filename write result to filename instead of stdout\n"
" program program name to start\n"
" options the program's own arguments\n" << std::endl;
exit(1);
}
/* Discovered command line options */
struct CliParams {
bool verbose; /* true if verbose output */
std::wstring outputFileName; /* file name to write results, or empty string */
std::wstring cmdLine; /* The rest of command line options combined in a string */
std::wstring progName; /* Isolated program name to create */
};
/* Returns true on success, false if parsing failed */
/* BUG: may not handle quoted arguments and spaces in them as a whole */
static bool ParseArgv(int argc, wchar_t *argv[], CliParams &result) {
assert(argc >= 1);
argv++;
argc--;
std::vector<std::wstring> arguments(argc);
/* We start counting from 1 to omit program name */
for (int i = 0; i < argc; i++) {
arguments[i] = std::wstring(argv[i]);
}
int argNo = 0;
bool consumeNextPositionalArgument = false;
std::wstring posArg(L"");
while (argNo < argc) {
std::wstring &curWord = arguments[argNo];
if (consumeNextPositionalArgument) {
posArg = curWord;
consumeNextPositionalArgument = false;
argNo++;
continue;
}
if (!curWord.compare(L"--")) {
/* Optional separator of flags and positional arguments */
argNo++; /* skip the "--" itself */
break;
}
/* Look for matches for supported options */
if (curWord.find(L"-o") == 0) {
curWord = curWord.substr(2); /* remove the '-o' part */
if (curWord.empty()) { /* must be the next word */
consumeNextPositionalArgument = true;
} else { /* argument is attached to the flag */
posArg = curWord;
}
} else if (curWord.find(L"--output") == 0) {
curWord = curWord.substr(8);
if (curWord.empty()) {
consumeNextPositionalArgument = true;
} else {
posArg = curWord;
}
} else if (!curWord.compare(L"-v")
|| !curWord.compare(L"--verbose")) {
result.verbose = true;
} else if (!curWord.compare(L"-h")
|| !curWord.compare(L"--help")) {
/* Help asked */
return false;
} else if (curWord.find(L"-") == 0) { /* Unknown option */
std::wcerr << "Unknown option " << curWord << std::endl;
return false;
break;
} else { /* Non positional arguments have started */
break;
}
argNo++;
}
if (!posArg.compare(L"--")) {
std::wcerr << "Missing positional argument" << std::endl;
return false;
}
if (posArg.length() != 0) {
result.outputFileName = posArg;
}
/* Check if there is at least one positional parameter left */
if (argNo == argc) {
std::wcerr << "Missing program name" << std::endl;
return false;
}
result.progName = arguments[argNo];
result.cmdLine = result.progName;
/* Concatenate all arguments into one line */
for (int i = argNo + 1; i < argc; i++) {
result.cmdLine += L" " + arguments[i];
}
return true;
}
int wmain(int argc, wchar_t* argv[]) {
const double timeUnit = 1.0e-7; /* 100 nanoseconds time resolution unit */
int ret = 0;
/* Parse command line arguments */
CliParams params = { 0 };
if (!ParseArgv(argc, argv, params)) {
UsageAndExit(argv);
}
/* Prepare to start application */
STARTUPINFO startUp;
GetStartupInfo(&startUp);
/* Start program in paused state */
PROCESS_INFORMATION procInfo;
const wchar_t *programNamePtr = NULL;
if (IsBatFile(params.progName)) {
/* Running batch files is unnecessarily tricky.
Leave parsing of command line arguments to the system.
The drawback - potential security problem for program names
with spaces */
programNamePtr = NULL;
} else {
programNamePtr = params.progName.c_str();
}
if (!CreateProcess(programNamePtr,
const_cast<LPWSTR>(params.cmdLine.c_str()),
NULL, NULL, TRUE,
CREATE_SUSPENDED | NORMAL_PRIORITY_CLASS,
NULL, NULL, &startUp, &procInfo)) {
std::wcerr << L"Unable to start the process: "
<< GetLastErrorDescription() << std::endl;
return 127;
}
HANDLE hProcess = procInfo.hProcess;
/* Create job object and attach the process to it */
HANDLE hJob = CreateJobObject(NULL, NULL); // XXX no security attributes passed
assert(hJob != NULL);
ret = AssignProcessToJobObject(hJob, hProcess);
assert(ret);
/* Now run the process and allow it to spawn children */
ResumeThread(procInfo.hThread);
/* Block until the process terminates */
if (WaitForSingleObject(hProcess, INFINITE) != WAIT_OBJECT_0) {
std::wcerr << L"Failed waiting for process termination: "
<< GetLastErrorDescription() << std::endl;
return 127;
}
DWORD exitCode = 0;
ret = GetExitCodeProcess(hProcess, &exitCode);
assert(ret);
/* Calculate wallclock time in hundreds of nanoseconds.
Ignore user and kernel times (third and fourth return parameters) */
FILETIME createTime, exitTime, unusedTime;
ret = GetProcessTimes(hProcess, &createTime, &exitTime, &unusedTime, &unusedTime);
assert(ret);
LONGLONG createTime100Ns = (LONGLONG)createTime.dwHighDateTime << 32 | createTime.dwLowDateTime;
LONGLONG exitTime100Ns = (LONGLONG)exitTime.dwHighDateTime << 32 | exitTime.dwLowDateTime;
LONGLONG wallclockTime100Ns = exitTime100Ns - createTime100Ns;
/* Get total user and kernel times for all processes of the job object */
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION jobInfo;
ret = QueryInformationJobObject(hJob, JobObjectBasicAccountingInformation,
&jobInfo, sizeof(jobInfo), NULL);
assert(ret);
/* Close unused handlers */
CloseHandle(hProcess);
CloseHandle(hJob);
if (jobInfo.ActiveProcesses != 0) {
std::cerr << "Warning: there are still "
<< jobInfo.ActiveProcesses
<< " alive children processes" << std::endl;
/* We may kill survived processes, if desired */
//std::cerr << "Killing them" << std::endl;
//TerminateJobObject(hJob, 127);
}
/* Get kernel and user times in hundreds of nanoseconds */
LONGLONG kernelTime100Ns = jobInfo.TotalKernelTime.QuadPart;
LONGLONG userTime100Ns = jobInfo.TotalUserTime.QuadPart;
DWORD pageFaults = jobInfo.TotalPageFaultCount; /* Also available, why not report it as well */
/* Choose where to print results - to a file or stdout */
std::wstreambuf *buf;
std::wofstream of;
if (!params.outputFileName.empty()) {
of.open(params.outputFileName);
buf = of.rdbuf();
} else {
buf = std::wcout.rdbuf();
}
std::wostream out(buf);
/* Print floats with two digits after the dot */
out << std::fixed << std::setprecision(2);
out << std::endl;
if (params.verbose) {
out << L"Command being timed: " << L"\"" << params.cmdLine << L"\"" << std::endl;
out << "Elapsed (wall clock) time (seconds): " << timeUnit * wallclockTime100Ns << std::endl;
out << "User time (seconds): " << timeUnit * userTime100Ns << std::endl;
out << "System time (seconds): " << timeUnit * kernelTime100Ns << std::endl;
out << "Page faults: " << pageFaults << std::endl;
out << "Exit status: " << exitCode << std::endl;
} else {
/* Match POSIX time output */
out << "real" << "\t" << timeUnit * wallclockTime100Ns << "s"<< std::endl;
out << "user" << "\t" << timeUnit * userTime100Ns << "s" << std::endl;
out << "sys" << "\t" << timeUnit * kernelTime100Ns << "s" << std::endl;
}
if (of.is_open()) {
of.close();
}
return exitCode;
}
<|endoftext|>
|
<commit_before>#ifndef DISSENT_MESSAGING_FILTER_H_GUARD
#define DISSENT_MESSAGING_FILTER_H_GUARD
#include "ISink.hpp"
#include "Source.hpp"
namespace Dissent {
namespace Messaging {
/**
* Acts as a basic messaging Filter
*/
class Filter : public Source, public ISender, public ISink {
inline virtual void HandleData(const QByteArray &data, ISender *)
{
PushData(data, this);
}
};
}
}
#endif
<commit_msg>[Messaging] Filter HandleData should be public<commit_after>#ifndef DISSENT_MESSAGING_FILTER_H_GUARD
#define DISSENT_MESSAGING_FILTER_H_GUARD
#include "ISink.hpp"
#include "Source.hpp"
namespace Dissent {
namespace Messaging {
/**
* Acts as a basic messaging Filter
*/
class Filter : public Source, public ISender, public ISink {
public:
inline virtual void HandleData(const QByteArray &data, ISender *)
{
PushData(data, this);
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>//
// SuperheroPosition.cpp
// CGP-Superhero
//
// Created by Amir Blum on 4/27/15.
// Copyright (c) 2015 Amir Blum. All rights reserved.
//
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
using namespace glm;
#include "SuperheroPosition.h"
#define CAMERA_DISTANCE (2.5f)
SuperheroPosition::SuperheroPosition(City *city, Superhero *superhero) :
_city(city), _superhero(superhero)
{
}
SuperheroPosition::~SuperheroPosition()
{}
void SuperheroPosition::update(float dt)
{
vec3 oldPosition = _superhero->getWorldPosition();
vec3 newPosition = oldPosition + _superhero->getVelocity() * dt;
float radius = _superhero->getRadius();
float blockSize = BUILDING_WIDTH + ROAD_WIDTH;
float halfRoad = ROAD_WIDTH * 0.5f;
int row = floor((newPosition.z + halfRoad) / blockSize);
int col = floor((newPosition.x + halfRoad) / blockSize);
// std::cout << "Row: " << row << " Col: " << col << std::endl;
if (row < 0 || row >= _city->getGridLength() ||
col < 0 || col >= _city->getGridWidth()) {
vec3 positionDiff = newPosition - oldPosition;
_superhero->setPosition(_superhero->getPosition() + positionDiff);
return;
}
float buildingLeft = col * blockSize;
float buildingRight = buildingLeft + BUILDING_WIDTH;
buildingLeft -= radius;
buildingRight += radius;
float buildingBottom = row * blockSize;
float buildingTop = buildingBottom + BUILDING_WIDTH;
buildingBottom -= radius;
buildingTop += radius;
bool collided = false;
if (newPosition.z > buildingBottom && newPosition.z < buildingTop) {
if (oldPosition.x <= buildingLeft && newPosition.x > buildingLeft) {
newPosition.x = buildingLeft;
collided = true;
} else if (oldPosition.x >= buildingRight && newPosition.x < buildingRight) {
newPosition.x = buildingRight;
collided = true;
}
}
if (newPosition.x > buildingLeft && newPosition.x < buildingRight) {
if (oldPosition.z <= buildingBottom && newPosition.z > buildingBottom) {
newPosition.z = buildingBottom;
collided = true;
} else if (oldPosition.z >= buildingTop && newPosition.z < buildingTop) {
newPosition.z = buildingTop;
collided = true;
}
}
vec3 positionDiff = newPosition - oldPosition;
_superhero->setPosition(_superhero->getPosition() + positionDiff);
if (collided) {
_superhero->collideWithBuilding();
}
}
<commit_msg>Collisions on all the buildings now<commit_after>//
// SuperheroPosition.cpp
// CGP-Superhero
//
// Created by Amir Blum on 4/27/15.
// Copyright (c) 2015 Amir Blum. All rights reserved.
//
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
using namespace glm;
#include "SuperheroPosition.h"
#define CAMERA_DISTANCE (2.5f)
SuperheroPosition::SuperheroPosition(City *city, Superhero *superhero) :
_city(city), _superhero(superhero)
{
}
SuperheroPosition::~SuperheroPosition()
{}
void SuperheroPosition::update(float dt)
{
vec3 oldPosition = _superhero->getWorldPosition();
vec3 newPosition = oldPosition + _superhero->getVelocity() * dt;
float radius = _superhero->getRadius();
float blockSize = BUILDING_WIDTH + ROAD_WIDTH;
float halfRoad = ROAD_WIDTH * 0.5f;
int row = floor((newPosition.z + halfRoad) / blockSize);
int col = floor((newPosition.x + halfRoad) / blockSize);
// std::cout << "Row: " << row << " Col: " << col << std::endl;
float buildingLeft = col * blockSize;
float buildingRight = buildingLeft + BUILDING_WIDTH;
buildingLeft -= radius;
buildingRight += radius;
float buildingBottom = row * blockSize;
float buildingTop = buildingBottom + BUILDING_WIDTH;
buildingBottom -= radius;
buildingTop += radius;
bool collided = false;
if (newPosition.z > buildingBottom && newPosition.z < buildingTop) {
if (oldPosition.x <= buildingLeft && newPosition.x > buildingLeft) {
newPosition.x = buildingLeft;
collided = true;
} else if (oldPosition.x >= buildingRight && newPosition.x < buildingRight) {
newPosition.x = buildingRight;
collided = true;
}
}
if (newPosition.x > buildingLeft && newPosition.x < buildingRight) {
if (oldPosition.z <= buildingBottom && newPosition.z > buildingBottom) {
newPosition.z = buildingBottom;
collided = true;
} else if (oldPosition.z >= buildingTop && newPosition.z < buildingTop) {
newPosition.z = buildingTop;
collided = true;
}
}
vec3 positionDiff = newPosition - oldPosition;
_superhero->setPosition(_superhero->getPosition() + positionDiff);
if (collided) {
_superhero->collideWithBuilding();
}
}
<|endoftext|>
|
<commit_before>#include "TGrid.h"
#include "TGridCollection.h"
#include "TSystem.h"
#include "TString.h"
#include "TFile.h"
#include "TMap.h"
#include "TGridResult.h"
#include "TAlien.h"
#include "TAlienResult.h"
#include <fstream>
/*
Simple toolkit for Alien
Use ROOT C++ interfaces classes to access information from ALIEN
Important functionality:
MakeJobList - prepared the list which is later used by agent.sh
to analyze data on batch system
See example bellow and class heeader for details.
!!! The functionality not expelicitly mentioned in example can be not working
Code is still under development
*/
/*
gSystem->Load("libXrdClient.so");
gSystem->Load("libNetx.so");
.L $ALICE_ROOT/TPC/macros/testTPC/AlienToolkit.cxx+
//Raw data example
char *mask = "20225";
char *path = "/alice/data/2008/"
//
AlienToolkit toolkit;
toolkit.MakeCollection(path,mask); // make a list of the registerd data
toolkit.StageCastor(); // stage files on castor
//
toolkit.MakeJobList("job.list","", "", "rec");
*/
class AlienToolkit: public TObject{
public:
AlienToolkit();
TGridCollection* MakeCollection(const char *path, char *mask);
void Stage();
void StageCastor();
void LocalCopy(const char* destination);
void RemoteCopy(const char* destination="root://gsiaf.gsi.de:1094/", Int_t maxfiles=20);
void PrintPFN();
void MakeJobList(const char * outname, const char *outputPrefix, const char *action, const char *suffix);
static Bool_t IsDir(const char * name);
static Bool_t IsFile(const char * name);
static Bool_t ResubmitJobs();
public:
TGridCollection *fCollection;
TObjArray fInfoArray;
ClassDef(AlienToolkit,1)
};
ClassImp(AlienToolkit)
AlienToolkit::AlienToolkit():
fCollection(0)
{
if (!gGrid)
TGrid::Connect("alien://",0,0,"t");
}
Bool_t AlienToolkit::IsDir(const char * name){
//
// Check if it is directory
//
void *dir = gSystem->OpenDirectory(name);
return (dir!=0);
}
Bool_t AlienToolkit::IsFile(const char *name ){
//
// Check if is it file
//
Long_t id, size, flags, modtime ;
Int_t ret = gSystem->GetPathInfo(name,&id, &size, &flags, &modtime);
if (ret==0) return kFALSE;
if ((flags&2)>0) return kFALSE;
return kTRUE;
}
TGridCollection* AlienToolkit::MakeCollection(const char *path, char *mask){
//
/*char *mask = "root_archive.zip";
char *path = "/alice/cern.ch/user/m/miranov/test2007/"
*/
//
TGridResult* query = gGrid->Query(path,mask);
TGridCollection* collection=gGrid->OpenCollectionQuery(query);
// collection->SelectFile(mask,1,20); // select files 0-100
collection->LookupSUrls();
//collection->CheckIfOnline();
collection->Reset();
fCollection = collection;
//
collection->Reset();
Int_t counter=0;
Int_t counterm=0;
Int_t counterf=0;
TMap *filemap;
while ( (filemap = collection->Next())) {
TIterator *nextfile = filemap->MakeIterator();
TMap *attributes;
while ((attributes = (TMap *) nextfile->Next())) {
printf("%d\t%d\t%d\n",counter, counterm,counterf);
TMap * map = new TMap;
fInfoArray.AddLast(map);
TObjString *surl = new TObjString(collection->GetSURL(attributes->GetName()));
TObjString *turl = new TObjString(collection->GetTURL(attributes->GetName()));
TObjString *lfn = new TObjString(collection->GetLFN(attributes->GetName()));
map->Add(new TObjString("alienLFN"),lfn);
map->Add(new TObjString("alienSURL"),surl);
map->Add(new TObjString("alienTURL"),turl);
Int_t isOnline = collection->IsOnline(attributes->GetName());
printf("Base Name:\t%s\n",attributes->GetName());
printf("Size:\t%d\n",(Int_t)collection->GetSize());
printf("IsOnline:\t%d\n",collection->IsOnline());
printf("IsSelected:\t%d\n",collection->IsSelected());
printf("IsOnline:\t%d\n",isOnline);
printf("LFN Name:\t%s\n",lfn->String().Data());
printf("TURL Name:\t%s\n",turl->String().Data());
printf("SURL Name:\t%s\n",surl->String().Data());
counter++;
counterf++;
}
counterf=0;
counterm++;
}
}
void AlienToolkit::Stage(){
//
// Stage selected alien files
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.txt");
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
if (!lfn) continue;
printf("Staging submitfor\t%s\n",lfn->String().Data());
aout<<"stage "<<lfn->String().Data()<<endl;
}
aout.close();
gSystem->Exec("aliensh file:stage.txt");
}
void AlienToolkit::StageCastor(){
//
// Stage selected alien files
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.sh");
aout<<"#!/usr/local/bin/bash"<<endl;
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *pfn = (TObjString*)map("alienSURL");
if (!pfn) continue;
if (!pfn->String().Contains("//castor")) continue;
Char_t * cstr = &( pfn->String()[pfn->String().Index("/castor")]);
if (!cstr) continue;
printf("Staging submitfor\t%s\n",cstr);
char command[1000];
sprintf(command,"stager_qry -M %s | grep /castor | gawk \'{print $3;}\'", cstr);
gSystem->Exec(command);
sprintf(command,"stager_get -M %s", cstr);
aout<<command<<endl;
gSystem->Exec(command);
}
aout.close();
gSystem->Exec("source stage.sh");
}
void AlienToolkit::LocalCopy(const char *destination){
//
// Copy selected files to the destination directory
// the LFN path name translated to the directory name replacing
// separtor - the flat structure is created
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.txt");
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
if (!lfn) continue;
printf("Staging submitfor\t%s\n",lfn->String().Data());
TString dnames=lfn->String().Data();
dnames.ReplaceAll(".root_dir","");
dnames.ReplaceAll("/","_");
TString dname=destination;
dname+=dnames;
aout<<"cp "<<lfn->String().Data()<<" "<<dname.Data()<<endl;
}
aout.close();
gSystem->Exec("aliensh file:stage.txt");
}
void AlienToolkit::PrintPFN(){
//
//
//
Int_t entries = fInfoArray.GetEntries();
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
TObjString *pfn = (TObjString*)map("alienSURL");
if (!lfn) continue;
if (!pfn) continue;
printf("%s\n",pfn->String().Data());
}
}
void AlienToolkit::MakeJobList(const char * outname, const char *outputPrefix, const char *action, const char *suffix){
//
//
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout(outname);
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
TObjString *pfn = (TObjString*)map("alienSURL");
if (!lfn) continue;
if (!pfn) continue;
if (lfn->String().Contains(".tag.")) continue;
printf("Job info\t%s\n",lfn->String().Data());
TString jobID=lfn->String().Data();
jobID.ReplaceAll("/","_");
//
//
//
//
TString outputDir=outputPrefix;
outputDir+=lfn->String().Data();
aout<<jobID<<" "<<pfn->String().Data()<<" "<<outputDir.Data()<<" "<<action;
if (suffix) aout<<" "<<suffix<<"\n";
aout<<endl;
}
aout.close();
//
}
void AlienToolkit::RemoteCopy(const char *destination,Int_t maxfiles){
//
// Copy selected files to the destination directory
// the LFN path name translated to the directory name replacing
// separtor - the flat structure is created
Int_t entries = fInfoArray.GetEntries();
ofstream *aout=0;
for (Int_t i=0; i<entries;i++){
if (i%maxfiles==0){
if (aout) aout->close();
aout = new ofstream(Form("stage_%d.sh",i/maxfiles));
(*aout)<<"!/bin/bash\n";
(*aout)<<"source ~/.balice\n";
}
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *pfn = (TObjString*)map("alienSURL");
TObjString *lfn = (TObjString*)map("alienLFN");
if (!pfn) continue;
if (!lfn) continue;
TString dnames=lfn->String().Data();
TString dname=destination;
dname+=dnames;
(*aout)<<"xrdcp -d 1 "<<pfn->String().Data()<<" "<<dname.Data()<<endl;
}
aout->close();
//gSystem->Exec("aliensh file:stage.txt");
}
Bool_t AlienToolkit::ResubmitJobs(){
//
// Resubmit the processes finished in error state
//
//gSystem->Exec("alien_ps | grep EE > ps.txt")
gSystem->Exec("alien_ps | grep EE |gawk '{print $2}' > psEE.txt");
gSystem->Exec("alien_ps | grep EXPIRED |gawk '{print $2}' > psEXPIRED.txt");
//
ifstream in;
in.open("psEXPIRED.txt");
TString line;
TString result;
while(in.good()) {
in >> line;
// line.ReplaceAll("-","");
printf("Resubmiting %s\n",line.Data());
Int_t pos = line.First("-");
printf("%s\n",Form("alien_resubmit %s",&line.Data()[pos+1]));
gSystem->Exec(Form("alien_resubmit %s",&line.Data()[pos+1]));
}
in.close();
}
/*
Problems:
1. ???? fCollection.IsOnline("")
#12 0x04e9a03f in XrdClientAdmin::IsFileOnline (this=0x94a91b0, vs=@0xbfe07f60, vb=@0xbfe07f80) at ../../src/XrdClient/XrdClientVector.hh:55
#13 0x0423a975 in TXNetSystem::IsOnline (this=0x9652800,
path=0x9661488 "root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91")
at netx/src/TXNetSystem.cxx:476
#14 0x04237c6e in TXNetFileStager::IsStaged (this=0x96526b8,
path=0x9661400 "root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91")
at netx/src/TXNetFileStager.cxx:63
#15 0x00551117 in TFileStager::GetStaged (this=0x96526b8, pathlist=0x9649820) at net/src/TFileStager.cxx:58
#16 0x010e5d96 in TAlienCollection::CheckIfOnline (this=0x95da8d8, bulk=true) at alien/src/TAlienCollection.cxx:1143
2. id xrootd on voalice04.cern.ch ?
"root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91"
3. How to check if the file exist in redirector ?
4. Ho
*/
<commit_msg>Skip repeating entries (Marian)<commit_after>#include "TGrid.h"
#include "TGridCollection.h"
#include "TSystem.h"
#include "TString.h"
#include "TFile.h"
#include "TMap.h"
#include "TGridResult.h"
#include "TAlien.h"
#include "TAlienResult.h"
#include <fstream>
/*
Simple toolkit for Alien
Use ROOT C++ interfaces classes to access information from ALIEN
Important functionality:
MakeJobList - prepared the list which is later used by agent.sh
to analyze data on batch system
See example bellow and class heeader for details.
!!! The functionality not expelicitly mentioned in example can be not working
Code is still under development
*/
/*
gSystem->Load("libXrdClient.so");
gSystem->Load("libNetx.so");
//Raw data example
char *mask = "20225";
char *path = "/alice/data/2008/"
.L $ALICE_ROOT/TPC/macros/testTPC/AlienToolkit.cxx+
//
AlienToolkit toolkit;
toolkit.MakeCollection(path,mask); // make a list of the registerd data
toolkit.StageCastor(); // stage files on castor
//
toolkit.MakeJobList("job.list","", "", "rec");
*/
class AlienToolkit: public TObject{
public:
AlienToolkit();
TGridCollection* MakeCollection(const char *path, char *mask);
void Stage();
void StageCastor();
void LocalCopy(const char* destination);
void RemoteCopy(const char* destination="root://gsiaf.gsi.de:1094/", Int_t maxfiles=20);
void PrintPFN();
void MakeJobList(const char * outname, const char *outputPrefix, const char *action, const char *suffix);
static Bool_t IsDir(const char * name);
static Bool_t IsFile(const char * name);
static Bool_t ResubmitJobs();
public:
TGridCollection *fCollection;
TObjArray fInfoArray;
ClassDef(AlienToolkit,1)
};
ClassImp(AlienToolkit)
AlienToolkit::AlienToolkit():
fCollection(0)
{
if (!gGrid)
TGrid::Connect("alien://",0,0,"t");
}
Bool_t AlienToolkit::IsDir(const char * name){
//
// Check if it is directory
//
void *dir = gSystem->OpenDirectory(name);
return (dir!=0);
}
Bool_t AlienToolkit::IsFile(const char *name ){
//
// Check if is it file
//
Long_t id, size, flags, modtime ;
Int_t ret = gSystem->GetPathInfo(name,&id, &size, &flags, &modtime);
if (ret==0) return kFALSE;
if ((flags&2)>0) return kFALSE;
return kTRUE;
}
TGridCollection* AlienToolkit::MakeCollection(const char *path, char *mask){
//
/*char *mask = "root_archive.zip";
char *path = "/alice/cern.ch/user/m/miranov/test2007/"
*/
//
TGridResult* query = gGrid->Query(path,mask);
TGridCollection* collection=gGrid->OpenCollectionQuery(query);
// collection->SelectFile(mask,1,20); // select files 0-100
collection->LookupSUrls();
//collection->CheckIfOnline();
collection->Reset();
fCollection = collection;
//
collection->Reset();
Int_t counter=0;
Int_t counterm=0;
Int_t counterf=0;
TMap *filemap;
TObjString lastLFN;
while ( (filemap = collection->Next())) {
TIterator *nextfile = filemap->MakeIterator();
TMap *attributes;
while ((attributes = (TMap *) nextfile->Next())) {
printf("%d\t%d\t%d\n",counter, counterm,counterf);
TMap * map = new TMap;
TObjString *surl = new TObjString(collection->GetSURL(attributes->GetName()));
TObjString *turl = new TObjString(collection->GetTURL(attributes->GetName()));
TObjString *lfn = new TObjString(collection->GetLFN(attributes->GetName()));
map->Add(new TObjString("alienLFN"),lfn);
map->Add(new TObjString("alienSURL"),surl);
map->Add(new TObjString("alienTURL"),turl);
if (lastLFN.String().CompareTo(lfn->String())==0) continue;
lastLFN = *lfn;
Int_t isOnline = collection->IsOnline(attributes->GetName());
printf("Base Name:\t%s\n",attributes->GetName());
printf("Size:\t%d\n",(Int_t)collection->GetSize());
printf("IsOnline:\t%d\n",collection->IsOnline());
printf("IsSelected:\t%d\n",collection->IsSelected());
printf("IsOnline:\t%d\n",isOnline);
printf("LFN Name:\t%s\n",lfn->String().Data());
printf("TURL Name:\t%s\n",turl->String().Data());
printf("SURL Name:\t%s\n",surl->String().Data());
counter++;
counterf++;
fInfoArray.AddLast(map);
}
counterf=0;
counterm++;
}
}
void AlienToolkit::Stage(){
//
// Stage selected alien files
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.txt");
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
if (!lfn) continue;
printf("Staging submitfor\t%s\n",lfn->String().Data());
aout<<"stage "<<lfn->String().Data()<<endl;
}
aout.close();
gSystem->Exec("aliensh file:stage.txt");
}
void AlienToolkit::StageCastor(){
//
// Stage selected alien files
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.sh");
aout<<"#!/usr/local/bin/bash"<<endl;
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *pfn = (TObjString*)map("alienSURL");
if (!pfn) continue;
if (!pfn->String().Contains("//castor")) continue;
Char_t * cstr = &( pfn->String()[pfn->String().Index("/castor")]);
if (!cstr) continue;
printf("Staging submitfor\t%s\n",cstr);
char command[1000];
sprintf(command,"stager_qry -M %s | grep /castor | gawk \'{print $3;}\'", cstr);
gSystem->Exec(command);
sprintf(command,"stager_get -M %s", cstr);
aout<<command<<endl;
gSystem->Exec(command);
}
aout.close();
gSystem->Exec("source stage.sh");
}
void AlienToolkit::LocalCopy(const char *destination){
//
// Copy selected files to the destination directory
// the LFN path name translated to the directory name replacing
// separtor - the flat structure is created
Int_t entries = fInfoArray.GetEntries();
ofstream aout("stage.txt");
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
if (!lfn) continue;
printf("Staging submitfor\t%s\n",lfn->String().Data());
TString dnames=lfn->String().Data();
dnames.ReplaceAll(".root_dir","");
dnames.ReplaceAll("/","_");
TString dname=destination;
dname+=dnames;
aout<<"cp "<<lfn->String().Data()<<" "<<dname.Data()<<endl;
}
aout.close();
gSystem->Exec("aliensh file:stage.txt");
}
void AlienToolkit::PrintPFN(){
//
//
//
Int_t entries = fInfoArray.GetEntries();
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
TObjString *pfn = (TObjString*)map("alienSURL");
if (!lfn) continue;
if (!pfn) continue;
printf("%s\n",pfn->String().Data());
}
}
void AlienToolkit::MakeJobList(const char * outname, const char *outputPrefix, const char *action, const char *suffix){
//
//
//
Int_t entries = fInfoArray.GetEntries();
ofstream aout(outname);
for (Int_t i=0; i<entries;i++){
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *lfn = (TObjString*)map("alienLFN");
TObjString *pfn = (TObjString*)map("alienSURL");
if (!lfn) continue;
if (!pfn) continue;
if (lfn->String().Contains(".tag.")) continue;
printf("Job info\t%s\n",lfn->String().Data());
TString jobID=lfn->String().Data();
jobID.ReplaceAll("/","_");
//
//
//
//
TString outputDir=outputPrefix;
outputDir+=lfn->String().Data();
aout<<jobID<<" "<<pfn->String().Data()<<" "<<outputDir.Data()<<" "<<action;
if (suffix) aout<<" "<<suffix<<"\n";
aout<<endl;
}
aout.close();
//
}
void AlienToolkit::RemoteCopy(const char *destination,Int_t maxfiles){
//
// Copy selected files to the destination directory
// the LFN path name translated to the directory name replacing
// separtor - the flat structure is created
Int_t entries = fInfoArray.GetEntries();
ofstream *aout=0;
for (Int_t i=0; i<entries;i++){
if (i%maxfiles==0){
if (aout) aout->close();
aout = new ofstream(Form("stage_%d.sh",i/maxfiles));
(*aout)<<"!/bin/bash\n";
(*aout)<<"source ~/.balice\n";
}
TMap &map = *((TMap*)fInfoArray.At(i));
TObjString *pfn = (TObjString*)map("alienSURL");
TObjString *lfn = (TObjString*)map("alienLFN");
if (!pfn) continue;
if (!lfn) continue;
TString dnames=lfn->String().Data();
TString dname=destination;
dname+=dnames;
(*aout)<<"xrdcp -d 1 "<<pfn->String().Data()<<" "<<dname.Data()<<endl;
}
aout->close();
//gSystem->Exec("aliensh file:stage.txt");
}
Bool_t AlienToolkit::ResubmitJobs(){
//
// Resubmit the processes finished in error state
//
//gSystem->Exec("alien_ps | grep EE > ps.txt")
gSystem->Exec("alien_ps | grep EE |gawk '{print $2}' > psEE.txt");
gSystem->Exec("alien_ps | grep EXPIRED |gawk '{print $2}' > psEXPIRED.txt");
//
ifstream in;
in.open("psEXPIRED.txt");
TString line;
TString result;
while(in.good()) {
in >> line;
// line.ReplaceAll("-","");
printf("Resubmiting %s\n",line.Data());
Int_t pos = line.First("-");
printf("%s\n",Form("alien_resubmit %s",&line.Data()[pos+1]));
gSystem->Exec(Form("alien_resubmit %s",&line.Data()[pos+1]));
}
in.close();
}
/*
Problems:
1. ???? fCollection.IsOnline("")
#12 0x04e9a03f in XrdClientAdmin::IsFileOnline (this=0x94a91b0, vs=@0xbfe07f60, vb=@0xbfe07f80) at ../../src/XrdClient/XrdClientVector.hh:55
#13 0x0423a975 in TXNetSystem::IsOnline (this=0x9652800,
path=0x9661488 "root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91")
at netx/src/TXNetSystem.cxx:476
#14 0x04237c6e in TXNetFileStager::IsStaged (this=0x96526b8,
path=0x9661400 "root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91")
at netx/src/TXNetFileStager.cxx:63
#15 0x00551117 in TFileStager::GetStaged (this=0x96526b8, pathlist=0x9649820) at net/src/TFileStager.cxx:58
#16 0x010e5d96 in TAlienCollection::CheckIfOnline (this=0x95da8d8, bulk=true) at alien/src/TAlienCollection.cxx:1143
2. id xrootd on voalice04.cern.ch ?
"root://voalice04.cern.ch:1094//castor/cern.ch/alice/2005_castor2/15/23612/9e787bec-b010-11dc-a80c-000e0c3e6d91"
3. How to check if the file exist in redirector ?
4. Ho
*/
<|endoftext|>
|
<commit_before>// RUN: clang-cc -fsyntax-only -verify -std=c++0x
void f() {
int b[5];
auto a[5] = b; // expected-error{{'a' declared as array of 'auto'}}
}
<commit_msg>Fix test.<commit_after>// RUN: clang-cc -fsyntax-only -verify %s -std=c++0x
void f() {
int b[5];
auto a[5] = b; // expected-error{{'a' declared as array of 'auto'}}
}
<|endoftext|>
|
<commit_before>
#include "stdafx.h"
#include "python_cheats.h"
#include <temple/dll.h>
#include <util/fixes.h>
#include <common.h>
#include <party.h>
#include <obj.h>
#include <gamesystems/gamesystems.h>
#include <gamesystems/objects/objsystem.h>
// Returns 1 if it can handle the command
typedef int (__cdecl *CheatFn)(const char *command);
typedef void (__cdecl *CheatSetStateFn)(const char *command, int state);
const int cheatCount = 40;
#pragma pack(push, 1)
struct Cheat {
char *name;
int unk1;
CheatSetStateFn setState;
CheatFn handler;
};
#pragma pack(pop)
static struct PythonCheatsAddresses : temple::AddressTable {
Cheat *cheats;
PythonCheatsAddresses() {
rebase(cheats, 0x102B02E8);
}
} addresses;
static PyObject *PyCheats_GetAttr(PyObject*, char *name) {
for (int i = 0; i < cheatCount; ++i) {
auto cheat = addresses.cheats[i];
if (!_stricmp(name, cheat.name) && cheat.handler) {
return PyInt_FromLong(cheat.handler(name));
}
}
PyErr_Format(PyExc_AttributeError, "Unknown attribute: %s", name);
return 0;
}
static int PyCheats_SetAttr(PyObject*, char *name, PyObject *value) {
auto intVal = PyInt_AsLong(value);
for (int i = 0; i < cheatCount; ++i) {
auto cheat = addresses.cheats[i];
if (!_stricmp(name, cheat.name) && cheat.setState) {
cheat.setState(name, intVal);
return 0;
}
}
PyErr_Format(PyExc_AttributeError, "Unknown attribute: %s", name);
return -1;
}
static PyTypeObject PyCheatsType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"toee.PyCheats", /*tp_name*/
sizeof(PyObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) PyObject_Del, /*tp_dealloc*/
0, /*tp_print*/
PyCheats_GetAttr, /*tp_getattr*/
PyCheats_SetAttr, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
PyObject* PyCheats_Create() {
return PyObject_New(PyObject, &PyCheatsType);
}
class CheatHooks : TempleFix
{ // using this to prevent players from spawning invalid protos (and more importantly, not crashing the game when I make console typos!!!)
public:
const char* name() override { return "PyCheat hooks";}
static char * ParseString(char * in, char* out);
void apply() override
{
// give
replaceFunction<int(__cdecl)(char*)>(0x100492D0, [](char* consoleStr)
{
char cStrCopy[256];
auto v1 = ParseString(consoleStr, cStrCopy);
ParseString(v1, cStrCopy);
int protoNum = 5001; // DO NOT USE arrow
sscanf(cStrCopy, "%d", &protoNum);
if (protoNum < 1000){
logger->warn("Invalid proto for give command: {}", protoNum);
}
return 0;
auto protoHandle = gameSystems->GetObj().GetProtoHandle(protoNum);
if (!protoHandle)
return 0;
auto leader = party.GetConsciousPartyLeader();
auto loc = objects.GetLocation(leader);
auto handleNew = gameSystems->GetObj().CreateObject(protoHandle, loc);
if (handleNew){
if (!inventory.ItemGet(handleNew, leader, 0))
{
objects.Destroy(handleNew);
return 0;
}
auto obj = gameSystems->GetObj().GetObject(handleNew);
obj->SetItemFlag(OIF_IDENTIFIED, 1);
}
return 1;
});
// create
replaceFunction<int(__cdecl)(char*)>(0x100496D0, [](char* consoleStr)
{
char cStrCopy[256];
auto v1 = ParseString(consoleStr, cStrCopy);
ParseString(v1, cStrCopy);
int protoNum = 5001; // DO NOT USE arrow
sscanf(cStrCopy, "%d", &protoNum);
auto protoHandle = gameSystems->GetObj().GetProtoHandle(protoNum);
if (!protoHandle)
return 0;
auto leader = party.GetConsciousPartyLeader();
auto loc = objects.GetLocation(leader);
auto handleNew = gameSystems->GetObj().CreateObject(protoHandle, loc);
if (handleNew) {
auto objGenerateHp = temple::GetRef<void(__cdecl)(objHndl)>(0x1007F720);
objGenerateHp(handleNew);
}
auto& consoleNewlyCreatedObj = temple::GetRef<objHndl>(0x10AA31B8);
consoleNewlyCreatedObj = handleNew;
return 1;
});
}
} hooks;
char* CheatHooks::ParseString(char*in, char* out)
{
int i = 0;
auto chr = *in;
// advance to first non-whitespace / terminator
while(chr && chr == ' '){
chr = *++in;
}
if (*in == '"'){
while (*in && *in != '"'){
out[i] = *in;
in++;
i++;
}
}
else
{
while (*in){
if (*in == ' ')
break;
out[i++] = *in;
in++;
}
}
out[i] = 0;
return in;
}
<commit_msg>Fixed small oops bug in "give" cheat command<commit_after>
#include "stdafx.h"
#include "python_cheats.h"
#include <temple/dll.h>
#include <util/fixes.h>
#include <common.h>
#include <party.h>
#include <obj.h>
#include <gamesystems/gamesystems.h>
#include <gamesystems/objects/objsystem.h>
// Returns 1 if it can handle the command
typedef int (__cdecl *CheatFn)(const char *command);
typedef void (__cdecl *CheatSetStateFn)(const char *command, int state);
const int cheatCount = 40;
#pragma pack(push, 1)
struct Cheat {
char *name;
int unk1;
CheatSetStateFn setState;
CheatFn handler;
};
#pragma pack(pop)
static struct PythonCheatsAddresses : temple::AddressTable {
Cheat *cheats;
PythonCheatsAddresses() {
rebase(cheats, 0x102B02E8);
}
} addresses;
static PyObject *PyCheats_GetAttr(PyObject*, char *name) {
for (int i = 0; i < cheatCount; ++i) {
auto cheat = addresses.cheats[i];
if (!_stricmp(name, cheat.name) && cheat.handler) {
return PyInt_FromLong(cheat.handler(name));
}
}
PyErr_Format(PyExc_AttributeError, "Unknown attribute: %s", name);
return 0;
}
static int PyCheats_SetAttr(PyObject*, char *name, PyObject *value) {
auto intVal = PyInt_AsLong(value);
for (int i = 0; i < cheatCount; ++i) {
auto cheat = addresses.cheats[i];
if (!_stricmp(name, cheat.name) && cheat.setState) {
cheat.setState(name, intVal);
return 0;
}
}
PyErr_Format(PyExc_AttributeError, "Unknown attribute: %s", name);
return -1;
}
static PyTypeObject PyCheatsType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"toee.PyCheats", /*tp_name*/
sizeof(PyObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) PyObject_Del, /*tp_dealloc*/
0, /*tp_print*/
PyCheats_GetAttr, /*tp_getattr*/
PyCheats_SetAttr, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
PyObject* PyCheats_Create() {
return PyObject_New(PyObject, &PyCheatsType);
}
class CheatHooks : TempleFix
{ // using this to prevent players from spawning invalid protos (and more importantly, not crashing the game when I make console typos!!!)
public:
const char* name() override { return "PyCheat hooks";}
static char * ParseString(char * in, char* out);
void apply() override
{
// give
replaceFunction<int(__cdecl)(char*)>(0x100492D0, [](char* consoleStr)
{
char cStrCopy[256];
auto v1 = ParseString(consoleStr, cStrCopy);
ParseString(v1, cStrCopy);
int protoNum = 5001; // DO NOT USE arrow
sscanf(cStrCopy, "%d", &protoNum);
if (protoNum < 1000){
logger->warn("Invalid proto for give command: {}", protoNum);
return 0;
}
auto protoHandle = gameSystems->GetObj().GetProtoHandle(protoNum);
if (!protoHandle)
return 0;
auto leader = party.GetConsciousPartyLeader();
auto loc = objects.GetLocation(leader);
auto handleNew = gameSystems->GetObj().CreateObject(protoHandle, loc);
if (handleNew){
if (!inventory.ItemGet(handleNew, leader, 0))
{
objects.Destroy(handleNew);
return 0;
}
auto obj = gameSystems->GetObj().GetObject(handleNew);
obj->SetItemFlag(OIF_IDENTIFIED, 1);
}
return 1;
});
// create
replaceFunction<int(__cdecl)(char*)>(0x100496D0, [](char* consoleStr)
{
char cStrCopy[256];
auto v1 = ParseString(consoleStr, cStrCopy);
ParseString(v1, cStrCopy);
int protoNum = 5001; // DO NOT USE arrow
sscanf(cStrCopy, "%d", &protoNum);
auto protoHandle = gameSystems->GetObj().GetProtoHandle(protoNum);
if (!protoHandle)
return 0;
auto leader = party.GetConsciousPartyLeader();
auto loc = objects.GetLocation(leader);
auto handleNew = gameSystems->GetObj().CreateObject(protoHandle, loc);
if (handleNew) {
auto objGenerateHp = temple::GetRef<void(__cdecl)(objHndl)>(0x1007F720);
objGenerateHp(handleNew);
}
auto& consoleNewlyCreatedObj = temple::GetRef<objHndl>(0x10AA31B8);
consoleNewlyCreatedObj = handleNew;
return 1;
});
}
} hooks;
char* CheatHooks::ParseString(char*in, char* out)
{
int i = 0;
auto chr = *in;
// advance to first non-whitespace / terminator
while(chr && chr == ' '){
chr = *++in;
}
if (*in == '"'){
while (*in && *in != '"'){
out[i] = *in;
in++;
i++;
}
}
else
{
while (*in){
if (*in == ' ')
break;
out[i++] = *in;
in++;
}
}
out[i] = 0;
return in;
}
<|endoftext|>
|
<commit_before>#include "wrapper.h"
#ifdef __WXMSW__
# include <windows.h>
#endif
wxString GetApplicationPath()
{
static bool found = false;
static wxString path;
if (!found)
{
/* Windows */
#ifdef __WXMSW__
char buf[512] = "";
GetModuleFileName(NULL, buf, 511);
path = buf;
/* MAC */
#elif defined(__WXMAC__)
ProcessInfoRec processinfo;
ProcessSerialNumber procno ;
FSSpec fsSpec;
procno.highLongOfPSN = NULL ;
procno.lowLongOfPSN = kCurrentProcess ;
processinfo.processInfoLength = sizeof(ProcessInfoRec);
processinfo.processName = NULL;
processinfo.processAppSpec = &fsSpec;
GetProcessInformation( &procno , &processinfo ) ;
path = wxMacFSSpec2MacFilename(&fsSpec);
/* UNIX */
#else
wxString argv0 = wxTheApp->argv[0];
/* check absolute path */
if (wxIsAbsolutePath(argv0)) {
path = argv0;
}
else {
/* check relative path */
wxString fname = wxGetCwd + wxFILE_SEP_PATH + argv0;
if (wxFileExists(fname)) {
path = fname;
} else {
/* find on PATH */
wxPathList pathlist;
pathlist.AddEnvList(wxT("PATH"));
path = pathlist.FindAbsoluteValidPath(argv0);
}
}
wxFileName filename(path);
filename.Normalize();
path = filename.GetFullPath();
#endif
found = true;
}
return path;
}
wxString GetApplicationDir()
{
wxString path;
/* check APPDIR on unix's */
#ifndef __WXMSW__
# ifndef __WXMAC__
path = wxGetenv("APPDIR");
if (!path.IsEmpty()) return path;
# endif
#endif
path = GetApplicationPath();
if (path.IsEmpty())
return wxGetCwd();
else {
wxFileName fname(path);
return fname.GetPath(wxPATH_GET_VOLUME);
}
}
extern "C"
{
EWXWEXPORT(int, wxGetApplicationDir)(char* buffer)
{
wxString result = GetApplicationDir();
if (buffer) memcpy(buffer, result.c_str(), result.Length());
return result.Length();
}
EWXWEXPORT(int, wxGetApplicationPath)(char* buffer)
{
wxString result = GetApplicationPath();
if (buffer) memcpy(buffer, result.c_str(), result.Length());
return result.Length();
}
}<commit_msg>[wxhaskell-from-cvs @ 2003-10-21 15:03:34 by dleijen]<commit_after>#include "wrapper.h"
#ifdef __WXMSW__
# include <windows.h>
#elif defined(__WXMAC__)
# ifdef __DARWIN__
# include <ApplicationServices/ApplicationServices.h>
# else
# include <Types.h>
# include <Files.h>
# include <Processes.h>
# endif
#endif
#ifdef __WXMAC__
void fss2path(char *path, FSSpec *fss)
{
int l; //fss->name contains name of last item in path
for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
path[l] = 0;
if(fss->parID != fsRtParID) //path is more than just a volume name
{
int i, len;
CInfoPBRec pb;
pb.dirInfo.ioNamePtr = fss->name;
pb.dirInfo.ioVRefNum = fss->vRefNum;
pb.dirInfo.ioDrParID = fss->parID;
do
{
pb.dirInfo.ioFDirIndex = -1; //get parent directory name
pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
if(PBGetCatInfoSync(&pb) != noErr) break;
len = fss->name[0] + 1;
for(i=l; i>=0; i--) path[i + len] = path[i];
for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
path[i - 1] = ':';
l += len;
} while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
}
}
#endif
wxString GetApplicationPath()
{
static bool found = false;
static wxString path;
if (!found)
{
/* Windows */
#ifdef __WXMSW__
char buf[512] = "";
GetModuleFileName(NULL, buf, 511);
path = buf;
/* MAC */
#elif defined(__WXMAC__)
char buf[512] = "";
ProcessInfoRec processinfo;
ProcessSerialNumber procno ;
FSSpec fsSpec;
procno.highLongOfPSN = NULL ;
procno.lowLongOfPSN = kCurrentProcess ;
processinfo.processInfoLength = sizeof(ProcessInfoRec);
processinfo.processName = NULL;
processinfo.processAppSpec = &fsSpec;
GetProcessInformation( &procno , &processinfo ) ;
fss2path(buf,&fsSpec);
path = buf;
/* UNIX */
#else
wxString argv0 = wxTheApp->argv[0];
/* check absolute path */
if (wxIsAbsolutePath(argv0)) {
path = argv0;
}
else {
/* check relative path */
wxString fname = wxGetCwd + wxFILE_SEP_PATH + argv0;
if (wxFileExists(fname)) {
path = fname;
} else {
/* find on PATH */
wxPathList pathlist;
pathlist.AddEnvList(wxT("PATH"));
path = pathlist.FindAbsoluteValidPath(argv0);
}
}
wxFileName filename(path);
filename.Normalize();
path = filename.GetFullPath();
#endif
found = true;
}
return path;
}
wxString GetApplicationDir()
{
wxString path;
/* check APPDIR on unix's */
#ifndef __WXMSW__
# ifndef __WXMAC__
path = wxGetenv("APPDIR");
if (!path.IsEmpty()) return path;
# endif
#endif
path = GetApplicationPath();
if (path.IsEmpty())
return wxGetCwd();
else {
wxFileName fname(path);
return fname.GetPath(wxPATH_GET_VOLUME);
}
}
extern "C"
{
EWXWEXPORT(int, wxGetApplicationDir)(char* buffer)
{
wxString result = GetApplicationDir();
if (buffer) memcpy(buffer, result.c_str(), result.Length());
return result.Length();
}
EWXWEXPORT(int, wxGetApplicationPath)(char* buffer)
{
wxString result = GetApplicationPath();
if (buffer) memcpy(buffer, result.c_str(), result.Length());
return result.Length();
}
}<|endoftext|>
|
<commit_before>/* r_interface.cpp
*
* SimplR - Basic Symbolic Expression Simplification
* R interface to SimplR's C++ functions.
* (c) 2015 Oliver Flasch, Felix Gorschlueter, sourcewerk UG
*/
#include "expression.h"
#include <R.h>
#include <Rinternals.h>
#include <string.h>
using namespace ev3;
struct SexpToEv3ExpressionContext {
int nextVariableIndex;
map<string, int> variableIndexMap;
};
Expression sexp_to_ev3_expression_rec(SEXP sexp, SexpToEv3ExpressionContext& ctx) {
//Rprintf("expr type: %d\n", TYPEOF(sexp)); // DEBUG
switch (TYPEOF(sexp)) {
// base cases...
case INTSXP: {
Expression result = (double) INTEGER(sexp)[0];
return result;
}
case REALSXP: {
Expression result = REAL(sexp)[0];
return result;
}
case SYMSXP: {
Expression result;
result->SetOpType(VAR);
string name = string(CHAR(PRINTNAME(sexp)));
if (ctx.variableIndexMap.find(name) == ctx.variableIndexMap.end()) {
// create new variable table entry...
ctx.variableIndexMap[name] = ctx.nextVariableIndex;
ctx.nextVariableIndex++;
}
result->SetVarIndex(ctx.variableIndexMap[name]);
result->SetVarName(name);
//Rprintf("created variable '%s' with index %d\n", name.c_str(), ctx.variableIndexMap[name]); // DEBUG
return result;
}
// recursive cases...
case LANGSXP: {
const char *function_symbol = CHAR(PRINTNAME(CAR(sexp)));
if (!strcmp("+", function_symbol)) { // +
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
+ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("-", function_symbol) && (2 == length(sexp))) { // unary -
Expression result = -sexp_to_ev3_expression_rec(CADR(sexp), ctx);
return result;
} else if (!strcmp("-", function_symbol) && (3 == length(sexp))) { // binary -
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
- sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("*", function_symbol)) { // *
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
* sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("/", function_symbol)) { // /
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
/ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("^", function_symbol)) { // ^
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
^ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("log", function_symbol)) { // log
Expression result = Log(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("exp", function_symbol)) { // exp
Expression result = Exp(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sin", function_symbol)) { // sin
Expression result = Sin(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("cos", function_symbol)) { // cos
Expression result = Cos(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("tan", function_symbol)) { // tan
Expression result = Tan(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sinh", function_symbol)) { // sinh
Expression result = Sinh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("cosh", function_symbol)) { // cosh
Expression result = Cosh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("tanh", function_symbol)) { // tanh
Expression result = Tanh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sqrt", function_symbol)) { // sqrt
Expression result = Sqrt(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("(", function_symbol)) { // sexp in parens
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx);
return result;
} else {
list<Expression> arg_list;
for (SEXP i = CDR(sexp); i != R_NilValue; i = CDR(i)) {
arg_list.push_back(sexp_to_ev3_expression_rec(CAR(i), ctx));
}
Expression result = Other(string(function_symbol), arg_list);
return result;
}
}
// fallback case...
default: {
error("sexp_to_ev3_expression: unsupported expression type");
}
}
}
Expression sexp_to_ev3_expression(SEXP sexp) {
SexpToEv3ExpressionContext ctx;
ctx.nextVariableIndex = 1;
return sexp_to_ev3_expression_rec(sexp, ctx);
}
SEXP ev3_expression_to_sexp(Expression expr) {
//Rprintf("ev3_expression_to_sexp: %s\n", expr->ToString().c_str()); // DEBUG
SEXP result, args1, args2, arg1, arg2, arg3, arg4;
if (expr->IsLeaf()) { // leaf node: base case...
if (expr->GetCoeff() == 0) {
PROTECT(result = allocVector(REALSXP, 1));
REAL(result)[0] = 0.0;
UNPROTECT(1);
return result;
} else if (expr->GetOpType() == CONST) {
PROTECT(result = allocVector(REALSXP, 1));
REAL(result)[0] = expr->GetValue();
UNPROTECT(1);
return result;
} else if (expr->GetOpType() == VAR) {
string name = expr->GetVarName();
if (expr->GetCoeff() == 1) { // TODO may be near 1, also: maybe add special case for -1
if (expr->GetExponent() == 1) {
PROTECT(result = install(name.c_str()));
UNPROTECT(1);
return result;
} else {
PROTECT(arg1 = install(name.c_str()));
PROTECT(arg2 = allocVector(REALSXP, 1));
REAL(arg2)[0] = expr->GetExponent();
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(result = LCONS(install("^"), args1));
UNPROTECT(4);
return result;
}
} else { // expr->GetCoeff() != 1
if (expr->GetExponent() == 1) {
PROTECT(arg1 = allocVector(REALSXP, 1));
REAL(arg1)[0] = expr->GetCoeff();
PROTECT(arg2 = install(name.c_str()));
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(result = LCONS(install("*"), args1));
UNPROTECT(4);
return result;
} else {
PROTECT(arg1 = install(name.c_str()));
PROTECT(arg2 = allocVector(REALSXP, 1));
REAL(arg2)[0] = expr->GetExponent();
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(arg4 = LCONS(install("^"), args1));
PROTECT(arg3 = allocVector(REALSXP, 1));
REAL(arg3)[0] = expr->GetCoeff();
PROTECT(args2 = CONS(arg3, CONS(arg4, R_NilValue)));
PROTECT(result = LCONS(install("*"), args2));
UNPROTECT(7);
return result;
}
}
} else {
error("ev3_expression_to_sexp: unknown Ev3 leaf expression");
}
} else { // operator node: recursive case...
int protect_count = 0;
Int n_args = expr->GetSize();
Int op_type = expr->GetOpType();
string op_label = "";
switch (op_type) {
case SUM:
op_label = "+";
break;
case DIFFERENCE:
op_label = "-";
break;
case PRODUCT:
op_label = "*";
break;
case FRACTION:
op_label = "/";
break;
case POWER:
op_label = "^";
break;
case PLUS:
op_label = "+";
break;
case MINUS:
op_label = "-";
break;
case LOG:
op_label = "log";
break;
case EXP:
op_label = "exp";
break;
case SIN:
op_label = "sin";
break;
case COS:
op_label = "cos";
break;
case TAN:
op_label = "tan";
break;
case COT:
op_label = "cot";
break;
case SINH:
op_label = "sinh";
break;
case COSH:
op_label = "cosh";
break;
case TANH:
op_label = "tanh";
break;
case COTH:
op_label = "coth";
break;
case SQRT:
op_label = "sqrt";
break;
case OTHER:
op_label = expr->GetOpLabel();
break;
default:
error("ev3_expression_to_sexp: unkown op_type");
}
//Rprintf("operator node '%s' of type %d with %d arguments\n", op_label.c_str(), op_type, n_args); // DEBUG
if (n_args == 1) { // unary operator...
PROTECT(result = LCONS(install(op_label.c_str()), CONS(ev3_expression_to_sexp(expr->GetNode(0)), R_NilValue)));
protect_count++;
} else { // n-ary operator...
PROTECT(result = R_NilValue);
protect_count++;
for (Int i = n_args-1; i >= 0; i--) { // TODO BUGGY
PROTECT(result = CONS(ev3_expression_to_sexp(expr->GetNode(i)), result));
protect_count++;
//Rprintf("i: %d, child expr: %s\n", i, expr->GetNode(i)->ToString().c_str()); // DEBUG
if (i != n_args-1) {
PROTECT(result = LCONS(install(op_label.c_str()), result)); // TODO
protect_count++;
if (i != 0) { // add another layer of parentheses...
PROTECT(result = CONS(result, R_NilValue)); // TODO
protect_count++;
}
}
}
}
if (expr->GetCoeff() != 1) {
PROTECT(arg1 = allocVector(REALSXP, 1));
protect_count++;
REAL(arg1)[0] = expr->GetCoeff();
PROTECT(args1 = CONS(arg1, CONS(result, R_NilValue)));
protect_count++;
PROTECT(result = LCONS(install("*"), args1));
protect_count++;
}
assert(expr->GetExponent() == 1); // Ev3 does not use exponents in inner nodes, or does it?
UNPROTECT(protect_count);
return result;
}
}
extern "C" { // R can only .Call C functions...
SEXP simplify(SEXP sexp) {
try {
Expression expr = sexp_to_ev3_expression(sexp);
Simplify(&expr);
return ev3_expression_to_sexp(expr);
} catch (ErrBase& e) {
error(e.description.c_str());
}
}
} // extern "C"
<commit_msg>added special cases for coefficients of value -1<commit_after>/* r_interface.cpp
*
* SimplR - Basic Symbolic Expression Simplification
* R interface to SimplR's C++ functions.
* (c) 2015 Oliver Flasch, Felix Gorschlueter, sourcewerk UG
*/
#include "expression.h"
#include <R.h>
#include <Rinternals.h>
#include <string.h>
using namespace ev3;
struct SexpToEv3ExpressionContext {
int nextVariableIndex;
map<string, int> variableIndexMap;
};
Expression sexp_to_ev3_expression_rec(SEXP sexp, SexpToEv3ExpressionContext& ctx) {
//Rprintf("expr type: %d\n", TYPEOF(sexp)); // DEBUG
switch (TYPEOF(sexp)) {
// base cases...
case INTSXP: {
Expression result = (double) INTEGER(sexp)[0];
return result;
}
case REALSXP: {
Expression result = REAL(sexp)[0];
return result;
}
case SYMSXP: {
Expression result;
result->SetOpType(VAR);
string name = string(CHAR(PRINTNAME(sexp)));
if (ctx.variableIndexMap.find(name) == ctx.variableIndexMap.end()) {
// create new variable table entry...
ctx.variableIndexMap[name] = ctx.nextVariableIndex;
ctx.nextVariableIndex++;
}
result->SetVarIndex(ctx.variableIndexMap[name]);
result->SetVarName(name);
//Rprintf("created variable '%s' with index %d\n", name.c_str(), ctx.variableIndexMap[name]); // DEBUG
return result;
}
// recursive cases...
case LANGSXP: {
const char *function_symbol = CHAR(PRINTNAME(CAR(sexp)));
if (!strcmp("+", function_symbol)) { // +
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
+ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("-", function_symbol) && (2 == length(sexp))) { // unary -
Expression result = -sexp_to_ev3_expression_rec(CADR(sexp), ctx);
return result;
} else if (!strcmp("-", function_symbol) && (3 == length(sexp))) { // binary -
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
- sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("*", function_symbol)) { // *
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
* sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("/", function_symbol)) { // /
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
/ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("^", function_symbol)) { // ^
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx)
^ sexp_to_ev3_expression_rec(CADDR(sexp), ctx);
return result;
} else if (!strcmp("log", function_symbol)) { // log
Expression result = Log(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("exp", function_symbol)) { // exp
Expression result = Exp(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sin", function_symbol)) { // sin
Expression result = Sin(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("cos", function_symbol)) { // cos
Expression result = Cos(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("tan", function_symbol)) { // tan
Expression result = Tan(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sinh", function_symbol)) { // sinh
Expression result = Sinh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("cosh", function_symbol)) { // cosh
Expression result = Cosh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("tanh", function_symbol)) { // tanh
Expression result = Tanh(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("sqrt", function_symbol)) { // sqrt
Expression result = Sqrt(sexp_to_ev3_expression_rec(CADR(sexp), ctx));
return result;
} else if (!strcmp("(", function_symbol)) { // sexp in parens
Expression result = sexp_to_ev3_expression_rec(CADR(sexp), ctx);
return result;
} else {
list<Expression> arg_list;
for (SEXP i = CDR(sexp); i != R_NilValue; i = CDR(i)) {
arg_list.push_back(sexp_to_ev3_expression_rec(CAR(i), ctx));
}
Expression result = Other(string(function_symbol), arg_list);
return result;
}
}
// fallback case...
default: {
error("sexp_to_ev3_expression: unsupported expression type");
}
}
}
Expression sexp_to_ev3_expression(SEXP sexp) {
SexpToEv3ExpressionContext ctx;
ctx.nextVariableIndex = 1;
return sexp_to_ev3_expression_rec(sexp, ctx);
}
SEXP ev3_expression_to_sexp(Expression expr) {
//Rprintf("ev3_expression_to_sexp: %s\n", expr->ToString().c_str()); // DEBUG
SEXP result, args1, args2, arg1, arg2, arg3, arg4;
if (expr->IsLeaf()) { // leaf node: base case...
if (expr->GetCoeff() == 0) {
PROTECT(result = allocVector(REALSXP, 1));
REAL(result)[0] = 0.0;
UNPROTECT(1);
return result;
} else if (expr->GetOpType() == CONST) {
PROTECT(result = allocVector(REALSXP, 1));
REAL(result)[0] = expr->GetValue();
UNPROTECT(1);
return result;
} else if (expr->GetOpType() == VAR) {
string name = expr->GetVarName();
if (expr->GetCoeff() == 1) { // TODO may be near 1
if (expr->GetExponent() == 1) {
PROTECT(result = install(name.c_str()));
UNPROTECT(1);
return result;
} else {
PROTECT(arg1 = install(name.c_str()));
PROTECT(arg2 = allocVector(REALSXP, 1));
REAL(arg2)[0] = expr->GetExponent();
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(result = LCONS(install("^"), args1));
UNPROTECT(4);
return result;
}
} else if (expr->GetCoeff() == -1) {
if (expr->GetExponent() == 1) {
PROTECT(arg1 = install(name.c_str()));
PROTECT(args1 = CONS(arg1, R_NilValue));
PROTECT(result = LCONS(install("-"), args1));
UNPROTECT(3);
return result;
} else {
PROTECT(arg1 = install(name.c_str()));
PROTECT(arg2 = allocVector(REALSXP, 1));
REAL(arg2)[0] = expr->GetExponent();
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(arg4 = LCONS(install("^"), args1));
PROTECT(args2 = CONS(arg4, R_NilValue));
PROTECT(result = LCONS(install("-"), args2));
UNPROTECT(6);
return result;
}
} else { // expr->GetCoeff() is not 1 or -1
if (expr->GetExponent() == 1) {
PROTECT(arg1 = allocVector(REALSXP, 1));
REAL(arg1)[0] = expr->GetCoeff();
PROTECT(arg2 = install(name.c_str()));
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(result = LCONS(install("*"), args1));
UNPROTECT(4);
return result;
} else {
PROTECT(arg1 = install(name.c_str()));
PROTECT(arg2 = allocVector(REALSXP, 1));
REAL(arg2)[0] = expr->GetExponent();
PROTECT(args1 = CONS(arg1, CONS(arg2, R_NilValue)));
PROTECT(arg4 = LCONS(install("^"), args1));
PROTECT(arg3 = allocVector(REALSXP, 1));
REAL(arg3)[0] = expr->GetCoeff();
PROTECT(args2 = CONS(arg3, CONS(arg4, R_NilValue)));
PROTECT(result = LCONS(install("*"), args2));
UNPROTECT(7);
return result;
}
}
} else {
error("ev3_expression_to_sexp: unknown Ev3 leaf expression");
}
} else { // operator node: recursive case...
int protect_count = 0;
Int n_args = expr->GetSize();
Int op_type = expr->GetOpType();
string op_label = "";
switch (op_type) {
case SUM:
op_label = "+";
break;
case DIFFERENCE:
op_label = "-";
break;
case PRODUCT:
op_label = "*";
break;
case FRACTION:
op_label = "/";
break;
case POWER:
op_label = "^";
break;
case PLUS:
op_label = "+";
break;
case MINUS:
op_label = "-";
break;
case LOG:
op_label = "log";
break;
case EXP:
op_label = "exp";
break;
case SIN:
op_label = "sin";
break;
case COS:
op_label = "cos";
break;
case TAN:
op_label = "tan";
break;
case COT:
op_label = "cot";
break;
case SINH:
op_label = "sinh";
break;
case COSH:
op_label = "cosh";
break;
case TANH:
op_label = "tanh";
break;
case COTH:
op_label = "coth";
break;
case SQRT:
op_label = "sqrt";
break;
case OTHER:
op_label = expr->GetOpLabel();
break;
default:
error("ev3_expression_to_sexp: unkown op_type");
}
//Rprintf("operator node '%s' of type %d with %d arguments\n", op_label.c_str(), op_type, n_args); // DEBUG
if (n_args == 1) { // unary operator...
PROTECT(result = LCONS(install(op_label.c_str()), CONS(ev3_expression_to_sexp(expr->GetNode(0)), R_NilValue)));
protect_count++;
} else { // n-ary operator...
PROTECT(result = R_NilValue);
protect_count++;
for (Int i = n_args-1; i >= 0; i--) { // TODO BUGGY
PROTECT(result = CONS(ev3_expression_to_sexp(expr->GetNode(i)), result));
protect_count++;
//Rprintf("i: %d, child expr: %s\n", i, expr->GetNode(i)->ToString().c_str()); // DEBUG
if (i != n_args-1) {
PROTECT(result = LCONS(install(op_label.c_str()), result)); // TODO
protect_count++;
if (i != 0) { // add another layer of parentheses...
PROTECT(result = CONS(result, R_NilValue)); // TODO
protect_count++;
}
}
}
}
if (expr->GetCoeff() == -1) {
PROTECT(args1 = CONS(result, R_NilValue));
protect_count++;
PROTECT(result = LCONS(install("-"), args1));
protect_count++;
} else if (expr->GetCoeff() != 1) {
PROTECT(arg1 = allocVector(REALSXP, 1));
protect_count++;
REAL(arg1)[0] = expr->GetCoeff();
PROTECT(args1 = CONS(arg1, CONS(result, R_NilValue)));
protect_count++;
PROTECT(result = LCONS(install("*"), args1));
protect_count++;
}
assert(expr->GetExponent() == 1); // Ev3 does not use exponents in inner nodes, or does it?
UNPROTECT(protect_count);
return result;
}
}
extern "C" { // R can only .Call C functions...
SEXP simplify(SEXP sexp) {
try {
Expression expr = sexp_to_ev3_expression(sexp);
Simplify(&expr);
return ev3_expression_to_sexp(expr);
} catch (ErrBase& e) {
error(e.description.c_str());
}
}
} // extern "C"
<|endoftext|>
|
<commit_before>#include "xchainer/context.h"
#include <dlfcn.h>
#include <atomic>
#include <cstdlib>
#include <gsl/gsl>
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_backend.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/error.h"
#include "xchainer/native/native_backend.h"
namespace xchainer {
namespace {
std::atomic<Context*> g_global_default_context{nullptr};
thread_local Context* t_default_context{nullptr};
std::string GetXchainerPath() {
char* xchainer_path = std::getenv("XCHAINER_PATH");
if (xchainer_path != nullptr) {
return xchainer_path;
}
char* home_path = std::getenv("HOME");
if (home_path == nullptr) {
throw XchainerError{"Xchainer path is not defined. Set either XCHAINER_PATH or HOME."};
}
return std::string(home_path) + "/.xchainer";
}
} // namespace
Context::~Context() {
// Need to call dtor of all backends before closing shared objects
backends_.clear();
for (void* handle : dlopen_handles_) {
::dlclose(handle);
}
}
native::NativeBackend& Context::GetNativeBackend() {
return static_cast<native::NativeBackend&>(GetBackend(native::NativeBackend::kDefaultName));
}
Backend& Context::GetBackend(const std::string& backend_name) {
{
std::lock_guard<std::mutex> lock{mutex_};
auto it = backends_.find(backend_name);
if (it != backends_.end()) {
return *it->second;
}
}
// Ctor of each backend may call member functions of Context.
// Lock is released here to avoid any deadlocks.
std::unique_ptr<Backend> backend;
if (backend_name == native::NativeBackend::kDefaultName) {
backend = std::make_unique<native::NativeBackend>(*this);
#ifdef XCHAINER_ENABLE_CUDA
} else if (backend_name == cuda::CudaBackend::kDefaultName) {
backend = std::make_unique<cuda::CudaBackend>(*this);
#endif // XCHAINER_ENABLE_CUDA
} else {
// Load .so file
std::string so_file_path = GetXchainerPath() + "/backends/" + backend_name + ".so";
void* handle = ::dlopen(so_file_path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (handle == nullptr) {
throw BackendError{"Backend not found: '", backend_name, "'"};
}
{
std::lock_guard<std::mutex> lock{mutex_};
dlopen_handles_.push_back(handle);
}
// Create backend
void* ptr = ::dlsym(handle, "CreateBackend");
auto create_backend = reinterpret_cast<std::unique_ptr<Backend> (*)(Context&)>(ptr); // NOLINT: reinterpret_cast
if (create_backend == nullptr) {
throw BackendError{"Invalid backend plugin: CreateBackend is not found in '", so_file_path, "'."};
}
backend = create_backend(*this);
}
{
// In a multi-threaded case, backends_[backend_name] may already exist at this point.
// In that case, the backend created above is thrown away.
std::lock_guard<std::mutex> lock{mutex_};
auto pair = backends_.emplace(backend_name, std::move(backend));
return *pair.first->second;
}
}
Device& Context::GetDevice(const DeviceId& device_id) {
Backend& backend = GetBackend(device_id.backend_name());
return backend.GetDevice(device_id.index());
}
Context& GetGlobalDefaultContext() {
Context* context = g_global_default_context;
if (context == nullptr) {
throw ContextError{"Global default context is not set."};
}
return *context;
}
void SetGlobalDefaultContext(Context* context) { g_global_default_context = context; }
namespace internal {
Context* GetDefaultContextNoExcept() noexcept { return t_default_context; }
} // namespace internal
Context& GetDefaultContext() {
if (t_default_context == nullptr) {
return GetGlobalDefaultContext();
}
return *t_default_context;
}
void SetDefaultContext(Context* context) {
if (t_default_context != context) {
t_default_context = context;
SetDefaultDevice(nullptr);
}
}
} // namespace xchainer
<commit_msg>NOLINT for downcasting with static_cast<><commit_after>#include "xchainer/context.h"
#include <dlfcn.h>
#include <atomic>
#include <cstdlib>
#include <gsl/gsl>
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_backend.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/error.h"
#include "xchainer/native/native_backend.h"
namespace xchainer {
namespace {
std::atomic<Context*> g_global_default_context{nullptr};
thread_local Context* t_default_context{nullptr};
std::string GetXchainerPath() {
char* xchainer_path = std::getenv("XCHAINER_PATH");
if (xchainer_path != nullptr) {
return xchainer_path;
}
char* home_path = std::getenv("HOME");
if (home_path == nullptr) {
throw XchainerError{"Xchainer path is not defined. Set either XCHAINER_PATH or HOME."};
}
return std::string(home_path) + "/.xchainer";
}
} // namespace
Context::~Context() {
// Need to call dtor of all backends before closing shared objects
backends_.clear();
for (void* handle : dlopen_handles_) {
::dlclose(handle);
}
}
native::NativeBackend& Context::GetNativeBackend() {
Backend& backend = GetBackend(native::NativeBackend::kDefaultName);
return static_cast<native::NativeBackend&>(backend); // NOLINT
}
Backend& Context::GetBackend(const std::string& backend_name) {
{
std::lock_guard<std::mutex> lock{mutex_};
auto it = backends_.find(backend_name);
if (it != backends_.end()) {
return *it->second;
}
}
// Ctor of each backend may call member functions of Context.
// Lock is released here to avoid any deadlocks.
std::unique_ptr<Backend> backend;
if (backend_name == native::NativeBackend::kDefaultName) {
backend = std::make_unique<native::NativeBackend>(*this);
#ifdef XCHAINER_ENABLE_CUDA
} else if (backend_name == cuda::CudaBackend::kDefaultName) {
backend = std::make_unique<cuda::CudaBackend>(*this);
#endif // XCHAINER_ENABLE_CUDA
} else {
// Load .so file
std::string so_file_path = GetXchainerPath() + "/backends/" + backend_name + ".so";
void* handle = ::dlopen(so_file_path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (handle == nullptr) {
throw BackendError{"Backend not found: '", backend_name, "'"};
}
{
std::lock_guard<std::mutex> lock{mutex_};
dlopen_handles_.push_back(handle);
}
// Create backend
void* ptr = ::dlsym(handle, "CreateBackend");
auto create_backend = reinterpret_cast<std::unique_ptr<Backend> (*)(Context&)>(ptr); // NOLINT: reinterpret_cast
if (create_backend == nullptr) {
throw BackendError{"Invalid backend plugin: CreateBackend is not found in '", so_file_path, "'."};
}
backend = create_backend(*this);
}
{
// In a multi-threaded case, backends_[backend_name] may already exist at this point.
// In that case, the backend created above is thrown away.
std::lock_guard<std::mutex> lock{mutex_};
auto pair = backends_.emplace(backend_name, std::move(backend));
return *pair.first->second;
}
}
Device& Context::GetDevice(const DeviceId& device_id) {
Backend& backend = GetBackend(device_id.backend_name());
return backend.GetDevice(device_id.index());
}
Context& GetGlobalDefaultContext() {
Context* context = g_global_default_context;
if (context == nullptr) {
throw ContextError{"Global default context is not set."};
}
return *context;
}
void SetGlobalDefaultContext(Context* context) { g_global_default_context = context; }
namespace internal {
Context* GetDefaultContextNoExcept() noexcept { return t_default_context; }
} // namespace internal
Context& GetDefaultContext() {
if (t_default_context == nullptr) {
return GetGlobalDefaultContext();
}
return *t_default_context;
}
void SetDefaultContext(Context* context) {
if (t_default_context != context) {
t_default_context = context;
SetDefaultDevice(nullptr);
}
}
} // namespace xchainer
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
//
// Copyright(c) 2015 huan.wang
//
// 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 "stdafx.h"
#include "CppUnitTest.h"
#include "net/base/strings/string_utils.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestSuite
{
TEST_CLASS(string_utils_Test)
{
public:
TEST_METHOD(Test_StartsWith)
{
std::string strData = "Hello, ";
std::string strSearch = "Hello, ";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = "hello,";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch, true));
strSearch = "Helloxxx";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch) == false);
strSearch = "";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = strData;
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = "HELLO, ";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch, true));
}
TEST_METHOD(Test_EndsWith)
{
std::string strData = "Hello, ";
std::string strSearch = " ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = "O, ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch, true));
strSearch = "Helloxxx";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch) == false);
strSearch = "";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = strData;
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = "HELLO, ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch, true));
}
TEST_METHOD(Test_ToLower_ToUpper)
{
std::string str = "Hello, ";
Assert::IsTrue(base::strings::ToLower(str) == "hello, ");
Assert::IsTrue(base::strings::ToUpper(str) == "HELLO, ");
}
TEST_METHOD(Test_ToLowerSelf_ToUpperSelf)
{
std::string str = "Hello, ";
base::strings::ToLowerSelf(str);
Assert::IsTrue("hello, " == str);
base::strings::ToUpperSelf(str);
Assert::IsTrue("HELLO, " == str);
}
TEST_METHOD(Test_TrimLeftSelf_TrimRightSelf_TrimSelf)
{
std::string str = " Hello, ";
base::strings::TrimLeftSelf(str, " ");
Assert::IsTrue("Hello, " == str);
base::strings::TrimLeftSelf(str, "Helo, ");
Assert::IsTrue(" " == str);
base::strings::TrimLeftSelf(str, "");
Assert::IsTrue(" " == str);
str = " Hello, ";
base::strings::TrimRightSelf(str, " ");
Assert::IsTrue(" Hello, " == str);
base::strings::TrimRightSelf(str, " ");
Assert::IsTrue(" Hello," == str);
str = " Hello, ";
base::strings::TrimSelf(str, " ");
Assert::IsTrue("Hello, " == str);
base::strings::TrimSelf(str, "H");
Assert::IsTrue("ello, " == str);
}
TEST_METHOD(Test_TrimLeft_TrimRight_Trim)
{
std::string str = " Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimLeft(str, " "));
Assert::IsTrue(" " == base::strings::TrimLeft(str, "Helo, "));
Assert::IsTrue(" Hello, " == base::strings::TrimRight(str, " "));
Assert::IsTrue(" Hello," == base::strings::TrimRight(str, " "));
Assert::IsTrue("Hello, " == base::strings::Trim(str, " "));
Assert::IsTrue("ello, " == base::strings::Trim(str, "H "));
}
TEST_METHOD(Test_TrimLeftSpaceSelf_TrimRightSpaceSelf_TrimSpaceSelf)
{
#pragma warning(push)
#pragma warning(disable: 4309)
std::string str = " Hello, ";
base::strings::TrimLeftSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
base::strings::TrimRightSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
str = " Hello, ";
base::strings::TrimSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
str.push_back(0x85);
str.push_back(0xA0);
Assert::IsTrue("Hello, " != str);
base::strings::TrimRightSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
#pragma warning(pop)
}
TEST_METHOD(Test_TrimLeftSpace_TrimRightSpace_TrimSpace)
{
#pragma warning(push)
#pragma warning(disable: 4309)
std::string str = " Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimLeftSpace(str));
Assert::IsTrue(" Hello, " == base::strings::TrimRightSpace(str));
Assert::IsTrue("Hello, " == base::strings::TrimSpace(str));
str.push_back(0x85);
str.push_back(0xA0);
Assert::IsTrue(" Hello, " != str);
Assert::IsTrue(" Hello, " == base::strings::TrimRightSpace(str));
Assert::IsTrue("Hello, " == base::strings::TrimSpace(str));
#pragma warning(pop)
}
TEST_METHOD(Test_TrimPrefixSelf_TrimSuffixSelf)
{
std::string str = " hellohelloHello, ";
base::strings::TrimPrefixSelf(str, " ");
Assert::IsTrue("hellohelloHello, " == str);
base::strings::TrimPrefixSelf(str, "hello", false, true);
Assert::IsTrue("Hello, " == str);
base::strings::TrimPrefixSelf(str, "Hello", true);
Assert::IsTrue(", " == str);
str = "hellohelloHello, ";
base::strings::TrimPrefixSelf(str, "hello", true, true);
Assert::IsTrue(", " == str);
str = "Hello, helloHello";
base::strings::TrimSuffixSelf(str, "Hello");
Assert::IsTrue("Hello, hello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "Hello", false, true);
Assert::IsTrue("Hello, hello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "hello", true);
Assert::IsTrue("Hello, helloHello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "hello", true, true);
Assert::IsTrue("Hello, " == str);
base::strings::TrimSuffixSelf(str, "", false, true);
Assert::IsTrue("Hello, " == str);
}
TEST_METHOD(Test_TrimPrefix_TrimSuffix)
{
std::string str = "hellohelloHello, ";
Assert::IsTrue("helloHello, " == base::strings::TrimPrefix(str, "hello"));
Assert::IsTrue("Hello, " == base::strings::TrimPrefix(str, "hello", false, true));
Assert::IsTrue("helloHello, " == base::strings::TrimPrefix(str, "Hello", true));
Assert::IsTrue(", " == base::strings::TrimPrefix(str, "hello", true, true));
str = "Hello, helloHello";
Assert::IsTrue("Hello, hello" == base::strings::TrimSuffix(str, "Hello"));
str = "Hello, helloHelloHello";
Assert::IsTrue("Hello, hello" == base::strings::TrimSuffix(str, "Hello", false, true));
Assert::IsTrue("Hello, helloHello" == base::strings::TrimSuffix(str, "hello", true));
Assert::IsTrue("Hello, " == base::strings::TrimSuffix(str, "hello", true, true));
str = "Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimSuffix(str, "", false, true));
}
TEST_METHOD(Test_Split_SplitAfter_SplitN_SplitAfterN)
{
std::string str = "Hello world, I am a programmer";
auto spList = base::strings::Split(str, " ");
Assert::IsTrue(spList.size() == 6);
Assert::IsTrue(spList[0] == "Hello" && spList[5] == "programmer");
spList = base::strings::SplitAfter(str, " ");
Assert::IsTrue(spList.size() == 6 && spList[0] == "Hello " && spList[5] == "programmer");
spList = base::strings::Split(str, "/");
Assert::IsTrue(spList.size() == 1 && spList.front() == str);
spList = base::strings::SplitN(str, " ", 2);
Assert::IsTrue(spList.size() == 2);
Assert::IsTrue(spList.front() == "Hello" && spList.back() == "world, I am a programmer");
spList = base::strings::SplitAfterN(str, " ", 3);
Assert::IsTrue(spList.size() == 3 && spList[0] == "Hello " && spList[2] == "I am a programmer");
spList = base::strings::SplitAfterN(str, "/", 2);
Assert::IsTrue(spList.size() == 1 && spList.front() == str);
str = "/user/home/";
spList = base::strings::Split(str, "/");
Assert::IsTrue(spList.size() == 4 && spList[0].empty() && spList.back().empty());
spList = base::strings::SplitAfter(str, "/");
Assert::IsTrue(spList.size() == 4 && spList[0] == "/" && spList.back().empty());
spList = base::strings::SplitN(str, "/", 0);
Assert::IsTrue(spList.empty());
spList = base::strings::SplitN(str, "/", 1);
Assert::IsTrue(spList.size() == 1 && spList[0] == str);
spList = base::strings::SplitN(str, "/", 2);
Assert::IsTrue(spList.size() == 2 && spList[0].empty() && spList.back() == "user/home/");
spList = base::strings::SplitN(str, "/", 6);
Assert::IsTrue(spList.size() == 4 && spList[0].empty() && spList.back().empty());
spList = base::strings::SplitAfterN(str, "/", 2);
Assert::IsTrue(spList.size() == 2 && spList[0] == "/" && spList.back() == "user/home/");
spList = base::strings::SplitAfterN(str, "/", 6);
Assert::IsTrue(spList.size() == 4 && spList[0] == "/" && spList.back().empty());
str = "A##a111A$$a";
spList = base::strings::Split(str, "A");
Assert::IsTrue(spList.size() == 3);
spList = base::strings::Split(str, "A", true);
Assert::IsTrue(spList.size() == 5 && spList.back() == "");
spList = base::strings::SplitAfter(str, "A");
Assert::IsTrue(spList.size() == 3);
spList = base::strings::SplitAfter(str, "A", true);
Assert::IsTrue(spList.size() == 5 && spList.front() == "A");
spList = base::strings::SplitN(str, "A", 2);
Assert::IsTrue(spList.size() == 2);
spList = base::strings::SplitN(str, "A", 3, true);
Assert::IsTrue(spList.size() == 3 && spList[0].empty() && spList.back() == "111A$$a");
spList = base::strings::SplitN(str, "A", 6, true);
Assert::IsTrue(spList.size() == 5 && spList[0].empty() && spList.back() == "");
spList = base::strings::SplitAfterN(str, "A", 3);
Assert::IsTrue(spList.size() == 3 && spList[0] == "A" && spList.back() == "$$a");
spList = base::strings::SplitAfterN(str, "A", 3, true);
Assert::IsTrue(spList.size() == 3 && spList[0] == "A" && spList.back() == "111A$$a");
}
};
}<commit_msg>Add some particular test cases for Split* methods<commit_after>// The MIT License (MIT)
//
// Copyright(c) 2015 huan.wang
//
// 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 "stdafx.h"
#include "CppUnitTest.h"
#include "net/base/strings/string_utils.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestSuite
{
TEST_CLASS(string_utils_Test)
{
public:
TEST_METHOD(Test_StartsWith)
{
std::string strData = "Hello, ";
std::string strSearch = "Hello, ";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = "hello,";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch, true));
strSearch = "Helloxxx";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch) == false);
strSearch = "";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = strData;
Assert::IsTrue(base::strings::StartsWith(strData, strSearch));
strSearch = "HELLO, ";
Assert::IsTrue(base::strings::StartsWith(strData, strSearch, true));
}
TEST_METHOD(Test_EndsWith)
{
std::string strData = "Hello, ";
std::string strSearch = " ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = "O, ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch, true));
strSearch = "Helloxxx";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch) == false);
strSearch = "";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = strData;
Assert::IsTrue(base::strings::EndsWith(strData, strSearch));
strSearch = "HELLO, ";
Assert::IsTrue(base::strings::EndsWith(strData, strSearch, true));
}
TEST_METHOD(Test_ToLower_ToUpper)
{
std::string str = "Hello, ";
Assert::IsTrue(base::strings::ToLower(str) == "hello, ");
Assert::IsTrue(base::strings::ToUpper(str) == "HELLO, ");
}
TEST_METHOD(Test_ToLowerSelf_ToUpperSelf)
{
std::string str = "Hello, ";
base::strings::ToLowerSelf(str);
Assert::IsTrue("hello, " == str);
base::strings::ToUpperSelf(str);
Assert::IsTrue("HELLO, " == str);
}
TEST_METHOD(Test_TrimLeftSelf_TrimRightSelf_TrimSelf)
{
std::string str = " Hello, ";
base::strings::TrimLeftSelf(str, " ");
Assert::IsTrue("Hello, " == str);
base::strings::TrimLeftSelf(str, "Helo, ");
Assert::IsTrue(" " == str);
base::strings::TrimLeftSelf(str, "");
Assert::IsTrue(" " == str);
str = " Hello, ";
base::strings::TrimRightSelf(str, " ");
Assert::IsTrue(" Hello, " == str);
base::strings::TrimRightSelf(str, " ");
Assert::IsTrue(" Hello," == str);
str = " Hello, ";
base::strings::TrimSelf(str, " ");
Assert::IsTrue("Hello, " == str);
base::strings::TrimSelf(str, "H");
Assert::IsTrue("ello, " == str);
}
TEST_METHOD(Test_TrimLeft_TrimRight_Trim)
{
std::string str = " Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimLeft(str, " "));
Assert::IsTrue(" " == base::strings::TrimLeft(str, "Helo, "));
Assert::IsTrue(" Hello, " == base::strings::TrimRight(str, " "));
Assert::IsTrue(" Hello," == base::strings::TrimRight(str, " "));
Assert::IsTrue("Hello, " == base::strings::Trim(str, " "));
Assert::IsTrue("ello, " == base::strings::Trim(str, "H "));
}
TEST_METHOD(Test_TrimLeftSpaceSelf_TrimRightSpaceSelf_TrimSpaceSelf)
{
#pragma warning(push)
#pragma warning(disable: 4309)
std::string str = " Hello, ";
base::strings::TrimLeftSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
base::strings::TrimRightSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
str = " Hello, ";
base::strings::TrimSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
str.push_back(0x85);
str.push_back(0xA0);
Assert::IsTrue("Hello, " != str);
base::strings::TrimRightSpaceSelf(str);
Assert::IsTrue("Hello, " == str);
#pragma warning(pop)
}
TEST_METHOD(Test_TrimLeftSpace_TrimRightSpace_TrimSpace)
{
#pragma warning(push)
#pragma warning(disable: 4309)
std::string str = " Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimLeftSpace(str));
Assert::IsTrue(" Hello, " == base::strings::TrimRightSpace(str));
Assert::IsTrue("Hello, " == base::strings::TrimSpace(str));
str.push_back(0x85);
str.push_back(0xA0);
Assert::IsTrue(" Hello, " != str);
Assert::IsTrue(" Hello, " == base::strings::TrimRightSpace(str));
Assert::IsTrue("Hello, " == base::strings::TrimSpace(str));
#pragma warning(pop)
}
TEST_METHOD(Test_TrimPrefixSelf_TrimSuffixSelf)
{
std::string str = " hellohelloHello, ";
base::strings::TrimPrefixSelf(str, " ");
Assert::IsTrue("hellohelloHello, " == str);
base::strings::TrimPrefixSelf(str, "hello", false, true);
Assert::IsTrue("Hello, " == str);
base::strings::TrimPrefixSelf(str, "Hello", true);
Assert::IsTrue(", " == str);
str = "hellohelloHello, ";
base::strings::TrimPrefixSelf(str, "hello", true, true);
Assert::IsTrue(", " == str);
str = "Hello, helloHello";
base::strings::TrimSuffixSelf(str, "Hello");
Assert::IsTrue("Hello, hello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "Hello", false, true);
Assert::IsTrue("Hello, hello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "hello", true);
Assert::IsTrue("Hello, helloHello" == str);
str = "Hello, helloHelloHello";
base::strings::TrimSuffixSelf(str, "hello", true, true);
Assert::IsTrue("Hello, " == str);
base::strings::TrimSuffixSelf(str, "", false, true);
Assert::IsTrue("Hello, " == str);
}
TEST_METHOD(Test_TrimPrefix_TrimSuffix)
{
std::string str = "hellohelloHello, ";
Assert::IsTrue("helloHello, " == base::strings::TrimPrefix(str, "hello"));
Assert::IsTrue("Hello, " == base::strings::TrimPrefix(str, "hello", false, true));
Assert::IsTrue("helloHello, " == base::strings::TrimPrefix(str, "Hello", true));
Assert::IsTrue(", " == base::strings::TrimPrefix(str, "hello", true, true));
str = "Hello, helloHello";
Assert::IsTrue("Hello, hello" == base::strings::TrimSuffix(str, "Hello"));
str = "Hello, helloHelloHello";
Assert::IsTrue("Hello, hello" == base::strings::TrimSuffix(str, "Hello", false, true));
Assert::IsTrue("Hello, helloHello" == base::strings::TrimSuffix(str, "hello", true));
Assert::IsTrue("Hello, " == base::strings::TrimSuffix(str, "hello", true, true));
str = "Hello, ";
Assert::IsTrue("Hello, " == base::strings::TrimSuffix(str, "", false, true));
}
TEST_METHOD(Test_Split_SplitAfter_SplitN_SplitAfterN)
{
std::string str = "Hello world, I am a programmer";
auto spList = base::strings::Split(str, " ");
Assert::IsTrue(spList.size() == 6);
Assert::IsTrue(spList[0] == "Hello" && spList[5] == "programmer");
spList = base::strings::SplitAfter(str, " ");
Assert::IsTrue(spList.size() == 6 && spList[0] == "Hello " && spList[5] == "programmer");
spList = base::strings::Split(str, "/");
Assert::IsTrue(spList.size() == 1 && spList.front() == str);
spList = base::strings::SplitN(str, " ", 2);
Assert::IsTrue(spList.size() == 2);
Assert::IsTrue(spList.front() == "Hello" && spList.back() == "world, I am a programmer");
spList = base::strings::SplitAfterN(str, " ", 3);
Assert::IsTrue(spList.size() == 3 && spList[0] == "Hello " && spList[2] == "I am a programmer");
spList = base::strings::SplitAfterN(str, "/", 2);
Assert::IsTrue(spList.size() == 1 && spList.front() == str);
str = "/user/home/";
spList = base::strings::Split(str, "/");
Assert::IsTrue(spList.size() == 4 && spList[0].empty() && spList.back().empty());
spList = base::strings::SplitAfter(str, "/");
Assert::IsTrue(spList.size() == 4 && spList[0] == "/" && spList.back().empty());
spList = base::strings::Split(str, "");
Assert::IsTrue(spList.size() == str.length() && spList.front() == "/");
spList = base::strings::SplitN(str, "", 2);
Assert::IsTrue(spList.size() == 2 && spList.back() == "user/home/");
spList = base::strings::SplitN(str, "/", 0);
Assert::IsTrue(spList.empty());
spList = base::strings::SplitN(str, "/", 1);
Assert::IsTrue(spList.size() == 1 && spList[0] == str);
spList = base::strings::SplitN(str, "/", 2);
Assert::IsTrue(spList.size() == 2 && spList[0].empty() && spList.back() == "user/home/");
spList = base::strings::SplitN(str, "/", 6);
Assert::IsTrue(spList.size() == 4 && spList[0].empty() && spList.back().empty());
spList = base::strings::SplitAfterN(str, "/", 2);
Assert::IsTrue(spList.size() == 2 && spList[0] == "/" && spList.back() == "user/home/");
spList = base::strings::SplitAfterN(str, "/", 6);
Assert::IsTrue(spList.size() == 4 && spList[0] == "/" && spList.back().empty());
str = "A##a111A$$a";
spList = base::strings::Split(str, "A");
Assert::IsTrue(spList.size() == 3);
spList = base::strings::Split(str, "A", true);
Assert::IsTrue(spList.size() == 5 && spList.back() == "");
spList = base::strings::SplitAfter(str, "A");
Assert::IsTrue(spList.size() == 3);
spList = base::strings::SplitAfter(str, "A", true);
Assert::IsTrue(spList.size() == 5 && spList.front() == "A");
spList = base::strings::SplitN(str, "A", 2);
Assert::IsTrue(spList.size() == 2);
spList = base::strings::SplitN(str, "A", 3, true);
Assert::IsTrue(spList.size() == 3 && spList[0].empty() && spList.back() == "111A$$a");
spList = base::strings::SplitN(str, "A", 6, true);
Assert::IsTrue(spList.size() == 5 && spList[0].empty() && spList.back() == "");
spList = base::strings::SplitAfterN(str, "A", 3);
Assert::IsTrue(spList.size() == 3 && spList[0] == "A" && spList.back() == "$$a");
spList = base::strings::SplitAfterN(str, "A", 3, true);
Assert::IsTrue(spList.size() == 3 && spList[0] == "A" && spList.back() == "111A$$a");
}
};
}<|endoftext|>
|
<commit_before>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/thread/posix/PosixConditionVariable.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/utils.h>
#include <stingraykit/Singleton.h>
#include <errno.h>
namespace stingray
{
class CancellationHolder : public CancellationRegistratorBase
{
class CancellationHandler : public ICancellationHandler
{
private:
const PosixMutex& _mutex;
PosixConditionVariable& _cond;
public:
CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond)
: _mutex(mutex), _cond(cond)
{ }
virtual ~CancellationHandler()
{ }
virtual void Cancel()
{
MutexLock l(_mutex);
_cond.Broadcast();
}
const PosixMutex& GetMutex() const
{ return _mutex; }
};
private:
CancellationHandler _handler;
public:
CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token)
: CancellationRegistratorBase(token), _handler(mutex, cond)
{ Register(_handler); }
~CancellationHolder()
{
if (TryUnregister(_handler))
return;
MutexUnlock ul(_handler.GetMutex());
Unregister(_handler);
}
};
class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
{
STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);
private:
pthread_condattr_t _condAttr;
private:
PosixConditionVariableAttr()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
}
public:
~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }
const pthread_condattr_t& Get() const { return _condAttr; }
};
PosixConditionVariable::PosixConditionVariable()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
}
PosixConditionVariable::~PosixConditionVariable()
{
pthread_cond_destroy(&_cond);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return;
Wait(mutex);
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return true;
return TimedWait(mutex, interval);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex) const
{
int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_wait", ret));
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
{
timespec t = { };
posix::timespec_now(CLOCK_MONOTONIC, &t);
posix::timespec_add(&t, interval);
int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
STINGRAYKIT_CHECK(ret == 0 || ret == ETIMEDOUT, SystemException("pthread_cond_timedwait", ret));
return ret != ETIMEDOUT;
}
void PosixConditionVariable::Broadcast()
{
int ret = pthread_cond_broadcast(&_cond);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_broadcast", ret));
}
}
<commit_msg>PosixConditionVariable::Wait(mutex, token): support timeout in ICancellationToken<commit_after>// Copyright (c) 2011 - 2017, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/thread/posix/PosixConditionVariable.h>
#include <stingraykit/thread/CancellationRegistrator.h>
#include <stingraykit/time/posix/utils.h>
#include <stingraykit/Singleton.h>
#include <errno.h>
namespace stingray
{
class CancellationHolder : public CancellationRegistratorBase
{
class CancellationHandler : public ICancellationHandler
{
private:
const PosixMutex& _mutex;
PosixConditionVariable& _cond;
public:
CancellationHandler(const PosixMutex& mutex, PosixConditionVariable& cond)
: _mutex(mutex), _cond(cond)
{ }
virtual ~CancellationHandler()
{ }
virtual void Cancel()
{
MutexLock l(_mutex);
_cond.Broadcast();
}
const PosixMutex& GetMutex() const
{ return _mutex; }
};
private:
CancellationHandler _handler;
public:
CancellationHolder(const PosixMutex& mutex, PosixConditionVariable& cond, const ICancellationToken& token)
: CancellationRegistratorBase(token), _handler(mutex, cond)
{ Register(_handler); }
~CancellationHolder()
{
if (TryUnregister(_handler))
return;
MutexUnlock ul(_handler.GetMutex());
Unregister(_handler);
}
};
class PosixConditionVariableAttr : public Singleton<PosixConditionVariableAttr>
{
STINGRAYKIT_SINGLETON(PosixConditionVariableAttr);
private:
pthread_condattr_t _condAttr;
private:
PosixConditionVariableAttr()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_condattr_init(&_condAttr)) == 0, SystemException("pthread_condattr_init", ret));
STINGRAYKIT_CHECK((ret = pthread_condattr_setclock(&_condAttr, CLOCK_MONOTONIC)) == 0, SystemException("pthread_condattr_setclock", ret));
}
public:
~PosixConditionVariableAttr() { pthread_condattr_destroy(&_condAttr); }
const pthread_condattr_t& Get() const { return _condAttr; }
};
PosixConditionVariable::PosixConditionVariable()
{
int ret = 0;
STINGRAYKIT_CHECK((ret = pthread_cond_init(&_cond, &PosixConditionVariableAttr::ConstInstance().Get())) == 0, SystemException("pthread_cond_init", ret));
}
PosixConditionVariable::~PosixConditionVariable()
{
pthread_cond_destroy(&_cond);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return;
if (const optional<TimeDuration> timeout = token.GetTimeout())
TimedWait(mutex, *timeout);
else
Wait(mutex);
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval, const ICancellationToken& token)
{
CancellationHolder holder(mutex, *this, token);
if (holder.IsCancelled())
return true;
return TimedWait(mutex, interval);
}
void PosixConditionVariable::Wait(const PosixMutex& mutex) const
{
int ret = pthread_cond_wait(&_cond, &mutex._rawMutex);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_wait", ret));
}
bool PosixConditionVariable::TimedWait(const PosixMutex& mutex, TimeDuration interval) const
{
timespec t = { };
posix::timespec_now(CLOCK_MONOTONIC, &t);
posix::timespec_add(&t, interval);
int ret = pthread_cond_timedwait(&_cond, &mutex._rawMutex, &t);
STINGRAYKIT_CHECK(ret == 0 || ret == ETIMEDOUT, SystemException("pthread_cond_timedwait", ret));
return ret != ETIMEDOUT;
}
void PosixConditionVariable::Broadcast()
{
int ret = pthread_cond_broadcast(&_cond);
STINGRAYKIT_CHECK(ret == 0, SystemException("pthread_cond_broadcast", ret));
}
}
<|endoftext|>
|
<commit_before>#ifndef HMLIB_BIO_OSI_INC
#define HMLIB_BIO_OSI_INC 100
#
#include<utility>
#include<vector>
#include<cmath>
#include<boost/optional.hpp>
#include"../tuple.hpp"
#include"../algorithm/sampling.hpp"
#include"../random.hpp"
#include"../exceptions.hpp"
#include"pairgame.hpp"
namespace hmLib {
namespace bio {
namespace osi {
// birth rate: b = rate*(w/meanw)
// daeth rate: d = rate
// w > 0 and meanw > 0 are requried.
struct birth_ratio_invasion_fitness {
// birth rate: b = rate*(w/meanw)
// daeth rate: d = rate
// mutation rate: m = mutation_frequency*birth_rate = TimeStep
// invasion rate: f = (b - d)/b = 1 - meanw/w
//Note: w and meanw should be positive
public:
double operator()(double w, double meanw)const {
return 1 - meanw / w;
}
};
// birth rate: b = rate*exp(alpha*(w-meanw))
// daeth rate: d = rate
// w and meanw can be negative.
struct birth_exp_invasion_fitness {
// birth rate: b = rate*exp(alpha*(w-meanw))
// daeth rate: d = rate
// mutation rate: m = mutation_frequency*birth_rate = TimeStep
// invasion rate: f = (b - d)/b = 1 - exp(-alpha*(w-meanw))
// alpha determines the strength of the selection.
//Note: w and/or meanw can be negative
private:
double alpha;
public:
birth_exp_invasion_fitness()noexcept : alpha(1.0) {}
explicit birth_exp_invasion_fitness(double alpha_)noexcept : alpha(alpha_) {}
double operator()(double w, double meanw)const {
return 1 - std::exp(-alpha * (w - meanw));
}
};
// invasion control (strict trial)
template<typename invasion_fitness>
struct simple_osi_policy {
private:
invasion_fitness Invasion;
public:
simple_osi_policy(invasion_fitness Invasion_ = invasion_fitness()) :Invasion(std::move(Invasion_)) {}
void reset() {}
std::pair<bool, double> try_invade(double w, double meanw) {
double f = Invasion(w, meanw);
return std::make_pair(f < hmLib::random::uniform_real(0.0, 1.0), -std::log(hmLib::random::uniform_real(0.0, 1.0)));
}
bool can_invade(double w, double meanw) { return Invasion(w, meanw) > 0; }
};
// invasion control (approximate by normal distribution based on central limit theorem)
template<typename invasion_fitness>
struct clt_osi_policy {
//average time consumption invasion trial
//sum of log(uniform_real(0.0,1.0)) for N times seems to be apploximated by a normal distribution with
// mean := -N
// var := N
//i.e., hmLib::random::normal(-1.0*N, std::sqrt(N))
private:
invasion_fitness Invasion;
double target; //[0:1]: target "mean probability" that an optimal mutant can successfully invade.
double decay; //[0:1]: reduction rate of the old data (1: no reduction, 0: forget immidiately).
double overrate;//[0: ]: rate of the over-estimation of the maximum probability from current probability. (0: no over-estimation 1: twice as large as f can appear)
unsigned int max_trial;
private:
double maxf;
public:
clt_osi_policy(double target_, double decay_, double overrate_, unsigned int max_trial_ = 5u, invasion_fitness Invasion_ = invasion_fitness())
: Invasion(std::move(Invasion_)), target(target_), decay(decay_), overrate(overrate_), max_trial(max_trial_), maxf(target) {
}
void reset() { maxf = target; }
std::pair<bool, double> try_invade(double w, double meanw) {
double f = Invasion(w, meanw);
unsigned int trial = std::max<unsigned int>(1, static_cast<unsigned int>(std::floor(std::log(1 - target) / std::log(1 - maxf))));
maxf = std::max(f * (1.0 + overrate), (1.0 - decay) * maxf);
bool Success = false;
double dt = 0;
//Success of invasion flag
if (trial < max_trial) {
//if trial number is enough small, just try 5 times.
// this is because approximation by normal distribution is less precious in small trial number.
if (f <= 0) {
for (unsigned int i = 0; i < trial; ++i) {
dt += -std::log(hmLib::random::uniform_real(0.0, 1.0));
}
} else {
for (unsigned int i = 0; i < trial; ++i) {
dt += -std::log(hmLib::random::uniform_real(0.0, 1.0));
if (f > hmLib::random::uniform_real(0.0, 1.0)) {
Success = true;
break;
}
}
}
} else {
//aproximate by normal distribution
if (f < 0 || std::pow(1 - f, trial) > hmLib::random::uniform_real(0.0, 1.0)) {
//fail to invade
do {
dt = -hmLib::random::normal(-1.0 * trial, std::sqrt(trial));
} while (dt <= 0);
} else {
//success to invade
Success = true;
//check mean time for invasion
// mean trial = 1*p + 2*p*(1-p)+ ... N*p*(1-p)^(N-1) with N = invasion_trial
// = ( (1 - (1-p)^N)/p - N*(1-p)^N )/( 1 - (1-p)^N )
double miss_prob = std::pow(1 - f, trial);
double mean_trial = ((1 - miss_prob) / f - trial * miss_prob) / (1 - miss_prob);
//hmLib::random::normal(-1.0*N, std::sqrt(N))
do {
dt = -hmLib::random::normal(-mean_trial, std::sqrt(mean_trial));
} while (dt <= 0);
}
}
return std::make_pair(Success, dt);
}
bool can_invade(double w, double meanw) { return Invasion(w, meanw) > 0; }
};
}
//return type of invasion policy
template<typename trait>
struct osi_step_result {
bool success;
double dt;
boost::optional<trait> branch;
osi_step_result() = default;
osi_step_result(bool success_, double dt_) :success(success_), dt(dt_), branch(boost::none) {}
osi_step_result(bool success_, double dt_, trait x) :success(success_), dt(dt_), branch(std::move(x)) {}
};
template<typename osi_policy_>
struct osi_stepper {
using osi_policy = osi_policy_; //control invasion trial
private:
osi_policy OSIPolicy;
unsigned int MaxMutationTrial;
public:
osi_stepper(osi_policy OSIPolicy_, unsigned int MaxMutationTrial_ = 10000)
: OSIPolicy(std::move(OSIPolicy_)), MaxMutationTrial(MaxMutationTrial_) {
}
void reset() { OSIPolicy.reset(); }
//return value is osi_step_result with the focal trait type
//[fbeg,fend) and meanw is changed inside of the function
template<typename strainfitness, typename mutate, typename trait_iterator, typename frac_iterator,typename URBG>
auto operator()(strainfitness&& Fitness, mutate&& Mutate, trait_iterator xbeg, trait_iterator xend, frac_iterator fbeg, frac_iterator fend, double& meanw, URBG&& Engine) {
hmLib_assert(std::distance(xbeg, xend) == std::distance(fbeg, fend), hmLib::numeric_exceptions::incorrect_arithmetic_request, "distance of two iterator pairs are different.");
//make sampler following frequency of each strain
auto Sampler = hmLib::make_roulette_sampler(xbeg, xend, fbeg, fend);
//consumed time
double dt = 0.0;
//create trait variable for mutant
auto mutant = (*xbeg);
//try to find successful invasion
for (unsigned int MTrial = 0; MTrial < MaxMutationTrial; ++MTrial) {
//select strain producing mutant
auto sxitr = Sampler(Engine);
//create mutant
mutant = Mutate(*sxitr, Engine);
double w = Fitness(mutant, xbeg, xend, fbeg, fend);
//calc current trial num with updating maxf
// std::tuple<bool[Success], double[dt]>
auto Invasion = OSIPolicy.try_invade(w, meanw);
dt += std::get<1>(Invasion);
//if fail to invade, just continue loop.
if (!std::get<0>(Invasion))continue;
//swap trait value
std::swap(*sxitr, mutant);
//Update fraction with mutant
double nmeanw = Fitness.solve(xbeg, xend, fbeg, fend);
//calculate fitness for pre-resident
double nw = Fitness(mutant, xbeg, xend, fbeg, fend);
//reverse invasion is possible
if (OSIPolicy.can_invade(nw, nmeanw)) {
//swap trait value again (so mutant is now back to mutant)
std::swap(*sxitr, mutant);
meanw = Fitness.solve(xbeg, xend, fbeg, fend);
return osi_step_result<decltype(mutant)>{ true, dt, mutant };
} else {
meanw = nmeanw;
return osi_step_result<decltype(mutant)>{ true, dt };
}
}
return osi_step_result<decltype(mutant)>{ false, dt };
}
};
template<typename pair_game_, typename mutate_, typename osi_policy_>
struct pairgame_osi_dsystem {
using pair_game = pair_game_;
using strainfitness = pairgame_strainfitness<pair_game>;
using trait_type = typename pair_game::trait_type;
using mutate = mutate_;
using osi_policy = osi_policy_;
struct state_type {
std::vector<std::pair<trait_type, double>> strains;
double meanw;
};
private:
strainfitness Fitness;
mutate Mutate;
osi_stepper<osi_policy_> Stepper;
double ThrFreq;
public:
pairgame_osi_dsystem(pair_game Game_, mutate Mutate_, osi_policy OSIPolicy_, double ThrFreq_ = 1e-6)
: Fitness(std::move(Game_)), Mutate(std::move(Mutate_)), Stepper(OSIPolicy_), ThrFreq(ThrFreq_) {
}
void operator()(state_type& s, double& t) {
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
auto Result = Stepper(Fitness, Mutate, xrange.begin(), xrange.end(), frange.begin(), frange.end(), s.meanw, hmLib::random::default_engine());
t += Result.dt;
//add new strain
if (Result.branch) {
s.strains.emplace_back(std::move(Result.branch).value(), ThrFreq);
auto xrange2 = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange2 = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange2.begin(), xrange2.end(), frange2.begin(), frange2.end());
}
//remove extinction
auto ssend = std::remove_if(s.strains.begin(), s.strains.end(), [=](const auto& v) {return v.second < ThrFreq/2; });
s.strains.erase(ssend, s.strains.end());
}
void reset() { Stepper.reset(); }
template<typename trait_iterator>
state_type make_state(trait_iterator Beg, trait_iterator End) {
state_type s;
for (; Beg != End; ++Beg){
s.strains.emplace_back(*Beg, 0.0);
}
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange.begin(), xrange.end(), frange.begin(), frange.end());
return s;
}
state_type make_state(trait_type Trait) {
state_type s;
s.strains.emplace_back(std::move(Trait), 1.0);
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange.begin(), xrange.end(), frange.begin(), frange.end());
return s;
}
};
}
}
#
#endif
<commit_msg>Add pairgame_osi_state<commit_after>#ifndef HMLIB_BIO_OSI_INC
#define HMLIB_BIO_OSI_INC 100
#
#include<utility>
#include<vector>
#include<cmath>
#include<boost/optional.hpp>
#include"../tuple.hpp"
#include"../algorithm/sampling.hpp"
#include"../random.hpp"
#include"../exceptions.hpp"
#include"pairgame.hpp"
namespace hmLib {
namespace bio {
namespace osi {
// birth rate: b = rate*(w/meanw)
// daeth rate: d = rate
// w > 0 and meanw > 0 are requried.
struct birth_ratio_invasion_fitness {
// birth rate: b = rate*(w/meanw)
// daeth rate: d = rate
// mutation rate: m = mutation_frequency*birth_rate = TimeStep
// invasion rate: f = (b - d)/b = 1 - meanw/w
//Note: w and meanw should be positive
public:
double operator()(double w, double meanw)const {
return 1 - meanw / w;
}
};
// birth rate: b = rate*exp(alpha*(w-meanw))
// daeth rate: d = rate
// w and meanw can be negative.
struct birth_exp_invasion_fitness {
// birth rate: b = rate*exp(alpha*(w-meanw))
// daeth rate: d = rate
// mutation rate: m = mutation_frequency*birth_rate = TimeStep
// invasion rate: f = (b - d)/b = 1 - exp(-alpha*(w-meanw))
// alpha determines the strength of the selection.
//Note: w and/or meanw can be negative
private:
double alpha;
public:
birth_exp_invasion_fitness()noexcept : alpha(1.0) {}
explicit birth_exp_invasion_fitness(double alpha_)noexcept : alpha(alpha_) {}
double operator()(double w, double meanw)const {
return 1 - std::exp(-alpha * (w - meanw));
}
};
// invasion control (strict trial)
template<typename invasion_fitness>
struct simple_osi_policy {
private:
invasion_fitness Invasion;
public:
simple_osi_policy(invasion_fitness Invasion_ = invasion_fitness()) :Invasion(std::move(Invasion_)) {}
void reset() {}
std::pair<bool, double> try_invade(double w, double meanw) {
double f = Invasion(w, meanw);
return std::make_pair(f < hmLib::random::uniform_real(0.0, 1.0), -std::log(hmLib::random::uniform_real(0.0, 1.0)));
}
bool can_invade(double w, double meanw) { return Invasion(w, meanw) > 0; }
};
// invasion control (approximate by normal distribution based on central limit theorem)
template<typename invasion_fitness>
struct clt_osi_policy {
//average time consumption invasion trial
//sum of log(uniform_real(0.0,1.0)) for N times seems to be apploximated by a normal distribution with
// mean := -N
// var := N
//i.e., hmLib::random::normal(-1.0*N, std::sqrt(N))
private:
invasion_fitness Invasion;
double target; //[0:1]: target "mean probability" that an optimal mutant can successfully invade.
double decay; //[0:1]: reduction rate of the old data (1: no reduction, 0: forget immidiately).
double overrate;//[0: ]: rate of the over-estimation of the maximum probability from current probability. (0: no over-estimation 1: twice as large as f can appear)
unsigned int max_trial;
private:
double maxf;
public:
clt_osi_policy(double target_, double decay_, double overrate_, unsigned int max_trial_ = 5u, invasion_fitness Invasion_ = invasion_fitness())
: Invasion(std::move(Invasion_)), target(target_), decay(decay_), overrate(overrate_), max_trial(max_trial_), maxf(target) {
}
void reset() { maxf = target; }
std::pair<bool, double> try_invade(double w, double meanw) {
double f = Invasion(w, meanw);
unsigned int trial = std::max<unsigned int>(1, static_cast<unsigned int>(std::floor(std::log(1 - target) / std::log(1 - maxf))));
maxf = std::max(f * (1.0 + overrate), (1.0 - decay) * maxf);
bool Success = false;
double dt = 0;
//Success of invasion flag
if (trial < max_trial) {
//if trial number is enough small, just try 5 times.
// this is because approximation by normal distribution is less precious in small trial number.
if (f <= 0) {
for (unsigned int i = 0; i < trial; ++i) {
dt += -std::log(hmLib::random::uniform_real(0.0, 1.0));
}
} else {
for (unsigned int i = 0; i < trial; ++i) {
dt += -std::log(hmLib::random::uniform_real(0.0, 1.0));
if (f > hmLib::random::uniform_real(0.0, 1.0)) {
Success = true;
break;
}
}
}
} else {
//aproximate by normal distribution
if (f < 0 || std::pow(1 - f, trial) > hmLib::random::uniform_real(0.0, 1.0)) {
//fail to invade
do {
dt = -hmLib::random::normal(-1.0 * trial, std::sqrt(trial));
} while (dt <= 0);
} else {
//success to invade
Success = true;
//check mean time for invasion
// mean trial = 1*p + 2*p*(1-p)+ ... N*p*(1-p)^(N-1) with N = invasion_trial
// = ( (1 - (1-p)^N)/p - N*(1-p)^N )/( 1 - (1-p)^N )
double miss_prob = std::pow(1 - f, trial);
double mean_trial = ((1 - miss_prob) / f - trial * miss_prob) / (1 - miss_prob);
//hmLib::random::normal(-1.0*N, std::sqrt(N))
do {
dt = -hmLib::random::normal(-mean_trial, std::sqrt(mean_trial));
} while (dt <= 0);
}
}
return std::make_pair(Success, dt);
}
bool can_invade(double w, double meanw) { return Invasion(w, meanw) > 0; }
};
}
//return type of invasion policy
template<typename trait>
struct osi_step_result {
bool success;
double dt;
boost::optional<trait> branch;
osi_step_result() = default;
osi_step_result(bool success_, double dt_) :success(success_), dt(dt_), branch(boost::none) {}
osi_step_result(bool success_, double dt_, trait x) :success(success_), dt(dt_), branch(std::move(x)) {}
};
template<typename osi_policy_>
struct osi_stepper {
using osi_policy = osi_policy_; //control invasion trial
private:
osi_policy OSIPolicy;
unsigned int MaxMutationTrial;
public:
osi_stepper(osi_policy OSIPolicy_, unsigned int MaxMutationTrial_ = 10000)
: OSIPolicy(std::move(OSIPolicy_)), MaxMutationTrial(MaxMutationTrial_) {
}
void reset() { OSIPolicy.reset(); }
//return value is osi_step_result with the focal trait type
//[fbeg,fend) and meanw is changed inside of the function
template<typename strainfitness, typename mutate, typename trait_iterator, typename frac_iterator,typename URBG>
auto operator()(strainfitness&& Fitness, mutate&& Mutate, trait_iterator xbeg, trait_iterator xend, frac_iterator fbeg, frac_iterator fend, double& meanw, URBG&& Engine) {
hmLib_assert(std::distance(xbeg, xend) == std::distance(fbeg, fend), hmLib::numeric_exceptions::incorrect_arithmetic_request, "distance of two iterator pairs are different.");
//make sampler following frequency of each strain
auto Sampler = hmLib::make_roulette_sampler(xbeg, xend, fbeg, fend);
//consumed time
double dt = 0.0;
//create trait variable for mutant
auto mutant = (*xbeg);
//try to find successful invasion
for (unsigned int MTrial = 0; MTrial < MaxMutationTrial; ++MTrial) {
//select strain producing mutant
auto sxitr = Sampler(Engine);
//create mutant
mutant = Mutate(*sxitr, Engine);
double w = Fitness(mutant, xbeg, xend, fbeg, fend);
//calc current trial num with updating maxf
// std::tuple<bool[Success], double[dt]>
auto Invasion = OSIPolicy.try_invade(w, meanw);
dt += std::get<1>(Invasion);
//if fail to invade, just continue loop.
if (!std::get<0>(Invasion))continue;
//swap trait value
std::swap(*sxitr, mutant);
//Update fraction with mutant
double nmeanw = Fitness.solve(xbeg, xend, fbeg, fend);
//calculate fitness for pre-resident
double nw = Fitness(mutant, xbeg, xend, fbeg, fend);
//reverse invasion is possible
if (OSIPolicy.can_invade(nw, nmeanw)) {
//swap trait value again (so mutant is now back to mutant)
std::swap(*sxitr, mutant);
meanw = Fitness.solve(xbeg, xend, fbeg, fend);
return osi_step_result<decltype(mutant)>{ true, dt, mutant };
} else {
meanw = nmeanw;
return osi_step_result<decltype(mutant)>{ true, dt };
}
}
return osi_step_result<decltype(mutant)>{ false, dt };
}
};
template<typename trait_type>
struct pairgame_osi_state {
std::vector<std::pair<trait_type, double>> strains;
double meanw;
};
template<typename pair_game_, typename mutate_, typename osi_policy_>
struct pairgame_osi_dsystem {
using pair_game = pair_game_;
using strainfitness = pairgame_strainfitness<pair_game>;
using trait_type = typename pair_game::trait_type;
using mutate = mutate_;
using osi_policy = osi_policy_;
using state_type = pairgame_osi_state<trait_type>;
private:
strainfitness Fitness;
mutate Mutate;
osi_stepper<osi_policy_> Stepper;
double ThrFreq;
public:
pairgame_osi_dsystem(pair_game Game_, mutate Mutate_, osi_policy OSIPolicy_, double ThrFreq_ = 1e-6)
: Fitness(std::move(Game_)), Mutate(std::move(Mutate_)), Stepper(OSIPolicy_), ThrFreq(ThrFreq_) {
}
void operator()(state_type& s, double& t) {
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
auto Result = Stepper(Fitness, Mutate, xrange.begin(), xrange.end(), frange.begin(), frange.end(), s.meanw, hmLib::random::default_engine());
t += Result.dt;
//add new strain
if (Result.branch) {
s.strains.emplace_back(std::move(Result.branch).value(), ThrFreq);
auto xrange2 = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange2 = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange2.begin(), xrange2.end(), frange2.begin(), frange2.end());
}
//remove extinction
auto ssend = std::remove_if(s.strains.begin(), s.strains.end(), [=](const auto& v) {return v.second < ThrFreq/2; });
s.strains.erase(ssend, s.strains.end());
}
void reset() { Stepper.reset(); }
template<typename trait_iterator>
state_type make_state(trait_iterator Beg, trait_iterator End) {
state_type s;
for (; Beg != End; ++Beg){
s.strains.emplace_back(*Beg, 0.0);
}
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange.begin(), xrange.end(), frange.begin(), frange.end());
return s;
}
state_type make_state(trait_type Trait) {
state_type s;
s.strains.emplace_back(std::move(Trait), 1.0);
auto xrange = hmLib::make_get_range<0>(s.strains.begin(), s.strains.end());
auto frange = hmLib::make_get_range<1>(s.strains.begin(), s.strains.end());
s.meanw = Fitness.solve(xrange.begin(), xrange.end(), frange.begin(), frange.end());
return s;
}
};
}
}
#
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
* PROGRAM NAME: COutputLine.cpp
* PROGRAMMER: Wei Sun wsun@vt.edu
* PURPOSE: COutputLine Class Implemention
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <iomanip>
#include "copasi.h"
#include "model/CCompartment.h"
#include "CDatum.h"
#include "COutputLine.h"
/**
* Default constructor.
*/
COutputLine::COutputLine()
{
// mLine = NULL;
}
void COutputLine::init()
{
// mLine = new CCDatum;
}
void COutputLine::cleanup()
{
// if (mLine) delete mLine;
// mLine = NULL;
mLine.cleanup();
}
/**
* Destructor.
*/
COutputLine::~COutputLine()
{
// cleanup();
}
/**
* Assignement operator.
* Copies the contents from one COutputLine object to another.
* @param source reference to the recipient object.
*/
COutputLine& COutputLine::operator=(const COutputLine &source)
{
mLine = source.mLine;
return *this;
}
/**
* Return the pointer of the CDatum that can be output at the same line.
* @return mLine
* @see mLine
*/
const CCopasiVectorS < CDatum > & COutputLine::getLine() const
{
return mLine;
}
/**
* Sets the name of this line, (For example: Interactive time course)
* @param title constant reference to a string.
*/
void COutputLine::setName(string LineName)
{
mName = LineName;
}
/**
* Add new CDatum object to a line
* @param newDatum constant reference to CDatum.
* @see CDatum Class
*/
void COutputLine::addDatum(CDatum & newDatum)
{
mLine.add(newDatum);
}
C_INT32 COutputLine::load(CReadConfig & configbuffer) {return 0;}
/**
* Loads an object with data coming from a CReadConfig object.
* (CReadConfig object reads an input stream)
* @param pconfigbuffer reference to a CReadConfig object.
* @param searchName refernece to a the time of seach section,
* for example: Interactive time course
* @return mFail
* @see mFail
*/
C_INT32 COutputLine::load(CReadConfig & configbuffer, string &searchName)
{
C_INT32 Fail = 0;
C_INT32 Size = 0;
// Search string searchName from configure variable
if ((Fail = configbuffer.getVariable(searchName, "string",
&mName,
CReadConfig::SEARCH)))
return Fail;
// now pout points the end of search string
// Read the number of items in this section
if ((Fail = configbuffer.getVariable("Items", "C_INT32",
&Size, CReadConfig::NEXT)))
return Fail;
init();
// Read objects and create the OutputLine
for (int i = 0; i < Size; i++)
{
CDatum newItem;
newItem.load(configbuffer);
addDatum(newItem);
}
return Fail;
}
/**
* Saves the contents of the object to a CWriteConfig object.
* (Which usually has a file attached but may also have socket)
* @param pconfigbuffer reference to a CWriteConfig object.
* @return mFail
* @see mFail
*/
C_INT32 COutputLine::save(CWriteConfig & configbuffer)
{
C_INT32 Fail = 0;
C_INT32 Size = 0;
Size = mLine.size();
if ((Fail = configbuffer.setVariable(mName, "string", NULL)))
return Fail;
if ((Fail = configbuffer.setVariable("Items", "C_INT32", &Size)))
return Fail;
// Output each datum in this line
//Fail = mLine->save(configbuffer);
mLine.save(configbuffer);
return Fail;
}
/**
* print the titles of the steady-state data file
*/
void COutputLine::sSOutputTitles(ofstream &fout, C_INT16 SSSeparator, C_INT16 SSColWidth, C_INT16 SSQuotes)
{
unsigned C_INT32 i;
CDatum item;
string Title;
// Set Left Justification
fout.setf(ios::left);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (SSSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
item = *mLine[i];
if (item.getTitle().length() > (unsigned C_INT32) SSColWidth)
Title = item.getTitle().substr(0, SSColWidth);
else Title = item.getTitle();
if (SSQuotes) fout << "\"" << setw(SSColWidth) << Title << "\"";
else fout << setw(SSColWidth) <<Title;
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the mpValue of each Object in the steady-state data file
*/
void COutputLine::sSOutputData(ofstream &fout, C_INT16 SSSeparator, C_INT16 SSColWidth, C_INT16 SSQuotes)
{
unsigned C_INT32 i;
C_INT32 Type;
C_INT16 *Value1;
C_INT32 *Value2;
C_FLOAT32 *Value3;
C_FLOAT64 *Value4;
CDatum *datum;
// Set Left Justification
fout.setf(ios::left);
// Set Float manipulators
fout.setf(ios::scientific, ios::floatfield);
fout.setf(ios::showpoint);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (SSSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
datum = mLine[i];
// before outputing value of user defined function, need to
// calculate first
if (datum->getObjectType(datum->getObject()) == D_UFUNC)
datum->calcFunc();
Type = mLine[i]->getType();
switch (Type)
{
case 1:
// Type is C_INT16
Value1 = (C_INT16 *)mLine[i]->getValue();
if (!Value1)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0; //?? Sign setw(SSColWidth-1)
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value1; //?? Sign
break;
case 2:
// Type is C_INT32
Value2 = (C_INT32 *)mLine[i]->getValue();
if (!Value2)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value2;
break;
case 3:
// Type is C_FLOAT32
Value3 = (C_FLOAT32 *)mLine[i]->getValue();
if (!Value3)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value3;
break;
case 4:
// Type is C_FLOAT64
Value4 = (C_FLOAT64 *)mLine[i]->getValue();
if (!Value4)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value4;
break;
}
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the titles of the time course data file
*/
void COutputLine::dynOutputTitles(ofstream &fout, C_INT16 DynSeparator, C_INT16 DynColWidth, C_INT16 DynQuotes)
{
unsigned C_INT32 i;
CDatum item;
string Title;
// Set Left Justification
fout.setf(ios::left);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (DynSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
item = *mLine[i];
if (item.getTitle().length() > (unsigned C_INT16) DynColWidth)
Title = item.getTitle().substr(0, DynColWidth);
else Title = item.getTitle();
if (DynQuotes) fout << "\"" << setw(DynColWidth) << Title << "\"";
else fout << setw(DynColWidth) <<Title;
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the mpValue of each Object in the time course data file
*/
void COutputLine::dynOutputData(ofstream &fout, C_INT16 DynSeparator, C_INT16 DynColWidth, C_INT16 DynQuotes)
{
unsigned C_INT32 i;
C_INT32 Type;
C_INT16 *Value1;
C_INT32 *Value2;
C_FLOAT32 *Value3;
C_FLOAT64 *Value4;
CDatum *datum;
// Set Left Justification
fout.setf(ios::left);
// Set Float manipulators
fout.setf(ios::scientific, ios::floatfield);
fout.setf(ios::showpoint);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (DynSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
datum = mLine[i];
// before outputing value of user defined function, need to
// calculate first
if (datum->getObjectType(datum->getObject()) == D_UFUNC)
datum->calcFunc();
Type = mLine[i]->getType();
switch (Type)
{
case 1:
// Type is C_INT16
Value1 = (C_INT16 *)mLine[i]->getValue();
if (!Value1)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value1;
break;
case 2:
// Type is C_INT32
Value2 = (C_INT32 *)mLine[i]->getValue();
if (!Value2)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value2;
break;
case 3:
// Type is C_FLOAT32
Value3 = (C_FLOAT32 *)mLine[i]->getValue();
if (!Value3)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value3;
break;
case 4:
// Type is C_FLOAT64
Value4 = (C_FLOAT64 *)mLine[i]->getValue();
if (!Value4)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value4;
break;
}
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* Assign the pointer to each datum object in the output line for time course
*/
void COutputLine::compile(string &name, CModel *model, CTrajectory *traj)
{
if (!mName.compare(name))
{ // ???? Maybe it isnot necessary after finish whole module
for (unsigned C_INT32 i = 0; i < mLine.size(); i++)
{
mLine[i]->compileDatum(model, traj, NULL);
}
}
}
/**
* Assign the pointer to each datum object in the output line for steady state
*/
void COutputLine::compile(string &name, CModel *model, CSS_Solution *soln)
{
if (!mName.compare(name))
{ // ???? Maybe it isnot necessary after finish whole module
for (unsigned C_INT32 i = 0; i < mLine.size(); i++)
{
mLine[i]->compileDatum(model, soln->getTrajectory(), soln);
}
}
}
#ifdef XXXX
COutputLine::CCDatum::CCDatum() {}
COutputLine::CCDatum::~CCDatum() {}
C_INT16 COutputLine::CCDatum::isInsertAllowed(const CDatum & src)
{return TRUE;}
#endif // XXXX
<commit_msg>Update code related steady state output<commit_after>/*****************************************************************************
* PROGRAM NAME: COutputLine.cpp
* PROGRAMMER: Wei Sun wsun@vt.edu
* PURPOSE: COutputLine Class Implemention
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <iomanip>
#include "copasi.h"
#include "model/CCompartment.h"
#include "CDatum.h"
#include "COutputLine.h"
/**
* Default constructor.
*/
COutputLine::COutputLine()
{
// mLine = NULL;
}
void COutputLine::init()
{
// mLine = new CCDatum;
}
void COutputLine::cleanup()
{
// if (mLine) delete mLine;
// mLine = NULL;
mLine.cleanup();
}
/**
* Destructor.
*/
COutputLine::~COutputLine()
{
// cleanup();
}
/**
* Assignement operator.
* Copies the contents from one COutputLine object to another.
* @param source reference to the recipient object.
*/
COutputLine& COutputLine::operator=(const COutputLine &source)
{
mLine = source.mLine;
return *this;
}
/**
* Return the pointer of the CDatum that can be output at the same line.
* @return mLine
* @see mLine
*/
const CCopasiVectorS < CDatum > & COutputLine::getLine() const
{
return mLine;
}
/**
* Sets the name of this line, (For example: Interactive time course)
* @param title constant reference to a string.
*/
void COutputLine::setName(string LineName)
{
mName = LineName;
}
/**
* Add new CDatum object to a line
* @param newDatum constant reference to CDatum.
* @see CDatum Class
*/
void COutputLine::addDatum(CDatum & newDatum)
{
mLine.add(newDatum);
}
C_INT32 COutputLine::load(CReadConfig & configbuffer) {return 0;}
/**
* Loads an object with data coming from a CReadConfig object.
* (CReadConfig object reads an input stream)
* @param pconfigbuffer reference to a CReadConfig object.
* @param searchName refernece to a the time of seach section,
* for example: Interactive time course
* @return mFail
* @see mFail
*/
C_INT32 COutputLine::load(CReadConfig & configbuffer, string &searchName)
{
C_INT32 Fail = 0;
C_INT32 Size = 0;
// Search string searchName from configure variable
if ((Fail = configbuffer.getVariable(searchName, "string",
&mName,
CReadConfig::SEARCH)))
return Fail;
// now pout points the end of search string
// Read the number of items in this section
if ((Fail = configbuffer.getVariable("Items", "C_INT32",
&Size, CReadConfig::NEXT)))
return Fail;
init();
// Read objects and create the OutputLine
for (int i = 0; i < Size; i++)
{
CDatum newItem;
newItem.load(configbuffer);
addDatum(newItem);
}
return Fail;
}
/**
* Saves the contents of the object to a CWriteConfig object.
* (Which usually has a file attached but may also have socket)
* @param pconfigbuffer reference to a CWriteConfig object.
* @return mFail
* @see mFail
*/
C_INT32 COutputLine::save(CWriteConfig & configbuffer)
{
C_INT32 Fail = 0;
C_INT32 Size = 0;
Size = mLine.size();
if ((Fail = configbuffer.setVariable(mName, "string", NULL)))
return Fail;
if ((Fail = configbuffer.setVariable("Items", "C_INT32", &Size)))
return Fail;
// Output each datum in this line
//Fail = mLine->save(configbuffer);
mLine.save(configbuffer);
return Fail;
}
/**
* print the titles of the steady-state data file
*/
void COutputLine::sSOutputTitles(ofstream &fout, C_INT16 SSSeparator, C_INT16 SSColWidth, C_INT16 SSQuotes)
{
unsigned C_INT32 i;
CDatum item;
string Title;
// Set Left Justification
fout.setf(ios::left);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (SSSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
item = *mLine[i];
if (item.getTitle().length() > (unsigned C_INT32) SSColWidth)
Title = item.getTitle().substr(0, SSColWidth);
else Title = item.getTitle();
if (SSQuotes) fout << "\"" << setw(SSColWidth) << Title << "\"";
else fout << setw(SSColWidth) <<Title;
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the mpValue of each Object in the steady-state data file
*/
void COutputLine::sSOutputData(ofstream &fout, C_INT16 SSSeparator, C_INT16 SSColWidth, C_INT16 SSQuotes, C_INT32 ss_solution)
{
unsigned C_INT32 i;
C_INT32 Type;
C_INT16 *Value1;
C_INT32 *Value2;
C_FLOAT32 *Value3;
C_FLOAT64 *Value4;
CDatum *datum;
// Set Left Justification
fout.setf(ios::left);
// Set Float manipulators
fout.setf(ios::scientific, ios::floatfield);
fout.setf(ios::showpoint);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (SSSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
if (ss_solution == SS_FOUND)
{
datum = mLine[i];
// before outputing value of user defined function, need to
// calculate first
if (datum->getObjectType(datum->getObject()) == D_UFUNC)
datum->calcFunc();
Type = mLine[i]->getType();
switch (Type)
{
case 1:
// Type is C_INT16
Value1 = (C_INT16 *)mLine[i]->getValue();
if (!Value1)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0; //?? Sign setw(SSColWidth-1)
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value1; //?? Sign
break;
case 2:
// Type is C_INT32
Value2 = (C_INT32 *)mLine[i]->getValue();
if (!Value2)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value2;
break;
case 3:
// Type is C_FLOAT32
Value3 = (C_FLOAT32 *)mLine[i]->getValue();
if (!Value3)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value3;
break;
case 4:
// Type is C_FLOAT64
Value4 = (C_FLOAT64 *)mLine[i]->getValue();
if (!Value4)
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
else fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << *Value4;
break;
}
}
else
fout << setprecision(SSColWidth - 8) << setw(SSColWidth) << 0;
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the titles of the time course data file
*/
void COutputLine::dynOutputTitles(ofstream &fout, C_INT16 DynSeparator, C_INT16 DynColWidth, C_INT16 DynQuotes)
{
unsigned C_INT32 i;
CDatum item;
string Title;
// Set Left Justification
fout.setf(ios::left);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (DynSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
item = *mLine[i];
if (item.getTitle().length() > (unsigned C_INT16) DynColWidth)
Title = item.getTitle().substr(0, DynColWidth);
else Title = item.getTitle();
if (DynQuotes) fout << "\"" << setw(DynColWidth) << Title << "\"";
else fout << setw(DynColWidth) <<Title;
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* print the mpValue of each Object in the time course data file
*/
void COutputLine::dynOutputData(ofstream &fout, C_INT16 DynSeparator, C_INT16 DynColWidth, C_INT16 DynQuotes)
{
unsigned C_INT32 i;
C_INT32 Type;
C_INT16 *Value1;
C_INT32 *Value2;
C_FLOAT32 *Value3;
C_FLOAT64 *Value4;
CDatum *datum;
// Set Left Justification
fout.setf(ios::left);
// Set Float manipulators
fout.setf(ios::scientific, ios::floatfield);
fout.setf(ios::showpoint);
for (i = 0; i < mLine.size(); i++)
{
if (i) {
switch (DynSeparator)
{
case 9:
fout << "\t";
break;
case 32:
fout << " ";
break;
case 44:
fout << ",";
break;
}
}
datum = mLine[i];
// before outputing value of user defined function, need to
// calculate first
if (datum->getObjectType(datum->getObject()) == D_UFUNC)
datum->calcFunc();
Type = mLine[i]->getType();
switch (Type)
{
case 1:
// Type is C_INT16
Value1 = (C_INT16 *)mLine[i]->getValue();
if (!Value1)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value1;
break;
case 2:
// Type is C_INT32
Value2 = (C_INT32 *)mLine[i]->getValue();
if (!Value2)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value2;
break;
case 3:
// Type is C_FLOAT32
Value3 = (C_FLOAT32 *)mLine[i]->getValue();
if (!Value3)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value3;
break;
case 4:
// Type is C_FLOAT64
Value4 = (C_FLOAT64 *)mLine[i]->getValue();
if (!Value4)
fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << 0;
else fout << setprecision(DynColWidth - 8) << setw(DynColWidth) << *Value4;
break;
}
}
fout.unsetf(ios::left);
fout << endl;
}
/**
* Assign the pointer to each datum object in the output line for time course
*/
void COutputLine::compile(string &name, CModel *model, CTrajectory *traj)
{
if (!mName.compare(name))
{ // ???? Maybe it isnot necessary after finish whole module
for (unsigned C_INT32 i = 0; i < mLine.size(); i++)
{
mLine[i]->compileDatum(model, traj, NULL);
}
}
}
/**
* Assign the pointer to each datum object in the output line for steady state
*/
void COutputLine::compile(string &name, CModel *model, CSS_Solution *soln)
{
if (!mName.compare(name))
{ // ???? Maybe it isnot necessary after finish whole module
for (unsigned C_INT32 i = 0; i < mLine.size(); i++)
{
mLine[i]->compileDatum(model, soln->getTrajectory(), soln);
}
}
}
#ifdef XXXX
COutputLine::CCDatum::CCDatum() {}
COutputLine::CCDatum::~CCDatum() {}
C_INT16 COutputLine::CCDatum::isInsertAllowed(const CDatum & src)
{return TRUE;}
#endif // XXXX
<|endoftext|>
|
<commit_before>
#include "MapFileParser.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <DbgHelp.h>
#include <ClangReflectCore/Database.h>
#include <ClangReflectCore/FileUtils.h>
#include <ClangReflectCore/Logging.h>
#include <cstdio>
#include <cstring>
namespace
{
bool InitialiseSymbolHandler()
{
SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
{
LOG(main, ERROR, "Couldn't initialise symbol handler - no function addresses will be available!");
return false;
}
return true;
}
void ShutdownSymbolHandler()
{
SymCleanup(GetCurrentProcess());
}
std::string UndecorateFunctionName(const char* token)
{
char function_name[1024];
UnDecorateSymbolName(token, function_name, sizeof(function_name), UNDNAME_NAME_ONLY);
return function_name;
}
std::string UndecorateFunctionSignature(const char* token)
{
char function_signature[1024];
UnDecorateSymbolName(token, function_signature, sizeof(function_signature),
UNDNAME_COMPLETE |
UNDNAME_NO_ACCESS_SPECIFIERS |
UNDNAME_NO_ALLOCATION_LANGUAGE |
UNDNAME_NO_ALLOCATION_MODEL |
UNDNAME_NO_MEMBER_TYPE |
UNDNAME_NO_SPECIAL_SYMS |
UNDNAME_NO_THROW_SIGNATURES);
return function_signature;
}
unsigned int ParseAddressField(const char* line, const char* function_name)
{
// First parse the address as hex
char token[1024];
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
unsigned int function_address = hextoi(token);
// Double-check that the map file knows this is a function
line = SkipWhitespace(line);
if (line[0] != 'f')
{
LOG(main, ERROR, "Function '%s' is not a function symbol in the map file", function_name);
return 0;
}
return function_address;
}
void AddFunctionAddress(crdb::Database& db, const std::string& function_name, const std::string& function_signature, unsigned int function_address)
{
if (function_address == 0)
{
return;
}
}
void AddClassImplFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address, bool is_constructor)
{
if (function_address == 0)
{
return;
}
// Isolate the parameter list
size_t pos = function_signature.find('(');
if (pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate opening bracket of class impl function");
return;
}
pos++;
// Skip the prefix
if (!strncmp(function_signature.c_str() + pos, "struct ", sizeof("struct")))
{
pos += sizeof("struct");
}
if (!strncmp(function_signature.c_str() + pos, "class ", sizeof("class")))
{
pos += sizeof("class");
}
// Locate the end of the typename of the first parameter by checking for its
// pointer spec and accounting for whitespace
size_t end_pos = function_signature.find('*', pos);
if (end_pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate pointer character for first parameter of class impl function");
return;
}
while (function_signature[end_pos] == ' ' || function_signature[end_pos] == '*')
end_pos--;
// Generate the names for the parameter
std::string parameter_type_name_str = function_signature.substr(pos, end_pos - pos + 1);
crdb::Name parameter_type_name = db.GetName(parameter_type_name_str.c_str());
crdb::Name parameter_name = db.GetName("this");
// Generate a name for the new function
std::string function_name_str = parameter_type_name_str + "::";
if (is_constructor)
{
function_name_str += "ConstructObject";
}
else
{
function_name_str += "DestructObject";
}
crdb::Name function_name = db.GetName(function_name_str.c_str());
// Create the parameter
crdb::Field parameter(
parameter_name,
function_name,
parameter_type_name,
crdb::Field::MODIFIER_POINTER,
false,
0);
// Generate a unique ID that binds the function and parameter together
std::vector<crdb::Field> parameters;
parameters.push_back(parameter);
crdb::u32 unique_id = crdb::CalculateFunctionUniqueID(0, parameters);
// Create the function and bind the parameter to it
crdb::Function function(
function_name,
parameter_type_name,
unique_id);
parameter.parent_unique_id = unique_id;
// Record the transient function address that will be exported
function.address = function_address;
// Add the new primitives to the database
db.AddPrimitive(parameter);
db.AddPrimitive(function);
}
void AddConstructFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address)
{
AddClassImplFunction(db, function_signature, function_address, true);
}
void AddDestructFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address)
{
AddClassImplFunction(db, function_signature, function_address, false);
}
}
MapFileParser::MapFileParser(crdb::Database& db, const char* filename)
{
static const char* construct_object = "crcpp::internal::ConstructObject";
static const char* destruct_object = "crcpp::internal::DestructObject";
if (!InitialiseSymbolHandler())
{
return;
}
FILE* fp = fopen(filename, "rb");
if (fp == 0)
{
return;
}
bool public_symbols = false;
while (const char* line = ReadLine(fp))
{
if (public_symbols)
{
char token[1024];
// Consume everything up to the function name
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
// Undecorate the symbol name alone and see if it's a known crcpp function
std::string function_name = UndecorateFunctionName(token);
if (function_name == construct_object)
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddConstructFunction(db, function_signature, function_address);
}
else if (function_name == destruct_object)
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddDestructFunction(db, function_signature, function_address);
}
// Otherwise see if it's a function in the database
else if (const crdb::Function* function = db.GetFirstPrimitive<crdb::Function>(function_name.c_str()))
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddFunctionAddress(db, function_name, function_signature, function_address);
}
}
// Look for the start of the public symbols descriptors
if (strstr(line, " Address"))
{
ReadLine(fp);
public_symbols = true;
}
}
fclose(fp);
ShutdownSymbolHandler();
}<commit_msg>Added parsing of all functions in the map file so that nearly everything now has an address. I think there's a few bugs in there to do with the this pointer, though.<commit_after>
#include "MapFileParser.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <DbgHelp.h>
#include <ClangReflectCore/Database.h>
#include <ClangReflectCore/FileUtils.h>
#include <ClangReflectCore/Logging.h>
#include <cstdio>
#include <cstring>
namespace
{
bool InitialiseSymbolHandler()
{
SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
{
LOG(main, ERROR, "Couldn't initialise symbol handler - no function addresses will be available!");
return false;
}
return true;
}
void ShutdownSymbolHandler()
{
SymCleanup(GetCurrentProcess());
}
std::string UndecorateFunctionName(const char* token)
{
char function_name[1024];
UnDecorateSymbolName(token, function_name, sizeof(function_name), UNDNAME_NAME_ONLY);
return function_name;
}
std::string UndecorateFunctionSignature(const char* token)
{
char function_signature[1024];
UnDecorateSymbolName(token, function_signature, sizeof(function_signature),
UNDNAME_COMPLETE |
UNDNAME_NO_ACCESS_SPECIFIERS |
UNDNAME_NO_ALLOCATION_LANGUAGE |
UNDNAME_NO_ALLOCATION_MODEL |
UNDNAME_NO_MEMBER_TYPE |
UNDNAME_NO_SPECIAL_SYMS |
UNDNAME_NO_THROW_SIGNATURES);
return function_signature;
}
unsigned int ParseAddressField(const char* line, const char* function_name)
{
// First parse the address as hex
char token[1024];
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
unsigned int function_address = hextoi(token);
// Double-check that the map file knows this is a function
line = SkipWhitespace(line);
if (line[0] != 'f')
{
LOG(main, ERROR, "Function '%s' is not a function symbol in the map file", function_name);
return 0;
}
return function_address;
}
const char* ConsumeParameterToken(const char* text, char* dest, int dest_size)
{
char* end = dest + dest_size;
while (*text
&& *text != ' '
&& *text != ','
&& *text != ')'
&& dest != end)
{
*dest++ = *text++;
}
*dest = 0;
return text;
}
crdb::Field MatchParameter(crdb::Database& db, const char*& ptr, const char* end)
{
crdb::Field parameter;
char type_name[1024] = { 0 };
char token[1024] = { 0 };
// Loop reading tokens irrespective of order. Note that this parsing strategy won't distinguish between
// the type of const-qualifier. However, only one mode of qualification is currently supported so this
// will suffice for now.
bool parse = true;
while (parse && ptr < end)
{
ptr = ConsumeParameterToken(ptr, token, sizeof(token));
ptr = SkipWhitespace(ptr);
// Check for modifiers
if (token[0] == '&')
{
parameter.modifier = crdb::Field::MODIFIER_REFERENCE;
}
else if (token[0] == '*')
{
parameter.modifier = crdb::Field::MODIFIER_POINTER;
}
// Check for const qualification
else if (!strcmp(token, "const"))
{
parameter.is_const = true;
}
// Check for any type prefixes
else if (!strcmp(token, "unsigned") || !strcmp(token, "signed"))
{
strcpy(type_name, token);
strcat(type_name, " ");
}
// What's remaining must be the type name
else
{
strcat(type_name, token);
}
if (*ptr == ',' || *ptr == ')')
{
ptr++;
break;
}
}
parameter.type = db.GetName(type_name);
return parameter;
}
void AddFunctionAddress(crdb::Database& db, const std::string& function_name, const std::string& function_signature, unsigned int function_address)
{
if (function_address == 0)
{
return;
}
// Find where the return type ends
size_t func_pos = function_signature.find(function_name);
if (func_pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate function name in signature for '%s'", function_name.c_str());
return;
}
// Parse the return parameter and only remember it if it's non-void
const char* ptr = function_signature.c_str();
crdb::Field return_parameter = MatchParameter(db, ptr, ptr + func_pos);
crdb::Field* return_parameter_ptr = 0;
if (return_parameter.type.text != "void")
{
return_parameter_ptr = &return_parameter;
}
// Isolate the parameters in the signature
size_t l_pos = function_signature.find('(', func_pos);
if (l_pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate left bracket in signature for '%s'", function_name.c_str());
return;
}
size_t r_pos = function_signature.find(')', l_pos);
if (r_pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate right bracket in signature for '%s'", function_name.c_str());
return;
}
// Parse the parameters
std::vector<crdb::Field> parameters;
ptr = function_signature.c_str() + l_pos + 1;
const char* end = function_signature.c_str() + r_pos;
while (ptr < end)
{
crdb::Field parameter = MatchParameter(db, ptr, end);
if (parameter.type.text != "void")
{
parameters.push_back(parameter);
}
}
// Calculate the ID of the matching function
crdb::u32 unique_id = crdb::CalculateFunctionUniqueID(return_parameter_ptr, parameters);
// Search through all functions of the same name
crdb::u32 function_hash = crcpp::internal::HashNameString(function_name.c_str());
crdb::PrimitiveStore<crdb::Function>::range functions = db.m_Functions.equal_range(function_hash);
for (crdb::PrimitiveStore<crdb::Function>::iterator i = functions.first; i != functions.second; ++i)
{
// Assign the function address when the unique IDs match
if (i->second.unique_id == unique_id)
{
i->second.address = function_address;
break;
}
}
}
void AddClassImplFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address, bool is_constructor)
{
if (function_address == 0)
{
return;
}
// Isolate the parameter list
size_t pos = function_signature.find('(');
if (pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate opening bracket of class impl function");
return;
}
pos++;
// Skip the prefix
if (!strncmp(function_signature.c_str() + pos, "struct ", sizeof("struct")))
{
pos += sizeof("struct");
}
if (!strncmp(function_signature.c_str() + pos, "class ", sizeof("class")))
{
pos += sizeof("class");
}
// Locate the end of the typename of the first parameter by checking for its
// pointer spec and accounting for whitespace
size_t end_pos = function_signature.find('*', pos);
if (end_pos == std::string::npos)
{
LOG(main, ERROR, "Couldn't locate pointer character for first parameter of class impl function");
return;
}
while (function_signature[end_pos] == ' ' || function_signature[end_pos] == '*')
end_pos--;
// Generate the names for the parameter
std::string parameter_type_name_str = function_signature.substr(pos, end_pos - pos + 1);
crdb::Name parameter_type_name = db.GetName(parameter_type_name_str.c_str());
crdb::Name parameter_name = db.GetName("this");
// Generate a name for the new function
std::string function_name_str = parameter_type_name_str + "::";
if (is_constructor)
{
function_name_str += "ConstructObject";
}
else
{
function_name_str += "DestructObject";
}
crdb::Name function_name = db.GetName(function_name_str.c_str());
// Create the parameter
crdb::Field parameter(
parameter_name,
function_name,
parameter_type_name,
crdb::Field::MODIFIER_POINTER,
false,
0);
// Generate a unique ID that binds the function and parameter together
std::vector<crdb::Field> parameters;
parameters.push_back(parameter);
crdb::u32 unique_id = crdb::CalculateFunctionUniqueID(0, parameters);
// Create the function and bind the parameter to it
crdb::Function function(
function_name,
parameter_type_name,
unique_id);
parameter.parent_unique_id = unique_id;
// Record the transient function address that will be exported
function.address = function_address;
// Add the new primitives to the database
db.AddPrimitive(parameter);
db.AddPrimitive(function);
}
void AddConstructFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address)
{
AddClassImplFunction(db, function_signature, function_address, true);
}
void AddDestructFunction(crdb::Database& db, const std::string& function_signature, unsigned int function_address)
{
AddClassImplFunction(db, function_signature, function_address, false);
}
}
MapFileParser::MapFileParser(crdb::Database& db, const char* filename)
{
static const char* construct_object = "crcpp::internal::ConstructObject";
static const char* destruct_object = "crcpp::internal::DestructObject";
if (!InitialiseSymbolHandler())
{
return;
}
FILE* fp = fopen(filename, "rb");
if (fp == 0)
{
return;
}
bool public_symbols = false;
while (const char* line = ReadLine(fp))
{
if (public_symbols)
{
char token[1024];
// Consume everything up to the function name
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
line = SkipWhitespace(line);
line = ConsumeToken(line, ' ', token, sizeof(token));
// Undecorate the symbol name alone and see if it's a known crcpp function
std::string function_name = UndecorateFunctionName(token);
if (function_name == construct_object)
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddConstructFunction(db, function_signature, function_address);
}
else if (function_name == destruct_object)
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddDestructFunction(db, function_signature, function_address);
}
// Otherwise see if it's a function in the database
else if (const crdb::Function* function = db.GetFirstPrimitive<crdb::Function>(function_name.c_str()))
{
std::string function_signature = UndecorateFunctionSignature(token);
unsigned int function_address = ParseAddressField(line, function_name.c_str());
AddFunctionAddress(db, function_name, function_signature, function_address);
}
}
// Look for the start of the public symbols descriptors
if (strstr(line, " Address"))
{
ReadLine(fp);
public_symbols = true;
}
}
fclose(fp);
ShutdownSymbolHandler();
}<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/fusion_bitcast_lift.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/core/platform/errors.h"
namespace xla {
namespace gpu {
// Returns true if all instructions are supported operations.
static bool AreInstructionSupported(HloComputation* comp) {
for (HloInstruction* instr : comp->instructions()) {
bool supported =
HloInstruction::IsOpElementwise(instr->opcode()) ||
instr->opcode() == HloOpcode::kConstant ||
// We only support reduction when they are at the root or when
// in a MOF, at the end. This should always be true for now,
// but if we implement reduction epilog fusion in the future,
// this optimization need to be updated. So disable it just for
// future safety.
(instr->opcode() == HloOpcode::kReduce &&
(comp->root_instruction() == instr ||
(instr->users().size() == 1 &&
instr->users()[0]->opcode() == HloOpcode::kTuple))) ||
instr->opcode() == HloOpcode::kTuple ||
instr->opcode() == HloOpcode::kParameter ||
(instr->opcode() == HloOpcode::kBitcast &&
instr->shape().rank() < instr->operand(0)->shape().rank()) ||
(instr->opcode() == HloOpcode::kBroadcast &&
(instr->dimensions().empty() || // scalar broadcasting
(instr->dimensions().size() == 1 && // row broadcasting
instr->dimensions()[0] == (instr->shape().rank() - 1))));
if (!supported) {
VLOG(2) << "NOT SUPPORTED: " << instr->ToString();
return false;
}
}
return true;
}
StatusOr<bool> FusionBitcastLift::Run(HloModule* module) {
XLA_VLOG_LINES(2, "FusionBitcastLift::Run(), before:\n" + module->ToString());
bool changed = false;
for (HloComputation* comp : module->MakeNonfusionComputations()) {
// Copy the instruction list as we modify the HloComputation.
std::vector<HloInstruction*> comp_instruction(comp->instructions().begin(),
comp->instructions().end());
for (HloInstruction* instr : comp_instruction) {
// 1) Is this a fusion that we want to modify.
if (auto* fusion = DynCast<HloFusionInstruction>(instr)) {
// 1.1) We only support kInput fusion and some operations.
if (fusion->fusion_kind() != HloInstruction::FusionKind::kInput ||
!AreInstructionSupported(
fusion->fused_instructions_computation())) {
continue;
}
// 1.2) Check if there is a bitcast that we lift. Currently
// we do not lift(merge) bitcast above(with) broadcast.
if (!std::any_of(fusion->fused_instructions().begin(),
fusion->fused_instructions().end(),
[](HloInstruction* inner) {
return inner->opcode() == HloOpcode::kBitcast &&
inner->operand(0)->opcode() != HloOpcode::kBroadcast;
})) {
continue;
}
// 1.3) Check that all the bitcast have the same shape pattern.
// Multiple bitcast pattern isn't supported/tested.
HloInstruction* bitcast = nullptr;
bool same_shape_pattern = true;
for (HloInstruction* fused_instr : fusion->fused_instructions()) {
if (fused_instr->opcode() == HloOpcode::kBitcast &&
fused_instr->shape().rank() <
fused_instr->operand(0)->shape().rank()) {
if (bitcast != nullptr &&
(!ShapeUtil::Equal(fused_instr->shape(), bitcast->shape()) ||
!ShapeUtil::Equal(bitcast->operand(0)->shape(),
fused_instr->operand(0)->shape()))) {
same_shape_pattern = false;
break;
}
bitcast = fused_instr;
}
}
if (bitcast == nullptr || !same_shape_pattern) {
VLOG(2) << "NOT SUPPORTED: Multiple rank-reducing bitcast pattern.";
continue;
}
// 2) Now that we have found a fusion that we want to modify,
// create the new fusion. We do so by:
// a) Cloning the old fusion.
// b) Recursively walk the graph from the root and lift the
// bitcast up across one instruction at a time.
std::unique_ptr<HloInstruction> cloned_fusion =
fusion->Clone("bitcast");
// The following stack and set always contain the same data.
// The stack is used for the order of traversal.
// The set is used only as an optimization to search in the set.
std::vector<HloInstruction*> stack(
{cloned_fusion->fused_expression_root()});
absl::flat_hash_set<HloInstruction*> set(
{cloned_fusion->fused_expression_root()});
bool clone_changed = false;
while (!stack.empty()) {
HloInstruction* i = stack.back();
stack.pop_back();
set.erase(i);
if (i->opcode() == HloOpcode::kTuple) {
stack.insert(stack.end(), i->operands().begin(),
i->operands().end());
set.insert(i->operands().begin(),
i->operands().end());
continue;
} else if (i->opcode() == HloOpcode::kParameter &&
absl::c_all_of(i->users(), [](HloInstruction* u) {
return u->opcode() == HloOpcode::kBitcast;
})) {
// Replace the parameter inside the fusion.
Shape new_shape = i->users()[0]->shape();
int64 parameter_number = i->parameter_number();
string name = i->name();
auto n = HloInstruction::CreateParameter(parameter_number,
new_shape, name);
HloInstruction* new_parameter =
i->parent()->ReplaceParameter(parameter_number,
std::move(n));
// Remove the old inner bitcast.
auto old_users = new_parameter->users();
for (HloInstruction* param_user : old_users) {
DCHECK(param_user->opcode() == HloOpcode::kBitcast)
<< "Expected a bitcast";
TF_RETURN_IF_ERROR(param_user->parent()->ReplaceInstructionWithDifferentShape(
param_user, new_parameter));
}
// Replace the corresponding fusion operands with a new bitcast.
HloInstruction* old_outer_parameter =
cloned_fusion->mutable_operand(parameter_number);
HloInstruction* new_op =
old_outer_parameter->parent()->AddInstruction(
HloInstruction::CreateBitcast(new_shape,
old_outer_parameter));
TF_RETURN_IF_ERROR(cloned_fusion->ReplaceOperandWithDifferentShape(
parameter_number, new_op));
clone_changed = true;
changed = true;
} else if (i->opcode() == HloOpcode::kBroadcast) {
// For now, do nothing. Later we can merge the broadcast
// and the bitcast, but this doesn't bring benefit in my
// current case.
if (set.count(i->mutable_operand(0)) == 0) {
stack.push_back(i->mutable_operand(0));
set.insert(i->mutable_operand(0));
}
} else if (!i->users().empty() &&
absl::c_all_of(i->users(), [](HloInstruction* u) {
return u->opcode() == HloOpcode::kBitcast;
})) {
// All users are bitcast, so lift the bitcast.
Shape new_shape = i->users()[0]->shape();
std::vector<HloInstruction*> new_operands;
for (HloInstruction* opnd : i->operands()) {
Shape dtyped_new_shape = ShapeUtil::ChangeElementType(
new_shape, opnd->shape().element_type());
HloInstruction* new_opnd = opnd->parent()->AddInstruction(
HloInstruction::CreateBitcast(dtyped_new_shape, opnd));
new_operands.push_back(new_opnd);
// Handle the operand right before the inserted bitcast now.
if (set.count(opnd) == 0) {
stack.push_back(opnd);
set.insert(opnd);
}
}
Shape dtyped_new_shape = ShapeUtil::ChangeElementType(
new_shape, i->shape().element_type());
HloInstruction* cloned_i = i->parent()->AddInstruction(
i->CloneWithNewOperands(dtyped_new_shape, new_operands));
// Replace the old bitcasts with the new instruction to
// remove it.
// Copy the vector as it will be modified while we iterate on it.
const std::vector<HloInstruction*> users = i->users();
for (HloInstruction* user: users) {
TF_RETURN_IF_ERROR(i->parent()->ReplaceInstructionWithDifferentShape(
user, cloned_i));
}
clone_changed = true;
changed = true;
} else {
for(auto* opnd : i->operands()) {
if (set.count(opnd) == 0) {
stack.push_back(opnd);
set.insert(opnd);
}
}
}
} // while
DCHECK(clone_changed) << "We should have changed the fusion!";
if (clone_changed) {
// 3) Replace the old fusion with the new fusion.
TF_RETURN_IF_ERROR(fusion->parent()->ReplaceWithNewInstruction(
fusion, std::move(cloned_fusion)));
}
} // if fusion
}
}
XLA_VLOG_LINES(2, "FusionBitcastLift::Run(), after:\n" + module->ToString());
return changed;
}
} // namespace gpu
} // namespace xla
<commit_msg>Remove useless code line.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/fusion_bitcast_lift.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/core/platform/errors.h"
namespace xla {
namespace gpu {
// Returns true if all instructions are supported operations.
static bool AreInstructionSupported(HloComputation* comp) {
for (HloInstruction* instr : comp->instructions()) {
bool supported =
HloInstruction::IsOpElementwise(instr->opcode()) ||
instr->opcode() == HloOpcode::kConstant ||
// We only support reduction when they are at the root or when
// in a MOF, at the end. This should always be true for now,
// but if we implement reduction epilog fusion in the future,
// this optimization need to be updated. So disable it just for
// future safety.
(instr->opcode() == HloOpcode::kReduce &&
(comp->root_instruction() == instr ||
(instr->users().size() == 1 &&
instr->users()[0]->opcode() == HloOpcode::kTuple))) ||
instr->opcode() == HloOpcode::kTuple ||
instr->opcode() == HloOpcode::kParameter ||
(instr->opcode() == HloOpcode::kBitcast &&
instr->shape().rank() < instr->operand(0)->shape().rank()) ||
(instr->opcode() == HloOpcode::kBroadcast &&
(instr->dimensions().empty() || // scalar broadcasting
(instr->dimensions().size() == 1 && // row broadcasting
instr->dimensions()[0] == (instr->shape().rank() - 1))));
if (!supported) {
VLOG(2) << "NOT SUPPORTED: " << instr->ToString();
return false;
}
}
return true;
}
StatusOr<bool> FusionBitcastLift::Run(HloModule* module) {
XLA_VLOG_LINES(2, "FusionBitcastLift::Run(), before:\n" + module->ToString());
bool changed = false;
for (HloComputation* comp : module->MakeNonfusionComputations()) {
// Copy the instruction list as we modify the HloComputation.
std::vector<HloInstruction*> comp_instruction(comp->instructions().begin(),
comp->instructions().end());
for (HloInstruction* instr : comp_instruction) {
// 1) Is this a fusion that we want to modify.
if (auto* fusion = DynCast<HloFusionInstruction>(instr)) {
// 1.1) We only support kInput fusion and some operations.
if (fusion->fusion_kind() != HloInstruction::FusionKind::kInput ||
!AreInstructionSupported(
fusion->fused_instructions_computation())) {
continue;
}
// 1.2) Check if there is a bitcast that we lift. Currently
// we do not lift(merge) bitcast above(with) broadcast.
if (!std::any_of(fusion->fused_instructions().begin(),
fusion->fused_instructions().end(),
[](HloInstruction* inner) {
return inner->opcode() == HloOpcode::kBitcast &&
inner->operand(0)->opcode() != HloOpcode::kBroadcast;
})) {
continue;
}
// 1.3) Check that all the bitcast have the same shape pattern.
// Multiple bitcast pattern isn't supported/tested.
HloInstruction* bitcast = nullptr;
bool same_shape_pattern = true;
for (HloInstruction* fused_instr : fusion->fused_instructions()) {
if (fused_instr->opcode() == HloOpcode::kBitcast &&
fused_instr->shape().rank() <
fused_instr->operand(0)->shape().rank()) {
if (bitcast != nullptr &&
(!ShapeUtil::Equal(fused_instr->shape(), bitcast->shape()) ||
!ShapeUtil::Equal(bitcast->operand(0)->shape(),
fused_instr->operand(0)->shape()))) {
same_shape_pattern = false;
break;
}
bitcast = fused_instr;
}
}
if (bitcast == nullptr || !same_shape_pattern) {
VLOG(2) << "NOT SUPPORTED: Multiple rank-reducing bitcast pattern.";
continue;
}
// 2) Now that we have found a fusion that we want to modify,
// create the new fusion. We do so by:
// a) Cloning the old fusion.
// b) Recursively walk the graph from the root and lift the
// bitcast up across one instruction at a time.
std::unique_ptr<HloInstruction> cloned_fusion =
fusion->Clone("bitcast");
// The following stack and set always contain the same data.
// The stack is used for the order of traversal.
// The set is used only as an optimization to search in the set.
std::vector<HloInstruction*> stack(
{cloned_fusion->fused_expression_root()});
absl::flat_hash_set<HloInstruction*> set(
{cloned_fusion->fused_expression_root()});
bool clone_changed = false;
while (!stack.empty()) {
HloInstruction* i = stack.back();
stack.pop_back();
set.erase(i);
if (i->opcode() == HloOpcode::kTuple) {
stack.insert(stack.end(), i->operands().begin(),
i->operands().end());
set.insert(i->operands().begin(),
i->operands().end());
} else if (i->opcode() == HloOpcode::kParameter &&
absl::c_all_of(i->users(), [](HloInstruction* u) {
return u->opcode() == HloOpcode::kBitcast;
})) {
// Replace the parameter inside the fusion.
Shape new_shape = i->users()[0]->shape();
int64 parameter_number = i->parameter_number();
string name = i->name();
auto n = HloInstruction::CreateParameter(parameter_number,
new_shape, name);
HloInstruction* new_parameter =
i->parent()->ReplaceParameter(parameter_number,
std::move(n));
// Remove the old inner bitcast.
auto old_users = new_parameter->users();
for (HloInstruction* param_user : old_users) {
DCHECK(param_user->opcode() == HloOpcode::kBitcast)
<< "Expected a bitcast";
TF_RETURN_IF_ERROR(param_user->parent()->ReplaceInstructionWithDifferentShape(
param_user, new_parameter));
}
// Replace the corresponding fusion operands with a new bitcast.
HloInstruction* old_outer_parameter =
cloned_fusion->mutable_operand(parameter_number);
HloInstruction* new_op =
old_outer_parameter->parent()->AddInstruction(
HloInstruction::CreateBitcast(new_shape,
old_outer_parameter));
TF_RETURN_IF_ERROR(cloned_fusion->ReplaceOperandWithDifferentShape(
parameter_number, new_op));
clone_changed = true;
changed = true;
} else if (i->opcode() == HloOpcode::kBroadcast) {
// For now, do nothing. Later we can merge the broadcast
// and the bitcast, but this doesn't bring benefit in my
// current case.
if (set.count(i->mutable_operand(0)) == 0) {
stack.push_back(i->mutable_operand(0));
set.insert(i->mutable_operand(0));
}
} else if (!i->users().empty() &&
absl::c_all_of(i->users(), [](HloInstruction* u) {
return u->opcode() == HloOpcode::kBitcast;
})) {
// All users are bitcast, so lift the bitcast.
Shape new_shape = i->users()[0]->shape();
std::vector<HloInstruction*> new_operands;
for (HloInstruction* opnd : i->operands()) {
Shape dtyped_new_shape = ShapeUtil::ChangeElementType(
new_shape, opnd->shape().element_type());
HloInstruction* new_opnd = opnd->parent()->AddInstruction(
HloInstruction::CreateBitcast(dtyped_new_shape, opnd));
new_operands.push_back(new_opnd);
// Handle the operand right before the inserted bitcast now.
if (set.count(opnd) == 0) {
stack.push_back(opnd);
set.insert(opnd);
}
}
Shape dtyped_new_shape = ShapeUtil::ChangeElementType(
new_shape, i->shape().element_type());
HloInstruction* cloned_i = i->parent()->AddInstruction(
i->CloneWithNewOperands(dtyped_new_shape, new_operands));
// Replace the old bitcasts with the new instruction to
// remove it.
// Copy the vector as it will be modified while we iterate on it.
const std::vector<HloInstruction*> users = i->users();
for (HloInstruction* user: users) {
TF_RETURN_IF_ERROR(i->parent()->ReplaceInstructionWithDifferentShape(
user, cloned_i));
}
clone_changed = true;
changed = true;
} else {
for(auto* opnd : i->operands()) {
if (set.count(opnd) == 0) {
stack.push_back(opnd);
set.insert(opnd);
}
}
}
} // while
DCHECK(clone_changed) << "We should have changed the fusion!";
if (clone_changed) {
// 3) Replace the old fusion with the new fusion.
TF_RETURN_IF_ERROR(fusion->parent()->ReplaceWithNewInstruction(
fusion, std::move(cloned_fusion)));
}
} // if fusion
}
}
XLA_VLOG_LINES(2, "FusionBitcastLift::Run(), after:\n" + module->ToString());
return changed;
}
} // namespace gpu
} // namespace xla
<|endoftext|>
|
<commit_before>#include <botan/tls_server.h>
#include <botan/tls_client.h>
#include <botan/pkcs10.h>
#include <botan/x509self.h>
#include <botan/rsa.h>
#include <botan/x509_ca.h>
#include <botan/hex.h>
#include "validate.h"
#include <iostream>
#include <vector>
#include <memory>
using namespace Botan;
namespace {
class Credentials_Manager_Test : public Botan::Credentials_Manager
{
public:
Credentials_Manager_Test(const X509_Certificate& server_cert,
const X509_Certificate& ca_cert,
Private_Key* server_key) :
m_server_cert(server_cert),
m_ca_cert(ca_cert),
m_key(server_key)
{
}
std::vector<X509_Certificate>
trusted_certificate_authorities(const std::string&,
const std::string&) override
{
std::vector<X509_Certificate> certs;
certs.push_back(m_ca_cert);
return certs;
}
std::vector<X509_Certificate> cert_chain(
const std::vector<std::string>& cert_key_types,
const std::string& type,
const std::string&) override
{
std::vector<X509_Certificate> chain;
if(type == "tls-server")
{
bool have_match = false;
for(size_t i = 0; i != cert_key_types.size(); ++i)
if(cert_key_types[i] == m_key->algo_name())
have_match = true;
if(have_match)
{
chain.push_back(m_server_cert);
chain.push_back(m_ca_cert);
}
}
return chain;
}
void verify_certificate_chain(
const std::string& type,
const std::string& purported_hostname,
const std::vector<Botan::X509_Certificate>& cert_chain) override
{
try
{
Credentials_Manager::verify_certificate_chain(type,
purported_hostname,
cert_chain);
}
catch(std::exception& e)
{
std::cout << "Certificate verification failed - " << e.what() << " - but will ignore\n";
}
}
Private_Key* private_key_for(const X509_Certificate&,
const std::string&,
const std::string&) override
{
return m_key;
}
public:
X509_Certificate m_server_cert, m_ca_cert;
Private_Key* m_key;
};
Credentials_Manager* create_creds(RandomNumberGenerator& rng)
{
std::auto_ptr<Private_Key> ca_key(new RSA_PrivateKey(rng, 1024));
X509_Cert_Options ca_opts;
ca_opts.common_name = "Test CA";
ca_opts.country = "US";
ca_opts.CA_key(1);
X509_Certificate ca_cert =
X509::create_self_signed_cert(ca_opts,
*ca_key,
"SHA-256",
rng);
Private_Key* server_key = new RSA_PrivateKey(rng, 1024);
X509_Cert_Options server_opts;
server_opts.common_name = "localhost";
server_opts.country = "US";
PKCS10_Request req = X509::create_cert_req(server_opts,
*server_key,
"SHA-256",
rng);
X509_CA ca(ca_cert, *ca_key, "SHA-256");
auto now = std::chrono::system_clock::now();
X509_Time start_time(now);
typedef std::chrono::duration<int, std::ratio<31556926>> years;
X509_Time end_time(now + years(1));
X509_Certificate server_cert = ca.sign_request(req,
rng,
start_time,
end_time);
return new Credentials_Manager_Test(server_cert, ca_cert, server_key);
}
void test_handshake(RandomNumberGenerator& rng)
{
TLS::Policy default_policy;
std::auto_ptr<Credentials_Manager> creds(create_creds(rng));
TLS::Session_Manager_In_Memory server_sessions;
TLS::Session_Manager_In_Memory client_sessions;
std::vector<byte> c2s_q, s2c_q, c2s_data, s2c_data;
auto handshake_complete = [](const TLS::Session& session) -> bool
{
std::cout << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << "\n";
if(!session.session_id().empty())
std::cout << "Session ID " << hex_encode(session.session_id()) << "\n";
if(!session.session_ticket().empty())
std::cout << "Session ticket " << hex_encode(session.session_ticket()) << "\n";
return true;
};
auto save_server_data = [&](const byte buf[], size_t sz, TLS::Alert alert)
{
c2s_data.insert(c2s_data.end(), buf, buf+sz);
if(alert.is_valid())
std::cout << "Server recvd alert " << alert.type_string() << "\n";
};
auto save_client_data = [&](const byte buf[], size_t sz, TLS::Alert alert)
{
s2c_data.insert(s2c_data.end(), buf, buf+sz);
if(alert.is_valid())
std::cout << "Client recvd alert " << alert.type_string() << "\n";
};
TLS::Server server([&](const byte buf[], size_t sz)
{ s2c_q.insert(s2c_q.end(), buf, buf+sz); },
save_server_data,
handshake_complete,
server_sessions,
*creds,
default_policy,
rng);
TLS::Client client([&](const byte buf[], size_t sz)
{ c2s_q.insert(c2s_q.end(), buf, buf+sz); },
save_client_data,
handshake_complete,
client_sessions,
*creds,
default_policy,
rng);
while(true)
{
if(client.is_active())
client.send("1");
if(server.is_active())
server.send("2");
/*
* Use this as a temp value to hold the queues as otherwise they
* might end up appending more in response to messages during the
* handshake.
*/
std::vector<byte> input;
std::swap(c2s_q, input);
try
{
server.received_data(&input[0], input.size());
}
catch(std::exception& e)
{
std::cout << "Server error - " << e.what() << "\n";
break;
}
input.clear();
std::swap(s2c_q, input);
try
{
client.received_data(&input[0], input.size());
}
catch(std::exception& e)
{
std::cout << "Client error - " << e.what() << "\n";
break;
}
if(c2s_data.size())
{
if(c2s_data[0] != '1')
{
std::cout << "Error\n";
break;
}
}
if(s2c_data.size())
{
if(s2c_data[0] != '2')
{
std::cout << "Error\n";
break;
}
}
if(s2c_data.size() && c2s_data.size())
break;
}
}
}
size_t do_tls_tests(RandomNumberGenerator& rng)
{
size_t errors = 0;
std::cout << "TLS tests: ";
test_handshake(rng);
std::cout << std::endl;
return errors;
}
<commit_msg>Compile fix<commit_after>#include <botan/tls_server.h>
#include <botan/tls_client.h>
#include <botan/pkcs10.h>
#include <botan/x509self.h>
#include <botan/rsa.h>
#include <botan/x509_ca.h>
#include <botan/hex.h>
#include "validate.h"
#include <iostream>
#include <vector>
#include <memory>
using namespace Botan;
namespace {
class Credentials_Manager_Test : public Botan::Credentials_Manager
{
public:
Credentials_Manager_Test(const X509_Certificate& server_cert,
const X509_Certificate& ca_cert,
Private_Key* server_key) :
m_server_cert(server_cert),
m_ca_cert(ca_cert),
m_key(server_key)
{
m_stores.push_back(new Certificate_Store_In_Memory);
m_stores[0]->add_certificate(m_ca_cert);
}
std::vector<Certificate_Store*>
trusted_certificate_authorities(const std::string&,
const std::string&) override
{
return m_stores;
}
std::vector<X509_Certificate> cert_chain(
const std::vector<std::string>& cert_key_types,
const std::string& type,
const std::string&) override
{
std::vector<X509_Certificate> chain;
if(type == "tls-server")
{
bool have_match = false;
for(size_t i = 0; i != cert_key_types.size(); ++i)
if(cert_key_types[i] == m_key->algo_name())
have_match = true;
if(have_match)
{
chain.push_back(m_server_cert);
chain.push_back(m_ca_cert);
}
}
return chain;
}
void verify_certificate_chain(
const std::string& type,
const std::string& purported_hostname,
const std::vector<Botan::X509_Certificate>& cert_chain) override
{
try
{
Credentials_Manager::verify_certificate_chain(type,
purported_hostname,
cert_chain);
}
catch(std::exception& e)
{
std::cout << "Certificate verification failed - " << e.what() << " - but will ignore\n";
}
}
Private_Key* private_key_for(const X509_Certificate&,
const std::string&,
const std::string&) override
{
return m_key;
}
public:
X509_Certificate m_server_cert, m_ca_cert;
Private_Key* m_key;
std::vector<Certificate_Store*> m_stores;
};
Credentials_Manager* create_creds(RandomNumberGenerator& rng)
{
std::auto_ptr<Private_Key> ca_key(new RSA_PrivateKey(rng, 1024));
X509_Cert_Options ca_opts;
ca_opts.common_name = "Test CA";
ca_opts.country = "US";
ca_opts.CA_key(1);
X509_Certificate ca_cert =
X509::create_self_signed_cert(ca_opts,
*ca_key,
"SHA-256",
rng);
Private_Key* server_key = new RSA_PrivateKey(rng, 1024);
X509_Cert_Options server_opts;
server_opts.common_name = "localhost";
server_opts.country = "US";
PKCS10_Request req = X509::create_cert_req(server_opts,
*server_key,
"SHA-256",
rng);
X509_CA ca(ca_cert, *ca_key, "SHA-256");
auto now = std::chrono::system_clock::now();
X509_Time start_time(now);
typedef std::chrono::duration<int, std::ratio<31556926>> years;
X509_Time end_time(now + years(1));
X509_Certificate server_cert = ca.sign_request(req,
rng,
start_time,
end_time);
return new Credentials_Manager_Test(server_cert, ca_cert, server_key);
}
void test_handshake(RandomNumberGenerator& rng)
{
TLS::Policy default_policy;
std::auto_ptr<Credentials_Manager> creds(create_creds(rng));
TLS::Session_Manager_In_Memory server_sessions;
TLS::Session_Manager_In_Memory client_sessions;
std::vector<byte> c2s_q, s2c_q, c2s_data, s2c_data;
auto handshake_complete = [](const TLS::Session& session) -> bool
{
std::cout << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << "\n";
if(!session.session_id().empty())
std::cout << "Session ID " << hex_encode(session.session_id()) << "\n";
if(!session.session_ticket().empty())
std::cout << "Session ticket " << hex_encode(session.session_ticket()) << "\n";
return true;
};
auto save_server_data = [&](const byte buf[], size_t sz, TLS::Alert alert)
{
c2s_data.insert(c2s_data.end(), buf, buf+sz);
if(alert.is_valid())
std::cout << "Server recvd alert " << alert.type_string() << "\n";
};
auto save_client_data = [&](const byte buf[], size_t sz, TLS::Alert alert)
{
s2c_data.insert(s2c_data.end(), buf, buf+sz);
if(alert.is_valid())
std::cout << "Client recvd alert " << alert.type_string() << "\n";
};
TLS::Server server([&](const byte buf[], size_t sz)
{ s2c_q.insert(s2c_q.end(), buf, buf+sz); },
save_server_data,
handshake_complete,
server_sessions,
*creds,
default_policy,
rng);
TLS::Client client([&](const byte buf[], size_t sz)
{ c2s_q.insert(c2s_q.end(), buf, buf+sz); },
save_client_data,
handshake_complete,
client_sessions,
*creds,
default_policy,
rng);
while(true)
{
if(client.is_active())
client.send("1");
if(server.is_active())
server.send("2");
/*
* Use this as a temp value to hold the queues as otherwise they
* might end up appending more in response to messages during the
* handshake.
*/
std::vector<byte> input;
std::swap(c2s_q, input);
try
{
server.received_data(&input[0], input.size());
}
catch(std::exception& e)
{
std::cout << "Server error - " << e.what() << "\n";
break;
}
input.clear();
std::swap(s2c_q, input);
try
{
client.received_data(&input[0], input.size());
}
catch(std::exception& e)
{
std::cout << "Client error - " << e.what() << "\n";
break;
}
if(c2s_data.size())
{
if(c2s_data[0] != '1')
{
std::cout << "Error\n";
break;
}
}
if(s2c_data.size())
{
if(s2c_data[0] != '2')
{
std::cout << "Error\n";
break;
}
}
if(s2c_data.size() && c2s_data.size())
break;
}
}
}
size_t do_tls_tests(RandomNumberGenerator& rng)
{
size_t errors = 0;
std::cout << "TLS tests: ";
test_handshake(rng);
std::cout << std::endl;
return errors;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/media_file/interface/media_file.h"
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"
class MediaFileTest : public testing::Test {
protected:
void SetUp() {
// Use number 0 as the the identifier and pass to CreateMediaFile.
media_file_ = webrtc::MediaFile::CreateMediaFile(0);
ASSERT_TRUE(media_file_ != NULL);
}
void TearDown() {
webrtc::MediaFile::DestroyMediaFile(media_file_);
media_file_ = NULL;
}
webrtc::MediaFile* media_file_;
};
TEST_F(MediaFileTest, DISABLED_ON_ANDROID(StartPlayingAudioFileWithoutError)) {
// TODO(leozwang): Use hard coded filename here, we want to
// loop through all audio files in future
const std::string audio_file = webrtc::test::ProjectRootPath() +
"data/voice_engine/audio_tiny48.wav";
ASSERT_EQ(0, media_file_->StartPlayingAudioFile(
audio_file.c_str(),
0,
false,
webrtc::kFileFormatWavFile));
ASSERT_EQ(true, media_file_->IsPlaying());
webrtc::SleepMs(1);
ASSERT_EQ(0, media_file_->StopPlaying());
}
<commit_msg>Add unit test for MediaFile WAV file writing<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/media_file/interface/media_file.h"
#include "webrtc/system_wrappers/interface/compile_assert.h"
#include "webrtc/system_wrappers/interface/sleep.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"
class MediaFileTest : public testing::Test {
protected:
void SetUp() {
// Use number 0 as the the identifier and pass to CreateMediaFile.
media_file_ = webrtc::MediaFile::CreateMediaFile(0);
ASSERT_TRUE(media_file_ != NULL);
}
void TearDown() {
webrtc::MediaFile::DestroyMediaFile(media_file_);
media_file_ = NULL;
}
webrtc::MediaFile* media_file_;
};
TEST_F(MediaFileTest, DISABLED_ON_ANDROID(StartPlayingAudioFileWithoutError)) {
// TODO(leozwang): Use hard coded filename here, we want to
// loop through all audio files in future
const std::string audio_file = webrtc::test::ProjectRootPath() +
"data/voice_engine/audio_tiny48.wav";
ASSERT_EQ(0, media_file_->StartPlayingAudioFile(
audio_file.c_str(),
0,
false,
webrtc::kFileFormatWavFile));
ASSERT_EQ(true, media_file_->IsPlaying());
webrtc::SleepMs(1);
ASSERT_EQ(0, media_file_->StopPlaying());
}
TEST_F(MediaFileTest, WriteWavFile) {
// Write file.
static const int kHeaderSize = 44;
static const int kPayloadSize = 320;
webrtc::CodecInst codec = {0, "L16", 16000, kPayloadSize, 1};
std::string outfile = webrtc::test::OutputPath() + "wavtest.wav";
ASSERT_EQ(0,
media_file_->StartRecordingAudioFile(
outfile.c_str(), webrtc::kFileFormatWavFile, codec));
static const int8_t kFakeData[kPayloadSize] = {0};
ASSERT_EQ(0, media_file_->IncomingAudioData(kFakeData, kPayloadSize));
ASSERT_EQ(0, media_file_->StopRecording());
// Check the file we just wrote.
static const uint8_t kExpectedHeader[] = {
'R', 'I', 'F', 'F',
0x64, 0x1, 0, 0, // size of whole file - 8: 320 + 44 - 8
'W', 'A', 'V', 'E',
'f', 'm', 't', ' ',
0x10, 0, 0, 0, // size of fmt block - 8: 24 - 8
0x1, 0, // format: PCM (1)
0x1, 0, // channels: 1
0x80, 0x3e, 0, 0, // sample rate: 16000
0, 0x7d, 0, 0, // byte rate: 2 * 16000
0x2, 0, // block align: NumChannels * BytesPerSample
0x10, 0, // bits per sample: 2 * 8
'd', 'a', 't', 'a',
0x40, 0x1, 0, 0, // size of payload: 320
};
COMPILE_ASSERT(sizeof(kExpectedHeader) == kHeaderSize, header_size);
EXPECT_EQ(size_t(kHeaderSize + kPayloadSize),
webrtc::test::GetFileSize(outfile));
FILE* f = fopen(outfile.c_str(), "rb");
ASSERT_TRUE(f);
uint8_t header[kHeaderSize];
ASSERT_EQ(1u, fread(header, kHeaderSize, 1, f));
EXPECT_EQ(0, memcmp(kExpectedHeader, header, kHeaderSize));
uint8_t payload[kPayloadSize];
ASSERT_EQ(1u, fread(payload, kPayloadSize, 1, f));
EXPECT_EQ(0, memcmp(kFakeData, payload, kPayloadSize));
EXPECT_EQ(0, fclose(f));
}
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool check_label(bool &active, std::string run_from, std::string run_to, std::string label)
{
if (label == run_from)
active = true;
if (label == run_to)
active = false;
return active;
}
struct SynthXilinxPass : public Pass {
SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-series and 6-series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module (default='top')\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
log("\n");
log(" begin:\n");
log(" hierarchy -check -top <top>\n");
log("\n");
log(" coarse:\n");
log(" synth -run coarse\n");
log("\n");
log(" bram:\n");
log(" memory_bram -rules +/xilinx/brams.txt\n");
log(" techmap -map +/xilinx/brams.v\n");
log("\n");
log(" fine:\n");
log(" synth -run fine\n");
log("\n");
log(" map_luts:\n");
log(" abc -lut 6:8\n");
log(" clean\n");
log("\n");
log(" map_cells:\n");
log(" techmap -map +/xilinx/cells.v\n");
log(" clean\n");
log("\n");
log(" edif:\n");
log(" write_edif synth.edif\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
std::string top_module = "top";
std::string arch_name = "spartan6";
std::string edif_file;
std::string run_from, run_to;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_module = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This comannd only operates on fully selected designs!\n");
bool active = run_from.empty();
log_header("Executing SYNTH_XILINX pass.\n");
log_push();
if (check_label(active, run_from, run_to, "begin"))
{
Pass::call(design, stringf("hierarchy -check -top %s", top_module.c_str()));
}
if (check_label(active, run_from, run_to, "coarse"))
{
Pass::call(design, "synth -run coarse");
}
if (check_label(active, run_from, run_to, "bram"))
{
Pass::call(design, "memory_bram -rules +/xilinx/brams.txt");
Pass::call(design, "techmap -map +/xilinx/brams.v");
}
if (check_label(active, run_from, run_to, "fine"))
{
Pass::call(design, "synth -run fine");
}
if (check_label(active, run_from, run_to, "map_luts"))
{
Pass::call(design, "abc -lut 6:8");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "map_cells"))
{
Pass::call(design, "techmap -map +/xilinx/cells.v");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "edif"))
{
if (!edif_file.empty())
Pass::call(design, stringf("write_edif %s", edif_file.c_str()));
}
log_pop();
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
<commit_msg>Added dff2dffe to synth_xilinx<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool check_label(bool &active, std::string run_from, std::string run_to, std::string label)
{
if (label == run_from)
active = true;
if (label == run_to)
active = false;
return active;
}
struct SynthXilinxPass : public Pass {
SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-series and 6-series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module (default='top')\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
log("\n");
log(" begin:\n");
log(" hierarchy -check -top <top>\n");
log("\n");
log(" coarse:\n");
log(" synth -run coarse\n");
log(" dff2dffe\n");
log("\n");
log(" bram:\n");
log(" memory_bram -rules +/xilinx/brams.txt\n");
log(" techmap -map +/xilinx/brams.v\n");
log("\n");
log(" fine:\n");
log(" synth -run fine\n");
log("\n");
log(" map_luts:\n");
log(" abc -lut 6:8\n");
log(" clean\n");
log("\n");
log(" map_cells:\n");
log(" techmap -map +/xilinx/cells.v\n");
log(" clean\n");
log("\n");
log(" edif:\n");
log(" write_edif synth.edif\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
std::string top_module = "top";
std::string arch_name = "spartan6";
std::string edif_file;
std::string run_from, run_to;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_module = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This comannd only operates on fully selected designs!\n");
bool active = run_from.empty();
log_header("Executing SYNTH_XILINX pass.\n");
log_push();
if (check_label(active, run_from, run_to, "begin"))
{
Pass::call(design, stringf("hierarchy -check -top %s", top_module.c_str()));
}
if (check_label(active, run_from, run_to, "coarse"))
{
Pass::call(design, "synth -run coarse");
Pass::call(design, "dff2dffe");
}
if (check_label(active, run_from, run_to, "bram"))
{
Pass::call(design, "memory_bram -rules +/xilinx/brams.txt");
Pass::call(design, "techmap -map +/xilinx/brams.v");
}
if (check_label(active, run_from, run_to, "fine"))
{
Pass::call(design, "synth -run fine");
}
if (check_label(active, run_from, run_to, "map_luts"))
{
Pass::call(design, "abc -lut 6:8");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "map_cells"))
{
Pass::call(design, "techmap -map +/xilinx/cells.v");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "edif"))
{
if (!edif_file.empty())
Pass::call(design, stringf("write_edif %s", edif_file.c_str()));
}
log_pop();
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SynthXilinxPass : public ScriptPass
{
SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -arch {xcup|xcu|xc7|xc6s}\n");
log(" run synthesis for the specified Xilinx architecture\n");
log(" default: xc7\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nocarry\n");
log(" disable inference of carry chains\n");
log("\n");
log(" -nobram\n");
log(" disable inference of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable inference of distributed rams\n");
log("\n");
log(" -nosrl\n");
log(" disable inference of shift registers\n");
log("\n");
log(" -nomux\n");
log(" disable inference of wide multiplexers\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log(" -abc9\n");
log(" use abc9 instead of abc\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
std::string top_opt, edif_file, blif_file, abc, arch;
bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
edif_file.clear();
blif_file.clear();
abc = "abc";
flatten = false;
retime = false;
vpr = false;
nocarry = false;
nobram = false;
nodram = false;
nosrl = false;
nomux = false;
arch = "xc7";
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-arch" && argidx+1 < args.size()) {
arch = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nocarry") {
nocarry = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
if (args[argidx] == "-nosrl") {
nosrl = true;
continue;
}
if (args[argidx] == "-nomux") {
nomux = true;
continue;
}
if (args[argidx] == "-abc9") {
abc = "abc9";
continue;
}
break;
}
extra_args(args, argidx, design);
if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (vpr)
run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
else
run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v");
run("read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram || help_mode)
run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");
run(stringf("hierarchy -check %s", top_opt.c_str()));
}
if (check_label("flatten", "(with '-flatten' only)")) {
if (flatten || help_mode) {
run("proc");
run("flatten");
}
}
if (check_label("coarse")) {
run("synth -run coarse");
// shregmap -tech xilinx can cope with $shiftx and $mux
// cells for identifying variable-length shift registers,
// so attempt to convert $pmux-es to the former
// Also: wide multiplexer inference benefits from this too
if (!(nosrl && nomux) || help_mode)
run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')");
// Run a number of peephole optimisations, including one
// that optimises $mul cells driving $shiftx's B input
// and that aids wide mux analysis
run("peepopt");
}
if (check_label("bram", "(skip if '-nobram')")) {
if (!nobram || help_mode) {
run("memory_bram -rules +/xilinx/brams.txt");
run("techmap -map +/xilinx/brams_map.v");
}
}
if (check_label("dram", "(skip if '-nodram')")) {
if (!nodram || help_mode) {
run("memory_bram -rules +/xilinx/drams.txt");
run("techmap -map +/xilinx/drams_map.v");
}
}
if (check_label("fine")) {
run("opt -fast -full");
run("memory_map");
run("dffsr2dff");
run("dff2dffe");
run("opt -full");
if (!nosrl || help_mode) {
// shregmap operates on bit-level flops, not word-level,
// so break those down here
run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
// shregmap to infer variable length shift regs
run("shregmap -tech xilinx_dynamic -minlen 3", "(skip if '-nosrl')");
}
std::string techmap_files = " -map +/techmap.v";
if (help_mode)
techmap_files += " [-map +/xilinx/mux_map.v]";
else if (!nomux)
techmap_files += " -map +/xilinx/mux_map.v";
if (help_mode)
techmap_files += " [-map +/xilinx/arith_map.v]";
else if (!nocarry) {
techmap_files += " -map +/xilinx/arith_map.v";
if (vpr)
techmap_files += " -D _EXPLICIT_CARRY";
else if (abc == "abc9")
techmap_files += " -D _CLB_CARRY";
}
run("techmap " + techmap_files);
run("opt -fast");
}
if (check_label("map_cells")) {
run("techmap -map +/techmap.v -map +/xilinx/cells_map.v");
run("clean");
}
if (check_label("map_luts")) {
if (abc == "abc9")
run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : ""));
else if (help_mode)
run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
else
run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
run("clean");
// This shregmap call infers fixed length shift registers after abc
// has performed any necessary retiming
if (!nosrl || help_mode)
run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v");
run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
run("clean");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat -tech xilinx");
run("check -noinit");
}
if (check_label("edif")) {
if (!edif_file.empty() || help_mode)
run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label("blif")) {
if (!blif_file.empty() || help_mode)
run(stringf("write_blif %s", edif_file.c_str()));
}
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
<commit_msg>Revert "Move ff_map back after ABC for shregmap"<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct SynthXilinxPass : public ScriptPass
{
SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -arch {xcup|xcu|xc7|xc6s}\n");
log(" run synthesis for the specified Xilinx architecture\n");
log(" default: xc7\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nocarry\n");
log(" disable inference of carry chains\n");
log("\n");
log(" -nobram\n");
log(" disable inference of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable inference of distributed rams\n");
log("\n");
log(" -nosrl\n");
log(" disable inference of shift registers\n");
log("\n");
log(" -nomux\n");
log(" disable inference of wide multiplexers\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log(" -abc9\n");
log(" use abc9 instead of abc\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
help_script();
log("\n");
}
std::string top_opt, edif_file, blif_file, abc, arch;
bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux;
void clear_flags() YS_OVERRIDE
{
top_opt = "-auto-top";
edif_file.clear();
blif_file.clear();
abc = "abc";
flatten = false;
retime = false;
vpr = false;
nocarry = false;
nobram = false;
nodram = false;
nosrl = false;
nomux = false;
arch = "xc7";
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-arch" && argidx+1 < args.size()) {
arch = args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nocarry") {
nocarry = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
if (args[argidx] == "-nosrl") {
nosrl = true;
continue;
}
if (args[argidx] == "-nomux") {
nomux = true;
continue;
}
if (args[argidx] == "-abc9") {
abc = "abc9";
continue;
}
break;
}
extra_args(args, argidx, design);
if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("begin")) {
if (vpr)
run("read_verilog -lib -D _ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
else
run("read_verilog -lib -D _ABC +/xilinx/cells_sim.v");
run("read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram || help_mode)
run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");
run(stringf("hierarchy -check %s", top_opt.c_str()));
}
if (check_label("flatten", "(with '-flatten' only)")) {
if (flatten || help_mode) {
run("proc");
run("flatten");
}
}
if (check_label("coarse")) {
run("synth -run coarse");
// shregmap -tech xilinx can cope with $shiftx and $mux
// cells for identifying variable-length shift registers,
// so attempt to convert $pmux-es to the former
// Also: wide multiplexer inference benefits from this too
if (!(nosrl && nomux) || help_mode)
run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')");
// Run a number of peephole optimisations, including one
// that optimises $mul cells driving $shiftx's B input
// and that aids wide mux analysis
run("peepopt");
}
if (check_label("bram", "(skip if '-nobram')")) {
if (!nobram || help_mode) {
run("memory_bram -rules +/xilinx/brams.txt");
run("techmap -map +/xilinx/brams_map.v");
}
}
if (check_label("dram", "(skip if '-nodram')")) {
if (!nodram || help_mode) {
run("memory_bram -rules +/xilinx/drams.txt");
run("techmap -map +/xilinx/drams_map.v");
}
}
if (check_label("fine")) {
run("opt -fast -full");
run("memory_map");
run("dffsr2dff");
run("dff2dffe");
run("opt -full");
if (!nosrl || help_mode) {
// shregmap operates on bit-level flops, not word-level,
// so break those down here
run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
// shregmap to infer variable length shift regs
run("shregmap -tech xilinx_dynamic -minlen 3", "(skip if '-nosrl')");
}
std::string techmap_files = " -map +/techmap.v";
if (help_mode)
techmap_files += " [-map +/xilinx/mux_map.v]";
else if (!nomux)
techmap_files += " -map +/xilinx/mux_map.v";
if (help_mode)
techmap_files += " [-map +/xilinx/arith_map.v]";
else if (!nocarry) {
techmap_files += " -map +/xilinx/arith_map.v";
if (vpr)
techmap_files += " -D _EXPLICIT_CARRY";
else if (abc == "abc9")
techmap_files += " -D _CLB_CARRY";
}
run("techmap " + techmap_files);
run("opt -fast");
}
if (check_label("map_cells")) {
run("techmap -map +/techmap.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v ");
run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
run("clean");
}
if (check_label("map_luts")) {
if (abc == "abc9")
run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : ""));
else if (help_mode)
run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
else
run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
run("clean");
// This shregmap call infers fixed length shift registers after abc
// has performed any necessary retiming
if (!nosrl || help_mode)
run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v");
run("clean");
}
if (check_label("check")) {
run("hierarchy -check");
run("stat -tech xilinx");
run("check -noinit");
}
if (check_label("edif")) {
if (!edif_file.empty() || help_mode)
run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label("blif")) {
if (!blif_file.empty() || help_mode)
run(stringf("write_blif %s", edif_file.c_str()));
}
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include <Windows.h>
#include <iostream>
#include <string>
#define BUFFER_SIZE 512
using namespace std;
int main()
{
//
HANDLE hFatherWriteOver = NULL;
HANDLE hChildReadOver = NULL;
//ַ
string str;
//ǷʾûӽѶ
bool giveHint = false;
//ӽ
TCHAR* appName = TEXT("D:\\ϵͳ\\ʵ\\2\\OS_expe2_2_child\\Debug\\OS_expe2_2_child.exe");
//Ϣṹ
STARTUPINFO startupInfo;
//Ϣṹ
PROCESS_INFORMATION processInfo;
//ṹڴ0䣬ڳʼ
ZeroMemory(&startupInfo,sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
ZeroMemory(&processInfo,sizeof(processInfo));
//ӽ
BOOL result = CreateProcess(appName,NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo);
if (result == FALSE)
{
cout<<"ӽʧܣ"<<endl;
goto FATHER_PROCESS_END;
}
else
{
cout<<"ӽ̳ɹ"<<endl;
//رӽ߳̾
CloseHandle( processInfo.hThread );
//رӽ̾
CloseHandle( processInfo.hProcess );
}
//¼ɽ̼ͬ
//д¼
hFatherWriteOver = CreateEvent(NULL, //ȫԣ˾ܱ̳УĬϻһȫ
TRUE, //λʽΪֹλ
FALSE, //ʼΪź״̬
L"fatherWriteOver"); //¼
//ӽ̶¼
hChildReadOver = CreateEvent(NULL, //ȫԣ˾ܱ̳УĬϻһȫ
TRUE, //λʽΪֹλ
FALSE, //ʼΪź״̬
L"childReadOver"); //¼
//¼ʧ
if (NULL == hFatherWriteOver ||
NULL == hChildReadOver)
{
cout << "¼ʧܣ" << GetLastError() << endl;
goto FATHER_PROCESS_END;
}
do
{
//ʱַ
char temp[BUFFER_SIZE];
//ȴӽ̶ϣȴ¼5s
if (WaitForSingleObject(hChildReadOver, 5*1000) != WAIT_OBJECT_0)
goto FATHER_PROCESS_END;
//ӽ̶¼
if (!ResetEvent(hChildReadOver))
goto FATHER_PROCESS_END;
//һβʾûӽ̶
if(!giveHint)
{
cout<<"ַ"<<endl;
giveHint = true;
}
else
{
cout<<"ӽѶϣַ"<<endl;
}
//ȡ
gets(temp);
//ַstr
str.assign(temp);
//а
if(!OpenClipboard(NULL))
{
cout<<"аʧܣ"<<endl;
goto FATHER_PROCESS_END;
}
//ռа
EmptyClipboard();
//һȫڴ
HGLOBAL hClipboardData = GlobalAlloc(GHND,str.length()+1);
//ͨȫڴöȫڴ
char* pData = (char *)GlobalLock(hClipboardData);
//ʱַַȫڴ
strcpy(pData, temp);
//ȫڴ
GlobalUnlock(hClipboardData);
//ݼʽ
SetClipboardData(CF_TEXT, hClipboardData);
//ͷȫڴ
GlobalFree(hClipboardData);
//رռа
CloseClipboard();
//øд¼
if (!SetEvent(hFatherWriteOver))
goto FATHER_PROCESS_END;
} while(str != "END");
FATHER_PROCESS_END:
//ͷڴռ
if (NULL != hFatherWriteOver) CloseHandle(hFatherWriteOver);
if (NULL != hChildReadOver) CloseHandle(hChildReadOver);
return 0;
}
<commit_msg>Delete OS_expe2_2_father.cpp<commit_after><|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 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 <cmath>
#include <Core/Utils/Exception.h>
#include <gtest/gtest.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <iostream>
#include <sstream>
using namespace ::testing;
const static float epsilon = 0.2e-5;
TEST(GLMTests, CameraTransform)
{
glm::mat4 t(1.0);
float identityList[16] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
glm::mat4 identity = glm::make_mat4(identityList);
ASSERT_EQ(t, identity);
glm::vec3 lookAt = glm::vec3(2, 4.5, 7);
t = glm::translate(t, -lookAt);
float translateList[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -2, -4.5, -7, 1};
glm::mat4 translatedMat = glm::make_mat4(translateList);
ASSERT_EQ(t, translatedMat);
const static float theta = static_cast<float>(M_PI) * 0.25f;
auto rot = glm::rotate(glm::mat4(1.0f), theta, glm::vec3(0.f, 0.f, 1.f));
t = rot * t;
float rotList[16] = {std::cos(theta), std::sin(theta), 0, 0, -std::sin(theta), std::cos(theta), 0,
0, 0, 0, 1, 0, 1.7677669, -4.5961941, -7, 1};
glm::mat4 rotMat = glm::make_mat4(rotList);
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
ASSERT_NEAR(t[i][j], rotMat[i][j], epsilon);
float camDist = 0.7;
t[3][2] -= camDist;
float camDistList[16] = {std::cos(theta), std::sin(theta), 0, 0, -std::sin(theta), std::cos(theta), 0,
0, 0, 0, 1, 0, 1.7677669, -4.5961941, -7.7, 1};
glm::mat4 camDistMat = glm::make_mat4(camDistList);
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) ASSERT_NEAR(t[i][j], camDistMat[i][j], epsilon);
}
<commit_msg>Fix windows build<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 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 <algorithm>
#include <Core/Math/MiscMath.h>
#include <Core/Utils/Exception.h>
#include <gtest/gtest.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec3.hpp>
using namespace ::testing;
const static float epsilon = 0.2e-5f;
TEST(GLMTests, CameraTransform)
{
glm::mat4 t(1.0);
float identityList[16] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
glm::mat4 identity = glm::make_mat4(identityList);
ASSERT_EQ(t, identity);
glm::vec3 lookAt = glm::vec3(2, 4.5, 7);
t = glm::translate(t, -lookAt);
float translateList[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -2, -4.5, -7, 1};
glm::mat4 translatedMat = glm::make_mat4(translateList);
ASSERT_EQ(t, translatedMat);
const static float theta = static_cast<float>(M_PI) * 0.25f;
auto rot = glm::rotate(glm::mat4(1.0f), theta, glm::vec3(0.f, 0.f, 1.f));
t = rot * t;
float rotList[16] = {std::cos(theta), std::sin(theta), 0, 0, -std::sin(theta), std::cos(theta), 0,
0, 0, 0, 1, 0, 1.7677669, -4.5961941, -7, 1};
glm::mat4 rotMat = glm::make_mat4(rotList);
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
ASSERT_NEAR(t[i][j], rotMat[i][j], epsilon);
float camDist = 0.7;
t[3][2] -= camDist;
float camDistList[16] = {std::cos(theta), std::sin(theta), 0, 0, -std::sin(theta), std::cos(theta), 0,
0, 0, 0, 1, 0, 1.7677669, -4.5961941, -7.7, 1};
glm::mat4 camDistMat = glm::make_mat4(camDistList);
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) ASSERT_NEAR(t[i][j], camDistMat[i][j], epsilon);
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "parameters.hpp"
#include <autobahn/autobahn.hpp>
#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <tuple>
const std::string PREFIX("com.examples.calculator");
void calculator(autobahn::wamp_invocation invocation)
{
auto a = invocation->argument<uint64_t>(0);
auto b = invocation->argument<uint64_t>(1);
std::cerr << "Procedure " << invocation->uri() << "invoked: " << a << ", " << b << std::endl;
auto suffix = invocation->uri().substr(PREFIX.size());
if (suffix == ".add")
{
invocation->result(std::make_tuple(a + b));
}
else if (suffix == ".mul2")
{
invocation->result(std::make_tuple(a * b));
}
else
{
throw std::exception("procedure not found");
}
}
void on_topic(const autobahn::wamp_event& event)
{
std::cerr << "received event: " << event.uri() << " with argument " << event.argument<std::string>(0) << std::endl;
}
int main(int argc, char** argv)
{
std::cerr << "Boost: " << BOOST_VERSION << std::endl;
try {
auto parameters = get_parameters(argc, argv);
std::cerr << "Connecting to realm: " << parameters->realm() << std::endl;
boost::asio::io_service io;
auto transport = std::make_shared<autobahn::wamp_tcp_transport>(
io, parameters->rawsocket_endpoint(), true);
bool debug = parameters->debug();
auto session = std::make_shared<autobahn::wamp_session>(io, debug);
transport->attach(std::static_pointer_cast<autobahn::wamp_transport_handler>(session));
// Make sure the continuation futures we use do not run out of scope prematurely.
// Since we are only using one thread here this can cause the io service to block
// as a future generated by a continuation will block waiting for its promise to be
// fulfilled when it goes out of scope. This would prevent the session from receiving
// responses from the router.
boost::future<void> connect_future;
boost::future<void> start_future;
boost::future<void> join_future;
boost::future<void> provide_future;
boost::future<void> subscribe_future;
connect_future = transport->connect().then([&](boost::future<void> connected) {
try {
connected.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "transport connected" << std::endl;
start_future = session->start().then([&](boost::future<void> started) {
try {
started.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "session started" << std::endl;
join_future = session->join(parameters->realm()).then([&](boost::future<uint64_t> joined) {
try {
std::cerr << "joined realm: " << joined.get() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
provide_future = session->provide(PREFIX, &calculator, { { "match", msgpack::object("prefix") } }).then(
[&](boost::future<autobahn::wamp_registration> registration) {
try {
std::cerr << "registered procedure:" << registration.get().id() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
});
subscribe_future = session->subscribe("com.examples.subscriptions", &on_topic, autobahn::wamp_subscribe_options("prefix")).then([&](boost::future<autobahn::wamp_subscription> subscribed)
{
try {
std::cerr << "subscribed to topic: " << subscribed.get().id() << std::endl;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
});
});
});
});
std::cerr << "starting io service" << std::endl;
io.run();
std::cerr << "stopped io service" << std::endl;
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << std::endl;
return -1;
}
return 0;
}
<commit_msg>prefix provide compilation fix for std::exception<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "parameters.hpp"
#include <autobahn/autobahn.hpp>
#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <tuple>
const std::string PREFIX("com.examples.calculator");
void calculator(autobahn::wamp_invocation invocation)
{
auto a = invocation->argument<uint64_t>(0);
auto b = invocation->argument<uint64_t>(1);
std::cerr << "Procedure " << invocation->uri() << "invoked: " << a << ", " << b << std::endl;
auto suffix = invocation->uri().substr(PREFIX.size());
if (suffix == ".add")
{
invocation->result(std::make_tuple(a + b));
}
else if (suffix == ".mul2")
{
invocation->result(std::make_tuple(a * b));
}
else
{
std::string errorMessage = std::string("procedure not found ")+invocation->uri();
throw std::exception(errorMessage);
}
}
void on_topic(const autobahn::wamp_event& event)
{
std::cerr << "received event: " << event.uri() << " with argument " << event.argument<std::string>(0) << std::endl;
}
int main(int argc, char** argv)
{
std::cerr << "Boost: " << BOOST_VERSION << std::endl;
try {
auto parameters = get_parameters(argc, argv);
std::cerr << "Connecting to realm: " << parameters->realm() << std::endl;
boost::asio::io_service io;
auto transport = std::make_shared<autobahn::wamp_tcp_transport>(
io, parameters->rawsocket_endpoint(), true);
bool debug = parameters->debug();
auto session = std::make_shared<autobahn::wamp_session>(io, debug);
transport->attach(std::static_pointer_cast<autobahn::wamp_transport_handler>(session));
// Make sure the continuation futures we use do not run out of scope prematurely.
// Since we are only using one thread here this can cause the io service to block
// as a future generated by a continuation will block waiting for its promise to be
// fulfilled when it goes out of scope. This would prevent the session from receiving
// responses from the router.
boost::future<void> connect_future;
boost::future<void> start_future;
boost::future<void> join_future;
boost::future<void> provide_future;
boost::future<void> subscribe_future;
connect_future = transport->connect().then([&](boost::future<void> connected) {
try {
connected.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "transport connected" << std::endl;
start_future = session->start().then([&](boost::future<void> started) {
try {
started.get();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
std::cerr << "session started" << std::endl;
join_future = session->join(parameters->realm()).then([&](boost::future<uint64_t> joined) {
try {
std::cerr << "joined realm: " << joined.get() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
provide_future = session->provide(PREFIX, &calculator, { { "match", msgpack::object("prefix") } }).then(
[&](boost::future<autobahn::wamp_registration> registration) {
try {
std::cerr << "registered procedure:" << registration.get().id() << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
});
subscribe_future = session->subscribe("com.examples.subscriptions", &on_topic, autobahn::wamp_subscribe_options("prefix")).then([&](boost::future<autobahn::wamp_subscription> subscribed)
{
try {
std::cerr << "subscribed to topic: " << subscribed.get().id() << std::endl;
}
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
io.stop();
return;
}
});
});
});
});
std::cerr << "starting io service" << std::endl;
io.run();
std::cerr << "stopped io service" << std::endl;
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 AUV-IITK
#include <cv.h>
#include <highgui.h>
#include <ros/ros.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <fstream>
#include <vector>
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <dynamic_reconfigure/server.h>
#include <task_line/lineConfig.h>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
int percentage = 5, x = -1; // used for how much percent of the screen should be orange
// before deciding that a line is below. Used in
// dynamic_reconfig
// callback for change the percent of orange before saying there is a line below
bool IP = false;
bool flag = false;
bool video = false;
cv::Mat red_hue_image;
cv::Mat frame;
cv::Mat newframe;
int count = 0;
void callback(task_line::lineConfig &config, uint32_t level)
{
percentage = config.orange_param;
ROS_INFO("%s Reconfigure Request : New parameters :%d", ros::this_node::getName().c_str(), percentage);
}
void lineDetectedListener(std_msgs::Bool msg)
{
IP = msg.data;
}
void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
if (x == 32)
return;
try
{
count++;
newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
cvNamedWindow("newframe", CV_WINDOW_NORMAL);
///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
newframe.copyTo(frame);
cv::imshow("newframe", newframe);
////////////////////////// FATAL ///////////////////////////////////////////////////
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
}
}
// callback for off switch.
int detect(cv::Mat image)
{
cv::Size size(640, 480); // the dst image size,e.g.100x100
cv::Mat resizeimage; // dst image
cv::Mat bgr_image;
resize(image, resizeimage, size); // resize image
cv::waitKey(20);
// detect red color here
medianBlur(resizeimage, bgr_image, 3); // blur to reduce noise
// Convert input image to HSV
cv::Mat hsv_image;
cvtColor(bgr_image, hsv_image, cv::COLOR_BGR2HSV);
// keep only red color
inRange(hsv_image, cv::Scalar(0, 100, 100), cv::Scalar(179, 255, 255), red_hue_image);
GaussianBlur(red_hue_image, red_hue_image, cv::Size(9, 9), 2, 2); // gaussian blur to remove false positives
int nonzero = countNonZero(red_hue_image);
int nonzeropercentage = nonzero / 3072;
if (nonzero > (3072 * percentage)) // return 1 if a major portion of image
// has red color, Note : here the size of
// image is 640X480 = 307200.
return 1;
return 0;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "line_detection");
ros::NodeHandle n;
ros::Publisher robot_pub = n.advertise<std_msgs::Bool>("/varun/ip/line_detection", 1000);
ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_detection_switch", 1000, &lineDetectedListener);
image_transport::ImageTransport it(n);
image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/front_camera/image_raw", 1, imageCallback);
ros::Rate loop_rate(12); // this rate should be same as the rate of camera
// input. and in the case of other sensors , this
// rate should be same as there rate of data
// generation
n.getParam("line_detection/percentage", percentage);
dynamic_reconfigure::Server<task_line::lineConfig> server;
dynamic_reconfigure::Server<task_line::lineConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);
server.setCallback(f);
if (argc == 2)
{
cvNamedWindow("F3", CV_WINDOW_NORMAL);
cvCreateTrackbar("percentage", "red_hue_image", &percentage, 100, NULL);
}
while (ros::ok())
{
if (!frame.data) // Check for invalid input
{
ROS_INFO("%s: Could not open or find the image\n", ros::this_node::getName().c_str());
ros::spinOnce();
continue;
// TODO(shikherverma) : for now I am resetting the video but later we need to handle this
// camera not available error properly
}
if (!IP)
{
int alert = detect(frame);
cv::imshow("red_hue_image", red_hue_image);
if (alert == 1)
{
std_msgs::Bool msg;
msg.data = true;
robot_pub.publish(msg);
ROS_INFO("%s: found line", ros::this_node::getName().c_str());
}
else if (alert == 0)
{
std_msgs::Bool msg;
msg.data = false;
robot_pub.publish(msg);
ROS_INFO("%s: no line", ros::this_node::getName().c_str());
}
else
{
return 0;
}
ros::spinOnce();
loop_rate.sleep();
if ((cvWaitKey(10) & 255) == 32)
{
if (x == 32)
x = -1;
else
x = 32;
}
if (x == 32)
ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
ros::spinOnce();
}
else
{
ROS_INFO("%s: waiting\n", ros::this_node::getName().c_str());
if ((cvWaitKey(10) & 255) == 32)
{
if (x == 32)
x = -1;
else
x = 32;
}
if (x == 32)
ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
ros::spinOnce();
}
}
return 0;
}
<commit_msg>changed the camera<commit_after>// Copyright 2016 AUV-IITK
#include <cv.h>
#include <highgui.h>
#include <ros/ros.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <fstream>
#include <vector>
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <dynamic_reconfigure/server.h>
#include <task_line/lineConfig.h>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
int percentage = 5, x = -1; // used for how much percent of the screen should be orange
// before deciding that a line is below. Used in
// dynamic_reconfig
// callback for change the percent of orange before saying there is a line below
bool IP = false;
bool flag = false;
bool video = false;
cv::Mat red_hue_image;
cv::Mat frame;
cv::Mat newframe;
int count = 0;
void callback(task_line::lineConfig &config, uint32_t level)
{
percentage = config.orange_param;
ROS_INFO("%s Reconfigure Request : New parameters :%d", ros::this_node::getName().c_str(), percentage);
}
void lineDetectedListener(std_msgs::Bool msg)
{
IP = msg.data;
}
void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
if (x == 32)
return;
try
{
count++;
newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
cvNamedWindow("newframe", CV_WINDOW_NORMAL);
///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
newframe.copyTo(frame);
cv::imshow("newframe", newframe);
////////////////////////// FATAL ///////////////////////////////////////////////////
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
}
}
// callback for off switch.
int detect(cv::Mat image)
{
cv::Size size(640, 480); // the dst image size,e.g.100x100
cv::Mat resizeimage; // dst image
cv::Mat bgr_image;
resize(image, resizeimage, size); // resize image
cv::waitKey(20);
// detect red color here
medianBlur(resizeimage, bgr_image, 3); // blur to reduce noise
// Convert input image to HSV
cv::Mat hsv_image;
cvtColor(bgr_image, hsv_image, cv::COLOR_BGR2HSV);
// keep only red color
inRange(hsv_image, cv::Scalar(0, 100, 100), cv::Scalar(179, 255, 255), red_hue_image);
GaussianBlur(red_hue_image, red_hue_image, cv::Size(9, 9), 2, 2); // gaussian blur to remove false positives
int nonzero = countNonZero(red_hue_image);
int nonzeropercentage = nonzero / 3072;
if (nonzero > (3072 * percentage)) // return 1 if a major portion of image
// has red color, Note : here the size of
// image is 640X480 = 307200.
return 1;
return 0;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "line_detection");
ros::NodeHandle n;
ros::Publisher robot_pub = n.advertise<std_msgs::Bool>("/varun/ip/line_detection", 1000);
ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_detection_switch", 1000, &lineDetectedListener);
image_transport::ImageTransport it(n);
image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/bottom_camera/image_raw", 1, imageCallback);
ros::Rate loop_rate(12); // this rate should be same as the rate of camera
// input. and in the case of other sensors , this
// rate should be same as there rate of data
// generation
n.getParam("line_detection/percentage", percentage);
dynamic_reconfigure::Server<task_line::lineConfig> server;
dynamic_reconfigure::Server<task_line::lineConfig>::CallbackType f;
f = boost::bind(&callback, _1, _2);
server.setCallback(f);
if (argc == 2)
{
cvNamedWindow("F3", CV_WINDOW_NORMAL);
cvCreateTrackbar("percentage", "red_hue_image", &percentage, 100, NULL);
}
while (ros::ok())
{
if (!frame.data) // Check for invalid input
{
ROS_INFO("%s: Could not open or find the image\n", ros::this_node::getName().c_str());
ros::spinOnce();
continue;
// TODO(shikherverma) : for now I am resetting the video but later we need to handle this
// camera not available error properly
}
if (!IP)
{
int alert = detect(frame);
cv::imshow("red_hue_image", red_hue_image);
if (alert == 1)
{
std_msgs::Bool msg;
msg.data = true;
robot_pub.publish(msg);
ROS_INFO("%s: found line", ros::this_node::getName().c_str());
}
else if (alert == 0)
{
std_msgs::Bool msg;
msg.data = false;
robot_pub.publish(msg);
ROS_INFO("%s: no line", ros::this_node::getName().c_str());
}
else
{
return 0;
}
ros::spinOnce();
loop_rate.sleep();
if ((cvWaitKey(10) & 255) == 32)
{
if (x == 32)
x = -1;
else
x = 32;
}
if (x == 32)
ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
ros::spinOnce();
}
else
{
ROS_INFO("%s: waiting\n", ros::this_node::getName().c_str());
if ((cvWaitKey(10) & 255) == 32)
{
if (x == 32)
x = -1;
else
x = 32;
}
if (x == 32)
ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
ros::spinOnce();
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* The goal of these tests is to verify the behavior of all blob commands given
* the current state is verificationStarted. This state is achieved as a out of
* verificationPending.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
/*
* There are the following calls (parameters may vary):
* canHandleBlob(blob)
* getBlobIds
* deleteBlob(blob)
* stat(blob)
* stat(session)
* open(blob)
* close(session)
* writemeta(session)
* write(session)
* read(session)
* commit(session)
*
* Testing canHandleBlob is uninteresting in this state. Getting the BlobIDs
* will inform what canHandleBlob will return.
*/
class FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest
{
};
/*
* canHandleBlob(blob)
* getBlobIds()
*/
TEST_F(FirmwareHandlerVerificationStartedTest, GetBlobIdsReturnsExpectedList)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::string> expectedList = {
activeImageBlobId, staticLayoutBlobId, hashBlobId, verifyBlobId};
EXPECT_THAT(handler->getBlobIds(), UnorderedElementsAreArray(expectedList));
for (const auto& blob : expectedList)
{
EXPECT_TRUE(handler->canHandleBlob(blob));
}
}
/*
* stat(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::running));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committing;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::running));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsOther)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::unknown));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committing;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::unknown));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)
{
/* If the returned state from the verification handler is failed, it sets
* commit_error and transitions to verificationCompleted.
*/
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::failed));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::commit_error;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::failed));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)
{
/* If the returned state from the verification handler is success, it sets
* committed and transitions to verificationCompleted.
*/
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::success));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committed;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::success));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
/* TODO: Once verificationCompleted is the state, canHandleBlob should accept
* updateBlobId.
*/
/*
* deleteBlob(blob)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, DeleteBlobReturnsFalse)
{
/* Try deleting all blobs, it doesn't really matter which though because you
* cannot close out an open session, therefore you must fail to delete
* anything unless everything is closed.
*/
getToVerificationStarted(staticLayoutBlobId);
auto blobs = handler->getBlobIds();
for (const auto& b : blobs)
{
EXPECT_FALSE(handler->deleteBlob(b));
}
}
/*
* stat(blob)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)
{
getToVerificationStarted(hashBlobId);
ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)
{
/* the verifyBlobId is available starting at verificationPending. */
getToVerificationStarted(staticLayoutBlobId);
ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)
{
getToVerificationStarted(staticLayoutBlobId);
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
ASSERT_TRUE(handler->canHandleBlob(blob));
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/*
* writemeta(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
WriteMetaOnVerifySessionReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->writeMeta(session, 0, bytes));
}
/*
* write(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
WriteOnVerifySessionReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->write(session, 0, bytes));
}
/*
* open(blob) - there is nothing you can open, this state has an open file.
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
AttemptToOpenImageFileReturnsFailure)
{
/* Attempt to open a file one normally can open, however, as there is
* already a file open, this will fail.
*/
getToVerificationStarted(staticLayoutBlobId);
auto blobsToOpen = handler->getBlobIds();
for (const auto& blob : blobsToOpen)
{
EXPECT_FALSE(handler->open(session + 1, flags, blob));
}
}
/*
* read(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, ReadOfVerifyBlobReturnsEmpty)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_THAT(handler->read(session, 0, 1), IsEmpty());
}
/*
* commit(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
CommitOnVerifyDuringVerificationHasNoImpact)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_TRUE(handler->commit(session, {}));
expectedState(FirmwareBlobHandler::UpdateState::verificationStarted);
}
/*
* close(session) - close while state if verificationStarted without calling
* stat first will abort.
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
CloseOnVerifyDuringVerificationAbortsProcess)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, abort()).Times(1);
EXPECT_TRUE(handler->close(session));
std::vector<std::string> expectedBlobs = {staticLayoutBlobId, hashBlobId};
EXPECT_THAT(handler->getBlobIds(),
UnorderedElementsAreArray(expectedBlobs));
expectedState(FirmwareBlobHandler::UpdateState::notYetStarted);
}
} // namespace
} // namespace ipmi_flash
<commit_msg>test: verificationStarted: drop incorrect todo<commit_after>/* The goal of these tests is to verify the behavior of all blob commands given
* the current state is verificationStarted. This state is achieved as a out of
* verificationPending.
*/
#include "firmware_handler.hpp"
#include "firmware_unittest.hpp"
#include "status.hpp"
#include "util.hpp"
#include <cstdint>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace ipmi_flash
{
namespace
{
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::UnorderedElementsAreArray;
/*
* There are the following calls (parameters may vary):
* canHandleBlob(blob)
* getBlobIds
* deleteBlob(blob)
* stat(blob)
* stat(session)
* open(blob)
* close(session)
* writemeta(session)
* write(session)
* read(session)
* commit(session)
*
* Testing canHandleBlob is uninteresting in this state. Getting the BlobIDs
* will inform what canHandleBlob will return.
*/
class FirmwareHandlerVerificationStartedTest : public IpmiOnlyFirmwareStaticTest
{
};
/*
* canHandleBlob(blob)
* getBlobIds()
*/
TEST_F(FirmwareHandlerVerificationStartedTest, GetBlobIdsReturnsExpectedList)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::string> expectedList = {
activeImageBlobId, staticLayoutBlobId, hashBlobId, verifyBlobId};
EXPECT_THAT(handler->getBlobIds(), UnorderedElementsAreArray(expectedList));
for (const auto& blob : expectedList)
{
EXPECT_TRUE(handler->canHandleBlob(blob));
}
}
/*
* stat(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsRunning)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::running));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committing;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::running));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitChecksStateAndReturnsOther)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::unknown));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committing;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::unknown));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsFailed)
{
/* If the returned state from the verification handler is failed, it sets
* commit_error and transitions to verificationCompleted.
*/
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::failed));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::commit_error;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::failed));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
TEST_F(FirmwareHandlerVerificationStartedTest,
StatOnVerifyBlobIdAfterCommitCheckStateAndReturnsSuccess)
{
/* If the returned state from the verification handler is success, it sets
* committed and transitions to verificationCompleted.
*/
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, status())
.WillOnce(Return(ActionStatus::success));
blobs::BlobMeta meta, expectedMeta = {};
expectedMeta.size = 0;
expectedMeta.blobState = flags | blobs::StateFlags::committed;
expectedMeta.metadata.push_back(
static_cast<std::uint8_t>(ActionStatus::success));
EXPECT_TRUE(handler->stat(session, &meta));
EXPECT_EQ(expectedMeta, meta);
expectedState(FirmwareBlobHandler::UpdateState::verificationCompleted);
}
/*
* deleteBlob(blob)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, DeleteBlobReturnsFalse)
{
/* Try deleting all blobs, it doesn't really matter which though because you
* cannot close out an open session, therefore you must fail to delete
* anything unless everything is closed.
*/
getToVerificationStarted(staticLayoutBlobId);
auto blobs = handler->getBlobIds();
for (const auto& b : blobs)
{
EXPECT_FALSE(handler->deleteBlob(b));
}
}
/*
* stat(blob)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveImageReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
ASSERT_TRUE(handler->canHandleBlob(activeImageBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeImageBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnActiveHashReturnsFailure)
{
getToVerificationStarted(hashBlobId);
ASSERT_TRUE(handler->canHandleBlob(activeHashBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(activeHashBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnVerifyBlobReturnsFailure)
{
/* the verifyBlobId is available starting at verificationPending. */
getToVerificationStarted(staticLayoutBlobId);
ASSERT_TRUE(handler->canHandleBlob(verifyBlobId));
blobs::BlobMeta meta;
EXPECT_FALSE(handler->stat(verifyBlobId, &meta));
}
TEST_F(FirmwareHandlerVerificationStartedTest, StatOnNormalBlobsReturnsSuccess)
{
getToVerificationStarted(staticLayoutBlobId);
blobs::BlobMeta expected;
expected.blobState = FirmwareBlobHandler::UpdateFlags::ipmi;
expected.size = 0;
std::vector<std::string> testBlobs = {staticLayoutBlobId, hashBlobId};
for (const auto& blob : testBlobs)
{
ASSERT_TRUE(handler->canHandleBlob(blob));
blobs::BlobMeta meta = {};
EXPECT_TRUE(handler->stat(blob, &meta));
EXPECT_EQ(expected, meta);
}
}
/*
* writemeta(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
WriteMetaOnVerifySessionReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->writeMeta(session, 0, bytes));
}
/*
* write(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
WriteOnVerifySessionReturnsFailure)
{
getToVerificationStarted(staticLayoutBlobId);
std::vector<std::uint8_t> bytes = {0x01, 0x02};
EXPECT_FALSE(handler->write(session, 0, bytes));
}
/*
* open(blob) - there is nothing you can open, this state has an open file.
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
AttemptToOpenImageFileReturnsFailure)
{
/* Attempt to open a file one normally can open, however, as there is
* already a file open, this will fail.
*/
getToVerificationStarted(staticLayoutBlobId);
auto blobsToOpen = handler->getBlobIds();
for (const auto& blob : blobsToOpen)
{
EXPECT_FALSE(handler->open(session + 1, flags, blob));
}
}
/*
* read(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest, ReadOfVerifyBlobReturnsEmpty)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_THAT(handler->read(session, 0, 1), IsEmpty());
}
/*
* commit(session)
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
CommitOnVerifyDuringVerificationHasNoImpact)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_TRUE(handler->commit(session, {}));
expectedState(FirmwareBlobHandler::UpdateState::verificationStarted);
}
/*
* close(session) - close while state if verificationStarted without calling
* stat first will abort.
*/
TEST_F(FirmwareHandlerVerificationStartedTest,
CloseOnVerifyDuringVerificationAbortsProcess)
{
getToVerificationStarted(staticLayoutBlobId);
EXPECT_CALL(*verifyMockPtr, abort()).Times(1);
EXPECT_TRUE(handler->close(session));
std::vector<std::string> expectedBlobs = {staticLayoutBlobId, hashBlobId};
EXPECT_THAT(handler->getBlobIds(),
UnorderedElementsAreArray(expectedBlobs));
expectedState(FirmwareBlobHandler::UpdateState::notYetStarted);
}
} // namespace
} // namespace ipmi_flash
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreMaya/FromMayaMeshConverter.h"
#include "IECoreMaya/FromMayaPlugConverter.h"
#include "IECoreMaya/MArrayIter.h"
#include "IECoreMaya/VectorTraits.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/VectorOps.h"
#include "IECore/CompoundParameter.h"
#include "IECore/NumericParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/ClassData.h"
#include "maya/MFn.h"
#include "maya/MFnMesh.h"
#include "maya/MFnAttribute.h"
#include "maya/MString.h"
#include <algorithm>
using namespace IECoreMaya;
using namespace IECore;
using namespace std;
using namespace Imath;
static const MFn::Type fromTypes[] = { MFn::kMesh, MFn::kMeshData, MFn::kInvalid };
static const IECore::TypeId toTypes[] = { BlindDataHolderTypeId, RenderableTypeId, VisibleRenderableTypeId, PrimitiveTypeId, MeshPrimitiveTypeId, InvalidTypeId };
FromMayaShapeConverter::Description<FromMayaMeshConverter> FromMayaMeshConverter::m_description( fromTypes, toTypes );
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// structors
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FromMayaMeshConverter::FromMayaMeshConverter( const MObject &object )
: FromMayaShapeConverter( "FromMayaShapeConverter", "Converts poly meshes to IECore::MeshPrimitive objects.", object )
{
constructCommon();
}
FromMayaMeshConverter::FromMayaMeshConverter( const MDagPath &dagPath )
: FromMayaShapeConverter( "FromMayaShapeConverter", "Converts poly meshes to IECore::MeshPrimitive objects.", dagPath )
{
constructCommon();
}
void FromMayaMeshConverter::constructCommon()
{
// interpolation
StringParameter::PresetsMap interpolationPresets;
interpolationPresets["poly"] = "linear";
interpolationPresets["subdiv"] = "catmullClark";
m_interpolation = new StringParameter(
"interpolation",
"Sets the interpolation type of the new mesh",
"linear",
interpolationPresets
);
parameters()->addParameter( m_interpolation );
// points
BoolParameter::PresetsMap pointsPresets;
pointsPresets["poly"] = true;
pointsPresets["subdiv"] = true;
m_points = new BoolParameter(
"points",
"When this is on the mesh points are added to the result as a primitive variable named \"P\".",
true,
pointsPresets
);
parameters()->addParameter( m_points );
// normals
BoolParameter::PresetsMap normalsPresets;
normalsPresets["poly"] = true;
normalsPresets["subdiv"] = false;
m_normals = new BoolParameter(
"normals",
"When this is on the mesh normals are added to the result as a primitive variable named \"N\". "
"Note that normals will only ever be added to meshes created with linear interpolation as "
"vertex normals are unsuitable for meshes which will be rendered with some form of "
"subdivision.",
true,
normalsPresets
);
parameters()->addParameter( m_normals );
// st
BoolParameter::PresetsMap stPresets;
stPresets["poly"] = true;
stPresets["subdiv"] = true;
m_st = new BoolParameter(
"st",
"When this is on the default uv set is added to the result as primitive variables named \"s\" and \"t\".",
true,
stPresets
);
parameters()->addParameter( m_st );
// extra st
BoolParameter::PresetsMap extraSTPresets;
extraSTPresets["poly"] = true;
extraSTPresets["subdiv"] = true;
m_extraST = new BoolParameter(
"extraST",
"When this is on any additional uv sets are added to the result as primitive variables named \"setName_s\" and \"setName_t\".",
true,
extraSTPresets
);
parameters()->addParameter( m_extraST );
}
FromMayaMeshConverter::~FromMayaMeshConverter()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parameter access
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IECore::StringParameterPtr FromMayaMeshConverter::interpolationParameter()
{
return m_interpolation;
}
IECore::StringParameterPtr FromMayaMeshConverter::interpolationParameter() const
{
return m_interpolation;
}
IECore::BoolParameterPtr FromMayaMeshConverter::pointsParameter()
{
return m_points;
}
IECore::BoolParameterPtr FromMayaMeshConverter::pointsParameter() const
{
return m_points;
}
IECore::BoolParameterPtr FromMayaMeshConverter::normalsParameter()
{
return m_normals;
}
IECore::BoolParameterPtr FromMayaMeshConverter::normalsParameter() const
{
return m_normals;
}
IECore::BoolParameterPtr FromMayaMeshConverter::stParameter()
{
return m_st;
}
IECore::BoolParameterPtr FromMayaMeshConverter::stParameter() const
{
return m_st;
}
IECore::BoolParameterPtr FromMayaMeshConverter::extraSTParameter()
{
return m_extraST;
}
IECore::BoolParameterPtr FromMayaMeshConverter::extraSTParameter() const
{
return m_extraST;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// conversion
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IECore::V3fVectorDataPtr FromMayaMeshConverter::points() const
{
MFnMesh fnMesh;
const MDagPath *d = dagPath( true );
if( d )
{
fnMesh.setObject( *d );
}
else
{
fnMesh.setObject( object() );
}
MFloatPointArray mPoints;
fnMesh.getPoints( mPoints, space() );
V3fVectorDataPtr points = new V3fVectorData;
points->writable().resize( mPoints.length() );
std::transform( MArrayIter<MFloatPointArray>::begin( mPoints ), MArrayIter<MFloatPointArray>::end( mPoints ), points->writable().begin(), VecConvert<MFloatPoint, V3f>() );
return points;
}
IECore::V3fVectorDataPtr FromMayaMeshConverter::normals() const
{
MFnMesh fnMesh;
const MDagPath *d = dagPath( true );
if( d )
{
fnMesh.setObject( *d );
}
else
{
fnMesh.setObject( object() );
}
V3fVectorDataPtr normalsData = new V3fVectorData;
vector<V3f> &normals = normalsData->writable();
normals.resize( fnMesh.numFaceVertices() );
int numPolygons = fnMesh.numPolygons();
MFloatVectorArray faceNormals;
unsigned int normalIndex = 0;
for( int i=0; i<numPolygons; i++ )
{
fnMesh.getFaceVertexNormals( i, faceNormals, space() );
for( unsigned j=0; j<faceNormals.length(); j++ )
{
normals[normalIndex++] = vecConvert<MVector, V3f>( faceNormals[j] );
}
}
assert( normalIndex==normals.size() );
return normalsData;
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::sOrT( const MString &uvSet, unsigned int index ) const
{
MFnMesh fnMesh( object() );
FloatVectorDataPtr resultData = new FloatVectorData;
vector<float> &result = resultData->writable();
result.resize( fnMesh.numFaceVertices() );
int numPolygons = fnMesh.numPolygons();
unsigned int resultIndex = 0;
for( int i=0; i<numPolygons; i++ )
{
for( int j=0; j<fnMesh.polygonVertexCount( i ); j++ )
{
float uv[2];
fnMesh.getPolygonUV( i, j, uv[0], uv[1], &uvSet );
result[resultIndex++] = index==1 ? 1-uv[index] : uv[index];
}
}
return resultData;
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::s( const MString &uvSet ) const
{
return sOrT( uvSet, 0 );
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::t( const MString &uvSet ) const
{
return sOrT( uvSet, 1 );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const
{
MFnMesh fnMesh( object );
return doPrimitiveConversion( fnMesh );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const
{
MFnMesh fnMesh( dagPath );
return doPrimitiveConversion( fnMesh );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( MFnMesh &fnMesh ) const
{
// get basic topology and create a mesh
int numPolygons = fnMesh.numPolygons();
IntVectorDataPtr verticesPerFaceData = new IntVectorData;
verticesPerFaceData->writable().resize( numPolygons );
vector<int>::iterator verticesPerFaceIt = verticesPerFaceData->writable().begin();
IntVectorDataPtr vertexIds = new IntVectorData;
vertexIds->writable().resize( fnMesh.numFaceVertices() );
vector<int>::iterator vertexIdsIt = vertexIds->writable().begin();
MIntArray polygonVertices;
for( int i=0; i<numPolygons; i++ )
{
fnMesh.getPolygonVertices( i, polygonVertices );
*verticesPerFaceIt++ = polygonVertices.length();
copy( MArrayIter<MIntArray>::begin( polygonVertices ), MArrayIter<MIntArray>::end( polygonVertices ), vertexIdsIt );
vertexIdsIt += polygonVertices.length();
}
MeshPrimitivePtr result = new MeshPrimitive( verticesPerFaceData, vertexIds, m_interpolation->getTypedValue() );
if( m_points->getTypedValue() )
{
result->variables["P"] = PrimitiveVariable( PrimitiveVariable::Vertex, points() );
}
if( m_normals->getTypedValue() && m_interpolation->getTypedValue()=="linear" )
{
result->variables["N"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, normals() );
}
MString currentUVSet;
fnMesh.getCurrentUVSetName( currentUVSet );
MStringArray uvSets;
fnMesh.getUVSetNames( uvSets );
for( unsigned int i=0; i<uvSets.length(); i++ )
{
FloatVectorDataPtr sData = s( uvSets[i] );
FloatVectorDataPtr tData = t( uvSets[i] );
if( uvSets[i]==currentUVSet )
{
if( m_st->getTypedValue() )
{
result->variables["s"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, sData );
result->variables["t"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, tData );
}
}
else
{
if( m_extraST->getTypedValue() )
{
MString sName = uvSets[i] + "_s";
MString tName = uvSets[i] + "_t";
result->variables[sName.asChar()] = PrimitiveVariable( PrimitiveVariable::FaceVarying, sData );
result->variables[tName.asChar()] = PrimitiveVariable( PrimitiveVariable::FaceVarying, tData );
}
}
}
return result;
}
<commit_msg>Removed redundant include<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreMaya/FromMayaMeshConverter.h"
#include "IECoreMaya/FromMayaPlugConverter.h"
#include "IECoreMaya/MArrayIter.h"
#include "IECoreMaya/VectorTraits.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/VectorOps.h"
#include "IECore/CompoundParameter.h"
#include "IECore/NumericParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/DespatchTypedData.h"
#include "maya/MFn.h"
#include "maya/MFnMesh.h"
#include "maya/MFnAttribute.h"
#include "maya/MString.h"
#include <algorithm>
using namespace IECoreMaya;
using namespace IECore;
using namespace std;
using namespace Imath;
static const MFn::Type fromTypes[] = { MFn::kMesh, MFn::kMeshData, MFn::kInvalid };
static const IECore::TypeId toTypes[] = { BlindDataHolderTypeId, RenderableTypeId, VisibleRenderableTypeId, PrimitiveTypeId, MeshPrimitiveTypeId, InvalidTypeId };
FromMayaShapeConverter::Description<FromMayaMeshConverter> FromMayaMeshConverter::m_description( fromTypes, toTypes );
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// structors
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FromMayaMeshConverter::FromMayaMeshConverter( const MObject &object )
: FromMayaShapeConverter( "FromMayaShapeConverter", "Converts poly meshes to IECore::MeshPrimitive objects.", object )
{
constructCommon();
}
FromMayaMeshConverter::FromMayaMeshConverter( const MDagPath &dagPath )
: FromMayaShapeConverter( "FromMayaShapeConverter", "Converts poly meshes to IECore::MeshPrimitive objects.", dagPath )
{
constructCommon();
}
void FromMayaMeshConverter::constructCommon()
{
// interpolation
StringParameter::PresetsMap interpolationPresets;
interpolationPresets["poly"] = "linear";
interpolationPresets["subdiv"] = "catmullClark";
m_interpolation = new StringParameter(
"interpolation",
"Sets the interpolation type of the new mesh",
"linear",
interpolationPresets
);
parameters()->addParameter( m_interpolation );
// points
BoolParameter::PresetsMap pointsPresets;
pointsPresets["poly"] = true;
pointsPresets["subdiv"] = true;
m_points = new BoolParameter(
"points",
"When this is on the mesh points are added to the result as a primitive variable named \"P\".",
true,
pointsPresets
);
parameters()->addParameter( m_points );
// normals
BoolParameter::PresetsMap normalsPresets;
normalsPresets["poly"] = true;
normalsPresets["subdiv"] = false;
m_normals = new BoolParameter(
"normals",
"When this is on the mesh normals are added to the result as a primitive variable named \"N\". "
"Note that normals will only ever be added to meshes created with linear interpolation as "
"vertex normals are unsuitable for meshes which will be rendered with some form of "
"subdivision.",
true,
normalsPresets
);
parameters()->addParameter( m_normals );
// st
BoolParameter::PresetsMap stPresets;
stPresets["poly"] = true;
stPresets["subdiv"] = true;
m_st = new BoolParameter(
"st",
"When this is on the default uv set is added to the result as primitive variables named \"s\" and \"t\".",
true,
stPresets
);
parameters()->addParameter( m_st );
// extra st
BoolParameter::PresetsMap extraSTPresets;
extraSTPresets["poly"] = true;
extraSTPresets["subdiv"] = true;
m_extraST = new BoolParameter(
"extraST",
"When this is on any additional uv sets are added to the result as primitive variables named \"setName_s\" and \"setName_t\".",
true,
extraSTPresets
);
parameters()->addParameter( m_extraST );
}
FromMayaMeshConverter::~FromMayaMeshConverter()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parameter access
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IECore::StringParameterPtr FromMayaMeshConverter::interpolationParameter()
{
return m_interpolation;
}
IECore::StringParameterPtr FromMayaMeshConverter::interpolationParameter() const
{
return m_interpolation;
}
IECore::BoolParameterPtr FromMayaMeshConverter::pointsParameter()
{
return m_points;
}
IECore::BoolParameterPtr FromMayaMeshConverter::pointsParameter() const
{
return m_points;
}
IECore::BoolParameterPtr FromMayaMeshConverter::normalsParameter()
{
return m_normals;
}
IECore::BoolParameterPtr FromMayaMeshConverter::normalsParameter() const
{
return m_normals;
}
IECore::BoolParameterPtr FromMayaMeshConverter::stParameter()
{
return m_st;
}
IECore::BoolParameterPtr FromMayaMeshConverter::stParameter() const
{
return m_st;
}
IECore::BoolParameterPtr FromMayaMeshConverter::extraSTParameter()
{
return m_extraST;
}
IECore::BoolParameterPtr FromMayaMeshConverter::extraSTParameter() const
{
return m_extraST;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// conversion
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IECore::V3fVectorDataPtr FromMayaMeshConverter::points() const
{
MFnMesh fnMesh;
const MDagPath *d = dagPath( true );
if( d )
{
fnMesh.setObject( *d );
}
else
{
fnMesh.setObject( object() );
}
MFloatPointArray mPoints;
fnMesh.getPoints( mPoints, space() );
V3fVectorDataPtr points = new V3fVectorData;
points->writable().resize( mPoints.length() );
std::transform( MArrayIter<MFloatPointArray>::begin( mPoints ), MArrayIter<MFloatPointArray>::end( mPoints ), points->writable().begin(), VecConvert<MFloatPoint, V3f>() );
return points;
}
IECore::V3fVectorDataPtr FromMayaMeshConverter::normals() const
{
MFnMesh fnMesh;
const MDagPath *d = dagPath( true );
if( d )
{
fnMesh.setObject( *d );
}
else
{
fnMesh.setObject( object() );
}
V3fVectorDataPtr normalsData = new V3fVectorData;
vector<V3f> &normals = normalsData->writable();
normals.resize( fnMesh.numFaceVertices() );
int numPolygons = fnMesh.numPolygons();
MFloatVectorArray faceNormals;
unsigned int normalIndex = 0;
for( int i=0; i<numPolygons; i++ )
{
fnMesh.getFaceVertexNormals( i, faceNormals, space() );
for( unsigned j=0; j<faceNormals.length(); j++ )
{
normals[normalIndex++] = vecConvert<MVector, V3f>( faceNormals[j] );
}
}
assert( normalIndex==normals.size() );
return normalsData;
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::sOrT( const MString &uvSet, unsigned int index ) const
{
MFnMesh fnMesh( object() );
FloatVectorDataPtr resultData = new FloatVectorData;
vector<float> &result = resultData->writable();
result.resize( fnMesh.numFaceVertices() );
int numPolygons = fnMesh.numPolygons();
unsigned int resultIndex = 0;
for( int i=0; i<numPolygons; i++ )
{
for( int j=0; j<fnMesh.polygonVertexCount( i ); j++ )
{
float uv[2];
fnMesh.getPolygonUV( i, j, uv[0], uv[1], &uvSet );
result[resultIndex++] = index==1 ? 1-uv[index] : uv[index];
}
}
return resultData;
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::s( const MString &uvSet ) const
{
return sOrT( uvSet, 0 );
}
IECore::FloatVectorDataPtr FromMayaMeshConverter::t( const MString &uvSet ) const
{
return sOrT( uvSet, 1 );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( const MObject &object, IECore::ConstCompoundObjectPtr operands ) const
{
MFnMesh fnMesh( object );
return doPrimitiveConversion( fnMesh );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const
{
MFnMesh fnMesh( dagPath );
return doPrimitiveConversion( fnMesh );
}
IECore::PrimitivePtr FromMayaMeshConverter::doPrimitiveConversion( MFnMesh &fnMesh ) const
{
// get basic topology and create a mesh
int numPolygons = fnMesh.numPolygons();
IntVectorDataPtr verticesPerFaceData = new IntVectorData;
verticesPerFaceData->writable().resize( numPolygons );
vector<int>::iterator verticesPerFaceIt = verticesPerFaceData->writable().begin();
IntVectorDataPtr vertexIds = new IntVectorData;
vertexIds->writable().resize( fnMesh.numFaceVertices() );
vector<int>::iterator vertexIdsIt = vertexIds->writable().begin();
MIntArray polygonVertices;
for( int i=0; i<numPolygons; i++ )
{
fnMesh.getPolygonVertices( i, polygonVertices );
*verticesPerFaceIt++ = polygonVertices.length();
copy( MArrayIter<MIntArray>::begin( polygonVertices ), MArrayIter<MIntArray>::end( polygonVertices ), vertexIdsIt );
vertexIdsIt += polygonVertices.length();
}
MeshPrimitivePtr result = new MeshPrimitive( verticesPerFaceData, vertexIds, m_interpolation->getTypedValue() );
if( m_points->getTypedValue() )
{
result->variables["P"] = PrimitiveVariable( PrimitiveVariable::Vertex, points() );
}
if( m_normals->getTypedValue() && m_interpolation->getTypedValue()=="linear" )
{
result->variables["N"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, normals() );
}
MString currentUVSet;
fnMesh.getCurrentUVSetName( currentUVSet );
MStringArray uvSets;
fnMesh.getUVSetNames( uvSets );
for( unsigned int i=0; i<uvSets.length(); i++ )
{
FloatVectorDataPtr sData = s( uvSets[i] );
FloatVectorDataPtr tData = t( uvSets[i] );
if( uvSets[i]==currentUVSet )
{
if( m_st->getTypedValue() )
{
result->variables["s"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, sData );
result->variables["t"] = PrimitiveVariable( PrimitiveVariable::FaceVarying, tData );
}
}
else
{
if( m_extraST->getTypedValue() )
{
MString sName = uvSets[i] + "_s";
MString tName = uvSets[i] + "_t";
result->variables[sName.asChar()] = PrimitiveVariable( PrimitiveVariable::FaceVarying, sData );
result->variables[tName.asChar()] = PrimitiveVariable( PrimitiveVariable::FaceVarying, tData );
}
}
}
return result;
}
<|endoftext|>
|
<commit_before>#pragma once
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode {
namespace {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
template <typename A>
static inline void killPtr(A* &a) noexcept {
if (a != nullptr) {
delete a;
a = nullptr;
}
}
template <>
static inline void killPtr(A) noexcept;
template <>
static inline void killPtr(bitnode<A>) noexcept;
}
public:
inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}
template <typename... A>
explicit bitnode(A... a) = delete;
private:
bitnode* zero;
bitnode* one;
A* data;
};
}
}<commit_msg>helpful accessors and mutators<commit_after>#pragma once
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode {
namespace {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
template <typename A>
static inline void killPtr(A* &a) noexcept {
if (a != nullptr) {
delete a;
a = nullptr;
}
}
template <>
static inline void killPtr(A) noexcept;
template <>
static inline void killPtr(bitnode<A>) noexcept;
}
public:
inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}
template <typename... A>
explicit bitnode(A... a) = delete;
inline ~bitnode(void) noexcept {
if (data != nullptr) {
delete data;
}
}
inline void dump(void) noexcept {
bitnode<A>::killPtr<A>(data);
}
inline const A &getData(void) const noexcept {
return *data;
}
inline void setData(conref<A> a) noexcept {
this->dump();
data = new A{a};
}
inline void dumpZero(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(zero);
}
inline bitnode<A>* getZero(void) const noexcept {
return *zero;
}
inline void setZero(bitnode<A>* a) noexcept {
this->dumpZero();
data = a;
}
inline void dumpOne(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(one);
}
inline bitnode<A>* getOne(void) const noexcept {
return *one;
}
inline void setOne(bitnode<A>* a) noexcept {
this->dumpOne();
data = a;
}
inline void dumpAll(void) noexcept {
this->dump();
this->dumpZero();
this->dumpOne();
}
private:
bitnode<A>* zero;
bitnode<A>* one;
A* data;
};
}
}<|endoftext|>
|
<commit_before>#pragma once
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode final {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
template <typename A>
static inline void killPtr(A* &a) noexcept {
if (a != nullptr) {
delete a;
a = nullptr;
}
}
template <>
static inline void killPtr(A) noexcept;
template <>
static inline void killPtr(bitnode<A>) noexcept;
public:
inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}
template <typename... A>
explicit bitnode(A... a) = delete;
inline ~bitnode(void) noexcept {
if (data != nullptr) {
delete data;
}
}
inline void dump(void) noexcept {
bitnode<A>::killPtr<A>(data);
}
inline A* getData(void) const noexcept {
return data;
}
inline void setData(conref<A> a) noexcept {
this->dump();
data = new A{a};
}
inline void setData(A* a) noexcept {
this->dump();
data = a;
}
inline void dumpZero(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(zero);
}
inline bitnode<A>* getZero(void) const noexcept {
return *zero;
}
inline void setZero(bitnode<A>* a) noexcept {
this->dumpZero();
data = a;
}
inline void dumpOne(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(one);
}
inline bitnode<A>* getOne(void) const noexcept {
return *one;
}
inline void setOne(bitnode<A>* a) noexcept {
this->dumpOne();
data = a;
}
inline void dumpAll(void) noexcept {
this->dump();
this->dumpZero();
this->dumpOne();
}
inline bool isEmpty(void) const noexcept {
return data == nullptr;
}
inline bool isNotEmpty(void) const noexcept {
return !this->isEmpty();
}
inline bool haveZero(void) const noexcept {
return zero == nullptr;
}
inline bool noZero(void) const noexcept {
return !this->noZero();
}
inline bool haveOne(void) const noexcept {
return one == nullptr;
}
inline bool noOne(void) const noexcept {
return !this->noOne();
}
inline bool isBarren(void) const noexcept {
return this->haveZero() && this->haveOne();
}
inline bool isNotBarren(void) const noexcept {
return !this->isBarren();
}
private:
bitnode<A>* zero;
bitnode<A>* one;
A* data;
};
}
}<commit_msg>add class to anon namespace<commit_after>#pragma once
namespace {
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode final {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
template <typename A>
static inline void killPtr(A* &a) noexcept {
if (a != nullptr) {
delete a;
a = nullptr;
}
}
template <>
static inline void killPtr(A) noexcept;
template <>
static inline void killPtr(bitnode<A>) noexcept;
public:
inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {}
template <typename... A>
explicit bitnode(A... a) = delete;
inline ~bitnode(void) noexcept {
if (data != nullptr) {
delete data;
}
}
inline void dump(void) noexcept {
bitnode<A>::killPtr<A>(data);
}
inline A* getData(void) const noexcept {
return data;
}
inline void setData(conref<A> a) noexcept {
this->dump();
data = new A{a};
}
inline void setData(A* a) noexcept {
this->dump();
data = a;
}
inline void dumpZero(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(zero);
}
inline bitnode<A>* getZero(void) const noexcept {
return *zero;
}
inline void setZero(bitnode<A>* a) noexcept {
this->dumpZero();
data = a;
}
inline void dumpOne(void) noexcept {
bitnode<A>::killPtr<bitnode<A>>(one);
}
inline bitnode<A>* getOne(void) const noexcept {
return *one;
}
inline void setOne(bitnode<A>* a) noexcept {
this->dumpOne();
data = a;
}
inline void dumpAll(void) noexcept {
this->dump();
this->dumpZero();
this->dumpOne();
}
inline bool isEmpty(void) const noexcept {
return data == nullptr;
}
inline bool isNotEmpty(void) const noexcept {
return !this->isEmpty();
}
inline bool haveZero(void) const noexcept {
return zero == nullptr;
}
inline bool noZero(void) const noexcept {
return !this->noZero();
}
inline bool haveOne(void) const noexcept {
return one == nullptr;
}
inline bool noOne(void) const noexcept {
return !this->noOne();
}
inline bool isBarren(void) const noexcept {
return this->haveZero() && this->haveOne();
}
inline bool isNotBarren(void) const noexcept {
return !this->isBarren();
}
private:
bitnode<A>* zero;
bitnode<A>* one;
A* data;
};
}
}
}<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Sean Kasun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "chunkcache.h"
#include "chunkloader.h"
ChunkID::ChunkID(int x,int z) : x(x),z(z)
{
}
bool ChunkID::operator==(const ChunkID &other) const
{
return other.x==x && other.z==z;
}
uint qHash(const ChunkID &c)
{
return c.x^c.z; //quick way to hash a pair of integers
}
ChunkCache::ChunkCache()
{
cache.setMaxCost(10000); // 10000 chunks, or a little bit more than 1920x1200 blocks
}
ChunkCache::~ChunkCache()
{
}
void ChunkCache::clear()
{
QThreadPool::globalInstance()->waitForDone();
mutex.lock();
cache.clear();
mutex.unlock();
}
void ChunkCache::setPath(QString path)
{
this->path=path;
}
QString ChunkCache::getPath()
{
return path;
}
Chunk *ChunkCache::fetch(int x, int z)
{
ChunkID id(x,z);
mutex.lock();
Chunk *chunk=cache[id];
mutex.unlock();
if (chunk!=NULL)
{
if (chunk->loaded)
return chunk;
return NULL; //we're loading this chunk, or it's blank.
}
// launch background process to load this chunk
chunk=new Chunk();
mutex.lock();
cache.insert(id,chunk);
mutex.unlock();
ChunkLoader *loader=new ChunkLoader(path,x,z,cache,mutex);
connect(loader,SIGNAL(loaded(int,int)),
this,SLOT(gotChunk(int,int)));
QThreadPool::globalInstance()->start(loader);
return NULL;
}
void ChunkCache::gotChunk(int x,int z)
{
emit chunkLoaded(x,z);
}
<commit_msg>Extended ChunkChache size for 4K monitors<commit_after>/*
Copyright (c) 2013, Sean Kasun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "chunkcache.h"
#include "chunkloader.h"
ChunkID::ChunkID(int x,int z) : x(x),z(z)
{
}
bool ChunkID::operator==(const ChunkID &other) const
{
return other.x==x && other.z==z;
}
uint qHash(const ChunkID &c)
{
return c.x^c.z; //quick way to hash a pair of integers
}
ChunkCache::ChunkCache()
{
// set cache size to 37000 chunks (for UHD and 4K displays)
// a little bit more than 3840x2400 or 4096x2304 blocks
cache.setMaxCost(37000);
}
ChunkCache::~ChunkCache()
{
}
void ChunkCache::clear()
{
QThreadPool::globalInstance()->waitForDone();
mutex.lock();
cache.clear();
mutex.unlock();
}
void ChunkCache::setPath(QString path)
{
this->path=path;
}
QString ChunkCache::getPath()
{
return path;
}
Chunk *ChunkCache::fetch(int x, int z)
{
ChunkID id(x,z);
mutex.lock();
Chunk *chunk=cache[id];
mutex.unlock();
if (chunk!=NULL)
{
if (chunk->loaded)
return chunk;
return NULL; //we're loading this chunk, or it's blank.
}
// launch background process to load this chunk
chunk=new Chunk();
mutex.lock();
cache.insert(id,chunk);
mutex.unlock();
ChunkLoader *loader=new ChunkLoader(path,x,z,cache,mutex);
connect(loader,SIGNAL(loaded(int,int)),
this,SLOT(gotChunk(int,int)));
QThreadPool::globalInstance()->start(loader);
return NULL;
}
void ChunkCache::gotChunk(int x,int z)
{
emit chunkLoaded(x,z);
}
<|endoftext|>
|
<commit_before>#include "oglWidget.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default constructor for OGLWidget.
*/
OGLWidget::OGLWidget()
{
// Update the widget after a frameswap
connect( this, SIGNAL( frameSwapped() ),
this, SLOT( update() ) );
// Allows keyboard input to fall through
setFocusPolicy( Qt::ClickFocus );
// Setup the Camera
camera.rotate( -40.0f, 1.0f, 0.0f, 0.0f );
camera.translate( 0.0f, 30.0f, 45.0f );
renderables.push_back( new Sun() );
renderables.push_back( new Skybox() );
}
/**
* @brief Destructor class to unallocate OpenGL information.
*/
OGLWidget::~OGLWidget()
{
makeCurrent();
teardownGL();
}
//
// OPENGL FUNCTIONS ////////////////////////////////////////////////////////////
//
void OGLWidget::initializeGL()
{
// Init OpenGL Backend
initializeOpenGLFunctions();
printContextInfo();
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->initializeGL();
}
}
/**
* @brief Sets the prespective whenever the window is resized.
*
* @param[in] width The width of the new window.
* @param[in] height The height of the new window.
*/
void OGLWidget::resizeGL( int width, int height )
{
projection.setToIdentity();
projection.perspective( 55.0f, // Field of view angle
float( width ) / float( height ), // Aspect Ratio
0.01f, // Near Plane (MUST BE GREATER THAN 0)
1000.0f ); // Far Plane
}
/**
* @brief OpenGL function to draw elements to the surface.
*/
void OGLWidget::paintGL()
{
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glDepthMask( GL_TRUE );
glEnable( GL_CULL_FACE );
glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->paintGL( camera, projection );
}
}
/**
* @brief Destroys any OpenGL data.
*/
void OGLWidget::teardownGL()
{
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->teardownGL();
}
}
//
// QT SLOTS ////////////////////////////////////////////////////////////////////
//
/**
* @brief Updates any user interactions and model transformations.
*/
void OGLWidget::update()
{
Input::update();
// Camera Transforms
if( Input::buttonPressed( Qt::RightButton ) )
{
static const float cameraTranslationSpeed = 0.3f;
static const float cameraRotationSpeed = 0.1f;
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(),
Camera3D::LocalUp );
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),
camera.right() );
QVector3D cameraTranslations;
if( Input::keyPressed( Qt::Key_W ) )
cameraTranslations += camera.forward();
if( Input::keyPressed( Qt::Key_S ) )
cameraTranslations -= camera.forward();
if( Input::keyPressed( Qt::Key_A ) )
cameraTranslations -= camera.right();
if( Input::keyPressed( Qt::Key_D ) )
cameraTranslations += camera.right();
if( Input::keyPressed( Qt::Key_Q ) )
cameraTranslations -= camera.up();
if( Input::keyPressed( Qt::Key_E ) )
cameraTranslations += camera.up();
camera.translate( cameraTranslationSpeed * cameraTranslations );
}
if( !paused )
{
for( auto renderable : renderables )
{
renderable->update();
}
}
QOpenGLWidget::update();
}
/**
* @brief Slot for pausing/unpausing.
*/
void OGLWidget::swapPause()
{
paused = !paused;
}
void OGLWidget::swapScaledView()
{
Planet::SCALED = !Planet::SCALED;
}
//
// INPUT EVENTS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default slot for handling key press events.
*
* @param event The key event information.
*/
void OGLWidget::keyPressEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyPress( event->key() );
}
/**
* @brief Default slot for handling key release events.
*
* @param event The key event information.
*/
void OGLWidget::keyReleaseEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyRelease( event->key() );
}
/**
* @brief Default slot for handling mouse press events.
*
* @param event The mouse event information.
*/
void OGLWidget::mousePressEvent( QMouseEvent* event )
{
Input::registerMousePress( event->button() );
}
/**
* @brief Default slot for handling mouse release events.
*
* @param event The mouse event information.
*/
void OGLWidget::mouseReleaseEvent( QMouseEvent* event )
{
Input::registerMouseRelease( event->button() );
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
/**
* @brief Helper function to print OpenGL Context information to the debug.
*/
void OGLWidget::printContextInfo()
{
QString glType;
QString glVersion;
QString glProfile;
// Get Version Information
glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
// Get Profile Information
switch( format().profile() )
{
case QSurfaceFormat::NoProfile:
glProfile = "No Profile";
break;
case QSurfaceFormat::CoreProfile:
glProfile = "Core Profile";
break;
case QSurfaceFormat::CompatibilityProfile:
glProfile = "Compatibility Profile";
break;
}
qDebug() << qPrintable( glType ) << qPrintable( glVersion ) <<
"(" << qPrintable( glProfile ) << ")";
}<commit_msg>Added an update loop in the OGLWidget constructor so planets don't appear stacked<commit_after>#include "oglWidget.h"
//
// CONSTRUCTORS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default constructor for OGLWidget.
*/
OGLWidget::OGLWidget()
{
// Update the widget after a frameswap
connect( this, SIGNAL( frameSwapped() ),
this, SLOT( update() ) );
// Allows keyboard input to fall through
setFocusPolicy( Qt::ClickFocus );
// Setup the Camera
camera.rotate( -40.0f, 1.0f, 0.0f, 0.0f );
camera.translate( 0.0f, 30.0f, 45.0f );
renderables.push_back( new Sun() );
renderables.push_back( new Skybox() );
// this is so all the planets aren't stacked together in the beginning
for( auto renderable : renderables )
{
renderable->update();
}
}
/**
* @brief Destructor class to unallocate OpenGL information.
*/
OGLWidget::~OGLWidget()
{
makeCurrent();
teardownGL();
}
//
// OPENGL FUNCTIONS ////////////////////////////////////////////////////////////
//
void OGLWidget::initializeGL()
{
// Init OpenGL Backend
initializeOpenGLFunctions();
printContextInfo();
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->initializeGL();
}
}
/**
* @brief Sets the prespective whenever the window is resized.
*
* @param[in] width The width of the new window.
* @param[in] height The height of the new window.
*/
void OGLWidget::resizeGL( int width, int height )
{
projection.setToIdentity();
projection.perspective( 55.0f, // Field of view angle
float( width ) / float( height ), // Aspect Ratio
0.01f, // Near Plane (MUST BE GREATER THAN 0)
1000.0f ); // Far Plane
}
/**
* @brief OpenGL function to draw elements to the surface.
*/
void OGLWidget::paintGL()
{
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glDepthMask( GL_TRUE );
glEnable( GL_CULL_FACE );
glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->paintGL( camera, projection );
}
}
/**
* @brief Destroys any OpenGL data.
*/
void OGLWidget::teardownGL()
{
QVectorIterator<Renderable*> i_renderable( renderables );
while( i_renderable.hasNext() )
{
( i_renderable.next() )->teardownGL();
}
}
//
// QT SLOTS ////////////////////////////////////////////////////////////////////
//
/**
* @brief Updates any user interactions and model transformations.
*/
void OGLWidget::update()
{
Input::update();
// Camera Transforms
if( Input::buttonPressed( Qt::RightButton ) )
{
static const float cameraTranslationSpeed = 0.3f;
static const float cameraRotationSpeed = 0.1f;
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(),
Camera3D::LocalUp );
camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),
camera.right() );
QVector3D cameraTranslations;
if( Input::keyPressed( Qt::Key_W ) )
cameraTranslations += camera.forward();
if( Input::keyPressed( Qt::Key_S ) )
cameraTranslations -= camera.forward();
if( Input::keyPressed( Qt::Key_A ) )
cameraTranslations -= camera.right();
if( Input::keyPressed( Qt::Key_D ) )
cameraTranslations += camera.right();
if( Input::keyPressed( Qt::Key_Q ) )
cameraTranslations -= camera.up();
if( Input::keyPressed( Qt::Key_E ) )
cameraTranslations += camera.up();
camera.translate( cameraTranslationSpeed * cameraTranslations );
}
if( !paused )
{
for( auto renderable : renderables )
{
renderable->update();
}
}
QOpenGLWidget::update();
}
/**
* @brief Slot for pausing/unpausing.
*/
void OGLWidget::swapPause()
{
paused = !paused;
}
void OGLWidget::swapScaledView()
{
Planet::SCALED = !Planet::SCALED;
}
//
// INPUT EVENTS ////////////////////////////////////////////////////////////////
//
/**
* @brief Default slot for handling key press events.
*
* @param event The key event information.
*/
void OGLWidget::keyPressEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyPress( event->key() );
}
/**
* @brief Default slot for handling key release events.
*
* @param event The key event information.
*/
void OGLWidget::keyReleaseEvent( QKeyEvent* event )
{
if( event->isAutoRepeat() )
event->ignore();
else
Input::registerKeyRelease( event->key() );
}
/**
* @brief Default slot for handling mouse press events.
*
* @param event The mouse event information.
*/
void OGLWidget::mousePressEvent( QMouseEvent* event )
{
Input::registerMousePress( event->button() );
}
/**
* @brief Default slot for handling mouse release events.
*
* @param event The mouse event information.
*/
void OGLWidget::mouseReleaseEvent( QMouseEvent* event )
{
Input::registerMouseRelease( event->button() );
}
//
// PRIVATE HELPER FUNCTIONS ////////////////////////////////////////////////////
//
/**
* @brief Helper function to print OpenGL Context information to the debug.
*/
void OGLWidget::printContextInfo()
{
QString glType;
QString glVersion;
QString glProfile;
// Get Version Information
glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );
// Get Profile Information
switch( format().profile() )
{
case QSurfaceFormat::NoProfile:
glProfile = "No Profile";
break;
case QSurfaceFormat::CoreProfile:
glProfile = "Core Profile";
break;
case QSurfaceFormat::CompatibilityProfile:
glProfile = "Compatibility Profile";
break;
}
qDebug() << qPrintable( glType ) << qPrintable( glVersion ) <<
"(" << qPrintable( glProfile ) << ")";
}<|endoftext|>
|
<commit_before>/*
Allocore Example: Fluid
Description:
This demonstrates a 3D fluid simulation
Author:
Graham Wakefield 2011
*/
#include "allocore/al_Allocore.hpp"
#include "allocore/graphics/al_Shader.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
#include "alloutil/al_Field3D.hpp"
using namespace al;
// As a 3D Texture:
Texture tex(32, 32, 32, Graphics::LUMINANCE);
float amean;
// As an Isosurface:
Isosurface iso;
Graphics gl;
Mesh mesh;
ShaderProgram shaderP;
Shader shaderV, shaderF;
static const char * vField = AL_STRINGIFY(
varying vec3 texcoord0;
void main(){
texcoord0 = gl_Vertex.xyz / 32.;
//texcoord0 = vec3(gl_MultiTexCoord0);
gl_Position = ftransform();
}
);
static const char * fField = AL_STRINGIFY(
uniform sampler3D tex;
varying vec3 texcoord0;
void main() {
float intensity = texture3D(tex, texcoord0).r;
vec3 rgb = vec3(intensity, intensity, intensity);
gl_FragColor = vec4(rgb, 0.5);
//gl_FragColor = vec4(texcoord0, 1);
}
);
struct MyWindow : public Window {
bool onCreate(){
// reconfigure textures based on arrays:
tex.submit(tex.array(), true);
// shader method:
shaderV.source(vField, Shader::VERTEX).compile();
shaderF.source(fField, Shader::FRAGMENT).compile();
shaderP.attach(shaderV).attach(shaderF).link();
shaderV.printLog();
shaderF.printLog();
shaderP.printLog();
// create rendering mesh:
mesh.reset();
mesh.primitive(Graphics::POINTS);
for (int x=0; x<32; x++) {
for (int y=0; y<32; y++) {
for (int z=0; z<32; z++) {
mesh.texCoord(x/32., y/32., z/32.);
mesh.vertex(x, y, z);
}}}
return true;
}
bool onFrame(){
gl.clearColor(0,0,0,0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.viewport(0,0, width(), height());
gl.matrixMode(gl.PROJECTION);
gl.loadMatrix(Matrix4d::perspective(45, aspect(), 0.1, 100));
gl.matrixMode(gl.MODELVIEW);
gl.loadMatrix(Matrix4d::lookAt(Vec3d(16, 16, 64), Vec3d(16, 16, 16), Vec3d(0,1,0)));
gl.lineWidth(0.5);
gl.color(1, 1, 1, 0.02);
gl.pointSize(1);
gl.polygonMode(gl.LINE);
iso.level(amean + 4.*sin(fmod(al_time() * 0.125, 1.) * M_2PI));
iso.generate((char *)tex.array().data.ptr, 32, 32, 32, 1./32, 1./32, 1./32);
gl.pushMatrix();
gl.scale(32, 32, 32);
gl.draw(iso);
gl.popMatrix();
// draw it:
gl.blending(true);
gl.blendModeAdd();
shaderP.begin();
shaderP.uniform("tex", 0);
tex.bind();
gl.draw(mesh);
tex.unbind();
shaderP.end();
gl.polygonMode(gl.FILL);
gl.color(1, 1, 1, 1.);
float slice = 1.-fmod(al_time() * 0.25, 1.);
tex.bind();
float s = 32.;
gl.begin(gl.QUADS);
gl.texCoord(0, 0, slice);
gl.vertex(0, 0, slice*s);
gl.texCoord(0, 1, slice);
gl.vertex(0, s, slice*s);
gl.texCoord(1, 1, slice);
gl.vertex(s, s, slice*s);
gl.texCoord(1, 0, slice);
gl.vertex(s, 0, slice*s);
gl.end();
tex.unbind();
return true;
}
};
MyWindow win;
enum MRCMode {
MRC_IMAGE_SINT8 = 0, //image : signed 8-bit bytes range -128 to 127
MRC_IMAGE_SINT16 = 1, //image : 16-bit halfwords
MRC_IMAGE_FLOAT32 = 2, //image : 32-bit reals
MRC_TRANSFORM_INT16 = 3, //transform : complex 16-bit integers
MRC_TRANSFORM_FLOAT32 = 4, //transform : complex 32-bit reals
MRC_IMAGE_UINT16 = 6 //image : unsigned 16-bit range 0 to 65535
};
struct MRCHeader {
int32_t nx; /* # of Columns */
int32_t ny; /* # of Rows */
int32_t nz; /* # of Sections. */
int32_t mode; /* given by #define MRC_MODE... */
int32_t startx; /* Starting point of sub image. */
int32_t starty;
int32_t startz;
int32_t mx; /* Number of rows to read. */
int32_t my;
int32_t mz;
float_t xlen; /* length of x element in um. */
float_t ylen; /* get scale = xlen/nx ... */
float_t zlen;
float_t alpha; /* cell angles, ignore */
float_t beta;
float_t gamma;
int32_t mapx; /* map coloumn 1=x,2=y,3=z. */
int32_t mapy; /* map row 1=x,2=y,3=z. */
int32_t mapz; /* map section 1=x,2=y,3=z. */
float_t amin;
float_t amax;
float_t amean;
int16_t ispg; /* image type */
int16_t nsymbt; /* space group number */
/* IMOD-SPECIFIC */
int32_t next;
int16_t creatid; /* Used to be creator id, hvem = 1000, now 0 */
char blank[30];
int16_t nint;
int16_t nreal;
int16_t sub;
int16_t zfac;
float_t min2;
float_t max2;
float_t min3;
float_t max3;
int32_t imodStamp;
int32_t imodFlags;
int16_t idtype;
int16_t lens;
int16_t nd1; /* Devide by 100 to get float value. */
int16_t nd2;
int16_t vd1;
int16_t vd2;
float_t tiltangles[6]; /* 0,1,2 = original: 3,4,5 = current */
/* MRC 2000 standard */
float_t origin[3];
char cmap[4];
char machinestamp[4];
float_t rms;
int32_t nlabl; // number of labels
char labels[10][80];
} MrcHeader;
MRCHeader& mrcParse(const char * data, Array& array) {
MRCHeader& header = *(MRCHeader *)data;
// check for byte swap:
bool swapped =
(header.nx <= 0 || header.ny <= 0 || header.nz <= 0 ||
(header.nx > 65535 && header.ny > 65535 && header.nz > 65535) ||
header.mapx < 0 || header.mapx > 4 ||
header.mapy < 0 || header.mapy > 4 ||
header.mapz < 0 || header.mapz > 4);
// ugh.
if (swapped) {
printf("swapping byte order...\n");
swapbytes(&header.nx, 10);
swapbytes(&header.xlen, 6);
swapbytes(&header.mapx, 3);
swapbytes(&header.amin, 3);
swapbytes(&header.ispg, 2);
swapbytes(&header.next, 1);
swapbytes(&header.creatid, 1);
swapbytes(&header.nint, 4);
swapbytes(&header.min2, 4);
swapbytes(&header.imodStamp, 2);
swapbytes(&header.idtype, 6);
swapbytes(&header.tiltangles[0], 6);
swapbytes(&header.origin[0], 3);
swapbytes(&header.rms, 1);
swapbytes(&header.nlabl, 1);
}
printf("NX %d NY %d NZ %d\n", header.nx, header.ny, header.nz);
printf("mode %d\n", header.mode);
printf("startX %d startY %d startZ %d\n", header.startx, header.starty, header.startz);
printf("intervals X %d intervals Y %d intervals Z %d\n", header.mx, header.my, header.mz);
printf("angstroms X %f angstroms Y %f angstroms Z %f\n", header.xlen, header.ylen, header.zlen);
printf("axis X %d axis Y %d axis Z %d\n", header.mapx, header.mapy, header.mapz);
printf("density min %f max %f mean %f\n", header.amin, header.amax, header.amean);
printf("origin %f %f %f\n", header.origin[0], header.origin[1], header.origin[2]);
printf("map %s\n", header.cmap);
printf("machine stamp %s\n", header.machinestamp);
printf("rms %f\n", header.rms);
printf("labels %d\n", header.nlabl);
for (int i=0; i<header.nlabl; i++) {
//printf("\t%02d: %s\n", i, header.labels[i]);
}
const char * start = data + 1024;
AlloTy ty;
// set type:
switch (header.mode) {
case MRC_IMAGE_SINT8:
printf("signed int 8\n");
ty = Array::type<int8_t>();
break;
case MRC_IMAGE_SINT16:
printf("signed int 16\n");
ty = Array::type<int16_t>();
break;
case MRC_IMAGE_FLOAT32:
printf("float\n");
ty = Array::type<float_t>();
break;
case MRC_IMAGE_UINT16:
printf("unsigned int 16\n");
ty = Array::type<uint16_t>();
break;
default:
printf("MRC mode not supported\n");
break;
}
array.formatAligned(1, ty, header.nx, header.ny, header.nz, 0);
memcpy(array.data.ptr, start, array.size());
if (swapped) {
// set type:
switch (header.mode) {
case MRC_IMAGE_SINT8:
swapbytes((int8_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_SINT16:
swapbytes((int16_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_FLOAT32:
swapbytes((float_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_UINT16:
swapbytes((uint16_t *)array.data.ptr, array.cells());
break;
default:
break;
}
}
return header;
}
int main(){
SearchPaths paths;
paths.addAppPaths();
paths.addSearchPath(paths.appPath() + "../../", true);
paths.print();
std::string mrcpath = paths.find("golgi.mrc").filepath();
printf("golgi: %s\n", mrcpath.c_str());
File f(mrcpath, "rb", true);
Array& array = tex.array();
MRCHeader& header = mrcParse(f.readAll(), array);
amean = header.amean;
win.append(*new StandardWindowKeyControls);
win.create(Window::Dim(640, 480));
iso.primitive(Graphics::TRIANGLES);
MainLoop::start();
return 0;
}
<commit_msg>first working demo of MRC reader<commit_after>/*
Allocore Example: Fluid
Description:
This demonstrates a 3D fluid simulation
Author:
Graham Wakefield 2011
*/
#include "allocore/al_Allocore.hpp"
#include "allocore/graphics/al_Shader.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
#include "alloutil/al_Field3D.hpp"
using namespace al;
// As a 3D Texture:
Texture tex(32, 32, 32, Graphics::LUMINANCE);
float amean;
// As an Isosurface:
Isosurface iso;
Graphics gl;
Mesh mesh;
ShaderProgram shaderP;
Shader shaderV, shaderF;
static const char * vField = AL_STRINGIFY(
varying vec3 texcoord0;
void main(){
texcoord0 = gl_Vertex.xyz / 32.;
//texcoord0 = vec3(gl_MultiTexCoord0);
gl_Position = ftransform();
}
);
static const char * fField = AL_STRINGIFY(
uniform sampler3D tex;
varying vec3 texcoord0;
void main() {
float intensity = texture3D(tex, texcoord0).r;
vec3 rgb = vec3(intensity, intensity, intensity);
gl_FragColor = vec4(rgb, 0.5);
//gl_FragColor = vec4(texcoord0, 1);
}
);
struct MyWindow : public Window {
bool onCreate(){
// reconfigure textures based on arrays:
tex.submit(tex.array(), true);
// shader method:
shaderV.source(vField, Shader::VERTEX).compile();
shaderF.source(fField, Shader::FRAGMENT).compile();
shaderP.attach(shaderV).attach(shaderF).link();
shaderV.printLog();
shaderF.printLog();
shaderP.printLog();
// create rendering mesh:
mesh.reset();
mesh.primitive(Graphics::POINTS);
for (int x=0; x<32; x++) {
for (int y=0; y<32; y++) {
for (int z=0; z<32; z++) {
mesh.texCoord(x/32., y/32., z/32.);
mesh.vertex(x, y, z);
}}}
return true;
}
bool onFrame(){
gl.clearColor(0,0,0,0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.viewport(0,0, width(), height());
gl.matrixMode(gl.PROJECTION);
gl.loadMatrix(Matrix4d::perspective(45, aspect(), 0.1, 100));
gl.matrixMode(gl.MODELVIEW);
gl.loadMatrix(Matrix4d::lookAt(Vec3d(16, 16, 64), Vec3d(16, 16, 16), Vec3d(0,1,0)));
gl.lineWidth(0.5);
gl.color(1, 1, 1, 0.02);
gl.pointSize(1);
gl.polygonMode(gl.LINE);
iso.level(amean + 4.*sin(fmod(al_time() * 0.125, 1.) * M_2PI));
iso.generate((char *)tex.array().data.ptr, 32, 32, 32, 1./32, 1./32, 1./32);
gl.pushMatrix();
gl.scale(32, 32, 32);
gl.draw(iso);
gl.popMatrix();
// draw it:
gl.blending(true);
gl.blendModeAdd();
shaderP.begin();
shaderP.uniform("tex", 0);
tex.bind();
gl.draw(mesh);
tex.unbind();
shaderP.end();
gl.polygonMode(gl.FILL);
gl.color(1, 1, 1, 1.);
float slice = 1.-fmod(al_time() * 0.25, 1.);
tex.bind();
float s = 32.;
gl.begin(gl.QUADS);
gl.texCoord(0, 0, slice);
gl.vertex(0, 0, slice*s);
gl.texCoord(0, 1, slice);
gl.vertex(0, s, slice*s);
gl.texCoord(1, 1, slice);
gl.vertex(s, s, slice*s);
gl.texCoord(1, 0, slice);
gl.vertex(s, 0, slice*s);
gl.end();
tex.unbind();
return true;
}
};
MyWindow win;
enum MRCMode {
MRC_IMAGE_SINT8 = 0, //image : signed 8-bit bytes range -128 to 127
MRC_IMAGE_SINT16 = 1, //image : 16-bit halfwords
MRC_IMAGE_FLOAT32 = 2, //image : 32-bit reals
MRC_TRANSFORM_INT16 = 3, //transform : complex 16-bit integers
MRC_TRANSFORM_FLOAT32 = 4, //transform : complex 32-bit reals
MRC_IMAGE_UINT16 = 6 //image : unsigned 16-bit range 0 to 65535
};
struct MRCHeader {
// @see http://ami.scripps.edu/software/mrctools/mrc_specification.php
// or http://bio3d.colorado.edu/imod/doc/mrc_format.txt
int32_t nx; /* # of Columns */
int32_t ny; /* # of Rows */
int32_t nz; /* # of Sections. */
int32_t mode; /* given by #define MRC_MODE... */
int32_t startx; /* Starting point of sub image. */
int32_t starty;
int32_t startz;
int32_t mx; /* Number of rows to read. */
int32_t my;
int32_t mz;
float_t xlen; /* length of x element in um. */
float_t ylen; /* get scale = xlen/nx ... */
float_t zlen;
float_t alpha; /* cell angles, ignore */
float_t beta;
float_t gamma;
int32_t mapx; /* map coloumn 1=x,2=y,3=z. */
int32_t mapy; /* map row 1=x,2=y,3=z. */
int32_t mapz; /* map section 1=x,2=y,3=z. */
float_t amin;
float_t amax;
float_t amean;
int16_t ispg; /* image type */
int16_t nsymbt; /* space group number */
/* IMOD-SPECIFIC */
int32_t next;
int16_t creatid; /* Used to be creator id, hvem = 1000, now 0 */
char blank[30];
int16_t nint;
int16_t nreal;
int16_t sub;
int16_t zfac;
float_t min2;
float_t max2;
float_t min3;
float_t max3;
int32_t imodStamp;
int32_t imodFlags;
int16_t idtype;
int16_t lens;
int16_t nd1; /* Devide by 100 to get float value. */
int16_t nd2;
int16_t vd1;
int16_t vd2;
float_t tiltangles[6]; /* 0,1,2 = original: 3,4,5 = current */
/* MRC 2000 standard */
float_t origin[3];
char cmap[4];
char machinestamp[4];
float_t rms;
int32_t nlabl; // number of labels
char labels[10][80];
} MrcHeader;
MRCHeader& mrcParse(const char * data, Array& array) {
MRCHeader& header = *(MRCHeader *)data;
// check for byte swap:
bool swapped =
(header.nx <= 0 || header.ny <= 0 || header.nz <= 0 ||
(header.nx > 65535 && header.ny > 65535 && header.nz > 65535) ||
header.mapx < 0 || header.mapx > 4 ||
header.mapy < 0 || header.mapy > 4 ||
header.mapz < 0 || header.mapz > 4);
// ugh.
if (swapped) {
printf("swapping byte order...\n");
swapbytes(&header.nx, 10);
swapbytes(&header.xlen, 6);
swapbytes(&header.mapx, 3);
swapbytes(&header.amin, 3);
swapbytes(&header.ispg, 2);
swapbytes(&header.next, 1);
swapbytes(&header.creatid, 1);
swapbytes(&header.nint, 4);
swapbytes(&header.min2, 4);
swapbytes(&header.imodStamp, 2);
swapbytes(&header.idtype, 6);
swapbytes(&header.tiltangles[0], 6);
swapbytes(&header.origin[0], 3);
swapbytes(&header.rms, 1);
swapbytes(&header.nlabl, 1);
}
printf("NX %d NY %d NZ %d\n", header.nx, header.ny, header.nz);
printf("mode %d\n", header.mode);
printf("startX %d startY %d startZ %d\n", header.startx, header.starty, header.startz);
printf("intervals X %d intervals Y %d intervals Z %d\n", header.mx, header.my, header.mz);
printf("angstroms X %f angstroms Y %f angstroms Z %f\n", header.xlen, header.ylen, header.zlen);
printf("axis X %d axis Y %d axis Z %d\n", header.mapx, header.mapy, header.mapz);
printf("density min %f max %f mean %f\n", header.amin, header.amax, header.amean);
printf("origin %f %f %f\n", header.origin[0], header.origin[1], header.origin[2]);
printf("map %s\n", header.cmap);
printf("machine stamp %s\n", header.machinestamp);
printf("rms %f\n", header.rms);
printf("labels %d\n", header.nlabl);
for (int i=0; i<header.nlabl; i++) {
//printf("\t%02d: %s\n", i, header.labels[i]);
}
const char * start = data + 1024;
AlloTy ty;
// set type:
switch (header.mode) {
case MRC_IMAGE_SINT8:
printf("signed int 8\n");
ty = Array::type<int8_t>();
break;
case MRC_IMAGE_SINT16:
printf("signed int 16\n");
ty = Array::type<int16_t>();
break;
case MRC_IMAGE_FLOAT32:
printf("float\n");
ty = Array::type<float_t>();
break;
case MRC_IMAGE_UINT16:
printf("unsigned int 16\n");
ty = Array::type<uint16_t>();
break;
default:
printf("MRC mode not supported\n");
break;
}
array.formatAligned(1, ty, header.nx, header.ny, header.nz, 0);
memcpy(array.data.ptr, start, array.size());
if (swapped) {
// set type:
switch (header.mode) {
case MRC_IMAGE_SINT8:
swapbytes((int8_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_SINT16:
swapbytes((int16_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_FLOAT32:
swapbytes((float_t *)array.data.ptr, array.cells());
break;
case MRC_IMAGE_UINT16:
swapbytes((uint16_t *)array.data.ptr, array.cells());
break;
default:
break;
}
}
return header;
}
int main(){
SearchPaths paths;
paths.addAppPaths();
paths.addSearchPath(paths.appPath() + "../../", true);
paths.print();
std::string mrcpath = paths.find("golgi.mrc").filepath();
printf("golgi: %s\n", mrcpath.c_str());
File f(mrcpath, "rb", true);
Array& array = tex.array();
MRCHeader& header = mrcParse(f.readAll(), array);
amean = header.amean;
win.append(*new StandardWindowKeyControls);
win.create(Window::Dim(640, 480));
iso.primitive(Graphics::TRIANGLES);
MainLoop::start();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include "common.h"
#include "bgfx_utils.h"
#include <entry/cmd.h>
#include <entry/input.h>
#include <debugdraw/debugdraw.h>
#include "camera.h"
#include <bx/uint32_t.h>
void imageCheckerboard(void* _dst, uint32_t _width, uint32_t _height, uint32_t _step, uint32_t _0, uint32_t _1)
{
uint32_t* dst = (uint32_t*)_dst;
for (uint32_t yy = 0; yy < _height; ++yy)
{
for (uint32_t xx = 0; xx < _width; ++xx)
{
uint32_t abgr = ( (xx/_step)&1) ^ ( (yy/_step)&1) ? _1 : _0;
*dst++ = abgr;
}
}
}
class DebugDrawApp : public entry::AppI
{
void init(int _argc, char** _argv) BX_OVERRIDE
{
Args args(_argc, _argv);
m_width = 1280;
m_height = 720;
m_debug = BGFX_DEBUG_TEXT;
m_reset = BGFX_RESET_VSYNC | BGFX_RESET_MSAA_X16;
bgfx::init(args.m_type, args.m_pciId);
bgfx::reset(m_width, m_height, m_reset);
// Enable m_debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
m_timeOffset = bx::getHPCounter();
cameraCreate();
const float initialPos[3] = { 0.0f, 2.0f, -12.0f };
cameraSetPosition(initialPos);
cameraSetVerticalAngle(0.0f);
ddInit();
uint8_t data[32*32*4];
imageCheckerboard(data, 32, 32, 4, 0xff808080, 0xffc0c0c0);
m_sprite = ddCreateSprite(32, 32, data);
}
virtual int shutdown() BX_OVERRIDE
{
ddDestroy(m_sprite);
ddShutdown();
cameraDestroy();
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
bool update() BX_OVERRIDE
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
int64_t now = bx::getHPCounter() - m_timeOffset;
static int64_t last = now;
const int64_t frameTime = now - last;
last = now;
const double freq = double(bx::getHPFrequency() );
const double toMs = 1000.0/freq;
const float deltaTime = float(frameTime/freq);
// Use debug font to print information about this example.
bgfx::dbgTextClear();
bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/29-debugdraw");
bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Debug draw.");
bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
// Update camera.
cameraUpdate(deltaTime, m_mouseState);
float view[16];
cameraGetViewMtx(view);
float proj[16];
// Set view and projection matrix for view 0.
const bgfx::HMD* hmd = bgfx::getHMD();
if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
{
float eye[3];
cameraGetPosition(eye);
bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);
bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection);
bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
}
else
{
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f);
bgfx::setViewTransform(0, view, proj);
bgfx::setViewRect(0, 0, 0, m_width, m_height);
}
float zero[3] = {};
float mvp[16];
float eye[] = { 5.0f, 10.0f, 5.0f };
bx::mtxLookAt(view, eye, zero);
bx::mtxProj(proj, 45.0f, float(m_width)/float(m_height), 1.0f, 15.0f);
bx::mtxMul(mvp, view, proj);
ddBegin(0);
ddDrawAxis(0.0f, 0.0f, 0.0f);
ddPush();
ddSetColor(0xff00ff00);
Aabb aabb =
{
{ 5.0f, 1.0f, 1.0f },
{ 10.0f, 5.0f, 5.0f },
};
ddDraw(aabb);
ddPop();
float time = float(now/freq);
Obb obb;
bx::mtxRotateX(obb.m_mtx, time);
ddSetWireframe(true);
ddDraw(obb);
ddSetColor(0xffffffff);
bx::mtxSRT(obb.m_mtx, 1.0f, 1.0f, 1.0f, 0.0f, time, 0.0f, 3.0f, 0.0f, 0.0f);
ddSetWireframe(false);
ddDraw(obb);
ddSetTranslate(0.0f, -2.0f, 0.0f);
ddDrawGrid(Axis::Y, zero, 20, 1.0f);
ddSetTransform(NULL);
ddDrawFrustum(mvp);
ddPush();
Sphere sphere = { { 0.0f, 5.0f, 0.0f }, 1.0f };
ddSetColor(0xfff0c0ff);
ddSetWireframe(true);
ddSetLod(3);
ddDraw(sphere);
ddSetWireframe(false);
ddSetColor(0xc0ffc0ff);
sphere.m_center[0] = -2.0f;
ddSetLod(2);
ddDraw(sphere);
ddSetColor(0xa0f0ffff);
sphere.m_center[0] = -4.0f;
ddSetLod(1);
ddDraw(sphere);
ddSetColor(0xffc0ff00);
sphere.m_center[0] = -6.0f;
ddSetLod(0);
ddDraw(sphere);
ddPop();
ddSetColor(0xffffffff);
ddPush();
{
float normal[3] = { 0.0f, 0.0f, 1.0f };
float center[3] = { -8.0f, 0.0f, 0.0f };
ddPush();
ddSetStipple(true, 1.0f, time*0.1f);
ddSetColor(0xff0000ff);
ddDrawCircle(normal, center, 1.0f, 0.5f + bx::fsin(time*10.0f) );
ddPop();
ddSetSpin(time);
ddDrawQuad(m_sprite, normal, center, 2.0f);
}
ddPop();
ddPush();
ddSetStipple(true, 1.0f, -time*0.1f);
ddDrawCircle(Axis::Z, -8.0f, 0.0f, 0.0f, 1.25f, 2.0f);
ddPop();
ddPush();
ddSetLod(UINT8_MAX);
ddPush();
ddSetSpin(time*0.3f);
{
float from[3] = { -11.0f, 4.0f, 0.0f };
float to[3] = { -13.0f, 6.0f, 1.0f };
ddDrawCone(from, to, 1.0f );
}
{
float from[3] = { -9.0f, 2.0f, -1.0f };
float to[3] = { -11.0f, 4.0f, 0.0f };
ddDrawCylinder(from, to, 0.5f );
}
ddPop();
{
float from[3] = { 0.0f, 7.0f, 0.0f };
float to[3] = { -6.0f, 7.0f, 0.0f };
ddDrawCylinder(from, to, 0.5f, true);
}
ddPop();
ddPush();
float mtx[16];
bx::mtxSRT(mtx
, 1.0f, 1.0f, 1.0f
, 0.0f, time, time*0.53f
, -10.0f, 1.0f, 10.0f
);
Cylinder cylinder =
{
{ -10.0f, 1.0f, 10.0f },
{ 0.0f, 0.0f, 0.0f },
1.0f
};
float up[3] = { 0.0f, 4.0f, 0.0f };
bx::vec3MulMtx(cylinder.m_end, up, mtx);
ddDraw(cylinder);
toAabb(aabb, cylinder);
ddSetColor(0xff0000ff);
ddDraw(aabb);
ddPop();
ddDrawOrb(-11.0f, 0.0f, 0.0f, 1.0f);
ddEnd();
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
SpriteHandle m_sprite;
int64_t m_timeOffset;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
};
ENTRY_IMPLEMENT_MAIN(DebugDrawApp);
<commit_msg>Cleanup.<commit_after>/*
* Copyright 2011-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include "common.h"
#include "bgfx_utils.h"
#include <entry/cmd.h>
#include <entry/input.h>
#include <debugdraw/debugdraw.h>
#include "camera.h"
#include <bx/uint32_t.h>
void imageCheckerboard(void* _dst, uint32_t _width, uint32_t _height, uint32_t _step, uint32_t _0, uint32_t _1)
{
uint32_t* dst = (uint32_t*)_dst;
for (uint32_t yy = 0; yy < _height; ++yy)
{
for (uint32_t xx = 0; xx < _width; ++xx)
{
uint32_t abgr = ( (xx/_step)&1) ^ ( (yy/_step)&1) ? _1 : _0;
*dst++ = abgr;
}
}
}
class DebugDrawApp : public entry::AppI
{
void init(int _argc, char** _argv) BX_OVERRIDE
{
Args args(_argc, _argv);
m_width = 1280;
m_height = 720;
m_debug = BGFX_DEBUG_TEXT;
m_reset = BGFX_RESET_VSYNC | BGFX_RESET_MSAA_X16;
bgfx::init(args.m_type, args.m_pciId);
bgfx::reset(m_width, m_height, m_reset);
// Enable m_debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
m_timeOffset = bx::getHPCounter();
cameraCreate();
const float initialPos[3] = { 0.0f, 2.0f, -12.0f };
cameraSetPosition(initialPos);
cameraSetVerticalAngle(0.0f);
ddInit();
uint8_t data[32*32*4];
imageCheckerboard(data, 32, 32, 4, 0xff808080, 0xffc0c0c0);
m_sprite = ddCreateSprite(32, 32, data);
}
virtual int shutdown() BX_OVERRIDE
{
ddDestroy(m_sprite);
ddShutdown();
cameraDestroy();
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
bool update() BX_OVERRIDE
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
int64_t now = bx::getHPCounter() - m_timeOffset;
static int64_t last = now;
const int64_t frameTime = now - last;
last = now;
const double freq = double(bx::getHPFrequency() );
const double toMs = 1000.0/freq;
const float deltaTime = float(frameTime/freq);
// Use debug font to print information about this example.
bgfx::dbgTextClear();
bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/29-debugdraw");
bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Debug draw.");
bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
// Update camera.
cameraUpdate(deltaTime, m_mouseState);
float view[16];
cameraGetViewMtx(view);
float proj[16];
// Set view and projection matrix for view 0.
const bgfx::HMD* hmd = bgfx::getHMD();
if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
{
float eye[3];
cameraGetPosition(eye);
bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye);
bgfx::setViewTransform(0, view, hmd->eye[0].projection, BGFX_VIEW_STEREO, hmd->eye[1].projection);
bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);
}
else
{
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f);
bgfx::setViewTransform(0, view, proj);
bgfx::setViewRect(0, 0, 0, m_width, m_height);
}
float zero[3] = {};
float mvp[16];
float eye[] = { 5.0f, 10.0f, 5.0f };
bx::mtxLookAt(view, eye, zero);
bx::mtxProj(proj, 45.0f, float(m_width)/float(m_height), 1.0f, 15.0f);
bx::mtxMul(mvp, view, proj);
ddBegin(0);
ddDrawAxis(0.0f, 0.0f, 0.0f);
ddPush();
ddSetColor(0xff00ff00);
Aabb aabb =
{
{ 5.0f, 1.0f, 1.0f },
{ 10.0f, 5.0f, 5.0f },
};
ddDraw(aabb);
ddPop();
float time = float(now/freq);
Obb obb;
bx::mtxRotateX(obb.m_mtx, time);
ddSetWireframe(true);
ddDraw(obb);
ddSetColor(0xffffffff);
bx::mtxSRT(obb.m_mtx, 1.0f, 1.0f, 1.0f, 0.0f, time, 0.0f, 3.0f, 0.0f, 0.0f);
ddSetWireframe(false);
ddDraw(obb);
ddSetTranslate(0.0f, -2.0f, 0.0f);
ddDrawGrid(Axis::Y, zero, 20, 1.0f);
ddSetTransform(NULL);
ddDrawFrustum(mvp);
ddPush();
Sphere sphere = { { 0.0f, 5.0f, 0.0f }, 1.0f };
ddSetColor(0xfff0c0ff);
ddSetWireframe(true);
ddSetLod(3);
ddDraw(sphere);
ddSetWireframe(false);
ddSetColor(0xc0ffc0ff);
sphere.m_center[0] = -2.0f;
ddSetLod(2);
ddDraw(sphere);
ddSetColor(0xa0f0ffff);
sphere.m_center[0] = -4.0f;
ddSetLod(1);
ddDraw(sphere);
ddSetColor(0xffc0ff00);
sphere.m_center[0] = -6.0f;
ddSetLod(0);
ddDraw(sphere);
ddPop();
ddSetColor(0xffffffff);
ddPush();
{
float normal[3] = { 0.0f, 0.0f, 1.0f };
float center[3] = { -8.0f, 0.0f, 0.0f };
ddPush();
ddSetStipple(true, 1.0f, time*0.1f);
ddSetColor(0xff0000ff);
ddDrawCircle(normal, center, 1.0f, 0.5f + bx::fsin(time*10.0f) );
ddPop();
ddSetSpin(time);
ddDrawQuad(m_sprite, normal, center, 2.0f);
}
ddPop();
ddPush();
ddSetStipple(true, 1.0f, -time*0.1f);
ddDrawCircle(Axis::Z, -8.0f, 0.0f, 0.0f, 1.25f, 2.0f);
ddPop();
ddPush();
ddSetLod(UINT8_MAX);
ddPush();
ddSetSpin(time*0.3f);
{
float from[3] = { -11.0f, 4.0f, 0.0f };
float to[3] = { -13.0f, 6.0f, 1.0f };
ddDrawCone(from, to, 1.0f );
}
{
float from[3] = { -9.0f, 2.0f, -1.0f };
float to[3] = { -11.0f, 4.0f, 0.0f };
ddDrawCylinder(from, to, 0.5f );
}
ddPop();
{
float from[3] = { 0.0f, 7.0f, 0.0f };
float to[3] = { -6.0f, 7.0f, 0.0f };
ddDrawCylinder(from, to, 0.5f, true);
}
ddPop();
ddPush();
float mtx[16];
bx::mtxSRT(mtx
, 1.0f, 1.0f, 1.0f
, 0.0f, time, time*0.53f
, -10.0f, 1.0f, 10.0f
);
Cylinder cylinder =
{
{ -10.0f, 1.0f, 10.0f },
{ 0.0f, 0.0f, 0.0f },
1.0f
};
float up[3] = { 0.0f, 4.0f, 0.0f };
bx::vec3MulMtx(cylinder.m_end, up, mtx);
ddDraw(cylinder);
toAabb(aabb, cylinder);
ddSetColor(0xff0000ff);
ddDraw(aabb);
ddPop();
ddDrawOrb(-11.0f, 0.0f, 0.0f, 1.0f);
ddEnd();
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
SpriteHandle m_sprite;
int64_t m_timeOffset;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
};
ENTRY_IMPLEMENT_MAIN(DebugDrawApp);
<|endoftext|>
|
<commit_before>/**********************************************************************
* Copyright (c) 2013-2014 Red Hat, Inc.
*
* Developed by Daynix Computing LTD.
*
* Authors:
* Dmitry Fleytman <dmitry@daynix.com>
* Pavel Gurvich <pavel@daynix.com>
*
* 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 "stdafx.h"
#include "UsbDkHelper.h"
#include "UsbDkHelperHider.h"
#include "UsbDkDataHider.h"
using namespace std;
//-------------------------------------------------------------------------------
static void ShowUsage()
{
tcout << endl;
tcout << TEXT(" UsbDkController usage:") << endl;
tcout << endl;
tcout << TEXT(" UsbDkController -i - install UsbDk driver") << endl;
tcout << TEXT(" UsbDkController -u - uninstall UsbDk driver") << endl;
tcout << TEXT(" UsbDkController -n - enumerate USB devices") << endl;
tcout << TEXT(" UsbDkController -r ID SN - Redirect device by ID and serial number") << endl;
tcout << TEXT(" UsbDkController -H VID - Hide devices by vendor ID") << endl;
tcout << endl;
}
//-------------------------------------------------------------------------------
static int Controller_InstallDriver()
{
tcout << TEXT("Installing UsbDk driver") << endl;
auto res = UsbDk_InstallDriver();
switch (res)
{
case InstallSuccess:
tcout << TEXT("UsbDk driver installation succeeded") << endl;
return 0;
case InstallFailure:
tcout << TEXT("UsbDk driver installation failed") << endl;
return 1;
case InstallSuccessNeedReboot:
tcout << TEXT("UsbDk driver installation succeeded but reboot is required in order to make it functional.") << endl;
return 2;
default:
tcout << TEXT("UsbDk driver installation returned unknown error code") << endl;
assert(0);
return 3;
}
}
//-------------------------------------------------------------------------------
static int Controller_UninstallDriver()
{
tcout << TEXT("Uninstalling UsbDk driver") << endl;
if (UsbDk_UninstallDriver())
{
tcout << TEXT("UsbDk driver uninstall succeeded") << endl;
return 0;
}
else
{
tcout << TEXT("UsbDk driver uninstall failed") << endl;
return 1;
}
}
//-------------------------------------------------------------------------------
static void Controller_DumpConfigurationDescriptors(USB_DK_DEVICE_INFO &Device)
{
for (UCHAR i = 0; i < Device.DeviceDescriptor.bNumConfigurations; i++)
{
USB_DK_CONFIG_DESCRIPTOR_REQUEST Request;
Request.ID = Device.ID;
Request.Index = i;
PUSB_CONFIGURATION_DESCRIPTOR Descriptor;
ULONG Length;
if (!UsbDk_GetConfigurationDescriptor(&Request, &Descriptor, &Length))
{
tcout << TEXT("Failed to read configuration descriptor #") << (int) i << endl;
}
else
{
tcout << TEXT("Descriptor for configuration #") << (int) i << TEXT(": size ") << Length << endl;
UsbDk_ReleaseConfigurationDescriptor(Descriptor);
}
}
}
//-------------------------------------------------------------------------------
static int Controller_EnumerateDevices()
{
PUSB_DK_DEVICE_INFO devicesArray;
ULONG numberDevices;
tcout << TEXT("Enumerate USB devices") << endl;
if (UsbDk_GetDevicesList(&devicesArray, &numberDevices))
{
tcout << TEXT("Found ") << to_tstring(numberDevices) << TEXT(" USB devices:") << endl;
for (ULONG deviceIndex = 0; deviceIndex < numberDevices; ++deviceIndex)
{
auto &Dev = devicesArray[deviceIndex];
tcout << to_tstring(deviceIndex) << TEXT(". ")
<< TEXT("FilterID: ") << Dev.FilterID << TEXT(", ")
<< TEXT("Port: ") << Dev.Port << TEXT(", ")
<< TEXT("ID: ")
<< hex
<< setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idVendor) << TEXT(":")
<< setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idProduct) << TEXT(", ")
<< dec
<< TEXT("Configs: ") << static_cast<int>(Dev.DeviceDescriptor.bNumConfigurations) << TEXT(", ")
<< TEXT("Speed: ") << static_cast<int>(Dev.Speed) << endl << TEXT("\t")
<< Dev.ID.DeviceID << TEXT(" ")
<< Dev.ID.InstanceID
<< endl;
Controller_DumpConfigurationDescriptors(Dev);
}
UsbDk_ReleaseDevicesList(devicesArray);
return 0;
}
else
{
tcout << TEXT("Enumeration failed") << endl;
return 1;
}
}
//-------------------------------------------------------------------------------
static int Controller_RedirectDevice(TCHAR *DeviceID, TCHAR *InstanceID)
{
USB_DK_DEVICE_ID deviceID;
UsbDkFillIDStruct(&deviceID, tstring2wstring(DeviceID), tstring2wstring(InstanceID));
tcout << TEXT("Redirect USB device ") << deviceID.DeviceID << TEXT(", ") << deviceID.InstanceID << endl;
HANDLE redirectedDevice = UsbDk_StartRedirect(&deviceID);
if (INVALID_HANDLE_VALUE == redirectedDevice)
{
tcout << TEXT("Redirect of USB device failed") << endl;
return 100;
}
tcout << TEXT("USB device was redirected successfully. Redirected device handle = ") << redirectedDevice << endl;
tcout << TEXT("Press some key to stop redirection");
getchar();
// STOP redirect
tcout << TEXT("Restore USB device ") << redirectedDevice << endl;
if (TRUE == UsbDk_StopRedirect(redirectedDevice))
{
tcout << TEXT("USB device redirection was stopped successfully.") << endl;
return 0;
}
else
{
tcout << TEXT("Stopping of USB device redirection failed.") << endl;
return 101;
}
}
//-------------------------------------------------------------------------------
bool Controller_ParseRule(TCHAR *RuleString, USB_DK_HIDE_RULE &Rule)
{
UNREFERENCED_PARAMETER(RuleString);
Rule.Hide = 1;
Rule.Class = ULONG64(-1);
Rule.BCD = ULONG64(-1);
Rule.PID = ULONG64(-1);
tstringstream VIDStream;
VIDStream << hex << tstring(RuleString);
if (VIDStream >> Rule.VID)
{
tcout << TEXT("Loading rule to hide devices with VID ") << hex << showbase << setw(4) << Rule.VID << endl;
return true;
}
else
{
tcout << TEXT("Invalid VID specification: ") << RuleString << endl;
return false;
}
}
static void Controller_HideDevice(TCHAR *RuleString)
{
USB_DK_HIDE_RULE Rule;
if (!Controller_ParseRule(RuleString, Rule))
{
tcout << TEXT("Hide rule parsing failed") << endl;
return;
}
auto hiderHandle = UsbDk_CreateHiderHandle();
if (hiderHandle == INVALID_HANDLE_VALUE)
{
tcout << TEXT("Faiuled to open the hider device") << endl;
return;
}
if (UsbDk_AddHideRule(hiderHandle, &Rule))
{
tcout << TEXT("Hide rule loaded succesfully. Press any key to continue.") << endl;
getchar();
}
else
{
tcout << TEXT("Failed to load hide rule.") << endl;
}
if (UsbDk_ClearHideRules(hiderHandle))
{
tcout << TEXT("Hide rules cleared successfully.") << endl;
}
else
{
tcout << TEXT("Failed to clear hide rules.") << endl;
}
UsbDk_CloseHiderHandle(hiderHandle);
}
//-------------------------------------------------------------------------------
static bool Controller_ChdirToPackageFolder()
{
TCHAR PackagePath[MAX_PATH];
auto Length = GetModuleFileName(NULL, PackagePath, ARRAY_SIZE(PackagePath));
if ((Length == 0) || (Length == ARRAY_SIZE(PackagePath)))
{
tcout << TEXT("Failed to get executable path.") << endl;
return false;
}
if (!PathRemoveFileSpec(PackagePath))
{
tcout << TEXT("Failed to get package directory.") << endl;
return false;
}
if (!SetCurrentDirectory(PackagePath))
{
auto Error = GetLastError();
tcout << TEXT("Failed to make package directory current, error: ") << Error << TEXT(".") << endl;
return false;
}
return true;
}
//-------------------------------------------------------------------------------
int __cdecl _tmain(int argc, TCHAR* argv[])
{
if (argc > 1)
{
if (!Controller_ChdirToPackageFolder())
{
return -1;
}
if (_tcsicmp(L"-i", argv[1]) == 0)
{
return Controller_InstallDriver();
}
else if (_tcsicmp(L"-u", argv[1]) == 0)
{
return Controller_UninstallDriver();
}
else if (_tcsicmp(L"-n", argv[1]) == 0)
{
return Controller_EnumerateDevices();
}
else if (_tcsicmp(L"-r", argv[1]) == 0)
{
if (argc < 4)
{
ShowUsage();
return -2;
}
return Controller_RedirectDevice(argv[2], argv[3]);
}
else if (_tcscmp(L"-H", argv[1]) == 0)
{
if (argc < 3)
{
ShowUsage();
return 0;
}
Controller_HideDevice(argv[2]);
}
else
{
ShowUsage();
return -3;
}
}
else
{
ShowUsage();
return -4;
}
}
//-------------------------------------------------------------------------------
<commit_msg>UsbDkController: Fix typo in error message<commit_after>/**********************************************************************
* Copyright (c) 2013-2014 Red Hat, Inc.
*
* Developed by Daynix Computing LTD.
*
* Authors:
* Dmitry Fleytman <dmitry@daynix.com>
* Pavel Gurvich <pavel@daynix.com>
*
* 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 "stdafx.h"
#include "UsbDkHelper.h"
#include "UsbDkHelperHider.h"
#include "UsbDkDataHider.h"
using namespace std;
//-------------------------------------------------------------------------------
static void ShowUsage()
{
tcout << endl;
tcout << TEXT(" UsbDkController usage:") << endl;
tcout << endl;
tcout << TEXT(" UsbDkController -i - install UsbDk driver") << endl;
tcout << TEXT(" UsbDkController -u - uninstall UsbDk driver") << endl;
tcout << TEXT(" UsbDkController -n - enumerate USB devices") << endl;
tcout << TEXT(" UsbDkController -r ID SN - Redirect device by ID and serial number") << endl;
tcout << TEXT(" UsbDkController -H VID - Hide devices by vendor ID") << endl;
tcout << endl;
}
//-------------------------------------------------------------------------------
static int Controller_InstallDriver()
{
tcout << TEXT("Installing UsbDk driver") << endl;
auto res = UsbDk_InstallDriver();
switch (res)
{
case InstallSuccess:
tcout << TEXT("UsbDk driver installation succeeded") << endl;
return 0;
case InstallFailure:
tcout << TEXT("UsbDk driver installation failed") << endl;
return 1;
case InstallSuccessNeedReboot:
tcout << TEXT("UsbDk driver installation succeeded but reboot is required in order to make it functional.") << endl;
return 2;
default:
tcout << TEXT("UsbDk driver installation returned unknown error code") << endl;
assert(0);
return 3;
}
}
//-------------------------------------------------------------------------------
static int Controller_UninstallDriver()
{
tcout << TEXT("Uninstalling UsbDk driver") << endl;
if (UsbDk_UninstallDriver())
{
tcout << TEXT("UsbDk driver uninstall succeeded") << endl;
return 0;
}
else
{
tcout << TEXT("UsbDk driver uninstall failed") << endl;
return 1;
}
}
//-------------------------------------------------------------------------------
static void Controller_DumpConfigurationDescriptors(USB_DK_DEVICE_INFO &Device)
{
for (UCHAR i = 0; i < Device.DeviceDescriptor.bNumConfigurations; i++)
{
USB_DK_CONFIG_DESCRIPTOR_REQUEST Request;
Request.ID = Device.ID;
Request.Index = i;
PUSB_CONFIGURATION_DESCRIPTOR Descriptor;
ULONG Length;
if (!UsbDk_GetConfigurationDescriptor(&Request, &Descriptor, &Length))
{
tcout << TEXT("Failed to read configuration descriptor #") << (int) i << endl;
}
else
{
tcout << TEXT("Descriptor for configuration #") << (int) i << TEXT(": size ") << Length << endl;
UsbDk_ReleaseConfigurationDescriptor(Descriptor);
}
}
}
//-------------------------------------------------------------------------------
static int Controller_EnumerateDevices()
{
PUSB_DK_DEVICE_INFO devicesArray;
ULONG numberDevices;
tcout << TEXT("Enumerate USB devices") << endl;
if (UsbDk_GetDevicesList(&devicesArray, &numberDevices))
{
tcout << TEXT("Found ") << to_tstring(numberDevices) << TEXT(" USB devices:") << endl;
for (ULONG deviceIndex = 0; deviceIndex < numberDevices; ++deviceIndex)
{
auto &Dev = devicesArray[deviceIndex];
tcout << to_tstring(deviceIndex) << TEXT(". ")
<< TEXT("FilterID: ") << Dev.FilterID << TEXT(", ")
<< TEXT("Port: ") << Dev.Port << TEXT(", ")
<< TEXT("ID: ")
<< hex
<< setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idVendor) << TEXT(":")
<< setw(4) << setfill(L'0') << static_cast<int>(Dev.DeviceDescriptor.idProduct) << TEXT(", ")
<< dec
<< TEXT("Configs: ") << static_cast<int>(Dev.DeviceDescriptor.bNumConfigurations) << TEXT(", ")
<< TEXT("Speed: ") << static_cast<int>(Dev.Speed) << endl << TEXT("\t")
<< Dev.ID.DeviceID << TEXT(" ")
<< Dev.ID.InstanceID
<< endl;
Controller_DumpConfigurationDescriptors(Dev);
}
UsbDk_ReleaseDevicesList(devicesArray);
return 0;
}
else
{
tcout << TEXT("Enumeration failed") << endl;
return 1;
}
}
//-------------------------------------------------------------------------------
static int Controller_RedirectDevice(TCHAR *DeviceID, TCHAR *InstanceID)
{
USB_DK_DEVICE_ID deviceID;
UsbDkFillIDStruct(&deviceID, tstring2wstring(DeviceID), tstring2wstring(InstanceID));
tcout << TEXT("Redirect USB device ") << deviceID.DeviceID << TEXT(", ") << deviceID.InstanceID << endl;
HANDLE redirectedDevice = UsbDk_StartRedirect(&deviceID);
if (INVALID_HANDLE_VALUE == redirectedDevice)
{
tcout << TEXT("Redirect of USB device failed") << endl;
return 100;
}
tcout << TEXT("USB device was redirected successfully. Redirected device handle = ") << redirectedDevice << endl;
tcout << TEXT("Press some key to stop redirection");
getchar();
// STOP redirect
tcout << TEXT("Restore USB device ") << redirectedDevice << endl;
if (TRUE == UsbDk_StopRedirect(redirectedDevice))
{
tcout << TEXT("USB device redirection was stopped successfully.") << endl;
return 0;
}
else
{
tcout << TEXT("Stopping of USB device redirection failed.") << endl;
return 101;
}
}
//-------------------------------------------------------------------------------
bool Controller_ParseRule(TCHAR *RuleString, USB_DK_HIDE_RULE &Rule)
{
UNREFERENCED_PARAMETER(RuleString);
Rule.Hide = 1;
Rule.Class = ULONG64(-1);
Rule.BCD = ULONG64(-1);
Rule.PID = ULONG64(-1);
tstringstream VIDStream;
VIDStream << hex << tstring(RuleString);
if (VIDStream >> Rule.VID)
{
tcout << TEXT("Loading rule to hide devices with VID ") << hex << showbase << setw(4) << Rule.VID << endl;
return true;
}
else
{
tcout << TEXT("Invalid VID specification: ") << RuleString << endl;
return false;
}
}
static void Controller_HideDevice(TCHAR *RuleString)
{
USB_DK_HIDE_RULE Rule;
if (!Controller_ParseRule(RuleString, Rule))
{
tcout << TEXT("Hide rule parsing failed") << endl;
return;
}
auto hiderHandle = UsbDk_CreateHiderHandle();
if (hiderHandle == INVALID_HANDLE_VALUE)
{
tcout << TEXT("Failed to open the hider device") << endl;
return;
}
if (UsbDk_AddHideRule(hiderHandle, &Rule))
{
tcout << TEXT("Hide rule loaded succesfully. Press any key to continue.") << endl;
getchar();
}
else
{
tcout << TEXT("Failed to load hide rule.") << endl;
}
if (UsbDk_ClearHideRules(hiderHandle))
{
tcout << TEXT("Hide rules cleared successfully.") << endl;
}
else
{
tcout << TEXT("Failed to clear hide rules.") << endl;
}
UsbDk_CloseHiderHandle(hiderHandle);
}
//-------------------------------------------------------------------------------
static bool Controller_ChdirToPackageFolder()
{
TCHAR PackagePath[MAX_PATH];
auto Length = GetModuleFileName(NULL, PackagePath, ARRAY_SIZE(PackagePath));
if ((Length == 0) || (Length == ARRAY_SIZE(PackagePath)))
{
tcout << TEXT("Failed to get executable path.") << endl;
return false;
}
if (!PathRemoveFileSpec(PackagePath))
{
tcout << TEXT("Failed to get package directory.") << endl;
return false;
}
if (!SetCurrentDirectory(PackagePath))
{
auto Error = GetLastError();
tcout << TEXT("Failed to make package directory current, error: ") << Error << TEXT(".") << endl;
return false;
}
return true;
}
//-------------------------------------------------------------------------------
int __cdecl _tmain(int argc, TCHAR* argv[])
{
if (argc > 1)
{
if (!Controller_ChdirToPackageFolder())
{
return -1;
}
if (_tcsicmp(L"-i", argv[1]) == 0)
{
return Controller_InstallDriver();
}
else if (_tcsicmp(L"-u", argv[1]) == 0)
{
return Controller_UninstallDriver();
}
else if (_tcsicmp(L"-n", argv[1]) == 0)
{
return Controller_EnumerateDevices();
}
else if (_tcsicmp(L"-r", argv[1]) == 0)
{
if (argc < 4)
{
ShowUsage();
return -2;
}
return Controller_RedirectDevice(argv[2], argv[3]);
}
else if (_tcscmp(L"-H", argv[1]) == 0)
{
if (argc < 3)
{
ShowUsage();
return 0;
}
Controller_HideDevice(argv[2]);
}
else
{
ShowUsage();
return -3;
}
}
else
{
ShowUsage();
return -4;
}
}
//-------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "core/HierarchicalEA.hpp"
#include "core/CrossoverOperation.hpp"
#include "core/EndCondition.hpp"
#include "core/FitnessFunction.hpp"
#include "core/ToStringFunction.hpp"
#include "core/GeneNode.hpp"
#include "core/EvolutionarySystem.hpp"
#include "core/Genome.hpp"
#include "core/PopulationNode.hpp"
#include "core/NonEvolvingPopulationNode.hpp"
#include "core/Individual.hpp"
#include "core/MutationOperation.hpp"
#include "core/LibraryNode.hpp"
#include "core/SelectionStrategy.hpp"
#include "core/PropertiesList.hpp"
#include "core/Property.hpp"
#include "core/FitnessPropagator.hpp"
#include "core/migration/MigratoryRelationship.hpp"
#include "core/migration/TranslationFunction.hpp"
#include "core/migration/NullTranslationFunction.hpp"
#include "loci/IntLocus.hpp"
#include "loci/FloatLocus.hpp"
#include "crossovers/CutAndSpliceCrossover.hpp"
#include "crossovers/NPointCrossover.hpp"
#include "crossovers/UniformCrossover.hpp"
#include "endconditions/FitnessMatchEnd.hpp"
#include "endconditions/MaxFitnessConvergenceEnd.hpp"
#include "systems/ES.hpp"
#include "systems/GA.hpp"
#include "systems/ReplacingGA.hpp"
#include "systems/StrongIterativeReplacingGA.hpp"
#include "systems/WeakIterativeReplacingGA.hpp"
#include "systems/SSGA.hpp"
#include "systems/AccelSSGA.hpp"
#include "systems/niching/Crowding.hpp"
#include "mutations/BoundaryMutation.hpp"
#include "mutations/GaussianMutation.hpp"
#include "mutations/UniformMutation.hpp"
#include "selections/TournamentSelection.hpp"
#include "propagators/NonPropagator.hpp"
#include "propagators/DownPropagator.hpp"
#include "propagators/ApportioningPropagator.hpp"
#include "propagators/apportioning/AveragingPropagator.hpp"
#include "propagators/apportioning/SummingPropagator.hpp"
#include "propagators/apportioning/WeightedAveragePropagator.hpp"
#include "secondary-pop-nodes/annealer/SimulatedAnnealer.hpp"
#include "secondary-pop-nodes/annealer/schedules/TemperatureSchedule.hpp"
#include "secondary-pop-nodes/annealer/schedules/LinearTempSchedule.hpp"
#include "secondary-pop-nodes/annealer/schedules/ExponentialTempSchedule.hpp"
#pragma once
// Legacy
typedef PopulationNode HierarchicalGenePool;
typedef GeneNode GenePool;
typedef EvolutionarySystem GenerationModel;
typedef GA GAGeneration;
typedef ES ESGeneration;
typedef SSGA SSGAGeneration;
typedef ReplacingGA ReplacingGAGeneration;
<commit_msg>[All-Header]: Updated all-header<commit_after>#include "endconditions/FitnessMatchEnd.hpp"
#include "endconditions/IterationCountEnd.hpp"
#include "endconditions/MaxFitnessConvergenceEnd.hpp"
#include "nodes/SANode/schedules/LinearTempSchedule.hpp"
#include "nodes/SANode/schedules/ExponentialTempSchedule.hpp"
#include "nodes/SANode/SANode.hpp"
#include "nodes/SANode/TemperatureSchedule.hpp"
#include "nodes/NonOptimizingNode.hpp"
#include "nodes/EANode/EvolutionarySystem.hpp"
#include "nodes/EANode/MutationOperation.hpp"
#include "nodes/EANode/EANode.hpp"
#include "nodes/EANode/SelectionStrategy.hpp"
#include "nodes/EANode/CrossoverOperation.hpp"
#include "exception/InvalidNodeException.hpp"
#include "exception/MismatchedCountsException.hpp"
#include "exception/ValueOutOfRangeException.hpp"
#include "exception/NodeAlreadyExistsException.hpp"
#include "exception/NoNodesException.hpp"
#include "exception/NoEvolutionOrderException.hpp"
#include "propagators/apportioning/SummingPropagator.hpp"
#include "propagators/apportioning/WeightedAveragePropagator.hpp"
#include "propagators/apportioning/AveragingPropagator.hpp"
#include "propagators/ApportioningPropagator.hpp"
#include "propagators/NonPropagator.hpp"
#include "propagators/DownPropagator.hpp"
#include "mutations/BoundaryMutation.hpp"
#include "mutations/UniformMutation.hpp"
#include "mutations/GaussianMutation.hpp"
#include "selections/TournamentSelection.hpp"
#include "crossovers/UniformCrossover.hpp"
#include "crossovers/NPointCrossover.hpp"
#include "crossovers/CutAndSpliceCrossover.hpp"
#include "core/ObjectiveFunction.hpp"
#include "core/HierarchicalEA.hpp"
#include "core/ToStringFunction.hpp"
#include "core/Locus.hpp"
#include "core/Genome.hpp"
#include "core/PopulationNode.hpp"
#include "core/migration/MigratoryRelationship.hpp"
#include "core/migration/TranslationFunction.hpp"
#include "core/migration/NullTranslationFunction.hpp"
#include "core/EndCondition.hpp"
#include "systems/ES.hpp"
#include "systems/niching/Crowding.hpp"
#include "systems/niching/NichingStrategy.hpp"
#include "systems/ReplacingGA.hpp"
#include "systems/SSGA.hpp"
#include "systems/WeakIterativeReplacingGA.hpp"
#include "systems/AccelSSGA.hpp"
#include "systems/StrongIterativeReplacingGA.hpp"
#include "systems/GA.hpp"
#include "loci/IntLocus.hpp"
#include "loci/FloatLocus.hpp"
#include "loci/BoolLocus.hpp"
#include "loci/PopulationLocus.hpp"
#pragma once
<|endoftext|>
|
<commit_before>#include "hermes1d.h"
#include "legendre.h"
#include "quad_std.h"
// This test makes sure that Legendre
// polynomial starting with the linear
// one, integrated from -1 to 1 numerically,
// gives zero.
#define ERROR_SUCCESS 0
#define ERROR_FAILURE -1
int main(int argc, char* argv[])
{
// maximum poly degree of Legendre polynomials tested
int max_test_poly_degree = max(100, MAX_P);
// maximum allowed error
double max_allowed_error = 1e-12;
// loop over polynomial degrees, starting with 1
double max_actual_error = 0;
for (int poly_deg=1; poly_deg < max_test_poly_degree + 1; poly_deg++) {
// integrating the Legendre polynomial of degree 'poly_deg'
// from -1 to 1 using Gauss quadratures of orders 1, 2, ...
// MAX_P
for (int quad_order=poly_deg; quad_order < max_test_poly_degree + 1; quad_order++) {
int num_pts = g_quad_1d_std.get_num_points(quad_order);
double2 *quad_tab = g_quad_1d_std.get_points(quad_order);
double val = 0;
for (int i=0; i<num_pts; i++) {
double point_i = quad_tab[i][0];
double weight_i = quad_tab[i][1];
//val += legendre_fn_tab_1d[poly_deg](point_i) * weight_i;
val += calc_leg_pol_val(point_i, poly_deg) * weight_i;
}
printf("poly_deg = %d, quad_order = %d, integral = %g\n",
poly_deg, quad_order, val);
if (max_actual_error > max_allowed_error) {
printf("Failure!\n");
return ERROR_FAILURE;
}
if (fabs(val) > max_actual_error) max_actual_error = fabs(val);
}
}
printf("Success!\n");
return ERROR_SUCCESS;
}
<commit_msg>Forgot to add file tests/legendre-1/main.cpp to commit.<commit_after>#include "hermes1d.h"
#include "legendre.h"
#include "quad_std.h"
// This test makes sure that all Legendre
// polynomials (starting with the linear
// one) integrated from -1 to 1 numerically
// with all quadrature rules of same or
// higher order, give zero.
#define ERROR_SUCCESS 0
#define ERROR_FAILURE -1
int main(int argc, char* argv[])
{
// maximum poly degree of Legendre polynomials tested
int max_test_poly_degree = max(100, MAX_P);
// maximum allowed error
double max_allowed_error = 1e-12;
// loop over polynomial degrees, starting with 1
double max_actual_error = 0;
for (int poly_deg=1; poly_deg < max_test_poly_degree + 1; poly_deg++) {
// integrating the Legendre polynomial of degree 'poly_deg'
// from -1 to 1 using Gauss quadratures of orders 1, 2, ...
// MAX_P
for (int quad_order=poly_deg; quad_order < max_test_poly_degree + 1; quad_order++) {
int num_pts = g_quad_1d_std.get_num_points(quad_order);
double2 *quad_tab = g_quad_1d_std.get_points(quad_order);
double val = 0;
for (int i=0; i<num_pts; i++) {
double point_i = quad_tab[i][0];
double weight_i = quad_tab[i][1];
//val += legendre_fn_tab_1d[poly_deg](point_i) * weight_i;
val += calc_leg_pol_val(point_i, poly_deg) * weight_i;
}
printf("poly_deg = %d, quad_order = %d, integral = %g\n",
poly_deg, quad_order, val);
if (max_actual_error > max_allowed_error) {
printf("Failure!\n");
return ERROR_FAILURE;
}
if (fabs(val) > max_actual_error) max_actual_error = fabs(val);
}
}
printf("Success!\n");
return ERROR_SUCCESS;
}
<|endoftext|>
|
<commit_before>//===-- SIPropagateImmReads.cpp - TODO: Add brief description -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TODO: Add full description
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUUtil.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
using namespace llvm;
namespace {
class SIPropagateImmReadsPass : public MachineFunctionPass {
private:
static char ID;
TargetMachine &TM;
public:
SIPropagateImmReadsPass(TargetMachine &tm) :
MachineFunctionPass(ID), TM(tm) { }
virtual bool runOnMachineFunction(MachineFunction &MF);
};
} /* End anonymous namespace */
char SIPropagateImmReadsPass::ID = 0;
FunctionPass *llvm::createSIPropagateImmReadsPass(TargetMachine &tm) {
return new SIPropagateImmReadsPass(tm);
}
bool SIPropagateImmReadsPass::runOnMachineFunction(MachineFunction &MF)
{
const SIInstrInfo * TII = static_cast<const SIInstrInfo*>(TM.getInstrInfo());
for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
BB != BB_E; ++BB) {
MachineBasicBlock &MBB = *BB;
for (MachineBasicBlock::iterator I = MBB.begin(), Next = llvm::next(I);
I != MBB.end(); I = Next, Next = llvm::next(I)) {
MachineInstr &MI = *I;
switch (MI.getOpcode()) {
case AMDIL::LOADCONST_f32:
case AMDIL::LOADCONST_i32:
break;
default:
continue;
}
/* XXX: Create and use S_MOV_IMM for SREGs */
BuildMI(MBB, I, MBB.findDebugLoc(I), TII->get(AMDIL::V_MOV_IMM))
.addOperand(MI.getOperand(0))
.addOperand(MI.getOperand(1));
MI.eraseFromParent();
}
}
}
<commit_msg>radeonsi/llvm: Silence a warning<commit_after>//===-- SIPropagateImmReads.cpp - TODO: Add brief description -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TODO: Add full description
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUUtil.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
using namespace llvm;
namespace {
class SIPropagateImmReadsPass : public MachineFunctionPass {
private:
static char ID;
TargetMachine &TM;
public:
SIPropagateImmReadsPass(TargetMachine &tm) :
MachineFunctionPass(ID), TM(tm) { }
virtual bool runOnMachineFunction(MachineFunction &MF);
};
} /* End anonymous namespace */
char SIPropagateImmReadsPass::ID = 0;
FunctionPass *llvm::createSIPropagateImmReadsPass(TargetMachine &tm) {
return new SIPropagateImmReadsPass(tm);
}
bool SIPropagateImmReadsPass::runOnMachineFunction(MachineFunction &MF)
{
const SIInstrInfo * TII = static_cast<const SIInstrInfo*>(TM.getInstrInfo());
for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
BB != BB_E; ++BB) {
MachineBasicBlock &MBB = *BB;
for (MachineBasicBlock::iterator I = MBB.begin(), Next = llvm::next(I);
I != MBB.end(); I = Next, Next = llvm::next(I)) {
MachineInstr &MI = *I;
switch (MI.getOpcode()) {
case AMDIL::LOADCONST_f32:
case AMDIL::LOADCONST_i32:
break;
default:
continue;
}
/* XXX: Create and use S_MOV_IMM for SREGs */
BuildMI(MBB, I, MBB.findDebugLoc(I), TII->get(AMDIL::V_MOV_IMM))
.addOperand(MI.getOperand(0))
.addOperand(MI.getOperand(1));
MI.eraseFromParent();
}
}
return false;
}
<|endoftext|>
|
<commit_before>#include "include/FeedbackDelegate.h"
#include <memory>
#include <QPainter>
#include <QMouseEvent>
#include "SearchObject.h"
#include "SearchResultElementFeedback.h"
#include "DualFeedbackEditor.h"
/**
* @brief Implementation of QStyledItemDelegate::paint.
* @param painter
* @param option
* @param index
*/
void FeedbackDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//painter->save();
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
QImage scaledImg = element.img.scaled(option.rect.width(), option.rect.height(), Qt::KeepAspectRatio);
painter->drawImage(option.rect.topLeft(), scaledImg);
if(element.rating == 0)
painter->setPen(Qt::black);
else if(element.rating > 0)
painter->setPen(Qt::green);
else
painter->setPen(Qt::red);
QRect imageRect(option.rect.x(), option.rect.y(), scaledImg.width(), scaledImg.height());
painter->drawRect(imageRect);
painter->setPen(QPen());
painter->drawText(imageRect, Qt::AlignRight | Qt::AlignTop, QString::number(element.rating));
}
//painter->restore();
}
/**
* @brief Implementation of QStyledItemDelegate::sizeHint.
* @param option
* @param index
* @return
*/
QSize FeedbackDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize hint;
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
hint = element.img.size();
} else {
hint = QStyledItemDelegate::sizeHint(option, index);
}
return hint;
}
/**
* @brief Implementation of QStyledItemDelegate::createEditor.
* @param parent
* @param option
* @param index
* @return
*/
QWidget *FeedbackDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QWidget* editor;
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
DualFeedbackEditor* dfEditor = new DualFeedbackEditor(parent);
connect(dfEditor, &DualFeedbackEditor::feedbackChanged, this, &FeedbackDelegate::commit);
editor = dfEditor;
} else {
editor = QStyledItemDelegate::createEditor(parent, option, index);
}
return editor;
}
/**
* @brief Implementation of QStyledItemDelegate::setEditorData.
* @param editor
* @param index
*/
void FeedbackDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
FeedbackEditor* e = qobject_cast<FeedbackEditor*>(editor);
e->setFeedback(element.rating);
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
/**
* @brief Implementation of QStyledItemDelegate::updateEditorGeometry.
* @param editor
* @param option
* @param index
*/
void FeedbackDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyledItemDelegate::updateEditorGeometry(editor, option, index);
}
/**
* @brief Implementation of QStyledItemDelegate::setModelData.
* @param editor
* @param model
* @param index
*/
void FeedbackDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if(index.data().canConvert<SearchResultElementFeedback>()){
FeedbackEditor* e = qobject_cast<FeedbackEditor*>(editor);
model->setData(index, e->getFeedback());
} else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void FeedbackDelegate::commit()
{
FeedbackEditor* editor = qobject_cast<FeedbackEditor*>(sender());
emit commitData(editor);
}
<commit_msg>Changed appearance of search results.<commit_after>#include "include/FeedbackDelegate.h"
#include <memory>
#include <QPainter>
#include <QMouseEvent>
#include "SearchObject.h"
#include "SearchResultElementFeedback.h"
#include "DualFeedbackEditor.h"
/**
* @brief Implementation of QStyledItemDelegate::paint.
* @param painter
* @param option
* @param index
*/
void FeedbackDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
QImage scaledImg = element.img.scaled(option.rect.width(), option.rect.height(), Qt::KeepAspectRatio);
painter->drawImage(option.rect.topLeft(), scaledImg);
if(element.rating == 0)
painter->setPen(Qt::black);
else if(element.rating > 0)
painter->setPen(Qt::green);
else
painter->setPen(Qt::red);
QPen pen = painter->pen();
pen.setWidth(3);
painter->setPen(pen);
QRect imageRect(option.rect.x(), option.rect.y(), scaledImg.width(), scaledImg.height());
painter->drawRect(imageRect);
painter->setPen(QPen());
}
}
/**
* @brief Implementation of QStyledItemDelegate::sizeHint.
* @param option
* @param index
* @return
*/
QSize FeedbackDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize hint;
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
hint = element.img.size();
} else {
hint = QStyledItemDelegate::sizeHint(option, index);
}
return hint;
}
/**
* @brief Implementation of QStyledItemDelegate::createEditor.
* @param parent
* @param option
* @param index
* @return
*/
QWidget *FeedbackDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QWidget* editor;
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
DualFeedbackEditor* dfEditor = new DualFeedbackEditor(parent);
connect(dfEditor, &DualFeedbackEditor::feedbackChanged, this, &FeedbackDelegate::commit);
editor = dfEditor;
} else {
editor = QStyledItemDelegate::createEditor(parent, option, index);
}
return editor;
}
/**
* @brief Implementation of QStyledItemDelegate::setEditorData.
* @param editor
* @param index
*/
void FeedbackDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if(index.data().canConvert<SearchResultElementFeedback>()){
SearchResultElementFeedback element = index.data().value<SearchResultElementFeedback>();
FeedbackEditor* e = qobject_cast<FeedbackEditor*>(editor);
e->setFeedback(element.rating);
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
/**
* @brief Implementation of QStyledItemDelegate::updateEditorGeometry.
* @param editor
* @param option
* @param index
*/
void FeedbackDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyledItemDelegate::updateEditorGeometry(editor, option, index);
}
/**
* @brief Implementation of QStyledItemDelegate::setModelData.
* @param editor
* @param model
* @param index
*/
void FeedbackDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
if(index.data().canConvert<SearchResultElementFeedback>()){
FeedbackEditor* e = qobject_cast<FeedbackEditor*>(editor);
model->setData(index, e->getFeedback());
} else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void FeedbackDelegate::commit()
{
FeedbackEditor* editor = qobject_cast<FeedbackEditor*>(sender());
emit commitData(editor);
}
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/bigtable/kernels/bigtable_lib.h"
namespace tensorflow {
Status GrpcStatusToTfStatus(const ::grpc::Status& status) {
if (status.ok()) {
return Status::OK();
}
auto grpc_code = status.error_code();
if (status.error_code() == ::grpc::StatusCode::ABORTED ||
status.error_code() == ::grpc::StatusCode::UNAVAILABLE ||
status.error_code() == ::grpc::StatusCode::OUT_OF_RANGE) {
grpc_code = ::grpc::StatusCode::INTERNAL;
}
return Status(static_cast<::tensorflow::error::Code>(status.error_code()),
strings::StrCat("Error reading from Cloud Bigtable: ",
status.error_message(),
" (Details: ", status.error_details(), ")"));
}
string RegexFromStringSet(const std::vector<string>& strs) {
CHECK(!strs.empty()) << "The list of strings to turn into a regex was empty.";
std::unordered_set<string> uniq(strs.begin(), strs.end());
if (uniq.size() == 1) {
return *uniq.begin();
}
return str_util::Join(uniq, "|");
}
} // namespace tensorflow
<commit_msg>[tf.data / Cloud Bigtable]: Improve error messages.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/contrib/bigtable/kernels/bigtable_lib.h"
namespace tensorflow {
Status GrpcStatusToTfStatus(const ::grpc::Status& status) {
if (status.ok()) {
return Status::OK();
}
auto grpc_code = status.error_code();
if (status.error_code() == ::grpc::StatusCode::ABORTED ||
status.error_code() == ::grpc::StatusCode::UNAVAILABLE ||
status.error_code() == ::grpc::StatusCode::OUT_OF_RANGE) {
grpc_code = ::grpc::StatusCode::INTERNAL;
}
return Status(static_cast<::tensorflow::error::Code>(status.error_code()),
strings::StrCat("Error reading from Cloud Bigtable: ",
status.error_message()));
}
string RegexFromStringSet(const std::vector<string>& strs) {
CHECK(!strs.empty()) << "The list of strings to turn into a regex was empty.";
std::unordered_set<string> uniq(strs.begin(), strs.end());
if (uniq.size() == 1) {
return *uniq.begin();
}
return str_util::Join(uniq, "|");
}
} // namespace tensorflow
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2012
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
using std::string;
#include <utility>
using std::make_pair;
#include <vector>
using std::vector;
#include <stdexcept>
using std::out_of_range;
#include <cmath>
#include <Timer.hpp>
using isa::utils::Timer;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::toStringValue;
#ifndef KERNEL_HPP
#define KERNEL_HPP
namespace isa {
namespace OpenCL {
template< typename T > class Kernel {
public:
Kernel(string name, string dataType);
~Kernel();
inline void bindOpenCL(cl::Context * context, cl::Device * device, cl::CommandQueue * queue);
inline void setAsync(bool asy);
inline void setNvidia(bool nvd);
inline string getName() const;
inline string getCode() const;
inline string getDataType() const;
inline string getBuildLog() const;
char * getBinary(unsigned int binary);
inline Timer& getTimer();
inline double getArithmeticIntensity() const;
inline double getGFLOP() const;
inline double getGB() const;
inline double getGFLOPs() const;
inline double getGFLOPsErr() const;
inline double getGBs() const;
inline double getGBsErr() const;
protected:
void compile() throw (OpenCLError);
template< typename A > inline void setArgument(unsigned int id, A param) throw (OpenCLError);
void run(cl::NDRange & globalSize, cl::NDRange & localSize) throw (OpenCLError);
bool async;
bool nvidia;
string name;
string * code;
string dataType;
string buildLog;
cl::Kernel * kernel;
cl::Context * clContext;
cl::Device * clDevice;
cl::CommandQueue * clCommands;
cl::Event clEvent;
Timer timer;
vector< char * > binaries;
double arInt;
double gflop;
double gb;
double gflops;
double gflopsErr;
double gbs;
double gbsErr;
};
// Implementation
template< typename T > Kernel< T >::Kernel(string name, string dataType) : async(false), nvidia(false), name(name), code(0), dataType(dataType), buildLog(string()), kernel(0), clContext(0), clDevice(0), clCommands(0), clEvent(cl::Event()), timer(Timer(name)), binaries(vector< char * >()), arInt(0.0), gflop(0.0), gb(0.0), gflops(0.0), gflopsErr(0.0), gbs(0.0), gbsErr(0.0) {}
template< typename T > Kernel< T >::~Kernel() {
delete code;
delete kernel;
for ( std::vector< char * >::iterator item = binaries.begin(); item != binaries.end(); item++ ) {
delete [] *item;
}
}
template< typename T > void Kernel< T >::compile() throw (OpenCLError) {
cl::Program *program = 0;
try {
cl::Program::Sources sources(1, make_pair(code->c_str(), code->length()));
program = new cl::Program(*clContext, sources, NULL);
if ( nvidia ) {
program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable -cl-nv-verbose", NULL, NULL);
program->getInfo(CL_PROGRAM_BINARIES, &binaries);
}
else {
program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable", NULL, NULL);
}
buildLog = program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice);
}
catch ( cl::Error err ) {
throw OpenCLError("It is not possible to build the " + name + " OpenCL program: " + program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice) + ".");
}
if ( kernel != 0 ) {
delete kernel;
}
try {
kernel = new cl::Kernel(*program, name.c_str(), NULL);
}
catch ( cl::Error err ) {
delete program;
throw OpenCLError("It is not possible to create the kernel for " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
delete program;
}
template< typename T > template< typename A > inline void Kernel< T >::setArgument(unsigned int id, A param) throw (OpenCLError) {
if ( kernel == 0 ) {
throw OpenCLError("First generate the kernel for " + name + ".");
}
try {
kernel->setArg(id, param);
}
catch ( cl::Error err ) {
throw OpenCLError("Impossible to set " + name + " arguments: " + toStringValue< cl_int >(err.err()) + ".");
}
}
template< typename T > void Kernel< T >::run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError) {
if ( kernel == 0 ) {
throw OpenCLError("First generate the kernel for " + name + ".");
}
if ( async ) {
try {
clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, NULL);
}
catch ( cl::Error err ) {
throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
}
else {
try {
timer.start();
clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, &clEvent);
clEvent.wait();
timer.stop();
if ( timer.getNrRuns() == 1 ) {
gflops = gflop / timer.getLastRunTime();
gflopsErr = 0.0;
gbs = gb / timer.getLastRunTime();
gbsErr = 0.0;
} else {
double oldGFLOPs = gflops;
double newGFLOPs = gflop / timer.getLastRunTime();
double oldGBs = gbs;
double newGBs = gb / timer.getLastRunTime();
gflops = oldGFLOPs + ((newGFLOPs - oldGFLOPs) / timer.getNrRuns());
gflopsErr += (newGFLOPs - oldGFLOPs) * (newGFLOPs - gflops);
gbs = oldGBs + ((newGBs - oldGBs) / timer.getNrRuns());
gbsErr += (newGBs - oldGBs) * (newGBs - gbs);
}
}
catch ( cl::Error err ) {
timer.reset();
throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
}
}
template< typename T > inline void Kernel< T >::bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue) {
clContext = context;
clDevice = device;
clCommands = queue;
}
template< typename T > inline void Kernel< T >::setAsync(bool asy) {
async = asy;
}
template< typename T > inline void Kernel< T >::setNvidia(bool nvd) {
nvidia = nvd;
}
template< typename T > inline string Kernel< T >::getName() const {
return name;
}
template< typename T > inline string Kernel< T >::getCode() const {
if ( code != 0 ) {
return *code;
}
return string();
}
template< typename T > inline string Kernel< T >::getDataType() const {
return dataType;
}
template< typename T > inline string Kernel< T >::getBuildLog() const {
return buildLog;
}
template< typename T > char *Kernel< T >::getBinary(unsigned int binary) {
if ( nvidia ) {
try {
return binaries.at(binary);
}
catch ( out_of_range err ) {
return 0;
}
}
return 0;
}
template< typename T > inline Timer& Kernel< T >::getTimer() {
return timer;
}
template< typename T > inline double Kernel< T >::getArithmeticIntensity() const {
return arInt;
}
template< typename T > inline double Kernel< T >::getGFLOP() const {
return gflop;
}
template< typename T > inline double Kernel< T >::getGB() const {
return gb;
}
template< typename T > inline double Kernel< T >::getGFLOPs() const {
return gflops;
}
template< typename T > inline double Kernel< T >::getGFLOPsErr() const {
return sqrt(gflopsErr / timer.getNrRuns());
}
template< typename T > inline double Kernel< T >::getGBs() const {
return gbs;
}
template< typename T > inline double Kernel< T >::getGBsErr() const {
return sqrt(gbsErr / timer.getNrRuns());
}
} // OpenCL
} // isa
#endif // KERNEL_HPP
<commit_msg>Using isa::utils::Stats to compute GFLOP/s and GB/s<commit_after>//
// Copyright (C) 2012
// Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
using std::string;
#include <utility>
using std::make_pair;
#include <vector>
using std::vector;
#include <stdexcept>
using std::out_of_range;
#include <cmath>
#include <Timer.hpp>
using isa::utils::Timer;
#include <Stats.hpp>
using isa::utils::Stats;
#include <Exceptions.hpp>
using isa::Exceptions::OpenCLError;
#include <utils.hpp>
using isa::utils::toStringValue;
#ifndef KERNEL_HPP
#define KERNEL_HPP
namespace isa {
namespace OpenCL {
template< typename T > class Kernel {
public:
Kernel(string name, string dataType);
~Kernel();
inline void bindOpenCL(cl::Context * context, cl::Device * device, cl::CommandQueue * queue);
inline void setAsync(bool asy);
inline void setNvidia(bool nvd);
inline string getName() const;
inline string getCode() const;
inline string getDataType() const;
inline string getBuildLog() const;
char * getBinary(unsigned int binary);
inline Timer& getTimer();
inline double getArithmeticIntensity() const;
inline double getGFLOP() const;
inline double getGB() const;
inline double getGFLOPs() const;
inline double getGFLOPsErr() const;
inline double getGBs() const;
inline double getGBsErr() const;
protected:
void compile() throw (OpenCLError);
template< typename A > inline void setArgument(unsigned int id, A param) throw (OpenCLError);
void run(cl::NDRange & globalSize, cl::NDRange & localSize) throw (OpenCLError);
bool async;
bool nvidia;
string name;
string * code;
string dataType;
string buildLog;
cl::Kernel * kernel;
cl::Context * clContext;
cl::Device * clDevice;
cl::CommandQueue * clCommands;
cl::Event clEvent;
Timer timer;
vector< char * > binaries;
double arInt;
double gflop;
double gb;
Stats< double > GFLOPs;
Stats< double > GBs;
};
// Implementation
template< typename T > Kernel< T >::Kernel(string name, string dataType) : async(false), nvidia(false), name(name), code(0), dataType(dataType), buildLog(string()), kernel(0), clContext(0), clDevice(0), clCommands(0), clEvent(cl::Event()), timer(Timer(name)), binaries(vector< char * >()), arInt(0.0), gflop(0.0), gb(0.0), GFLOPs(Stats< double >()), GBs(Stats< double >()) {}
template< typename T > Kernel< T >::~Kernel() {
delete code;
delete kernel;
for ( std::vector< char * >::iterator item = binaries.begin(); item != binaries.end(); item++ ) {
delete [] *item;
}
}
template< typename T > void Kernel< T >::compile() throw (OpenCLError) {
cl::Program *program = 0;
try {
cl::Program::Sources sources(1, make_pair(code->c_str(), code->length()));
program = new cl::Program(*clContext, sources, NULL);
if ( nvidia ) {
program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable -cl-nv-verbose", NULL, NULL);
program->getInfo(CL_PROGRAM_BINARIES, &binaries);
} else {
program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable", NULL, NULL);
}
buildLog = program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice);
} catch ( cl::Error err ) {
throw OpenCLError("It is not possible to build the " + name + " OpenCL program: " + program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice) + ".");
}
if ( kernel != 0 ) {
delete kernel;
}
try {
kernel = new cl::Kernel(*program, name.c_str(), NULL);
} catch ( cl::Error err ) {
delete program;
throw OpenCLError("It is not possible to create the kernel for " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
delete program;
}
template< typename T > template< typename A > inline void Kernel< T >::setArgument(unsigned int id, A param) throw (OpenCLError) {
if ( kernel == 0 ) {
throw OpenCLError("First generate the kernel for " + name + ".");
}
try {
kernel->setArg(id, param);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to set " + name + " arguments: " + toStringValue< cl_int >(err.err()) + ".");
}
}
template< typename T > void Kernel< T >::run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError) {
if ( kernel == 0 ) {
throw OpenCLError("First generate the kernel for " + name + ".");
}
if ( async ) {
try {
clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, NULL);
} catch ( cl::Error err ) {
throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
} else {
try {
timer.start();
clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, &clEvent);
clEvent.wait();
timer.stop();
GFLOPs.addElement(gflop / timer.getLastRunTime());
GBs.addElement(gb / timer.getLastRunTime());
} catch ( cl::Error err ) {
timer.reset();
throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + ".");
}
}
}
template< typename T > inline void Kernel< T >::bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue) {
clContext = context;
clDevice = device;
clCommands = queue;
}
template< typename T > inline void Kernel< T >::setAsync(bool asy) {
async = asy;
}
template< typename T > inline void Kernel< T >::setNvidia(bool nvd) {
nvidia = nvd;
}
template< typename T > inline string Kernel< T >::getName() const {
return name;
}
template< typename T > inline string Kernel< T >::getCode() const {
if ( code != 0 ) {
return *code;
}
return string();
}
template< typename T > inline string Kernel< T >::getDataType() const {
return dataType;
}
template< typename T > inline string Kernel< T >::getBuildLog() const {
return buildLog;
}
template< typename T > char *Kernel< T >::getBinary(unsigned int binary) {
if ( nvidia ) {
try {
return binaries.at(binary);
} catch ( out_of_range err ) {
return 0;
}
}
return 0;
}
template< typename T > inline Timer& Kernel< T >::getTimer() {
return timer;
}
template< typename T > inline double Kernel< T >::getArithmeticIntensity() const {
return arInt;
}
template< typename T > inline double Kernel< T >::getGFLOP() const {
return gflop;
}
template< typename T > inline double Kernel< T >::getGB() const {
return gb;
}
template< typename T > inline double Kernel< T >::getGFLOPs() const {
return GFLOPs.getAverage();
}
template< typename T > inline double Kernel< T >::getGFLOPsErr() const {
return GFLOPs.getStdDev();
}
template< typename T > inline double Kernel< T >::getGBs() const {
return GBs.getAverage();
}
template< typename T > inline double Kernel< T >::getGBsErr() const {
return GBs.getStdDev();
}
} // OpenCL
} // isa
#endif // KERNEL_HPP
<|endoftext|>
|
<commit_before>//modify maxn to the max length/9
//* can be improved
// / and % are not completely tested.
//can not support negative number
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int base=1000000000;
const int maxn=500;
struct bigint
{
int len;
int data[maxn];
inline bigint():len(0){}
inline bigint(const bigint& x):len(x.len)
{
memcpy(data,x.data,len * sizeof(int));
}
inline bigint(int x):len(0)
{
for(;x>0;x/=base)
data[len++]=x%base;
}
inline bigint& operator=(const bigint& x)
{
len=x.len;
memcpy(data, x.data, len * sizeof *data);
return *this;
}
inline int&operator[](int i){return data[i];}
inline int operator[](int i) const{return i<len?data[i]:0;}
};
inline int compare(const bigint& a, const bigint& b)
{
int i;
if(a.len!=b.len)
return a.len>b.len?1:-1;
for(i=a.len-1;i>=0&&a[i]==b[i];i--);
if(i<0)return 0;
return a[i]>b[i]?1:-1;
}
inline bool operator==(const bigint&a,const bigint&b){return compare(a,b)==0;}
inline bool operator!=(const bigint&a,const bigint&b){return compare(a,b)!=0;}
inline bool operator> (const bigint&a,const bigint&b){return compare(a,b)>0;}
inline bool operator< (const bigint&a,const bigint&b){return compare(a,b)<0;}
inline bool operator>=(const bigint&a,const bigint&b){return compare(a,b)>=0;}
inline bool operator<=(const bigint&a,const bigint&b){return compare(a,b)<=0;}
inline bigint operator+(const bigint&a,const bigint&b)
{
bigint c;
int i;
int x=0;
for(i=0;i<a.len||i<b.len||x>0;i++)
{
if(i<a.len)x+=a[i];
if(i<b.len)x+=b[i];
if(x>=base)
{
x-=base;
c[i]=x;
x=1;
}
else
{
c[i]=x;
x=0;
}
}
c.len=i;
return c;
}
inline bigint operator-(const bigint&a,const bigint&b)
{
bigint c;
int x=0;
c.len=a.len;
for(int i=0;i<c.len;i++)
{
c[i]=a[i]-x;
if(i<b.len)c[i]-=b[i];
if(c[i]<0)
{
x=1;
c[i]+=base;
}
else
x=0;
}
while(c.len>0&&c[c.len-1]==0)c.len--;
return c;
}
inline bigint operator*(const bigint&a,const int b)
{
int i;
if(b==0)return 0;
bigint c;
long long x=0;
for(i=0;i<a.len||x>0;i++)
{
if(i<a.len)x+=(long long)(a[i])*b;
c[i]=x%base;
x/=base;
}
c.len=i;
return c;
}
inline bigint operator*(const bigint&a,const bigint&b)
{
if(!b.len)return 0;
bigint c;
for(int i=0;i<a.len;i++)
{
long long x=0;
for(int j=0;j<b.len||x>0;j++)
{
if(j<b.len)x+=(long long)(a[i])*b[j];
if(i+j<c.len)x+=c[i+j];
if(i+j>=c.len)
c[c.len++]=x%base;
else
c[i+j]=x%base;
x/=base;
}
}
return c;
}
inline bigint operator/(const bigint&a,const int b)
{
bigint c;
long long x=0;
for(int i=a.len-1;i>=0;i--)
{
x=x*base+a[i];
c[i]=x/b;
x%=b;
}
c.len=a.len;
while(c.len>0&&c[c.len-1]==0)c.len--;
return c;
}
inline bigint operator/(const bigint&a,const bigint&b)
{
bigint c,x=0;
int l,r,mid;
for(int i=a.len-1;i>=0;i--)
{
x=x*base+a[i];
l=0;
r=base-1;
while(l<=r)
{
mid=(l+r)>>1;
if(compare(b*mid,x)<=0)
l=mid+1;
else
r=mid-1;
}
c[i]=r;
x=x-b*r;
}
c.len=a.len;
while(c.len>0&&c[c.len-1]==0)c.len--;
return c;
}
inline bigint operator%(const bigint&a,const bigint&b)
{
bigint c,x;
c=a/b;
x=a-b*c;
return x;
}
inline bigint gcd(bigint a,bigint b)
{
return b==0?a:gcd(b,a%b);
}
inline istream&operator>>(istream&input,bigint& x)
{
char c;
for(x=0;input>>c;)
{
x=x*10+(c-'0');
if(input.peek()<=' ')break;
}
return input;
}
inline ostream&operator<<(ostream&output,const bigint&x)
{
output<<(x.len==0?0:x[x.len-1]);
for(int i=x.len-2;i>=0;i--)
for(int j=base/10;j>0;j/=10)
output<<x[i]/j%10;
return output;
}
/*
bigint a,b;
int main()
{
cin>>a>>b; //input
cout<<a+b<<endl; //output a+b
cout<<a-b<<endl; //output a-b
cout<<a*b<<endl; //output a*b
cout<<a/b<<endl; //output a/b
cout<<a%b<<endl; //output a%b
if(a<b)cout<<1<<endl; //compare numbers
return 0;
}
*/
<commit_msg>Delete BigInt.cpp<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
class tst_QSparqlEndpoint : public QObject
{
Q_OBJECT
public:
tst_QSparqlEndpoint();
virtual ~tst_QSparqlEndpoint();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void query_places_of_birth();
void construct_current_members();
void ask_current_member();
void query_with_error();
};
tst_QSparqlEndpoint::tst_QSparqlEndpoint()
{
}
tst_QSparqlEndpoint::~tst_QSparqlEndpoint()
{
}
void tst_QSparqlEndpoint::initTestCase()
{
// For running the test without installing the plugins. Should work in
// normal and vpath builds.
QCoreApplication::addLibraryPath("../../../plugins");
// Check for a proxy
QString url = getenv("http_proxy");
if (!url.isEmpty()) {
qDebug() << "Proxy found:"<<url;
QUrl proxyUrl(url);
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(proxyUrl.host());
proxy.setPort(proxyUrl.port());
QNetworkProxy::setApplicationProxy(proxy);
qDebug() << "Proxy Setup";
}
}
void tst_QSparqlEndpoint::cleanupTestCase()
{
}
void tst_QSparqlEndpoint::init()
{
}
void tst_QSparqlEndpoint::cleanup()
{
}
void tst_QSparqlEndpoint::query_places_of_birth()
{
QSparqlConnectionOptions options;
options.setHostName("dbpedia.org");
QSparqlConnection conn("QSPARQL_ENDPOINT", options);
QSparqlQuery q("SELECT DISTINCT ?Object ?PlaceOfBirth "
"WHERE { "
"<http://dbpedia.org/resource/The_Beatles> <http://dbpedia.org/property/currentMembers> ?Object . "
"?Object <http://dbpedia.org/ontology/birthPlace> ?PlaceOfBirth . }");
QSparqlResult* r = conn.exec(q);
QVERIFY(r != 0);
QCOMPARE(r->hasError(), false);
r->waitForFinished(); // this test is synchronous only
QCOMPARE(r->hasError(), false);
// dbpedia gives 5 results for the query, rather than 4
// so comment this out for now
//QCOMPARE(r->size(), 4);
QHash<QString, QString> placesOfBirth;
while (r->next()) {
QCOMPARE(r->current().count(), 2);
placesOfBirth[r->current().binding(0).toString()] = r->current().binding(1).toString();
}
// ringo isn't getting his place of birth returned
// so comment this out for now
// QCOMPARE(placesOfBirth.size(), 4);
// George Harrison is having several locations for places of birth returned, so comment this out for now
// QCOMPARE(placesOfBirth["<http://dbpedia.org/resource/George_Harrison>"], QString("<http://dbpedia.org/resource/Wavertree>"));
QCOMPARE(placesOfBirth["<http://dbpedia.org/resource/John_Lennon>"], QString("<http://dbpedia.org/resource/Liverpool>"));
// Commented out due to fault with dbpedia
//QCOMPARE(placesOfBirth["<http://dbpedia.org/resource/Ringo_Starr>"], QString("<http://dbpedia.org/resource/Dingle%252C_Liverpool>"));
QCOMPARE(placesOfBirth["<http://dbpedia.org/resource/Paul_McCartney>"], QString("<http://dbpedia.org/resource/Liverpool>"));
delete r;
}
void tst_QSparqlEndpoint::construct_current_members()
{
QSparqlConnectionOptions options;
options.setHostName("dbpedia.org");
QSparqlConnection conn("QSPARQL_ENDPOINT", options);
QSparqlQuery q("CONSTRUCT { <http://dbpedia.org/resource/The_Beatles> <http://dbpedia.org/property/currentMembers> ?Object } "
"WHERE { <http://dbpedia.org/resource/The_Beatles> <http://dbpedia.org/property/currentMembers> ?Object . }",
QSparqlQuery::ConstructStatement );
QSparqlResult* r = conn.exec(q);
QVERIFY(r != 0);
QCOMPARE(r->hasError(), false);
r->waitForFinished(); // this test is synchronous only
QCOMPARE(r->hasError(), false);
QCOMPARE(r->isGraph(), true);
QCOMPARE(r->size(), 4);
QStringList currentMembers;
currentMembers << QLatin1String("<http://dbpedia.org/resource/George_Harrison>");
currentMembers << QLatin1String("<http://dbpedia.org/resource/John_Lennon>");
currentMembers << QLatin1String("<http://dbpedia.org/resource/Ringo_Starr>");
currentMembers << QLatin1String("<http://dbpedia.org/resource/Paul_McCartney>");
while (r->next()) {
QCOMPARE(r->current().count(), 3);
QCOMPARE(r->current().binding(0).name(), QString("s"));
QCOMPARE(r->current().binding(0).toString(), QString("<http://dbpedia.org/resource/The_Beatles>"));
QCOMPARE(r->current().binding(1).name(), QString("p"));
QCOMPARE(r->current().binding(1).toString(), QString("<http://dbpedia.org/property/currentMembers>"));
QCOMPARE(r->current().binding(2).name(), QString("o"));
// Commented out due to fault with dbpedia
//QCOMPARE((bool) currentMembers.contains(r->current().binding(2).toString()), true);
}
delete r;
}
void tst_QSparqlEndpoint::ask_current_member()
{
QSparqlConnectionOptions options;
options.setHostName("dbpedia.org");
QSparqlConnection conn("QSPARQL_ENDPOINT", options);
QSparqlQuery add1("ASK { <http://dbpedia.org/resource/The_Beatles> <http://dbpedia.org/property/currentMembers> <http://dbpedia.org/resource/George_Harrison> . }",
QSparqlQuery::AskStatement);
QSparqlResult* r = conn.exec(add1);
QVERIFY(r != 0);
QCOMPARE(r->hasError(), false);
r->waitForFinished(); // this test is synchronous only
QCOMPARE(r->hasError(), false);
QCOMPARE(r->isBool(), true);
QCOMPARE(r->boolValue(), true);
delete r;
QSparqlQuery add2("ASK { <http://dbpedia.org/resource/The_Beatles> <http://dbpedia.org/property/currentMembers> <http://dbpedia.org/resource/Pete_Best> . }",
QSparqlQuery::AskStatement);
r = conn.exec(add2);
QVERIFY(r != 0);
QCOMPARE(r->hasError(), false);
r->waitForFinished(); // this test is synchronous only
QCOMPARE(r->hasError(), false);
QCOMPARE(r->boolValue(), false);
delete r;
}
void tst_QSparqlEndpoint::query_with_error()
{
QSparqlConnectionOptions options;
options.setHostName("dbpedia.org");
QSparqlConnection conn("QSPARQL_ENDPOINT", options);
QSparqlQuery q("this is not a valid query");
QSparqlResult* r = conn.exec(q);
QVERIFY(r != 0);
QCOMPARE(r->hasError(), false);
r->waitForFinished(); // this test is synchronous only
QCOMPARE(r->hasError(), true);
QCOMPARE(r->lastError().type(), QSparqlError::StatementError);
delete r;
}
QTEST_MAIN( tst_QSparqlEndpoint )
#include "tst_qsparql_endpoint.moc"
<commit_msg>Remove existing endpoint test cases<commit_after>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtSparql/QtSparql>
class tst_QSparqlEndpoint : public QObject
{
Q_OBJECT
public:
tst_QSparqlEndpoint();
virtual ~tst_QSparqlEndpoint();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
};
tst_QSparqlEndpoint::tst_QSparqlEndpoint()
{
}
tst_QSparqlEndpoint::~tst_QSparqlEndpoint()
{
}
void tst_QSparqlEndpoint::initTestCase()
{
// For running the test without installing the plugins. Should work in
// normal and vpath builds.
QCoreApplication::addLibraryPath("../../../plugins");
// Check for a proxy
QString url = getenv("http_proxy");
if (!url.isEmpty()) {
qDebug() << "Proxy found:"<<url;
QUrl proxyUrl(url);
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(proxyUrl.host());
proxy.setPort(proxyUrl.port());
QNetworkProxy::setApplicationProxy(proxy);
qDebug() << "Proxy Setup";
}
}
void tst_QSparqlEndpoint::cleanupTestCase()
{
}
void tst_QSparqlEndpoint::init()
{
}
void tst_QSparqlEndpoint::cleanup()
{
}
QTEST_MAIN( tst_QSparqlEndpoint )
#include "tst_qsparql_endpoint.moc"
<|endoftext|>
|
<commit_before>// Petter Strandmark 2013
// petter.strandmark@gmail.com
//
// Dantzig, G B, chapter 3.3 in Linear Programming and Extensions,
// Princeton University Press, Princeton, New Jersey, 1963.
// http://en.wikipedia.org/wiki/AMPL
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
#include <easy-ip.h>
// In order to have two-dimensional "arrays" (maps).
pair<string, string> operator , (string p1, string p2)
{
return make_pair(p1, p2);
}
void main_program()
{
IP lp;
typedef string Place;
Place seattle = "Seattle";
Place san_diego = "San Diego";
Place new_york = "New York";
Place chicago = "Chicago";
Place topeka = "Topeka";
set<Place> all_places;
all_places.insert(seattle);
all_places.insert(san_diego);
all_places.insert(new_york);
all_places.insert(chicago);
all_places.insert(topeka);
map<Place, double> market_demand;
market_demand[new_york] = 325;
market_demand[chicago] = 300;
market_demand[topeka] = 275;
map<Place, double> plant_capacity;
plant_capacity[seattle] = 350;
plant_capacity[san_diego] = 600;
map< pair<Place, Place>, double> distance;
distance[seattle, new_york] = 2.5;
distance[san_diego, new_york] = 2.5;
distance[seattle, chicago] = 1.7;
distance[san_diego, chicago] = 1.8;
distance[seattle, topeka] = 2.5;
distance[san_diego, topeka] = 2.5;
map< pair<Place, Place>, Variable> shipment;
Sum cost = 0;
for (auto p : all_places) {
for (auto m : all_places) {
shipment[p, m] = lp.add_variable(IP::Real);
lp.set_bounds(0, shipment[p, m], 1e10);
cost += shipment[p, m] * 90 * distance[p, m] / 1000;
}
}
// Observe supply limit at p.
for (auto p : all_places) {
Sum leaving_plant = 0;
for (auto m : all_places) {
leaving_plant += shipment[p, m];
}
lp.add_constraint(leaving_plant <= plant_capacity[p]);
}
// Satisfy demand at market m.
for (auto m : all_places) {
Sum arriving_to_market = 0;
for (auto p : all_places) {
arriving_to_market += shipment[p, m];
}
lp.add_constraint(arriving_to_market >= market_demand[m]);
}
// Solve linear program.
lp.solve();
for (auto p : all_places) {
for (auto m : all_places) {
if (shipment[p, m].value() > 0.1) {
std::cout << p << " ships " << shipment[p, m]
<< " units to " << m << std::endl;
}
}
}
cout << "Cost is " << cost << endl;
}
int main()
{
try {
main_program();
}
catch (std::exception& err) {
std::cerr << "ERROR: " << err.what() << std::endl;
}
}
<commit_msg>Newline in transportation example.<commit_after>// Petter Strandmark 2013
// petter.strandmark@gmail.com
//
// Dantzig, G B, chapter 3.3 in Linear Programming and Extensions,
// Princeton University Press, Princeton, New Jersey, 1963.
// http://en.wikipedia.org/wiki/AMPL
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
#include <easy-ip.h>
// In order to have two-dimensional "arrays" (maps).
pair<string, string> operator , (string p1, string p2)
{
return make_pair(p1, p2);
}
void main_program()
{
IP lp;
typedef string Place;
Place seattle = "Seattle";
Place san_diego = "San Diego";
Place new_york = "New York";
Place chicago = "Chicago";
Place topeka = "Topeka";
set<Place> all_places;
all_places.insert(seattle);
all_places.insert(san_diego);
all_places.insert(new_york);
all_places.insert(chicago);
all_places.insert(topeka);
map<Place, double> market_demand;
market_demand[new_york] = 325;
market_demand[chicago] = 300;
market_demand[topeka] = 275;
map<Place, double> plant_capacity;
plant_capacity[seattle] = 350;
plant_capacity[san_diego] = 600;
map< pair<Place, Place>, double> distance;
distance[seattle, new_york] = 2.5;
distance[san_diego, new_york] = 2.5;
distance[seattle, chicago] = 1.7;
distance[san_diego, chicago] = 1.8;
distance[seattle, topeka] = 2.5;
distance[san_diego, topeka] = 2.5;
map< pair<Place, Place>, Variable> shipment;
Sum cost = 0;
for (auto p : all_places) {
for (auto m : all_places) {
shipment[p, m] = lp.add_variable(IP::Real);
lp.set_bounds(0, shipment[p, m], 1e10);
cost += shipment[p, m] * 90 * distance[p, m] / 1000;
}
}
// Observe supply limit at p.
for (auto p : all_places) {
Sum leaving_plant = 0;
for (auto m : all_places) {
leaving_plant += shipment[p, m];
}
lp.add_constraint(leaving_plant <= plant_capacity[p]);
}
// Satisfy demand at market m.
for (auto m : all_places) {
Sum arriving_to_market = 0;
for (auto p : all_places) {
arriving_to_market += shipment[p, m];
}
lp.add_constraint(arriving_to_market >= market_demand[m]);
}
// Solve linear program.
lp.solve();
cout << endl << endl;
for (auto p : all_places) {
for (auto m : all_places) {
if (shipment[p, m].value() > 0.1) {
std::cout << p << " ships " << shipment[p, m]
<< " units to " << m << std::endl;
}
}
}
cout << "Cost is " << cost << endl;
}
int main()
{
try {
main_program();
}
catch (std::exception& err) {
std::cerr << "ERROR: " << err.what() << std::endl;
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Generated by the tf_library build rule. DO NOT EDIT!
//
// This file contains a test and benchmark for the function generated by
// tfcompile. All tokens of the form `{{TFCOMPILE_*}}` must be rewritten to
// real values before this file can be compiled.
//
// TFCOMPILE_HEADER : Path to the header file generated by tfcompile.
// TFCOMPILE_CPP_CLASS : Name of the C++ class generated by tfcompile.
// TFCOMPILE_NAME : Name for tests and benchmarks.
//
// The tf_library bazel macro in tfcompile.bzl performs the token rewriting, and
// generates a cc_test rule for you.
// These macros must be defined before eigen files are included.
#define EIGEN_USE_THREADS
#define EIGEN_USE_CUSTOM_THREAD_POOL
// clang-format off
#include "{{TFCOMPILE_HEADER}}" // NOLINT(whitespace/braces)
// clang-format on
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/platform/byte_order.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
// Macros that expand to tokens based on the entry point name.
// clang-format off
#define CPP_CLASS {{TFCOMPILE_CPP_CLASS}} // NOLINT(whitespace/braces)
#define TEST_NAME {{TFCOMPILE_NAME}}Test // NOLINT(whitespace/braces)
#define BM_NAME BM_{{TFCOMPILE_NAME}} // NOLINT(whitespace/braces)
// clang-format on
namespace tensorflow {
namespace tfcompile {
namespace {
void zero_buffers(XlaCompiledCpuFunction* computation) {
for (int i = 0; i < computation->num_args(); ++i) {
memset(computation->arg_data(i), 0, computation->arg_size(i));
}
}
// Trivial test that runs the generated function to ensure it doesn't crash.
TEST(TEST_NAME, NoCrash) {
Eigen::ThreadPool pool(port::MaxParallelism());
Eigen::ThreadPoolDevice device(&pool, pool.NumThreads());
CPP_CLASS computation;
computation.set_thread_pool(&device);
zero_buffers(&computation);
EXPECT_TRUE(computation.Run());
}
// Simple benchmark that repeatedly runs the generated function.
void BM_NAME(int iters) {
testing::StopTiming();
Eigen::ThreadPool pool(port::MaxParallelism());
Eigen::ThreadPoolDevice device(&pool, pool.NumThreads());
CPP_CLASS computation;
computation.set_thread_pool(&device);
zero_buffers(&computation);
testing::StartTiming();
while (--iters) {
computation.Run();
}
testing::StopTiming();
}
BENCHMARK(BM_NAME);
} // namespace
} // namespace tfcompile
} // namespace tensorflow
<commit_msg>Update benchmark to newer API<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Generated by the tf_library build rule. DO NOT EDIT!
//
// This file contains a test and benchmark for the function generated by
// tfcompile. All tokens of the form `{{TFCOMPILE_*}}` must be rewritten to
// real values before this file can be compiled.
//
// TFCOMPILE_HEADER : Path to the header file generated by tfcompile.
// TFCOMPILE_CPP_CLASS : Name of the C++ class generated by tfcompile.
// TFCOMPILE_NAME : Name for tests and benchmarks.
//
// The tf_library bazel macro in tfcompile.bzl performs the token rewriting, and
// generates a cc_test rule for you.
// These macros must be defined before eigen files are included.
#define EIGEN_USE_THREADS
#define EIGEN_USE_CUSTOM_THREAD_POOL
// clang-format off
#include "{{TFCOMPILE_HEADER}}" // NOLINT(whitespace/braces)
// clang-format on
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/platform/byte_order.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
// Macros that expand to tokens based on the entry point name.
// clang-format off
#define CPP_CLASS {{TFCOMPILE_CPP_CLASS}} // NOLINT(whitespace/braces)
#define TEST_NAME {{TFCOMPILE_NAME}}Test // NOLINT(whitespace/braces)
#define BM_NAME BM_{{TFCOMPILE_NAME}} // NOLINT(whitespace/braces)
// clang-format on
namespace tensorflow {
namespace tfcompile {
namespace {
void zero_buffers(XlaCompiledCpuFunction* computation) {
for (int i = 0; i < computation->num_args(); ++i) {
memset(computation->arg_data(i), 0, computation->arg_size(i));
}
}
// Trivial test that runs the generated function to ensure it doesn't crash.
TEST(TEST_NAME, NoCrash) {
Eigen::ThreadPool pool(port::MaxParallelism());
Eigen::ThreadPoolDevice device(&pool, pool.NumThreads());
CPP_CLASS computation;
computation.set_thread_pool(&device);
zero_buffers(&computation);
EXPECT_TRUE(computation.Run());
}
// Simple benchmark that repeatedly runs the generated function.
void BM_NAME(benchmark::State& state) {
Eigen::ThreadPool pool(port::MaxParallelism());
Eigen::ThreadPoolDevice device(&pool, pool.NumThreads());
CPP_CLASS computation;
computation.set_thread_pool(&device);
zero_buffers(&computation);
for (auto s : state) {
computation.Run();
}
}
BENCHMARK(BM_NAME);
} // namespace
} // namespace tfcompile
} // namespace tensorflow
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <vector>
#include <set>
#include <map>
#include <bh_ir.hpp>
namespace bohrium {
namespace dag {
typedef uint64_t Vertex;
//The weight class bundled with the weight graph
struct EdgeWeight
{
int64_t value;
EdgeWeight(){}
EdgeWeight(int64_t weight):value(weight){}
};
//The type declaration of the boost graphs, vertices and edges.
typedef boost::adjacency_list<boost::setS, boost::vecS, boost::bidirectionalS,
bh_ir_kernel> GraphD;
typedef boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS,
boost::no_property, EdgeWeight> GraphW;
typedef typename boost::graph_traits<GraphD>::edge_descriptor EdgeD;
typedef typename boost::graph_traits<GraphW>::edge_descriptor EdgeW;
//Forward declarations
class GraphDW;
bool path_exist(Vertex a, Vertex b, const GraphD &dag,
bool ignore_neighbors);
void pprint(const GraphDW &dag, const char filename[]);
bool cycles(const GraphD &g);
/* The GraphDW class encapsulate both a dependency graph and
* a weight graph. The public methods ensures that the two
* graphs are synchronized and are always in a valid state.
*/
class GraphDW
{
protected:
GraphD _bglD;
GraphW _bglW;
public:
//Map from base-array to the set of vertices that accesses it
const GraphD &bglD() const {return _bglD;}
const GraphW &bglW() const {return _bglW;}
/* Adds a vertex to both the dependency and weight graph.
* Additionally, both dependency and weight edges are
* added / updated as needed.
*
* @base2vertices In order to improve the build process, this
* function accepts and maintain a map from base-
* array to the set of vertices that accesses it
*/
Vertex add_vertex(const bh_ir_kernel &kernel,
std::map<bh_base*,std::set<Vertex> > &base2vertices);
/* The default constructor */
GraphDW(){};
/* Constructor based on a dependency graph.
*
* @dag The dependency graph
*/
GraphDW(const GraphD &dag);
/* Add the set of vertices 'sub_graph' to 'this' graph.
*
* @sub_graph The set of vertices in 'dag' to add
* @dag The source graph
*/
void add_from_subgraph(const std::set<Vertex> &sub_graph, const GraphDW &dag);
/* Removes both weight and dependency edge that connect v1 and v2
*
* @v1 Vertex
* @v2 Vertex
*/
void remove_edges(Vertex v1, Vertex v2)
{
{
auto e = edge(v1, v2, _bglD);
if(e.second)
boost::remove_edge(e.first, _bglD);
}
{
auto e = edge(v2, v1, _bglD);
if(e.second)
boost::remove_edge(e.first, _bglD);
}
{
auto e = edge(v1, v2, _bglW);
if(e.second)
boost::remove_edge(e.first, _bglW);
}
}
/* Clear the vertex without actually removing it.
*
* @v The Vertex
*/
void clear_vertex(Vertex v)
{
boost::clear_vertex(v, _bglD);
boost::clear_vertex(v, _bglW);
_bglD[v].clear();
}
/* Remove the previously cleared vertices.
* NB: invalidates all existing vertex and edge pointers
* and iterators
*/
void remove_cleared_vertices()
{
std::vector<Vertex> removes;
BOOST_FOREACH(Vertex v, boost::vertices(_bglD))
{
if(_bglD[v].instr_indexes().size() == 0)
{
removes.push_back(v);
}
}
//NB: because of Vertex invalidation, we have to traverse in reverse
BOOST_REVERSE_FOREACH(Vertex &v, removes)
{
boost::remove_vertex(v, _bglD);
boost::remove_vertex(v, _bglW);
}
}
/* Merge vertex 'a' and 'b' where 'b' is cleared and 'a' becomes
* the merged vertex.
*
* @a The surviving vertex
* @b The cleared vertex
* @a_before_b Whether to append or prepend the instructions of 'b' to 'a'
*/
void merge_vertices(Vertex a, Vertex b, bool a_before_b=true);
/* Merge vertex 'id_a' and 'id_b' where 'id_b' is cleared and 'id_a' becomes
* the merged vertex.
*
* @a The surviving vertex (as kernel ID)
* @b The cleared vertex (as kernel ID)
*/
void merge_vertices_by_id(uint64_t id_a, uint64_t id_b);
/* Transitive reduce the 'dag', i.e. remove all redundant edges,
*
* Complexity: O(E * (E + V))
*
* @a The first vertex
* @b The second vertex
* @dag The DAG
*/
void transitive_reduction();
};
/* Creates a new DAG based on a bhir that consist of gently fused
* instructions.
* NB: the 'bhir' must not be deallocated or moved before 'dag'
*
* Complexity: O(n^2) where 'n' is the number of instructions
*
* @bhir The BhIR
* @dag The output dag
*
* Throw logic_error() if the kernel_list wihtin 'bhir' isn't empty
*/
void from_bhir(BhIR &bhir, GraphDW &dag);
/* Creates a new DAG based on a kernel list where each vertex is a kernel.
* NB: the 'kernels' must not be deallocated or moved before 'dag'.
*
* Complexity: O(E + V)
*
* @kernels The kernel list
* @dag The output dag
*/
void from_kernels(const std::vector<bh_ir_kernel> &kernels, GraphDW &dag);
/* Fills the kernel list based on the DAG where each vertex is a kernel.
*
* Complexity: O(E + V)
*
* @dag The dag
* @kernels The kernel list output
*/
void fill_kernel_list(const GraphD &dag, std::vector<bh_ir_kernel> &kernel_list);
/* Split the 'dag' into sub-graphs that may be handle individually
*
* Complexity: O(E + V)
*
* @dag The dag
* @kernels The vector of output sub-graphs in topological order
*/
void split(const GraphDW &dag, std::vector<GraphDW> &output);
/* Determines whether there exist a path from 'a' to 'b'
*
* Complexity: O(E + V)
*
* @a The first vertex
* @b The second vertex
* @dag The DAG
* @only_long_path Only accept path of length greater than one
* @return True if there is a path
*/
bool path_exist(Vertex a, Vertex b, const GraphD &dag, bool only_long_path=false);
/* Determines whether there are cycles in the Graph
*
* Complexity: O(E + V)
*
* @g The digraph
* @return True if there are cycles in the digraph, else false
*/
bool cycles(const GraphD &g);
/* Determines the cost of the DAG.
*
* Complexity: O(E + V)
*
* @dag The DAG
* @return The cost
*/
uint64_t dag_cost(const GraphD &dag, FusePriceModel model=ENV_DECIDE);
/* Sort the weights in descending order
*
* Complexity: O(E * log E)
*
* @edges The input/output edge list
*/
void sort_weights(const GraphW &dag, std::vector<EdgeW> &edges);
/* Writes the DOT file of a DAG
*
* Complexity: O(E + V)
*
* @dag The DAG to write
* @filename The name of DOT file
*/
void pprint(const GraphDW &dag, const char filename[]);
/* Check that the 'dag' is valid
*
* @dag The dag in question
* @transitivity_allowed Is transitive edges allowed in the dag?
* @return The bool answer
*/
bool dag_validate(const GraphDW &dag, bool transitivity_allowed=true);
/* Check that the vector of 'dags' is valid
*
* @bhir The BhIR in question
* @dags The vector of dags in question
* @transitivity_allowed Is transitive edges allowed in the dag?
* @return The bool answer
*/
bool dag_validate(const BhIR &bhir, const std::vector<GraphDW> &dags, bool transitivity_allowed=true);
/* Returns the set of non-fusibles for each vertex in 'dag'
*
* @dag The dag in question
* @return The vertex-to-non-fusibles map
*/
std::map<Vertex, std::set<Vertex> > get_vertex2nonfusibles(const GraphD &dag);
/* Fuse vertices in the graph that can be fused without
* changing any future possible fusings
* NB: invalidates all existing vertex and edge pointers.
*
* Complexity: O(E * (E + V))
*
* @dag The DAG to fuse
*/
void fuse_gently(GraphDW &dag);
/* Fuse vertices in the graph greedily, which is a non-optimal
* algorithm that fuses the most costly edges in the DAG first.
* The edges in 'ignores' will not be merged.
* NB: invalidates all existing edge iterators.
*
* Complexity: O(E^2 * (E + V))
*
* @dag The DAG to fuse
* @ignores List of edges not to merge
*/
void fuse_greedy(GraphDW &dag);
void fuse_greedy(GraphDW &dag, const std::set<Vertex> *ignores);
}} //namespace bohrium::dag
<commit_msg>Remove bh_dag<commit_after><|endoftext|>
|
<commit_before>#include "Shader.h"
#include <functional>
Shader::Shader() {
// Create the program
program = glCreateProgram();
const GLchar* vshader[] =
{
"#version 140\nin vec2 LVertexPos2D; void main() { gl_Position = vec4( LVertexPos2D.x, LVertexPos2D.y, 0, 1 ); }"
};
// Create and compile the vertex shader
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, vshader, NULL);
glCompileShader(vertexShader);
glAttachShader(program, vertexShader);
// Create Frame buffer and Render buffer
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &rb);
}
void Shader::SetShader(const char* shaderSource) {
//TODO Detach current shader (if anything)
// Create and compile the fragment shader
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &shaderSource, NULL);
glCompileShader(fragmentShader);
GLint length, result;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE) {
glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &length);
GLchar* log = new GLchar[length + 1];
glGetShaderInfoLog(fragmentShader, length, &result, log);
std::string logStr(log);
delete log;
throw ShaderCompilationException(logStr);
}
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glGetShaderiv(program, GL_LINK_STATUS, &result);
if (result == GL_FALSE) {
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
GLchar* log = new GLchar[length + 1];
glGetProgramInfoLog(program, length, &result, log);
std::string logStr(log);
delete log;
throw ShaderLinkException(logStr);
}
vertAttrib = glGetAttribLocation(program, "LVertexPos2D");
}
void Shader::Render(const GLuint texture, const int w, const int h, const int scale /* = 1 */) {
// Bind framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glBindRenderbuffer(GL_RENDERBUFFER, rb);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w / scale, h / scale);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
// Bind and format the given render texture
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w / scale, h / scale, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
// Filtering!
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// Set the renderTexture as the FBO target
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
// Draw on texture
Draw();
// De-bind FBO, Render buffer and texture
glPopAttrib();
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
void Shader::Draw() {
// Enable Shader
glUseProgram(program);
// Apply uniforms
for (auto& item : uniforms) {
GLint uniformLoc = GetUniform(item.first);
item.second->Apply(uniformLoc);
}
// Render!
quad.Draw(vertAttrib);
// Disable shader
glUseProgram(0);
}
GLint Shader::GetUniform(const std::string name) {
if (uniformCache.find(name) == uniformCache.end()) {
uniformCache[name] = glGetUniformLocation(program, name.c_str());
}
return uniformCache[name];
}
ShaderCompilationException::ShaderCompilationException(const std::string what) { reason = what; }
std::string ShaderCompilationException::what() { return reason; }
ShaderLinkException::ShaderLinkException(const std::string what) { reason = what; }
std::string ShaderLinkException::what() { return reason; }<commit_msg>Unnecessary dependency<commit_after>#include "Shader.h"
Shader::Shader() {
// Create the program
program = glCreateProgram();
const GLchar* vshader[] =
{
"#version 140\nin vec2 LVertexPos2D; void main() { gl_Position = vec4( LVertexPos2D.x, LVertexPos2D.y, 0, 1 ); }"
};
// Create and compile the vertex shader
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, vshader, NULL);
glCompileShader(vertexShader);
glAttachShader(program, vertexShader);
// Create Frame buffer and Render buffer
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &rb);
}
void Shader::SetShader(const char* shaderSource) {
//TODO Detach current shader (if anything)
// Create and compile the fragment shader
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &shaderSource, NULL);
glCompileShader(fragmentShader);
GLint length, result;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE) {
glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &length);
GLchar* log = new GLchar[length + 1];
glGetShaderInfoLog(fragmentShader, length, &result, log);
std::string logStr(log);
delete log;
throw ShaderCompilationException(logStr);
}
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glGetShaderiv(program, GL_LINK_STATUS, &result);
if (result == GL_FALSE) {
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
GLchar* log = new GLchar[length + 1];
glGetProgramInfoLog(program, length, &result, log);
std::string logStr(log);
delete log;
throw ShaderLinkException(logStr);
}
vertAttrib = glGetAttribLocation(program, "LVertexPos2D");
}
void Shader::Render(const GLuint texture, const int w, const int h, const int scale /* = 1 */) {
// Bind framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glBindRenderbuffer(GL_RENDERBUFFER, rb);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w / scale, h / scale);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
// Bind and format the given render texture
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w / scale, h / scale, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
// Filtering!
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// Set the renderTexture as the FBO target
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
// Draw on texture
Draw();
// De-bind FBO, Render buffer and texture
glPopAttrib();
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
void Shader::Draw() {
// Enable Shader
glUseProgram(program);
// Apply uniforms
for (auto& item : uniforms) {
GLint uniformLoc = GetUniform(item.first);
item.second->Apply(uniformLoc);
}
// Render!
quad.Draw(vertAttrib);
// Disable shader
glUseProgram(0);
}
GLint Shader::GetUniform(const std::string name) {
if (uniformCache.find(name) == uniformCache.end()) {
uniformCache[name] = glGetUniformLocation(program, name.c_str());
}
return uniformCache[name];
}
ShaderCompilationException::ShaderCompilationException(const std::string what) { reason = what; }
std::string ShaderCompilationException::what() { return reason; }
ShaderLinkException::ShaderLinkException(const std::string what) { reason = what; }
std::string ShaderLinkException::what() { return reason; }<|endoftext|>
|
<commit_before>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "manager.hpp"
#include "logger.hpp"
#include "exception.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker() { };
virtual ~component_broker() { };
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name) {
_topic_map.insert(topic_map::value_type(topic_name, component->get_name()));
return true;
}
/**
* @brief publish data pack to specific service component
* @return times published
*/
template<typename... Args>
unsigned int publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) {
auto range = _topic_map.equal_range(to_topic);
unsigned int times = 0;
for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {
if(itr->second.compare(component->get_name())==0) {
driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());
if(_drv) {
_drv->request(api, args...);
times++;
}
else
throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);
}
}
return times;
}
private:
topic_map _topic_map;
};
#define cossb_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<commit_msg>fixed bug in publish function, topic comparison should be not equal<commit_after>/**
* @file broker.hpp
* @brief Component Broker
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details
*/
#ifndef _COSSB_BROKER_HPP_
#define _COSSB_BROKER_HPP_
#include <map>
#include <string>
#include "interface/icomponent.hpp"
#include "arch/singleton.hpp"
#include "manager.hpp"
#include "logger.hpp"
#include "exception.hpp"
using namespace std;
namespace cossb {
namespace broker {
//(topic, component name) pair
typedef multimap<string, string> topic_map;
class component_broker : public arch::singleton<component_broker> {
public:
component_broker() { };
virtual ~component_broker() { };
/**
*@brief regist component with topic
*/
bool regist(interface::icomponent* component, string topic_name) {
cossb_log->log(log::loglevel::INFO, fmt::format("Topic registered : {}", topic_name).c_str());
_topic_map.insert(topic_map::value_type(topic_name, component->get_name()));
return true;
}
/**
* @brief publish data pack to specific service component
* @return times published
*/
template<typename... Args>
unsigned int publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) {
auto range = _topic_map.equal_range(to_topic);
unsigned int times = 0;
for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) {
if(itr->second.compare(component->get_name())!=0) {
driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str());
if(_drv) {
_drv->request(api, args...);
times++;
}
else
throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND);
}
}
return times;
}
private:
topic_map _topic_map;
};
#define cossb_broker cossb::broker::component_broker::instance()
} /* namespace broker */
} /* namespace cossb */
#endif
<|endoftext|>
|
<commit_before>#include <math.h>
#include <cstdio>
#include <cstdlib>
#include "Sprite.h"
#include "Game.h"
#ifndef clamp
#define clamp(N,L,U) N=std::max((float)L,std::min(N,(float)U))
#endif
Sprite::Sprite():
destroyTexture(false)
{
texture = nullptr;
}
Sprite::Sprite(std::string file, int frameCount, float frameTime, bool enableAlpha, bool loops):
destroyTexture(false)
{
texture = nullptr;
Sprite::frameCount = frameCount;
Sprite::frameTime = frameTime;
Sprite::loops = loops;
Open(file,enableAlpha);
}
Sprite::Sprite(SDL_Texture *tex, int frameCount, float frameTime, bool enableAlpha, bool loops):
destroyTexture(true)
{
texture = tex;
Sprite::frameCount = frameCount;
Sprite::frameTime = frameTime;
Sprite::loops = loops;
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
if(enableAlpha)
SDL_SetTextureBlendMode(texture,SDL_BLENDMODE_BLEND);
}
Sprite::~Sprite() {
if (destroyTexture)
SDL_DestroyTexture(texture);
texture = nullptr;
}
void Sprite::Open(std::string file, bool enableAlpha)
{
texture = Resources::GetImage(file,enableAlpha);
if(!IsOpen())
{
printf("IMG_LoadTexture failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
if(enableAlpha)
SDL_SetTextureBlendMode(texture,SDL_BLENDMODE_BLEND);
}
void Sprite::Update(float dt)
{
timeElapsed += dt;
if(timeElapsed > frameTime && frameTime > 0)
{
if(currentFrame < frameCount)
currentFrame++;
else if(!loops)
currentFrame = 1;
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
timeElapsed = 0;
}
}
void Sprite::Render(int x, int y, float angle)
{
dstRect.w = clipRect.w*scaleX;
dstRect.h = clipRect.h*scaleY;
dstRect.x = x - ((dstRect.w-clipRect.w)/2);
dstRect.y = y - ((dstRect.h-clipRect.h)/2);
if (texture!=nullptr)
SDL_RenderCopyEx(Game::GetInstance().GetRenderer(), texture, &clipRect, &dstRect, angle, nullptr, flipHorizontal);
}
void Sprite::Render(Vec2 pos, float angle)
{
Render(pos.x,pos.y,angle);
}
void Sprite::SetClip(int x, int y, int w, int h)
{
clipRect.x = x;
clipRect.y = y;
clipRect.w = w;
clipRect.h = h;
}
SDL_Rect Sprite::GetClip()
{
return clipRect;
}
void Sprite::SetScaleX(float scale)
{
scaleX = scale;
}
void Sprite::SetScaleY(float scale)
{
scaleY = scale;
}
void Sprite::SetTransparency(float a)
{
//a = (0.0,1.0)
clamp(a,0.0f,1.0f);
SDL_SetTextureAlphaMod(texture,(unsigned short int)(255*a));
}
void Sprite::SetFrame(int frame)
{
currentFrame = frame;
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
}
void Sprite::SetFrameNormalized(float f)
{
//f = (0.0,1.0)
SetFrame(round(f*(frameCount-1)+1));
}
void Sprite::SetFrameCount(int frameCount)
{
Sprite::frameCount = frameCount;
}
void Sprite::SetFrameTime(float frameTime)
{
Sprite::frameTime = frameTime;
}
void Sprite::SetBlending(bool b)
{
SDL_SetTextureBlendMode(texture, b ? SDL_BLENDMODE_BLEND : SDL_BLENDMODE_NONE);
}
void Sprite::SetTexture(SDL_Texture* tex, bool destroyTexture_)
{
if (destroyTexture)
SDL_DestroyTexture(texture);
destroyTexture = destroyTexture_;
texture = tex;
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
}
void Sprite::Mirror(bool m)
{
flipHorizontal = m ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
}
int Sprite::GetWidth()
{
return width/frameCount*((scaleX-1)*0.5+1);
}
int Sprite::GetHeight()
{
return height*((scaleY-1)*0.5+1);
}
Vec2 Sprite::GetSize()
{
return Vec2(GetWidth(), GetHeight());
}
int Sprite::GetFrameCount()
{
return frameCount;
}
bool Sprite::Loops()
{
return !loops;
}
bool Sprite::GetMirror()
{
return flipHorizontal==SDL_FLIP_HORIZONTAL;
}
bool Sprite::IsOpen()
{
return (!texture) ? false : true;
}
<commit_msg>Aplicando folha de estilo 3<commit_after>#include <math.h>
#include <cstdio>
#include <cstdlib>
#include "Sprite.h"
#include "Game.h"
#ifndef clamp
#define clamp(N, L, U) N=std::max((float)L, std::min(N, (float)U))
#endif
Sprite::Sprite():
destroyTexture(false) {
texture = nullptr;
}
Sprite::Sprite(std::string file, int frameCount, float frameTime, bool enableAlpha, bool loops):
destroyTexture(false) {
texture = nullptr;
Sprite::frameCount = frameCount;
Sprite::frameTime = frameTime;
Sprite::loops = loops;
Open(file, enableAlpha);
}
Sprite::Sprite(SDL_Texture *tex, int frameCount, float frameTime, bool enableAlpha, bool loops):
destroyTexture(true) {
texture = tex;
Sprite::frameCount = frameCount;
Sprite::frameTime = frameTime;
Sprite::loops = loops;
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
if (enableAlpha) {
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
}
Sprite::~Sprite() {
if (destroyTexture) {
SDL_DestroyTexture(texture);
}
texture = nullptr;
}
void Sprite::Open(std::string file, bool enableAlpha) {
texture = Resources::GetImage(file, enableAlpha);
if (!IsOpen()) {
printf("IMG_LoadTexture failed: %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
if (enableAlpha) {
SDL_SetTextureBlendMode(texture,SDL_BLENDMODE_BLEND);
}
}
void Sprite::Update(float dt) {
timeElapsed += dt;
if (timeElapsed > frameTime && frameTime > 0) {
if (currentFrame < frameCount) {
currentFrame++;
} else if (!loops) {
currentFrame = 1;
}
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
timeElapsed = 0;
}
}
void Sprite::Render(int x, int y, float angle) {
dstRect.w = clipRect.w*scaleX;
dstRect.h = clipRect.h*scaleY;
dstRect.x = x - ((dstRect.w-clipRect.w)/2);
dstRect.y = y - ((dstRect.h-clipRect.h)/2);
if (texture!=nullptr) {
SDL_RenderCopyEx(Game::GetInstance().GetRenderer(), texture,
&clipRect, &dstRect, angle, nullptr, flipHorizontal);
}
}
void Sprite::Render(Vec2 pos, float angle) {
Render(pos.x, pos.y, angle);
}
void Sprite::SetClip(int x, int y, int w, int h) {
clipRect.x = x;
clipRect.y = y;
clipRect.w = w;
clipRect.h = h;
}
SDL_Rect Sprite::GetClip() {
return clipRect;
}
void Sprite::SetScaleX(float scale) {
scaleX = scale;
}
void Sprite::SetScaleY(float scale) {
scaleY = scale;
}
void Sprite::SetTransparency(float a) {
//a = (0.0, 1.0)
clamp(a, 0.0f, 1.0f);
SDL_SetTextureAlphaMod(texture, (unsigned short int)(255*a));
}
void Sprite::SetFrame(int frame) {
currentFrame = frame;
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
}
void Sprite::SetFrameNormalized(float f) {
//f = (0.0, 1.0)
SetFrame(round(f*(frameCount-1)+1));
}
void Sprite::SetFrameCount(int frameCount) {
Sprite::frameCount = frameCount;
}
void Sprite::SetFrameTime(float frameTime) {
Sprite::frameTime = frameTime;
}
void Sprite::SetBlending(bool b) {
SDL_SetTextureBlendMode(texture, b ? SDL_BLENDMODE_BLEND : SDL_BLENDMODE_NONE);
}
void Sprite::SetTexture(SDL_Texture* tex, bool destroyTexture_) {
if (destroyTexture) {
SDL_DestroyTexture(texture);
}
destroyTexture = destroyTexture_;
texture = tex;
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
SetClip((width/frameCount)*(currentFrame-1), 0, width/frameCount, height);
}
void Sprite::Mirror(bool m) {
flipHorizontal = m ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
}
int Sprite::GetWidth() {
return width/frameCount*((scaleX-1)*0.5+1);
}
int Sprite::GetHeight() {
return height*((scaleY-1)*0.5+1);
}
Vec2 Sprite::GetSize() {
return Vec2(GetWidth(), GetHeight());
}
int Sprite::GetFrameCount() {
return frameCount;
}
bool Sprite::Loops() {
return !loops;
}
bool Sprite::GetMirror() {
return flipHorizontal==SDL_FLIP_HORIZONTAL;
}
bool Sprite::IsOpen() {
return (!texture) ? false : true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWidgetRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWidgetRepresentation.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkInteractorObserver.h"
vtkCxxRevisionMacro(vtkWidgetRepresentation, "1.5");
//----------------------------------------------------------------------
vtkWidgetRepresentation::vtkWidgetRepresentation()
{
this->Renderer = NULL;
this->InteractionState = 0;
this->StartEventPosition[0] = 0;
this->StartEventPosition[1] = 0;
this->PlaceFactor = 0.5;
this->Placed = 0;
this->HandleSize = 0.05;
this->ValidPick = 0;
this->HandleSize = 0.01;
this->InitialBounds[0] = this->InitialBounds[2] = this->InitialBounds[4] = 0.0;
this->InitialBounds[1] = this->InitialBounds[3] = this->InitialBounds[5] = 1.0;
this->InitialLength = 0.0;
this->NeedToRender = 0;
}
//----------------------------------------------------------------------
vtkWidgetRepresentation::~vtkWidgetRepresentation()
{
if ( this->Renderer )
{
this->Renderer->Delete();
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::SetRenderer(vtkRenderer *ren)
{
if ( ren != this->Renderer )
{
if ( this->Renderer )
{
this->Renderer->Delete();
}
this->Renderer = ren;
if ( this->Renderer )
{
this->Renderer->Register(this);
}
this->Modified();
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::AdjustBounds(double bounds[6], double newBounds[6],
double center[3])
{
center[0] = (bounds[0] + bounds[1])/2.0;
center[1] = (bounds[2] + bounds[3])/2.0;
center[2] = (bounds[4] + bounds[5])/2.0;
newBounds[0] = center[0] + this->PlaceFactor*(bounds[0]-center[0]);
newBounds[1] = center[0] + this->PlaceFactor*(bounds[1]-center[0]);
newBounds[2] = center[1] + this->PlaceFactor*(bounds[2]-center[1]);
newBounds[3] = center[1] + this->PlaceFactor*(bounds[3]-center[1]);
newBounds[4] = center[2] + this->PlaceFactor*(bounds[4]-center[2]);
newBounds[5] = center[2] + this->PlaceFactor*(bounds[5]-center[2]);
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::ShallowCopy(vtkProp *prop)
{
vtkWidgetRepresentation *rep = vtkWidgetRepresentation::SafeDownCast(prop);
if ( rep )
{
this->SetPlaceFactor(rep->GetPlaceFactor());
this->SetHandleSize(rep->GetHandleSize());
}
this->Superclass::ShallowCopy(prop);
}
//----------------------------------------------------------------------
int vtkWidgetRepresentation::ComputeInteractionState(int, int, int)
{
return 0;
}
//----------------------------------------------------------------------
double vtkWidgetRepresentation::SizeHandlesInPixels(double factor,
double pos[3])
{
//
int i;
vtkRenderer *renderer;
if ( !this->ValidPick || !(renderer=this->Renderer) ||
!renderer->GetActiveCamera() )
{
return (this->HandleSize * factor * this->InitialLength);
}
else
{
double radius, z;
double lowerLeft[4], upperRight[4];
double focalPoint[4];
vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer,
pos[0], pos[1], pos[2],
focalPoint);
z = focalPoint[2];
double x = focalPoint[0] - this->HandleSize/2.0;
double y = focalPoint[1] - this->HandleSize/2.0;
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,lowerLeft);
x = focalPoint[0] + this->HandleSize/2.0;
y = focalPoint[1] + this->HandleSize/2.0;
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,upperRight);
for (radius=0.0, i=0; i<3; i++)
{
radius += (upperRight[i] - lowerLeft[i]) *
(upperRight[i] - lowerLeft[i]);
}
return (factor * (sqrt(radius) / 2.0));
}
}
//----------------------------------------------------------------------
double vtkWidgetRepresentation::SizeHandlesRelativeToViewport(double factor,
double pos[3])
{
int i;
vtkRenderer *renderer;
if ( !this->ValidPick || !(renderer=this->Renderer) ||
!renderer->GetActiveCamera() )
{
return (this->HandleSize * factor * this->InitialLength);
}
else
{
double radius, z;
double windowLowerLeft[4], windowUpperRight[4];
double *viewport = renderer->GetViewport();
int *winSize = renderer->GetRenderWindow()->GetSize();
double focalPoint[4];
vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer,
pos[0], pos[1], pos[2],
focalPoint);
z = focalPoint[2];
double x = winSize[0] * viewport[0];
double y = winSize[1] * viewport[1];
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,windowLowerLeft);
x = winSize[0] * viewport[2];
y = winSize[1] * viewport[3];
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,windowUpperRight);
for (radius=0.0, i=0; i<3; i++)
{
radius += (windowUpperRight[i] - windowLowerLeft[i]) *
(windowUpperRight[i] - windowLowerLeft[i]);
}
return (sqrt(radius) * factor * this->HandleSize);
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
//Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
this->Superclass::PrintSelf(os,indent);
os << indent << "Renderer: " << this->Renderer << "\n";
os << indent << "Interaction State: " << this->InteractionState << "\n";
}
<commit_msg>ENH:Properly initialize ivar StartEventPosition<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWidgetRepresentation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWidgetRepresentation.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkInteractorObserver.h"
vtkCxxRevisionMacro(vtkWidgetRepresentation, "1.6");
//----------------------------------------------------------------------
vtkWidgetRepresentation::vtkWidgetRepresentation()
{
this->Renderer = NULL;
this->InteractionState = 0;
this->StartEventPosition[0] = 0;
this->StartEventPosition[1] = 0;
this->StartEventPosition[2] = 0;
this->PlaceFactor = 0.5;
this->Placed = 0;
this->HandleSize = 0.05;
this->ValidPick = 0;
this->HandleSize = 0.01;
this->InitialBounds[0] = this->InitialBounds[2] = this->InitialBounds[4] = 0.0;
this->InitialBounds[1] = this->InitialBounds[3] = this->InitialBounds[5] = 1.0;
this->InitialLength = 0.0;
this->NeedToRender = 0;
}
//----------------------------------------------------------------------
vtkWidgetRepresentation::~vtkWidgetRepresentation()
{
if ( this->Renderer )
{
this->Renderer->Delete();
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::SetRenderer(vtkRenderer *ren)
{
if ( ren != this->Renderer )
{
if ( this->Renderer )
{
this->Renderer->Delete();
}
this->Renderer = ren;
if ( this->Renderer )
{
this->Renderer->Register(this);
}
this->Modified();
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::AdjustBounds(double bounds[6], double newBounds[6],
double center[3])
{
center[0] = (bounds[0] + bounds[1])/2.0;
center[1] = (bounds[2] + bounds[3])/2.0;
center[2] = (bounds[4] + bounds[5])/2.0;
newBounds[0] = center[0] + this->PlaceFactor*(bounds[0]-center[0]);
newBounds[1] = center[0] + this->PlaceFactor*(bounds[1]-center[0]);
newBounds[2] = center[1] + this->PlaceFactor*(bounds[2]-center[1]);
newBounds[3] = center[1] + this->PlaceFactor*(bounds[3]-center[1]);
newBounds[4] = center[2] + this->PlaceFactor*(bounds[4]-center[2]);
newBounds[5] = center[2] + this->PlaceFactor*(bounds[5]-center[2]);
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::ShallowCopy(vtkProp *prop)
{
vtkWidgetRepresentation *rep = vtkWidgetRepresentation::SafeDownCast(prop);
if ( rep )
{
this->SetPlaceFactor(rep->GetPlaceFactor());
this->SetHandleSize(rep->GetHandleSize());
}
this->Superclass::ShallowCopy(prop);
}
//----------------------------------------------------------------------
int vtkWidgetRepresentation::ComputeInteractionState(int, int, int)
{
return 0;
}
//----------------------------------------------------------------------
double vtkWidgetRepresentation::SizeHandlesInPixels(double factor,
double pos[3])
{
//
int i;
vtkRenderer *renderer;
if ( !this->ValidPick || !(renderer=this->Renderer) ||
!renderer->GetActiveCamera() )
{
return (this->HandleSize * factor * this->InitialLength);
}
else
{
double radius, z;
double lowerLeft[4], upperRight[4];
double focalPoint[4];
vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer,
pos[0], pos[1], pos[2],
focalPoint);
z = focalPoint[2];
double x = focalPoint[0] - this->HandleSize/2.0;
double y = focalPoint[1] - this->HandleSize/2.0;
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,lowerLeft);
x = focalPoint[0] + this->HandleSize/2.0;
y = focalPoint[1] + this->HandleSize/2.0;
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,upperRight);
for (radius=0.0, i=0; i<3; i++)
{
radius += (upperRight[i] - lowerLeft[i]) *
(upperRight[i] - lowerLeft[i]);
}
return (factor * (sqrt(radius) / 2.0));
}
}
//----------------------------------------------------------------------
double vtkWidgetRepresentation::SizeHandlesRelativeToViewport(double factor,
double pos[3])
{
int i;
vtkRenderer *renderer;
if ( !this->ValidPick || !(renderer=this->Renderer) ||
!renderer->GetActiveCamera() )
{
return (this->HandleSize * factor * this->InitialLength);
}
else
{
double radius, z;
double windowLowerLeft[4], windowUpperRight[4];
double *viewport = renderer->GetViewport();
int *winSize = renderer->GetRenderWindow()->GetSize();
double focalPoint[4];
vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer,
pos[0], pos[1], pos[2],
focalPoint);
z = focalPoint[2];
double x = winSize[0] * viewport[0];
double y = winSize[1] * viewport[1];
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,windowLowerLeft);
x = winSize[0] * viewport[2];
y = winSize[1] * viewport[3];
vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,x,y,z,windowUpperRight);
for (radius=0.0, i=0; i<3; i++)
{
radius += (windowUpperRight[i] - windowLowerLeft[i]) *
(windowUpperRight[i] - windowLowerLeft[i]);
}
return (sqrt(radius) * factor * this->HandleSize);
}
}
//----------------------------------------------------------------------
void vtkWidgetRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
//Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
this->Superclass::PrintSelf(os,indent);
os << indent << "Renderer: " << this->Renderer << "\n";
os << indent << "Interaction State: " << this->InteractionState << "\n";
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011 Josh A. Beam
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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 CONTACT, 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 <sstream>
#include "String.h"
using namespace std;
string
String::fromInt(int n)
{
stringstream stream;
stream << n;
return stream.str();
}
string
String::fromUInt(unsigned int n)
{
stringstream stream;
stream << n;
return stream.str();
}
string
String::hexFromUInt(unsigned int n)
{
if(n == 0)
return string("0");
string s;
while(n > 0) {
char c;
unsigned int tmp = n % 16;
if(tmp > 9)
c = ('a' + (char)(tmp - 10));
else
c = ('0' + (char)tmp);
s = c + s;
n /= 16;
}
return s;
}
int
String::toInt(const string &s)
{
int n;
stringstream stream(s);
stream >> n;
return n;
}
unsigned int
String::toUInt(const string &s)
{
unsigned int n;
stringstream stream(s);
stream >> n;
return n;
}
unsigned int
String::hexToUInt(const string &s, size_t index, size_t length)
{
unsigned int value = 0;
// set length to be one higher than the index
// of the last character to consider; if length
// is zero, go to the end of the string
if(length == 0) {
length = s.length();
} else {
length += index;
if(length > s.length())
length = s.length();
}
while(index < length) {
char c = s[index++];
if(c >= '0' && c <= '9') {
value *= 16;
value += (unsigned int)(c - '0');
} else if(c >= 'a' && c <= 'f') {
value *= 16;
value += (unsigned int)(c - 'a' + 10);
} else if(c >= 'A' && c <= 'F') {
value *= 16;
value += (unsigned int)(c - 'A' + 10);
} else {
break;
}
}
return value;
}
unsigned int
String::hexToUInt(const string &s, size_t index)
{
return hexToUInt(s, index, 0);
}
unsigned int
String::hexToUInt(const string &s)
{
return hexToUInt(s, 0, 0);
}
string
String::toLower(const string &s)
{
const char diff = 'a' - 'A';
string t = s;
size_t length = t.length();
for(size_t i = 0; i < length; ++i) {
if(t[i] >= 'A' && t[i] <= 'Z')
t[i] += diff;
}
return t;
}
string
String::toUpper(const string &s)
{
const char diff = 'A' - 'a';
string t = s;
size_t length = t.length();
for(size_t i = 0; i < length; ++i) {
if(t[i] >= 'a' && t[i] <= 'z')
t[i] += diff;
}
return t;
}
bool
String::isWhitespace(char c)
{
return (c == ' ' || c == '\t' || c == '\r' || c == '\n');
}
string
String::trim(const string &s)
{
size_t length = s.length();
if(length == 0)
return s;
// find the first non-whitespace character
size_t start = 0;
while(start != length && isWhitespace(s[start]))
++start;
// find the last non-whitespace character
size_t end = length - 1;
while(end != 0 && isWhitespace(s[end]))
--end;
if(start > end)
return s;
return s.substr(start, end - start + 1);
}
string
String::htmlEncode(const string &s)
{
const char *specialChars = "<>&\"";
size_t tmp = s.find_first_of(specialChars);
if(tmp == string::npos) {
return s;
} else {
string t = s;
do {
switch(t[tmp]) {
default:
++tmp;
break;
case '<':
t.replace(tmp, 1, "<");
tmp += 4;
break;
case '>':
t.replace(tmp, 1, ">");
tmp += 4;
break;
case '&':
t.replace(tmp, 1, "&");
tmp += 5;
break;
case '"':
t.replace(tmp, 1, """);
tmp += 6;
break;
}
} while((tmp = t.find_first_of(specialChars, tmp)) != string::npos);
return t;
}
}
string
String::urlDecode(const string &s)
{
const char *specialChars = "+%";
size_t tmp = s.find_first_of(specialChars);
if(tmp == string::npos) {
return s;
} else {
string t = s;
size_t length = t.length();
do {
switch(t[tmp]) {
default:
break;
case '+':
t[tmp] = ' ';
break;
case '%':
if(tmp + 2 < length)
t.replace(tmp, 3, 1, (char)hexToUInt(t, tmp + 1, 2));
break;
}
++tmp;
} while((tmp = t.find_first_of(specialChars, tmp)) != string::npos);
return t;
}
}
<commit_msg>Made the String::toInt and String::toUInt functions returns 0 by default when given invalid strings.<commit_after>/*
* Copyright (C) 2011 Josh A. Beam
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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 CONTACT, 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 <sstream>
#include "String.h"
using namespace std;
string
String::fromInt(int n)
{
stringstream stream;
stream << n;
return stream.str();
}
string
String::fromUInt(unsigned int n)
{
stringstream stream;
stream << n;
return stream.str();
}
string
String::hexFromUInt(unsigned int n)
{
if(n == 0)
return string("0");
string s;
while(n > 0) {
char c;
unsigned int tmp = n % 16;
if(tmp > 9)
c = ('a' + (char)(tmp - 10));
else
c = ('0' + (char)tmp);
s = c + s;
n /= 16;
}
return s;
}
int
String::toInt(const string &s)
{
int n = 0;
stringstream stream(s);
stream >> n;
return n;
}
unsigned int
String::toUInt(const string &s)
{
unsigned int n = 0;
stringstream stream(s);
stream >> n;
return n;
}
unsigned int
String::hexToUInt(const string &s, size_t index, size_t length)
{
unsigned int value = 0;
// set length to be one higher than the index
// of the last character to consider; if length
// is zero, go to the end of the string
if(length == 0) {
length = s.length();
} else {
length += index;
if(length > s.length())
length = s.length();
}
while(index < length) {
char c = s[index++];
if(c >= '0' && c <= '9') {
value *= 16;
value += (unsigned int)(c - '0');
} else if(c >= 'a' && c <= 'f') {
value *= 16;
value += (unsigned int)(c - 'a' + 10);
} else if(c >= 'A' && c <= 'F') {
value *= 16;
value += (unsigned int)(c - 'A' + 10);
} else {
break;
}
}
return value;
}
unsigned int
String::hexToUInt(const string &s, size_t index)
{
return hexToUInt(s, index, 0);
}
unsigned int
String::hexToUInt(const string &s)
{
return hexToUInt(s, 0, 0);
}
string
String::toLower(const string &s)
{
const char diff = 'a' - 'A';
string t = s;
size_t length = t.length();
for(size_t i = 0; i < length; ++i) {
if(t[i] >= 'A' && t[i] <= 'Z')
t[i] += diff;
}
return t;
}
string
String::toUpper(const string &s)
{
const char diff = 'A' - 'a';
string t = s;
size_t length = t.length();
for(size_t i = 0; i < length; ++i) {
if(t[i] >= 'a' && t[i] <= 'z')
t[i] += diff;
}
return t;
}
bool
String::isWhitespace(char c)
{
return (c == ' ' || c == '\t' || c == '\r' || c == '\n');
}
string
String::trim(const string &s)
{
size_t length = s.length();
if(length == 0)
return s;
// find the first non-whitespace character
size_t start = 0;
while(start != length && isWhitespace(s[start]))
++start;
// find the last non-whitespace character
size_t end = length - 1;
while(end != 0 && isWhitespace(s[end]))
--end;
if(start > end)
return s;
return s.substr(start, end - start + 1);
}
string
String::htmlEncode(const string &s)
{
const char *specialChars = "<>&\"";
size_t tmp = s.find_first_of(specialChars);
if(tmp == string::npos) {
return s;
} else {
string t = s;
do {
switch(t[tmp]) {
default:
++tmp;
break;
case '<':
t.replace(tmp, 1, "<");
tmp += 4;
break;
case '>':
t.replace(tmp, 1, ">");
tmp += 4;
break;
case '&':
t.replace(tmp, 1, "&");
tmp += 5;
break;
case '"':
t.replace(tmp, 1, """);
tmp += 6;
break;
}
} while((tmp = t.find_first_of(specialChars, tmp)) != string::npos);
return t;
}
}
string
String::urlDecode(const string &s)
{
const char *specialChars = "+%";
size_t tmp = s.find_first_of(specialChars);
if(tmp == string::npos) {
return s;
} else {
string t = s;
size_t length = t.length();
do {
switch(t[tmp]) {
default:
break;
case '+':
t[tmp] = ' ';
break;
case '%':
if(tmp + 2 < length)
t.replace(tmp, 3, 1, (char)hexToUInt(t, tmp + 1, 2));
break;
}
++tmp;
} while((tmp = t.find_first_of(specialChars, tmp)) != string::npos);
return t;
}
}
<|endoftext|>
|
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
utils/gnupg-helper.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "gnupg-helper.h"
#include <gpgme++/engineinfo.h>
#include <KStandardDirs>
#include <QDir>
#include <QFile>
#include <QString>
#include <gpg-error.h>
#ifdef Q_OS_WIN
#include "gnupg-registry.h"
#endif // Q_OS_WIN
QString Kleo::gnupgHomeDirectory()
{
#ifdef Q_OS_WIN
return QFile::decodeName( default_homedir() );
#else
const QByteArray gnupgHome = qgetenv( "GNUPGHOME" );
if ( !gnupgHome.isEmpty() )
return QFile::decodeName( gnupgHome );
else
return QDir::homePath() + "/.gnupg";
#endif
}
int Kleo::makeGnuPGError( int code ) {
return gpg_error( static_cast<gpg_err_code_t>( code ) );
}
static QString findGpgExe( GpgME::Engine engine, const char * exe ) {
const GpgME::EngineInfo info = GpgME::engineInfo( engine );
return info.fileName() ? QFile::decodeName( info.fileName() ) : KStandardDirs::findExe( exe ) ;
}
QString Kleo::gpgConfPath() {
return findGpgExe( GpgME::GpgConfEngine, "gpgconf" );
}
QString Kleo::gpgSmPath() {
return findGpgExe( GpgME::GpgSMEngine, "gpgsm" );
}
QString Kleo::gpgPath() {
return findGpgExe( GpgME::GpgEngine, "gpg" );
}
QStringList Kleo::gnupgFileBlacklist() {
return QStringList()
<< "dirmngr-cache.d"
<< "S.uiserver"
<< "random_seed"
<< "*~"
<< "*.bak"
<< "*.lock"
;
}
<commit_msg>Blacklist *.tmp files, created by gpg when re-writing the keybox<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
utils/gnupg-helper.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "gnupg-helper.h"
#include <gpgme++/engineinfo.h>
#include <KStandardDirs>
#include <QDir>
#include <QFile>
#include <QString>
#include <gpg-error.h>
#ifdef Q_OS_WIN
#include "gnupg-registry.h"
#endif // Q_OS_WIN
QString Kleo::gnupgHomeDirectory()
{
#ifdef Q_OS_WIN
return QFile::decodeName( default_homedir() );
#else
const QByteArray gnupgHome = qgetenv( "GNUPGHOME" );
if ( !gnupgHome.isEmpty() )
return QFile::decodeName( gnupgHome );
else
return QDir::homePath() + "/.gnupg";
#endif
}
int Kleo::makeGnuPGError( int code ) {
return gpg_error( static_cast<gpg_err_code_t>( code ) );
}
static QString findGpgExe( GpgME::Engine engine, const char * exe ) {
const GpgME::EngineInfo info = GpgME::engineInfo( engine );
return info.fileName() ? QFile::decodeName( info.fileName() ) : KStandardDirs::findExe( exe ) ;
}
QString Kleo::gpgConfPath() {
return findGpgExe( GpgME::GpgConfEngine, "gpgconf" );
}
QString Kleo::gpgSmPath() {
return findGpgExe( GpgME::GpgSMEngine, "gpgsm" );
}
QString Kleo::gpgPath() {
return findGpgExe( GpgME::GpgEngine, "gpg" );
}
QStringList Kleo::gnupgFileBlacklist() {
return QStringList()
<< "dirmngr-cache.d"
<< "S.uiserver"
<< "random_seed"
<< "*~"
<< "*.bak"
<< "*.lock"
<< "*.tmp"
;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.