text
stringlengths 54
60.6k
|
---|
<commit_before>#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"
#include <Indie.h>
namespace Symp {
GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer){
//Initialize the engine
IndieLib::init(IND_DEBUG_MODE);
m_pWindow = new Window();
m_pRender = new Render();
m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
m_pWindow->setCursor(true);
InputManager::getInstance();
InputManager::initRender(m_pRender);
m_pParser = new Parser("../assets/data.xml");
//m_pSoundManager = new SoundManager();
//m_pSoundManager->loadSound("../assets/audio/test.wav"); //test sound
//Initialize the game elements to null and start the menu
m_pLevelManager = nullptr;
m_bIsMenu = false;
switchToMenu();
}
GameManager::~GameManager(){
IndieLib::end();
delete m_pWindow;
delete m_pRender;
InputManager::removeInstance();
MenuManager::removeInstance();
}
/**
* @brief Displays the game when it needs to be
* This function displays the game, usually called from a menu.
* @see MenuManager
* @see updateGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToGame(){
//Reset the menuManager attribut
MenuManager::getInstance()->setLevelChoosen(false);
EntityManager::getInstance();
if (m_pLevelManager == nullptr) {
EntityManager::initRender(m_pRender);
//If no game have been created before then create a new one (from the main menu)
m_pLevelManager = new LevelManager();
loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());
m_bIsInGame = true;
}
else{
m_bIsInGame = true;
}
}
/**
* @brief Clear the game entities and attributes for displaying the main menu
* @see MenuManager
* @see EntityManager
* @see LevelManager
* @see updateMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::clear(){
EntityManager::getInstance()->deleteAllEntities();
delete m_pLevelManager;
MenuManager::removeInstance();
m_bIsMenu = false;
EntityManager::removeInstance();
m_pLevelManager = nullptr;
}
/**
* @brief Displays the menus when it needs to be
* This function displays wether the main menu, or the PauseMenu. This function can be called in game for displaying
* again the main menus, in this case, the #GameManager needs to be cleared using the #clear() function. To display the
* game, see #switchToGame().
* @see MenuManager
* @see updateMenu()
* @see switchToGame()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToMenu(){
//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
if (m_bIsMenu == false){
// Retrive data from the player data file
std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();
// Start the menus
MenuManager::getInstance();
MenuManager::init(m_pRender, playerData);
m_bIsMenu = true;
// Manage Camera
m_pRender->setCamera();
m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
}else {
// Pause menu
RenderEntity* pDino = EntityManager::getInstance()->getRenderDino();
PauseMenu* pPauseMenu = new PauseMenu(MenuManager::getInstance(), pDino->getPosX(), pDino->getPosY());
MenuManager::getInstance()->setState(pPauseMenu);
}
m_bIsInGame = false;
}
/**
* @brief The main loop of the game responsible the application to run
* @see updateMenu()
* @see updateGame()
* @see switchToGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::startMainLoop(){
//If the user didn't closed the window or didn't clicked a "quit" button, then update
while (!MenuManager::getInstance()->isAboutToQuit() && !InputManager::getInstance()->quit())
{
InputManager::getInstance()->update();
if(m_bIsInGame) {
updateGame();
}
else {
updateMenu();
}
}
}
/**
* @brief Update the game part of the application each loop
* @see updateMenu()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateGame() {
//move dino
PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
//debug : velocity of dino
//std::cout << pDino->getLinearVelocity().x << " - " << pDino->getLinearVelocity().y << std::endl;
float impulse = pDino->getMass() * 2;
if (InputManager::getInstance()->isKeyPressed(IND_KEYLEFT)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse - pDino->getLinearVelocity().x, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYRIGHT)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse+pDino->getLinearVelocity().x, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYUP)) {
//float force = pDino->getMass() / (1/60.0); //f = mv/t
float force = - pDino->getMass() * 200 * 10;
pDino->getb2Body()->ApplyForce(b2Vec2(0, force), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYDOWN)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse+pDino->getLinearVelocity().y), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
// The following condition manage the camera zoom (for debug)
if (InputManager::getInstance()->isKeyPressed(IND_S)){
float newZoom = m_pRender->getZoom()+0.005;
m_pRender->setZoom(newZoom);
}
else if (InputManager::getInstance()->isKeyPressed(IND_Q)){
float newZoom = m_pRender->getZoom()-0.005;
m_pRender->setZoom(newZoom);
}
else if (InputManager::getInstance()->isKeyPressed(IND_D)){
m_pRender->setZoom(1);
}
//manage Camera
m_pRender->setCamera();
m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);
//update all list of entities
EntityManager::getInstance()->updateEntities();
//sound
if (InputManager::getInstance()->isKeyPressed(IND_SPACE)){
//m_pSoundManager->play(0); //seg fault : still no song !
}
//render openGL
m_pRender->clearViewPort(60, 60, 60);
m_pRender->beginScene();
EntityManager::getInstance()->renderEntities();
//test hitbox
displayHitboxes();
m_pRender->endScene();
//Pause
if (InputManager::getInstance()->onKeyPress(IND_ESCAPE)){
switchToMenu();
}
}
/**
* @brief Update the menu part of the application each loop
* @see updateGame()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateMenu() {
//Forward inputs
//The following offsets are necessary to the mouse pointer to click on the pause menu
//because it's not the same coordinate space
int offsetX = 0;
int offsetY = 0;
if(MenuManager::getInstance()->isDisplayingPauseState()){
PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
offsetX = pDino->getPosition().x - m_pWindow->getIND_Window()->getWidth()*0.5;
offsetY = pDino->getPosition().y - m_pWindow->getIND_Window()->getHeight()*0.5;
}
if (InputManager::getInstance()->onKeyPress(IND_KEYDOWN)){
MenuManager::getInstance()->handleKeyPressed("KEYDOWN");
}
else if (InputManager::getInstance()->onKeyPress(IND_KEYUP)){
MenuManager::getInstance()->handleKeyPressed("KEYUP");
}
else if (InputManager::getInstance()->isMouseMotion()){
// Mouse hover
MenuManager::getInstance()->handleMouseHover(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
}
else if(InputManager::getInstance()->onMouseButtonPress(IND_MBUTTON_LEFT)){
// Clic
MenuManager::getInstance()->handleMouseClic(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
}
else if (InputManager::getInstance()->onKeyPress(IND_ESCAPE) && MenuManager::getInstance()->isDisplayingPauseState()){
// Hidding the Pause menu
MenuManager::getInstance()->setLevelChoosen(false);
m_bIsInGame = true;
}
// The PauseMenu need not to refresh the window in order to displayed upon the game view
if(!MenuManager::getInstance()->isDisplayingPauseState()){
m_pRender->clearViewPort(60, 60, 60);
}
// Otherwise, all the menus needs to refresh the window
m_pRender->beginScene();
MenuManager::getInstance()->renderEntities();
m_pRender->endScene();
//manage camera
m_pRender->setCamera();
//Manage user decisions
if(MenuManager::getInstance()->isLevelChoosen()){
// If the game part needs to be launch
switchToGame();
MenuManager::getInstance()->clear();
}else if (MenuManager::getInstance()->isGoingBackToMenu() && MenuManager::getInstance()->isDisplayingPauseState()){
// If the user wants to go back to the main menu from the pause menu
m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
clear();
switchToMenu();
}
}
void GameManager::loadLevel(const char* mapFile) {
EntityManager::getInstance()->deleteAllEntities();
m_pLevelManager->loadLevel(mapFile);
}
void GameManager::displayHitboxes() {
for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getPhysicalEntityArray().size(); ++idEntity) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntityArray()[idEntity];
if(pEntity != NULL) {
b2Vec2 topleft;
topleft.x = pEntity->getPosition().x - pEntity->getWidth()/2;
topleft.y = pEntity->getPosition().y + pEntity->getHeight()/2;
b2Vec2 botright;
botright.x = pEntity->getPosition().x + pEntity->getWidth()/2;
botright.y = pEntity->getPosition().y - pEntity->getHeight()/2;
m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 255, 0, 0, 255);
}
}
}
}
<commit_msg>sone clean<commit_after>#include "GameManager.h"
#include "menu/PauseMenu.h"
#include "menu/Player.h"
#include <Indie.h>
namespace Symp {
GameManager::GameManager(const char *title, int width, int height, int bpp, bool vsync, bool fs, bool dBuffer){
//Initialize the engine
IndieLib::init(IND_DEBUG_MODE);
m_pWindow = new Window();
m_pRender = new Render();
m_pWindow->setWindow(m_pRender->init(title, width, height, bpp, vsync, fs, dBuffer));
m_pWindow->setCursor(true);
InputManager::getInstance();
InputManager::initRender(m_pRender);
m_pParser = new Parser("../assets/data.xml");
//m_pSoundManager = new SoundManager();
//m_pSoundManager->loadSound("../assets/audio/test.wav"); //test sound
//Initialize the game elements to null and start the menu
m_pLevelManager = nullptr;
m_bIsMenu = false;
switchToMenu();
}
GameManager::~GameManager(){
IndieLib::end();
delete m_pWindow;
delete m_pRender;
InputManager::removeInstance();
MenuManager::removeInstance();
}
/**
* @brief Displays the game when it needs to be
* This function displays the game, usually called from a menu.
* @see MenuManager
* @see updateGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToGame(){
//Reset the menuManager attribut
MenuManager::getInstance()->setLevelChoosen(false);
EntityManager::getInstance();
if (m_pLevelManager == nullptr) {
EntityManager::initRender(m_pRender);
//If no game have been created before then create a new one (from the main menu)
m_pLevelManager = new LevelManager();
loadLevel(MenuManager::getInstance()->getLevelToLoad().c_str());
m_bIsInGame = true;
}
else{
m_bIsInGame = true;
}
}
/**
* @brief Clear the game entities and attributes for displaying the main menu
* @see MenuManager
* @see EntityManager
* @see LevelManager
* @see updateMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::clear(){
EntityManager::getInstance()->deleteAllEntities();
delete m_pLevelManager;
MenuManager::removeInstance();
m_bIsMenu = false;
EntityManager::removeInstance();
m_pLevelManager = nullptr;
}
/**
* @brief Displays the menus when it needs to be
* This function displays wether the main menu, or the PauseMenu. This function can be called in game for displaying
* again the main menus, in this case, the #GameManager needs to be cleared using the #clear() function. To display the
* game, see #switchToGame().
* @see MenuManager
* @see updateMenu()
* @see switchToGame()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::switchToMenu(){
//If the MenuManager doesn't exists, means at the first launch or when the user quit the game, then create it.
if (m_bIsMenu == false){
// Retrive data from the player data file
std::pair<Player*, std::vector<Player*>> playerData = m_pParser->loadPlayerData();
// Start the menus
MenuManager::getInstance();
MenuManager::init(m_pRender, playerData);
m_bIsMenu = true;
// Manage Camera
m_pRender->setCamera();
m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
}else {
// Pause menu
RenderEntity* pDino = EntityManager::getInstance()->getRenderDino();
PauseMenu* pPauseMenu = new PauseMenu(MenuManager::getInstance(), pDino->getPosX(), pDino->getPosY());
MenuManager::getInstance()->setState(pPauseMenu);
}
m_bIsInGame = false;
}
/**
* @brief The main loop of the game responsible the application to run
* @see updateMenu()
* @see updateGame()
* @see switchToGame()
* @see switchToMenu()
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::startMainLoop(){
//If the user didn't closed the window or didn't clicked a "quit" button, then update
while (!MenuManager::getInstance()->isAboutToQuit() && !InputManager::getInstance()->quit())
{
InputManager::getInstance()->update();
if(m_bIsInGame) {
updateGame();
}
else {
updateMenu();
}
}
}
/**
* @brief Update the game part of the application each loop
* @see updateMenu()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateGame() {
// Move dino
PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
float impulse = pDino->getMass() * 2;
if (InputManager::getInstance()->isKeyPressed(IND_KEYLEFT)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(-impulse - pDino->getLinearVelocity().x, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYRIGHT)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(impulse+pDino->getLinearVelocity().x, 0.f), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYUP)) {
//float force = pDino->getMass() / (1/60.0); //f = mv/t
float force = - pDino->getMass() * 200 * 10;
pDino->getb2Body()->ApplyForce(b2Vec2(0, force), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
else if (InputManager::getInstance()->isKeyPressed(IND_KEYDOWN)) {
pDino->getb2Body()->ApplyLinearImpulse(b2Vec2(0.f, impulse+pDino->getLinearVelocity().y), pDino->getb2Body()->GetWorldCenter(), pDino->isAwake());
}
// The following condition manage the camera zoom (for debug)
if (InputManager::getInstance()->isKeyPressed(IND_S)){
float newZoom = m_pRender->getZoom()+0.005;
m_pRender->setZoom(newZoom);
}
else if (InputManager::getInstance()->isKeyPressed(IND_Q)){
float newZoom = m_pRender->getZoom()-0.005;
m_pRender->setZoom(newZoom);
}
else if (InputManager::getInstance()->isKeyPressed(IND_D)){
m_pRender->setZoom(1);
}
//manage Camera
m_pRender->setCamera();
m_pRender->setCameraPosition(pDino->getPosition().x, pDino->getPosition().y);
//update all list of entities
EntityManager::getInstance()->updateEntities();
//sound
if (InputManager::getInstance()->isKeyPressed(IND_SPACE)){
//m_pSoundManager->play(0); //seg fault : still no song !
}
//render openGL
m_pRender->clearViewPort(60, 60, 60);
m_pRender->beginScene();
EntityManager::getInstance()->renderEntities();
//test hitbox
displayHitboxes();
m_pRender->endScene();
//Pause
if (InputManager::getInstance()->onKeyPress(IND_ESCAPE)){
switchToMenu();
}
}
/**
* @brief Update the menu part of the application each loop
* @see updateGame()
* @see InputManager
* @see switchToGame()
* @see switchToMenu()
* @see EntityManager
* @see GameManager()
* @see ~GameManager()
*/
void GameManager::updateMenu() {
//Forward inputs
//The following offsets are necessary to the mouse pointer to click on the pause menu
//because it's not the same coordinate space
int offsetX = 0;
int offsetY = 0;
if(MenuManager::getInstance()->isDisplayingPauseState()){
PhysicalEntity* pDino = EntityManager::getInstance()->getPhysicalDino();
offsetX = pDino->getPosition().x - m_pWindow->getIND_Window()->getWidth()*0.5;
offsetY = pDino->getPosition().y - m_pWindow->getIND_Window()->getHeight()*0.5;
}
if (InputManager::getInstance()->onKeyPress(IND_KEYDOWN)){
MenuManager::getInstance()->handleKeyPressed("KEYDOWN");
}
else if (InputManager::getInstance()->onKeyPress(IND_KEYUP)){
MenuManager::getInstance()->handleKeyPressed("KEYUP");
}
else if (InputManager::getInstance()->isMouseMotion()){
// Mouse hover
MenuManager::getInstance()->handleMouseHover(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
}
else if(InputManager::getInstance()->onMouseButtonPress(IND_MBUTTON_LEFT)){
// Clic
MenuManager::getInstance()->handleMouseClic(InputManager::getInstance()->getMouseX()+offsetX, InputManager::getInstance()->getMouseY()+offsetY);
}
else if (InputManager::getInstance()->onKeyPress(IND_ESCAPE) && MenuManager::getInstance()->isDisplayingPauseState()){
// Hidding the Pause menu
MenuManager::getInstance()->setLevelChoosen(false);
m_bIsInGame = true;
}
// The PauseMenu need not to refresh the window in order to displayed upon the game view
if(!MenuManager::getInstance()->isDisplayingPauseState()){
m_pRender->clearViewPort(60, 60, 60);
}
// Otherwise, all the menus needs to refresh the window
m_pRender->beginScene();
MenuManager::getInstance()->renderEntities();
m_pRender->endScene();
//manage camera
m_pRender->setCamera();
//Manage user decisions
if(MenuManager::getInstance()->isLevelChoosen()){
// If the game part needs to be launch
switchToGame();
MenuManager::getInstance()->clear();
}else if (MenuManager::getInstance()->isGoingBackToMenu() && MenuManager::getInstance()->isDisplayingPauseState()){
// If the user wants to go back to the main menu from the pause menu
m_pRender->setCameraPosition(m_pWindow->getIND_Window()->getWidth()*0.5, m_pWindow->getIND_Window()->getHeight()*0.5);
clear();
switchToMenu();
}
}
void GameManager::loadLevel(const char* mapFile) {
EntityManager::getInstance()->deleteAllEntities();
m_pLevelManager->loadLevel(mapFile);
}
void GameManager::displayHitboxes() {
for (unsigned int idEntity = 0; idEntity < EntityManager::getInstance()->getPhysicalEntityArray().size(); ++idEntity) {
PhysicalEntity* pEntity = EntityManager::getInstance()->getPhysicalEntityArray()[idEntity];
if(pEntity != NULL) {
b2Vec2 topleft;
topleft.x = pEntity->getPosition().x - pEntity->getWidth()/2;
topleft.y = pEntity->getPosition().y + pEntity->getHeight()/2;
b2Vec2 botright;
botright.x = pEntity->getPosition().x + pEntity->getWidth()/2;
botright.y = pEntity->getPosition().y - pEntity->getHeight()/2;
m_pRender->getIND_Render()->blitRectangle(topleft.x, topleft.y, botright.x, botright.y, 255, 0, 0, 255);
}
}
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Program: Wake Forest University - Virginia Tech CTC Software
Id: $Id$
Language: C++
*******************************************************************************/
#include <limits>
#include "ctcSegmentProjectionFilter.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageSliceConstIteratorWithIndex.h"
namespace ctc
{
SegmentProjectionFilter::SegmentProjectionFilter()
{
}
void SegmentProjectionFilter::GenerateOutputInformation()
{
// get pointers to the input and output
Superclass::OutputImagePointer outputPtr = this->GetOutput();
Superclass::InputImageConstPointer inputPtr = this->GetInput();
if ( !outputPtr || !inputPtr)
{
return;
}
BinaryImageType::RegionType inputRegion =
inputPtr->GetLargestPossibleRegion();
ProjectionImageType::RegionType outputRegion;
ProjectionImageType::RegionType::SizeType outputSize;
ProjectionImageType::RegionType::IndexType outputIndex;
outputIndex[0] = 0;
outputIndex[1] = 0;
outputSize[0] = inputRegion.GetSize()[1];
outputSize[1] = inputRegion.GetSize()[2];
outputRegion.SetSize( outputSize );
outputRegion.SetIndex( outputIndex );
outputPtr->SetLargestPossibleRegion( outputRegion );
outputPtr->SetBufferedRegion( outputRegion );
outputPtr->SetRequestedRegion( outputRegion );
BinaryImageType::SpacingType inputSpacing = inputPtr->GetSpacing();
ProjectionImageType::SpacingType outputSpacing;
outputSpacing[0] = inputSpacing[1];
outputSpacing[1] = inputSpacing[2];
outputPtr->SetSpacing( outputSpacing );
BinaryImageType::DirectionType inputDirection = inputPtr->GetDirection();
ProjectionImageType::DirectionType outputDirection;
outputDirection[0][0] = inputDirection[0][1];
outputDirection[1][0] = inputDirection[1][1];
outputDirection[2][0] = inputDirection[2][1];
outputDirection[0][1] = inputDirection[0][2];
outputDirection[1][1] = inputDirection[1][2];
outputDirection[2][1] = inputDirection[2][2];
outputPtr->SetDirection(outputDirection);
BinaryImageType::PointType inputOrigin = inputPtr->GetOrigin();
ProjectionImageType::PointType outputOrigin;
outputOrigin[0] = inputOrigin[0];
outputOrigin[1] = inputOrigin[1];
outputOrigin[2] = inputOrigin[2];
outputPtr->SetOrigin( outputOrigin );
outputPtr->SetNumberOfComponentsPerPixel(1);
}
void SegmentProjectionFilter::GenerateData()
{
// get pointer to input image
BinaryImageType::ConstPointer inputImage = this->GetInput();
// allocate the output image
ProjectionImageType::Pointer outputImage = this->GetOutput();
outputImage->Allocate();
// create the projection
BinaryImageType::RegionType inputRegion =
this->GetInput()->GetLargestPossibleRegion();
typedef itk::ImageSliceConstIteratorWithIndex<BinaryImageType> BinaryIteratorType;
BinaryIteratorType
iit(this->GetInput(),
inputRegion);
typedef itk::ImageLinearIteratorWithIndex< ProjectionImageType >
ProjectionIteratorType;
ProjectionIteratorType oit(outputImage, outputImage->GetBufferedRegion());
// integrate in the sagital direction
iit.SetFirstDirection(0);
iit.SetSecondDirection(2);
oit.SetDirection(0);
iit.GoToBegin();
oit.GoToBegin();
while ( ! iit.IsAtEnd() )
{
while ( ! iit.IsAtEndOfSlice() )
{
while ( ! iit.IsAtEndOfLine() )
{
oit.Set( oit.Get() + iit.Get() );
++iit;
++oit;
}
iit.NextLine();
oit.NextLine();
}
iit.NextSlice();
oit.GoToBegin();
}
}
void SegmentProjectionFilter::PrintSelf(
std::ostream& os,
itk::Indent indent ) const
{
Superclass::PrintSelf(os,indent);
}
}
<commit_msg>CLW this was just a test to demo svn<commit_after>/*******************************************************************************
Program: Wake Forest University - Virginia Tech CTC Software
Id: $Id$
Language: C++
*******************************************************************************/
#include <limits>
#include "ctcSegmentProjectionFilter.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageSliceConstIteratorWithIndex.h"
namespace ctc
{
SegmentProjectionFilter::SegmentProjectionFilter()
{
}
void SegmentProjectionFilter::GenerateOutputInformation()
{
// get pointers to the input and output
Superclass::OutputImagePointer outputPtr = this->GetOutput();
Superclass::InputImageConstPointer inputPtr = this->GetInput();
if ( !outputPtr || !inputPtr)
{
return;
}
BinaryImageType::RegionType inputRegion =
inputPtr->GetLargestPossibleRegion();
ProjectionImageType::RegionType outputRegion;
ProjectionImageType::RegionType::SizeType outputSize;
ProjectionImageType::RegionType::IndexType outputIndex;
outputIndex[0] = 0;
outputIndex[1] = 0;
outputSize[0] = inputRegion.GetSize()[1];
outputSize[1] = inputRegion.GetSize()[2];
outputRegion.SetSize( outputSize );
outputRegion.SetIndex( outputIndex );
outputPtr->SetLargestPossibleRegion( outputRegion );
outputPtr->SetBufferedRegion( outputRegion );
outputPtr->SetRequestedRegion( outputRegion );
BinaryImageType::SpacingType inputSpacing = inputPtr->GetSpacing();
ProjectionImageType::SpacingType outputSpacing;
outputSpacing[0] = inputSpacing[1];
outputSpacing[1] = inputSpacing[2];
outputPtr->SetSpacing( outputSpacing );
BinaryImageType::DirectionType inputDirection = inputPtr->GetDirection();
ProjectionImageType::DirectionType outputDirection;
outputDirection[0][0] = inputDirection[0][1];
outputDirection[1][0] = inputDirection[1][1];
outputDirection[2][0] = inputDirection[2][1];
outputDirection[0][1] = inputDirection[0][2];
outputDirection[1][1] = inputDirection[1][2];
outputDirection[2][1] = inputDirection[2][2];
outputPtr->SetDirection(outputDirection);
BinaryImageType::PointType inputOrigin = inputPtr->GetOrigin();
ProjectionImageType::PointType outputOrigin;
outputOrigin[0] = inputOrigin[0];
outputOrigin[1] = inputOrigin[1];
outputOrigin[2] = inputOrigin[2];
outputPtr->SetOrigin( outputOrigin );
outputPtr->SetNumberOfComponentsPerPixel(1);
}
void SegmentProjectionFilter::GenerateData()
{
// get pointer to input image
BinaryImageType::ConstPointer inputImage = this->GetInput();
// allocate the output image
ProjectionImageType::Pointer outputImage = this->GetOutput();
outputImage->Allocate();
// create the projection
BinaryImageType::RegionType inputRegion =
this->GetInput()->GetLargestPossibleRegion();
typedef itk::ImageSliceConstIteratorWithIndex<BinaryImageType> BinaryIteratorType;
BinaryIteratorType
iit(this->GetInput(),
inputRegion);
typedef itk::ImageLinearIteratorWithIndex< ProjectionImageType >
ProjectionIteratorType;
ProjectionIteratorType oit(outputImage, outputImage->GetBufferedRegion());
// integrate in the sagital direction
iit.SetFirstDirection(0);
iit.SetSecondDirection(2);
clog << "hi" << endl;
oit.SetDirection(0);
iit.GoToBegin();
oit.GoToBegin();
while ( ! iit.IsAtEnd() )
{
while ( ! iit.IsAtEndOfSlice() )
{
while ( ! iit.IsAtEndOfLine() )
{
oit.Set( oit.Get() + iit.Get() );
++iit;
++oit;
}
iit.NextLine();
oit.NextLine();
}
iit.NextSlice();
oit.GoToBegin();
}
}
void SegmentProjectionFilter::PrintSelf(
std::ostream& os,
itk::Indent indent ) const
{
Superclass::PrintSelf(os,indent);
}
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "TransientExecutioner.h"
//Moose includes
#include "Kernel.h"
#include "MaterialFactory.h"
#include "MooseSystem.h"
#include "ComputeJacobian.h"
#include "ComputeResidual.h"
//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"
// C++ Includes
#include <iomanip>
#include <iostream>
#include <fstream>
template<>
InputParameters validParams<TransientExecutioner>()
{
InputParameters params = validParams<Executioner>();
std::vector<Real> sync_times(1);
sync_times[0] = -1;
params.addParam<Real>("start_time", 0.0, "The start time of the simulation");
params.addParam<Real>("end_time", 1.0e30, "The end time of the simulation");
params.addRequiredParam<Real>("dt", "The timestep size between solves");
params.addParam<Real>("dtmin", 0.0, "The minimum timestep size in an adaptive run");
params.addParam<Real>("dtmax", 1.0e30, "The maximum timestep size in an adaptive run");
params.addParam<Real>("num_steps", std::numeric_limits<Real>::max(), "The number of timesteps in a transient run");
params.addParam<int> ("n_startup_steps", 0, "The number of timesteps during startup");
params.addParam<bool>("trans_ss_check", false, "Whether or not to check for steady state conditions");
params.addParam<Real>("ss_check_tol", 1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
params.addParam<Real>("ss_tmin", 0.0, "Minimum number of timesteps to take before checking for steady state conditions.");
params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");
params.addParam<std::vector<Real> >("time_t", "The values of t");
params.addParam<std::vector<Real> >("time_dt", "The values of dt");
return params;
}
TransientExecutioner::TransientExecutioner(const std::string & name, InputParameters parameters)
:Executioner(name, parameters),
_t_step(_moose_system.parameters().set<int> ("t_step") = 0),
_time(_moose_system.parameters().set<Real>("time") = getParam<Real>("start_time")),
_time_old(_time),
_input_dt(getParam<Real>("dt")),
_dt(_moose_system.parameters().set<Real>("dt") = 0),
_prev_dt(-1),
_reset_dt(false),
_end_time(getParam<Real>("end_time")),
_dtmin(getParam<Real>("dtmin")),
_dtmax(getParam<Real>("dtmax")),
_num_steps(getParam<Real>("num_steps")),
_n_startup_steps(getParam<int>("n_startup_steps")),
_trans_ss_check(getParam<bool>("trans_ss_check")),
_ss_check_tol(getParam<Real>("ss_check_tol")),
_ss_tmin(getParam<Real>("ss_tmin")),
_converged(true),
_sync_times(getParam<std::vector<Real> >("sync_times")),
_curr_sync_time_iter(_sync_times.begin()),
_remaining_sync_time(true),
_time_ipol( getParam<std::vector<Real> >("time_t"),
getParam<std::vector<Real> >("time_dt") ),
_use_time_ipol(_time_ipol.getSampleSize() > 0)
{
const std::vector<Real> & time = getParam<std::vector<Real> >("time_t");
if (_use_time_ipol)
{
_sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); // insert times as sync points except the very first one
_curr_sync_time_iter = _sync_times.begin();
}
sort(_sync_times.begin(), _sync_times.end());
_moose_system.reinitDT();
// Advance to the first sync time if one is provided in sim time range
while (_remaining_sync_time && *_curr_sync_time_iter < _time)
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
}
void
TransientExecutioner::execute()
{
preExecute();
// Start time loop...
while(keepGoing())
{
takeStep();
}
postExecute();
}
void
TransientExecutioner::takeStep(Real input_dt)
{
if(_converged)
{
// std::cout << "copy" << std::endl;
// Update backward time solution vectors
_moose_system.copy_old_solutions();
}
else
{
*_moose_system.getNonlinearSystem()->current_local_solution = *_moose_system.getNonlinearSystem()->old_local_solution;
*_moose_system.getNonlinearSystem()->solution = *_moose_system.getNonlinearSystem()->old_local_solution;
}
_moose_system.getNonlinearSystem()->update();
if (input_dt == -1.0)
_dt = computeConstrainedDT();
else
_dt = input_dt;
_moose_system.reinitDT();
_moose_system.onTimestepBegin();
if(_converged)
{
// Update backward material data structures
_moose_system.updateMaterials();
}
// Increment time
_time = _time_old + _dt;
_moose_system.reinitDT();
std::cout<<"DT: "<<_dt<<std::endl;
std::cout << " Solving time step ";
{
OStringStream out;
OSSInt(out,2,_t_step);
out << ", time=";
OSSRealzeroleft(out,9,6,_time);
out << "...";
std::cout << out.str() << std::endl;
}
Moose::setSolverDefaults(_moose_system, this);
setScaling();
preSolve();
Moose::perf_log.push("solve()","Solve");
// System Solve
_moose_system.solve();
Moose::perf_log.pop("solve()","Solve");
_converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;
postSolve();
std::cout<<"Norm of each nonlinear variable:"<<std::endl;
for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)
std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << ": "
<< _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;
// We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
bool last_solve_converged = lastSolveConverged();
// If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
if (last_solve_converged)
{
_moose_system.computePostprocessors(*(_moose_system.getNonlinearSystem()->current_local_solution));
_moose_system.outputPostprocessors();
if(((_t_step+1)%_moose_system._interval == 0 || _reset_dt))
_moose_system.outputSystem(_t_step, _time);
}
if(last_solve_converged && input_dt == -1)
{
endStep();
}
}
void
TransientExecutioner::endStep()
{
adaptMesh();
_t_step++;
_time_old = _time;
}
Real
TransientExecutioner::computeConstrainedDT()
{
// If this is the first step
if(_t_step == 0)
{
_t_step = 1;
_dt = _input_dt;
}
Real dt_cur = computeDT();
// Don't let the time step size exceed maximum time step size
if(dt_cur > _dtmax)
dt_cur = _dtmax;
// Don't allow time step size to be smaller than minimum time step size
if(dt_cur < _dtmin)
dt_cur = _dtmin;
// Don't let time go beyond simulation end time
if(_time + dt_cur > _end_time)
dt_cur = _end_time - _time;
// Adjust to a sync time if supplied and skipped over
if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)
{
dt_cur = *_curr_sync_time_iter - _time;
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
_prev_dt = _dt;
_reset_dt = true;
}
else
{
if (_reset_dt)
{
if (_use_time_ipol)
dt_cur = _time_ipol.sample(_time);
else
dt_cur = _prev_dt;
_reset_dt = false;
}
}
return dt_cur;
}
Real
TransientExecutioner::computeDT()
{
if(!lastSolveConverged())
{
std::cout<<"Solve failed... cutting timestep"<<std::endl;
return _dt / 2.0;
}
if (_use_time_ipol)
{
return _time_ipol.sample(_time);
}
else
{
// If start up steps are needed
if(_t_step == 1 && _n_startup_steps > 1)
return _dt/(double)(_n_startup_steps);
else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)
return _dt*(double)(_n_startup_steps);
else
return _dt;
}
}
bool
TransientExecutioner::keepGoing()
{
// Check for stop condition based upon steady-state check flag:
if(_converged && _trans_ss_check == true && _time > _ss_tmin)
{
// Compute new time solution l2_norm
Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();
// Compute l2_norm relative error
Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;
// Check current solution relative error norm against steady-state tolerance
if(ss_relerr_norm < _ss_check_tol)
{
std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
return false;
}
else // Keep going
{
// Update solution norm for next time step
_old_time_solution_norm = new_time_solution_norm;
// Print steady-state relative error norm
std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
}
}
// Check for stop condition based upon number of simulation steps and/or solution end time:
if(_t_step>_num_steps)
return false;
if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
return false;
return true;
}
bool
TransientExecutioner::lastSolveConverged()
{
return _converged;
}
void
TransientExecutioner::postExecute()
{
/*
MeshFunction mf(* _moose_system.getEquationSystems(), * _moose_system.getNonlinearSystem()->solution, * _moose_system._dof_map, 0);
mf.init();
Real out[10001];
std::ofstream outfile("values_DG_adaptive.xls");
for (unsigned int i = 0; i <= 10000; i++)
{
DenseVector<Number> output;
Point p(i * 2.0e-4, 0.45, 0);
mf(p, 0.0, output);
out[i] = output(0);
outfile << i * 2.0e-4 << " " << output(0) << std::endl;
// std::cout << "x = " << i*2.0e-4 << ", y = " << out[i] << std::endl;
}
outfile.close();
return;
*/
}
<commit_msg>r3089 dd8cd9ef-2931-0410-98ca-75ad22d19dd1<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "TransientExecutioner.h"
//Moose includes
#include "Kernel.h"
#include "MaterialFactory.h"
#include "MooseSystem.h"
#include "ComputeJacobian.h"
#include "ComputeResidual.h"
//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"
// C++ Includes
#include <iomanip>
#include <iostream>
#include <fstream>
template<>
InputParameters validParams<TransientExecutioner>()
{
InputParameters params = validParams<Executioner>();
std::vector<Real> sync_times(1);
sync_times[0] = -1;
params.addParam<Real>("start_time", 0.0, "The start time of the simulation");
params.addParam<Real>("end_time", 1.0e30, "The end time of the simulation");
params.addRequiredParam<Real>("dt", "The timestep size between solves");
params.addParam<Real>("dtmin", 0.0, "The minimum timestep size in an adaptive run");
params.addParam<Real>("dtmax", 1.0e30, "The maximum timestep size in an adaptive run");
params.addParam<Real>("num_steps", std::numeric_limits<Real>::max(), "The number of timesteps in a transient run");
params.addParam<int> ("n_startup_steps", 0, "The number of timesteps during startup");
params.addParam<bool>("trans_ss_check", false, "Whether or not to check for steady state conditions");
params.addParam<Real>("ss_check_tol", 1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
params.addParam<Real>("ss_tmin", 0.0, "Minimum number of timesteps to take before checking for steady state conditions.");
params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");
params.addParam<std::vector<Real> >("time_t", "The values of t");
params.addParam<std::vector<Real> >("time_dt", "The values of dt");
return params;
}
TransientExecutioner::TransientExecutioner(const std::string & name, InputParameters parameters)
:Executioner(name, parameters),
_t_step(_moose_system.parameters().set<int> ("t_step") = 0),
_time(_moose_system.parameters().set<Real>("time") = getParam<Real>("start_time")),
_time_old(_time),
_input_dt(getParam<Real>("dt")),
_dt(_moose_system.parameters().set<Real>("dt") = 0),
_prev_dt(-1),
_reset_dt(false),
_end_time(getParam<Real>("end_time")),
_dtmin(getParam<Real>("dtmin")),
_dtmax(getParam<Real>("dtmax")),
_num_steps(getParam<Real>("num_steps")),
_n_startup_steps(getParam<int>("n_startup_steps")),
_trans_ss_check(getParam<bool>("trans_ss_check")),
_ss_check_tol(getParam<Real>("ss_check_tol")),
_ss_tmin(getParam<Real>("ss_tmin")),
_converged(true),
_sync_times(getParam<std::vector<Real> >("sync_times")),
_curr_sync_time_iter(_sync_times.begin()),
_remaining_sync_time(true),
_time_ipol( getParam<std::vector<Real> >("time_t"),
getParam<std::vector<Real> >("time_dt") ),
_use_time_ipol(_time_ipol.getSampleSize() > 0)
{
const std::vector<Real> & time = getParam<std::vector<Real> >("time_t");
if (_use_time_ipol)
{
_sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); // insert times as sync points except the very first one
_curr_sync_time_iter = _sync_times.begin();
}
sort(_sync_times.begin(), _sync_times.end());
_moose_system.reinitDT();
// Advance to the first sync time if one is provided in sim time range
while (_remaining_sync_time && *_curr_sync_time_iter < _time)
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
}
void
TransientExecutioner::execute()
{
preExecute();
// Start time loop...
while(keepGoing())
{
takeStep();
}
postExecute();
}
void
TransientExecutioner::takeStep(Real input_dt)
{
if(_converged)
{
// std::cout << "copy" << std::endl;
// Update backward time solution vectors
_moose_system.copy_old_solutions();
}
else
{
*_moose_system.getNonlinearSystem()->current_local_solution = *_moose_system.getNonlinearSystem()->old_local_solution;
*_moose_system.getNonlinearSystem()->solution = *_moose_system.getNonlinearSystem()->old_local_solution;
}
_moose_system.getNonlinearSystem()->update();
if (input_dt == -1.0)
_dt = computeConstrainedDT();
else
_dt = input_dt;
_moose_system.reinitDT();
_moose_system.onTimestepBegin();
if(_converged)
{
// Update backward material data structures
_moose_system.updateMaterials();
}
// Increment time
_time = _time_old + _dt;
_moose_system.reinitDT();
std::cout<<"DT: "<<_dt<<std::endl;
std::cout << " Solving time step ";
{
OStringStream out;
OSSInt(out,2,_t_step);
out << ", time=";
OSSRealzeroleft(out,9,6,_time);
out << "...";
std::cout << out.str() << std::endl;
}
Moose::setSolverDefaults(_moose_system, this);
setScaling();
preSolve();
Moose::perf_log.push("solve()","Solve");
// System Solve
_moose_system.solve();
Moose::perf_log.pop("solve()","Solve");
_converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;
postSolve();
std::cout<<"Norm of each nonlinear variable:"<<std::endl;
for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)
std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << ": "
<< _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;
// We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
bool last_solve_converged = lastSolveConverged();
// If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
if (last_solve_converged)
{
_moose_system.computePostprocessors(*(_moose_system.getNonlinearSystem()->current_local_solution));
_moose_system.outputPostprocessors();
if(((_t_step+1)%_moose_system._interval == 0 || _reset_dt))
_moose_system.outputSystem(_t_step, _time);
}
if(last_solve_converged && input_dt == -1)
{
endStep();
}
}
void
TransientExecutioner::endStep()
{
adaptMesh();
_t_step++;
_time_old = _time;
}
Real
TransientExecutioner::computeConstrainedDT()
{
// If this is the first step
if(_t_step == 0)
{
_t_step = 1;
_dt = _input_dt;
}
// If start up steps are needed
if(_t_step == 1 && _n_startup_steps > 1)
_dt = _input_dt/(double)(_n_startup_steps);
else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)
_dt = _input_dt;
Real dt_cur = _dt;
//After startup steps, compute new dt
if (_t_step > _n_startup_steps)
dt_cur = computeDT();
// Don't let the time step size exceed maximum time step size
if(dt_cur > _dtmax)
dt_cur = _dtmax;
// Don't allow time step size to be smaller than minimum time step size
if(dt_cur < _dtmin)
dt_cur = _dtmin;
// Don't let time go beyond simulation end time
if(_time + dt_cur > _end_time)
dt_cur = _end_time - _time;
// Adjust to a sync time if supplied and skipped over
if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)
{
dt_cur = *_curr_sync_time_iter - _time;
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
_prev_dt = _dt;
_reset_dt = true;
}
else
{
if (_reset_dt)
{
if (_use_time_ipol)
dt_cur = _time_ipol.sample(_time);
else
dt_cur = _prev_dt;
_reset_dt = false;
}
}
return dt_cur;
}
Real
TransientExecutioner::computeDT()
{
if(!lastSolveConverged())
{
std::cout<<"Solve failed... cutting timestep"<<std::endl;
return _dt / 2.0;
}
if (_use_time_ipol)
{
return _time_ipol.sample(_time);
}
else
return _dt;
}
bool
TransientExecutioner::keepGoing()
{
// Check for stop condition based upon steady-state check flag:
if(_converged && _trans_ss_check == true && _time > _ss_tmin)
{
// Compute new time solution l2_norm
Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();
// Compute l2_norm relative error
Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;
// Check current solution relative error norm against steady-state tolerance
if(ss_relerr_norm < _ss_check_tol)
{
std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
return false;
}
else // Keep going
{
// Update solution norm for next time step
_old_time_solution_norm = new_time_solution_norm;
// Print steady-state relative error norm
std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
}
}
// Check for stop condition based upon number of simulation steps and/or solution end time:
if(_t_step>_num_steps)
return false;
if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
return false;
return true;
}
bool
TransientExecutioner::lastSolveConverged()
{
return _converged;
}
void
TransientExecutioner::postExecute()
{
/*
MeshFunction mf(* _moose_system.getEquationSystems(), * _moose_system.getNonlinearSystem()->solution, * _moose_system._dof_map, 0);
mf.init();
Real out[10001];
std::ofstream outfile("values_DG_adaptive.xls");
for (unsigned int i = 0; i <= 10000; i++)
{
DenseVector<Number> output;
Point p(i * 2.0e-4, 0.45, 0);
mf(p, 0.0, output);
out[i] = output(0);
outfile << i * 2.0e-4 << " " << output(0) << std::endl;
// std::cout << "x = " << i*2.0e-4 << ", y = " << out[i] << std::endl;
}
outfile.close();
return;
*/
}
<|endoftext|> |
<commit_before>#include "libwintermutecore/message.hpp"
#include <cxxtest/TestSuite.h>
using Wintermute::Procedure::Message;
class MessageTestSuite : public CxxTest::TestSuite
{
public:
void testClone(void)
{
Message::HashType data;
data.insert(std::make_pair("foo", "bar"));
Message message;
message.setPayload(data);
TS_ASSERT( message.payload().at("foo") == Message::HashValue("bar") );
}
};
<commit_msg>Add test to ensured that empty messages identify as empty.<commit_after>#include "libwintermutecore/message.hpp"
#include <cxxtest/TestSuite.h>
using Wintermute::Procedure::Message;
class MessageTestSuite : public CxxTest::TestSuite
{
public:
void testClone(void)
{
Message::HashType data;
data.insert(std::make_pair("foo", "bar"));
Message message;
message.setPayload(data);
TS_ASSERT( message.payload().at("foo") == Message::HashValue("bar") );
}
void testEmpty(void)
{
Message aMessage;
TS_ASSERT( aMessage.isEmpty() == true );
}
};
<|endoftext|> |
<commit_before>/**
* $ g++ solution.cpp && ./a.out < input.txt
* Day 6!
* part 1: 3156
*/
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
/**
* Notes on accumulate():
*
* - http://en.cppreference.com/w/cpp/algorithm/accumulate
* - http://www.cplusplus.com/reference/numeric/accumulate/
*/
string get_banks_string(vector<int> banks) {
return accumulate(next(banks.begin()),
banks.end(),
// start with first element
to_string(banks[0]),
// [] is an anonymous function/lambda expression
// http://en.cppreference.com/w/cpp/language/lambda
// Only from C++11
[](string a, int b) {
return a + '-' + to_string(b);
});
}
int get_biggest_bank(vector<int> banks) {
int maxBank, maxBankSize;
for (int i = 0; i < banks.size(); i++) {
if (i == 0) {
maxBank = 0;
maxBankSize = banks[0];
continue;
}
if (banks[i] > maxBankSize) {
maxBank = i;
maxBankSize = banks[i];
}
}
return maxBank;
}
int part1(vector<int> banks) {
unordered_set<string> seen;
int redistributions = 0;
string banks_string;
int biggest_bank, bank_value, bank_index;
while(true) {
banks_string = get_banks_string(banks);
// cout << banks_string << endl;
auto search = seen.find(banks_string);
// Found it!
if (search != seen.end()) {
return redistributions;
}
// Not found. Redistribute.
seen.insert(banks_string);
biggest_bank = get_biggest_bank(banks);
bank_value = banks[biggest_bank];
banks[biggest_bank] = 0;
bank_index = biggest_bank + 1;
if (bank_index == banks.size()) {
bank_index = 0;
}
while (bank_value > 0) {
banks[bank_index]++;
bank_value--;
bank_index++;
if (bank_index == banks.size()) {
bank_index = 0;
}
}
redistributions++;
}
return 0;
}
int main() {
cout << "Day 6!" << endl;
vector<int> banks;
int blocks;
while (cin >> blocks) {
banks.push_back(blocks);
}
cout << "part 1: " << part1(banks) << endl;
}
<commit_msg>Day 6, part 2<commit_after>/**
* $ g++ solution.cpp && ./a.out < input.txt
* Day 6!
* part 1: 3156
* part 2: 1610
*/
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
/**
* Notes on accumulate():
*
* - http://en.cppreference.com/w/cpp/algorithm/accumulate
* - http://www.cplusplus.com/reference/numeric/accumulate/
*/
string get_banks_string(vector<int> banks) {
return accumulate(next(banks.begin()),
banks.end(),
// start with first element
to_string(banks[0]),
// [] is an anonymous function/lambda expression
// http://en.cppreference.com/w/cpp/language/lambda
// Only from C++11
[](string a, int b) {
return a + '-' + to_string(b);
});
}
int get_biggest_bank(vector<int> banks) {
int maxBank, maxBankSize;
for (int i = 0; i < banks.size(); i++) {
if (i == 0) {
maxBank = 0;
maxBankSize = banks[0];
continue;
}
if (banks[i] > maxBankSize) {
maxBank = i;
maxBankSize = banks[i];
}
}
return maxBank;
}
int part1(vector<int> banks) {
unordered_set<string> seen;
int redistributions = 0;
string banks_string;
int biggest_bank, bank_value, bank_index;
while(true) {
banks_string = get_banks_string(banks);
// cout << banks_string << endl;
auto search = seen.find(banks_string);
// Found it!
if (search != seen.end()) {
return redistributions;
}
// Not found. Redistribute.
seen.insert(banks_string);
biggest_bank = get_biggest_bank(banks);
bank_value = banks[biggest_bank];
banks[biggest_bank] = 0;
bank_index = biggest_bank + 1;
if (bank_index == banks.size()) {
bank_index = 0;
}
while (bank_value > 0) {
banks[bank_index]++;
bank_value--;
bank_index++;
if (bank_index == banks.size()) {
bank_index = 0;
}
}
redistributions++;
}
return 0;
}
/**
* `unordered_map` refs:
* - http://en.cppreference.com/w/cpp/container/unordered_map
* - http://en.cppreference.com/w/cpp/container/unordered_map/find
*/
int part2(vector<int> banks) {
// banks_string <string> / redistributions <int>
unordered_map<string, int> seen;
int redistributions = 0;
string banks_string;
int biggest_bank, bank_value, bank_index;
while(true) {
banks_string = get_banks_string(banks);
// cout << banks_string << endl;
auto search = seen.find(banks_string);
// Found it!
if (search != seen.end()) {
return redistributions - search->second;
}
// Not found. Redistribute.
seen.insert(make_pair(banks_string, redistributions));
biggest_bank = get_biggest_bank(banks);
bank_value = banks[biggest_bank];
banks[biggest_bank] = 0;
bank_index = biggest_bank + 1;
if (bank_index == banks.size()) {
bank_index = 0;
}
while (bank_value > 0) {
banks[bank_index]++;
bank_value--;
bank_index++;
if (bank_index == banks.size()) {
bank_index = 0;
}
}
redistributions++;
}
return 0;
}
int main() {
cout << "Day 6!" << endl;
vector<int> banks;
int blocks;
while (cin >> blocks) {
banks.push_back(blocks);
}
cout << "part 1: " << part1(banks) << endl;
cout << "part 2: " << part2(banks) << endl;
}
<|endoftext|> |
<commit_before>/**
* File : E2.cpp
* Author : Kazune Takahashi
* Created : 2018-3-28 12:29:59
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;
const int UFSIZE = 100010;
int union_find[UFSIZE];
int root(int a) {
if (a == union_find[a]) return a;
return (union_find[a] = root(union_find[a]));
}
bool issame(int a, int b) {
return root(a) == root(b);
}
void unite(int a, int b) {
union_find[root(a)] = root(b);
}
bool isroot(int a) {
return root(a) == a;
}
void init() {
for (auto i=0; i<UFSIZE; i++) {
union_find[i] = i;
}
}
long long power(long long x, long long n) {
if (n == 0) {
return 1;
} else if (n%2 == 1) {
return (x * power(x, n-1)) % MOD;
} else {
long long half = power(x, n/2);
return (half * half) % MOD;
}
}
typedef tuple<ll, int, int> edge;
typedef tuple<ll, int> path;
int N, M;
ll X;
vector<edge> V;
vector<path> T[1010];
vector<edge> W;
path parent[10][1010];
int depth[1010];
vector<ll> S;
void dfs(int v, int p, ll cost, int d)
{
parent[0][v] = path(cost, p);
depth[v] = d;
for (auto x : T[v])
{
if (get<1>(x) != p)
{
dfs(get<1>(x), v, get<0>(x), d + 1);
}
}
}
void init2()
{
dfs(0, -1, 0, 0);
for (auto k = 0; k+1 < 10; k++)
{
for (auto v = 0; v < N; v++)
{
if (get<1>(parent[k][v]) < 0)
{
parent[k + 1][v] = path(0, -1);
}
else
{
ll cost = get<0>(parent[k][v]);
int u = get<1>(parent[k][v]);
int new_u = get<1>(parent[k][u]);
ll new_cost = max(cost, get<0>(parent[k][u]));
parent[k + 1][v] = path(new_cost, new_u);
#if DEBUG == 1
cerr << "parent[" << k + 1 << "][" << v << "] = (" << new_cost << ", " << new_u << ")" << endl;
#endif
}
}
}
}
ll lca(int u, int v)
{
if (depth[u] > depth[v])
swap(u, v);
ll ans = 0;
#if DEBUG == 1
cerr << "depth[" << u << "] = " << depth[u]
<< ", depth[" << v << "] = " << depth[v] << endl;
#endif
for (auto k = 0; k < 10; k++)
{
if ((depth[v] - depth[u]) >> k & 1)
{
ans = max(ans, get<0>(parent[k][v]));
v = get<1>(parent[k][v]);
}
}
if (u == v)
return ans;
for (auto k = 9; k >= 0; k--)
{
if (get<1>(parent[k][u]) != get<1>(parent[k][v]))
{
ans = max(ans, get<0>(parent[k][u]));
ans = max(ans, get<0>(parent[k][v]));
u = get<1>(parent[k][u]);
v = get<1>(parent[k][v]);
}
}
ans = max(ans, get<0>(parent[0][v]));
ans = max(ans, get<0>(parent[0][u]));
return ans;
}
ll f(ll n)
{
ll lb = 0;
ll ub = S.size();
while (ub - lb > 1)
{
ll t = (ub + lb) / 2;
if (S[t] <= n)
{
lb = t;
}
else
{
ub = t;
}
}
ll c = lb;
if (c == 0)
{
return power(2, M);
}
else
{
return power(2, M - c + 1);
}
}
int main()
{
init();
cin >> N >> M;
cin >> X;
for (auto i = 0; i < M; i++)
{
int u, v;
ll w;
cin >> u >> v >> w;
u--;
v--;
V.push_back(edge(w, u, v));
}
sort(V.begin(), V.end());
ll Y = 0;
int cnt = 0;
for (auto e : V)
{
ll cost = get<0>(e);
int u = get<1>(e);
int v = get<2>(e);
if (!issame(u, v))
{
unite(u, v);
T[u].push_back(path(cost, v));
T[v].push_back(path(cost, u));
Y += cost;
cnt++;
}
else
{
W.push_back(e);
}
}
#if DEBUG == 1
cerr << "X = " << X << ", Y = " << Y << endl;
#endif
init2();
for (auto i = 0; i < cnt; i++)
{
S.push_back(Y);
}
for (auto e : W)
{
ll cost = get<0>(e);
int u = get<1>(e);
int v = get<2>(e);
S.push_back(cost - lca(u, v) + Y);
}
sort(S.begin(), S.end());
for (auto x : S)
{
cerr << x << " ";
}
cerr << endl;
cerr << "f(" << X - 1 << ") = " << f(X - 1)
<< ", f(" << X << ") = " << f(X) << endl;
cout << (f(X - 1) + MOD - f(X)) % MOD << endl;
}<commit_msg>tried E2.cpp to 'E'<commit_after>/**
* File : E2.cpp
* Author : Kazune Takahashi
* Created : 2018-3-28 12:29:59
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
const int MAX_SIZE = 1000010;
const long long MOD = 1000000007;
const int UFSIZE = 100010;
int union_find[UFSIZE];
int root(int a) {
if (a == union_find[a]) return a;
return (union_find[a] = root(union_find[a]));
}
bool issame(int a, int b) {
return root(a) == root(b);
}
void unite(int a, int b) {
union_find[root(a)] = root(b);
}
bool isroot(int a) {
return root(a) == a;
}
void init() {
for (auto i=0; i<UFSIZE; i++) {
union_find[i] = i;
}
}
long long power(long long x, long long n) {
if (n == 0) {
return 1;
} else if (n%2 == 1) {
return (x * power(x, n-1)) % MOD;
} else {
long long half = power(x, n/2);
return (half * half) % MOD;
}
}
typedef tuple<ll, int, int> edge;
typedef tuple<ll, int> path;
int N, M;
ll X;
vector<edge> V;
vector<path> T[1010];
vector<edge> W;
path parent[10][1010];
int depth[1010];
vector<ll> S;
void dfs(int v, int p, ll cost, int d)
{
parent[0][v] = path(cost, p);
depth[v] = d;
for (auto x : T[v])
{
if (get<1>(x) != p)
{
dfs(get<1>(x), v, get<0>(x), d + 1);
}
}
}
void init2()
{
dfs(0, -1, 0, 0);
for (auto k = 0; k+1 < 10; k++)
{
for (auto v = 0; v < N; v++)
{
if (get<1>(parent[k][v]) < 0)
{
parent[k + 1][v] = path(0, -1);
}
else
{
ll cost = get<0>(parent[k][v]);
int u = get<1>(parent[k][v]);
int new_u = get<1>(parent[k][u]);
ll new_cost = max(cost, get<0>(parent[k][u]));
parent[k + 1][v] = path(new_cost, new_u);
#if DEBUG == 1
cerr << "parent[" << k + 1 << "][" << v << "] = (" << new_cost << ", " << new_u << ")" << endl;
#endif
}
}
}
}
ll lca(int u, int v)
{
if (depth[u] > depth[v])
swap(u, v);
ll ans = 0;
#if DEBUG == 1
cerr << "depth[" << u << "] = " << depth[u]
<< ", depth[" << v << "] = " << depth[v] << endl;
#endif
for (auto k = 0; k < 10; k++)
{
if ((depth[v] - depth[u]) >> k & 1)
{
ans = max(ans, get<0>(parent[k][v]));
v = get<1>(parent[k][v]);
}
}
if (u == v)
return ans;
for (auto k = 9; k >= 0; k--)
{
if (get<1>(parent[k][u]) != get<1>(parent[k][v]))
{
ans = max(ans, get<0>(parent[k][u]));
ans = max(ans, get<0>(parent[k][v]));
u = get<1>(parent[k][u]);
v = get<1>(parent[k][v]);
}
}
ans = max(ans, get<0>(parent[0][v]));
ans = max(ans, get<0>(parent[0][u]));
return ans;
}
ll f(ll n)
{
ll lb = 0;
ll ub = S.size()+1;
while (ub - lb > 1)
{
ll t = (ub + lb) / 2;
if (S[t] <= n)
{
lb = t;
}
else
{
ub = t;
}
}
ll c = lb;
if (c == 0)
{
return power(2, M);
}
else
{
return power(2, M - c + 1);
}
}
int main()
{
init();
cin >> N >> M;
cin >> X;
for (auto i = 0; i < M; i++)
{
int u, v;
ll w;
cin >> u >> v >> w;
u--;
v--;
V.push_back(edge(w, u, v));
}
sort(V.begin(), V.end());
ll Y = 0;
int cnt = 0;
for (auto e : V)
{
ll cost = get<0>(e);
int u = get<1>(e);
int v = get<2>(e);
if (!issame(u, v))
{
unite(u, v);
T[u].push_back(path(cost, v));
T[v].push_back(path(cost, u));
Y += cost;
cnt++;
}
else
{
W.push_back(e);
}
}
#if DEBUG == 1
cerr << "X = " << X << ", Y = " << Y << endl;
#endif
init2();
for (auto i = 0; i < cnt; i++)
{
S.push_back(Y);
}
for (auto e : W)
{
ll cost = get<0>(e);
int u = get<1>(e);
int v = get<2>(e);
S.push_back(cost - lca(u, v) + Y);
}
sort(S.begin(), S.end());
#if DEBUG == 1
for (auto x : S)
{
cerr << x << " ";
}
cerr << endl;
cerr << "f(" << X - 1 << ") = " << f(X - 1)
<< ", f(" << X << ") = " << f(X) << endl;
#endif
cout << (f(X - 1) + MOD - f(X)) % MOD << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F2.cpp
* Author : Kazune Takahashi
* Created : 2019/9/1 22:51:39
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using point = complex<ll>;
bool cmp(point x, point y)
{
return arg(x) < arg(y);
}
int main()
{
int N;
cin >> N;
vector<point> V(N);
for (auto i = 0; i < N; i++)
{
ll x, y;
cin >> x >> y;
V[i] = point{x, y};
}
sort(V.begin(), V.end(), cmp);
ll ans{0};
for (auto i = 0; i < N; i++)
{
for (auto j = i + 1; j < N; j++)
{
point sum{0};
for (auto k = i; k < j; k++)
{
sum += V[k];
}
maxs(ans, norm(sum));
}
}
for (auto i = 0; i < N; i++)
{
for (auto j = i + 1; j < N; j++)
{
point sum{0};
for (auto k = 0; k < i; k++)
{
sum += V[k];
}
for (auto k = j; k < N; k++)
{
sum += V[k];
}
maxs(ans, norm(sum));
}
}
cout << fixed << setprecision(30) << sqrt(ans) << endl;
}<commit_msg>tried F2.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F2.cpp
* Author : Kazune Takahashi
* Created : 2019/9/1 22:51:39
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
using point = complex<ll>;
bool cmp(point x, point y)
{
return arg(x) < arg(y);
}
int main()
{
int N;
cin >> N;
vector<point> V(N);
for (auto i = 0; i < N; i++)
{
ll x, y;
cin >> x >> y;
V[i] = point{x, y};
}
sort(V.begin(), V.end(), cmp);
ll ans{0};
for (auto i = 0; i < N; i++)
{
for (auto j = i + 1; j <= N; j++)
{
point sum{0};
for (auto k = i; k < j; k++)
{
sum += V[k];
}
maxs(ans, norm(sum));
}
}
for (auto i = 0; i < N; i++)
{
for (auto j = i + 1; j <= N; j++)
{
point sum{0};
for (auto k = 0; k < i; k++)
{
sum += V[k];
}
for (auto k = j; k < N; k++)
{
sum += V[k];
}
maxs(ans, norm(sum));
}
}
cout << fixed << setprecision(30) << sqrt(ans) << endl;
}<|endoftext|> |
<commit_before>#include <cmath>
#include <gmpxx.h>
#include <iostream>
#include <vector>
#include <sstream>
#define SUCCESS 0
#define FAILURE 1
#define LOG_INFO
using namespace std;
mpf_class meanVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), length(size, acc), result(0, acc);
for (int i=0;i<length;i++)
{
sum += arr[i];
}
result = sum/length;
return result;
}
mpf_class varVal(const mpf_class* arr, const size_t& size, const size_t& acc,
const mpf_class& meanValue) {
mpf_class sum2(0, acc), length(size, acc), result(0, acc);
mpf_class temp(0, acc);
for (int i=0; i< length; i++) {
temp = arr[i] - meanValue;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
mpf_class periodVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), sum2(0, acc), length(size, acc), result(0, acc);
for (int i=0; i< length; i++)
sum += arr[i];
sum = (sum / length);
for (int i=0; i< length; i++) {
mpf_class temp(0, acc);
temp = arr[i] - sum;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
const vector<mpf_class> getStream(size_t acc) {
vector<mpf_class> vec;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
vec.push_back(input_val);
}
return vec;
}
mpf_class* getArrStream(size_t acc, size_t& size) {
mpf_class* arr = new mpf_class[16777216];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
arr[i] = input_val;
i++;
}
size = i;
return arr;
}
void debugPrintArr(const mpf_class* arr, long size) {
cout << "Debug array print:" << endl;
for (long i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printUsage(char **argv) {
cout <<"usage: "<< argv[0] <<" <accuracy>\n";
}
int main (int argc, char **argv) {
// Cin && cout optimization.
std::ios_base::sync_with_stdio(false);
// Max acc: 2^16 = 65536
// Max size of array: 2^24 = 16777216
// Max elem | value |: 2^64 = 18446744073709551616
int accuracy = 65536; // Default accuracy.
if ( argc > 1 ) {
if (!strcmp(argv[1], "-h")) {
printUsage(argv);
return SUCCESS;
}
accuracy = atoi(argv[1]);
if (accuracy > accuracy )
return FAILURE;
}
mpf_class meanValue(0, accuracy);
mpf_class varianceVal(0, accuracy);
mpf_class periodicVal(0, accuracy);
mpf_class sum(0, accuracy);
// Our array.
mpf_class* arr = new mpf_class[16777216];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
mpf_class input_val;
input_val.set_prec(accuracy);
while (true)
{
if(!(lineStream >> input_val)) break;
sum += input_val;
arr[i] = input_val;
i++;
}
meanValue = sum / i;
#ifdef LOG_INFO
cout << "Starting prog" << endl;
#endif
//debugPrintArr(&vec[0], vec.size());
cout.precision(accuracy);
cout << meanValue << endl;
cout << varVal(arr, i, accuracy, meanValue) << endl;
cout << varVal(arr, i, accuracy, meanValue) << endl;
delete[](arr);
return 0;
}
<commit_msg>More readable constants.<commit_after>#include <cmath>
#include <gmpxx.h>
#include <iostream>
#include <vector>
#include <sstream>
#define SUCCESS 0
#define FAILURE 1
#define MAX_ARR_SIZE 16777216
#define MAX_PRECISION 65536
#define LOG_INFO
using namespace std;
mpf_class meanVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), length(size, acc), result(0, acc);
for (int i=0;i<length;i++)
{
sum += arr[i];
}
result = sum/length;
return result;
}
mpf_class varVal(const mpf_class* arr, const size_t& size, const size_t& acc,
const mpf_class& meanValue) {
mpf_class sum2(0, acc), length(size, acc), result(0, acc);
mpf_class temp(0, acc);
for (int i=0; i< length; i++) {
temp = arr[i] - meanValue;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
mpf_class periodVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), sum2(0, acc), length(size, acc), result(0, acc);
for (int i=0; i< length; i++)
sum += arr[i];
sum = (sum / length);
for (int i=0; i< length; i++) {
mpf_class temp(0, acc);
temp = arr[i] - sum;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
const vector<mpf_class> getStream(size_t acc) {
vector<mpf_class> vec;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
vec.push_back(input_val);
}
return vec;
}
mpf_class* getArrStream(size_t acc, size_t& size) {
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
arr[i] = input_val;
i++;
}
size = i;
return arr;
}
void debugPrintArr(const mpf_class* arr, long size) {
cout << "Debug array print:" << endl;
for (long i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printUsage(char **argv) {
cout <<"usage: "<< argv[0] <<" <accuracy>\n";
}
int main (int argc, char **argv) {
// Cin && cout optimization.
std::ios_base::sync_with_stdio(false);
// Max acc: 2^16 = 65536
// Max size of array: 2^24 = 16777216
// Max elem | value |: 2^64 = 18446744073709551616
int accuracy = MAX_PRECISION; // Default accuracy.
if ( argc > 1 ) {
if (!strcmp(argv[1], "-h")) {
printUsage(argv);
return SUCCESS;
}
accuracy = atoi(argv[1]);
if (accuracy < 1 && accuracy > MAX_PRECISION)
return FAILURE;
}
mpf_class meanValue(0, accuracy);
mpf_class varianceVal(0, accuracy);
mpf_class periodicVal(0, accuracy);
mpf_class sum(0, accuracy);
// Our array.
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
mpf_class input_val;
input_val.set_prec(accuracy);
while (true)
{
if(!(lineStream >> input_val)) break;
sum += input_val;
arr[i] = input_val;
i++;
}
meanValue = sum / i;
#ifdef LOG_INFO
cout << "Starting prog" << endl;
#endif
//debugPrintArr(&vec[0], vec.size());
cout.precision(accuracy);
cout << meanValue << endl;
cout << varVal(arr, i, accuracy, meanValue) << endl;
cout << varVal(arr, i, accuracy, meanValue) << endl;
delete[](arr);
return 0;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreShaderCGProgramWriter.h"
#include "OgreStringConverter.h"
#include "OgreGpuProgramManager.h"
namespace Ogre {
namespace RTShader {
String CGProgramWriter::TargetLanguage = "cg";
//-----------------------------------------------------------------------
CGProgramWriter::CGProgramWriter()
{
initializeStringMaps();
}
//-----------------------------------------------------------------------
CGProgramWriter::~CGProgramWriter()
{
}
//-----------------------------------------------------------------------
void CGProgramWriter::initializeStringMaps()
{
mGpuConstTypeMap[GCT_FLOAT1] = "float";
mGpuConstTypeMap[GCT_FLOAT2] = "float2";
mGpuConstTypeMap[GCT_FLOAT3] = "float3";
mGpuConstTypeMap[GCT_FLOAT4] = "float4";
mGpuConstTypeMap[GCT_SAMPLER1D] = "sampler1D";
mGpuConstTypeMap[GCT_SAMPLER2D] = "sampler2D";
mGpuConstTypeMap[GCT_SAMPLER3D] = "sampler3D";
mGpuConstTypeMap[GCT_SAMPLERCUBE] = "samplerCUBE";
mGpuConstTypeMap[GCT_MATRIX_2X2] = "float2x2";
mGpuConstTypeMap[GCT_MATRIX_2X3] = "float2x3";
mGpuConstTypeMap[GCT_MATRIX_2X4] = "float2x4";
mGpuConstTypeMap[GCT_MATRIX_3X2] = "float3x2";
mGpuConstTypeMap[GCT_MATRIX_3X3] = "float3x3";
mGpuConstTypeMap[GCT_MATRIX_3X4] = "float3x4";
mGpuConstTypeMap[GCT_MATRIX_4X2] = "float4x2";
mGpuConstTypeMap[GCT_MATRIX_4X3] = "float4x3";
mGpuConstTypeMap[GCT_MATRIX_4X4] = "float4x4";
mGpuConstTypeMap[GCT_INT1] = "int";
mGpuConstTypeMap[GCT_INT2] = "int2";
mGpuConstTypeMap[GCT_INT3] = "int3";
mGpuConstTypeMap[GCT_INT4] = "int4";
mParamSemanticMap[Parameter::SPS_POSITION] = "POSITION";
mParamSemanticMap[Parameter::SPS_BLEND_WEIGHTS] = "BLENDWEIGHT";
mParamSemanticMap[Parameter::SPS_BLEND_INDICES] = "BLENDINDICES";
mParamSemanticMap[Parameter::SPS_NORMAL] = "NORMAL";
mParamSemanticMap[Parameter::SPS_COLOR] = "COLOR";
mParamSemanticMap[Parameter::SPS_TEXTURE_COORDINATES] = "TEXCOORD";
mParamSemanticMap[Parameter::SPS_BINORMAL] = "BINORMAL";
mParamSemanticMap[Parameter::SPS_TANGENT] = "TANGENT";
mParamSemanticMap[Parameter::SPS_UNKNOWN] = "";
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeSourceCode(std::ostream& os, Program* program)
{
const ShaderFunctionList& functionList = program->getFunctions();
ShaderFunctionConstIterator itFunction;
const UniformParameterList& parameterList = program->getParameters();
UniformParameterConstIterator itUniformParam = parameterList.begin();
// Generate source code header.
writeProgramTitle(os, program);
os << std::endl;
// Generate dependencies.
writeProgramDependencies(os, program);
os << std::endl;
// Generate global variable code.
writeUniformParametersTitle(os, program);
os << std::endl;
for (itUniformParam=parameterList.begin(); itUniformParam != parameterList.end(); ++itUniformParam)
{
writeUniformParameter(os, *itUniformParam);
os << ";" << std::endl;
}
os << std::endl;
// Write program function(s).
for (itFunction=functionList.begin(); itFunction != functionList.end(); ++itFunction)
{
Function* curFunction = *itFunction;
bool needToTranslateHlsl4Color = false;
ParameterPtr colorParameter;
writeFunctionTitle(os, curFunction);
writeFunctionDeclaration(os, curFunction, needToTranslateHlsl4Color, colorParameter);
os << "{" << std::endl;
// Write local parameters.
const ShaderParameterList& localParams = curFunction->getLocalParameters();
ShaderParameterConstIterator itParam;
for (itParam=localParams.begin(); itParam != localParams.end(); ++itParam)
{
os << "\t";
writeLocalParameter(os, *itParam);
os << ";" << std::endl;
}
// translate hlsl 4 color parameter if needed
if(needToTranslateHlsl4Color)
{
os << "\t";
writeLocalParameter(os, colorParameter);
os << ";" << std::endl;
os << std::endl <<"\tFFP_Assign(iHlsl4Color_0, " << colorParameter->getName() << ");" << std::endl;
}
// Sort and write function atoms.
curFunction->sortAtomInstances();
const FunctionAtomInstanceList& atomInstances = curFunction->getAtomInstances();
FunctionAtomInstanceConstIterator itAtom;
for (itAtom=atomInstances.begin(); itAtom != atomInstances.end(); ++itAtom)
{
writeAtomInstance(os, *itAtom);
}
os << "}" << std::endl;
}
os << std::endl;
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeProgramDependencies(std::ostream& os, Program* program)
{
os << "//-----------------------------------------------------------------------------" << std::endl;
os << "// PROGRAM DEPENDENCIES" << std::endl;
os << "//-----------------------------------------------------------------------------" << std::endl;
for (unsigned int i=0; i < program->getDependencyCount(); ++i)
{
const String& curDependency = program->getDependency(i);
os << "#include " << '\"' << curDependency << "." << getTargetLanguage() << '\"' << std::endl;
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeUniformParameter(std::ostream& os, UniformParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
if (parameter->isSampler())
{
os << " : register(s" << parameter->getIndex() << ")";
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeFunctionParameter(std::ostream& os, ParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
if (parameter->getSemantic() != Parameter::SPS_UNKNOWN)
{
os << " : ";
os << mParamSemanticMap[parameter->getSemantic()];
if (parameter->getSemantic() != Parameter::SPS_POSITION &&
parameter->getSemantic() != Parameter::SPS_NORMAL &&
(!(parameter->getSemantic() == Parameter::SPS_COLOR && parameter->getIndex() == 0)) &&
parameter->getIndex() >= 0)
{
os << StringConverter::toString(parameter->getIndex()).c_str();
}
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeLocalParameter(std::ostream& os, ParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeFunctionDeclaration(std::ostream& os, Function* function, bool & needToTranslateHlsl4Color, ParameterPtr & colorParameter)
{
const ShaderParameterList& inParams = function->getInputParameters();
const ShaderParameterList& outParams = function->getOutputParameters();
os << "void";
os << " ";
os << function->getName();
os << std::endl << "\t(" << std::endl;
ShaderParameterConstIterator it;
size_t paramsCount = inParams.size() + outParams.size();
size_t curParamIndex = 0;
// for shader model 4 - we need to get the color as unsigned int
bool isVs4 = GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0");
// Write input parameters.
for (it=inParams.begin(); it != inParams.end(); ++it)
{
os << "\t in ";
if (isVs4 &&
function->getFunctionType() == Function::FFT_VS_MAIN &&
(*it)->getSemantic() == Parameter::SPS_COLOR
)
{
os << "unsigned int iHlsl4Color_0 : COLOR";
needToTranslateHlsl4Color = true;
colorParameter = *it;
}
else
{
writeFunctionParameter(os, *it);
}
if (curParamIndex + 1 != paramsCount)
os << ", " << std::endl;
curParamIndex++;
}
// Write output parameters.
for (it=outParams.begin(); it != outParams.end(); ++it)
{
os << "\t out ";
writeFunctionParameter(os, *it);
if (curParamIndex + 1 != paramsCount)
os << ", " << std::endl;
curParamIndex++;
}
os << std::endl << "\t)" << std::endl;
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeAtomInstance(std::ostream& os, FunctionAtom* atom)
{
os << std::endl << "\t";
atom->writeSourceCode(os, getTargetLanguage());
os << std::endl;
}
}
}
<commit_msg>RTSS: Fixed SPS_TANGENT for HLSL4<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreShaderCGProgramWriter.h"
#include "OgreStringConverter.h"
#include "OgreGpuProgramManager.h"
namespace Ogre {
namespace RTShader {
String CGProgramWriter::TargetLanguage = "cg";
//-----------------------------------------------------------------------
CGProgramWriter::CGProgramWriter()
{
initializeStringMaps();
}
//-----------------------------------------------------------------------
CGProgramWriter::~CGProgramWriter()
{
}
//-----------------------------------------------------------------------
void CGProgramWriter::initializeStringMaps()
{
mGpuConstTypeMap[GCT_FLOAT1] = "float";
mGpuConstTypeMap[GCT_FLOAT2] = "float2";
mGpuConstTypeMap[GCT_FLOAT3] = "float3";
mGpuConstTypeMap[GCT_FLOAT4] = "float4";
mGpuConstTypeMap[GCT_SAMPLER1D] = "sampler1D";
mGpuConstTypeMap[GCT_SAMPLER2D] = "sampler2D";
mGpuConstTypeMap[GCT_SAMPLER3D] = "sampler3D";
mGpuConstTypeMap[GCT_SAMPLERCUBE] = "samplerCUBE";
mGpuConstTypeMap[GCT_MATRIX_2X2] = "float2x2";
mGpuConstTypeMap[GCT_MATRIX_2X3] = "float2x3";
mGpuConstTypeMap[GCT_MATRIX_2X4] = "float2x4";
mGpuConstTypeMap[GCT_MATRIX_3X2] = "float3x2";
mGpuConstTypeMap[GCT_MATRIX_3X3] = "float3x3";
mGpuConstTypeMap[GCT_MATRIX_3X4] = "float3x4";
mGpuConstTypeMap[GCT_MATRIX_4X2] = "float4x2";
mGpuConstTypeMap[GCT_MATRIX_4X3] = "float4x3";
mGpuConstTypeMap[GCT_MATRIX_4X4] = "float4x4";
mGpuConstTypeMap[GCT_INT1] = "int";
mGpuConstTypeMap[GCT_INT2] = "int2";
mGpuConstTypeMap[GCT_INT3] = "int3";
mGpuConstTypeMap[GCT_INT4] = "int4";
mParamSemanticMap[Parameter::SPS_POSITION] = "POSITION";
mParamSemanticMap[Parameter::SPS_BLEND_WEIGHTS] = "BLENDWEIGHT";
mParamSemanticMap[Parameter::SPS_BLEND_INDICES] = "BLENDINDICES";
mParamSemanticMap[Parameter::SPS_NORMAL] = "NORMAL";
mParamSemanticMap[Parameter::SPS_COLOR] = "COLOR";
mParamSemanticMap[Parameter::SPS_TEXTURE_COORDINATES] = "TEXCOORD";
mParamSemanticMap[Parameter::SPS_BINORMAL] = "BINORMAL";
mParamSemanticMap[Parameter::SPS_TANGENT] = "TANGENT";
mParamSemanticMap[Parameter::SPS_UNKNOWN] = "";
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeSourceCode(std::ostream& os, Program* program)
{
const ShaderFunctionList& functionList = program->getFunctions();
ShaderFunctionConstIterator itFunction;
const UniformParameterList& parameterList = program->getParameters();
UniformParameterConstIterator itUniformParam = parameterList.begin();
// Generate source code header.
writeProgramTitle(os, program);
os << std::endl;
// Generate dependencies.
writeProgramDependencies(os, program);
os << std::endl;
// Generate global variable code.
writeUniformParametersTitle(os, program);
os << std::endl;
for (itUniformParam=parameterList.begin(); itUniformParam != parameterList.end(); ++itUniformParam)
{
writeUniformParameter(os, *itUniformParam);
os << ";" << std::endl;
}
os << std::endl;
// Write program function(s).
for (itFunction=functionList.begin(); itFunction != functionList.end(); ++itFunction)
{
Function* curFunction = *itFunction;
bool needToTranslateHlsl4Color = false;
ParameterPtr colorParameter;
writeFunctionTitle(os, curFunction);
writeFunctionDeclaration(os, curFunction, needToTranslateHlsl4Color, colorParameter);
os << "{" << std::endl;
// Write local parameters.
const ShaderParameterList& localParams = curFunction->getLocalParameters();
ShaderParameterConstIterator itParam;
for (itParam=localParams.begin(); itParam != localParams.end(); ++itParam)
{
os << "\t";
writeLocalParameter(os, *itParam);
os << ";" << std::endl;
}
// translate hlsl 4 color parameter if needed
if(needToTranslateHlsl4Color)
{
os << "\t";
writeLocalParameter(os, colorParameter);
os << ";" << std::endl;
os << std::endl <<"\tFFP_Assign(iHlsl4Color_0, " << colorParameter->getName() << ");" << std::endl;
}
// Sort and write function atoms.
curFunction->sortAtomInstances();
const FunctionAtomInstanceList& atomInstances = curFunction->getAtomInstances();
FunctionAtomInstanceConstIterator itAtom;
for (itAtom=atomInstances.begin(); itAtom != atomInstances.end(); ++itAtom)
{
writeAtomInstance(os, *itAtom);
}
os << "}" << std::endl;
}
os << std::endl;
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeProgramDependencies(std::ostream& os, Program* program)
{
os << "//-----------------------------------------------------------------------------" << std::endl;
os << "// PROGRAM DEPENDENCIES" << std::endl;
os << "//-----------------------------------------------------------------------------" << std::endl;
for (unsigned int i=0; i < program->getDependencyCount(); ++i)
{
const String& curDependency = program->getDependency(i);
os << "#include " << '\"' << curDependency << "." << getTargetLanguage() << '\"' << std::endl;
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeUniformParameter(std::ostream& os, UniformParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
if (parameter->isSampler())
{
os << " : register(s" << parameter->getIndex() << ")";
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeFunctionParameter(std::ostream& os, ParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
if (parameter->getSemantic() != Parameter::SPS_UNKNOWN)
{
os << " : ";
os << mParamSemanticMap[parameter->getSemantic()];
if (parameter->getSemantic() != Parameter::SPS_POSITION &&
parameter->getSemantic() != Parameter::SPS_NORMAL &&
parameter->getSemantic() != Parameter::SPS_TANGENT &&
(!(parameter->getSemantic() == Parameter::SPS_COLOR && parameter->getIndex() == 0)) &&
parameter->getIndex() >= 0)
{
os << StringConverter::toString(parameter->getIndex()).c_str();
}
}
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeLocalParameter(std::ostream& os, ParameterPtr parameter)
{
os << mGpuConstTypeMap[parameter->getType()];
os << "\t";
os << parameter->getName();
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeFunctionDeclaration(std::ostream& os, Function* function, bool & needToTranslateHlsl4Color, ParameterPtr & colorParameter)
{
const ShaderParameterList& inParams = function->getInputParameters();
const ShaderParameterList& outParams = function->getOutputParameters();
os << "void";
os << " ";
os << function->getName();
os << std::endl << "\t(" << std::endl;
ShaderParameterConstIterator it;
size_t paramsCount = inParams.size() + outParams.size();
size_t curParamIndex = 0;
// for shader model 4 - we need to get the color as unsigned int
bool isVs4 = GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0");
// Write input parameters.
for (it=inParams.begin(); it != inParams.end(); ++it)
{
os << "\t in ";
if (isVs4 &&
function->getFunctionType() == Function::FFT_VS_MAIN &&
(*it)->getSemantic() == Parameter::SPS_COLOR
)
{
os << "unsigned int iHlsl4Color_0 : COLOR";
needToTranslateHlsl4Color = true;
colorParameter = *it;
}
else
{
writeFunctionParameter(os, *it);
}
if (curParamIndex + 1 != paramsCount)
os << ", " << std::endl;
curParamIndex++;
}
// Write output parameters.
for (it=outParams.begin(); it != outParams.end(); ++it)
{
os << "\t out ";
writeFunctionParameter(os, *it);
if (curParamIndex + 1 != paramsCount)
os << ", " << std::endl;
curParamIndex++;
}
os << std::endl << "\t)" << std::endl;
}
//-----------------------------------------------------------------------
void CGProgramWriter::writeAtomInstance(std::ostream& os, FunctionAtom* atom)
{
os << std::endl << "\t";
atom->writeSourceCode(os, getTargetLanguage());
os << std::endl;
}
}
}
<|endoftext|> |
<commit_before>
#include "sui_service.h"
#include <algorithm>
#include "pub14_core/messages/sui_create_page_message.h"
#include "pub14_core/messages/sui_event_notification.h"
#include "pub14_core/messages/sui_update_page_message.h"
#include "pub14_core/messages/sui_force_close.h"
#include "swganh/connection/connection_client_interface.h"
#include "swganh/connection/connection_service_interface.h"
#include "swganh/sui/sui_window_interface.h"
#include "swganh/object/object.h"
#include "swganh/object/player/player.h"
#include "sui_window.h"
#include "swganh/app/swganh_kernel.h"
#include "anh/service/service_manager.h"
#include "anh/event_dispatcher.h"
using namespace anh::service;
using namespace swganh::app;
using namespace swganh_core::sui;
using namespace swganh::sui;
using namespace swganh::object;
using namespace swganh::object::player;
using namespace swganh::connection;
using namespace swganh::messages;
SUIService::SUIService(swganh::app::SwganhKernel* kernel)
: window_id_counter_(0)
{
//Subscribe to EventNotifcation
auto connection_service = kernel->GetServiceManager()->GetService<ConnectionServiceInterface>("ConnectionService");
connection_service->RegisterMessageHandler(&SUIService::_handleEventNotifyMessage, this);
//Subscribe to player logouts
kernel->GetEventDispatcher()->Subscribe(
"Connection::PlayerRemoved",
[this] (std::shared_ptr<anh::EventInterface> incoming_event)
{
//Clear all of this player's SUIs
const auto& player = std::static_pointer_cast<anh::ValueEvent<std::shared_ptr<Player>>>(incoming_event)->Get();
WindowMapRange range = window_lookup_.equal_range(player->GetObjectId());
window_lookup_.erase(range.first, range.second);
});
}
void SUIService::_handleEventNotifyMessage(const std::shared_ptr<swganh::connection::ConnectionClientInterface>& client, swganh::messages::SUIEventNotification message)
{
auto owner = client->GetPlayerId();
WindowMapRange range = window_lookup_.equal_range(owner);
std::shared_ptr<SUIWindowInterface> result = nullptr;
for(auto itr=range.first; itr != range.second; ++itr)
{
if(itr->second->GetWindowId() == message.window_id)
{
if(itr->second->GetFunctionById(message.event_type)(itr->second->GetOwner(), message.event_type, message.returnList))
{
window_lookup_.erase(itr);
}
break;
}
};
}
ServiceDescription SUIService::GetServiceDescription()
{
ServiceDescription service_description(
"SUIService",
"sui",
"0.1",
"127.0.0.1",
0,
0,
0);
return service_description;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateSUIWindow(std::string script_name, std::shared_ptr<swganh::object::Object> owner,
std::shared_ptr<swganh::object::Object> ranged_object, float max_distance)
{
return std::shared_ptr<SUIWindowInterface>(new SUIWindow(script_name, owner, ranged_object, max_distance));
}
//Creates a new SUI page and returns the id of the corresponding window id
int32_t SUIService::OpenSUIWindow(std::shared_ptr<SUIWindowInterface> window)
{
int32_t window_id = -1;
auto owner = window->GetOwner()->GetController();
if(owner != nullptr)
{
window_id = window_id_counter_++;
window_lookup_.insert(WindowMap::value_type(window->GetOwner()->GetObjectId(), window));
//Send Create to controller
SUICreatePageMessage create_page;
create_page.window_id = window_id;
create_page.script_name = window->GetScriptName();
create_page.components = std::move(window->GetComponents());
if(window->GetRangedObject())
{
create_page.ranged_object = window->GetRangedObject()->GetObjectId();
create_page.range = window->GetMaxDistance();
}
else
{
create_page.ranged_object = 0;
create_page.range = 0.0f;
}
owner->Notify(create_page);
}
return window_id;
}
//UpdateWindow
int32_t SUIService::UpdateSUIWindow(std::shared_ptr<SUIWindowInterface> window)
{
int32_t window_id = -1;
auto owner = window->GetOwner()->GetController();
if(owner != nullptr)
{
window_id = window->GetWindowId();
//Send Update to controller
SUIUpdatePageMessage update_page;
update_page.window_id = window_id;
update_page.script_name = window->GetScriptName();
update_page.components = std::move(window->GetComponents());
if(window->GetRangedObject())
{
update_page.ranged_object = window->GetRangedObject()->GetObjectId();
update_page.range = window->GetMaxDistance();
}
else
{
update_page.ranged_object = 0;
update_page.range = 0.0f;
}
owner->Notify(update_page);
}
return window_id;
}
//Get Window
std::shared_ptr<SUIWindowInterface> SUIService::GetSUIWindowById(std::shared_ptr<swganh::object::Object> owner, int32_t windowId)
{
WindowMapRange range = window_lookup_.equal_range(owner->GetObjectId());
std::shared_ptr<SUIWindowInterface> result = nullptr;
std::find_if(range.first, range.second, [&] (WindowMap::value_type& element) -> bool {
if(element.second->GetWindowId() == windowId)
{
result = element.second;
return true;
}
return false;
});
return result;
}
//Forcefully closes a previously opened page.
void SUIService::CloseSUIWindow(std::shared_ptr<swganh::object::Object> owner, int32_t windowId)
{
WindowMapRange range = window_lookup_.equal_range(owner->GetObjectId());
std::shared_ptr<SUIWindowInterface> result = nullptr;
for(auto itr=range.first; itr != range.second; ++itr)
{
if(itr->second->GetWindowId() == windowId)
{
result = itr->second;
window_lookup_.erase(itr);
break;
}
};
if(result != nullptr)
{
//Send Window Force Close
auto controller = owner->GetController();
if(controller)
{
SUIForceClose force_close;
force_close.window_id = windowId;
controller->Notify(force_close);
}
}
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateMessageBox(MessageBoxType msgBox_type, std::wstring title, std::wstring caption,
std::shared_ptr<Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.messageBox", owner, ranged_object, max_distance);
//Write out the basic properties
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", caption);
//Write out the buttons
result->SetProperty("btnRevert:visible", L"False");
switch(msgBox_type)
{
case MESSAGE_BOX_OK:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"btnOk");
result->SetProperty("btnCancel:visible", L"False");
break;
case MESSAGE_BOX_OK_CANCEL:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"btnOk");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"btnCancel");
break;
case MESSAGE_BOX_YES_NO:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"@yes");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"@no");
break;
}
return result;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateListBox(ListBoxType lstBox_type, std::wstring title, std::wstring prompt,
std::vector<std::wstring> dataList, std::shared_ptr<Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.listBox", owner, ranged_object, max_distance);
//Write out the basic properties
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", prompt);
//Write out the buttons
switch(lstBox_type)
{
case LIST_BOX_OKCANCEL:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"btnOk");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"btnCancel");
break;
case LIST_BOX_OK:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"btnOk");
result->SetProperty("btnCancel:visible", L"False");
break;
}
//Clear out the list
result->ClearDataSource("List.dataList");
//Write out the list
size_t index = 0;
std::wstringstream wss;
std::stringstream ss;
for(auto& string : dataList)
{
wss << index;
ss << "List.dataList." << index << ":Text";
//Now for each entry, we add it to the list with the id as the name
result->AddProperty("List.dataList:Name", wss.str());
//And Then set it's text property to the given string
result->SetProperty(ss.str(), string);
//Increment and clear the streams
++index;
wss.str(L"");
ss.str("");
}
return result;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateInputBox(InputBoxType iptBox_type, std::wstring title, std::wstring prompt,
uint32_t input_max_length, std::shared_ptr<swganh::object::Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.inputBox", owner, ranged_object, max_distance);
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", prompt);
switch(iptBox_type)
{
case INPUT_BOX_OK:
break;
case INPUT_BOX_OKCANCEL:
break;
}
result->SetProperty("cmbInput:visible", L"False");
return result;
}<commit_msg>Fixed another minor mistake<commit_after>
#include "sui_service.h"
#include <algorithm>
#include "pub14_core/messages/sui_create_page_message.h"
#include "pub14_core/messages/sui_event_notification.h"
#include "pub14_core/messages/sui_update_page_message.h"
#include "pub14_core/messages/sui_force_close.h"
#include "swganh/connection/connection_client_interface.h"
#include "swganh/connection/connection_service_interface.h"
#include "swganh/sui/sui_window_interface.h"
#include "swganh/object/object.h"
#include "swganh/object/player/player.h"
#include "sui_window.h"
#include "swganh/app/swganh_kernel.h"
#include "anh/service/service_manager.h"
#include "anh/event_dispatcher.h"
using namespace anh::service;
using namespace swganh::app;
using namespace swganh_core::sui;
using namespace swganh::sui;
using namespace swganh::object;
using namespace swganh::object::player;
using namespace swganh::connection;
using namespace swganh::messages;
SUIService::SUIService(swganh::app::SwganhKernel* kernel)
: window_id_counter_(0)
{
//Subscribe to EventNotifcation
auto connection_service = kernel->GetServiceManager()->GetService<ConnectionServiceInterface>("ConnectionService");
connection_service->RegisterMessageHandler(&SUIService::_handleEventNotifyMessage, this);
//Subscribe to player logouts
kernel->GetEventDispatcher()->Subscribe(
"Connection::PlayerRemoved",
[this] (std::shared_ptr<anh::EventInterface> incoming_event)
{
//Clear all of this player's SUIs
const auto& player = std::static_pointer_cast<anh::ValueEvent<std::shared_ptr<Player>>>(incoming_event)->Get();
WindowMapRange range = window_lookup_.equal_range(player->GetObjectId());
window_lookup_.erase(range.first, range.second);
});
}
void SUIService::_handleEventNotifyMessage(const std::shared_ptr<swganh::connection::ConnectionClientInterface>& client, swganh::messages::SUIEventNotification message)
{
auto owner = client->GetController()->GetId();
WindowMapRange range = window_lookup_.equal_range(owner);
std::shared_ptr<SUIWindowInterface> result = nullptr;
for(auto itr=range.first; itr != range.second; ++itr)
{
if(itr->second->GetWindowId() == message.window_id)
{
if(itr->second->GetFunctionById(message.event_type)(itr->second->GetOwner(), message.event_type, message.returnList))
{
window_lookup_.erase(itr);
}
break;
}
};
}
ServiceDescription SUIService::GetServiceDescription()
{
ServiceDescription service_description(
"SUIService",
"sui",
"0.1",
"127.0.0.1",
0,
0,
0);
return service_description;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateSUIWindow(std::string script_name, std::shared_ptr<swganh::object::Object> owner,
std::shared_ptr<swganh::object::Object> ranged_object, float max_distance)
{
return std::shared_ptr<SUIWindowInterface>(new SUIWindow(script_name, owner, ranged_object, max_distance));
}
//Creates a new SUI page and returns the id of the corresponding window id
int32_t SUIService::OpenSUIWindow(std::shared_ptr<SUIWindowInterface> window)
{
int32_t window_id = -1;
auto owner = window->GetOwner()->GetController();
if(owner != nullptr)
{
window_id = window_id_counter_++;
window_lookup_.insert(WindowMap::value_type(window->GetOwner()->GetObjectId(), window));
//Send Create to controller
SUICreatePageMessage create_page;
create_page.window_id = window_id;
create_page.script_name = window->GetScriptName();
create_page.components = std::move(window->GetComponents());
if(window->GetRangedObject())
{
create_page.ranged_object = window->GetRangedObject()->GetObjectId();
create_page.range = window->GetMaxDistance();
}
else
{
create_page.ranged_object = 0;
create_page.range = 0.0f;
}
owner->Notify(create_page);
}
return window_id;
}
//UpdateWindow
int32_t SUIService::UpdateSUIWindow(std::shared_ptr<SUIWindowInterface> window)
{
int32_t window_id = -1;
auto owner = window->GetOwner()->GetController();
if(owner != nullptr)
{
window_id = window->GetWindowId();
//Send Update to controller
SUIUpdatePageMessage update_page;
update_page.window_id = window_id;
update_page.script_name = window->GetScriptName();
update_page.components = std::move(window->GetComponents());
if(window->GetRangedObject())
{
update_page.ranged_object = window->GetRangedObject()->GetObjectId();
update_page.range = window->GetMaxDistance();
}
else
{
update_page.ranged_object = 0;
update_page.range = 0.0f;
}
owner->Notify(update_page);
}
return window_id;
}
//Get Window
std::shared_ptr<SUIWindowInterface> SUIService::GetSUIWindowById(std::shared_ptr<swganh::object::Object> owner, int32_t windowId)
{
WindowMapRange range = window_lookup_.equal_range(owner->GetObjectId());
std::shared_ptr<SUIWindowInterface> result = nullptr;
std::find_if(range.first, range.second, [&] (WindowMap::value_type& element) -> bool {
if(element.second->GetWindowId() == windowId)
{
result = element.second;
return true;
}
return false;
});
return result;
}
//Forcefully closes a previously opened page.
void SUIService::CloseSUIWindow(std::shared_ptr<swganh::object::Object> owner, int32_t windowId)
{
WindowMapRange range = window_lookup_.equal_range(owner->GetObjectId());
std::shared_ptr<SUIWindowInterface> result = nullptr;
for(auto itr=range.first; itr != range.second; ++itr)
{
if(itr->second->GetWindowId() == windowId)
{
result = itr->second;
window_lookup_.erase(itr);
break;
}
};
if(result != nullptr)
{
//Send Window Force Close
auto controller = owner->GetController();
if(controller)
{
SUIForceClose force_close;
force_close.window_id = windowId;
controller->Notify(force_close);
}
}
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateMessageBox(MessageBoxType msgBox_type, std::wstring title, std::wstring caption,
std::shared_ptr<Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.messageBox", owner, ranged_object, max_distance);
//Write out the basic properties
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", caption);
//Write out the buttons
result->SetProperty("btnRevert:visible", L"False");
switch(msgBox_type)
{
case MESSAGE_BOX_OK:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"@ok");
result->SetProperty("btnCancel:visible", L"False");
break;
case MESSAGE_BOX_OK_CANCEL:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"@ok");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"@cancel");
break;
case MESSAGE_BOX_YES_NO:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"@yes");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"@no");
break;
}
return result;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateListBox(ListBoxType lstBox_type, std::wstring title, std::wstring prompt,
std::vector<std::wstring> dataList, std::shared_ptr<Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.listBox", owner, ranged_object, max_distance);
//Write out the basic properties
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", prompt);
//Write out the buttons
switch(lstBox_type)
{
case LIST_BOX_OKCANCEL:
result->SetProperty("btnOk:visible", L"True")->SetProperty("btnOk:Text", L"@ok");
result->SetProperty("btnCancel:visible", L"True")->SetProperty("btnCancel:Text", L"@cancel");
break;
case LIST_BOX_OK:
result->SetProperty("btnOk:visible", L"True");
result->SetProperty("btnCancel:visible", L"False");
break;
}
//Clear out the list
result->ClearDataSource("List.dataList");
//Write out the list
size_t index = 0;
std::wstringstream wss;
std::stringstream ss;
for(auto& string : dataList)
{
wss << index;
ss << "List.dataList." << index << ":Text";
//Now for each entry, we add it to the list with the id as the name
result->AddProperty("List.dataList:Name", wss.str());
//And Then set it's text property to the given string
result->SetProperty(ss.str(), string);
//Increment and clear the streams
++index;
wss.str(L"");
ss.str("");
}
return result;
}
std::shared_ptr<SUIWindowInterface> SUIService::CreateInputBox(InputBoxType iptBox_type, std::wstring title, std::wstring prompt,
uint32_t input_max_length, std::shared_ptr<swganh::object::Object> owner, std::shared_ptr<Object> ranged_object, float max_distance)
{
std::shared_ptr<SUIWindowInterface> result = CreateSUIWindow("Script.inputBox", owner, ranged_object, max_distance);
result->SetProperty("bg.caption.lblTitle:Text", title)->SetProperty("Prompt.lblPrompt:Text", prompt);
switch(iptBox_type)
{
case INPUT_BOX_OK:
break;
case INPUT_BOX_OKCANCEL:
break;
}
result->SetProperty("cmbInput:visible", L"False");
return result;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dispatchrecordersupplier.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: as $ $Date: 2002-09-23 05:52:38 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// include own things
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// include interfaces
#ifndef _COM_SUN_STAR_FRAME_XRECORDABLEDISPATCH_HPP_
#include <com/sun/star/frame/XRecordableDispatch.hpp>
#endif
//_________________________________________________________________________________________________________________
// include other projects
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
// declarations
//*****************************************************************************************************************
// XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(
DispatchRecorderSupplier,
OWeakObject,
DIRECT_INTERFACE(css::lang::XTypeProvider),
DIRECT_INTERFACE(css::lang::XServiceInfo),
DIRECT_INTERFACE(css::frame::XDispatchRecorderSupplier))
DEFINE_XTYPEPROVIDER_3(
DispatchRecorderSupplier,
css::lang::XTypeProvider,
css::lang::XServiceInfo,
css::frame::XDispatchRecorderSupplier)
DEFINE_XSERVICEINFO_MULTISERVICE(
DispatchRecorderSupplier,
::cppu::OWeakObject,
SERVICENAME_DISPATCHRECORDERSUPPLIER,
IMPLEMENTATIONNAME_DISPATCHRECORDERSUPPLIER)
DEFINE_INIT_SERVICE(
DispatchRecorderSupplier,
{
/*Attention
I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()
to create a new instance of this class by our own supported service factory.
see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations!
*/
}
)
//_____________________________________________________________________________
/**
@short standard constructor to create instance
@descr Because an instance will be initialized by her interface methods
it's not neccessary to do anything here.
*/
DispatchRecorderSupplier::DispatchRecorderSupplier( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory )
// init baseclasses first!
// Attention: Don't change order of initialization!
: ThreadHelpBase ( &Application::GetSolarMutex() )
, ::cppu::OWeakObject( )
// init member
, m_xFactory ( xFactory )
, m_xDispatchRecorder( NULL )
{
}
//_____________________________________________________________________________
/**
@short standard destructor
@descr We are a helper and not a real service. So we doesn't provide
dispose() functionality. This supplier dies by ref count mechanism
and should release all internal used ones too.
*/
DispatchRecorderSupplier::~DispatchRecorderSupplier()
{
m_xFactory = NULL;
m_xDispatchRecorder = NULL;
}
//_____________________________________________________________________________
/**
@short set a new dispatch recorder on this supplier
@descr Because there can exist more then one recorder implementations
(to generate java/basic/... scripts from recorded data) it must
be possible to set it on a supplier.
@see getDispatchRecorder()
@param xRecorder
the new recorder to set it
<br><NULL/> isn't recommended, because recording without a
valid recorder can't work. But it's not checked here. So user
of this supplier can decide that without changing this
implementation.
@change 09.04.2002 by Andreas Schluens
*/
void SAL_CALL DispatchRecorderSupplier::setDispatchRecorder( const css::uno::Reference< css::frame::XDispatchRecorder >& xRecorder ) throw (css::uno::RuntimeException)
{
// SAFE =>
WriteGuard aWriteLock(m_aLock);
m_xDispatchRecorder=xRecorder;
// => SAFE
}
//_____________________________________________________________________________
/**
@short provides access to the dispatch recorder of this supplier
@descr Such recorder can be used outside to record dispatches.
But normaly he is used internaly only. Of course he must used
from outside to get the recorded data e.g. for saving it as a
script.
@see setDispatchRecorder()
@return the internal used dispatch recorder
<br>May it can be <NULL/> if no one was set before.
@change 09.04.2002 by Andreas Schluens
*/
css::uno::Reference< css::frame::XDispatchRecorder > SAL_CALL DispatchRecorderSupplier::getDispatchRecorder() throw (css::uno::RuntimeException)
{
// SAFE =>
ReadGuard aReadLock(m_aLock);
return m_xDispatchRecorder;
// => SAFE
}
//_____________________________________________________________________________
/**
@short execute a dispatch request and record it
@descr If given dispatch object provides right recording interface it
will be used. If it's not supported it record the pure dispatch
parameters only. There is no code neither the possibility to
check if recording is enabled or not.
@param aURL the command URL
@param lArguments optional arguments (see com.sun.star.document.MediaDescriptor for further informations)
@param xDispatcher the original dispatch object which should be recorded
@change 09.04.2002 by Andreas Schluens
*/
void SAL_CALL DispatchRecorderSupplier::dispatchAndRecord( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatch >& xDispatcher ) throw (css::uno::RuntimeException)
{
// SAFE =>
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::frame::XDispatchRecorder > xRecorder = m_xDispatchRecorder;
aReadLock.unlock();
// => SAFE
// clear unspecific situations
if (!xDispatcher.is())
throw css::uno::RuntimeException(DECLARE_ASCII("specification violation: dispatcher is NULL"), static_cast< ::cppu::OWeakObject* >(this));
if (!xRecorder.is())
throw css::uno::RuntimeException(DECLARE_ASCII("specification violation: no valid dispatch recorder available"), static_cast< ::cppu::OWeakObject* >(this));
// check, if given dispatch supports record functionality by itself ...
// or must be wrapped.
css::uno::Reference< css::frame::XRecordableDispatch > xRecordable(
xDispatcher,
css::uno::UNO_QUERY);
if (xRecordable.is())
xRecordable->dispatchAndRecord(aURL,lArguments,xRecorder);
else
{
// There is no reason to wait for information about success
// of this request. Because status information of a dispatch
// are not guaranteed. So we execute it and record used
// parameters only.
xDispatcher->dispatch(aURL,lArguments);
xRecorder->recordDispatch(aURL,lArguments);
}
}
} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.556); FILE MERGED 2005/09/05 13:06:43 rt 1.2.556.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchrecordersupplier.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:38:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//_________________________________________________________________________________________________________________
// include own things
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// include interfaces
#ifndef _COM_SUN_STAR_FRAME_XRECORDABLEDISPATCH_HPP_
#include <com/sun/star/frame/XRecordableDispatch.hpp>
#endif
//_________________________________________________________________________________________________________________
// include other projects
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
// declarations
//*****************************************************************************************************************
// XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(
DispatchRecorderSupplier,
OWeakObject,
DIRECT_INTERFACE(css::lang::XTypeProvider),
DIRECT_INTERFACE(css::lang::XServiceInfo),
DIRECT_INTERFACE(css::frame::XDispatchRecorderSupplier))
DEFINE_XTYPEPROVIDER_3(
DispatchRecorderSupplier,
css::lang::XTypeProvider,
css::lang::XServiceInfo,
css::frame::XDispatchRecorderSupplier)
DEFINE_XSERVICEINFO_MULTISERVICE(
DispatchRecorderSupplier,
::cppu::OWeakObject,
SERVICENAME_DISPATCHRECORDERSUPPLIER,
IMPLEMENTATIONNAME_DISPATCHRECORDERSUPPLIER)
DEFINE_INIT_SERVICE(
DispatchRecorderSupplier,
{
/*Attention
I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()
to create a new instance of this class by our own supported service factory.
see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations!
*/
}
)
//_____________________________________________________________________________
/**
@short standard constructor to create instance
@descr Because an instance will be initialized by her interface methods
it's not neccessary to do anything here.
*/
DispatchRecorderSupplier::DispatchRecorderSupplier( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory )
// init baseclasses first!
// Attention: Don't change order of initialization!
: ThreadHelpBase ( &Application::GetSolarMutex() )
, ::cppu::OWeakObject( )
// init member
, m_xFactory ( xFactory )
, m_xDispatchRecorder( NULL )
{
}
//_____________________________________________________________________________
/**
@short standard destructor
@descr We are a helper and not a real service. So we doesn't provide
dispose() functionality. This supplier dies by ref count mechanism
and should release all internal used ones too.
*/
DispatchRecorderSupplier::~DispatchRecorderSupplier()
{
m_xFactory = NULL;
m_xDispatchRecorder = NULL;
}
//_____________________________________________________________________________
/**
@short set a new dispatch recorder on this supplier
@descr Because there can exist more then one recorder implementations
(to generate java/basic/... scripts from recorded data) it must
be possible to set it on a supplier.
@see getDispatchRecorder()
@param xRecorder
the new recorder to set it
<br><NULL/> isn't recommended, because recording without a
valid recorder can't work. But it's not checked here. So user
of this supplier can decide that without changing this
implementation.
@change 09.04.2002 by Andreas Schluens
*/
void SAL_CALL DispatchRecorderSupplier::setDispatchRecorder( const css::uno::Reference< css::frame::XDispatchRecorder >& xRecorder ) throw (css::uno::RuntimeException)
{
// SAFE =>
WriteGuard aWriteLock(m_aLock);
m_xDispatchRecorder=xRecorder;
// => SAFE
}
//_____________________________________________________________________________
/**
@short provides access to the dispatch recorder of this supplier
@descr Such recorder can be used outside to record dispatches.
But normaly he is used internaly only. Of course he must used
from outside to get the recorded data e.g. for saving it as a
script.
@see setDispatchRecorder()
@return the internal used dispatch recorder
<br>May it can be <NULL/> if no one was set before.
@change 09.04.2002 by Andreas Schluens
*/
css::uno::Reference< css::frame::XDispatchRecorder > SAL_CALL DispatchRecorderSupplier::getDispatchRecorder() throw (css::uno::RuntimeException)
{
// SAFE =>
ReadGuard aReadLock(m_aLock);
return m_xDispatchRecorder;
// => SAFE
}
//_____________________________________________________________________________
/**
@short execute a dispatch request and record it
@descr If given dispatch object provides right recording interface it
will be used. If it's not supported it record the pure dispatch
parameters only. There is no code neither the possibility to
check if recording is enabled or not.
@param aURL the command URL
@param lArguments optional arguments (see com.sun.star.document.MediaDescriptor for further informations)
@param xDispatcher the original dispatch object which should be recorded
@change 09.04.2002 by Andreas Schluens
*/
void SAL_CALL DispatchRecorderSupplier::dispatchAndRecord( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatch >& xDispatcher ) throw (css::uno::RuntimeException)
{
// SAFE =>
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::frame::XDispatchRecorder > xRecorder = m_xDispatchRecorder;
aReadLock.unlock();
// => SAFE
// clear unspecific situations
if (!xDispatcher.is())
throw css::uno::RuntimeException(DECLARE_ASCII("specification violation: dispatcher is NULL"), static_cast< ::cppu::OWeakObject* >(this));
if (!xRecorder.is())
throw css::uno::RuntimeException(DECLARE_ASCII("specification violation: no valid dispatch recorder available"), static_cast< ::cppu::OWeakObject* >(this));
// check, if given dispatch supports record functionality by itself ...
// or must be wrapped.
css::uno::Reference< css::frame::XRecordableDispatch > xRecordable(
xDispatcher,
css::uno::UNO_QUERY);
if (xRecordable.is())
xRecordable->dispatchAndRecord(aURL,lArguments,xRecorder);
else
{
// There is no reason to wait for information about success
// of this request. Because status information of a dispatch
// are not guaranteed. So we execute it and record used
// parameters only.
xDispatcher->dispatch(aURL,lArguments);
xRecorder->recordDispatch(aURL,lArguments);
}
}
} // namespace framework
<|endoftext|> |
<commit_before>
#include "base/bundle.hpp"
#include <functional>
#include <list>
#include "base/map_util.hpp"
#include "base/status.hpp"
namespace principia {
namespace base {
void Bundle::Add(Task task) {
absl::MutexLock l(&lock_);
CHECK(!joining_);
++number_of_active_workers_;
workers_.emplace_back(&Bundle::Toil, this, std::move(task));
}
Status Bundle::Join() {
joining_ = true;
all_done_.WaitForNotification();
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
Status Bundle::JoinWithin(std::chrono::steady_clock::duration Δt) {
joining_ = true;
if (!all_done_.WaitForNotificationWithTimeout(absl::FromChrono(Δt))) {
absl::MutexLock l(&status_lock_);
status_ = Status(Error::DEADLINE_EXCEEDED, "bundle deadline exceeded");
}
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
Status Bundle::JoinBefore(std::chrono::system_clock::time_point t) {
joining_ = true;
if (!all_done_.WaitForNotificationWithDeadline(absl::FromChrono(t))) {
absl::MutexLock l(&status_lock_);
status_ = Status(Error::DEADLINE_EXCEEDED, "bundle deadline exceeded");
}
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
void Bundle::Toil(Task const& task) {
Status const status = task();
// Avoid locking if the task succeeded: it cannot affect the overall status.
if (!status.ok()) {
absl::MutexLock l(&status_lock_);
status_.Update(status);
}
// No locking unless this is the last task and we are joining. This
// avoids contention during joining. Note that if |joining_| is true we know
// that |number_of_active_workers_| cannot increase.
--number_of_active_workers_;
if (joining_ && number_of_active_workers_ == 0) {
all_done_.Notify();
}
}
void Bundle::JoinAll() {
absl::ReaderMutexLock l(&lock_);
for (auto& worker : workers_) {
worker.join();
}
}
} // namespace base
} // namespace principia
<commit_msg>Fix a race condition in the Bundle.<commit_after>
#include "base/bundle.hpp"
#include <functional>
#include <list>
#include "base/map_util.hpp"
#include "base/status.hpp"
namespace principia {
namespace base {
void Bundle::Add(Task task) {
absl::MutexLock l(&lock_);
CHECK(!joining_);
++number_of_active_workers_;
workers_.emplace_back(&Bundle::Toil, this, std::move(task));
}
Status Bundle::Join() {
joining_ = true;
all_done_.WaitForNotification();
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
Status Bundle::JoinWithin(std::chrono::steady_clock::duration Δt) {
joining_ = true;
if (!all_done_.WaitForNotificationWithTimeout(absl::FromChrono(Δt))) {
absl::MutexLock l(&status_lock_);
status_ = Status(Error::DEADLINE_EXCEEDED, "bundle deadline exceeded");
}
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
Status Bundle::JoinBefore(std::chrono::system_clock::time_point t) {
joining_ = true;
if (!all_done_.WaitForNotificationWithDeadline(absl::FromChrono(t))) {
absl::MutexLock l(&status_lock_);
status_ = Status(Error::DEADLINE_EXCEEDED, "bundle deadline exceeded");
}
JoinAll();
absl::ReaderMutexLock status_lock(&status_lock_);
return status_;
}
void Bundle::Toil(Task const& task) {
Status const status = task();
// Avoid locking if the task succeeded: it cannot affect the overall status.
if (!status.ok()) {
absl::MutexLock l(&status_lock_);
status_.Update(status);
}
// No locking, so as to avoid contention during joining. Note that if
// |joining_| is true we know that |number_of_active_workers_| cannot
// increase. Reading |number_of_active_workers_| independently from the
// decrement would be incorrect as we must ensure that exactly one thread sees
// that counter dropping to zero.
int const number_of_active_workers = --number_of_active_workers_;
if (joining_ && number_of_active_workers == 0) {
all_done_.Notify();
}
}
void Bundle::JoinAll() {
absl::ReaderMutexLock l(&lock_);
for (auto& worker : workers_) {
worker.join();
}
}
} // namespace base
} // namespace principia
<|endoftext|> |
<commit_before>/***************************************************************************
[email protected] - last modified on 05/09/2016
//
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskKStarpPbRunII(
Bool_t isMC = kFALSE,
Bool_t isPP = kFALSE,
Int_t Strcut = 2011,
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidphikstarpPb2016,
Float_t nsigmaPi = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmaTOF = 3.0,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 5,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0,
TString outNameSuffix = "pPb"
)
{
Bool_t rejectPileUp = kTRUE;
//if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskKStarPbPbRunTwo", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("KStar%s%s", (isPP? "pp" : "PPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
task->UseESDTriggerMask(AliVEvent::kINT7);
//if (isPP)
//task->UseMultiplicity("QUALITY");
//else
// task->UseMultiplicity("AliMultSelection_V0M");//Only for RunII
task->UseMultiplicity("AliMultSelection_V0A");//Only for RunII
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskKStarPbPbRunTwo", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckAcceptedMultSelection();
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
//cutY->SetRangeD(-0.5, 0.5);
cutY->SetRangeD(-0.465, 0.035);// 0 < y_cm < 0.5; y_cm = y_lab + 0.465
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarpPbRunII.C");
// gROOT->LoadMacro("ConfigKStarPbPbRunII.C");
if (!ConfigKStarpPbRunII(task, isMC, isPP, cutsPair,Strcut,customQualityCutsID,cutKaCandidate,nsigmaPi,nsigmaK,nsigmaTOF,enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
//outputFileName += ":Rsn";
Printf("AddTaskKStarPbPbRunTwo - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>Add rapidity range for KStar analysis in pPb collisions<commit_after>/***************************************************************************
[email protected] - last modified on 05/09/2016
//
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskKStarpPbRunII(
Bool_t isMC = kFALSE,
Bool_t isPP = kFALSE,
Int_t Strcut = 2011,
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidphikstarpPb2016,
Float_t nsigmaPi = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmaTOF = 3.0,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 5,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0,
Float_t lrap = -0.465,
Float_t hrap = 0.035,
TString outNameSuffix = "pPb"
)
{
Bool_t rejectPileUp = kTRUE;
//if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskKStarPbPbRunTwo", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("KStar%s%s", (isPP? "pp" : "PPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
task->UseESDTriggerMask(AliVEvent::kINT7);
//if (isPP)
//task->UseMultiplicity("QUALITY");
//else
// task->UseMultiplicity("AliMultSelection_V0M");//Only for RunII
task->UseMultiplicity("AliMultSelection_V0A");//Only for RunII
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskKStarPbPbRunTwo", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckAcceptedMultSelection();
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 400, -20.0, 20.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 400, 0.0, 400.0);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
//cutY->SetRangeD(-0.5, 0.5);
cutY->SetRangeD(lrap, hrap);// 0 < y_cm < 0.5; y_cm = y_lab + 0.465
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarpPbRunII.C");
// gROOT->LoadMacro("ConfigKStarPbPbRunII.C");
if (!ConfigKStarpPbRunII(task, isMC, isPP, cutsPair,Strcut,customQualityCutsID,cutKaCandidate,nsigmaPi,nsigmaK,nsigmaTOF,enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
//outputFileName += ":Rsn";
Printf("AddTaskKStarPbPbRunTwo - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generictoolbarcontroller.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:20:18 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_GENERICTOOLBARCONTROLLER_HXX
#include "uielement/generictoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>
using namespace ::rtl;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace framework
{
static sal_Bool isEnumCommand( const rtl::OUString& rCommand )
{
INetURLObject aURL( rCommand );
if (( aURL.GetProtocol() == INET_PROT_UNO ) &&
( aURL.GetURLPath().indexOf( '.' ) != -1))
return sal_True;
return sal_False;
}
static rtl::OUString getEnumCommand( const rtl::OUString& rCommand )
{
INetURLObject aURL( rCommand );
rtl::OUString aEnumCommand;
String aURLPath = aURL.GetURLPath();
xub_StrLen nIndex = aURLPath.Search( '.' );
if (( nIndex > 0 ) && ( nIndex < aURLPath.Len() ))
aEnumCommand = aURLPath.Copy( nIndex+1 );
return aEnumCommand;
}
static rtl::OUString getMasterCommand( const rtl::OUString& rCommand )
{
rtl::OUString aMasterCommand( rCommand );
INetURLObject aURL( rCommand );
if ( aURL.GetProtocol() == INET_PROT_UNO )
{
sal_Int32 nIndex = aURL.GetURLPath().indexOf( '.' );
if ( nIndex )
{
aURL.SetURLPath( aURL.GetURLPath().copy( 0, nIndex ) );
aMasterCommand = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
}
return aMasterCommand;
}
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
GenericToolbarController::GenericToolbarController( const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBar* pToolbar,
USHORT nID,
const OUString& aCommand ) :
svt::ToolboxController( rServiceManager, rFrame, aCommand )
, m_pToolbar( pToolbar )
, m_nID( nID )
, m_bEnumCommand( isEnumCommand( aCommand ))
, m_bMadeInvisible( sal_False )
, m_aEnumCommand( getEnumCommand( aCommand ))
{
if ( m_bEnumCommand )
addStatusListener( getMasterCommand( aCommand ) );
}
GenericToolbarController::~GenericToolbarController()
{
}
void SAL_CALL GenericToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
svt::ToolboxController::dispose();
m_pToolbar = 0;
m_nID = 0;
}
void SAL_CALL GenericToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
aCommandURL = m_aCommandURL;
URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
if ( pIter != m_aListenerMap.end() )
xDispatch = pIter->second;
}
}
if ( xDispatch.is() && xURLTransformer.is() )
{
com::sun::star::util::URL aTargetURL;
Sequence<PropertyValue> aArgs( 1 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aTargetURL.Complete = aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, GenericToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
void GenericToolbarController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
return;
if ( m_pToolbar )
{
m_pToolbar->EnableItem( m_nID, Event.IsEnabled );
USHORT nItemBits = m_pToolbar->GetItemBits( m_nID );
nItemBits &= ~TIB_CHECKABLE;
TriState eTri = STATE_NOCHECK;
sal_Bool bValue = sal_Bool();
rtl::OUString aStrValue;
ItemStatus aItemState;
Visibility aItemVisibility;
if (( Event.State >>= bValue ) && !m_bEnumCommand )
{
// Boolean, treat it as checked/unchecked
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
m_pToolbar->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( Event.State >>= aStrValue )
{
if ( m_bEnumCommand )
{
if ( aStrValue == m_aEnumCommand )
bValue = sal_True;
else
bValue = sal_False;
m_pToolbar->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else
{
::rtl::OUString aText( MnemonicGenerator::EraseAllMnemonicChars( aStrValue ) );
m_pToolbar->SetItemText( m_nID, aText );
m_pToolbar->SetQuickHelpText( m_nID, aText );
}
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
}
else if (( Event.State >>= aItemState ) && !m_bEnumCommand )
{
eTri = STATE_DONTKNOW;
nItemBits |= TIB_CHECKABLE;
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
}
else if ( Event.State >>= aItemVisibility )
{
m_pToolbar->ShowItem( m_nID, aItemVisibility.bVisible );
m_bMadeInvisible = !aItemVisibility.bVisible;
}
else if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
m_pToolbar->SetItemState( m_nID, eTri );
m_pToolbar->SetItemBits( m_nID, nItemBits );
}
}
IMPL_STATIC_LINK_NOINSTANCE( GenericToolbarController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
const sal_uInt32 nRef = Application::ReleaseSolarMutex();
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
Application::AcquireSolarMutex( nRef );
delete pExecuteInfo;
return 0;
}
} // namespace
<commit_msg>INTEGRATION: CWS fwk66 (1.18.100); FILE MERGED 2007/06/04 11:22:20 cd 1.18.100.1: #i78020# Support merging to menu and toolbar for add-ons<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generictoolbarcontroller.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: ihi $ $Date: 2007-07-10 15:11:20 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_GENERICTOOLBARCONTROLLER_HXX
#include "uielement/generictoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>
using namespace ::rtl;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace framework
{
static sal_Bool isEnumCommand( const rtl::OUString& rCommand )
{
INetURLObject aURL( rCommand );
if (( aURL.GetProtocol() == INET_PROT_UNO ) &&
( aURL.GetURLPath().indexOf( '.' ) != -1))
return sal_True;
return sal_False;
}
static rtl::OUString getEnumCommand( const rtl::OUString& rCommand )
{
INetURLObject aURL( rCommand );
rtl::OUString aEnumCommand;
String aURLPath = aURL.GetURLPath();
xub_StrLen nIndex = aURLPath.Search( '.' );
if (( nIndex > 0 ) && ( nIndex < aURLPath.Len() ))
aEnumCommand = aURLPath.Copy( nIndex+1 );
return aEnumCommand;
}
static rtl::OUString getMasterCommand( const rtl::OUString& rCommand )
{
rtl::OUString aMasterCommand( rCommand );
INetURLObject aURL( rCommand );
if ( aURL.GetProtocol() == INET_PROT_UNO )
{
sal_Int32 nIndex = aURL.GetURLPath().indexOf( '.' );
if ( nIndex )
{
aURL.SetURLPath( aURL.GetURLPath().copy( 0, nIndex ) );
aMasterCommand = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
}
return aMasterCommand;
}
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
GenericToolbarController::GenericToolbarController( const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBox* pToolbar,
USHORT nID,
const OUString& aCommand ) :
svt::ToolboxController( rServiceManager, rFrame, aCommand )
, m_pToolbar( pToolbar )
, m_nID( nID )
, m_bEnumCommand( isEnumCommand( aCommand ))
, m_bMadeInvisible( sal_False )
, m_aEnumCommand( getEnumCommand( aCommand ))
{
if ( m_bEnumCommand )
addStatusListener( getMasterCommand( aCommand ) );
}
GenericToolbarController::~GenericToolbarController()
{
}
void SAL_CALL GenericToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
svt::ToolboxController::dispose();
m_pToolbar = 0;
m_nID = 0;
}
void SAL_CALL GenericToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
UNO_QUERY );
aCommandURL = m_aCommandURL;
URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
if ( pIter != m_aListenerMap.end() )
xDispatch = pIter->second;
}
}
if ( xDispatch.is() && xURLTransformer.is() )
{
com::sun::star::util::URL aTargetURL;
Sequence<PropertyValue> aArgs( 1 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aTargetURL.Complete = aCommandURL;
xURLTransformer->parseStrict( aTargetURL );
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, GenericToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
void GenericToolbarController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
return;
if ( m_pToolbar )
{
m_pToolbar->EnableItem( m_nID, Event.IsEnabled );
USHORT nItemBits = m_pToolbar->GetItemBits( m_nID );
nItemBits &= ~TIB_CHECKABLE;
TriState eTri = STATE_NOCHECK;
sal_Bool bValue = sal_Bool();
rtl::OUString aStrValue;
ItemStatus aItemState;
Visibility aItemVisibility;
if (( Event.State >>= bValue ) && !m_bEnumCommand )
{
// Boolean, treat it as checked/unchecked
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
m_pToolbar->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( Event.State >>= aStrValue )
{
if ( m_bEnumCommand )
{
if ( aStrValue == m_aEnumCommand )
bValue = sal_True;
else
bValue = sal_False;
m_pToolbar->CheckItem( m_nID, bValue );
if ( bValue )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else
{
::rtl::OUString aText( MnemonicGenerator::EraseAllMnemonicChars( aStrValue ) );
m_pToolbar->SetItemText( m_nID, aText );
m_pToolbar->SetQuickHelpText( m_nID, aText );
}
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
}
else if (( Event.State >>= aItemState ) && !m_bEnumCommand )
{
eTri = STATE_DONTKNOW;
nItemBits |= TIB_CHECKABLE;
if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
}
else if ( Event.State >>= aItemVisibility )
{
m_pToolbar->ShowItem( m_nID, aItemVisibility.bVisible );
m_bMadeInvisible = !aItemVisibility.bVisible;
}
else if ( m_bMadeInvisible )
m_pToolbar->ShowItem( m_nID, TRUE );
m_pToolbar->SetItemState( m_nID, eTri );
m_pToolbar->SetItemBits( m_nID, nItemBits );
}
}
IMPL_STATIC_LINK_NOINSTANCE( GenericToolbarController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
const sal_uInt32 nRef = Application::ReleaseSolarMutex();
try
{
// Asynchronous execution as this can lead to our own destruction!
// Framework can recycle our current frame and the layout manager disposes all user interface
// elements if a component gets detached from its frame!
pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
}
catch ( Exception& )
{
}
Application::AcquireSolarMutex( nRef );
delete pExecuteInfo;
return 0;
}
} // namespace
<|endoftext|> |
<commit_before>#pragma once
#include "../std/function.hpp"
namespace threads
{
typedef function<void()> RunnerFuncT;
// Base Runner interface: performes given tasks.
class IRunner
{
public:
virtual void Run(RunnerFuncT const & f) const = 0;
protected:
virtual ~IRunner() {}
// Waits until all running threads stop.
// Not for public use! Used in unit tests only, since
// some runners use global thread pool and interfere with each other.
virtual void Join() = 0;
};
// Synchronous implementation: just immediately executes given tasks.
class SimpleRunner : public IRunner
{
public:
virtual void Run(RunnerFuncT const & f) const
{
f();
}
protected:
virtual void Join()
{
}
};
}
<commit_msg>Move Runner destructor back to public.<commit_after>#pragma once
#include "../std/function.hpp"
namespace threads
{
typedef function<void()> RunnerFuncT;
// Base Runner interface: performes given tasks.
class IRunner
{
public:
virtual ~IRunner() {}
virtual void Run(RunnerFuncT const & f) const = 0;
protected:
// Waits until all running threads stop.
// Not for public use! Used in unit tests only, since
// some runners use global thread pool and interfere with each other.
virtual void Join() = 0;
};
// Synchronous implementation: just immediately executes given tasks.
class SimpleRunner : public IRunner
{
public:
virtual void Run(RunnerFuncT const & f) const
{
f();
}
protected:
virtual void Join()
{
}
};
}
<|endoftext|> |
<commit_before>#include "compress_keyword_encoding.h"
#include "bytebuffer.h"
#include <stdexcept>
#include <sstream>
#include <map>
#include <unordered_map>
std::string initializeSymbols()
{
std::string s;
for(int i = 32; i < 127; ++i)
s += i;
return s;
}
static std::string symbols = initializeSymbols();
bool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output)
{
const char * inChars = (const char *)input.Data();
size_t symIndex;
char c;
for(size_t i=0; i < input.Size(); ++i)
{
c = inChars[i];
if((symIndex = symbols.find(c)) != std::string::npos)
symbols.erase(symbols.begin() + symIndex);
}
std::map<std::string, unsigned int>::iterator it;
std::map<std::string, unsigned int> stringFrequencies;
std::istringstream in((char *)input.Data());
std::string temp;
while(in.good())
{
in >> temp;
it = stringFrequencies.find(temp);
if(it != stringFrequencies.end())
++it->second;
else
stringFrequencies.insert(it, std::make_pair(temp, 1));
}
std::map<unsigned int, std::vector<std::string>> foda;
std::map<unsigned int, std::vector<std::string>>::iterator it1;
for (const auto& elem: stringFrequencies)
{
it1 = foda.find(elem.second);
if (it1 != foda.end())
{
it1->second.push_back(elem.first);
}
else
{
it1 = foda.insert(it1, std::make_pair(elem.second, std::vector<std::string>()));
it1->second.push_back(elem.first);
}
}
std::unordered_map<std::string, char> encodedStrings;
std::unordered_map<std::string, char>::iterator encodedStringsIt;
it1 = foda.begin();
for(std::string::iterator it_s = symbols.begin(); it_s != symbols.end() && it1 != foda.end(); ++it_s, ++it1)
for(size_t i=0; i < it1->second.size(); ++i, ++it_s)
{
encodedStrings.insert(std::make_pair(it1->second[i], *it_s));
if(it_s == symbols.end())
break;
}
output.WriteDynInt(encodedStrings.size());
for(encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt)
{
output.WriteUInt8(encodedStringsIt->second);
output.WriteString(encodedStringsIt->first);
}
in = std::istringstream((char *)input.Data());
std::ostringstream out;
while(in.good())
{
in >> temp;
if((encodedStringsIt = encodedStrings.find(temp)) != encodedStrings.end())
output.WriteString(std::string(1,encodedStringsIt->second));//out << encodedStringsIt->second;
else
output.WriteString(temp); //out << temp;
}
/*temp = out.str();
output.WriteBuffer(temp.c_str(), temp.size());*/
//output.WriteUInt8(0);
return true;
}
bool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output)
{
ByteBuffer* hack = const_cast<ByteBuffer*>(&input);
std::unordered_map<char, std::string> encodedSymbols;
std::unordered_map<char, std::string>::iterator encodedSymbolsIt;
int numTableEntries;
numTableEntries = hack->ReadDynInt();
char symbol;
std::string expression;
for(; numTableEntries > 0; --numTableEntries)
{
symbol = (char)hack->ReadUInt8();
expression = hack->ReadString();
encodedSymbols.insert(std::make_pair(symbol, expression));
}
std::string temp;
do
{
temp = hack->ReadString();
if(temp.size() > 0 && (encodedSymbolsIt = encodedSymbols.find(temp.at(0))) != encodedSymbols.end())
output.WriteString(encodedSymbolsIt->second);
else
output.WriteString(temp);
} while(hack->GetReadPos() != hack->GetWritePos());
return true;
}
<commit_msg>Refactor CompressKeywordEncoding::CompressImpl and CompressKeywordEncoding::DecompressImpl: now without fodas<commit_after>#include "compress_keyword_encoding.h"
#include "bytebuffer.h"
#include <stdexcept>
#include <sstream>
#include <map>
#include <unordered_map>
std::string initializeSymbols()
{
std::string s;
for(int i = 0; i < 127; ++i)
s += i;
return s;
}
static std::string symbols = initializeSymbols();
bool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output)
{
const char * inChars = (const char *)input.Data();
size_t symIndex;
char c;
for(size_t i=0; i < input.Size(); ++i)
{
c = inChars[i];
if((symIndex = symbols.find(c)) != std::string::npos)
symbols.erase(symbols.begin() + symIndex);
}
std::map<std::string, unsigned int>::iterator it;
std::map<std::string, unsigned int> stringFrequencies;
std::istringstream in((char *)input.Data());
std::string temp;
while(in.good())
{
in >> temp;
it = stringFrequencies.find(temp);
if(it != stringFrequencies.end())
++it->second;
else
stringFrequencies.insert(it, std::make_pair(temp, 1));
}
std::map<unsigned int, std::vector<std::string>> reverseStringFrequencies;
std::map<unsigned int, std::vector<std::string>>::iterator it1;
for (const auto& elem: stringFrequencies)
{
it1 = reverseStringFrequencies.find(elem.second);
if (it1 != reverseStringFrequencies.end())
{
it1->second.push_back(elem.first);
}
else
{
it1 = reverseStringFrequencies.insert(it1, std::make_pair(elem.second, std::vector<std::string>()));
it1->second.push_back(elem.first);
}
}
std::unordered_map<std::string, char> encodedStrings;
std::unordered_map<std::string, char>::iterator encodedStringsIt;
it1 = reverseStringFrequencies.begin();
for(std::string::iterator it_s = symbols.begin(); it_s != symbols.end() && it1 != reverseStringFrequencies.end(); ++it_s, ++it1)
for(size_t i=0; i < it1->second.size(); ++i, ++it_s)
{
encodedStrings.insert(std::make_pair(it1->second[i], *it_s));
if(it_s == symbols.end())
break;
}
output.WriteDynInt(encodedStrings.size());
for(encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt)
{
output.WriteUInt8(encodedStringsIt->second);
output.WriteString(encodedStringsIt->first);
}
in = std::istringstream((char *)input.Data());
std::ostringstream out;
while(in.good())
{
in >> temp;
if((encodedStringsIt = encodedStrings.find(temp)) != encodedStrings.end())
output.WriteString(std::string(1,encodedStringsIt->second));
else
output.WriteString(temp);
}
return true;
}
bool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output)
{
ByteBuffer* hack = const_cast<ByteBuffer*>(&input);
std::unordered_map<char, std::string> encodedSymbols;
std::unordered_map<char, std::string>::iterator encodedSymbolsIt;
int numTableEntries;
numTableEntries = hack->ReadDynInt();
char symbol;
std::string expression;
for(; numTableEntries > 0; --numTableEntries)
{
symbol = (char)hack->ReadUInt8();
expression = hack->ReadString();
encodedSymbols.insert(std::make_pair(symbol, expression));
}
std::string temp;
do
{
temp = hack->ReadString();
if(temp.size() > 0 && (encodedSymbolsIt = encodedSymbols.find(temp.at(0))) != encodedSymbols.end())
output.WriteString(encodedSymbolsIt->second);
else
output.WriteString(temp);
} while(hack->CanRead());
return true;
}
<|endoftext|> |
<commit_before>//
// recurse example usage
//
// build as:
//
// qmake .
// make
//
#include "../recurse.hpp"
#include <QtConcurrent/QtConcurrent>
int main(int argc, char *argv[])
{
Recurse app(argc, argv);
// Start middleware, logger
app.use([](auto &ctx, auto next) {
qDebug() << "received a new request from:" << ctx.request.ip;
next();
});
// Second middleware, sets custom data
app.use([](auto &ctx, auto next) {
qDebug() << "routed request" << ctx.request.header;
// custom data to be passed around - qvariant types
ctx.set("customdata", "value");
// for any kind of data use
// ctx.data["key"] = *void
next();
});
// Final middleware, does long running action concurrently and sends response as json
app.use([](auto &ctx) {
auto &res = ctx.response;
auto &req = ctx.request;
// show header and our custom data
qDebug() << "last route" << req.header << " " << ctx.get("customdata");
// set custom header
res.header["x-foo-data"] = "tvmid";
// these are already default values
// text/plain will be overriden by send if json is wanted
res.status(200).type("text/plain");
// some long running action in new thread pool
auto future = QtConcurrent::run([]{
qDebug() << "long running action...";
// return our demo result
return QJsonDocument::fromJson("{\"hello\" : \"world\"}");
});
auto watcher = new QFutureWatcher<QJsonDocument>;
QObject::connect(watcher, &QFutureWatcher<QJsonDocument>::finished,[&res, future]() {
qDebug() << "long running action done";
// send our demo result
res.send(future.result());
});
watcher->setFuture(future);
});
qDebug() << "starting on port 3000...";
app.listen(3000);
}
<commit_msg>example: comment fixes<commit_after>//
// recurse example usage
//
// build as:
//
// qmake .
// make
//
#include "../recurse.hpp"
#include <QtConcurrent/QtConcurrent>
int main(int argc, char *argv[])
{
Recurse app(argc, argv);
// Start middleware, logger
app.use([](auto &ctx, auto next) {
qDebug() << "received a new request from:" << ctx.request.ip;
next();
});
// Second middleware, sets custom data
app.use([](auto &ctx, auto next) {
qDebug() << "routed request" << ctx.request.header;
// custom data to be passed around - qvariant types
ctx.set("customdata", "value");
// for any kind of data use
// ctx.data["key"] = *void
next();
});
// Final middleware, does long running action concurrently and sends response as json
app.use([](auto &ctx) {
auto &res = ctx.response;
auto &req = ctx.request;
// show header and our custom data
qDebug() << "last route" << req.header << " " << ctx.get("customdata");
// set custom header
res.header["x-foo-data"] = "tvmid";
// these are already default values
// text/plain will be overriden by send if json is wanted
res.status(200).type("text/plain");
// some long running action runs in thread pool
auto future = QtConcurrent::run([]{
qDebug() << "long running action...";
// return our demo result
return QJsonDocument::fromJson("{\"hello\" : \"world\"}");
});
// get results and send response to client
auto watcher = new QFutureWatcher<QJsonDocument>;
QObject::connect(watcher, &QFutureWatcher<QJsonDocument>::finished,[&res, future]() {
qDebug() << "long running action done";
// send our demo result
res.send(future.result());
});
watcher->setFuture(future);
});
qDebug() << "starting on port 3000...";
app.listen(3000);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebM 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 <cmath>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
// CQ level range: [kCQLevelMin, kCQLevelMax).
const int kCQLevelMin = 4;
const int kCQLevelMax = 63;
const int kCQLevelStep = 8;
const unsigned int kCQTargetBitrate = 2000;
class CQTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<int> {
protected:
CQTest() : EncoderTest(GET_PARAM(0)), cq_level_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
}
virtual ~CQTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(libvpx_test::kTwoPassGood);
}
virtual void BeginPassHook(unsigned int /*pass*/) {
file_size_ = 0;
psnr_ = 0.0;
n_frames_ = 0;
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
if (cfg_.rc_end_usage == VPX_CQ) {
encoder->Control(VP8E_SET_CQ_LEVEL, cq_level_);
}
encoder->Control(VP8E_SET_CPUUSED, 3);
}
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pow(10.0, pkt->data.psnr.psnr[0] / 10.0);
n_frames_++;
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
file_size_ += pkt->data.frame.sz;
}
double GetLinearPSNROverBitrate() const {
double avg_psnr = log10(psnr_ / n_frames_) * 10.0;
return pow(10.0, avg_psnr / 10.0) / file_size_;
}
size_t file_size() const { return file_size_; }
int n_frames() const { return n_frames_; }
private:
int cq_level_;
size_t file_size_;
double psnr_;
int n_frames_;
};
unsigned int prev_actual_bitrate = kCQTargetBitrate;
TEST_P(CQTest, LinearPSNRIsHigherForCQLevel) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = kCQTargetBitrate;
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_CQ;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double cq_psnr_lin = GetLinearPSNROverBitrate();
const unsigned int cq_actual_bitrate =
static_cast<unsigned int>(file_size()) * 8 * 30 / (n_frames() * 1000);
EXPECT_LE(cq_actual_bitrate, kCQTargetBitrate);
EXPECT_LE(cq_actual_bitrate, prev_actual_bitrate);
prev_actual_bitrate = cq_actual_bitrate;
// try targeting the approximate same bitrate with VBR mode
cfg_.rc_end_usage = VPX_VBR;
cfg_.rc_target_bitrate = cq_actual_bitrate;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double vbr_psnr_lin = GetLinearPSNROverBitrate();
EXPECT_GE(cq_psnr_lin, vbr_psnr_lin);
}
VP8_INSTANTIATE_TEST_CASE(CQTest,
::testing::Range(kCQLevelMin, kCQLevelMax,
kCQLevelStep));
} // namespace
<commit_msg>cq_test: allow test cases to be run out of order<commit_after>/*
* Copyright (c) 2012 The WebM 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 <cmath>
#include <map>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
// CQ level range: [kCQLevelMin, kCQLevelMax).
const int kCQLevelMin = 4;
const int kCQLevelMax = 63;
const int kCQLevelStep = 8;
const unsigned int kCQTargetBitrate = 2000;
class CQTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<int> {
public:
// maps the cqlevel to the bitrate produced.
typedef std::map<int, uint32_t> BitrateMap;
static void SetUpTestCase() {
bitrates_.clear();
}
static void TearDownTestCase() {
ASSERT_TRUE(!HasFailure())
<< "skipping bitrate validation due to earlier failure.";
uint32_t prev_actual_bitrate = kCQTargetBitrate;
for (BitrateMap::const_iterator iter = bitrates_.begin();
iter != bitrates_.end(); ++iter) {
const uint32_t cq_actual_bitrate = iter->second;
EXPECT_LE(cq_actual_bitrate, prev_actual_bitrate)
<< "cq_level: " << iter->first
<< ", bitrate should decrease with increase in CQ level.";
prev_actual_bitrate = cq_actual_bitrate;
}
}
protected:
CQTest() : EncoderTest(GET_PARAM(0)), cq_level_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
}
virtual ~CQTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(libvpx_test::kTwoPassGood);
}
virtual void BeginPassHook(unsigned int /*pass*/) {
file_size_ = 0;
psnr_ = 0.0;
n_frames_ = 0;
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
if (cfg_.rc_end_usage == VPX_CQ) {
encoder->Control(VP8E_SET_CQ_LEVEL, cq_level_);
}
encoder->Control(VP8E_SET_CPUUSED, 3);
}
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pow(10.0, pkt->data.psnr.psnr[0] / 10.0);
n_frames_++;
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
file_size_ += pkt->data.frame.sz;
}
double GetLinearPSNROverBitrate() const {
double avg_psnr = log10(psnr_ / n_frames_) * 10.0;
return pow(10.0, avg_psnr / 10.0) / file_size_;
}
int cq_level() const { return cq_level_; }
size_t file_size() const { return file_size_; }
int n_frames() const { return n_frames_; }
static BitrateMap bitrates_;
private:
int cq_level_;
size_t file_size_;
double psnr_;
int n_frames_;
};
CQTest::BitrateMap CQTest::bitrates_;
TEST_P(CQTest, LinearPSNRIsHigherForCQLevel) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = kCQTargetBitrate;
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_CQ;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
timebase.den, timebase.num, 0, 30);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double cq_psnr_lin = GetLinearPSNROverBitrate();
const unsigned int cq_actual_bitrate =
static_cast<unsigned int>(file_size()) * 8 * 30 / (n_frames() * 1000);
EXPECT_LE(cq_actual_bitrate, kCQTargetBitrate);
bitrates_[cq_level()] = cq_actual_bitrate;
// try targeting the approximate same bitrate with VBR mode
cfg_.rc_end_usage = VPX_VBR;
cfg_.rc_target_bitrate = cq_actual_bitrate;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const double vbr_psnr_lin = GetLinearPSNROverBitrate();
EXPECT_GE(cq_psnr_lin, vbr_psnr_lin);
}
VP8_INSTANTIATE_TEST_CASE(CQTest,
::testing::Range(kCQLevelMin, kCQLevelMax,
kCQLevelStep));
} // namespace
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/c7a.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_C7A_HEADER
#define C7A_C7A_HEADER
#include <c7a/api/dia.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/api/allgather.hpp>
#include <c7a/api/generate_from_file.hpp>
#include <c7a/api/generate.hpp>
#include <c7a/api/prefixsum.hpp>
#include <c7a/api/read.hpp>
#include <c7a/api/reduce.hpp>
#include <c7a/api/reduce_to_index.hpp>
#include <c7a/api/sum.hpp>
#include <c7a/api/write.hpp>
#include <c7a/api/zip.hpp>
#include <c7a/api/size.hpp>
namespace c7a {
// our public interface classes and methods. all others should be in a
// sub-namespace.
using api::DIARef;
using api::Context;
} // namespace c7a
#endif // !C7A_C7A_HEADER
/******************************************************************************/
<commit_msg>Disable compilation of zip.hpp for now. There is apparantly no test.<commit_after>/*******************************************************************************
* c7a/c7a.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <[email protected]>
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_C7A_HEADER
#define C7A_C7A_HEADER
#include <c7a/api/dia.hpp>
#include <c7a/api/bootstrap.hpp>
#include <c7a/api/allgather.hpp>
#include <c7a/api/generate_from_file.hpp>
#include <c7a/api/generate.hpp>
#include <c7a/api/prefixsum.hpp>
#include <c7a/api/read.hpp>
#include <c7a/api/reduce.hpp>
#include <c7a/api/reduce_to_index.hpp>
#include <c7a/api/sum.hpp>
#include <c7a/api/write.hpp>
//-tb: #include <c7a/api/zip.hpp>
#include <c7a/api/size.hpp>
namespace c7a {
// our public interface classes and methods. all others should be in a
// sub-namespace.
using api::DIARef;
using api::Context;
} // namespace c7a
#endif // !C7A_C7A_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
// Note that passing null for the first arg isn't strictly POSIX, but is
// supported everywhere we currently build.
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = !path.empty() && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
} else if (path.size() > 2 && path[0] == '\\' && path[1] == '\\') {
// Also allow for UNC-style paths beginning with double-backslash
is_absolute = true;
sep = path[0];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
#if LLVM_VERSION >= 60
internal_assert(!result) << "Failed to write archive: " << dst_file
<< ", reason: " << result << "\n";
#else
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
#endif
}
} // namespace Halide
<commit_msg>Workaround for Windows buildbots failures with trunk LLVM<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
// Note that passing null for the first arg isn't strictly POSIX, but is
// supported everywhere we currently build.
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = !path.empty() && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
} else if (path.size() > 2 && path[0] == '\\' && path[1] == '\\') {
// Also allow for UNC-style paths beginning with double-backslash
is_absolute = true;
sep = path[0];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
// This is a band-aid: MS COFF Lib format is almost-but-not-quite compatible with
// GNU ar format; amazingly, just generating the latter worked for quite a long
// time, but can intermittently fail. Shelling out to the 'lib' tool is a
// temporary fix to get the Halide buildbots unstuck; it would be much
// preferable to write the necessary code directly.
if (Internal::get_triple_for_target(target).isWindowsMSVCEnvironment()) {
std::string command = "lib /nologo /out:" + dst_file;
for (auto &src : src_files) {
command += " " + src;
}
int lib_result = system(command.c_str());
internal_assert(lib_result == 0) << "shelling out to lib failed: (" << command << ")\n";
return;
}
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
#if LLVM_VERSION >= 60
internal_assert(!result) << "Failed to write archive: " << dst_file
<< ", reason: " << result << "\n";
#else
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
#endif
}
} // namespace Halide
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPContingencyStatisticsMPI.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.
=========================================================================*/
/*
* Copyright 2011 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include "vtkContingencyStatistics.h"
#include "vtkPContingencyStatistics.h"
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkVariantArray.h"
struct RandomContingencyStatisticsArgs
{
int nVals;
double stdev;
double absTol;
int* retVal;
int ioRank;
};
// This will be called by all processes
void RandomContingencyStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomContingencyStatisticsArgs* args = reinterpret_cast<RandomContingencyStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) * ( myRank + 1 ) );
// Generate an input table that contains samples of mutually independent discrete random variables
int nVariables = 2;
vtkIntArray* intArray[2];
vtkStdString columnNames[] = { "Rounded Normal 0",
"Rounded Normal 1" };
vtkTable* inputData = vtkTable::New();
// Discrete rounded normal samples
for ( int c = 0; c < nVariables; ++ c )
{
intArray[c] = vtkIntArray::New();
intArray[c]->SetNumberOfComponents( 1 );
intArray[c]->SetName( columnNames[c] );
for ( int r = 0; r < args->nVals; ++ r )
{
intArray[c]->InsertNextValue( static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) ) );
}
inputData->AddColumn( intArray[c] );
intArray[c]->Delete();
}
// Entropies in the summary table should normally be retrieved as follows:
// column 2: H(X,Y)
// column 3: H(Y|X)
// column 4: H(X|Y)
int iEntropies[] = { 2,
3,
4 };
int nEntropies = 3; // correct number of entropies reported in the summary table
// ************************** Contingency Statistics **************************
// Synchronize and start clock
com->Barrier();
vtkTimerLog *timer=vtkTimerLog::New();
timer->StartTimer();
// Instantiate a parallel contingency statistics engine and set its ports
vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();
pcs->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, inputData );
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
// Select column pairs (uniform vs. uniform, normal vs. normal)
pcs->AddColumnPair( columnNames[0], columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pcs->SetLearnOption( true );
pcs->SetDeriveOption( true );
pcs->SetAssessOption( true );
pcs->Update();
// Synchronize and stop clock
com->Barrier();
timer->StopTimer();
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n"
<< " Wall time: "
<< timer->GetElapsedTime()
<< " sec.\n";
}
// Now perform verifications
vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );
vtkIdType nRowSumm = outputSummary->GetNumberOfRows();
double testDoubleValue1;
double testDoubleValue2;
int numProcs = controller->GetNumberOfProcesses();
// Verify that all processes have the same grand total and contingency tables size
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that all processes have the same grand total and contingency tables size.\n";
}
// Gather all grand totals
int GT_l = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
int* GT_g = new int[numProcs];
com->AllGather( >_l,
GT_g,
1 );
// Known global grand total
int testIntValue = args->nVals * numProcs;
// Print out all grand totals
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i
<< ", grand total = "
<< GT_g[i]
<< ", contingency table size = "
<< outputContingency->GetNumberOfRows()
<< "\n";
if ( GT_g[i] != testIntValue )
{
vtkGenericWarningMacro("Incorrect grand total:"
<< GT_g[i]
<< " <> "
<< testIntValue
<< ")");
*(args->retVal) = 1;
}
}
}
// Verify that information entropies on all processes make sense
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that information entropies are consistent on all processes.\n";
}
testIntValue = outputSummary->GetNumberOfColumns();
if ( testIntValue != nEntropies + 2 )
{
vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
<< testIntValue
<< " != "
<< nEntropies + 2
<< ".");
*(args->retVal) = 1;
}
else
{
// For each row in the summary table, fetch variable names and information entropies
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
// Get local information entropies from summary table
double* H_l = new double[nEntropies];
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
H_l[c] = outputSummary->GetValue( k, iEntropies[c] ).ToDouble();
}
// Gather all local entropies
double* H_g = new double[nEntropies * numProcs];
com->AllGather( H_l,
H_g,
nEntropies );
// Print out all entropies
if ( com->GetLocalProcessId() == args->ioRank )
{
// Get variable names
cout << " (X,Y) = ("
<< outputSummary->GetValue( k, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( k, 1 ).ToString()
<< "):\n";
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i;
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
cout << ", "
<< outputSummary->GetColumnName( iEntropies[c] )
<< " = "
<< H_g[nEntropies * i + c];
}
cout << "\n";
// Make sure that H(X,Y) >= H(Y|X)+ H(X|Y)
testDoubleValue1 = H_g[nEntropies * i + 1] + H_g[nEntropies * i + 2]; // H(Y|X)+ H(X|Y)
if ( testDoubleValue1 > H_g[nEntropies * i] )
{
vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
<< H_g[nEntropies * i]
<< " < "
<< testDoubleValue1
<< " = H(Y|X)+ H(X|Y).");
*(args->retVal) = 1;
}
}
cout << " where H(X,Y) = - Sum_{x,y} p(x,y) log p(x,y) and H(X|Y) = - Sum_{x,y} p(x,y) log p(x|y).\n";
}
// Clean up
delete [] H_l;
delete [] H_g;
}
}
// Verify that the local and global CDFs sum to 1 within presribed relative tolerance
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that local and global CDFs sum to 1 (within "
<< args->absTol
<< " relative tolerance).\n";
}
vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( outputContingency->GetColumnByName( "Key" ) );
if ( ! keys )
{
cout << "*** Error: "
<< "Empty contingency table column 'Key' on process "
<< com->GetLocalProcessId()
<< ".\n";
}
vtkStdString proName = "P";
vtkDoubleArray* prob = vtkDoubleArray::SafeDownCast( outputContingency->GetColumnByName( proName ) );
if ( ! prob )
{
cout << "*** Error: "
<< "Empty contingency table column '"
<< proName
<< "' on process "
<< com->GetLocalProcessId()
<< ".\n";
}
// Calculate local CDFs
double* cdf_l = new double[nRowSumm];
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
cdf_l[k] = 0;
}
int n = outputContingency->GetNumberOfRows();
// Skip first entry which is reserved for the cardinality
for ( vtkIdType r = 1; r < n; ++ r )
{
cdf_l[keys->GetValue( r )] += prob->GetValue( r );
}
// Gather all local CDFs
double* cdf_g = new double[nRowSumm * numProcs];
com->AllGather( cdf_l,
cdf_g,
nRowSumm );
// Print out all local and global CDFs
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
// Get variable names
cout << " (X,Y) = ("
<< outputSummary->GetValue( k, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( k, 1 ).ToString()
<< "):\n";
for ( int i = 0; i < numProcs; ++ i )
{
testDoubleValue1 = cdf_l[k];
testDoubleValue2 = cdf_g[i * nRowSumm + k];
cout << " On process "
<< i
<< ", local CDF = "
<< testDoubleValue1
<< ", global CDF = "
<< testDoubleValue2
<< "\n";
// Verify that local CDF = 1 (within absTol)
if ( fabs ( 1. - testDoubleValue1 ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect local CDF.");
*(args->retVal) = 1;
}
// Verify that global CDF = 1 (within absTol)
if ( fabs ( 1. - testDoubleValue2 ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect global CDF.");
*(args->retVal) = 1;
}
}
}
}
// Clean up
delete [] GT_g;
delete [] cdf_l;
delete [] cdf_g;
pcs->Delete();
inputData->Delete();
timer->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Process "
<< ioRank
<< " will be the I/O node.\n";
}
// Parameters for regression test.
int testValue = 0;
RandomContingencyStatisticsArgs args;
args.nVals = 1000000;
args.stdev = 5.;
args.absTol = 1.e-6;
args.retVal = &testValue;
args.ioRank = ioRank;
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes and standard deviation = "
<< args.stdev
<< ".\n";
}
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomContingencyStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<commit_msg>Added command line parser so parallel contingency can be tested parametrically<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestRandomPContingencyStatisticsMPI.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.
=========================================================================*/
/*
* Copyright 2011 Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the
* U.S. Government. Redistribution and use in source and binary forms, with
* or without modification, are permitted provided that this Notice and any
* statement of authorship are reproduced on all copies.
*/
// .SECTION Thanks
// Thanks to Philippe Pebay for implementing this test.
#include <mpi.h>
#include "vtkContingencyStatistics.h"
#include "vtkPContingencyStatistics.h"
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkMPIController.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkStdString.h"
#include "vtkTable.h"
#include "vtkTimerLog.h"
#include "vtkVariantArray.h"
#include "vtksys/CommandLineArguments.hxx"
struct RandomContingencyStatisticsArgs
{
int nVals;
double stdev;
double absTol;
int* retVal;
int ioRank;
};
// This will be called by all processes
void RandomContingencyStatistics( vtkMultiProcessController* controller, void* arg )
{
// Get test parameters
RandomContingencyStatisticsArgs* args = reinterpret_cast<RandomContingencyStatisticsArgs*>( arg );
*(args->retVal) = 0;
// Get MPI communicator
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// Get local rank
int myRank = com->GetLocalProcessId();
// Seed random number generator
vtkMath::RandomSeed( static_cast<int>( vtkTimerLog::GetUniversalTime() ) * ( myRank + 1 ) );
// Generate an input table that contains samples of mutually independent discrete random variables
int nVariables = 2;
vtkIntArray* intArray[2];
vtkStdString columnNames[] = { "Rounded Normal 0",
"Rounded Normal 1" };
vtkTable* inputData = vtkTable::New();
// Discrete rounded normal samples
for ( int c = 0; c < nVariables; ++ c )
{
intArray[c] = vtkIntArray::New();
intArray[c]->SetNumberOfComponents( 1 );
intArray[c]->SetName( columnNames[c] );
for ( int r = 0; r < args->nVals; ++ r )
{
intArray[c]->InsertNextValue( static_cast<int>( vtkMath::Round( vtkMath::Gaussian() * args->stdev ) ) );
}
inputData->AddColumn( intArray[c] );
intArray[c]->Delete();
}
// Entropies in the summary table should normally be retrieved as follows:
// column 2: H(X,Y)
// column 3: H(Y|X)
// column 4: H(X|Y)
int iEntropies[] = { 2,
3,
4 };
int nEntropies = 3; // correct number of entropies reported in the summary table
// ************************** Contingency Statistics **************************
// Synchronize and start clock
com->Barrier();
vtkTimerLog *timer=vtkTimerLog::New();
timer->StartTimer();
// Instantiate a parallel contingency statistics engine and set its ports
vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();
pcs->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, inputData );
vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
// Select column pairs (uniform vs. uniform, normal vs. normal)
pcs->AddColumnPair( columnNames[0], columnNames[1] );
// Test (in parallel) with Learn, Derive, and Assess options turned on
pcs->SetLearnOption( true );
pcs->SetDeriveOption( true );
pcs->SetAssessOption( true );
pcs->Update();
// Synchronize and stop clock
com->Barrier();
timer->StopTimer();
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Completed parallel calculation of contingency statistics (with assessment):\n"
<< " Wall time: "
<< timer->GetElapsedTime()
<< " sec.\n";
}
// Now perform verifications
vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );
vtkIdType nRowSumm = outputSummary->GetNumberOfRows();
double testDoubleValue1;
double testDoubleValue2;
int numProcs = controller->GetNumberOfProcesses();
// Verify that all processes have the same grand total and contingency tables size
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that all processes have the same grand total and contingency tables size.\n";
}
// Gather all grand totals
int GT_l = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
int* GT_g = new int[numProcs];
com->AllGather( >_l,
GT_g,
1 );
// Known global grand total
int testIntValue = args->nVals * numProcs;
// Print out all grand totals
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i
<< ", grand total = "
<< GT_g[i]
<< ", contingency table size = "
<< outputContingency->GetNumberOfRows()
<< "\n";
if ( GT_g[i] != testIntValue )
{
vtkGenericWarningMacro("Incorrect grand total:"
<< GT_g[i]
<< " <> "
<< testIntValue
<< ")");
*(args->retVal) = 1;
}
}
}
// Verify that information entropies on all processes make sense
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that information entropies are consistent on all processes.\n";
}
testIntValue = outputSummary->GetNumberOfColumns();
if ( testIntValue != nEntropies + 2 )
{
vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
<< testIntValue
<< " != "
<< nEntropies + 2
<< ".");
*(args->retVal) = 1;
}
else
{
// For each row in the summary table, fetch variable names and information entropies
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
// Get local information entropies from summary table
double* H_l = new double[nEntropies];
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
H_l[c] = outputSummary->GetValue( k, iEntropies[c] ).ToDouble();
}
// Gather all local entropies
double* H_g = new double[nEntropies * numProcs];
com->AllGather( H_l,
H_g,
nEntropies );
// Print out all entropies
if ( com->GetLocalProcessId() == args->ioRank )
{
// Get variable names
cout << " (X,Y) = ("
<< outputSummary->GetValue( k, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( k, 1 ).ToString()
<< "):\n";
for ( int i = 0; i < numProcs; ++ i )
{
cout << " On process "
<< i;
for ( vtkIdType c = 0; c < nEntropies; ++ c )
{
cout << ", "
<< outputSummary->GetColumnName( iEntropies[c] )
<< " = "
<< H_g[nEntropies * i + c];
}
cout << "\n";
// Make sure that H(X,Y) >= H(Y|X)+ H(X|Y)
testDoubleValue1 = H_g[nEntropies * i + 1] + H_g[nEntropies * i + 2]; // H(Y|X)+ H(X|Y)
if ( testDoubleValue1 > H_g[nEntropies * i] )
{
vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
<< H_g[nEntropies * i]
<< " < "
<< testDoubleValue1
<< " = H(Y|X)+ H(X|Y).");
*(args->retVal) = 1;
}
}
cout << " where H(X,Y) = - Sum_{x,y} p(x,y) log p(x,y) and H(X|Y) = - Sum_{x,y} p(x,y) log p(x|y).\n";
}
// Clean up
delete [] H_l;
delete [] H_g;
}
}
// Verify that the local and global CDFs sum to 1 within presribed relative tolerance
if ( com->GetLocalProcessId() == args->ioRank )
{
cout << "\n## Verifying that local and global CDFs sum to 1 (within "
<< args->absTol
<< " relative tolerance).\n";
}
vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( outputContingency->GetColumnByName( "Key" ) );
if ( ! keys )
{
cout << "*** Error: "
<< "Empty contingency table column 'Key' on process "
<< com->GetLocalProcessId()
<< ".\n";
}
vtkStdString proName = "P";
vtkDoubleArray* prob = vtkDoubleArray::SafeDownCast( outputContingency->GetColumnByName( proName ) );
if ( ! prob )
{
cout << "*** Error: "
<< "Empty contingency table column '"
<< proName
<< "' on process "
<< com->GetLocalProcessId()
<< ".\n";
}
// Calculate local CDFs
double* cdf_l = new double[nRowSumm];
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
cdf_l[k] = 0;
}
int n = outputContingency->GetNumberOfRows();
// Skip first entry which is reserved for the cardinality
for ( vtkIdType r = 1; r < n; ++ r )
{
cdf_l[keys->GetValue( r )] += prob->GetValue( r );
}
// Gather all local CDFs
double* cdf_g = new double[nRowSumm * numProcs];
com->AllGather( cdf_l,
cdf_g,
nRowSumm );
// Print out all local and global CDFs
if ( com->GetLocalProcessId() == args->ioRank )
{
for ( vtkIdType k = 0; k < nRowSumm; ++ k )
{
// Get variable names
cout << " (X,Y) = ("
<< outputSummary->GetValue( k, 0 ).ToString()
<< ", "
<< outputSummary->GetValue( k, 1 ).ToString()
<< "):\n";
for ( int i = 0; i < numProcs; ++ i )
{
testDoubleValue1 = cdf_l[k];
testDoubleValue2 = cdf_g[i * nRowSumm + k];
cout << " On process "
<< i
<< ", local CDF = "
<< testDoubleValue1
<< ", global CDF = "
<< testDoubleValue2
<< "\n";
// Verify that local CDF = 1 (within absTol)
if ( fabs ( 1. - testDoubleValue1 ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect local CDF.");
*(args->retVal) = 1;
}
// Verify that global CDF = 1 (within absTol)
if ( fabs ( 1. - testDoubleValue2 ) > args->absTol )
{
vtkGenericWarningMacro("Incorrect global CDF.");
*(args->retVal) = 1;
}
}
}
}
// Clean up
delete [] GT_g;
delete [] cdf_l;
delete [] cdf_g;
pcs->Delete();
inputData->Delete();
timer->Delete();
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
// **************************** MPI Initialization ***************************
vtkMPIController* controller = vtkMPIController::New();
controller->Initialize( &argc, &argv );
// If an MPI controller was not created, terminate in error.
if ( ! controller->IsA( "vtkMPIController" ) )
{
vtkGenericWarningMacro("Failed to initialize a MPI controller.");
controller->Delete();
return 1;
}
vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );
// ************************** Find an I/O node ********************************
int* ioPtr;
int ioRank;
int flag;
MPI_Attr_get( MPI_COMM_WORLD,
MPI_IO,
&ioPtr,
&flag );
if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )
{
// Getting MPI attributes did not return any I/O node found.
ioRank = MPI_PROC_NULL;
vtkGenericWarningMacro("No MPI I/O nodes found.");
// As no I/O node was found, we need an unambiguous way to report the problem.
// This is the only case when a testValue of -1 will be returned
controller->Finalize();
controller->Delete();
return -1;
}
else
{
if ( *ioPtr == MPI_ANY_SOURCE )
{
// Anyone can do the I/O trick--just pick node 0.
ioRank = 0;
}
else
{
// Only some nodes can do I/O. Make sure everyone agrees on the choice (min).
com->AllReduce( ioPtr,
&ioRank,
1,
vtkCommunicator::MIN_OP );
}
}
// **************************** Parse command line ***************************
// Set default argument values
int nVals = 1000000;
double stdev = 5.;
double absTol = 1.e-6;
// Initialize command line argument parser
vtksys::CommandLineArguments clArgs;
clArgs.Initialize( argc, argv );
clArgs.StoreUnusedArguments( false );
// Parse per-process cardinality of each pseudo-random sample
clArgs.AddArgument("--n-per-proc",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&nVals, "Per-process cardinality of each pseudo-random sample");
// Parse standard deviation of each pseudo-random sample
clArgs.AddArgument("--std-dev",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&stdev, "Standard deviation of each pseudo-random sample");
// Parse absolute tolerance to verify that final CDF is 1
clArgs.AddArgument("--abs-tol",
vtksys::CommandLineArguments::SPACE_ARGUMENT,
&stdev, "Absolute tolerance to verify that final CDF is 1");
// If incorrect arguments were provided, terminate in error.
if ( ! clArgs.Parse() )
{
vtkGenericWarningMacro("Incorrect input data arguments were provided.");
return 1;
}
// ************************** Initialize test *********************************
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Process "
<< ioRank
<< " will be the I/O node.\n";
}
// Parameters for regression test.
int testValue = 0;
RandomContingencyStatisticsArgs args;
args.nVals = nVals;
args.stdev = stdev;
args.absTol = absTol;
args.retVal = &testValue;
args.ioRank = ioRank;
// Check how many processes have been made available
int numProcs = controller->GetNumberOfProcesses();
if ( controller->GetLocalProcessId() == ioRank )
{
cout << "\n# Running test with "
<< numProcs
<< " processes and standard deviation = "
<< args.stdev
<< ".\n";
}
// Execute the function named "process" on both processes
controller->SetSingleMethod( RandomContingencyStatistics, &args );
controller->SingleMethodExecute();
// Clean up and exit
if ( com->GetLocalProcessId() == ioRank )
{
cout << "\n# Test completed.\n\n";
}
controller->Finalize();
controller->Delete();
return testValue;
}
<|endoftext|> |
<commit_before>/*
* File: multi_unbounded_queue.hpp
* Author: Barath Kannan
* Vector of unbounded queues. Enqueue operations are assigned a subqueue,
* which is used for all enqueue operations occuring from that thread. The dequeue
* operation maintains a list of subqueues on which a "hit" has occured - pertaining
* to the subqueues from which a successful dequeue operation has occured. On a
* successful dequeue operation, the queue that is used is pushed to the front of the
* list. The "hit lists" allow the queue to adapt fairly well to different usage contexts.
* Created on 25 September 2016, 12:04 AM
*/
#ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP
#define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP
#include <thread>
#include <vector>
#include <mutex>
#include <bk_conq/unbounded_queue.hpp>
namespace bk_conq {
template<typename TT>
class multi_unbounded_queue;
template <template <typename> class Q, typename T>
class multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{
friend unbounded_queue<T, multi_unbounded_queue<Q<T>>>;
public:
multi_unbounded_queue(size_t subqueues) :
_q(subqueues),
_hitlist([&]() {return hitlist_sequence(); }),
_enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); })
{
static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue");
}
multi_unbounded_queue(const multi_unbounded_queue&) = delete;
void operator=(const multi_unbounded_queue&) = delete;
protected:
template <typename R>
void sp_enqueue_impl(R&& input) {
size_t indx = _enqueue_identifier.get_tlcl();
_q[indx].sp_enqueue(std::forward<R>(input));
}
template <typename R>
void mp_enqueue_impl(R&& input) {
size_t indx = _enqueue_identifier.get_tlcl();
_q[indx].mp_enqueue(std::forward<R>(input));
}
bool sc_dequeue_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].sc_dequeue(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
bool mc_dequeue_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue_uncontended(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
bool mc_dequeue_uncontended_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue_uncontended(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
private:
template <typename U>
class tlcl {
public:
tlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) :
_defaultvalfunc(defaultvalfunc),
_defaultdeletefunc(defaultdeletefunc)
{
std::lock_guard<std::mutex> lock(_m);
if (!_available.empty()) {
_mycounter = _available.back();
_available.pop_back();
}
else {
_mycounter = _counter++;
}
}
virtual ~tlcl() {
std::lock_guard<std::mutex> lock(_m);
_available.push_back(_mycounter);
}
U& get_tlcl() {
thread_local std::vector<std::pair<tlcl<U>*, U>> vec;
if (vec.size() <= _mycounter) vec.resize(_mycounter+1);
auto& ret = vec[_mycounter];
if (ret.first != this) { //reset to default
if (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second);
if (_defaultvalfunc) ret.second = _defaultvalfunc();
ret.first = this;
}
return ret.second;
}
private:
std::function<U()> _defaultvalfunc;
std::function<void(U)> _defaultdeletefunc;
size_t _mycounter;
static size_t _counter;
static std::vector<size_t> _available;
static std::mutex _m;
};
std::vector<size_t> hitlist_sequence() {
std::vector<size_t> hitlist(_q.size());
std::iota(hitlist.begin(), hitlist.end(), 0);
return hitlist;
}
size_t get_enqueue_index() {
std::lock_guard<std::mutex> lock(_m);
if (_unused_enqueue_indexes.empty()) {
return (_enqueue_index++)%_q.size();
}
size_t ret = _unused_enqueue_indexes.back();
_unused_enqueue_indexes.pop_back();
return ret;
}
void return_enqueue_index(size_t index) {
std::lock_guard<std::mutex> lock(_m);
_unused_enqueue_indexes.push_back(index);
}
class padded_unbounded_queue : public Q<T>{
char padding[64];
};
std::vector<padded_unbounded_queue> _q;
std::vector<size_t> _unused_enqueue_indexes;
size_t _enqueue_index{ 0 };
std::mutex _m;
tlcl<std::vector<size_t>> _hitlist;
tlcl<size_t> _enqueue_identifier;
};
template <template <typename> class Q, typename T> template <typename U>
size_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0;
template <template <typename> class Q, typename T> template <typename U>
std::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available;
template <template <typename> class Q, typename T> template <typename U>
std::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m;
}//namespace bk_conq
#endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */
<commit_msg>include numeric for iota<commit_after>/*
* File: multi_unbounded_queue.hpp
* Author: Barath Kannan
* Vector of unbounded queues. Enqueue operations are assigned a subqueue,
* which is used for all enqueue operations occuring from that thread. The dequeue
* operation maintains a list of subqueues on which a "hit" has occured - pertaining
* to the subqueues from which a successful dequeue operation has occured. On a
* successful dequeue operation, the queue that is used is pushed to the front of the
* list. The "hit lists" allow the queue to adapt fairly well to different usage contexts.
* Created on 25 September 2016, 12:04 AM
*/
#ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP
#define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP
#include <thread>
#include <vector>
#include <mutex>
#include <numeric>
#include <bk_conq/unbounded_queue.hpp>
namespace bk_conq {
template<typename TT>
class multi_unbounded_queue;
template <template <typename> class Q, typename T>
class multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{
friend unbounded_queue<T, multi_unbounded_queue<Q<T>>>;
public:
multi_unbounded_queue(size_t subqueues) :
_q(subqueues),
_hitlist([&]() {return hitlist_sequence(); }),
_enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); })
{
static_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, "Q<T> must be an unbounded queue");
}
multi_unbounded_queue(const multi_unbounded_queue&) = delete;
void operator=(const multi_unbounded_queue&) = delete;
protected:
template <typename R>
void sp_enqueue_impl(R&& input) {
size_t indx = _enqueue_identifier.get_tlcl();
_q[indx].sp_enqueue(std::forward<R>(input));
}
template <typename R>
void mp_enqueue_impl(R&& input) {
size_t indx = _enqueue_identifier.get_tlcl();
_q[indx].mp_enqueue(std::forward<R>(input));
}
bool sc_dequeue_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].sc_dequeue(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
bool mc_dequeue_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue_uncontended(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
bool mc_dequeue_uncontended_impl(T& output) {
auto& hitlist = _hitlist.get_tlcl();
for (auto it = hitlist.begin(); it != hitlist.end(); ++it) {
if (_q[*it].mc_dequeue_uncontended(output)) {
for (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);
return true;
}
}
return false;
}
private:
template <typename U>
class tlcl {
public:
tlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) :
_defaultvalfunc(defaultvalfunc),
_defaultdeletefunc(defaultdeletefunc)
{
std::lock_guard<std::mutex> lock(_m);
if (!_available.empty()) {
_mycounter = _available.back();
_available.pop_back();
}
else {
_mycounter = _counter++;
}
}
virtual ~tlcl() {
std::lock_guard<std::mutex> lock(_m);
_available.push_back(_mycounter);
}
U& get_tlcl() {
thread_local std::vector<std::pair<tlcl<U>*, U>> vec;
if (vec.size() <= _mycounter) vec.resize(_mycounter+1);
auto& ret = vec[_mycounter];
if (ret.first != this) { //reset to default
if (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second);
if (_defaultvalfunc) ret.second = _defaultvalfunc();
ret.first = this;
}
return ret.second;
}
private:
std::function<U()> _defaultvalfunc;
std::function<void(U)> _defaultdeletefunc;
size_t _mycounter;
static size_t _counter;
static std::vector<size_t> _available;
static std::mutex _m;
};
std::vector<size_t> hitlist_sequence() {
std::vector<size_t> hitlist(_q.size());
std::iota(hitlist.begin(), hitlist.end(), 0);
return hitlist;
}
size_t get_enqueue_index() {
std::lock_guard<std::mutex> lock(_m);
if (_unused_enqueue_indexes.empty()) {
return (_enqueue_index++)%_q.size();
}
size_t ret = _unused_enqueue_indexes.back();
_unused_enqueue_indexes.pop_back();
return ret;
}
void return_enqueue_index(size_t index) {
std::lock_guard<std::mutex> lock(_m);
_unused_enqueue_indexes.push_back(index);
}
class padded_unbounded_queue : public Q<T>{
char padding[64];
};
std::vector<padded_unbounded_queue> _q;
std::vector<size_t> _unused_enqueue_indexes;
size_t _enqueue_index{ 0 };
std::mutex _m;
tlcl<std::vector<size_t>> _hitlist;
tlcl<size_t> _enqueue_identifier;
};
template <template <typename> class Q, typename T> template <typename U>
size_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0;
template <template <typename> class Q, typename T> template <typename U>
std::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available;
template <template <typename> class Q, typename T> template <typename U>
std::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m;
}//namespace bk_conq
#endif /* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP */
<|endoftext|> |
<commit_before>#include "GeneralPoissonInputSpikingNeurons.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <algorithm> // For random shuffle
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "../Helpers/FstreamWrapper.hpp"
using namespace std;
GeneralPoissonInputSpikingNeurons::GeneralPoissonInputSpikingNeurons() {
stimuli_rates = nullptr;
total_number_of_rates = 0;
}
GeneralPoissonInputSpikingNeurons::~GeneralPoissonInputSpikingNeurons() {
free(stimuli_rates);
}
void GeneralPoissonInputSpikingNeurons::state_update
(float current_time_in_seconds, float timestep) {
backend()->state_update(current_time_in_seconds, timestep);
}
void GeneralPoissonInputSpikingNeurons::reset_stimuli(){
free(stimuli_rates);
stimuli_rates = nullptr;
}
void GeneralPoissonInputSpikingNeurons::add_stimulus(float* rates, int num_rates){
// Check if the size of the rates is correct
if (num_rates != total_number_of_neurons){
printf("Error: The number of neurons does not match the number of rates!\n");
exit(1);
}
// If correct, allocate some memory save these values
stimuli_rates = (float*)realloc(stimuli_rates, sizeof(float)*(total_number_of_rates + num_rates));
for (int index = 0; index < num_rates; index++){
stimuli_rates[total_number_of_rates + index] = rates[index];
}
// After storing the stimulus, correct the number of input stimuli
total_number_of_rates += num_rates;
++total_number_of_input_stimuli;
}
void GeneralPoissonInputSpikingNeurons::copy_rates_to_device() {
backend()->copy_rates_to_device();
}
SPIKE_MAKE_INIT_BACKEND(GeneralPoissonInputSpikingNeurons);
<commit_msg>Allowing General Poisson neuron reset to set number of stimuli to zero.<commit_after>#include "GeneralPoissonInputSpikingNeurons.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <algorithm> // For random shuffle
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "../Helpers/FstreamWrapper.hpp"
using namespace std;
GeneralPoissonInputSpikingNeurons::GeneralPoissonInputSpikingNeurons() {
stimuli_rates = nullptr;
total_number_of_rates = 0;
}
GeneralPoissonInputSpikingNeurons::~GeneralPoissonInputSpikingNeurons() {
free(stimuli_rates);
}
void GeneralPoissonInputSpikingNeurons::state_update
(float current_time_in_seconds, float timestep) {
backend()->state_update(current_time_in_seconds, timestep);
}
void GeneralPoissonInputSpikingNeurons::reset_stimuli(){
total_number_of_rates = 0;
total_number_of_input_stimuli = 0;
free(stimuli_rates);
stimuli_rates = nullptr;
}
void GeneralPoissonInputSpikingNeurons::add_stimulus(float* rates, int num_rates){
// Check if the size of the rates is correct
if (num_rates != total_number_of_neurons){
printf("Error: The number of neurons does not match the number of rates!\n");
exit(1);
}
// If correct, allocate some memory save these values
stimuli_rates = (float*)realloc(stimuli_rates, sizeof(float)*(total_number_of_rates + num_rates));
for (int index = 0; index < num_rates; index++){
stimuli_rates[total_number_of_rates + index] = rates[index];
}
// After storing the stimulus, correct the number of input stimuli
total_number_of_rates += num_rates;
++total_number_of_input_stimuli;
}
void GeneralPoissonInputSpikingNeurons::copy_rates_to_device() {
backend()->copy_rates_to_device();
}
SPIKE_MAKE_INIT_BACKEND(GeneralPoissonInputSpikingNeurons);
<|endoftext|> |
<commit_before>// https://github.com/philsquared/Catch/wiki/Supplying-your-own-main()
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
// test utils
#include "test_utils.hpp"
#include "vector_tile_projection.hpp"
const unsigned x=0,y=0,z=0;
const unsigned tile_size = 256;
mapnik::box2d<double> bbox;
// vector output api
#include "vector_tile_processor.hpp"
#include "vector_tile_backend_pbf.hpp"
TEST_CASE( "vector tile projection 1", "should support z/x/y to bbox conversion at 0/0/0" ) {
mapnik::vector::spherical_mercator merc(256);
int x = 0;
int y = 0;
int z = 0;
double minx,miny,maxx,maxy;
merc.xyz(x,y,z,minx,miny,maxx,maxy);
mapnik::box2d<double> map_extent(minx,miny,maxx,maxy);
mapnik::box2d<double> e(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);
double epsilon = 0.000001;
CHECK(std::fabs(map_extent.minx() - e.minx()) < epsilon);
CHECK(std::fabs(map_extent.miny() - e.miny()) < epsilon);
CHECK(std::fabs(map_extent.maxx() - e.maxx()) < epsilon);
CHECK(std::fabs(map_extent.maxy() - e.maxy()) < epsilon);
}
TEST_CASE( "vector tile projection 2", "should support z/x/y to bbox conversion up to z33" ) {
mapnik::vector::spherical_mercator merc(256);
int x = 2145960701;
int y = 1428172928;
int z = 32;
double minx,miny,maxx,maxy;
merc.xyz(x,y,z,minx,miny,maxx,maxy);
mapnik::box2d<double> map_extent(minx,miny,maxx,maxy);
mapnik::box2d<double> e(-14210.1492817168364127,6711666.7204630710184574,-14210.1399510249066225,6711666.7297937674447894);
double epsilon = 0.00000001;
CHECK(std::fabs(map_extent.minx() - e.minx()) < epsilon);
CHECK(std::fabs(map_extent.miny() - e.miny()) < epsilon);
CHECK(std::fabs(map_extent.maxx() - e.maxx()) < epsilon);
CHECK(std::fabs(map_extent.maxy() - e.maxy()) < epsilon);
}
TEST_CASE( "vector tile output", "should create vector tile with one point" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
mapnik::request m_req(tile_size,tile_size,bbox);
renderer_type ren(backend,map,m_req);
ren.apply();
CHECK(1 == tile.layers_size());
mapnik::vector::tile_layer const& layer = tile.layers(0);
CHECK(std::string("layer") == layer.name());
CHECK(1 == layer.features_size());
mapnik::vector::tile_feature const& f = layer.features(0);
CHECK(static_cast<mapnik::value_integer>(1) == static_cast<mapnik::value_integer>(f.id()));
CHECK(3 == f.geometry_size());
CHECK(9 == f.geometry(0));
CHECK(4096 == f.geometry(1));
CHECK(4096 == f.geometry(2));
CHECK(52 == tile.ByteSize());
std::string buffer;
CHECK(tile.SerializeToString(&buffer));
CHECK(52 == buffer.size());
}
// vector input api
#include "vector_tile_datasource.hpp"
#include "vector_tile_backend_pbf.hpp"
TEST_CASE( "vector tile input", "should be able to parse message and render point" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
map.zoom_to_box(bbox);
mapnik::request m_req(map.width(),map.height(),map.get_current_extent());
renderer_type ren(backend,map,m_req);
ren.apply();
// serialize to message
std::string buffer;
CHECK(tile.SerializeToString(&buffer));
CHECK(52 == buffer.size());
// now create new objects
mapnik::Map map2(tile_size,tile_size);
tile_type tile2;
CHECK(tile2.ParseFromString(buffer));
CHECK(1 == tile2.layers_size());
mapnik::vector::tile_layer const& layer2 = tile2.layers(0);
CHECK(std::string("layer") == layer2.name());
mapnik::layer lyr2("layer");
boost::shared_ptr<mapnik::vector::tile_datasource> ds = boost::make_shared<
mapnik::vector::tile_datasource>(
layer2,x,y,z,map2.width());
ds->set_envelope(bbox);
mapnik::layer_descriptor lay_desc = ds->get_descriptor();
std::vector<std::string> expected_names;
expected_names.push_back("name");
std::vector<std::string> names;
BOOST_FOREACH(mapnik::attribute_descriptor const& desc, lay_desc.get_descriptors())
{
names.push_back(desc.get_name());
}
CHECK(names == expected_names);
lyr2.set_datasource(ds);
lyr2.add_style("style");
map2.addLayer(lyr2);
mapnik::feature_type_style s;
mapnik::rule r;
mapnik::color red(255,0,0);
mapnik::markers_symbolizer sym;
sym.set_fill(red);
r.append(sym);
s.add_rule(r);
map2.insert_style("style",s);
map2.zoom_to_box(bbox);
mapnik::image_32 im(map2.width(),map2.height());
mapnik::agg_renderer<mapnik::image_32> ren2(map2,im);
ren2.apply();
unsigned rgba = im.data()(128,128);
CHECK(red.rgba() == rgba);
//mapnik::save_to_file(im,"test.png");
}
TEST_CASE( "vector tile datasource", "should filter features outside extent" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
mapnik::request m_req(tile_size,tile_size,bbox);
renderer_type ren(backend,map,m_req);
ren.apply();
CHECK(1 == tile.layers_size());
mapnik::vector::tile_layer const& layer = tile.layers(0);
CHECK(std::string("layer") == layer.name());
CHECK(1 == layer.features_size());
mapnik::vector::tile_feature const& f = layer.features(0);
CHECK(static_cast<mapnik::value_integer>(1) == static_cast<mapnik::value_integer>(f.id()));
CHECK(3 == f.geometry_size());
CHECK(9 == f.geometry(0));
CHECK(4096 == f.geometry(1));
CHECK(4096 == f.geometry(2));
// now actually start the meat of the test
mapnik::vector::tile_datasource ds(layer,x,y,z,tile_size);
mapnik::featureset_ptr fs;
// ensure we can query single feature
fs = ds.features(mapnik::query(bbox));
mapnik::feature_ptr feat = fs->next();
CHECK(feat != mapnik::feature_ptr());
CHECK(feat->size() == 0);
CHECK(fs->next() == mapnik::feature_ptr());
mapnik::query qq = mapnik::query(mapnik::box2d<double>(-1,-1,1,1));
qq.add_property_name("name");
fs = ds.features(qq);
feat = fs->next();
CHECK(feat != mapnik::feature_ptr());
CHECK(feat->size() == 1);
// CHECK(feat->get("name") == "null island");
// now check that datasource api throws out feature which is outside extent
fs = ds.features(mapnik::query(mapnik::box2d<double>(-10,-10,-10,-10)));
CHECK(fs->next() == mapnik::feature_ptr());
// ensure same behavior for feature_at_point
fs = ds.features_at_point(mapnik::coord2d(0.0,0.0),0.0001);
CHECK(fs->next() != mapnik::feature_ptr());
fs = ds.features_at_point(mapnik::coord2d(1.0,1.0),1.0001);
CHECK(fs->next() != mapnik::feature_ptr());
fs = ds.features_at_point(mapnik::coord2d(-10,-10),0);
CHECK(fs->next() == mapnik::feature_ptr());
// finally, make sure attributes are also filtered
mapnik::feature_ptr f_ptr;
fs = ds.features(mapnik::query(bbox));
f_ptr = fs->next();
CHECK(f_ptr != mapnik::feature_ptr());
// no attributes
CHECK(f_ptr->context()->size() == 0);
mapnik::query q(bbox);
q.add_property_name("name");
fs = ds.features(q);
f_ptr = fs->next();
CHECK(f_ptr != mapnik::feature_ptr());
// one attribute
CHECK(f_ptr->context()->size() == 1);
}
int main (int argc, char* const argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
// set up bbox
double minx,miny,maxx,maxy;
mapnik::vector::spherical_mercator merc(256);
merc.xyz(x,y,z,minx,miny,maxx,maxy);
bbox.init(minx,miny,maxx,maxy);
int result = Catch::Session().run( argc, argv );
if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n");
google::protobuf::ShutdownProtobufLibrary();
return result;
}
<commit_msg>add test to ensure internal move_to commands are preserved even if high tolerance - refs #36<commit_after>// https://github.com/philsquared/Catch/wiki/Supplying-your-own-main()
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
// test utils
#include "test_utils.hpp"
#include "vector_tile_projection.hpp"
const unsigned x=0,y=0,z=0;
const unsigned tile_size = 256;
mapnik::box2d<double> bbox;
// vector output api
#include "vector_tile_processor.hpp"
#include "vector_tile_backend_pbf.hpp"
TEST_CASE( "vector tile projection 1", "should support z/x/y to bbox conversion at 0/0/0" ) {
mapnik::vector::spherical_mercator merc(256);
int x = 0;
int y = 0;
int z = 0;
double minx,miny,maxx,maxy;
merc.xyz(x,y,z,minx,miny,maxx,maxy);
mapnik::box2d<double> map_extent(minx,miny,maxx,maxy);
mapnik::box2d<double> e(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);
double epsilon = 0.000001;
CHECK(std::fabs(map_extent.minx() - e.minx()) < epsilon);
CHECK(std::fabs(map_extent.miny() - e.miny()) < epsilon);
CHECK(std::fabs(map_extent.maxx() - e.maxx()) < epsilon);
CHECK(std::fabs(map_extent.maxy() - e.maxy()) < epsilon);
}
TEST_CASE( "vector tile projection 2", "should support z/x/y to bbox conversion up to z33" ) {
mapnik::vector::spherical_mercator merc(256);
int x = 2145960701;
int y = 1428172928;
int z = 32;
double minx,miny,maxx,maxy;
merc.xyz(x,y,z,minx,miny,maxx,maxy);
mapnik::box2d<double> map_extent(minx,miny,maxx,maxy);
mapnik::box2d<double> e(-14210.1492817168364127,6711666.7204630710184574,-14210.1399510249066225,6711666.7297937674447894);
double epsilon = 0.00000001;
CHECK(std::fabs(map_extent.minx() - e.minx()) < epsilon);
CHECK(std::fabs(map_extent.miny() - e.miny()) < epsilon);
CHECK(std::fabs(map_extent.maxx() - e.maxx()) < epsilon);
CHECK(std::fabs(map_extent.maxy() - e.maxy()) < epsilon);
}
TEST_CASE( "vector tile output", "should create vector tile with one point" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
mapnik::request m_req(tile_size,tile_size,bbox);
renderer_type ren(backend,map,m_req);
ren.apply();
CHECK(1 == tile.layers_size());
mapnik::vector::tile_layer const& layer = tile.layers(0);
CHECK(std::string("layer") == layer.name());
CHECK(1 == layer.features_size());
mapnik::vector::tile_feature const& f = layer.features(0);
CHECK(static_cast<mapnik::value_integer>(1) == static_cast<mapnik::value_integer>(f.id()));
CHECK(3 == f.geometry_size());
CHECK(9 == f.geometry(0));
CHECK(4096 == f.geometry(1));
CHECK(4096 == f.geometry(2));
CHECK(52 == tile.ByteSize());
std::string buffer;
CHECK(tile.SerializeToString(&buffer));
CHECK(52 == buffer.size());
}
// vector input api
#include "vector_tile_datasource.hpp"
#include "vector_tile_backend_pbf.hpp"
TEST_CASE( "vector tile input", "should be able to parse message and render point" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
map.zoom_to_box(bbox);
mapnik::request m_req(map.width(),map.height(),map.get_current_extent());
renderer_type ren(backend,map,m_req);
ren.apply();
// serialize to message
std::string buffer;
CHECK(tile.SerializeToString(&buffer));
CHECK(52 == buffer.size());
// now create new objects
mapnik::Map map2(tile_size,tile_size);
tile_type tile2;
CHECK(tile2.ParseFromString(buffer));
CHECK(1 == tile2.layers_size());
mapnik::vector::tile_layer const& layer2 = tile2.layers(0);
CHECK(std::string("layer") == layer2.name());
mapnik::layer lyr2("layer");
boost::shared_ptr<mapnik::vector::tile_datasource> ds = boost::make_shared<
mapnik::vector::tile_datasource>(
layer2,x,y,z,map2.width());
ds->set_envelope(bbox);
mapnik::layer_descriptor lay_desc = ds->get_descriptor();
std::vector<std::string> expected_names;
expected_names.push_back("name");
std::vector<std::string> names;
BOOST_FOREACH(mapnik::attribute_descriptor const& desc, lay_desc.get_descriptors())
{
names.push_back(desc.get_name());
}
CHECK(names == expected_names);
lyr2.set_datasource(ds);
lyr2.add_style("style");
map2.addLayer(lyr2);
mapnik::feature_type_style s;
mapnik::rule r;
mapnik::color red(255,0,0);
mapnik::markers_symbolizer sym;
sym.set_fill(red);
r.append(sym);
s.add_rule(r);
map2.insert_style("style",s);
map2.zoom_to_box(bbox);
mapnik::image_32 im(map2.width(),map2.height());
mapnik::agg_renderer<mapnik::image_32> ren2(map2,im);
ren2.apply();
unsigned rgba = im.data()(128,128);
CHECK(red.rgba() == rgba);
//mapnik::save_to_file(im,"test.png");
}
TEST_CASE( "vector tile datasource", "should filter features outside extent" ) {
typedef mapnik::vector::backend_pbf backend_type;
typedef mapnik::vector::processor<backend_type> renderer_type;
typedef mapnik::vector::tile tile_type;
tile_type tile;
backend_type backend(tile,16);
mapnik::Map map(tile_size,tile_size);
mapnik::layer lyr("layer");
lyr.set_datasource(build_ds());
map.addLayer(lyr);
mapnik::request m_req(tile_size,tile_size,bbox);
renderer_type ren(backend,map,m_req);
ren.apply();
CHECK(1 == tile.layers_size());
mapnik::vector::tile_layer const& layer = tile.layers(0);
CHECK(std::string("layer") == layer.name());
CHECK(1 == layer.features_size());
mapnik::vector::tile_feature const& f = layer.features(0);
CHECK(static_cast<mapnik::value_integer>(1) == static_cast<mapnik::value_integer>(f.id()));
CHECK(3 == f.geometry_size());
CHECK(9 == f.geometry(0));
CHECK(4096 == f.geometry(1));
CHECK(4096 == f.geometry(2));
// now actually start the meat of the test
mapnik::vector::tile_datasource ds(layer,x,y,z,tile_size);
mapnik::featureset_ptr fs;
// ensure we can query single feature
fs = ds.features(mapnik::query(bbox));
mapnik::feature_ptr feat = fs->next();
CHECK(feat != mapnik::feature_ptr());
CHECK(feat->size() == 0);
CHECK(fs->next() == mapnik::feature_ptr());
mapnik::query qq = mapnik::query(mapnik::box2d<double>(-1,-1,1,1));
qq.add_property_name("name");
fs = ds.features(qq);
feat = fs->next();
CHECK(feat != mapnik::feature_ptr());
CHECK(feat->size() == 1);
// CHECK(feat->get("name") == "null island");
// now check that datasource api throws out feature which is outside extent
fs = ds.features(mapnik::query(mapnik::box2d<double>(-10,-10,-10,-10)));
CHECK(fs->next() == mapnik::feature_ptr());
// ensure same behavior for feature_at_point
fs = ds.features_at_point(mapnik::coord2d(0.0,0.0),0.0001);
CHECK(fs->next() != mapnik::feature_ptr());
fs = ds.features_at_point(mapnik::coord2d(1.0,1.0),1.0001);
CHECK(fs->next() != mapnik::feature_ptr());
fs = ds.features_at_point(mapnik::coord2d(-10,-10),0);
CHECK(fs->next() == mapnik::feature_ptr());
// finally, make sure attributes are also filtered
mapnik::feature_ptr f_ptr;
fs = ds.features(mapnik::query(bbox));
f_ptr = fs->next();
CHECK(f_ptr != mapnik::feature_ptr());
// no attributes
CHECK(f_ptr->context()->size() == 0);
mapnik::query q(bbox);
q.add_property_name("name");
fs = ds.features(q);
f_ptr = fs->next();
CHECK(f_ptr != mapnik::feature_ptr());
// one attribute
CHECK(f_ptr->context()->size() == 1);
}
// NOTE: encoding a multiple lines as one path is technically incorrect
// because in Mapnik the protocol is to split geometry parts into separate paths
// however this case should still be supported in error and its an optimization in the
// case where you know that lines do not need to be labeled in custom ways.
TEST_CASE( "encoding multi line as one path", "should maintain second move_to command" ) {
// Options
// here we use a multiplier of 1 to avoid rounding numbers
// and stay in integer space for simplity
unsigned path_multiplier = 1;
// here we use an extreme tolerance to prove tht all vertices are maintained no matter
// the tolerance because we never want to drop a move_to or the first line_to
unsigned tolerance = 2000000;
// now create the testing data
mapnik::vector::tile tile;
mapnik::vector::backend_pbf backend(tile,path_multiplier);
backend.start_tile_layer("layer");
mapnik::feature_ptr feature(mapnik::feature_factory::create(boost::make_shared<mapnik::context_type>(),1));
backend.start_tile_feature(*feature);
mapnik::geometry_type * line = new mapnik::geometry_type(mapnik::LineString);
line->move_to(0,0); // takes 3 geoms: command length,x,y
line->line_to(2,2); // new command, so again takes 3 geoms: command length,x,y | total 6
line->move_to(1,1); // takes 3 geoms: command length,x,y
line->line_to(2,2); // new command, so again takes 3 geoms: command length,x,y | total 6
backend.add_path(*line, tolerance, line->type());
backend.stop_tile_feature();
backend.stop_tile_layer();
// done encoding single feature/geometry
CHECK(1 == tile.layers_size());
mapnik::vector::tile_layer const& layer = tile.layers(0);
CHECK(1 == layer.features_size());
mapnik::vector::tile_feature const& f = layer.features(0);
CHECK(12 == f.geometry_size());
CHECK(9 == f.geometry(0)); // 1 move_to
CHECK(0 == f.geometry(1)); // x:0
CHECK(0 == f.geometry(2)); // y:0
CHECK(10 == f.geometry(3)); // 1 line_to
CHECK(4 == f.geometry(4)); // x:2
CHECK(4 == f.geometry(5)); // y:2
CHECK(9 == f.geometry(6)); // 1 move_to
CHECK(1 == f.geometry(7)); // x:1
CHECK(1 == f.geometry(8)); // y:1
CHECK(10 == f.geometry(9)); // 1 line_to
CHECK(2 == f.geometry(10)); // x:2
CHECK(2 == f.geometry(11)); // y:2
}
int main (int argc, char* const argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
// set up bbox
double minx,miny,maxx,maxy;
mapnik::vector::spherical_mercator merc(256);
merc.xyz(x,y,z,minx,miny,maxx,maxy);
bbox.init(minx,miny,maxx,maxy);
int result = Catch::Session().run( argc, argv );
if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n");
google::protobuf::ShutdownProtobufLibrary();
return result;
}
<|endoftext|> |
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file EC_Hydrax.cpp
* @brief A photorealistic water plane component using Hydrax, http://www.ogre3d.org/tikiwiki/Hydrax
*/
#define OGRE_INTEROP
#include "DebugOperatorNew.h"
#include "EC_Hydrax.h"
#include "Scene.h"
#include "Framework.h"
#include "FrameAPI.h"
#include "AssetAPI.h"
#include "IAssetTransfer.h"
#include "IAsset.h"
#include "OgreWorld.h"
#include "Renderer.h"
#include "EC_Camera.h"
#include "Entity.h"
#include "OgreConversionUtils.h"
#include "Profiler.h"
#include "AttributeMetadata.h"
#ifdef SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#include <Hydrax.h>
#include <Noise/Perlin/Perlin.h>
#include <Noise/FFT/FFT.h>
#include <Modules/ProjectedGrid/ProjectedGrid.h>
#include <Modules/RadialGrid/RadialGrid.h>
#include <Modules/SimpleGrid/SimpleGrid.h>
#include "LoggingFunctions.h"
#include "MemoryLeakCheck.h"
struct EC_HydraxImpl
{
EC_HydraxImpl() : hydrax(0), module(0) {}
~EC_HydraxImpl()
{
if (hydrax)
hydrax->remove();
SAFE_DELETE(hydrax);
//SAFE_DELETE(module); ///< @todo Possible mem leak?
}
Hydrax::Hydrax *hydrax;
Hydrax::Module::Module *module;
#ifdef SKYX_ENABLED
boost::weak_ptr<EC_SkyX> skyX;
#endif
};
EC_Hydrax::EC_Hydrax(Scene* scene) :
IComponent(scene),
configRef(this, "Config ref", AssetReference("HydraxDefault.hdx")),
visible(this, "Visible", true),
position(this, "Position"),
// noiseModule(this, "Noise module", 0),
// noiseType(this, "Noise type", 0),
// normalMode(this, "Normal mode", 0),
impl(0)
{
/*
static AttributeMetadata noiseTypeMetadata;
static AttributeMetadata normalModeMetadata;
static bool metadataInitialized = false;
if (!metadataInitialized)
{
noiseTypeMetadata.enums[Perlin] = "Perlin";
noiseTypeMetadata.enums[FFT] = "FFT";
normalModeMetadata.enums[Texture] = "Texture";
normalModeMetadata.enums[Vertex] = "Vertex";
normalModeMetadata.enums[RTT] = "RTT";
metadataInitialized = true;
}
noiseType.SetMetadata(&noiseTypeMetadata);
normalMode.SetMetadata(&normalModeMetadata);
*/
OgreWorldPtr w = scene->GetWorld<OgreWorld>();
if (!w)
{
LogError("EC_Hydrax: no OgreWorld available. Cannot be created.");
return;
}
connect(w->GetRenderer(), SIGNAL(MainCameraChanged(Entity *)), SLOT(OnActiveCameraChanged(Entity *)));
connect(this, SIGNAL(ParentEntitySet()), SLOT(Create()));
}
EC_Hydrax::~EC_Hydrax()
{
SAFE_DELETE(impl);
}
void EC_Hydrax::Create()
{
SAFE_DELETE(impl);
try
{
if (!ParentScene())
{
LogError("EC_Hydrax: no parent scene. Cannot be created.");
return;
}
OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();
assert(w);
Entity *mainCamera = w->GetRenderer()->MainCamera();
if (!mainCamera)
{
LogError("Cannot create EC_Hydrax: No main camera set!");
return; // Can't create Hydrax just yet, no main camera set.
}
Ogre::Camera *cam = mainCamera->GetComponent<EC_Camera>()->GetCamera();
impl = new EC_HydraxImpl();
impl->hydrax = new Hydrax::Hydrax(w->GetSceneManager(), cam, w->GetRenderer()->MainViewport());
// Using projected grid module by default
Hydrax::Module::ProjectedGrid *module = new Hydrax::Module::ProjectedGrid(impl->hydrax, new Hydrax::Noise::Perlin(),
Ogre::Plane(Ogre::Vector3::UNIT_Y, Ogre::Vector3::ZERO), Hydrax::MaterialManager::NM_VERTEX);
impl->hydrax->setModule(module);
impl->module = module;
// Load all parameters from config file
impl->hydrax->loadCfg(configRef.Get().ref.toStdString());
// position.Set(impl->hydrax->getPosition(), AttributeChange::Disconnected);
impl->hydrax->create();
connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection);
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection);
}
catch(Ogre::Exception &e)
{
// Currently if we try to create more than one Hydrax component we end up here due to Ogre internal name collision.
LogError("Could not create EC_Hydrax: " + std::string(e.what()));
}
}
void EC_Hydrax::OnActiveCameraChanged(Entity *newActiveCamera)
{
if (!newActiveCamera)
{
SAFE_DELETE(impl);
return;
}
// If we haven't yet initialized, do a full init.
if (!impl)
Create();
else // Otherwise, update the camera to an existing initialized Hydrax instance.
if (impl && impl->hydrax)
impl->hydrax->setCamera(newActiveCamera->GetComponent<EC_Camera>()->GetCamera());
}
void EC_Hydrax::UpdateAttribute(IAttribute *attr)
{
if (attr == &configRef)
{
if (!configRef.Get().ref.isEmpty())
{
AssetTransferPtr transfer = framework->Asset()->RequestAsset(configRef.Get().ref, "Binary");
if (transfer.get())
connect(transfer.get(), SIGNAL(Succeeded(AssetPtr)), SLOT(ConfigLoadSucceeded(AssetPtr)), Qt::UniqueConnection);
}
else
LoadDefaultConfig();
}
if (!impl->hydrax)
return;
if (attr == &configRef)
{
impl->hydrax->loadCfg(configRef.Get().ref.toStdString());
// The position attribute is always authoritative for the position value.
impl->hydrax->setPosition(position.Get());
}
else if (attr == &visible)
impl->hydrax->setVisible(visible.Get());
else if (attr == &position)
impl->hydrax->setPosition(position.Get());
/*
else if (attr == &noiseModule || attr == &normalMode || &noiseType)
UpdateNoiseModule();
*/
}
/*
void EC_Hydrax::UpdateNoiseModule()
{
Hydrax::Noise::Noise *noise = 0;
switch(noiseType.Get())
{
case Perlin:
noise = new Hydrax::Noise::Perlin();
break;
case FFT:
noise = new Hydrax::Noise::FFT();
break;
default:
LogError("Invalid Hydrax noise module type.");
return;
}
Hydrax::Module::Module *module = 0;
switch(noiseModule.Get())
{
case ProjectedGrid:
module = new Hydrax::Module::ProjectedGrid(impl->hydrax, noise, Ogre::Plane(Ogre::Vector3::UNIT_Y, Ogre::Vector3::ZERO),
(Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
case RadialGrid:
module = new Hydrax::Module::RadialGrid(impl->hydrax, noise, (Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
case SimpleGrid:
module = new Hydrax::Module::SimpleGrid(impl->hydrax, noise, (Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
default:
SAFE_DELETE(noise);
LogError("Invalid Hydrax noise module type.");
return;
}
//if (impl->module && noise)
// impl->module->setNoise(noise);
impl->hydrax->setModule(module);
impl->module = module;
//impl->hydrax->loadCfg("HydraxDemo.hdx");
impl->hydrax->create();
}
*/
void EC_Hydrax::Update(float frameTime)
{
if (impl->hydrax)
{
PROFILE(EC_Hydrax_Update);
#ifdef SKYX_ENABLED
// Find out if we have SkyX in the scene. If yes, use its sun position.
if (impl->skyX.expired())
{
EntityList entities = ParentEntity()->ParentScene()->GetEntitiesWithComponent(EC_SkyX::TypeNameStatic());
if (!entities.empty())
impl->skyX = (*entities.begin())->GetComponent<EC_SkyX>();
}
if (!impl->skyX.expired())
impl->hydrax->setSunPosition(impl->skyX.lock()->SunPosition());
#endif
impl->hydrax->update(frameTime);
}
}
void EC_Hydrax::ConfigLoadSucceeded(AssetPtr asset)
{
if (!impl || !impl->hydrax || !impl->module)
{
LogError("EC_Hydrax: Could not apply loaded config, hydrax not initialized.");
return;
}
std::vector<u8> rawData;
asset->SerializeTo(rawData);
QString configData = QString::fromAscii((const char*)&rawData[0], rawData.size());
if (configData.isEmpty())
{
LogInfo("EC_Hydrax: Downloaded config is empty!");
return;
}
try
{
// Update the noise module
if (configData.contains("noise=fft", Qt::CaseInsensitive))
{
/// \note Using the FFT noise plugin seems to crash somewhere after we leave this function.
/// FFT looks better so would be nice to investigate further!
if (impl->module->getNoise()->getName() != "FFT")
impl->module->setNoise(new Hydrax::Noise::FFT());
}
else if (configData.contains("noise=perlin", Qt::CaseInsensitive))
{
if (impl->module->getNoise()->getName() != "Perlin")
impl->module->setNoise(new Hydrax::Noise::Perlin());
}
else
{
LogError("EC_Hydrax: Unknown noise param in loaded config, acceptable = FFT/Perlin.");
return;
}
// Load config from the asset data string.
impl->hydrax->loadCfgString(configData.toStdString());
}
catch (Ogre::Exception &e)
{
LogError(std::string("EC_Hydrax: Ogre threw exception while loading new config: ") + e.what());
}
}
void EC_Hydrax::LoadDefaultConfig()
{
if (!impl || !impl->hydrax || !impl->module)
{
LogError("EC_Hydrax: Could not apply default config, hydrax not initialized.");
return;
}
if (impl->module->getNoise()->getName() != "Perlin")
impl->module->setNoise(new Hydrax::Noise::Perlin());
// Load all parameters from the default config file we ship in /media/hydrax
/// \todo Inspect if we can change the current ShaderMode to HLSL or GLSL on the fly here, depending on the platform!
impl->hydrax->loadCfg("HydraxDefault.hdx");
}
<commit_msg>Hydrax: More null checks. Remove a unneeded default config load from UpdateAttribute(). Changed config loading to remove() -> loadcfg() -> create() -> setPosition() for 'improved' stability. Still crashes after about 3-4 times of changing the config (doesnt seem to matter if its string or resource config load).<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file EC_Hydrax.cpp
* @brief A photorealistic water plane component using Hydrax, http://www.ogre3d.org/tikiwiki/Hydrax
*/
#define OGRE_INTEROP
#include "DebugOperatorNew.h"
#include "EC_Hydrax.h"
#include "Scene.h"
#include "Framework.h"
#include "FrameAPI.h"
#include "AssetAPI.h"
#include "IAssetTransfer.h"
#include "IAsset.h"
#include "OgreWorld.h"
#include "Renderer.h"
#include "EC_Camera.h"
#include "Entity.h"
#include "OgreConversionUtils.h"
#include "Profiler.h"
#include "AttributeMetadata.h"
#ifdef SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#include <Hydrax.h>
#include <Noise/Perlin/Perlin.h>
#include <Noise/FFT/FFT.h>
#include <Modules/ProjectedGrid/ProjectedGrid.h>
#include <Modules/RadialGrid/RadialGrid.h>
#include <Modules/SimpleGrid/SimpleGrid.h>
#include "LoggingFunctions.h"
#include "MemoryLeakCheck.h"
struct EC_HydraxImpl
{
EC_HydraxImpl() : hydrax(0), module(0) {}
~EC_HydraxImpl()
{
if (hydrax)
hydrax->remove();
SAFE_DELETE(hydrax);
//SAFE_DELETE(module); ///< @todo Possible mem leak?
}
Hydrax::Hydrax *hydrax;
Hydrax::Module::Module *module;
#ifdef SKYX_ENABLED
boost::weak_ptr<EC_SkyX> skyX;
#endif
};
EC_Hydrax::EC_Hydrax(Scene* scene) :
IComponent(scene),
configRef(this, "Config ref", AssetReference("HydraxDefault.hdx")),
visible(this, "Visible", true),
position(this, "Position", float3(0.0, 0.0, 0.0)),
// noiseModule(this, "Noise module", 0),
// noiseType(this, "Noise type", 0),
// normalMode(this, "Normal mode", 0),
impl(0)
{
/*
static AttributeMetadata noiseTypeMetadata;
static AttributeMetadata normalModeMetadata;
static bool metadataInitialized = false;
if (!metadataInitialized)
{
noiseTypeMetadata.enums[Perlin] = "Perlin";
noiseTypeMetadata.enums[FFT] = "FFT";
normalModeMetadata.enums[Texture] = "Texture";
normalModeMetadata.enums[Vertex] = "Vertex";
normalModeMetadata.enums[RTT] = "RTT";
metadataInitialized = true;
}
noiseType.SetMetadata(&noiseTypeMetadata);
normalMode.SetMetadata(&normalModeMetadata);
*/
OgreWorldPtr w = scene->GetWorld<OgreWorld>();
if (!w)
{
LogError("EC_Hydrax: no OgreWorld available. Cannot be created.");
return;
}
connect(w->GetRenderer(), SIGNAL(MainCameraChanged(Entity *)), SLOT(OnActiveCameraChanged(Entity *)));
connect(this, SIGNAL(ParentEntitySet()), SLOT(Create()));
}
EC_Hydrax::~EC_Hydrax()
{
SAFE_DELETE(impl);
}
void EC_Hydrax::Create()
{
SAFE_DELETE(impl);
if (framework->IsHeadless())
return;
try
{
if (!ParentScene())
{
LogError("EC_Hydrax: no parent scene. Cannot be created.");
return;
}
OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>();
assert(w);
Entity *mainCamera = w->GetRenderer()->MainCamera();
if (!mainCamera)
{
LogError("Cannot create EC_Hydrax: No main camera set!");
return; // Can't create Hydrax just yet, no main camera set.
}
Ogre::Camera *cam = mainCamera->GetComponent<EC_Camera>()->GetCamera();
impl = new EC_HydraxImpl();
impl->hydrax = new Hydrax::Hydrax(w->GetSceneManager(), cam, w->GetRenderer()->MainViewport());
// Using projected grid module by default
Hydrax::Module::ProjectedGrid *module = new Hydrax::Module::ProjectedGrid(impl->hydrax, new Hydrax::Noise::Perlin(),
Ogre::Plane(Ogre::Vector3::UNIT_Y, Ogre::Vector3::ZERO), Hydrax::MaterialManager::NM_VERTEX);
impl->hydrax->setModule(module);
impl->module = module;
// Load all parameters from config file
impl->hydrax->loadCfg(configRef.Get().ref.toStdString());
impl->hydrax->create();
impl->hydrax->setPosition(position.Get());
connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection);
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection);
}
catch(Ogre::Exception &e)
{
// Currently if we try to create more than one Hydrax component we end up here due to Ogre internal name collision.
LogError("Could not create EC_Hydrax: " + std::string(e.what()));
}
}
void EC_Hydrax::OnActiveCameraChanged(Entity *newActiveCamera)
{
if (!newActiveCamera)
{
SAFE_DELETE(impl);
return;
}
// If we haven't yet initialized, do a full init.
if (!impl)
Create();
else // Otherwise, update the camera to an existing initialized Hydrax instance.
if (impl && impl->hydrax)
impl->hydrax->setCamera(newActiveCamera->GetComponent<EC_Camera>()->GetCamera());
}
void EC_Hydrax::UpdateAttribute(IAttribute *attr)
{
if (attr == &configRef)
{
if (!configRef.Get().ref.isEmpty())
{
AssetTransferPtr transfer = framework->Asset()->RequestAsset(configRef.Get().ref, "Binary");
if (transfer.get())
connect(transfer.get(), SIGNAL(Succeeded(AssetPtr)), SLOT(ConfigLoadSucceeded(AssetPtr)), Qt::UniqueConnection);
}
else
LoadDefaultConfig();
}
if (impl && !impl->hydrax)
return;
else if (attr == &visible)
impl->hydrax->setVisible(visible.Get());
else if (attr == &position)
impl->hydrax->setPosition(position.Get());
/*
else if (attr == &noiseModule || attr == &normalMode || &noiseType)
UpdateNoiseModule();
*/
}
/*
void EC_Hydrax::UpdateNoiseModule()
{
Hydrax::Noise::Noise *noise = 0;
switch(noiseType.Get())
{
case Perlin:
noise = new Hydrax::Noise::Perlin();
break;
case FFT:
noise = new Hydrax::Noise::FFT();
break;
default:
LogError("Invalid Hydrax noise module type.");
return;
}
Hydrax::Module::Module *module = 0;
switch(noiseModule.Get())
{
case ProjectedGrid:
module = new Hydrax::Module::ProjectedGrid(impl->hydrax, noise, Ogre::Plane(Ogre::Vector3::UNIT_Y, Ogre::Vector3::ZERO),
(Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
case RadialGrid:
module = new Hydrax::Module::RadialGrid(impl->hydrax, noise, (Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
case SimpleGrid:
module = new Hydrax::Module::SimpleGrid(impl->hydrax, noise, (Hydrax::MaterialManager::NormalMode)normalMode.Get());
break;
default:
SAFE_DELETE(noise);
LogError("Invalid Hydrax noise module type.");
return;
}
//if (impl->module && noise)
// impl->module->setNoise(noise);
impl->hydrax->setModule(module);
impl->module = module;
//impl->hydrax->loadCfg("HydraxDemo.hdx");
impl->hydrax->create();
}
*/
void EC_Hydrax::Update(float frameTime)
{
if (impl && impl->hydrax)
{
PROFILE(EC_Hydrax_Update);
#ifdef SKYX_ENABLED
// Find out if we have SkyX in the scene. If yes, use its sun position.
if (impl->skyX.expired())
{
EntityList entities = ParentEntity()->ParentScene()->GetEntitiesWithComponent(EC_SkyX::TypeNameStatic());
if (!entities.empty())
impl->skyX = (*entities.begin())->GetComponent<EC_SkyX>();
}
if (!impl->skyX.expired() && impl->hydrax->isCreated())
impl->hydrax->setSunPosition(impl->skyX.lock()->SunPosition());
#endif
if (impl->hydrax->isCreated())
impl->hydrax->update(frameTime);
}
}
void EC_Hydrax::ConfigLoadSucceeded(AssetPtr asset)
{
if (!impl || !impl->hydrax || !impl->module)
{
LogError("EC_Hydrax: Could not apply loaded config, hydrax not initialized.");
return;
}
std::vector<u8> rawData;
asset->SerializeTo(rawData);
QString configData = QString::fromAscii((const char*)&rawData[0], rawData.size());
if (configData.isEmpty())
{
LogInfo("EC_Hydrax: Downloaded config is empty!");
return;
}
try
{
// Update the noise module
if (configData.contains("noise=fft", Qt::CaseInsensitive))
{
/// \note Using the FFT noise plugin seems to crash somewhere after we leave this function.
/// FFT looks better so would be nice to investigate further!
if (impl->module->getNoise()->getName() != "FFT")
impl->module->setNoise(new Hydrax::Noise::FFT());
}
else if (configData.contains("noise=perlin", Qt::CaseInsensitive))
{
if (impl->module->getNoise()->getName() != "Perlin")
impl->module->setNoise(new Hydrax::Noise::Perlin());
}
else
{
LogError("EC_Hydrax: Unknown noise param in loaded config, acceptable = FFT/Perlin.");
return;
}
// Load config from the asset data string.
impl->hydrax->remove();
impl->hydrax->loadCfgString(configData.toStdString());
impl->hydrax->create();
impl->hydrax->setPosition(position.Get());
}
catch (Ogre::Exception &e)
{
LogError(std::string("EC_Hydrax: Ogre threw exception while loading new config: ") + e.what());
}
}
void EC_Hydrax::LoadDefaultConfig()
{
if (!impl || !impl->hydrax || !impl->module)
{
LogError("EC_Hydrax: Could not apply default config, hydrax not initialized.");
return;
}
LogInfo(impl->module->getNoise()->getName());
if (impl->module->getNoise()->getName() != "Perlin")
impl->module->setNoise(new Hydrax::Noise::Perlin());
// Load all parameters from the default config file we ship in /media/hydrax
/// \todo Inspect if we can change the current ShaderMode to HLSL or GLSL on the fly here, depending on the platform!
try
{
impl->hydrax->remove();
impl->hydrax->loadCfg("HydraxDefault.hdx");
impl->hydrax->create();
impl->hydrax->setPosition(position.Get());
}
catch(Ogre::Exception &e)
{
LogError("EC_Hydrax failed to load default config: " + std::string(e.what()));
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <tuple>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include "locale"
#include "gmpfse.h"
#include "Benchmark.h"
using namespace forwardsec;
using namespace std;
bytes testVector = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
std::vector<string>makeTags(unsigned int n){
std::vector<string> tags(n);
for(unsigned int i=0;i<n;i++){
tags[i] = "tag"+std::to_string(i);
}
return tags;
}
Benchmark benchKeygen(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark b;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
b.start();
test.keygen();
b.stop();
b.computeTimeInMilliseconds();
}
return b;
}
Benchmark benchEnc(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
Benchmark benchE;
for(unsigned int i=0;i < iterations;i++){
benchE.start();
test.encrypt(test.pk,testVector,1,makeTags(n));
benchE.stop();
benchE.computeTimeInMilliseconds();
}
return benchE;
}
Benchmark benchDec(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
Benchmark benchD;
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
for(unsigned int i=0;i < iterations;i++){
benchD.start();
test.decrypt(ct);
benchD.stop();
benchD.computeTimeInMilliseconds();
}
return benchD;
}
Benchmark benchPuncFirst(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
benchP.start();
test.puncture("punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchPunc(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
test.puncture("punc");
benchP.start();
test.puncture("punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchNextInterval(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchN;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
benchN.start();
test.prepareNextInterval();
benchN.stop();
benchN.computeTimeInMilliseconds();
}
return benchN;
}
std::vector<std::tuple<unsigned int ,Benchmark>> benchDecPunctured(const unsigned int iterations,
const unsigned int punctures, const unsigned int puncture_steps,
const unsigned int d =32,
const unsigned int n = 1){
std::vector<std::tuple<unsigned int ,Benchmark>> b;
for(unsigned int p = 0; p < punctures;p+=puncture_steps){
cout << ".";
cout.flush();
Benchmark benchDP;
Pfse test(d,n);
test.keygen();
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
for(unsigned int i =0;i<p;i++){
test.puncture("punc"+std::to_string(i));
}
for(unsigned int i=0;i < iterations;i++){
benchDP.start();
test.decrypt(ct);
benchDP.stop();
benchDP.computeTimeInMilliseconds();
}
b.push_back(std::make_tuple (p,benchDP));
}
cout <<endl;
return b;
}
template <class T>
void sizes(const unsigned int d =32,const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
{
stringstream ss;
{
T oarchive(ss);
oarchive(test.pk);
}
cout << "\tPK size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(test.privatekeys);
}
cout << "\tSK size:\t" << ss.tellp() <<" bytes " << endl;
}
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
{
stringstream ss;
{
T oarchive(ss);
oarchive(ct);
}
cout << "\tCT size:\t" << ss.tellp() <<" bytes " << endl;
}
}
int main()
{
relicResourceHandle h;
unsigned int i = 10;
unsigned int d = 32;
unsigned int n = 1;
Benchmark K,E,D,PF,PS,N,DP;
cout << "Benchmarking " << i << " iterations of Puncturable forward secure encryption with depth " <<
d << " and " << n << " tags" << endl;
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
cout <<"Sizes(BinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::BinaryOutputArchive>();
cout <<"Sizes(PortableBinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::PortableBinaryOutputArchive>();
cout <<"Sizes(JSONOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::JSONOutputArchive>();
cout <<"Performance:" << endl;
K = benchKeygen(i,d,n);
cout << "\tkeygen:\t\t\t" << K << endl;
E = benchEnc(i,d,n);
cout << "\tEnc:\t\t\t" << E << endl;
D = benchDec(i,d,n);
cout << "\tDec(unpunctured):\t" << D << endl;
PF = benchPuncFirst(i,d,n);
cout << "\tInitial Puncture:\t" << PF << endl;
PS = benchPunc(i,d,n);
cout << "\tSubsequent Puncture:\t" << PS << endl;
N = benchNextInterval(i,d,n);
cout << "\tNextInterval:\t\t" << N << endl;
cout << "\tDec(punctured):" << endl;
auto marks = benchDecPunctured(i,100,20,d,n);
for(auto m:marks){
cout <<"\t\t" << std::get<0>(m) <<"\t" << std::get<1>(m) << endl;
}
}
<commit_msg>more benchmarks<commit_after>#include <iostream>
#include <vector>
#include <tuple>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/archives/json.hpp>
#include "locale"
#include "gmpfse.h"
#include "Benchmark.h"
using namespace forwardsec;
using namespace std;
bytes testVector = {{0x3a, 0x5d, 0x7a, 0x42, 0x44, 0xd3, 0xd8, 0xaf, 0xf5, 0xf3, 0xf1, 0x87, 0x81, 0x82, 0xb2,
0x53, 0x57, 0x30, 0x59, 0x75, 0x8d, 0xe6, 0x18, 0x17, 0x14, 0xdf, 0xa5, 0xa4, 0x0b,0x43,0xAD,0xBC}};
std::vector<string>makeTags(unsigned int n){
std::vector<string> tags(n);
for(unsigned int i=0;i<n;i++){
tags[i] = "tag"+std::to_string(i);
}
return tags;
}
Benchmark benchKeygen(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark b;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
b.start();
test.keygen();
b.stop();
b.computeTimeInMilliseconds();
}
return b;
}
Benchmark benchEnc(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
Benchmark benchE;
for(unsigned int i=0;i < iterations;i++){
benchE.start();
test.encrypt(test.pk,testVector,1,makeTags(n));
benchE.stop();
benchE.computeTimeInMilliseconds();
}
return benchE;
}
Benchmark benchDec(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
Benchmark benchD;
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
for(unsigned int i=0;i < iterations;i++){
benchD.start();
test.decrypt(ct);
benchD.stop();
benchD.computeTimeInMilliseconds();
}
return benchD;
}
Benchmark benchPuncFirst(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
benchP.start();
test.puncture("punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchPunc(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchP;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
test.puncture("punc");
benchP.start();
test.puncture("punc"+std::to_string(i));
benchP.stop();
benchP.computeTimeInMilliseconds();
}
return benchP;
}
Benchmark benchNextInterval(const unsigned int iterations, const unsigned int d =32,
const unsigned int n = 1){
Benchmark benchN;
for(unsigned int i=0;i < iterations;i++){
Pfse test(d,n);
test.keygen();
benchN.start();
test.prepareNextInterval();
benchN.stop();
benchN.computeTimeInMilliseconds();
}
return benchN;
}
std::vector<std::tuple<unsigned int ,Benchmark>> benchDecPunctured(const unsigned int iterations,
const unsigned int punctures, const unsigned int puncture_steps,
const unsigned int d =32,
const unsigned int n = 1){
std::vector<std::tuple<unsigned int ,Benchmark>> b;
for(unsigned int p = 0; p < punctures;p+=puncture_steps){
cout << ".";
cout.flush();
Benchmark benchDP;
Pfse test(d,n);
test.keygen();
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
for(unsigned int i =0;i<p;i++){
test.puncture("punc"+std::to_string(i));
}
for(unsigned int i=0;i < iterations;i++){
benchDP.start();
test.decrypt(ct);
benchDP.stop();
benchDP.computeTimeInMilliseconds();
}
b.push_back(std::make_tuple (p,benchDP));
}
cout <<endl;
return b;
}
template <class T>
void sizes(const unsigned int d =32,const unsigned int n = 1){
Pfse test(d,n);
test.keygen();
PairingGroup group;
{
ZR z = group.randomZR();
stringstream ss;
{
T oarchive(ss);
oarchive(z);
}
cout << "\tZR size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G1 g = group.randomG1();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG1 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
G2 g = group.randomG2();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tG2 size:\t" << ss.tellp() <<" bytes " << endl;
}
{
GT g = group.randomGT();
stringstream ss;
{
T oarchive(ss);
oarchive(g);
}
cout << "\tGT size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(test.pk);
}
cout << "\tPK size:\t" << ss.tellp() <<" bytes " << endl;
}
{
stringstream ss;
{
T oarchive(ss);
oarchive(test.privatekeys);
}
cout << "\tSK size:\t" << ss.tellp() <<" bytes " << endl;
}
PseCipherText ct = test.encrypt(test.pk,testVector,1,makeTags(n));;
{
stringstream ss;
{
T oarchive(ss);
oarchive(ct);
}
cout << "\tCT size:\t" << ss.tellp() <<" bytes " << endl;
}
}
int main()
{
relicResourceHandle h;
unsigned int i = 10;
unsigned int d = 32;
unsigned int n = 1;
Benchmark K,E,D,PF,PS,N,DP;
cout << "Benchmarking " << i << " iterations of Puncturable forward secure encryption with depth " <<
d << " and " << n << " tags" << endl;
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
cout <<"Sizes(BinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::BinaryOutputArchive>();
cout <<"Sizes(PortableBinaryOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::PortableBinaryOutputArchive>();
cout <<"Sizes(JSONOutputArchive) POINT_COMPRESSION=" << POINT_COMPRESS << ":"<< endl;
sizes<cereal::JSONOutputArchive>();
cout <<"Performance:" << endl;
K = benchKeygen(i,d,n);
cout << "\tkeygen:\t\t\t" << K << endl;
E = benchEnc(i,d,n);
cout << "\tEnc:\t\t\t" << E << endl;
D = benchDec(i,d,n);
cout << "\tDec(unpunctured):\t" << D << endl;
PF = benchPuncFirst(i,d,n);
cout << "\tInitial Puncture:\t" << PF << endl;
PS = benchPunc(i,d,n);
cout << "\tSubsequent Puncture:\t" << PS << endl;
N = benchNextInterval(i,d,n);
cout << "\tNextInterval:\t\t" << N << endl;
cout << "\tDec(punctured):" << endl;
auto marks = benchDecPunctured(i,100,20,d,n);
for(auto m:marks){
cout <<"\t\t" << std::get<0>(m) <<"\t" << std::get<1>(m) << endl;
}
}
<|endoftext|> |
<commit_before><commit_msg>Update a_very_big_sum.cpp<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int ceiling;
long long totsMagoats = 0;
cin >> ceiling;
long long shitToAddTogether[ceiling];
for (int i=0; i<ceiling; i++) {
int shit;
cin >> shit;
shitToAddTogether[i] = shit;
totsMagoats += shitToAddTogether[i];
}
cout << totsMagoats;
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionExclusionIteratorWithIndex.h"
template< class TRegion >
static bool RunTest(const TRegion & region, const TRegion & exclusionRegion)
{
const unsigned int ImageDimension = TRegion::ImageDimension;
typedef itk::Index< ImageDimension > IndexPixelType;
typedef unsigned char ValuePixelType;
typedef itk::Image< IndexPixelType, ImageDimension > IndexImageType;
typedef itk::Image< ValuePixelType, ImageDimension > ValueImageType;
typename IndexImageType::Pointer myIndexImage = IndexImageType::New();
myIndexImage->SetLargestPossibleRegion( region );
myIndexImage->SetBufferedRegion( region );
myIndexImage->SetRequestedRegion( region );
myIndexImage->Allocate();
typename ValueImageType::Pointer myValueImage = ValueImageType::New();
myValueImage->SetLargestPossibleRegion( region );
myValueImage->SetBufferedRegion( region );
myValueImage->SetRequestedRegion( region );
myValueImage->Allocate();
typedef itk::ImageRegionIteratorWithIndex< ValueImageType > ValueIteratorType;
typedef itk::ImageRegionIteratorWithIndex< IndexImageType > IndexIteratorType;
const unsigned char normalRegionValue = 100;
const unsigned char exclusionRegionValue = 200;
std::cout << "Initializing an image of indices and an image of values" << std::endl;
// Initialize the Image
IndexIteratorType ii( myIndexImage, region );
ValueIteratorType iv( myValueImage, region );
ii.GoToBegin();
iv.GoToBegin();
while( !ii.IsAtEnd() )
{
ii.Set( ii.GetIndex() );
iv.Set( normalRegionValue );
++ii;
++iv;
}
std::cout << "Initializing the exclusion region on the image of values " << std::endl;
// Set a different value inside the exclusion region
TRegion croppedExclusionRegion( exclusionRegion );
if ( !croppedExclusionRegion.Crop( region ) )
{
// Exclusion region is completely outside the region. Set it to
// have size 0.
typename TRegion::IndexType exclusionStart = region.GetIndex();
croppedExclusionRegion.SetIndex( exclusionStart );
typename TRegion::SizeType exclusionSize = croppedExclusionRegion.GetSize();
exclusionSize.Fill( 0 );
croppedExclusionRegion.SetSize( exclusionSize );
}
ValueIteratorType ive( myValueImage, croppedExclusionRegion );
ive.GoToBegin();
while( !ive.IsAtEnd() )
{
ive.Set( exclusionRegionValue );
++ive;
}
std::cout << "Starting walk with the exclusion iterator... ";
typedef itk::ImageRegionExclusionIteratorWithIndex< IndexImageType > ExclusionIndexIteratorType;
typedef itk::ImageRegionExclusionIteratorWithIndex< ValueImageType > ExclusionValueIteratorType;
ExclusionValueIteratorType ev( myValueImage, region );
ExclusionIndexIteratorType ei( myIndexImage, region );
ev.SetExclusionRegion( exclusionRegion );
ei.SetExclusionRegion( exclusionRegion );
unsigned int numberOfPixelsVisited = 0;
const unsigned int pixelsToVisit = region.GetNumberOfPixels() -
croppedExclusionRegion.GetNumberOfPixels();
ev.GoToBegin();
ei.GoToBegin();
while( !ev.IsAtEnd() )
{
if( ei.Get() != ei.GetIndex() )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It should be at " << ei.GetIndex();
std::cout << " but it is at " << ei.Get() << std::endl;
return false;
}
if( ev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
++ei;
++ev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
std::cout << " Ok ! " << std::endl;
std::cout << "Testing the iterator backwards... ";
numberOfPixelsVisited = 0;
ev.GoToReverseBegin();
ei.GoToReverseBegin();
while( !ev.IsAtReverseEnd() )
{
if( ei.Get() != ei.GetIndex() )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It should be at " << ei.GetIndex();
std::cout << " but it is at " << ei.Get() << std::endl;
return false;
}
if( ev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
--ei;
--ev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion iterator" << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
std::cout << " Ok ! " << std::endl;
std::cout << "Starting walk with the exclusion Const iterator... ";
typedef itk::ImageRegionExclusionConstIteratorWithIndex< IndexImageType > ExclusionIndexConstIteratorType;
typedef itk::ImageRegionExclusionConstIteratorWithIndex< ValueImageType > ExclusionValueConstIteratorType;
ExclusionValueConstIteratorType cev( myValueImage, region );
ExclusionIndexConstIteratorType cei( myIndexImage, region );
cev.SetExclusionRegion( exclusionRegion );
cei.SetExclusionRegion( exclusionRegion );
numberOfPixelsVisited = 0;
cev.GoToBegin();
cei.GoToBegin();
while( !cev.IsAtEnd() )
{
if( cei.Get() != cei.GetIndex() )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It should be at " << cei.GetIndex();
std::cout << " but it is at " << cei.Get() << std::endl;
return false;
}
if( cev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
++cei;
++cev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
std::cout << " Ok ! " << std::endl;
std::cout << "Testing the Const iterator backwards... ";
numberOfPixelsVisited = 0;
cev.GoToReverseBegin();
cei.GoToReverseBegin();
while( !cev.IsAtReverseEnd() )
{
if( cei.Get() != cei.GetIndex() )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It should be at " << cei.GetIndex();
std::cout << " but it is at " << cei.Get() << std::endl;
return false;
}
if( cev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << cev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
--cei;
--cev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
std::cout << " Ok ! " << std::endl;
std::cout << "Test PASSED ! " << std::endl;
return true;
}
int itkImageRegionExclusionIteratorWithIndexTest(int, char* [] )
{
const unsigned int Dimension = 3;
typedef itk::Size< Dimension > SizeType;
typedef itk::Index< Dimension > IndexType;
typedef itk::ImageRegion< Dimension > RegionType;
SizeType regionSize;
IndexType regionStart;
RegionType region;
regionStart.Fill( 0 );
regionSize.Fill( 7 );
region.SetIndex( regionStart );
region.SetSize( regionSize );
SizeType::SizeValueType size[2] = {4, 7};
unsigned int count = 0;
for (SizeType::SizeValueType s = 0; s < 2; ++s)
{
for (IndexType::IndexValueType k = -2; k < 6; ++k)
{
for (IndexType::IndexValueType j = -2; j < 6; ++j)
{
for (IndexType::IndexValueType i = -2; i < 6; ++i)
{
IndexType exclusionStart;
exclusionStart[0] = i;
exclusionStart[1] = j;
exclusionStart[2] = k;
SizeType exclusionSize;
exclusionSize.Fill( size[s] );
RegionType exclusionRegion( exclusionStart, exclusionSize );
std::cout << "Starting test " << count << "..." << std::endl;
count++;
if ( !RunTest( region, exclusionRegion ) )
{
std::cerr << "Test failed for exclusion region: " << exclusionRegion;
return EXIT_FAILURE;
}
}
}
}
}
// Test exclusion region completely outside the region.
IndexType exclusionStart;
exclusionStart.Fill( -3 );
SizeType exclusionSize;
exclusionSize.Fill( 2 );
RegionType exclusionRegion( exclusionStart, exclusionSize );
std::cout << "Starting test " << count << "..." << std::endl;
if ( !RunTest( region, exclusionRegion ) )
{
std::cerr << "Test failed for exclusion region: " << exclusionRegion;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>PERF: Reduced output of ImageRegionExclusionIteratorWithIndexTest<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRegionExclusionIteratorWithIndex.h"
template< class TRegion >
static bool RunTest(const TRegion & region, const TRegion & exclusionRegion)
{
const unsigned int ImageDimension = TRegion::ImageDimension;
typedef itk::Index< ImageDimension > IndexPixelType;
typedef unsigned char ValuePixelType;
typedef itk::Image< IndexPixelType, ImageDimension > IndexImageType;
typedef itk::Image< ValuePixelType, ImageDimension > ValueImageType;
typename IndexImageType::Pointer myIndexImage = IndexImageType::New();
myIndexImage->SetLargestPossibleRegion( region );
myIndexImage->SetBufferedRegion( region );
myIndexImage->SetRequestedRegion( region );
myIndexImage->Allocate();
typename ValueImageType::Pointer myValueImage = ValueImageType::New();
myValueImage->SetLargestPossibleRegion( region );
myValueImage->SetBufferedRegion( region );
myValueImage->SetRequestedRegion( region );
myValueImage->Allocate();
typedef itk::ImageRegionIteratorWithIndex< ValueImageType > ValueIteratorType;
typedef itk::ImageRegionIteratorWithIndex< IndexImageType > IndexIteratorType;
const unsigned char normalRegionValue = 100;
const unsigned char exclusionRegionValue = 200;
// Initialize the Image
IndexIteratorType ii( myIndexImage, region );
ValueIteratorType iv( myValueImage, region );
ii.GoToBegin();
iv.GoToBegin();
while( !ii.IsAtEnd() )
{
ii.Set( ii.GetIndex() );
iv.Set( normalRegionValue );
++ii;
++iv;
}
// Set a different value inside the exclusion region
TRegion croppedExclusionRegion( exclusionRegion );
if ( !croppedExclusionRegion.Crop( region ) )
{
// Exclusion region is completely outside the region. Set it to
// have size 0.
typename TRegion::IndexType exclusionStart = region.GetIndex();
croppedExclusionRegion.SetIndex( exclusionStart );
typename TRegion::SizeType exclusionSize = croppedExclusionRegion.GetSize();
exclusionSize.Fill( 0 );
croppedExclusionRegion.SetSize( exclusionSize );
}
ValueIteratorType ive( myValueImage, croppedExclusionRegion );
ive.GoToBegin();
while( !ive.IsAtEnd() )
{
ive.Set( exclusionRegionValue );
++ive;
}
typedef itk::ImageRegionExclusionIteratorWithIndex< IndexImageType > ExclusionIndexIteratorType;
typedef itk::ImageRegionExclusionIteratorWithIndex< ValueImageType > ExclusionValueIteratorType;
ExclusionValueIteratorType ev( myValueImage, region );
ExclusionIndexIteratorType ei( myIndexImage, region );
ev.SetExclusionRegion( exclusionRegion );
ei.SetExclusionRegion( exclusionRegion );
unsigned int numberOfPixelsVisited = 0;
const unsigned int pixelsToVisit = region.GetNumberOfPixels() -
croppedExclusionRegion.GetNumberOfPixels();
ev.GoToBegin();
ei.GoToBegin();
while( !ev.IsAtEnd() )
{
if( ei.Get() != ei.GetIndex() )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It should be at " << ei.GetIndex();
std::cout << " but it is at " << ei.Get() << std::endl;
return false;
}
if( ev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
++ei;
++ev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
numberOfPixelsVisited = 0;
ev.GoToReverseBegin();
ei.GoToReverseBegin();
while( !ev.IsAtReverseEnd() )
{
if( ei.Get() != ei.GetIndex() )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It should be at " << ei.GetIndex();
std::cout << " but it is at " << ei.Get() << std::endl;
return false;
}
if( ev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
--ei;
--ev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion iterator" << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
typedef itk::ImageRegionExclusionConstIteratorWithIndex< IndexImageType > ExclusionIndexConstIteratorType;
typedef itk::ImageRegionExclusionConstIteratorWithIndex< ValueImageType > ExclusionValueConstIteratorType;
ExclusionValueConstIteratorType cev( myValueImage, region );
ExclusionIndexConstIteratorType cei( myIndexImage, region );
cev.SetExclusionRegion( exclusionRegion );
cei.SetExclusionRegion( exclusionRegion );
numberOfPixelsVisited = 0;
cev.GoToBegin();
cei.GoToBegin();
while( !cev.IsAtEnd() )
{
if( cei.Get() != cei.GetIndex() )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It should be at " << cei.GetIndex();
std::cout << " but it is at " << cei.Get() << std::endl;
return false;
}
if( cev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << ev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
++cei;
++cev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
numberOfPixelsVisited = 0;
cev.GoToReverseBegin();
cei.GoToReverseBegin();
while( !cev.IsAtReverseEnd() )
{
if( cei.Get() != cei.GetIndex() )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It should be at " << cei.GetIndex();
std::cout << " but it is at " << cei.Get() << std::endl;
return false;
}
if( cev.Get() != normalRegionValue )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is stepping into the exclusion region " << std::endl;
std::cout << "Entry point = " << cev.GetIndex() << std::endl;
return false;
}
++numberOfPixelsVisited;
--cei;
--cev;
}
if( numberOfPixelsVisited != pixelsToVisit )
{
std::cout << "Error in exclusion const iterator " << std::endl;
std::cout << "It is not visiting all the pixels it should" << std::endl;
std::cout << numberOfPixelsVisited << " pixels were visited instead of ";
std::cout << pixelsToVisit << std::endl;
return false;
}
return true;
}
int itkImageRegionExclusionIteratorWithIndexTest(int, char* [] )
{
const unsigned int Dimension = 3;
typedef itk::Size< Dimension > SizeType;
typedef itk::Index< Dimension > IndexType;
typedef itk::ImageRegion< Dimension > RegionType;
SizeType regionSize;
IndexType regionStart;
RegionType region;
regionStart.Fill( 0 );
regionSize.Fill( 7 );
region.SetIndex( regionStart );
region.SetSize( regionSize );
SizeType::SizeValueType size[2] = {4, 7};
unsigned int count = 0;
for (SizeType::SizeValueType s = 0; s < 2; ++s)
{
for (IndexType::IndexValueType k = -2; k < 6; ++k)
{
for (IndexType::IndexValueType j = -2; j < 6; ++j)
{
for (IndexType::IndexValueType i = -2; i < 6; ++i)
{
IndexType exclusionStart;
exclusionStart[0] = i;
exclusionStart[1] = j;
exclusionStart[2] = k;
SizeType exclusionSize;
exclusionSize.Fill( size[s] );
RegionType exclusionRegion( exclusionStart, exclusionSize );
count++;
if ( !RunTest( region, exclusionRegion ) )
{
std::cerr << "Test failed for exclusion region: " << exclusionRegion;
return EXIT_FAILURE;
}
}
}
}
}
// Test exclusion region completely outside the region.
IndexType exclusionStart;
exclusionStart.Fill( -3 );
SizeType exclusionSize;
exclusionSize.Fill( 2 );
RegionType exclusionRegion( exclusionStart, exclusionSize );
if ( !RunTest( region, exclusionRegion ) )
{
std::cerr << "Test failed for exclusion region: " << exclusionRegion;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>NAN_METHOD(GitPatch::ConvenientFromDiff) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Diff diff is required.");
}
if (info.Length() == 1 || !info[1]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
ConvenientFromDiffBaton *baton = new ConvenientFromDiffBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->diff = Nan::ObjectWrap::Unwrap<GitDiff>(info[0]->ToObject())->GetValue();
baton->out = new std::vector<PatchData *>;
baton->out->reserve(git_diff_num_deltas(baton->diff));
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[1]));
ConvenientFromDiffWorker *worker = new ConvenientFromDiffWorker(baton, callback);
worker->SaveToPersistent("diff", info[0]);
Nan::AsyncQueueWorker(worker);
return;
}
void GitPatch::ConvenientFromDiffWorker::Execute() {
giterr_clear();
{
LockMaster lockMaster(true, baton->diff);
std::vector<git_patch *> patchesToBeFreed;
patchesToBeFreed.reserve(git_diff_num_deltas(baton->diff));
for (int i = 0; i < git_diff_num_deltas(baton->diff); ++i) {
git_patch * nextPatch;
int result = git_patch_from_diff(&nextPatch, baton->diff, i);
if (result) {
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
while (!baton->out->empty()) {
PatchDataFree(baton->out->back());
baton->out->pop_back();
}
baton->error_code = result;
if (giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
delete baton->out;
baton->out = NULL;
return;
}
if (nextPatch != NULL) {
baton->out->push_back(createFromRaw(nextPatch));
}
}
unsigned int size = patchesToBeFreed.size();
for (unsigned int i = 0; i < size; ++i) {
git_patch *patch = patchesToBeFreed.at(i);
git_patch_free(patch);
}
}
}
void GitPatch::ConvenientFromDiffWorker::HandleOKCallback() {
if (baton->out != NULL) {
unsigned int size = baton->out->size();
Local<Array> result = Nan::New<Array>(size);
for (unsigned int i = 0; i < size; ++i) {
Nan::Set(result, Nan::New<Number>(i), ConvenientPatch::New((void *)baton->out->at(i)));
}
delete baton->out;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
return;
}
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
{
free((void *)baton->error->message);
}
free((void *)baton->error);
return;
}
if (baton->error_code < 0) {
Local<v8::Object> err = Nan::Error("method convenientFromDiff has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
return;
}
callback->Call(0, NULL);
}
<commit_msg>Tidy up convenient_patches generator<commit_after>NAN_METHOD(GitPatch::ConvenientFromDiff) {
if (info.Length() == 0 || !info[0]->IsObject()) {
return Nan::ThrowError("Diff diff is required.");
}
if (info.Length() == 1 || !info[1]->IsFunction()) {
return Nan::ThrowError("Callback is required and must be a Function.");
}
ConvenientFromDiffBaton *baton = new ConvenientFromDiffBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->diff = Nan::ObjectWrap::Unwrap<GitDiff>(info[0]->ToObject())->GetValue();
baton->out = new std::vector<PatchData *>;
baton->out->reserve(git_diff_num_deltas(baton->diff));
Nan::Callback *callback = new Nan::Callback(Local<Function>::Cast(info[1]));
ConvenientFromDiffWorker *worker = new ConvenientFromDiffWorker(baton, callback);
worker->SaveToPersistent("diff", info[0]);
Nan::AsyncQueueWorker(worker);
return;
}
void GitPatch::ConvenientFromDiffWorker::Execute() {
giterr_clear();
{
LockMaster lockMaster(true, baton->diff);
std::vector<git_patch *> patchesToBeFreed;
for (int i = 0; i < git_diff_num_deltas(baton->diff); ++i) {
git_patch *nextPatch;
int result = git_patch_from_diff(&nextPatch, baton->diff, i);
if (result) {
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
while (!baton->out->empty()) {
PatchDataFree(baton->out->back());
baton->out->pop_back();
}
baton->error_code = result;
if (giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
delete baton->out;
baton->out = NULL;
return;
}
if (nextPatch != NULL) {
baton->out->push_back(createFromRaw(nextPatch));
}
}
while (!patchesToBeFreed.empty())
{
git_patch_free(patchesToBeFreed.back());
patchesToBeFreed.pop_back();
}
}
}
void GitPatch::ConvenientFromDiffWorker::HandleOKCallback() {
if (baton->out != NULL) {
unsigned int size = baton->out->size();
Local<Array> result = Nan::New<Array>(size);
for (unsigned int i = 0; i < size; ++i) {
Nan::Set(result, Nan::New<Number>(i), ConvenientPatch::New((void *)baton->out->at(i)));
}
delete baton->out;
Local<v8::Value> argv[2] = {
Nan::Null(),
result
};
callback->Call(2, argv);
return;
}
if (baton->error) {
Local<v8::Value> argv[1] = {
Nan::Error(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
{
free((void *)baton->error->message);
}
free((void *)baton->error);
return;
}
if (baton->error_code < 0) {
Local<v8::Object> err = Nan::Error("method convenientFromDiff has thrown an error.")->ToObject();
err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
Local<v8::Value> argv[1] = {
err
};
callback->Call(1, argv);
return;
}
callback->Call(0, NULL);
}
<|endoftext|> |
<commit_before>//===- Generics.cpp ---- Utilities for transforming generics ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "generic-specializer"
#include "swift/Strings.h"
#include "swift/SILPasses/Utils/Generics.h"
#include "swift/SILPasses/Utils/GenericCloner.h"
using namespace swift;
// Create a new apply based on an old one, but with a different
// function being applied.
static ApplySite replaceWithSpecializedFunction(ApplySite AI,
SILFunction *NewF) {
SILLocation Loc = AI.getLoc();
ArrayRef<Substitution> Subst;
SmallVector<SILValue, 4> Arguments;
for (auto &Op : AI.getArgumentOperands()) {
Arguments.push_back(Op.get());
}
SILBuilderWithScope<2> Builder(AI.getInstruction());
FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF);
if (auto *TAI = dyn_cast<TryApplyInst>(AI))
return Builder.createTryApply(Loc, FRI, TAI->getSubstCalleeSILType(),
{}, Arguments, TAI->getNormalBB(),
TAI->getErrorBB());
if (isa<ApplyInst>(AI))
return Builder.createApply(Loc, FRI, Arguments);
if (auto *PAI = dyn_cast<PartialApplyInst>(AI))
return Builder.createPartialApply(Loc, FRI,
PAI->getSubstCalleeSILType(),
{},
Arguments,
PAI->getType());
llvm_unreachable("unhandled kind of apply");
}
/// Try to convert definition into declaration.
static bool convertExtenralDefinitionIntoDeclaration(SILFunction *F) {
// Bail if it is a declaration already.
if (!F->isDefinition())
return false;
// Bail if there is no external implementation of this function.
if (!F->isAvailableExternally())
return false;
// Bail if has a shared visibility, as there are no guarantees
// that an implementation is available elsewhere.
if (hasSharedVisibility(F->getLinkage()))
return false;
// Make this definition a declaration by removing the body of a function.
F->convertToDeclaration();
assert(F->isExternalDeclaration() &&
"Function should be an external declaration");
DEBUG(llvm::dbgs() << " removed external function " << F->getName()
<< "\n");
return true;
}
/// Check of a given name could be a name of a white-listed
/// specialization.
bool swift::isWhitelistedSpecialization(StringRef SpecName) {
// The whitelist of classes and functions from the stdlib,
// whose specializations we want to preserve.
ArrayRef<StringRef> Whitelist = {
"Array",
"_ArrayBuffer",
"_ContiguousArrayBuffer",
"Range",
"RangeGenerator",
"UTF8",
"UTF16",
"String",
"_StringBuffer",
"_toStringReadOnlyPrintable",
};
// TODO: Once there is an efficient API to check if
// a given symbol is a specialization of a specific type,
// use it instead. Doing demangling just for this check
// is just wasteful.
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(SpecName);
StringRef DemangledName = DemangledNameString;
auto pos = DemangledName.find("generic ", 0);
if (pos == StringRef::npos)
return false;
// Create "of Swift"
llvm::SmallString<64> OfString;
llvm::raw_svector_ostream buffer(OfString);
buffer << "of ";
buffer << STDLIB_NAME <<'.';
StringRef OfStr = buffer.str();
pos = DemangledName.find(OfStr, pos);
if (pos == StringRef::npos)
return false;
pos += OfStr.size();
for(auto Name: Whitelist) {
auto pos1 = DemangledName.find(Name, pos);
if (pos1 == pos && !isalpha(DemangledName[pos1+Name.size()])) {
return true;
}
}
return false;
}
/// Cache a specialization.
/// For now, it is performed only for specializations in the
/// standard library. But in the future, one could think of
/// maintaining a cache of optimized specializations.
///
/// Mark specializations as public, so that they can be used
/// by user applications. These specializations are supposed to be
/// used only by -Onone compiled code. They should be never inlined.
static bool cacheSpecialization(SILModule &M, SILFunction *F) {
// Do not remove functions from the white-list. Keep them around.
// Change their linkage to public, so that other applications can refer to it.
if (M.getOptions().Optimization == SILOptions::SILOptMode::Optimize &&
F->getLinkage() != SILLinkage::Public &&
F->getModule().getSwiftModule()->getName().str() == STDLIB_NAME) {
if (F->getLinkage() != SILLinkage::Public &&
isWhitelistedSpecialization(F->getName())) {
DEBUG(
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(F->getName());
StringRef DemangledName = DemangledNameString;
llvm::dbgs() << "Keep specialization: " << DemangledName << " : "
<< F->getName() << "\n");
// Make it public, so that others can refer to it.
// NOTE: This function may refer to non-public symbols, which may lead
// to problems, if you ever try to inline this function. Therefore,
// these specializations should only be used to refer to them,
// but should never be inlined!
// The general rule could be: Never inline specializations from stdlib!
// NOTE: Making these specializations public at this point breaks
// some optimizations. Therefore, just mark the function.
// DeadFunctionElimination pass will check if the function is marked
// and preserve it if required.
F->setKeepAsPublic(true);
return true;
}
}
return false;
}
/// Try to look up an existing specialization in the specialization cache.
/// If it is found, it tries to link this specialization.
///
/// For now, it performs a lookup only in the standard library.
/// But in the future, one could think of maintaining a cache
/// of optimized specializations.
static SILFunction *lookupExistingSpecialization(SILModule &M,
StringRef FunctionName) {
// Try to link existing specialization only in -Onone mode.
// All other compilation modes perform specialization themselves.
// TODO: Cache optimized specializations and perform lookup here?
// TODO: Only check that this function exists, but don't read
// its body. It can save some compile-time.
if (M.getOptions().UsePrespecialized &&
isWhitelistedSpecialization(FunctionName) &&
M.linkFunction(FunctionName, SILOptions::LinkingMode::LinkNormal))
return M.lookUpFunction(FunctionName);
return nullptr;
}
ApplySite swift::trySpecializeApplyOfGeneric(ApplySite Apply,
SILFunction *&NewFunction,
llvm::SmallVectorImpl<FullApplyCollector::value_type> &NewApplyPairs) {
NewFunction = nullptr;
assert(NewApplyPairs.empty() && "Expected no new applies in vector yet!");
assert(Apply.hasSubstitutions() && "Expected an apply with substitutions!");
auto *F = cast<FunctionRefInst>(Apply.getCallee())->getReferencedFunction();
assert(F->isDefinition() && "Expected definition to specialize!");
DEBUG(llvm::dbgs() << " ApplyInst: " << *Apply.getInstruction());
// Create the substitution maps.
TypeSubstitutionMap InterfaceSubs;
TypeSubstitutionMap ContextSubs;
if (F->getLoweredFunctionType()->getGenericSignature())
InterfaceSubs = F->getLoweredFunctionType()->getGenericSignature()
->getSubstitutionMap(Apply.getSubstitutions());
if (F->getContextGenericParams())
ContextSubs = F->getContextGenericParams()
->getSubstitutionMap(Apply.getSubstitutions());
// We do not support partial specialization.
if (hasUnboundGenericTypes(InterfaceSubs)) {
DEBUG(llvm::dbgs() << " Can not specialize with interface subs.\n");
return ApplySite();
}
if (hasDynamicSelfTypes(InterfaceSubs)) {
DEBUG(llvm::dbgs() << " Cannot specialize with dynamic self.\n");
return ApplySite();
}
llvm::SmallString<64> ClonedName;
{
llvm::raw_svector_ostream buffer(ClonedName);
ArrayRef<Substitution> Subs = Apply.getSubstitutions();
Mangle::Mangler M(buffer);
Mangle::GenericSpecializationMangler Mangler(M, F, Subs);
Mangler.mangle();
}
DEBUG(llvm::dbgs() << " Specialized function " << ClonedName << '\n');
SILFunction *NewF = nullptr;
auto &M = Apply.getInstruction()->getModule();
// If we already have this specialization, reuse it.
if (auto PrevF = M.lookUpFunction(ClonedName)) {
NewF = PrevF;
} else {
PrevF = lookupExistingSpecialization(M, ClonedName);
if (PrevF) {
// The bodies of existing specializations cannot be used,
// as they may refer to non-public symbols.
if (PrevF->isDefinition())
PrevF->convertToDeclaration();
if (hasPublicVisibility(PrevF->getLinkage())) {
NewF = PrevF;
NewF->setLinkage(SILLinkage::PublicExternal);
// Ignore body for -Onone and -Odebug.
if (!convertExtenralDefinitionIntoDeclaration(NewF)) {
DEBUG(llvm::dbgs()
<< "Could not remove body of: " << ClonedName << '\n';);
}
DEBUG(
llvm::dbgs() << "Found existing specialization for: "
<< ClonedName << '\n';
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(NewF->getName());
llvm::dbgs() << DemangledNameString << "\n\n");
} else {
// Forget about this function.
llvm::dbgs() << "Cannot reuse the specialization: "
<< swift::Demangle::demangleSymbolAsString(PrevF->getName()) << "\n";
if (!PrevF->getRefCount())
M.eraseFunction(PrevF);
else {
// FIXME: We need to do something here.
return ApplySite();
}
}
}
}
if (NewF) {
#ifndef NDEBUG
// Make sure that NewF's subst type matches the expected type.
auto Subs = Apply.getSubstitutions();
auto FTy =
F->getLoweredFunctionType()->substGenericArgs(M,
M.getSwiftModule(),
Subs);
assert(FTy == NewF->getLoweredFunctionType() &&
"Previously specialized function does not match expected type.");
#endif
} else {
// Do not create any new specializations at Onone.
if (M.getOptions().Optimization <= SILOptions::SILOptMode::None)
return ApplySite();
DEBUG(
if (M.getOptions().Optimization <= SILOptions::SILOptMode::Debug) {
llvm::dbgs() << "Creating a specialization: " << ClonedName << "\n"; });
FullApplyCollector Collector;
// Create a new function.
NewF = GenericCloner::cloneFunction(F, InterfaceSubs, ContextSubs,
ClonedName, Apply,
Collector.getCallback());
for (auto &P : Collector.getApplyPairs())
NewApplyPairs.push_back(P);
NewFunction = NewF;
// Check if this specialization should be cached.
cacheSpecialization(M, NewF);
}
return replaceWithSpecializedFunction(Apply, NewF);
}
<commit_msg>Revert "Revert "Fix a bug in pre-specialization when it comes to re-use of specializations.""<commit_after>//===- Generics.cpp ---- Utilities for transforming generics ----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "generic-specializer"
#include "swift/Strings.h"
#include "swift/SILPasses/Utils/Generics.h"
#include "swift/SILPasses/Utils/GenericCloner.h"
using namespace swift;
// Create a new apply based on an old one, but with a different
// function being applied.
static ApplySite replaceWithSpecializedFunction(ApplySite AI,
SILFunction *NewF) {
SILLocation Loc = AI.getLoc();
ArrayRef<Substitution> Subst;
SmallVector<SILValue, 4> Arguments;
for (auto &Op : AI.getArgumentOperands()) {
Arguments.push_back(Op.get());
}
SILBuilderWithScope<2> Builder(AI.getInstruction());
FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF);
if (auto *TAI = dyn_cast<TryApplyInst>(AI))
return Builder.createTryApply(Loc, FRI, TAI->getSubstCalleeSILType(),
{}, Arguments, TAI->getNormalBB(),
TAI->getErrorBB());
if (isa<ApplyInst>(AI))
return Builder.createApply(Loc, FRI, Arguments);
if (auto *PAI = dyn_cast<PartialApplyInst>(AI))
return Builder.createPartialApply(Loc, FRI,
PAI->getSubstCalleeSILType(),
{},
Arguments,
PAI->getType());
llvm_unreachable("unhandled kind of apply");
}
/// Try to convert definition into declaration.
static bool convertExtenralDefinitionIntoDeclaration(SILFunction *F) {
// Bail if it is a declaration already.
if (!F->isDefinition())
return false;
// Bail if there is no external implementation of this function.
if (!F->isAvailableExternally())
return false;
// Bail if has a shared visibility, as there are no guarantees
// that an implementation is available elsewhere.
if (hasSharedVisibility(F->getLinkage()))
return false;
// Make this definition a declaration by removing the body of a function.
F->convertToDeclaration();
assert(F->isExternalDeclaration() &&
"Function should be an external declaration");
DEBUG(llvm::dbgs() << " removed external function " << F->getName()
<< "\n");
return true;
}
/// Check of a given name could be a name of a white-listed
/// specialization.
bool swift::isWhitelistedSpecialization(StringRef SpecName) {
// The whitelist of classes and functions from the stdlib,
// whose specializations we want to preserve.
ArrayRef<StringRef> Whitelist = {
"Array",
"_ArrayBuffer",
"_ContiguousArrayBuffer",
"Range",
"RangeGenerator",
"UTF8",
"UTF16",
"String",
"_StringBuffer",
"_toStringReadOnlyPrintable",
};
// TODO: Once there is an efficient API to check if
// a given symbol is a specialization of a specific type,
// use it instead. Doing demangling just for this check
// is just wasteful.
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(SpecName);
StringRef DemangledName = DemangledNameString;
auto pos = DemangledName.find("generic ", 0);
if (pos == StringRef::npos)
return false;
// Create "of Swift"
llvm::SmallString<64> OfString;
llvm::raw_svector_ostream buffer(OfString);
buffer << "of ";
buffer << STDLIB_NAME <<'.';
StringRef OfStr = buffer.str();
pos = DemangledName.find(OfStr, pos);
if (pos == StringRef::npos)
return false;
pos += OfStr.size();
for(auto Name: Whitelist) {
auto pos1 = DemangledName.find(Name, pos);
if (pos1 == pos && !isalpha(DemangledName[pos1+Name.size()])) {
return true;
}
}
return false;
}
/// Cache a specialization.
/// For now, it is performed only for specializations in the
/// standard library. But in the future, one could think of
/// maintaining a cache of optimized specializations.
///
/// Mark specializations as public, so that they can be used
/// by user applications. These specializations are supposed to be
/// used only by -Onone compiled code. They should be never inlined.
static bool cacheSpecialization(SILModule &M, SILFunction *F) {
// Do not remove functions from the white-list. Keep them around.
// Change their linkage to public, so that other applications can refer to it.
if (M.getOptions().Optimization == SILOptions::SILOptMode::Optimize &&
F->getLinkage() != SILLinkage::Public &&
F->getModule().getSwiftModule()->getName().str() == STDLIB_NAME) {
if (F->getLinkage() != SILLinkage::Public &&
isWhitelistedSpecialization(F->getName())) {
DEBUG(
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(F->getName());
StringRef DemangledName = DemangledNameString;
llvm::dbgs() << "Keep specialization: " << DemangledName << " : "
<< F->getName() << "\n");
// Make it public, so that others can refer to it.
// NOTE: This function may refer to non-public symbols, which may lead
// to problems, if you ever try to inline this function. Therefore,
// these specializations should only be used to refer to them,
// but should never be inlined!
// The general rule could be: Never inline specializations from stdlib!
// NOTE: Making these specializations public at this point breaks
// some optimizations. Therefore, just mark the function.
// DeadFunctionElimination pass will check if the function is marked
// and preserve it if required.
F->setKeepAsPublic(true);
return true;
}
}
return false;
}
/// Try to look up an existing specialization in the specialization cache.
/// If it is found, it tries to link this specialization.
///
/// For now, it performs a lookup only in the standard library.
/// But in the future, one could think of maintaining a cache
/// of optimized specializations.
static SILFunction *lookupExistingSpecialization(SILModule &M,
StringRef FunctionName) {
// Try to link existing specialization only in -Onone mode.
// All other compilation modes perform specialization themselves.
// TODO: Cache optimized specializations and perform lookup here?
// TODO: Only check that this function exists, but don't read
// its body. It can save some compile-time.
if (M.getOptions().UsePrespecialized &&
isWhitelistedSpecialization(FunctionName) &&
M.linkFunction(FunctionName, SILOptions::LinkingMode::LinkNormal))
return M.lookUpFunction(FunctionName);
return nullptr;
}
ApplySite swift::trySpecializeApplyOfGeneric(ApplySite Apply,
SILFunction *&NewFunction,
llvm::SmallVectorImpl<FullApplyCollector::value_type> &NewApplyPairs) {
NewFunction = nullptr;
assert(NewApplyPairs.empty() && "Expected no new applies in vector yet!");
assert(Apply.hasSubstitutions() && "Expected an apply with substitutions!");
auto *F = cast<FunctionRefInst>(Apply.getCallee())->getReferencedFunction();
assert(F->isDefinition() && "Expected definition to specialize!");
DEBUG(llvm::dbgs() << " ApplyInst: " << *Apply.getInstruction());
// Create the substitution maps.
TypeSubstitutionMap InterfaceSubs;
TypeSubstitutionMap ContextSubs;
if (F->getLoweredFunctionType()->getGenericSignature())
InterfaceSubs = F->getLoweredFunctionType()->getGenericSignature()
->getSubstitutionMap(Apply.getSubstitutions());
if (F->getContextGenericParams())
ContextSubs = F->getContextGenericParams()
->getSubstitutionMap(Apply.getSubstitutions());
// We do not support partial specialization.
if (hasUnboundGenericTypes(InterfaceSubs)) {
DEBUG(llvm::dbgs() << " Can not specialize with interface subs.\n");
return ApplySite();
}
if (hasDynamicSelfTypes(InterfaceSubs)) {
DEBUG(llvm::dbgs() << " Cannot specialize with dynamic self.\n");
return ApplySite();
}
llvm::SmallString<64> ClonedName;
{
llvm::raw_svector_ostream buffer(ClonedName);
ArrayRef<Substitution> Subs = Apply.getSubstitutions();
Mangle::Mangler M(buffer);
Mangle::GenericSpecializationMangler Mangler(M, F, Subs);
Mangler.mangle();
}
DEBUG(llvm::dbgs() << " Specialized function " << ClonedName << '\n');
SILFunction *NewF = nullptr;
auto &M = Apply.getInstruction()->getModule();
// If we already have this specialization, reuse it.
auto PrevF = M.lookUpFunction(ClonedName);
if (PrevF) {
if (PrevF->getLinkage() != SILLinkage::SharedExternal ||
!M.getOptions().UsePrespecialized)
NewF = PrevF;
} else {
PrevF = lookupExistingSpecialization(M, ClonedName);
if (PrevF) {
if (hasPublicVisibility(PrevF->getLinkage())) {
// The bodies of existing specializations cannot be used,
// as they may refer to non-public symbols.
if (PrevF->isDefinition())
PrevF->convertToDeclaration();
NewF = PrevF;
NewF->setLinkage(SILLinkage::PublicExternal);
// Ignore body for -Onone and -Odebug.
assert((NewF->isExternalDeclaration() ||
convertExtenralDefinitionIntoDeclaration(NewF)) &&
"Could not remove body of the found specialization");
if (!convertExtenralDefinitionIntoDeclaration(NewF)) {
DEBUG(llvm::dbgs()
<< "Could not remove body of: " << ClonedName << '\n';);
}
DEBUG(
llvm::dbgs() << "Found existing specialization for: "
<< ClonedName << '\n';
auto DemangledNameString =
swift::Demangle::demangleSymbolAsString(NewF->getName());
llvm::dbgs() << DemangledNameString << "\n\n");
} else {
// Forget about this function.
DEBUG(llvm::dbgs()
<< "Cannot reuse the specialization: "
<< swift::Demangle::demangleSymbolAsString(PrevF->getName())
<< "\n");
// TODO: It would be nice to jut remove this function from the module.
// But this is not possible, because SILDeserializer keeps a reference
// to this function and currently there is no implemented API to
// remove a specific reference from the SIL cache.
// So, this function stays in the final SIL, even though it is not
// used at all.
// M.eraseFunction(PrevF);
return ApplySite();
}
}
}
if (NewF) {
#ifndef NDEBUG
// Make sure that NewF's subst type matches the expected type.
auto Subs = Apply.getSubstitutions();
auto FTy =
F->getLoweredFunctionType()->substGenericArgs(M,
M.getSwiftModule(),
Subs);
assert(FTy == NewF->getLoweredFunctionType() &&
"Previously specialized function does not match expected type.");
#endif
} else {
// Do not create any new specializations at Onone.
if (M.getOptions().Optimization <= SILOptions::SILOptMode::None)
return ApplySite();
DEBUG(
if (M.getOptions().Optimization <= SILOptions::SILOptMode::Debug) {
llvm::dbgs() << "Creating a specialization: " << ClonedName << "\n"; });
FullApplyCollector Collector;
// Create a new function.
NewF = GenericCloner::cloneFunction(F, InterfaceSubs, ContextSubs,
ClonedName, Apply,
Collector.getCallback());
for (auto &P : Collector.getApplyPairs())
NewApplyPairs.push_back(P);
NewFunction = NewF;
// Check if this specialization should be cached.
cacheSpecialization(M, NewF);
}
return replaceWithSpecializedFunction(Apply, NewF);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbVectorImage.h"
#include "itkVector.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbStreamingWarpImageFilter.h"
int otbStreamingWarpImageFilter(int argc, char* argv[])
{
if (argc != 5)
{
std::cout << "usage: " << argv[0] << "infname deffname outfname radius" << std::endl;
return EXIT_SUCCESS;
}
// Input parameters
const char * infname = argv[1];
const char * deffname = argv[2];
const char * outfname = argv[3];
const double maxdef = atoi(argv[4]);
// Images definition
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::Image<PixelType, Dimension> ImageType;
typedef itk::Vector<PixelType, 2> DisplacementValueType;
typedef otb::Image<DisplacementValueType, Dimension> DisplacementFieldType;
// Warper
typedef otb::StreamingWarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType;
// Reader/Writer
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileReader<DisplacementFieldType> DisplacementReaderType;
typedef otb::ImageFileWriter<ImageType> WriterType;
// Objects creation
DisplacementReaderType::Pointer displacementReader = DisplacementReaderType::New();
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
ImageWarperType::Pointer warper = ImageWarperType::New();
// Reading
reader->SetFileName(infname);
displacementReader->SetFileName(deffname);
// Warping
DisplacementValueType maxDisplacement;
maxDisplacement.Fill(maxdef);
warper->SetMaximumDisplacement(maxDisplacement);
warper->SetInput(reader->GetOutput());
warper->SetDisplacementField(displacementReader->GetOutput());
// Writing
writer->SetInput(warper->GetOutput());
writer->SetFileName(outfname);
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: ensure output has the same origin as deformation field<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbVectorImage.h"
#include "itkVector.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbStreamingWarpImageFilter.h"
int otbStreamingWarpImageFilter(int argc, char* argv[])
{
if (argc != 5)
{
std::cout << "usage: " << argv[0] << "infname deffname outfname radius" << std::endl;
return EXIT_SUCCESS;
}
// Input parameters
const char * infname = argv[1];
const char * deffname = argv[2];
const char * outfname = argv[3];
const double maxdef = atoi(argv[4]);
// Images definition
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::Image<PixelType, Dimension> ImageType;
typedef itk::Vector<PixelType, 2> DisplacementValueType;
typedef otb::Image<DisplacementValueType, Dimension> DisplacementFieldType;
// Change default output origin
ImageType::PointType origin;
origin.Fill(0.5);
// Warper
typedef otb::StreamingWarpImageFilter<ImageType, ImageType, DisplacementFieldType> ImageWarperType;
// Reader/Writer
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileReader<DisplacementFieldType> DisplacementReaderType;
typedef otb::ImageFileWriter<ImageType> WriterType;
// Objects creation
DisplacementReaderType::Pointer displacementReader = DisplacementReaderType::New();
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
ImageWarperType::Pointer warper = ImageWarperType::New();
// Reading
reader->SetFileName(infname);
displacementReader->SetFileName(deffname);
// Warping
DisplacementValueType maxDisplacement;
maxDisplacement.Fill(maxdef);
warper->SetMaximumDisplacement(maxDisplacement);
warper->SetInput(reader->GetOutput());
warper->SetDisplacementField(displacementReader->GetOutput());
warper->SetOutputOrigin(origin);
// Writing
writer->SetInput(warper->GetOutput());
writer->SetFileName(outfname);
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
namespace
{
void runTest(...)
{
//std::cout << "Basis # " << basis << std::endl;
//FieldInformation lfi("LatVolMesh", basis, "double");
//size_type sizex = 2, sizey = 3, sizez = 4;
//Point minb(-1.0, -1.0, -1.0);
//Point maxb(1.0, 1.0, 1.0);
//MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
//FieldHandle ofh = CreateField(lfi,mesh);
//ofh->vfield()->clear_all_values();
//GetFieldBoundaryAlgo algo;
//FieldHandle boundary;
//MatrixHandle mapping;
//algo.run(ofh, boundary, mapping);
//ASSERT_TRUE(boundary);
/// @todo: need assertions on boundary field
//if (basis != -1)
//{
// ASSERT_TRUE(mapping);
// EXPECT_EQ(expectedMatrixRows, mapping->nrows());
// EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
// std::ostringstream ostr;
// ostr << *mapping;
// //std::cout << "expected\n" << expectedMatrixString << std::endl;
// //std::cout << "actual\n" << ostr.str() << std::endl;
// EXPECT_EQ(expectedMatrixString, ostr.str());
//}
}
}
TEST(ConvertMeshToTriSurfAlgoTests, DISABLED_Foo)
{
FAIL() << "TODO";
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
<commit_msg>Closes #475<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
namespace
{
void runTest(...)
{
}
}
TEST(ConvertMeshToTriSurfAlgoTests, DISABLED_Foo)
{
FAIL() << "TODO";
}
<|endoftext|> |
<commit_before>#include "TextureEditor.hpp"
#include <Engine/Texture/TextureAsset.hpp>
#include <Video/Texture/Texture2D.hpp>
#include "../FileSelector.hpp"
#include <functional>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <imgui.h>
using namespace GUI;
TextureEditor::TextureEditor() {
name[0] = '\0';
}
void TextureEditor::Show() {
if (ImGui::Begin(("Texture: " + texture->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(texture))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) {
ImGui::InputText("Name", name, 128);
texture->name = name;
if (texture->GetTexture()->IsLoaded()) {
ImGui::Image((void*) texture->GetTexture()->GetTextureID(), ImVec2(128, 128));
} else {
ImGui::Text("Not loaded");
}
if (ImGui::Button("Load PNG image")) {
fileSelector.AddExtensions("png");
fileSelector.SetFileSelectedCallback(std::bind(&TextureEditor::FileSelected, this, std::placeholders::_1));
fileSelector.SetVisible(true);
}
ImGui::Checkbox("SRGB", &texture->srgb);
}
ImGui::End();
if (fileSelector.IsVisible())
fileSelector.Show();
}
const TextureAsset* TextureEditor::GetTexture() const {
return texture;
}
void TextureEditor::SetTexture(TextureAsset* texture) {
this->texture = texture;
strcpy(name, texture->name.c_str());
}
bool TextureEditor::IsVisible() const {
return visible;
}
void TextureEditor::SetVisible(bool visible) {
this->visible = visible;
}
void TextureEditor::FileSelected(const std::string& file) {
std::string destination = Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png";
FileSystem::Copy(file.c_str(), destination.c_str());
texture->GetTexture()->Load(file.c_str(), texture->srgb);
}
<commit_msg>Fix copying texture<commit_after>#include "TextureEditor.hpp"
#include <Engine/Texture/TextureAsset.hpp>
#include <Video/Texture/Texture2D.hpp>
#include "../FileSelector.hpp"
#include <functional>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <imgui.h>
using namespace GUI;
TextureEditor::TextureEditor() {
name[0] = '\0';
}
void TextureEditor::Show() {
if (ImGui::Begin(("Texture: " + texture->name + "###" + std::to_string(reinterpret_cast<uintptr_t>(texture))).c_str(), &visible, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders)) {
ImGui::InputText("Name", name, 128);
texture->name = name;
if (texture->GetTexture()->IsLoaded()) {
ImGui::Image((void*) texture->GetTexture()->GetTextureID(), ImVec2(128, 128));
} else {
ImGui::Text("Not loaded");
}
if (ImGui::Button("Load PNG image")) {
fileSelector.AddExtensions("png");
fileSelector.SetFileSelectedCallback(std::bind(&TextureEditor::FileSelected, this, std::placeholders::_1));
fileSelector.SetVisible(true);
}
ImGui::Checkbox("SRGB", &texture->srgb);
}
ImGui::End();
if (fileSelector.IsVisible())
fileSelector.Show();
}
const TextureAsset* TextureEditor::GetTexture() const {
return texture;
}
void TextureEditor::SetTexture(TextureAsset* texture) {
this->texture = texture;
strcpy(name, texture->name.c_str());
}
bool TextureEditor::IsVisible() const {
return visible;
}
void TextureEditor::SetVisible(bool visible) {
this->visible = visible;
}
void TextureEditor::FileSelected(const std::string& file) {
std::string destination = Hymn().GetPath() + "/" + texture->path + texture->name + ".png";
FileSystem::Copy(file.c_str(), destination.c_str());
texture->GetTexture()->Load(file.c_str(), texture->srgb);
}
<|endoftext|> |
<commit_before>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Jory Stone <jcsston @ toughguy.net>
*/
#include <cassert>
#include "ebml/EbmlUnicodeString.h"
#include "lib/utf8-cpp/source/utf8/checked.h"
START_LIBEBML_NAMESPACE
// ===================== UTFstring class ===================
UTFstring::UTFstring()
:_Length(0)
,_Data(NULL)
{}
UTFstring::UTFstring(const wchar_t * _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf;
}
UTFstring::UTFstring(std::wstring const &_aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring::~UTFstring()
{
delete [] _Data;
}
UTFstring::UTFstring(const UTFstring & _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring & UTFstring::operator=(const UTFstring & _aBuf)
{
*this = _aBuf.c_str();
return *this;
}
UTFstring::operator const wchar_t*() const {return _Data;}
UTFstring & UTFstring::operator=(const wchar_t * _aBuf)
{
delete [] _Data;
if (_aBuf == NULL) {
_Data = new wchar_t[1];
_Data[0] = 0;
UpdateFromUCS2();
return *this;
}
size_t aLen;
for (aLen=0; _aBuf[aLen] != 0; aLen++);
_Length = aLen;
_Data = new wchar_t[_Length+1];
for (aLen=0; _aBuf[aLen] != 0; aLen++) {
_Data[aLen] = _aBuf[aLen];
}
_Data[aLen] = 0;
UpdateFromUCS2();
return *this;
}
UTFstring & UTFstring::operator=(wchar_t _aChar)
{
delete [] _Data;
_Data = new wchar_t[2];
_Length = 1;
_Data[0] = _aChar;
_Data[1] = 0;
UpdateFromUCS2();
return *this;
}
bool UTFstring::operator==(const UTFstring& _aStr) const
{
if ((_Data == NULL) && (_aStr._Data == NULL))
return true;
if ((_Data == NULL) || (_aStr._Data == NULL))
return false;
return wcscmp_internal(_Data, _aStr._Data);
}
void UTFstring::SetUTF8(const std::string & _aStr)
{
UTF8string = _aStr;
UpdateFromUTF8();
}
/*!
\see RFC 2279
*/
void UTFstring::UpdateFromUTF8()
{
// Only convert up to the first \0 character if present.
std::string::iterator End = UTF8string.end(), Current = UTF8string.begin();
while ((Current != End) && *Current)
++Current;
std::wstring Temp;
try {
::utf8::utf8to16(UTF8string.begin(), Current, std::back_inserter(Temp));
} catch (::utf8::invalid_code_point &) {
} catch (::utf8::invalid_utf8 &) {
}
delete [] _Data;
_Length = Temp.length();
_Data = new wchar_t[_Length + 1];
std::memcpy(_Data, Temp.c_str(), sizeof(wchar_t) * (_Length + 1));
}
void UTFstring::UpdateFromUCS2()
{
UTF8string.clear();
if (!_Data)
return;
// Only convert up to the first \0 character if present.
size_t Current = 0;
while ((Current < _Length) && _Data[Current])
++Current;
try {
::utf8::utf16to8(_Data, _Data + Current, std::back_inserter(UTF8string));
} catch (::utf8::invalid_code_point &) {
} catch (::utf8::invalid_utf16 &) {
}
}
bool UTFstring::wcscmp_internal(const wchar_t *str1, const wchar_t *str2)
{
size_t Index=0;
while (str1[Index] == str2[Index] && str1[Index] != 0) {
Index++;
}
return (str1[Index] == str2[Index]);
}
// ===================== EbmlUnicodeString class ===================
EbmlUnicodeString::EbmlUnicodeString()
:EbmlElement(0, false)
{
SetDefaultSize(0);
}
EbmlUnicodeString::EbmlUnicodeString(const UTFstring & aDefaultValue)
:EbmlElement(0, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultSize(0);
SetDefaultIsSet();
}
EbmlUnicodeString::EbmlUnicodeString(const EbmlUnicodeString & ElementToClone)
:EbmlElement(ElementToClone)
,Value(ElementToClone.Value)
,DefaultValue(ElementToClone.DefaultValue)
{
}
void EbmlUnicodeString::SetDefaultValue(UTFstring & aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
const UTFstring & EbmlUnicodeString::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
/*!
\note limited to UCS-2
\todo handle exception on errors
*/
filepos_t EbmlUnicodeString::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
uint32 Result = Value.GetUTF8().length();
if (Result != 0) {
output.writeFully(Value.GetUTF8().c_str(), Result);
}
if (Result < GetDefaultSize()) {
// pad the rest with 0
binary *Pad = new (std::nothrow) binary[GetDefaultSize() - Result];
if (Pad != NULL) {
memset(Pad, 0x00, GetDefaultSize() - Result);
output.writeFully(Pad, GetDefaultSize() - Result);
Result = GetDefaultSize();
delete [] Pad;
}
}
return Result;
}
EbmlUnicodeString::operator const UTFstring &() const {return Value;}
EbmlUnicodeString & EbmlUnicodeString::operator=(const UTFstring & NewString)
{
Value = NewString;
SetValueIsSet();
return *this;
}
EbmlUnicodeString &EbmlUnicodeString::SetValue(UTFstring const &NewValue) {
return *this = NewValue;
}
EbmlUnicodeString &EbmlUnicodeString::SetValueUTF8(std::string const &NewValue) {
UTFstring NewValueUTFstring;
NewValueUTFstring.SetUTF8(NewValue);
return *this = NewValueUTFstring;
}
UTFstring EbmlUnicodeString::GetValue() const {
return Value;
}
std::string EbmlUnicodeString::GetValueUTF8() const {
return Value.GetUTF8();
}
/*!
\note limited to UCS-2
*/
uint64 EbmlUnicodeString::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
SetSize_(Value.GetUTF8().length());
if (GetSize() < GetDefaultSize())
SetSize_(GetDefaultSize());
return GetSize();
}
/*!
\note limited to UCS-2
*/
filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully != SCOPE_NO_DATA) {
if (GetSize() == 0) {
Value = UTFstring::value_type(0);
SetValueIsSet();
} else {
char *Buffer = new (std::nothrow) char[GetSize()+1];
if (Buffer == NULL) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
} else {
input.readFully(Buffer, GetSize());
if (Buffer[GetSize()-1] != 0) {
Buffer[GetSize()] = 0;
}
Value.SetUTF8(Buffer); // implicit conversion to std::string
delete [] Buffer;
SetValueIsSet();
}
}
}
return GetSize();
}
END_LIBEBML_NAMESPACE
<commit_msg>EbmlUnicodeString: use UCS4 where wchar_t is four bytes long<commit_after>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Jory Stone <jcsston @ toughguy.net>
*/
#include <cassert>
#include "ebml/EbmlUnicodeString.h"
#include "lib/utf8-cpp/source/utf8/checked.h"
START_LIBEBML_NAMESPACE
// ===================== UTFstring class ===================
UTFstring::UTFstring()
:_Length(0)
,_Data(NULL)
{}
UTFstring::UTFstring(const wchar_t * _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf;
}
UTFstring::UTFstring(std::wstring const &_aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring::~UTFstring()
{
delete [] _Data;
}
UTFstring::UTFstring(const UTFstring & _aBuf)
:_Length(0)
,_Data(NULL)
{
*this = _aBuf.c_str();
}
UTFstring & UTFstring::operator=(const UTFstring & _aBuf)
{
*this = _aBuf.c_str();
return *this;
}
UTFstring::operator const wchar_t*() const {return _Data;}
UTFstring & UTFstring::operator=(const wchar_t * _aBuf)
{
delete [] _Data;
if (_aBuf == NULL) {
_Data = new wchar_t[1];
_Data[0] = 0;
UpdateFromUCS2();
return *this;
}
size_t aLen;
for (aLen=0; _aBuf[aLen] != 0; aLen++);
_Length = aLen;
_Data = new wchar_t[_Length+1];
for (aLen=0; _aBuf[aLen] != 0; aLen++) {
_Data[aLen] = _aBuf[aLen];
}
_Data[aLen] = 0;
UpdateFromUCS2();
return *this;
}
UTFstring & UTFstring::operator=(wchar_t _aChar)
{
delete [] _Data;
_Data = new wchar_t[2];
_Length = 1;
_Data[0] = _aChar;
_Data[1] = 0;
UpdateFromUCS2();
return *this;
}
bool UTFstring::operator==(const UTFstring& _aStr) const
{
if ((_Data == NULL) && (_aStr._Data == NULL))
return true;
if ((_Data == NULL) || (_aStr._Data == NULL))
return false;
return wcscmp_internal(_Data, _aStr._Data);
}
void UTFstring::SetUTF8(const std::string & _aStr)
{
UTF8string = _aStr;
UpdateFromUTF8();
}
/*!
\see RFC 2279
*/
void UTFstring::UpdateFromUTF8()
{
// Only convert up to the first \0 character if present.
std::string::iterator End = UTF8string.end(), Current = UTF8string.begin();
while ((Current != End) && *Current)
++Current;
std::wstring Temp;
try {
// Even though the function names hint at UCS2, the internal
// representation must actually be compatible with the C++
// library's implementation. Implementations with sizeof(wchar_t)
// == 4 are using UCS4.
if (sizeof(wchar_t) == 2)
::utf8::utf8to16(UTF8string.begin(), Current, std::back_inserter(Temp));
else
::utf8::utf8to32(UTF8string.begin(), Current, std::back_inserter(Temp));
} catch (::utf8::invalid_code_point &) {
} catch (::utf8::invalid_utf8 &) {
}
delete [] _Data;
_Length = Temp.length();
_Data = new wchar_t[_Length + 1];
std::memcpy(_Data, Temp.c_str(), sizeof(wchar_t) * (_Length + 1));
}
void UTFstring::UpdateFromUCS2()
{
UTF8string.clear();
if (!_Data)
return;
// Only convert up to the first \0 character if present.
size_t Current = 0;
while ((Current < _Length) && _Data[Current])
++Current;
try {
// Even though the function is called UCS2, the internal
// representation must actually be compatible with the C++
// library's implementation. Implementations with sizeof(wchar_t)
// == 4 are using UCS4.
if (sizeof(wchar_t) == 2)
::utf8::utf16to8(_Data, _Data + Current, std::back_inserter(UTF8string));
else
::utf8::utf32to8(_Data, _Data + Current, std::back_inserter(UTF8string));
} catch (::utf8::invalid_code_point &) {
} catch (::utf8::invalid_utf16 &) {
}
}
bool UTFstring::wcscmp_internal(const wchar_t *str1, const wchar_t *str2)
{
size_t Index=0;
while (str1[Index] == str2[Index] && str1[Index] != 0) {
Index++;
}
return (str1[Index] == str2[Index]);
}
// ===================== EbmlUnicodeString class ===================
EbmlUnicodeString::EbmlUnicodeString()
:EbmlElement(0, false)
{
SetDefaultSize(0);
}
EbmlUnicodeString::EbmlUnicodeString(const UTFstring & aDefaultValue)
:EbmlElement(0, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultSize(0);
SetDefaultIsSet();
}
EbmlUnicodeString::EbmlUnicodeString(const EbmlUnicodeString & ElementToClone)
:EbmlElement(ElementToClone)
,Value(ElementToClone.Value)
,DefaultValue(ElementToClone.DefaultValue)
{
}
void EbmlUnicodeString::SetDefaultValue(UTFstring & aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
const UTFstring & EbmlUnicodeString::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
/*!
\note limited to UCS-2
\todo handle exception on errors
*/
filepos_t EbmlUnicodeString::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
uint32 Result = Value.GetUTF8().length();
if (Result != 0) {
output.writeFully(Value.GetUTF8().c_str(), Result);
}
if (Result < GetDefaultSize()) {
// pad the rest with 0
binary *Pad = new (std::nothrow) binary[GetDefaultSize() - Result];
if (Pad != NULL) {
memset(Pad, 0x00, GetDefaultSize() - Result);
output.writeFully(Pad, GetDefaultSize() - Result);
Result = GetDefaultSize();
delete [] Pad;
}
}
return Result;
}
EbmlUnicodeString::operator const UTFstring &() const {return Value;}
EbmlUnicodeString & EbmlUnicodeString::operator=(const UTFstring & NewString)
{
Value = NewString;
SetValueIsSet();
return *this;
}
EbmlUnicodeString &EbmlUnicodeString::SetValue(UTFstring const &NewValue) {
return *this = NewValue;
}
EbmlUnicodeString &EbmlUnicodeString::SetValueUTF8(std::string const &NewValue) {
UTFstring NewValueUTFstring;
NewValueUTFstring.SetUTF8(NewValue);
return *this = NewValueUTFstring;
}
UTFstring EbmlUnicodeString::GetValue() const {
return Value;
}
std::string EbmlUnicodeString::GetValueUTF8() const {
return Value.GetUTF8();
}
/*!
\note limited to UCS-2
*/
uint64 EbmlUnicodeString::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
SetSize_(Value.GetUTF8().length());
if (GetSize() < GetDefaultSize())
SetSize_(GetDefaultSize());
return GetSize();
}
/*!
\note limited to UCS-2
*/
filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully != SCOPE_NO_DATA) {
if (GetSize() == 0) {
Value = UTFstring::value_type(0);
SetValueIsSet();
} else {
char *Buffer = new (std::nothrow) char[GetSize()+1];
if (Buffer == NULL) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
} else {
input.readFully(Buffer, GetSize());
if (Buffer[GetSize()-1] != 0) {
Buffer[GetSize()] = 0;
}
Value.SetUTF8(Buffer); // implicit conversion to std::string
delete [] Buffer;
SetValueIsSet();
}
}
}
return GetSize();
}
END_LIBEBML_NAMESPACE
<|endoftext|> |
<commit_before>/* $Id: Result.C,v 1.16 1999-11-19 23:02:53 wilson Exp $ */
/* File sections:
* Service: constructors, destructors
* Solution: functions directly related to the solution of a (sub)problem
* Utility: advanced member access such as searching and counting
* List: maintenance of lists or arrays of objects
*/
#include "Result.h"
#include "Output_def.h"
#include "Input/CoolingTime.h"
#include "Input/Mixture.h"
#include "Chains/Chain.h"
#include "Chains/Node.h"
#include "Calc/topScheduleT.h"
/****************************
********* Service **********
***************************/
int Result::nResults = 0;
FILE* Result::binDump = NULL;
const int Result::delimiter = -1;
double Result::actMult = 1;
double Result::metricMult = 1;
Result::Result(int setKza, Result* nxtPtr)
{
int resNum;
kza = setKza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = 0;
}
next = nxtPtr;
}
Result::Result(const Result& r)
{
int resNum;
kza = r.kza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = r.N[resNum];
}
next = NULL;
}
Result::Result(int setKza,float* floatN)
{
int resNum;
kza = setKza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = floatN[resNum];
}
next = NULL;
}
Result& Result::operator=(const Result& r)
{
if (this == &r)
return *this;
int resNum;
kza = r.kza;
delete N;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = r.N[resNum];
}
return *this;
}
/*******************************
*********** Utility ***********
******************************/
Result* Result::find(int srchKza)
{
Result *oldPtr, *ptr = this;
while (ptr->next != NULL)
{
oldPtr = ptr;
ptr = ptr->next;
if (ptr->kza == srchKza)
return ptr;
else if (ptr->kza > srchKza)
{
oldPtr->next = new Result(srchKza,ptr);
return oldPtr->next;
}
}
ptr->next = new Result(srchKza);
return ptr->next;
}
/****************************
********** Tally ***********
***************************/
void Result::tallySoln(Chain *chain, topScheduleT* schedT)
{
Result *ptr, *head = this;
int rank, setKza;
/* get the rank of the first node to be tallied */
rank = chain->getSetRank();
/* get the first kza to be set */
setKza = chain->getKza(rank);
/* if we are not done (finish condition: kza == 0) */
while (setKza > 0)
{
/* tally result */
double *Nlist = schedT->results(rank);
head->find(setKza)->tally(Nlist);
/* this is allocated in topScheduleT::results() */
delete Nlist;
/* get next isotope */
setKza = chain->getKza(++rank);
}
}
void Result::tally(double* Nlist, double scale)
{
int resNum;
for (resNum=0;resNum<nResults;resNum++)
{
N[resNum] += Nlist[resNum]*scale;
/* used during debugging
if ( isnan(N[resNum]) || isinf(N[resNum]))
error(2000,"A negative solution has been encountered, suggesting a possible round off error. Please notify the code author."); */
}
}
/*****************************
********* PostProc **********
****************************/
void Result::postProcTarget(Result* outputList, Mixture *mixPtr)
{
Component *compPtr=NULL;
double density;
int compNum;
Result *root = this;
/* for each initial isotope that generates this target */
while (root->next != NULL)
{
root = root->next;
/* get the first component number and density for this root */
compPtr = mixPtr->getComp(root->kza,density,NULL);
/* if we found the component */
while (compPtr)
{
compNum = mixPtr->getCompNum(compPtr);
/* update this component */
outputList[compNum].find(root->kza)->tally(root->N,density);
/* get the next component */
compPtr = mixPtr->getComp(root->kza,density,compPtr);
}
}
/* we are done with this data */
clear();
}
void Result::postProcList(Result* outputList, Mixture *mixPtr, int rootKza)
{
Component *compPtr=NULL;
double density;
int compNum;
/* get the first component number and density for this root
* isotope */
compPtr = mixPtr->getComp(rootKza,density,NULL);
/* if we found the component */
while (compPtr)
{
compNum = mixPtr->getCompNum(compPtr);
/* update this component */
postProc(outputList[compNum],density);
/* get the next component */
compPtr = mixPtr->getComp(rootKza,density,compPtr);
}
/* we are done with this data now */
clear();
}
void Result::postProc(Result& outputList, double density)
{
Result *ptr = this;
/* for each result isotope */
while (ptr->next != NULL)
{
ptr = ptr->next;
/* tally the output list */
outputList.find(ptr->kza)->tally(ptr->N,density);
}
}
void Result::write(int response, int targetKza, CoolingTime *coolList,
double*& total, double volume_mass)
{
int resNum;
Result* ptr = this;
double multiplier=1.0;
Node dataAccess;
char isoSym[15];
int mode = NuclearData::getMode();
/* initialize the total array */
delete total;
total = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
total[resNum] = 0;
/* write a standard header for this table */
coolList->writeHeader();
if (mode == MODE_REVERSE)
{
/* query the data library through a dummy Node object
* to get the nuclear data for the multiplier */
switch(response)
{
case OUTFMT_ACT:
multiplier = dataAccess.getLambda(targetKza)*actMult;
break;
case OUTFMT_HEAT:
multiplier = dataAccess.getHeat(targetKza) * EV2J;
break;
case OUTFMT_ALPHA:
multiplier = dataAccess.getAlpha(targetKza) * EV2J;
break;
case OUTFMT_BETA:
multiplier = dataAccess.getBeta(targetKza) * EV2J;
break;
case OUTFMT_GAMMA:
multiplier = dataAccess.getGamma(targetKza) * EV2J;
break;
case OUTFMT_WDR:
multiplier = dataAccess.getWDR(targetKza)*actMult;
break;
}
multiplier *= metricMult/volume_mass;
}
/* for each isotope in the table */
while (ptr->next != NULL)
{
ptr = ptr->next;
if (mode == MODE_FORWARD)
{
/* query the data library through a dummy Node object
* to get the nuclear data for the multiplier */
switch(response)
{
case OUTFMT_ACT:
multiplier = dataAccess.getLambda(ptr->kza)*actMult;
break;
case OUTFMT_HEAT:
multiplier = dataAccess.getHeat(ptr->kza) * EV2J;
break;
case OUTFMT_ALPHA:
multiplier = dataAccess.getAlpha(ptr->kza) * EV2J;
break;
case OUTFMT_BETA:
multiplier = dataAccess.getBeta(ptr->kza) * EV2J;
break;
case OUTFMT_GAMMA:
multiplier = dataAccess.getGamma(ptr->kza) * EV2J;
break;
case OUTFMT_WDR:
multiplier = dataAccess.getWDR(ptr->kza)*actMult;
break;
}
multiplier *= metricMult/volume_mass;
}
/* if the multipier is 0 (e.g. stable isotope for activity based
responses) skip this isotope */
if (multiplier == 0)
continue;
/* write the formatted output for this isotope */
cout << isoName(ptr->kza,isoSym) << "\t";
for (resNum=0;resNum<nResults;resNum++)
{
sprintf(isoSym,"%-11.4e ",ptr->N[resNum]*multiplier);
cout << isoSym;
/* increment the total */
total[resNum] += ptr->N[resNum]*multiplier;
}
cout << endl;
}
/* write a separator for the table */
coolList->writeSeparator();
/* write the formatted output for the total response */
cout << "total\t";
for (resNum=0;resNum<nResults;resNum++)
{
sprintf(isoSym,"%-11.4e ",total[resNum]);
cout << isoSym;
}
cout << endl;
}
/*****************************
********* PostProc **********
****************************/
void Result::initBinDump(char* fname)
{
binDump = fopen(fname,"wb+");
if (!binDump)
error(240,"Unable to open dump file %s",fname);
};
void Result::dumpHeader()
{
fwrite(&nResults,SINT,1,binDump);
}
void Result::xCheck()
{
if (binDump == NULL)
{
warning(440,"ALARA now requires a binary dump file. Openning the default file 'alara.dmp'");
binDump = fopen("alara.dmp","wb+");
if (!binDump)
error(441,"Unable to open dump file alara.dmp");
}
}
void Result::resetBinDump()
{
fflush(binDump);
fseek(binDump,0L,SEEK_SET);
fread(&nResults,SINT,1,binDump);
verbose(1,"Reset binary dump with %d results per isotope.",nResults);
}
void Result::writeDump()
{
Result *ptr = this;
static float *floatN = new float[nResults];
int resNum;
while (ptr->next != NULL)
{
ptr = ptr->next;
fwrite(&(ptr->kza),SINT,1,binDump);
for (resNum=0;resNum<nResults;resNum++)
floatN[resNum] = ptr->N[resNum];
fwrite(floatN,SFLOAT,nResults,binDump);
}
fwrite(&delimiter,SINT,1,binDump);
clear();
}
void Result::readDump()
{
Result *ptr = this;
int readKza,resNum;
static float *floatN = new float[nResults];
fread(&readKza,SINT,1,binDump);
while (readKza != delimiter)
{
fread(floatN,SFLOAT,nResults,binDump);
ptr->next = new Result(readKza,floatN);
ptr = ptr->next;
fread(&readKza,SINT,1,binDump);
}
}
void Result::setNorm(double passedActMult, int normType)
{
actMult = passedActMult;
switch (normType) {
case OUTNORM_M3:
metricMult = CM3_M3;
break;
case OUTNORM_KG:
metricMult = G_KG;
break;
default:
metricMult = 1;
}
}
<commit_msg>Fixed growing multiplier bug. Fixed metricMult to divide instead of multiply.<commit_after>/* $Id: Result.C,v 1.17 1999-12-21 21:42:47 wilson Exp $ */
/* File sections:
* Service: constructors, destructors
* Solution: functions directly related to the solution of a (sub)problem
* Utility: advanced member access such as searching and counting
* List: maintenance of lists or arrays of objects
*/
#include "Result.h"
#include "Output_def.h"
#include "Input/CoolingTime.h"
#include "Input/Mixture.h"
#include "Chains/Chain.h"
#include "Chains/Node.h"
#include "Calc/topScheduleT.h"
/****************************
********* Service **********
***************************/
int Result::nResults = 0;
FILE* Result::binDump = NULL;
const int Result::delimiter = -1;
double Result::actMult = 1;
double Result::metricMult = 1;
Result::Result(int setKza, Result* nxtPtr)
{
int resNum;
kza = setKza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = 0;
}
next = nxtPtr;
}
Result::Result(const Result& r)
{
int resNum;
kza = r.kza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = r.N[resNum];
}
next = NULL;
}
Result::Result(int setKza,float* floatN)
{
int resNum;
kza = setKza;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = floatN[resNum];
}
next = NULL;
}
Result& Result::operator=(const Result& r)
{
if (this == &r)
return *this;
int resNum;
kza = r.kza;
delete N;
N = NULL;
if (nResults>0)
{
N = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
N[resNum] = r.N[resNum];
}
return *this;
}
/*******************************
*********** Utility ***********
******************************/
Result* Result::find(int srchKza)
{
Result *oldPtr, *ptr = this;
while (ptr->next != NULL)
{
oldPtr = ptr;
ptr = ptr->next;
if (ptr->kza == srchKza)
return ptr;
else if (ptr->kza > srchKza)
{
oldPtr->next = new Result(srchKza,ptr);
return oldPtr->next;
}
}
ptr->next = new Result(srchKza);
return ptr->next;
}
/****************************
********** Tally ***********
***************************/
void Result::tallySoln(Chain *chain, topScheduleT* schedT)
{
Result *ptr, *head = this;
int rank, setKza;
/* get the rank of the first node to be tallied */
rank = chain->getSetRank();
/* get the first kza to be set */
setKza = chain->getKza(rank);
/* if we are not done (finish condition: kza == 0) */
while (setKza > 0)
{
/* tally result */
double *Nlist = schedT->results(rank);
head->find(setKza)->tally(Nlist);
/* this is allocated in topScheduleT::results() */
delete Nlist;
/* get next isotope */
setKza = chain->getKza(++rank);
}
}
void Result::tally(double* Nlist, double scale)
{
int resNum;
for (resNum=0;resNum<nResults;resNum++)
{
N[resNum] += Nlist[resNum]*scale;
/* used during debugging
if ( isnan(N[resNum]) || isinf(N[resNum]))
error(2000,"A negative solution has been encountered, suggesting a possible round off error. Please notify the code author."); */
}
}
/*****************************
********* PostProc **********
****************************/
void Result::postProcTarget(Result* outputList, Mixture *mixPtr)
{
Component *compPtr=NULL;
double density;
int compNum;
Result *root = this;
/* for each initial isotope that generates this target */
while (root->next != NULL)
{
root = root->next;
/* get the first component number and density for this root */
compPtr = mixPtr->getComp(root->kza,density,NULL);
/* if we found the component */
while (compPtr)
{
compNum = mixPtr->getCompNum(compPtr);
/* update this component */
outputList[compNum].find(root->kza)->tally(root->N,density);
/* get the next component */
compPtr = mixPtr->getComp(root->kza,density,compPtr);
}
}
/* we are done with this data */
clear();
}
void Result::postProcList(Result* outputList, Mixture *mixPtr, int rootKza)
{
Component *compPtr=NULL;
double density;
int compNum;
/* get the first component number and density for this root
* isotope */
compPtr = mixPtr->getComp(rootKza,density,NULL);
/* if we found the component */
while (compPtr)
{
compNum = mixPtr->getCompNum(compPtr);
/* update this component */
postProc(outputList[compNum],density);
/* get the next component */
compPtr = mixPtr->getComp(rootKza,density,compPtr);
}
/* we are done with this data now */
clear();
}
void Result::postProc(Result& outputList, double density)
{
Result *ptr = this;
/* for each result isotope */
while (ptr->next != NULL)
{
ptr = ptr->next;
/* tally the output list */
outputList.find(ptr->kza)->tally(ptr->N,density);
}
}
void Result::write(int response, int targetKza, CoolingTime *coolList,
double*& total, double volume_mass)
{
int resNum;
Result* ptr = this;
double multiplier=1.0;
Node dataAccess;
char isoSym[15];
int mode = NuclearData::getMode();
/* initialize the total array */
delete total;
total = new double[nResults];
for (resNum=0;resNum<nResults;resNum++)
total[resNum] = 0;
/* write a standard header for this table */
coolList->writeHeader();
if (mode == MODE_REVERSE)
{
/* query the data library through a dummy Node object
* to get the nuclear data for the multiplier */
switch(response)
{
case OUTFMT_ACT:
multiplier = dataAccess.getLambda(targetKza)*actMult;
break;
case OUTFMT_HEAT:
multiplier = dataAccess.getHeat(targetKza) * EV2J;
break;
case OUTFMT_ALPHA:
multiplier = dataAccess.getAlpha(targetKza) * EV2J;
break;
case OUTFMT_BETA:
multiplier = dataAccess.getBeta(targetKza) * EV2J;
break;
case OUTFMT_GAMMA:
multiplier = dataAccess.getGamma(targetKza) * EV2J;
break;
case OUTFMT_WDR:
multiplier = dataAccess.getWDR(targetKza)*actMult;
break;
default:
multiplier = 1.0;
}
multiplier *= metricMult/volume_mass;
}
/* for each isotope in the table */
while (ptr->next != NULL)
{
ptr = ptr->next;
if (mode == MODE_FORWARD)
{
/* query the data library through a dummy Node object
* to get the nuclear data for the multiplier */
switch(response)
{
case OUTFMT_ACT:
multiplier = dataAccess.getLambda(ptr->kza)*actMult;
break;
case OUTFMT_HEAT:
multiplier = dataAccess.getHeat(ptr->kza) * EV2J;
break;
case OUTFMT_ALPHA:
multiplier = dataAccess.getAlpha(ptr->kza) * EV2J;
break;
case OUTFMT_BETA:
multiplier = dataAccess.getBeta(ptr->kza) * EV2J;
break;
case OUTFMT_GAMMA:
multiplier = dataAccess.getGamma(ptr->kza) * EV2J;
break;
case OUTFMT_WDR:
multiplier = dataAccess.getWDR(ptr->kza)*actMult;
break;
default:
multiplier = 1.0;
}
multiplier *= metricMult/volume_mass;
}
/* if the multipier is 0 (e.g. stable isotope for activity based
responses) skip this isotope */
if (multiplier == 0)
continue;
/* write the formatted output for this isotope */
cout << isoName(ptr->kza,isoSym) << "\t";
for (resNum=0;resNum<nResults;resNum++)
{
sprintf(isoSym,"%-11.4e ",ptr->N[resNum]*multiplier);
cout << isoSym;
/* increment the total */
total[resNum] += ptr->N[resNum]*multiplier;
}
cout << endl;
}
/* write a separator for the table */
coolList->writeSeparator();
/* write the formatted output for the total response */
cout << "total\t";
for (resNum=0;resNum<nResults;resNum++)
{
sprintf(isoSym,"%-11.4e ",total[resNum]);
cout << isoSym;
}
cout << endl;
}
/*****************************
********* PostProc **********
****************************/
void Result::initBinDump(char* fname)
{
binDump = fopen(fname,"wb+");
if (!binDump)
error(240,"Unable to open dump file %s",fname);
};
void Result::dumpHeader()
{
fwrite(&nResults,SINT,1,binDump);
}
void Result::xCheck()
{
if (binDump == NULL)
{
warning(440,"ALARA now requires a binary dump file. Openning the default file 'alara.dmp'");
binDump = fopen("alara.dmp","wb+");
if (!binDump)
error(441,"Unable to open dump file alara.dmp");
}
}
void Result::resetBinDump()
{
fflush(binDump);
fseek(binDump,0L,SEEK_SET);
fread(&nResults,SINT,1,binDump);
verbose(1,"Reset binary dump with %d results per isotope.",nResults);
}
void Result::writeDump()
{
Result *ptr = this;
static float *floatN = new float[nResults];
int resNum;
while (ptr->next != NULL)
{
ptr = ptr->next;
fwrite(&(ptr->kza),SINT,1,binDump);
for (resNum=0;resNum<nResults;resNum++)
floatN[resNum] = ptr->N[resNum];
fwrite(floatN,SFLOAT,nResults,binDump);
}
fwrite(&delimiter,SINT,1,binDump);
clear();
}
void Result::readDump()
{
Result *ptr = this;
int readKza,resNum;
static float *floatN = new float[nResults];
fread(&readKza,SINT,1,binDump);
while (readKza != delimiter)
{
fread(floatN,SFLOAT,nResults,binDump);
ptr->next = new Result(readKza,floatN);
ptr = ptr->next;
fread(&readKza,SINT,1,binDump);
}
}
void Result::setNorm(double passedActMult, int normType)
{
actMult = passedActMult;
switch (normType) {
case OUTNORM_M3:
metricMult = 1.0/CM3_M3;
break;
case OUTNORM_KG:
metricMult = 1.0/G_KG;
break;
default:
metricMult = 1;
}
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAffineDataInteractor3D.h"
#include "mitkDispatcher.h"
#include "mitkInteractionConst.h" // TODO: refactor file
#include "mitkInteractionPositionEvent.h"
#include "mitkInternalEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkRenderingManager.h"
#include "mitkSurface.h"
#include <mitkPointOperation.h>
#include <vtkDataArray.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
mitk::AffineDataInteractor3D::AffineDataInteractor3D()
{
m_OriginalGeometry = Geometry3D::New();
// Initialize vector arithmetic
m_ObjectNormal[0] = 0.0;
m_ObjectNormal[1] = 0.0;
m_ObjectNormal[2] = 1.0;
}
mitk::AffineDataInteractor3D::~AffineDataInteractor3D()
{
}
void mitk::AffineDataInteractor3D::ConnectActionsAndFunctions()
{
CONNECT_FUNCTION("checkOverObject",CheckOverObject);
CONNECT_FUNCTION("selectObject",SelectObject);
CONNECT_FUNCTION("deselectObject",DeselectObject);
CONNECT_FUNCTION("initTranslate",InitTranslate);
CONNECT_FUNCTION("initRotate",InitRotate);
//CONNECT_FUNCTION("translateObject",TranslateObject);
//CONNECT_FUNCTION("rotateObject",RotateObject);
//CONNECT_FUNCTION("endTranslate",EndTranslate);
//CONNECT_FUNCTION("endRotate",EndRotate);
}
/*
* Check whether the DataNode contains a pointset, if not create one and add it.
*/
void mitk::AffineDataInteractor3D::DataNodeChanged()
{
//if (GetDataNode().IsNotNull())
//{
// // find proper place for this command!
// // maybe when DN is created ?
// GetDataNode()->SetBoolProperty("show contour", true);
// PointSet* points = dynamic_cast<PointSet*>(GetDataNode()->GetData());
// if (points == NULL)
// {
// m_PointSet = PointSet::New();
// GetDataNode()->SetData(m_PointSet);
// }
// else
// {
// m_PointSet = points;
// }
// // load config file parameter: maximal number of points
// mitk::PropertyList::Pointer properties = GetAttributes();
// std::string strNumber;
// if (properties->GetStringProperty("MaxPoints", strNumber))
// {
// m_MaxNumberOfPoints = atoi(strNumber.c_str());
// }
//}
}
bool mitk::AffineDataInteractor3D::CheckOverObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
//Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
//Re-enable VTK interactor (may have been disabled previously)
if ( renderWindowInteractor != NULL )
renderWindowInteractor->Enable();
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
if(interactionEvent->GetSender()->PickObject( m_CurrentPickedDisplayPoint, m_CurrentPickedPoint ) == this->GetDataNode().GetPointer())
{
//Object will be selected
InternalEvent::Pointer event = InternalEvent::New(NULL, this, "OverObject");
positionEvent->GetSender()->GetDispatcher()->QueueEvent(event.GetPointer());
}
return true;
}
bool mitk::AffineDataInteractor3D::SelectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 0.0, 0.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe dependend on distance from picked point
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), 0.0 );
return true;
}
bool mitk::AffineDataInteractor3D::DeselectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 1.0, 1.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe as inactive
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), -1.0 );
return true;
}
bool mitk::AffineDataInteractor3D::InitTranslate(StateMachineAction*, InteractionEvent* interactionEvent)
{
return true;
}
bool mitk::AffineDataInteractor3D::InitRotate(StateMachineAction*, InteractionEvent* interactionEvent)
{
return true;
}
bool mitk::AffineDataInteractor3D::ColorizeSurface(BaseRenderer::Pointer renderer, double scalar)
{
BaseData::Pointer data = this->GetDataNode()->GetData();
if(data.IsNull())
{
MITK_ERROR << "AffineInteractor3D: No data object present!";
return false;
}
// Get the timestep to also support 3D+t
int timeStep = 0;
if (renderer.IsNotNull())
timeStep = renderer->GetTimeStep(data);
// If data is an mitk::Surface, extract it
Surface* surface = dynamic_cast< Surface * >(data.GetPointer());
vtkPolyData* polyData = NULL;
if ( surface != NULL )
polyData = surface->GetVtkPolyData( timeStep );
if (polyData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No poly data present!";
return false;
}
vtkPointData *pointData = polyData->GetPointData();
if ( pointData == NULL )
{
MITK_ERROR << "AffineInteractor3D: No point data present!";
return false;
}
vtkDataArray *scalars = pointData->GetScalars();
if ( scalars == NULL )
{
MITK_ERROR << "AffineInteractor3D: No scalars for point data present!";
return false;
}
for ( unsigned int i = 0; i < pointData->GetNumberOfTuples(); ++i )
{
scalars->SetComponent( i, 0, scalar );
}
polyData->Modified();
pointData->Update();
return true;
}
<commit_msg>Some more events implemented, based on the old stuff but with new interaction concept style.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAffineDataInteractor3D.h"
#include "mitkDispatcher.h"
#include "mitkInteractionConst.h" // TODO: refactor file
#include "mitkInteractionPositionEvent.h"
#include "mitkInternalEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkRenderingManager.h"
#include "mitkSurface.h"
#include <mitkPointOperation.h>
#include <vtkDataArray.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
mitk::AffineDataInteractor3D::AffineDataInteractor3D()
{
m_OriginalGeometry = Geometry3D::New();
// Initialize vector arithmetic
m_ObjectNormal[0] = 0.0;
m_ObjectNormal[1] = 0.0;
m_ObjectNormal[2] = 1.0;
}
mitk::AffineDataInteractor3D::~AffineDataInteractor3D()
{
}
void mitk::AffineDataInteractor3D::ConnectActionsAndFunctions()
{
CONNECT_FUNCTION("checkOverObject",CheckOverObject);
CONNECT_FUNCTION("selectObject",SelectObject);
CONNECT_FUNCTION("deselectObject",DeselectObject);
CONNECT_FUNCTION("initTranslate",InitTranslate);
CONNECT_FUNCTION("initRotate",InitRotate);
//CONNECT_FUNCTION("translateObject",TranslateObject);
//CONNECT_FUNCTION("rotateObject",RotateObject);
//CONNECT_FUNCTION("endTranslate",EndTranslate);
//CONNECT_FUNCTION("endRotate",EndRotate);
}
/*
* Check whether the DataNode contains a pointset, if not create one and add it.
*/
void mitk::AffineDataInteractor3D::DataNodeChanged()
{
//if (GetDataNode().IsNotNull())
//{
// // find proper place for this command!
// // maybe when DN is created ?
// GetDataNode()->SetBoolProperty("show contour", true);
// PointSet* points = dynamic_cast<PointSet*>(GetDataNode()->GetData());
// if (points == NULL)
// {
// m_PointSet = PointSet::New();
// GetDataNode()->SetData(m_PointSet);
// }
// else
// {
// m_PointSet = points;
// }
// // load config file parameter: maximal number of points
// mitk::PropertyList::Pointer properties = GetAttributes();
// std::string strNumber;
// if (properties->GetStringProperty("MaxPoints", strNumber))
// {
// m_MaxNumberOfPoints = atoi(strNumber.c_str());
// }
//}
}
bool mitk::AffineDataInteractor3D::CheckOverObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
////Re-enable VTK interactor (may have been disabled previously)
//if ( renderWindowInteractor != NULL )
// renderWindowInteractor->Enable();
InteractionPositionEvent* positionEvent = dynamic_cast<InteractionPositionEvent*>(interactionEvent);
if(positionEvent == NULL)
return false;
m_CurrentPickedPoint = positionEvent->GetPositionInWorld();
m_CurrentPickedDisplayPoint = positionEvent->GetPointerPositionOnScreen();
if(interactionEvent->GetSender()->PickObject( m_CurrentPickedDisplayPoint, m_CurrentPickedPoint ) == this->GetDataNode().GetPointer())
{
//Object will be selected
InternalEvent::Pointer event = InternalEvent::New(NULL, this, "OverObject");
positionEvent->GetSender()->GetDispatcher()->QueueEvent(event.GetPointer());
}
return true;
}
bool mitk::AffineDataInteractor3D::SelectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 0.0, 0.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe dependend on distance from picked point
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), 0.0 );
return true;
}
bool mitk::AffineDataInteractor3D::DeselectObject(StateMachineAction*, InteractionEvent* interactionEvent)
{
DataNode::Pointer node = this->GetDataNode();
if (node.IsNull())
return false;
node->SetColor( 1.0, 1.0, 1.0 );
//TODO: Only 3D reinit
RenderingManager::GetInstance()->RequestUpdateAll();
// Colorize surface / wireframe as inactive
//TODO Check the return value
this->ColorizeSurface( interactionEvent->GetSender(), -1.0 );
return true;
}
bool mitk::AffineDataInteractor3D::InitTranslate(StateMachineAction*, InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
//// Disable VTK interactor until MITK interaction has been completed
// if ( renderWindowInteractor != NULL )
// renderWindowInteractor->Disable();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((this->GetSender()).IsNotNull())
timeStep = this->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::InitRotate(StateMachineAction*, InteractionEvent* interactionEvent)
{
////Is only a copy of the old AffineInteractor3D. Not sure if is still needed.
//// Disable VTK interactor until MITK interaction has been completed
// if ( renderWindowInteractor != NULL )
// renderWindowInteractor->Disable();
m_InitialPickedPoint = m_CurrentPickedPoint;
m_InitialPickedDisplayPoint = m_CurrentPickedDisplayPoint;
// Get the timestep to also support 3D+t
int timeStep = 0;
if ((this->GetSender()).IsNotNull())
timeStep = this->GetSender()->GetTimeStep(this->GetDataNode()->GetData());
// Make deep copy of current Geometry3D of the plane
this->GetDataNode()->GetData()->UpdateOutputInformation(); // make sure that the Geometry is up-to-date
m_OriginalGeometry = static_cast< Geometry3D * >(this->GetDataNode()->GetData()->GetGeometry( timeStep )->Clone().GetPointer() );
return true;
}
bool mitk::AffineDataInteractor3D::ColorizeSurface(BaseRenderer::Pointer renderer, double scalar)
{
BaseData::Pointer data = this->GetDataNode()->GetData();
if(data.IsNull())
{
MITK_ERROR << "AffineInteractor3D: No data object present!";
return false;
}
// Get the timestep to also support 3D+t
int timeStep = 0;
if (renderer.IsNotNull())
timeStep = renderer->GetTimeStep(data);
// If data is an mitk::Surface, extract it
Surface* surface = dynamic_cast< Surface * >(data.GetPointer());
vtkPolyData* polyData = NULL;
if ( surface != NULL )
polyData = surface->GetVtkPolyData( timeStep );
if (polyData == NULL)
{
MITK_ERROR << "AffineInteractor3D: No poly data present!";
return false;
}
vtkPointData *pointData = polyData->GetPointData();
if ( pointData == NULL )
{
MITK_ERROR << "AffineInteractor3D: No point data present!";
return false;
}
vtkDataArray *scalars = pointData->GetScalars();
if ( scalars == NULL )
{
MITK_ERROR << "AffineInteractor3D: No scalars for point data present!";
return false;
}
for ( unsigned int i = 0; i < pointData->GetNumberOfTuples(); ++i )
{
scalars->SetComponent( i, 0, scalar );
}
polyData->Modified();
pointData->Update();
return true;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-10-02 16:21:08 +0200 (Do, 02 Okt 2008) $
Version: $Revision: 13129 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPlanarFigureInteractor.h"
#include "mitkPointOperation.h"
#include "mitkPositionEvent.h"
#include "mitkPlanarFigure.h"
#include "mitkStatusBar.h"
#include "mitkDataTreeNode.h"
#include "mitkInteractionConst.h"
#include "mitkAction.h"
#include "mitkStateEvent.h"
#include "mitkOperationEvent.h"
#include "mitkUndoController.h"
#include "mitkStateMachineFactory.h"
#include "mitkStateTransitionOperation.h"
#include "mitkBaseRenderer.h"
#include "mitkRenderingManager.h"
//how precise must the user pick the point
//default value
mitk::PlanarFigureInteractor
::PlanarFigureInteractor(const char * type, DataTreeNode* dataTreeNode, int /* n */ )
: Interactor( type, dataTreeNode ),
m_Precision( 6.5 )
{
}
mitk::PlanarFigureInteractor::~PlanarFigureInteractor()
{
}
void mitk::PlanarFigureInteractor::SetPrecision( mitk::ScalarType precision )
{
m_Precision = precision;
}
// Overwritten since this class can handle it better!
float mitk::PlanarFigureInteractor
::CalculateJurisdiction(StateEvent const* stateEvent) const
{
float returnValue = 0.5;
// If it is a key event that can be handled in the current state,
// then return 0.5
mitk::DisplayPositionEvent const *disPosEvent =
dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
// Key event handling:
if (disPosEvent == NULL)
{
// Check if the current state has a transition waiting for that key event.
if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
{
return 0.5;
}
else
{
return 0.0;
}
}
//on MouseMove do nothing!
//if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
//{
// return 0.0;
//}
//if the event can be understood and if there is a transition waiting for that event
//if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
//{
// returnValue = 0.5;//it can be understood
//}
int timeStep = disPosEvent->GetSender()->GetTimeStep();
mitk::PlanarFigure *planarFigure = dynamic_cast<mitk::PlanarFigure *>(
m_DataTreeNode->GetData() );
if ( planarFigure != NULL )
{
// Give higher priority if this figure is currently selected
if ( planarFigure->GetSelectedControlPoint() >= 0 )
{
return 1.0;
}
// Get the Geometry2D of the window the user interacts with (for 2D point
// projection)
mitk::BaseRenderer *renderer = stateEvent->GetEvent()->GetSender();
const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D();
//// For reading on the points, Ids etc
//mitk::CurveModel::PointSetType *pointSet = curveModel->GetPointSet( timeStep );
//if ( pointSet == NULL )
//{
// return 0.0;
//}
//int visualizationMode = CurveModel::VISUALIZATION_MODE_PLANAR;
//if ( renderer != NULL )
//{
// m_DataTreeNode->GetIntProperty( "VisualizationMode", visualizationMode, renderer );
//}
//if ( visualizationMode == CurveModel::VISUALIZATION_MODE_PLANAR )
//{
// // Check if mouse is near the SELECTED point of the CurveModel (if != -1)
// if ( curveModel->GetSelectedPointId() != -1 )
// {
// Point3D selectedPoint;
// pointSet->GetPoint( curveModel->GetSelectedPointId(), &selectedPoint );
// float maxDistance = m_Precision * m_Precision;
// if ( maxDistance == 0.0 ) { maxDistance = 0.000001; }
// float distance = selectedPoint.SquaredEuclideanDistanceTo(
// disPosEvent->GetWorldPosition() );
// if ( distance < maxDistance )
// {
// returnValue = 1.0;
// }
// }
//}
//else if ( visualizationMode == CurveModel::VISUALIZATION_MODE_PROJECTION )
//{
// // Check if mouse is near the PROJECTION of any point of the CurveModel
// if ( curveModel->SearchPoint(
// disPosEvent->GetWorldPosition(), m_Precision, -1, projectionPlane, timeStep) > -1 )
// {
// returnValue = 1.0;
// }
//}
}
return returnValue;
}
bool mitk::PlanarFigureInteractor
::ExecuteAction( Action *action, mitk::StateEvent const *stateEvent )
{
bool ok = false;
// Check corresponding data; has to be sub-class of mitk::PlanarFigure
mitk::PlanarFigure *planarFigure =
dynamic_cast< mitk::PlanarFigure * >( m_DataTreeNode->GetData() );
if ( planarFigure == NULL )
{
return false;
}
// Get the timestep to also support 3D+t
const mitk::Event *theEvent = stateEvent->GetEvent();
int timeStep = 0;
mitk::ScalarType timeInMS = 0.0;
if ( theEvent )
{
if (theEvent->GetSender() != NULL)
{
timeStep = theEvent->GetSender()->GetTimeStep( planarFigure );
timeInMS = theEvent->GetSender()->GetTime();
}
}
// Get Geometry2D of PlanarFigure
mitk::Geometry2D *planarFigureGeometry =
dynamic_cast< mitk::Geometry2D * >( planarFigure->GetGeometry( timeStep ) );
// Get the Geometry2D of the window the user interacts with (for 2D point
// projection)
mitk::BaseRenderer *renderer = NULL;
const Geometry2D *projectionPlane = NULL;
if ( theEvent )
{
renderer = theEvent->GetSender();
projectionPlane = renderer->GetCurrentWorldGeometry2D();
}
// TODO: Check if display and PlanarFigure geometries are parallel (if they are PlaneGeometries)
switch (action->GetActionId())
{
case AcDONOTHING:
ok = true;
break;
case AcCHECKOBJECT:
{
if ( planarFigure->IsPlaced() )
{
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
}
ok = false;
break;
}
case AcADD:
{
// Use Geometry2D of the renderer clicked on for this PlanarFigure
mitk::PlaneGeometry *planeGeometry = const_cast< mitk::PlaneGeometry * >(
dynamic_cast< const mitk::PlaneGeometry * >(
renderer->GetSliceNavigationController()->GetCurrentPlaneGeometry() ) );
if ( planeGeometry != NULL )
{
planarFigureGeometry = planeGeometry;
planarFigure->SetGeometry2D( planeGeometry );
}
else
{
ok = false;
break;
}
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Place PlanarFigure at this point
planarFigure->PlaceFigure( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Set a bool property indicating that the figure has been placed in
// the current RenderWindow. This is required so that the same render
// window can be re-aligned to the Geometry2D of the PlanarFigure later
// on in an application.
m_DataTreeNode->SetBoolProperty( "PlanarFigureInitializedWindow", true, renderer );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcMOVEPOINT:
{
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Move current control point to this point
planarFigure->SetCurrentControlPoint( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcCHECKNMINUS1:
{
if ( planarFigure->GetNumberOfControlPoints() >=
planarFigure->GetMaximumNumberOfControlPoints() )
{
// Initial placement finished: deselect control point and send an
// InitializeEvent to notify application listeners
planarFigure->DeselectControlPoint();
planarFigure->InvokeEvent( itk::InitializeEvent() );
this->HandleEvent( new mitk::StateEvent( EIDYES, stateEvent->GetEvent() ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, stateEvent->GetEvent() ) );
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcCHECKEQUALS1:
{
// NOTE: Action name is a bit misleading; this action checks whether
// the figure has already the minimum number of required points to
// be finished.
if ( planarFigure->GetNumberOfControlPoints() >=
planarFigure->GetMinimumNumberOfControlPoints() )
{
planarFigure->DeselectControlPoint();
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcADDPOINT:
{
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Add point as new control point
planarFigure->AddControlPoint( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcDESELECTPOINT:
{
planarFigure->DeselectControlPoint();
// falls through
}
case AcCHECKPOINT:
{
int pointIndex = mitk::PlanarFigureInteractor::IsPositionInsideMarker(
stateEvent, planarFigure,
planarFigureGeometry,
renderer->GetCurrentWorldGeometry2D(),
renderer->GetDisplayGeometry() );
if ( pointIndex >= 0 )
{
planarFigure->SelectControlPoint( pointIndex );
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
// Return true: only this interactor is eligible to react on this event
ok = true;
}
else
{
planarFigure->DeselectControlPoint();
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
// Return false so that other (PlanarFigure) Interactors may react on this
// event as well
ok = false;
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
}
case AcSELECTPOINT:
{
ok = true;
break;
}
//case AcMOVEPOINT:
//case AcMOVESELECTED:
// {
// // Update the display
// mitk::RenderingManager::GetInstance()->RequestUpdateAll();
// ok = true;
// break;
// }
//case AcFINISHMOVE:
// {
// ok = true;
// break;
// }
default:
return Superclass::ExecuteAction( action, stateEvent );
}
return ok;
}
bool mitk::PlanarFigureInteractor::TransformPositionEventToPoint2D(
const StateEvent *stateEvent, Point2D &point2D,
const Geometry2D *planarFigureGeometry )
{
// Extract world position, and from this position on geometry, if
// available
const mitk::PositionEvent *positionEvent =
dynamic_cast< const mitk::PositionEvent * > ( stateEvent->GetEvent() );
if ( positionEvent == NULL )
{
return false;
}
mitk::Point3D worldPoint3D = positionEvent->GetWorldPosition();
// TODO: proper handling of distance tolerance
if ( planarFigureGeometry->Distance( worldPoint3D ) > 0.1 )
{
return false;
}
// Project point onto plane of this PlanarFigure
planarFigureGeometry->Map( worldPoint3D, point2D );
return true;
}
int mitk::PlanarFigureInteractor::IsPositionInsideMarker(
const StateEvent *stateEvent, const PlanarFigure *planarFigure,
const Geometry2D *planarFigureGeometry,
const Geometry2D *rendererGeometry,
const DisplayGeometry *displayGeometry ) const
{
// Extract display position
const mitk::PositionEvent *positionEvent =
dynamic_cast< const mitk::PositionEvent * > ( stateEvent->GetEvent() );
if ( positionEvent == NULL )
{
return -1;
}
//mitk::Point2D displayPosition;
//mitk::Point3D cursorWorldPosition = positionEvent->GetWorldPosition();
//displayGeometry->Project( cursorWorldPosition, cursorWorldPosition );
//displayGeometry->Map( cursorWorldPosition, displayPosition );
mitk::Point2D displayPosition = positionEvent->GetDisplayPosition();
// Iterate over all control points of planar figure, and check if
// any one is close to the current display position
typedef mitk::PlanarFigure::VertexContainerType VertexContainerType;
const VertexContainerType *controlPoints = planarFigure->GetControlPoints();
mitk::Point2D worldPoint2D, displayControlPoint;
mitk::Point3D worldPoint3D;
VertexContainerType::ConstIterator it;
for ( it = controlPoints->Begin(); it != controlPoints->End(); ++it )
{
planarFigureGeometry->Map( it->Value(), worldPoint3D );
// TODO: proper handling of distance tolerance
if ( displayGeometry->Distance( worldPoint3D ) < 0.1 )
{
rendererGeometry->Map( worldPoint3D, displayControlPoint );
displayGeometry->WorldToDisplay( displayControlPoint, displayControlPoint );
// TODO: variable size of markers
if ( (abs(displayPosition[0] - displayControlPoint[0]) < 4 )
&& (abs(displayPosition[1] - displayControlPoint[1]) < 4 ) )
{
return it->Index();
}
}
}
return -1;
}
void mitk::PlanarFigureInteractor::LogPrintPlanarFigureQuantities(
const PlanarFigure *planarFigure )
{
LOG_INFO << "PlanarFigure: " << planarFigure->GetNameOfClass();
for ( unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i )
{
LOG_INFO << "* " << planarFigure->GetFeatureName( i ) << ": "
<< planarFigure->GetQuantity( i ) << " " << planarFigure->GetFeatureUnit( i );
}
}
<commit_msg>FIX (#3031): Now issuing itk::EndEvent at the end of an interaction and setting modified flag of PlanarFigure<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-10-02 16:21:08 +0200 (Do, 02 Okt 2008) $
Version: $Revision: 13129 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPlanarFigureInteractor.h"
#include "mitkPointOperation.h"
#include "mitkPositionEvent.h"
#include "mitkPlanarFigure.h"
#include "mitkStatusBar.h"
#include "mitkDataTreeNode.h"
#include "mitkInteractionConst.h"
#include "mitkAction.h"
#include "mitkStateEvent.h"
#include "mitkOperationEvent.h"
#include "mitkUndoController.h"
#include "mitkStateMachineFactory.h"
#include "mitkStateTransitionOperation.h"
#include "mitkBaseRenderer.h"
#include "mitkRenderingManager.h"
//how precise must the user pick the point
//default value
mitk::PlanarFigureInteractor
::PlanarFigureInteractor(const char * type, DataTreeNode* dataTreeNode, int /* n */ )
: Interactor( type, dataTreeNode ),
m_Precision( 6.5 )
{
}
mitk::PlanarFigureInteractor::~PlanarFigureInteractor()
{
}
void mitk::PlanarFigureInteractor::SetPrecision( mitk::ScalarType precision )
{
m_Precision = precision;
}
// Overwritten since this class can handle it better!
float mitk::PlanarFigureInteractor
::CalculateJurisdiction(StateEvent const* stateEvent) const
{
float returnValue = 0.5;
// If it is a key event that can be handled in the current state,
// then return 0.5
mitk::DisplayPositionEvent const *disPosEvent =
dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
// Key event handling:
if (disPosEvent == NULL)
{
// Check if the current state has a transition waiting for that key event.
if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
{
return 0.5;
}
else
{
return 0.0;
}
}
//on MouseMove do nothing!
//if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
//{
// return 0.0;
//}
//if the event can be understood and if there is a transition waiting for that event
//if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
//{
// returnValue = 0.5;//it can be understood
//}
int timeStep = disPosEvent->GetSender()->GetTimeStep();
mitk::PlanarFigure *planarFigure = dynamic_cast<mitk::PlanarFigure *>(
m_DataTreeNode->GetData() );
if ( planarFigure != NULL )
{
// Give higher priority if this figure is currently selected
if ( planarFigure->GetSelectedControlPoint() >= 0 )
{
return 1.0;
}
// Get the Geometry2D of the window the user interacts with (for 2D point
// projection)
mitk::BaseRenderer *renderer = stateEvent->GetEvent()->GetSender();
const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D();
//// For reading on the points, Ids etc
//mitk::CurveModel::PointSetType *pointSet = curveModel->GetPointSet( timeStep );
//if ( pointSet == NULL )
//{
// return 0.0;
//}
//int visualizationMode = CurveModel::VISUALIZATION_MODE_PLANAR;
//if ( renderer != NULL )
//{
// m_DataTreeNode->GetIntProperty( "VisualizationMode", visualizationMode, renderer );
//}
//if ( visualizationMode == CurveModel::VISUALIZATION_MODE_PLANAR )
//{
// // Check if mouse is near the SELECTED point of the CurveModel (if != -1)
// if ( curveModel->GetSelectedPointId() != -1 )
// {
// Point3D selectedPoint;
// pointSet->GetPoint( curveModel->GetSelectedPointId(), &selectedPoint );
// float maxDistance = m_Precision * m_Precision;
// if ( maxDistance == 0.0 ) { maxDistance = 0.000001; }
// float distance = selectedPoint.SquaredEuclideanDistanceTo(
// disPosEvent->GetWorldPosition() );
// if ( distance < maxDistance )
// {
// returnValue = 1.0;
// }
// }
//}
//else if ( visualizationMode == CurveModel::VISUALIZATION_MODE_PROJECTION )
//{
// // Check if mouse is near the PROJECTION of any point of the CurveModel
// if ( curveModel->SearchPoint(
// disPosEvent->GetWorldPosition(), m_Precision, -1, projectionPlane, timeStep) > -1 )
// {
// returnValue = 1.0;
// }
//}
}
return returnValue;
}
bool mitk::PlanarFigureInteractor
::ExecuteAction( Action *action, mitk::StateEvent const *stateEvent )
{
bool ok = false;
// Check corresponding data; has to be sub-class of mitk::PlanarFigure
mitk::PlanarFigure *planarFigure =
dynamic_cast< mitk::PlanarFigure * >( m_DataTreeNode->GetData() );
if ( planarFigure == NULL )
{
return false;
}
// Get the timestep to also support 3D+t
const mitk::Event *theEvent = stateEvent->GetEvent();
int timeStep = 0;
mitk::ScalarType timeInMS = 0.0;
if ( theEvent )
{
if (theEvent->GetSender() != NULL)
{
timeStep = theEvent->GetSender()->GetTimeStep( planarFigure );
timeInMS = theEvent->GetSender()->GetTime();
}
}
// Get Geometry2D of PlanarFigure
mitk::Geometry2D *planarFigureGeometry =
dynamic_cast< mitk::Geometry2D * >( planarFigure->GetGeometry( timeStep ) );
// Get the Geometry2D of the window the user interacts with (for 2D point
// projection)
mitk::BaseRenderer *renderer = NULL;
const Geometry2D *projectionPlane = NULL;
if ( theEvent )
{
renderer = theEvent->GetSender();
projectionPlane = renderer->GetCurrentWorldGeometry2D();
}
// TODO: Check if display and PlanarFigure geometries are parallel (if they are PlaneGeometries)
switch (action->GetActionId())
{
case AcDONOTHING:
ok = true;
break;
case AcCHECKOBJECT:
{
if ( planarFigure->IsPlaced() )
{
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
}
ok = false;
break;
}
case AcADD:
{
// Use Geometry2D of the renderer clicked on for this PlanarFigure
mitk::PlaneGeometry *planeGeometry = const_cast< mitk::PlaneGeometry * >(
dynamic_cast< const mitk::PlaneGeometry * >(
renderer->GetSliceNavigationController()->GetCurrentPlaneGeometry() ) );
if ( planeGeometry != NULL )
{
planarFigureGeometry = planeGeometry;
planarFigure->SetGeometry2D( planeGeometry );
}
else
{
ok = false;
break;
}
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Place PlanarFigure at this point
planarFigure->PlaceFigure( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Set a bool property indicating that the figure has been placed in
// the current RenderWindow. This is required so that the same render
// window can be re-aligned to the Geometry2D of the PlanarFigure later
// on in an application.
m_DataTreeNode->SetBoolProperty( "PlanarFigureInitializedWindow", true, renderer );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcMOVEPOINT:
{
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Move current control point to this point
planarFigure->SetCurrentControlPoint( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcCHECKNMINUS1:
{
if ( planarFigure->GetNumberOfControlPoints() >=
planarFigure->GetMaximumNumberOfControlPoints() )
{
// Initial placement finished: deselect control point and send an
// InitializeEvent to notify application listeners
planarFigure->Modified();
planarFigure->DeselectControlPoint();
planarFigure->InvokeEvent( itk::InitializeEvent() );
planarFigure->InvokeEvent( itk::EndEvent() );
this->HandleEvent( new mitk::StateEvent( EIDYES, stateEvent->GetEvent() ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, stateEvent->GetEvent() ) );
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcCHECKEQUALS1:
{
// NOTE: Action name is a bit misleading; this action checks whether
// the figure has already the minimum number of required points to
// be finished.
if ( planarFigure->GetNumberOfControlPoints() >=
planarFigure->GetMinimumNumberOfControlPoints() )
{
planarFigure->DeselectControlPoint();
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
}
else
{
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcADDPOINT:
{
// Extract point in 2D world coordinates (relative to Geometry2D of
// PlanarFigure)
Point2D point2D;
if ( !this->TransformPositionEventToPoint2D( stateEvent, point2D,
planarFigureGeometry ) )
{
ok = false;
break;
}
// Add point as new control point
planarFigure->AddControlPoint( point2D );
// Re-evaluate features
planarFigure->EvaluateFeatures();
this->LogPrintPlanarFigureQuantities( planarFigure );
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
ok = true;
break;
}
case AcDESELECTPOINT:
{
planarFigure->DeselectControlPoint();
// Issue event so that listeners may update themselves
planarFigure->Modified();
planarFigure->InvokeEvent( itk::EndEvent() );
// falls through
}
case AcCHECKPOINT:
{
int pointIndex = mitk::PlanarFigureInteractor::IsPositionInsideMarker(
stateEvent, planarFigure,
planarFigureGeometry,
renderer->GetCurrentWorldGeometry2D(),
renderer->GetDisplayGeometry() );
if ( pointIndex >= 0 )
{
planarFigure->SelectControlPoint( pointIndex );
this->HandleEvent( new mitk::StateEvent( EIDYES, NULL ) );
// Return true: only this interactor is eligible to react on this event
ok = true;
}
else
{
planarFigure->DeselectControlPoint();
this->HandleEvent( new mitk::StateEvent( EIDNO, NULL ) );
// Return false so that other (PlanarFigure) Interactors may react on this
// event as well
ok = false;
}
// Update rendered scene
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
}
case AcSELECTPOINT:
{
ok = true;
break;
}
//case AcMOVEPOINT:
//case AcMOVESELECTED:
// {
// // Update the display
// mitk::RenderingManager::GetInstance()->RequestUpdateAll();
// ok = true;
// break;
// }
//case AcFINISHMOVE:
// {
// ok = true;
// break;
// }
default:
return Superclass::ExecuteAction( action, stateEvent );
}
return ok;
}
bool mitk::PlanarFigureInteractor::TransformPositionEventToPoint2D(
const StateEvent *stateEvent, Point2D &point2D,
const Geometry2D *planarFigureGeometry )
{
// Extract world position, and from this position on geometry, if
// available
const mitk::PositionEvent *positionEvent =
dynamic_cast< const mitk::PositionEvent * > ( stateEvent->GetEvent() );
if ( positionEvent == NULL )
{
return false;
}
mitk::Point3D worldPoint3D = positionEvent->GetWorldPosition();
// TODO: proper handling of distance tolerance
if ( planarFigureGeometry->Distance( worldPoint3D ) > 0.1 )
{
return false;
}
// Project point onto plane of this PlanarFigure
planarFigureGeometry->Map( worldPoint3D, point2D );
return true;
}
int mitk::PlanarFigureInteractor::IsPositionInsideMarker(
const StateEvent *stateEvent, const PlanarFigure *planarFigure,
const Geometry2D *planarFigureGeometry,
const Geometry2D *rendererGeometry,
const DisplayGeometry *displayGeometry ) const
{
// Extract display position
const mitk::PositionEvent *positionEvent =
dynamic_cast< const mitk::PositionEvent * > ( stateEvent->GetEvent() );
if ( positionEvent == NULL )
{
return -1;
}
//mitk::Point2D displayPosition;
//mitk::Point3D cursorWorldPosition = positionEvent->GetWorldPosition();
//displayGeometry->Project( cursorWorldPosition, cursorWorldPosition );
//displayGeometry->Map( cursorWorldPosition, displayPosition );
mitk::Point2D displayPosition = positionEvent->GetDisplayPosition();
// Iterate over all control points of planar figure, and check if
// any one is close to the current display position
typedef mitk::PlanarFigure::VertexContainerType VertexContainerType;
const VertexContainerType *controlPoints = planarFigure->GetControlPoints();
mitk::Point2D worldPoint2D, displayControlPoint;
mitk::Point3D worldPoint3D;
VertexContainerType::ConstIterator it;
for ( it = controlPoints->Begin(); it != controlPoints->End(); ++it )
{
planarFigureGeometry->Map( it->Value(), worldPoint3D );
// TODO: proper handling of distance tolerance
if ( displayGeometry->Distance( worldPoint3D ) < 0.1 )
{
rendererGeometry->Map( worldPoint3D, displayControlPoint );
displayGeometry->WorldToDisplay( displayControlPoint, displayControlPoint );
// TODO: variable size of markers
if ( (abs(displayPosition[0] - displayControlPoint[0]) < 4 )
&& (abs(displayPosition[1] - displayControlPoint[1]) < 4 ) )
{
return it->Index();
}
}
}
return -1;
}
void mitk::PlanarFigureInteractor::LogPrintPlanarFigureQuantities(
const PlanarFigure *planarFigure )
{
LOG_INFO << "PlanarFigure: " << planarFigure->GetNameOfClass();
for ( unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i )
{
LOG_INFO << "* " << planarFigure->GetFeatureName( i ) << ": "
<< planarFigure->GetQuantity( i ) << " " << planarFigure->GetFeatureUnit( i );
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2019 mogemimi. Distributed under the MIT license.
#include "Pomdog/Experimental/Graphics/SpriteFont.hpp"
#include "Pomdog/Experimental/Graphics/FontGlyph.hpp"
#include "Pomdog/Experimental/Graphics/SpriteBatch.hpp"
#include "Pomdog/Experimental/Graphics/TrueTypeFont.hpp"
#include "Pomdog/Graphics/Texture2D.hpp"
#include "Pomdog/Math/Color.hpp"
#include "Pomdog/Math/Matrix3x2.hpp"
#include "Pomdog/Math/Matrix4x4.hpp"
#include "Pomdog/Math/Point2D.hpp"
#include "Pomdog/Math/Radian.hpp"
#include "Pomdog/Math/Vector2.hpp"
#include "Pomdog/Math/Vector3.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include <utfcpp/source/utf8.h>
#include <algorithm>
#include <unordered_map>
namespace Pomdog {
namespace {
bool isSpace(char32_t c) noexcept
{
return (c == U' ') || (c == U'\t');
}
} // unnamed namespace
// MARK: - SpriteFont::Impl
class SpriteFont::Impl final {
public:
static constexpr int TextureWidth = 2048;
static constexpr int TextureHeight = 2048;
std::unordered_map<char32_t, FontGlyph> spriteFontMap;
char32_t defaultCharacter;
float lineSpacing;
float spacing;
float fontSize;
Impl(
std::vector<std::shared_ptr<Texture2D>>&& textures,
const std::vector<FontGlyph>& glyphs,
float spacing,
float lineSpacing);
Impl(
const std::shared_ptr<GraphicsDevice>& graphicsDevice,
const std::shared_ptr<TrueTypeFont>& font,
float fontSize,
float lineSpacing);
template <typename Func>
void ForEach(const std::string& text, Func func);
Vector2 MeasureString(const std::string& text);
void Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale);
void PrepareFonts(const std::string& text);
private:
std::vector<std::shared_ptr<Texture2D>> textures;
std::shared_ptr<GraphicsDevice> graphicsDevice;
std::shared_ptr<TrueTypeFont> font;
std::vector<std::uint8_t> pixelData;
Point2D currentPoint;
int bottomY;
};
constexpr int SpriteFont::Impl::TextureWidth;
constexpr int SpriteFont::Impl::TextureHeight;
SpriteFont::Impl::Impl(
std::vector<std::shared_ptr<Texture2D>>&& texturesIn,
const std::vector<FontGlyph>& glyphsIn,
float spacingIn,
float lineSpacingIn)
: defaultCharacter(U' ')
, lineSpacing(lineSpacingIn)
, spacing(spacingIn)
, fontSize(0)
, textures(std::move(texturesIn))
{
for (auto& glyph : glyphsIn) {
spriteFontMap.emplace(glyph.Character, glyph);
}
}
SpriteFont::Impl::Impl(
const std::shared_ptr<GraphicsDevice>& graphicsDeviceIn,
const std::shared_ptr<TrueTypeFont>& fontIn,
float fontSizeIn,
float lineSpacingIn)
: defaultCharacter(U' ')
, lineSpacing(lineSpacingIn)
, spacing(0)
, fontSize(fontSizeIn)
, graphicsDevice(graphicsDeviceIn)
, font(fontIn)
{
POMDOG_ASSERT(font);
pixelData.resize(TextureWidth * TextureHeight, 0);
currentPoint = {1, 1};
bottomY = 1;
auto texture = std::make_shared<Texture2D>(graphicsDevice,
TextureWidth, TextureHeight, false, SurfaceFormat::A8_UNorm);
textures.push_back(texture);
}
template <typename Func>
void SpriteFont::Impl::ForEach(const std::string& text, Func func)
{
Vector2 position = Vector2::Zero;
auto textIter = std::begin(text);
const auto textEnd = std::end(text);
while (textIter != textEnd) {
const auto character = utf8::next(textIter, textEnd);
switch (character) {
case U'\n': {
position.X = 0;
position.Y += lineSpacing;
FontGlyph glyph;
glyph.Character = U'\n';
glyph.Subrect = Rectangle{0, 0, 0, 0};
glyph.XAdvance = 0;
func(glyph, position);
break;
}
case U'\r': {
break;
}
default: {
POMDOG_ASSERT(character != 0x00);
POMDOG_ASSERT(character != 0x08);
POMDOG_ASSERT(character != 0x1B);
auto iter = spriteFontMap.find(character);
if (iter == std::end(spriteFontMap)) {
// NOTE: Rasterize glyphs immediately
PrepareFonts(text);
iter = spriteFontMap.find(character);
if (iter == std::end(spriteFontMap)) {
iter = spriteFontMap.find(defaultCharacter);
}
}
POMDOG_ASSERT(iter != std::end(spriteFontMap));
if (iter == std::end(spriteFontMap)) {
continue;
}
const auto& glyph = iter->second;
position.X += static_cast<float>(glyph.XOffset);
func(glyph, position);
const auto advance = glyph.XAdvance - glyph.XOffset;
position.X += (static_cast<float>(advance) - static_cast<float>(spacing));
break;
}
}
}
}
void SpriteFont::Impl::PrepareFonts(const std::string& text)
{
POMDOG_ASSERT(!text.empty());
if (!graphicsDevice || !font) {
return;
}
bool needToFetchPixelData = false;
auto fetchTextureData = [&] {
if (needToFetchPixelData) {
auto texture = textures.back();
texture->SetData(pixelData.data());
needToFetchPixelData = false;
}
};
auto textIter = std::begin(text);
auto textIterEnd = std::end(text);
while (textIter != textIterEnd) {
const auto character = utf8::next(textIter, textIterEnd);
if (spriteFontMap.find(character) != std::end(spriteFontMap)) {
continue;
}
auto glyph = font->RasterizeGlyph(character, fontSize, TextureWidth,
[&](int glyphWidth, int glyphHeight, Point2D& pointOut, std::uint8_t*& output) {
if (currentPoint.X + glyphWidth + 1 >= TextureWidth) {
// advance to next row
currentPoint.Y = bottomY;
currentPoint.X = 1;
}
if (currentPoint.Y + glyphHeight + 1 >= TextureHeight) {
fetchTextureData();
std::fill(std::begin(pixelData), std::end(pixelData), static_cast<std::uint8_t>(0));
auto textureNew = std::make_shared<Texture2D>(graphicsDevice,
TextureWidth, TextureHeight, false, SurfaceFormat::A8_UNorm);
textures.push_back(textureNew);
currentPoint = {1, 1};
bottomY = 1;
}
POMDOG_ASSERT(currentPoint.X + glyphWidth < TextureWidth);
POMDOG_ASSERT(currentPoint.Y + glyphHeight < TextureHeight);
pointOut = currentPoint;
output = pixelData.data();
});
if (!glyph) {
continue;
}
currentPoint.X = currentPoint.X + glyph->Subrect.Width + 1;
bottomY = std::max(bottomY, currentPoint.Y + glyph->Subrect.Height + 1);
POMDOG_ASSERT(!textures.empty() && textures.size() > 0);
glyph->TexturePage = static_cast<std::int16_t>(textures.size()) - 1;
spriteFontMap.emplace(glyph->Character, *glyph);
needToFetchPixelData = true;
}
fetchTextureData();
}
Vector2 SpriteFont::Impl::MeasureString(const std::string& text)
{
POMDOG_ASSERT(!text.empty());
Vector2 result = Vector2::Zero;
ForEach(text, [&](const FontGlyph& glyph, const Vector2& postion) {
if (glyph.Character == U'\n') {
result = Vector2::Max(result, postion + Vector2{0.0f, lineSpacing});
return;
}
float w = static_cast<float>(glyph.Subrect.Width);
float h = static_cast<float>(glyph.Subrect.Height);
h = std::max(h, lineSpacing);
result = Vector2::Max(result, postion + Vector2{w, h});
});
return result;
}
void SpriteFont::Impl::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale)
{
if (text.empty()) {
return;
}
if (textures.empty()) {
return;
}
if ((scale.X == 0.0f) || (scale.Y == 0.0f)) {
return;
}
// FIXME: Need to optimize layout calculation here.
const auto labelSize = MeasureString(text);
if ((labelSize.X < 1.0f) || (labelSize.Y < 1.0f)) {
return;
}
const auto baseOffset = labelSize * originPivot - Vector2{0.0f, labelSize.Y - lineSpacing};
ForEach(text, [&](const FontGlyph& glyph, const Vector2& pos) {
if (isSpace(glyph.Character)) {
// NOTE: Skip rendering
return;
}
if ((glyph.Subrect.Width <= 0) || (glyph.Subrect.Height <= 0)) {
// NOTE: Skip rendering
return;
}
POMDOG_ASSERT(glyph.Character != U'\n');
POMDOG_ASSERT(glyph.TexturePage >= 0);
POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size()));
auto w = static_cast<float>(glyph.Subrect.Width);
auto h = static_cast<float>(glyph.Subrect.Height);
auto offset = Vector2{
pos.X,
-pos.Y - (static_cast<float>(glyph.YOffset) + h)};
offset = (baseOffset - offset) / Vector2{w, h};
spriteBatch.Draw(textures[glyph.TexturePage], position, glyph.Subrect, color, rotation, offset, scale);
});
}
// MARK: - SpriteFont
SpriteFont::SpriteFont(
std::vector<std::shared_ptr<Texture2D>>&& textures,
const std::vector<FontGlyph>& glyphs,
float spacing,
float lineSpacing)
: impl(std::make_unique<Impl>(std::move(textures), glyphs, spacing, lineSpacing))
{
}
SpriteFont::SpriteFont(
const std::shared_ptr<GraphicsDevice>& graphicsDevice,
const std::shared_ptr<TrueTypeFont>& font,
float fontSize,
float lineSpacing)
: impl(std::make_unique<Impl>(graphicsDevice, font, fontSize, lineSpacing))
{
}
SpriteFont::~SpriteFont() = default;
void SpriteFont::PrepareFonts(const std::string& utf8String)
{
POMDOG_ASSERT(impl);
return impl->PrepareFonts(utf8String);
}
Vector2 SpriteFont::MeasureString(const std::string& utf8String) const
{
POMDOG_ASSERT(impl);
if (utf8String.empty()) {
return Vector2::Zero;
}
return impl->MeasureString(utf8String);
}
char32_t SpriteFont::GetDefaultCharacter() const
{
POMDOG_ASSERT(impl);
return impl->defaultCharacter;
}
void SpriteFont::SetDefaultCharacter(char32_t character)
{
POMDOG_ASSERT(impl);
POMDOG_ASSERT(ContainsCharacter(character));
impl->defaultCharacter = character;
}
float SpriteFont::GetLineSpacing() const
{
POMDOG_ASSERT(impl);
return impl->lineSpacing;
}
void SpriteFont::SetLineSpacing(float lineSpacingIn)
{
POMDOG_ASSERT(impl);
impl->lineSpacing = lineSpacingIn;
}
bool SpriteFont::ContainsCharacter(char32_t character) const
{
POMDOG_ASSERT(impl);
return impl->spriteFontMap.find(character) != std::end(impl->spriteFontMap);
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color)
{
if (text.empty()) {
return;
}
impl->PrepareFonts(text);
impl->Draw(spriteBatch, text, position, color, 0.0f, Vector2{0.0f, 0.0f}, Vector2{1.0f, 1.0f});
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
float scale)
{
this->Draw(spriteBatch, text, position, color, rotation, originPivot, Vector2{scale, scale});
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale)
{
if (text.empty()) {
return;
}
impl->PrepareFonts(text);
impl->Draw(spriteBatch, text, position, color, rotation, originPivot, scale);
}
} // namespace Pomdog
<commit_msg>Fix bug measuring string length in sprite font<commit_after>// Copyright (c) 2013-2019 mogemimi. Distributed under the MIT license.
#include "Pomdog/Experimental/Graphics/SpriteFont.hpp"
#include "Pomdog/Experimental/Graphics/FontGlyph.hpp"
#include "Pomdog/Experimental/Graphics/SpriteBatch.hpp"
#include "Pomdog/Experimental/Graphics/TrueTypeFont.hpp"
#include "Pomdog/Graphics/Texture2D.hpp"
#include "Pomdog/Math/Color.hpp"
#include "Pomdog/Math/Matrix3x2.hpp"
#include "Pomdog/Math/Matrix4x4.hpp"
#include "Pomdog/Math/Point2D.hpp"
#include "Pomdog/Math/Radian.hpp"
#include "Pomdog/Math/Vector2.hpp"
#include "Pomdog/Math/Vector3.hpp"
#include "Pomdog/Utility/Assert.hpp"
#include <utfcpp/source/utf8.h>
#include <algorithm>
#include <unordered_map>
namespace Pomdog {
namespace {
bool isSpace(char32_t c) noexcept
{
return (c == U' ') || (c == U'\t');
}
} // unnamed namespace
// MARK: - SpriteFont::Impl
class SpriteFont::Impl final {
public:
static constexpr int TextureWidth = 2048;
static constexpr int TextureHeight = 2048;
std::unordered_map<char32_t, FontGlyph> spriteFontMap;
char32_t defaultCharacter;
float lineSpacing;
float spacing;
float fontSize;
Impl(
std::vector<std::shared_ptr<Texture2D>>&& textures,
const std::vector<FontGlyph>& glyphs,
float spacing,
float lineSpacing);
Impl(
const std::shared_ptr<GraphicsDevice>& graphicsDevice,
const std::shared_ptr<TrueTypeFont>& font,
float fontSize,
float lineSpacing);
template <typename Func>
void ForEach(const std::string& text, Func func);
Vector2 MeasureString(const std::string& text);
void Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale);
void PrepareFonts(const std::string& text);
private:
std::vector<std::shared_ptr<Texture2D>> textures;
std::shared_ptr<GraphicsDevice> graphicsDevice;
std::shared_ptr<TrueTypeFont> font;
std::vector<std::uint8_t> pixelData;
Point2D currentPoint;
int bottomY;
};
constexpr int SpriteFont::Impl::TextureWidth;
constexpr int SpriteFont::Impl::TextureHeight;
SpriteFont::Impl::Impl(
std::vector<std::shared_ptr<Texture2D>>&& texturesIn,
const std::vector<FontGlyph>& glyphsIn,
float spacingIn,
float lineSpacingIn)
: defaultCharacter(U' ')
, lineSpacing(lineSpacingIn)
, spacing(spacingIn)
, fontSize(0)
, textures(std::move(texturesIn))
{
for (auto& glyph : glyphsIn) {
spriteFontMap.emplace(glyph.Character, glyph);
}
}
SpriteFont::Impl::Impl(
const std::shared_ptr<GraphicsDevice>& graphicsDeviceIn,
const std::shared_ptr<TrueTypeFont>& fontIn,
float fontSizeIn,
float lineSpacingIn)
: defaultCharacter(U' ')
, lineSpacing(lineSpacingIn)
, spacing(0)
, fontSize(fontSizeIn)
, graphicsDevice(graphicsDeviceIn)
, font(fontIn)
{
POMDOG_ASSERT(font);
pixelData.resize(TextureWidth * TextureHeight, 0);
currentPoint = {1, 1};
bottomY = 1;
auto texture = std::make_shared<Texture2D>(graphicsDevice,
TextureWidth, TextureHeight, false, SurfaceFormat::A8_UNorm);
textures.push_back(texture);
}
template <typename Func>
void SpriteFont::Impl::ForEach(const std::string& text, Func func)
{
Vector2 position = Vector2::Zero;
auto textIter = std::begin(text);
const auto textEnd = std::end(text);
while (textIter != textEnd) {
const auto character = utf8::next(textIter, textEnd);
switch (character) {
case U'\n': {
position.X = 0;
position.Y += lineSpacing;
FontGlyph glyph;
glyph.Character = U'\n';
glyph.Subrect = Rectangle{0, 0, 0, 0};
glyph.XAdvance = 0;
func(glyph, position);
break;
}
case U'\r': {
break;
}
default: {
POMDOG_ASSERT(character != 0x00);
POMDOG_ASSERT(character != 0x08);
POMDOG_ASSERT(character != 0x1B);
auto iter = spriteFontMap.find(character);
if (iter == std::end(spriteFontMap)) {
// NOTE: Rasterize glyphs immediately
PrepareFonts(text);
iter = spriteFontMap.find(character);
if (iter == std::end(spriteFontMap)) {
iter = spriteFontMap.find(defaultCharacter);
}
}
POMDOG_ASSERT(iter != std::end(spriteFontMap));
if (iter == std::end(spriteFontMap)) {
continue;
}
const auto& glyph = iter->second;
position.X += static_cast<float>(glyph.XOffset);
func(glyph, position);
const auto advance = glyph.XAdvance - glyph.XOffset;
position.X += (static_cast<float>(advance) - static_cast<float>(spacing));
break;
}
}
}
}
void SpriteFont::Impl::PrepareFonts(const std::string& text)
{
POMDOG_ASSERT(!text.empty());
if (!graphicsDevice || !font) {
return;
}
bool needToFetchPixelData = false;
auto fetchTextureData = [&] {
if (needToFetchPixelData) {
auto texture = textures.back();
texture->SetData(pixelData.data());
needToFetchPixelData = false;
}
};
auto textIter = std::begin(text);
auto textIterEnd = std::end(text);
while (textIter != textIterEnd) {
const auto character = utf8::next(textIter, textIterEnd);
if (spriteFontMap.find(character) != std::end(spriteFontMap)) {
continue;
}
auto glyph = font->RasterizeGlyph(character, fontSize, TextureWidth,
[&](int glyphWidth, int glyphHeight, Point2D& pointOut, std::uint8_t*& output) {
if (currentPoint.X + glyphWidth + 1 >= TextureWidth) {
// advance to next row
currentPoint.Y = bottomY;
currentPoint.X = 1;
}
if (currentPoint.Y + glyphHeight + 1 >= TextureHeight) {
fetchTextureData();
std::fill(std::begin(pixelData), std::end(pixelData), static_cast<std::uint8_t>(0));
auto textureNew = std::make_shared<Texture2D>(graphicsDevice,
TextureWidth, TextureHeight, false, SurfaceFormat::A8_UNorm);
textures.push_back(textureNew);
currentPoint = {1, 1};
bottomY = 1;
}
POMDOG_ASSERT(currentPoint.X + glyphWidth < TextureWidth);
POMDOG_ASSERT(currentPoint.Y + glyphHeight < TextureHeight);
pointOut = currentPoint;
output = pixelData.data();
});
if (!glyph) {
continue;
}
currentPoint.X = currentPoint.X + glyph->Subrect.Width + 1;
bottomY = std::max(bottomY, currentPoint.Y + glyph->Subrect.Height + 1);
POMDOG_ASSERT(!textures.empty() && textures.size() > 0);
glyph->TexturePage = static_cast<std::int16_t>(textures.size()) - 1;
spriteFontMap.emplace(glyph->Character, *glyph);
needToFetchPixelData = true;
}
fetchTextureData();
}
Vector2 SpriteFont::Impl::MeasureString(const std::string& text)
{
POMDOG_ASSERT(!text.empty());
Vector2 result = Vector2::Zero;
ForEach(text, [&](const FontGlyph& glyph, const Vector2& postion) {
if (glyph.Character == U'\n') {
result = Vector2::Max(result, postion + Vector2{0.0f, lineSpacing});
return;
}
float w = static_cast<float>(glyph.Subrect.Width);
float h = static_cast<float>(glyph.Subrect.Height);
h = std::max(h, lineSpacing);
if (glyph.Character == U' ') {
const auto advance = glyph.XAdvance - glyph.XOffset;
w += (static_cast<float>(advance) - static_cast<float>(spacing));
}
result = Vector2::Max(result, postion + Vector2{w, h});
});
return result;
}
void SpriteFont::Impl::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale)
{
if (text.empty()) {
return;
}
if (textures.empty()) {
return;
}
if ((scale.X == 0.0f) || (scale.Y == 0.0f)) {
return;
}
// FIXME: Need to optimize layout calculation here.
const auto labelSize = MeasureString(text);
if ((labelSize.X < 1.0f) || (labelSize.Y < 1.0f)) {
return;
}
const auto baseOffset = labelSize * originPivot - Vector2{0.0f, labelSize.Y - lineSpacing};
ForEach(text, [&](const FontGlyph& glyph, const Vector2& pos) {
if (isSpace(glyph.Character)) {
// NOTE: Skip rendering
return;
}
if ((glyph.Subrect.Width <= 0) || (glyph.Subrect.Height <= 0)) {
// NOTE: Skip rendering
return;
}
POMDOG_ASSERT(glyph.Character != U'\n');
POMDOG_ASSERT(glyph.TexturePage >= 0);
POMDOG_ASSERT(glyph.TexturePage < static_cast<int>(textures.size()));
auto w = static_cast<float>(glyph.Subrect.Width);
auto h = static_cast<float>(glyph.Subrect.Height);
auto offset = Vector2{
pos.X,
-pos.Y - (static_cast<float>(glyph.YOffset) + h)};
offset = (baseOffset - offset) / Vector2{w, h};
spriteBatch.Draw(textures[glyph.TexturePage], position, glyph.Subrect, color, rotation, offset, scale);
});
}
// MARK: - SpriteFont
SpriteFont::SpriteFont(
std::vector<std::shared_ptr<Texture2D>>&& textures,
const std::vector<FontGlyph>& glyphs,
float spacing,
float lineSpacing)
: impl(std::make_unique<Impl>(std::move(textures), glyphs, spacing, lineSpacing))
{
}
SpriteFont::SpriteFont(
const std::shared_ptr<GraphicsDevice>& graphicsDevice,
const std::shared_ptr<TrueTypeFont>& font,
float fontSize,
float lineSpacing)
: impl(std::make_unique<Impl>(graphicsDevice, font, fontSize, lineSpacing))
{
}
SpriteFont::~SpriteFont() = default;
void SpriteFont::PrepareFonts(const std::string& utf8String)
{
POMDOG_ASSERT(impl);
return impl->PrepareFonts(utf8String);
}
Vector2 SpriteFont::MeasureString(const std::string& utf8String) const
{
POMDOG_ASSERT(impl);
if (utf8String.empty()) {
return Vector2::Zero;
}
return impl->MeasureString(utf8String);
}
char32_t SpriteFont::GetDefaultCharacter() const
{
POMDOG_ASSERT(impl);
return impl->defaultCharacter;
}
void SpriteFont::SetDefaultCharacter(char32_t character)
{
POMDOG_ASSERT(impl);
POMDOG_ASSERT(ContainsCharacter(character));
impl->defaultCharacter = character;
}
float SpriteFont::GetLineSpacing() const
{
POMDOG_ASSERT(impl);
return impl->lineSpacing;
}
void SpriteFont::SetLineSpacing(float lineSpacingIn)
{
POMDOG_ASSERT(impl);
impl->lineSpacing = lineSpacingIn;
}
bool SpriteFont::ContainsCharacter(char32_t character) const
{
POMDOG_ASSERT(impl);
return impl->spriteFontMap.find(character) != std::end(impl->spriteFontMap);
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color)
{
if (text.empty()) {
return;
}
impl->PrepareFonts(text);
impl->Draw(spriteBatch, text, position, color, 0.0f, Vector2{0.0f, 0.0f}, Vector2{1.0f, 1.0f});
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
float scale)
{
this->Draw(spriteBatch, text, position, color, rotation, originPivot, Vector2{scale, scale});
}
void SpriteFont::Draw(
SpriteBatch& spriteBatch,
const std::string& text,
const Vector2& position,
const Color& color,
const Radian<float>& rotation,
const Vector2& originPivot,
const Vector2& scale)
{
if (text.empty()) {
return;
}
impl->PrepareFonts(text);
impl->Draw(spriteBatch, text, position, color, rotation, originPivot, scale);
}
} // namespace Pomdog
<|endoftext|> |
<commit_before>//*===================================================================
//The Medical Imaging Interaction Toolkit (MITK)
//Copyright (c) German Cancer Research Center,
//Division of Medical and Biological Informatics.
//All rights reserved.
//This software is distributed WITHOUT ANY WARRANTY; without
//even the implied warranty of MERCHANTABILITY or FITNESS FOR
//A PARTICULAR PURPOSE.
//See LICENSE.txt or http://www.mitk.org for details.
//===================================================================*/
#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
#include <mitkPASpectralUnmixingFilterBase.h>
#include <mitkPALinearSpectralUnmixingFilter.h>
#include <mitkPASpectralUnmixingFilterVigra.h>
#include <mitkPASpectralUnmixingFilterSimplex.h>
#include <mitkPASpectralUnmixingSO2.h>
#include <mitkImageReadAccessor.h>
class mitkSpectralUnmixingTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkSpectralUnmixingTestSuite);
MITK_TEST(testEigenSUAlgorithm);
MITK_TEST(testVigraSUAlgorithm);
//MITK_TEST(testSimplexSUAlgorithm);// --> RESULT FAILS
MITK_TEST(testSO2);
CPPUNIT_TEST_SUITE_END();
private:
mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter;
mitk::Image::Pointer inputImage;
std::vector<int> m_inputWavelengths;
std::vector<double> m_inputWeights;
std::vector<float> m_CorrectResult;
float threshold;
public:
void setUp() override
{
MITK_INFO << "setUp ... ";
//Set empty input image:
inputImage = mitk::Image::New();
mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>();
const int NUMBER_OF_SPATIAL_DIMENSIONS = 3;
auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS];
dimensions[0] = 1;
dimensions[1] = 1;
dimensions[2] = 5;
inputImage->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions);
//Set wavelengths for unmixing:
m_inputWavelengths.push_back(750);
m_inputWavelengths.push_back(800);
m_inputWeights.push_back(50);
m_inputWeights.push_back(100);
//Set fraction of Hb and HbO2 to unmix:
float fracHb = 100;
float fracHbO2 = 300;
m_CorrectResult.push_back(fracHbO2);
m_CorrectResult.push_back(fracHb);
m_CorrectResult.push_back(fracHbO2 + 10);
m_CorrectResult.push_back(fracHb - 10);
threshold = 0.01;
//Multiply values of wavelengths (750,800,850 nm) with fractions to get pixel values:
float px1 = fracHb * 7.52 + fracHbO2 * 2.77;
float px2 = fracHb * 4.08 + fracHbO2 * 4.37;
float px3 = (fracHb - 10) * 7.52 + (fracHbO2 + 10) * 2.77;
float px4 = (fracHb - 10) * 4.08 + (fracHbO2 + 10) * 4.37;
float* data = new float[3];
data[0] = px1;
data[1] = px2;
data[2] = px3;
data[3] = px4;
data[5] = 0;
inputImage->SetImportVolume(data, mitk::Image::ImportMemoryManagementType::CopyMemory);
delete[] data;
MITK_INFO << "[DONE]";
}
void testEigenSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
m_SpectralUnmixingFilter->SetInput(inputImage);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
ofstream myfile;
myfile.open("EigenTestResult.txt");
std::vector<mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType> m_Eigen = {
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::HOUSEHOLDERQR, /* mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::LDLT,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::LLT,*/ mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::COLPIVHOUSEHOLDERQR,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::JACOBISVD, mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVLU,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVHOUSEHOLDERQR};
for (int Algorithmidx = 0; Algorithmidx < m_Eigen.size();++Algorithmidx)
{
m_SpectralUnmixingFilter->SetAlgorithm(m_Eigen[Algorithmidx]);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Algorithmidx: " << Algorithmidx << "\n Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i]) < threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2]) < threshold);
}
}
myfile.close();
MITK_INFO << "EIGEN FILTER TEST SUCCESFULL :)";
}
void testVigraSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
m_SpectralUnmixingFilter->SetInput(inputImage);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
double Weight = m_inputWeights[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
m_SpectralUnmixingFilter->AddWeight(Weight);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
std::vector<mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType> Vigra = {
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LARS, mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::GOLDFARB,
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::WEIGHTED, mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LS/*,
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::vigratest*/};
ofstream myfile;
myfile.open("VigraTestResult.txt");
for (int Algorithmidx = 0; Algorithmidx < Vigra.size();++Algorithmidx)
{
m_SpectralUnmixingFilter->SetAlgorithm(Vigra[0]);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Algorithmidx: " << Algorithmidx << "\n Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i]) < threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2]) < threshold);
}
}
myfile.close();
MITK_INFO << "VIGRA FILTER TEST SUCCESFULL :)";
}
void testSimplexSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterSimplex::New();
m_SpectralUnmixingFilter->SetInput(inputImage);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
ofstream myfile;
myfile.open("SimplexTestResult.txt");
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i])<threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2])<threshold);
}
myfile.close();
MITK_INFO << "SIMPLEX FILTER TEST SUCCESFULL :)";
}
void testSO2()
{
MITK_INFO << "START SO2 TEST ... ";
std::vector<float> CorrectSO2Result1 = { 0, 0, 0, 0, 0 };
std::vector<float> Test1 = { 0,0,0,51 };
std::vector<float> CorrectSO2Result2 = { 0, 0.5, 0, 0.5, 0 };
std::vector<float> Test2 = { 1584, 0, 0, 0 };
std::vector<float> CorrectSO2Result3 = { 0.5, 0.5, 0, 0.5, 0 };
std::vector<float> Test3 = { 0, 1536, 0, 0 };
std::vector<float> CorrectSO2Result4 = { 0.5, 0.5, 0, 0.5, 0 };
std::vector<float> Test4 = { 0, 0, 3072, 49 };
std::vector<float> CorrectSO2Result5 = { 0.5, 0.5, 0.5, 0.5, 0 };
std::vector<float> Test5 = { 1, 1, 1, 49 };
std::vector<std::vector<float>> TestList;
std::vector<std::vector<float>> ResultList;
TestList.push_back(Test1);
TestList.push_back(Test2);
TestList.push_back(Test3);
TestList.push_back(Test4);
TestList.push_back(Test5);
ResultList.push_back(CorrectSO2Result1);
ResultList.push_back(CorrectSO2Result2);
ResultList.push_back(CorrectSO2Result3);
ResultList.push_back(CorrectSO2Result4);
ResultList.push_back(CorrectSO2Result5);
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
ofstream myfile;
myfile.open("SO2TestResult.txt");
for (int k = 0; k < 5; ++k)
{
std::vector<float> SO2Settings = TestList[k];
std::vector<float> m_CorrectSO2Result = ResultList[k];
auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
m_sO2->SetInput(0, inputImage);
m_sO2->SetInput(1, inputImage);
for (int i = 0; i < SO2Settings.size(); ++i)
m_sO2->AddSO2Settings(SO2Settings[i]);
m_sO2->Update();
mitk::Image::Pointer output = m_sO2->GetOutput(0);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
for (unsigned int Pixel = 0; Pixel < inputImage->GetDimensions()[2]; ++Pixel)
{
auto Value = inputDataArray[Pixel];
myfile << "Output(Test "<< k <<") "<< Pixel << ": " << "\n" << Value << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectSO2Result[Pixel] << "\n";
CPPUNIT_ASSERT(std::abs(Value - m_CorrectSO2Result[Pixel]) < threshold);
}
}
myfile.close();
MITK_INFO << "SO2 TEST SUCCESFULL :)";
}
void tearDown() override
{
m_SpectralUnmixingFilter = nullptr;
inputImage = nullptr;
m_inputWavelengths.clear();
m_CorrectResult.clear();
MITK_INFO << "tearDown ... [DONE]";
}
};
MITK_TEST_SUITE_REGISTRATION(mitkSpectralUnmixing)
<commit_msg>pulled test on latest changes of plugin to be able to start adding test cases now.<commit_after>//*===================================================================
//The Medical Imaging Interaction Toolkit (MITK)
//Copyright (c) German Cancer Research Center,
//Division of Medical and Biological Informatics.
//All rights reserved.
//This software is distributed WITHOUT ANY WARRANTY; without
//even the implied warranty of MERCHANTABILITY or FITNESS FOR
//A PARTICULAR PURPOSE.
//See LICENSE.txt or http://www.mitk.org for details.
//===================================================================*/
#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
#include <mitkPASpectralUnmixingFilterBase.h>
#include <mitkPALinearSpectralUnmixingFilter.h>
#include <mitkPASpectralUnmixingFilterVigra.h>
#include <mitkPASpectralUnmixingFilterSimplex.h>
#include <mitkPASpectralUnmixingSO2.h>
#include <mitkImageReadAccessor.h>
class mitkSpectralUnmixingTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkSpectralUnmixingTestSuite);
MITK_TEST(testEigenSUAlgorithm);
MITK_TEST(testVigraSUAlgorithm);
//MITK_TEST(testSimplexSUAlgorithm);// --> RESULT FAILS
MITK_TEST(testSO2);
CPPUNIT_TEST_SUITE_END();
private:
mitk::pa::SpectralUnmixingFilterBase::Pointer m_SpectralUnmixingFilter;
mitk::Image::Pointer inputImage;
std::vector<int> m_inputWavelengths;
std::vector<double> m_inputWeights;
std::vector<float> m_CorrectResult;
float threshold;
public:
void setUp() override
{
MITK_INFO << "setUp ... ";
//Set empty input image:
inputImage = mitk::Image::New();
mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>();
const int NUMBER_OF_SPATIAL_DIMENSIONS = 3;
auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS];
dimensions[0] = 1;
dimensions[1] = 1;
dimensions[2] = 5;
inputImage->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions);
//Set wavelengths for unmixing:
m_inputWavelengths.push_back(750);
m_inputWavelengths.push_back(800);
m_inputWeights.push_back(50);
m_inputWeights.push_back(100);
//Set fraction of Hb and HbO2 to unmix:
float fracHb = 100;
float fracHbO2 = 300;
m_CorrectResult.push_back(fracHbO2);
m_CorrectResult.push_back(fracHb);
m_CorrectResult.push_back(fracHbO2 + 10);
m_CorrectResult.push_back(fracHb - 10);
threshold = 0.01;
//Multiply values of wavelengths (750,800,850 nm) with fractions to get pixel values:
float px1 = fracHb * 7.52 + fracHbO2 * 2.77;
float px2 = fracHb * 4.08 + fracHbO2 * 4.37;
float px3 = (fracHb - 10) * 7.52 + (fracHbO2 + 10) * 2.77;
float px4 = (fracHb - 10) * 4.08 + (fracHbO2 + 10) * 4.37;
float* data = new float[3];
data[0] = px1;
data[1] = px2;
data[2] = px3;
data[3] = px4;
data[5] = 0;
inputImage->SetImportVolume(data, mitk::Image::ImportMemoryManagementType::CopyMemory);
delete[] data;
MITK_INFO << "[DONE]";
}
void testEigenSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();
m_SpectralUnmixingFilter->Verbose(true);
m_SpectralUnmixingFilter->RelativeError(false);
m_SpectralUnmixingFilter->SetInput(inputImage);
m_SpectralUnmixingFilter->AddOutputs(2);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
ofstream myfile;
myfile.open("EigenTestResult.txt");
std::vector<mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType> m_Eigen = {
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::HOUSEHOLDERQR, /* mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::LDLT,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::LLT,*/ mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::COLPIVHOUSEHOLDERQR,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::JACOBISVD, mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVLU,
mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::FULLPIVHOUSEHOLDERQR};
for (int Algorithmidx = 0; Algorithmidx < m_Eigen.size();++Algorithmidx)
{
m_SpectralUnmixingFilter->SetAlgorithm(m_Eigen[Algorithmidx]);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Algorithmidx: " << Algorithmidx << "\n Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i]) < threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2]) < threshold);
}
}
myfile.close();
MITK_INFO << "EIGEN FILTER TEST SUCCESFULL :)";
}
void testVigraSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterVigra::New();
m_SpectralUnmixingFilter->SetInput(inputImage);
m_SpectralUnmixingFilter->AddOutputs(2);
m_SpectralUnmixingFilter->Verbose(true);
m_SpectralUnmixingFilter->RelativeError(false);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
double Weight = m_inputWeights[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
m_SpectralUnmixingFilter->AddWeight(Weight);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
std::vector<mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType> Vigra = {
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LARS, mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::GOLDFARB,
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::WEIGHTED, mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::LS/*,
mitk::pa::SpectralUnmixingFilterVigra::VigraAlgortihmType::vigratest*/};
ofstream myfile;
myfile.open("VigraTestResult.txt");
for (int Algorithmidx = 0; Algorithmidx < Vigra.size();++Algorithmidx)
{
m_SpectralUnmixingFilter->SetAlgorithm(Vigra[0]);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Algorithmidx: " << Algorithmidx << "\n Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i]) < threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2]) < threshold);
}
}
myfile.close();
MITK_INFO << "VIGRA FILTER TEST SUCCESFULL :)";
}
void testSimplexSUAlgorithm()
{
MITK_INFO << "START FILTER TEST ... ";
// Set input image
auto m_SpectralUnmixingFilter = mitk::pa::SpectralUnmixingFilterSimplex::New();
m_SpectralUnmixingFilter->SetInput(inputImage);
m_SpectralUnmixingFilter->AddOutputs(2);
m_SpectralUnmixingFilter->Verbose(true);
m_SpectralUnmixingFilter->RelativeError(false);
//Set wavelengths to filter
for (unsigned int imageIndex = 0; imageIndex < m_inputWavelengths.size(); imageIndex++)
{
unsigned int wavelength = m_inputWavelengths[imageIndex];
m_SpectralUnmixingFilter->AddWavelength(wavelength);
}
//Set Chromophores to filter
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::OXYGENATED);
m_SpectralUnmixingFilter->AddChromophore(
mitk::pa::PropertyCalculator::ChromophoreType::DEOXYGENATED);
m_SpectralUnmixingFilter->Update();
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
ofstream myfile;
myfile.open("SimplexTestResult.txt");
for (int i = 0; i < 2; ++i)
{
mitk::Image::Pointer output = m_SpectralUnmixingFilter->GetOutput(i);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
auto pixel = inputDataArray[0];
auto pixel2 = inputDataArray[1];
myfile << "Output " << i << ": " << "\n" << inputDataArray[0] << "\n" << inputDataArray[1] << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectResult[i] << "\n" << m_CorrectResult[i + 2] << "\n";
CPPUNIT_ASSERT(std::abs(pixel - m_CorrectResult[i])<threshold);
CPPUNIT_ASSERT(std::abs(pixel2 - m_CorrectResult[i + 2])<threshold);
}
myfile.close();
MITK_INFO << "SIMPLEX FILTER TEST SUCCESFULL :)";
}
void testSO2()
{
MITK_INFO << "START SO2 TEST ... ";
std::vector<float> CorrectSO2Result1 = { 0, 0, 0, 0, 0 };
std::vector<float> Test1 = { 0,0,0,51 };
std::vector<float> CorrectSO2Result2 = { 0, 0.5, 0, 0.5, 0 };
std::vector<float> Test2 = { 1584, 0, 0, 0 };
std::vector<float> CorrectSO2Result3 = { 0.5, 0.5, 0, 0.5, 0 };
std::vector<float> Test3 = { 0, 1536, 0, 0 };
std::vector<float> CorrectSO2Result4 = { 0.5, 0.5, 0, 0.5, 0 };
std::vector<float> Test4 = { 0, 0, 3072, 49 };
std::vector<float> CorrectSO2Result5 = { 0.5, 0.5, 0.5, 0.5, 0 };
std::vector<float> Test5 = { 1, 1, 1, 49 };
std::vector<std::vector<float>> TestList;
std::vector<std::vector<float>> ResultList;
TestList.push_back(Test1);
TestList.push_back(Test2);
TestList.push_back(Test3);
TestList.push_back(Test4);
TestList.push_back(Test5);
ResultList.push_back(CorrectSO2Result1);
ResultList.push_back(CorrectSO2Result2);
ResultList.push_back(CorrectSO2Result3);
ResultList.push_back(CorrectSO2Result4);
ResultList.push_back(CorrectSO2Result5);
/*For printed pixel values and results look at: [...]\mitk-superbuild\MITK-build\Modules\PhotoacousticsLib\test\*/
ofstream myfile;
myfile.open("SO2TestResult.txt");
for (int k = 0; k < 5; ++k)
{
std::vector<float> SO2Settings = TestList[k];
std::vector<float> m_CorrectSO2Result = ResultList[k];
auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
m_sO2->SetInput(0, inputImage);
m_sO2->SetInput(1, inputImage);
for (int i = 0; i < SO2Settings.size(); ++i)
m_sO2->AddSO2Settings(SO2Settings[i]);
m_sO2->Update();
mitk::Image::Pointer output = m_sO2->GetOutput(0);
mitk::ImageReadAccessor readAccess(output);
const float* inputDataArray = ((const float*)readAccess.GetData());
for (unsigned int Pixel = 0; Pixel < inputImage->GetDimensions()[2]; ++Pixel)
{
auto Value = inputDataArray[Pixel];
myfile << "Output(Test "<< k <<") "<< Pixel << ": " << "\n" << Value << "\n";
myfile << "Correct Result: " << "\n" << m_CorrectSO2Result[Pixel] << "\n";
CPPUNIT_ASSERT(std::abs(Value - m_CorrectSO2Result[Pixel]) < threshold);
}
}
myfile.close();
MITK_INFO << "SO2 TEST SUCCESFULL :)";
}
void tearDown() override
{
m_SpectralUnmixingFilter = nullptr;
inputImage = nullptr;
m_inputWavelengths.clear();
m_CorrectResult.clear();
MITK_INFO << "tearDown ... [DONE]";
}
};
MITK_TEST_SUITE_REGISTRATION(mitkSpectralUnmixing)
<|endoftext|> |
<commit_before>#include "aten.h"
#include "atenscene.h"
#include "FbxImporter.h"
#include "MdlExporter.h"
#include "MtrlExporter.h"
#include "AnmExporter.h"
#include <cmdline.h>
#include <imgui.h>
static const int WIDTH = 1280;
static const int HEIGHT = 720;
static const char* TITLE = "FbxConverter";
struct Options {
std::string input;
std::string output;
std::string inputBasepath;
std::string inputFilename;
} g_opt;
aten::deformable g_mdl;
aten::DeformAnimation g_anm;
aten::Timeline g_timeline;
static aten::PinholeCamera g_camera;
static bool g_isCameraDirty = false;
static uint32_t g_lodTriCnt = 0;
static bool g_isWireFrame = true;
static bool g_isUpdateBuffer = false;
static bool g_displayLOD = true;
static bool g_willShowGUI = true;
static bool g_isMouseLBtnDown = false;
static bool g_isMouseRBtnDown = false;
static int g_prevX = 0;
static int g_prevY = 0;
void onRun()
{
if (g_isCameraDirty) {
g_camera.update();
auto camparam = g_camera.param();
camparam.znear = real(0.1);
camparam.zfar = real(10000.0);
g_isCameraDirty = false;
}
g_timeline.advance(0);
g_mdl.update(aten::mat4(), &g_anm, g_timeline.getTime());
aten::DeformableRenderer::render(&g_camera, &g_mdl);
}
void onClose()
{
}
void onMouseBtn(bool left, bool press, int x, int y)
{
g_isMouseLBtnDown = false;
g_isMouseRBtnDown = false;
if (press) {
g_prevX = x;
g_prevY = y;
g_isMouseLBtnDown = left;
g_isMouseRBtnDown = !left;
}
}
void onMouseMove(int x, int y)
{
if (g_isMouseLBtnDown) {
aten::CameraOperator::rotate(
g_camera,
WIDTH, HEIGHT,
g_prevX, g_prevY,
x, y);
g_isCameraDirty = true;
}
else if (g_isMouseRBtnDown) {
aten::CameraOperator::move(
g_camera,
g_prevX, g_prevY,
x, y,
real(0.001));
g_isCameraDirty = true;
}
g_prevX = x;
g_prevY = y;
}
void onMouseWheel(int delta)
{
aten::CameraOperator::dolly(g_camera, delta * real(0.1));
g_isCameraDirty = true;
}
void onKey(bool press, aten::Key key)
{
static const real offset = real(5);
if (press) {
if (key == aten::Key::Key_F1) {
g_willShowGUI = !g_willShowGUI;
return;
}
}
if (press) {
switch (key) {
case aten::Key::Key_W:
case aten::Key::Key_UP:
aten::CameraOperator::moveForward(g_camera, offset);
break;
case aten::Key::Key_S:
case aten::Key::Key_DOWN:
aten::CameraOperator::moveForward(g_camera, -offset);
break;
case aten::Key::Key_D:
case aten::Key::Key_RIGHT:
aten::CameraOperator::moveRight(g_camera, offset);
break;
case aten::Key::Key_A:
case aten::Key::Key_LEFT:
aten::CameraOperator::moveRight(g_camera, -offset);
break;
case aten::Key::Key_Z:
aten::CameraOperator::moveUp(g_camera, offset);
break;
case aten::Key::Key_X:
aten::CameraOperator::moveUp(g_camera, -offset);
break;
default:
break;
}
g_isCameraDirty = true;
}
}
bool parseOption(
int argc, char* argv[],
cmdline::parser& cmd,
Options& opt)
{
{
cmd.add<std::string>("input", 'i', "input filename", true);
cmd.add<std::string>("output", 'o', "output filename base", false, "result");
cmd.add<std::string>("help", '?', "print usage", false);
}
bool isCmdOk = cmd.parse(argc, argv);
if (cmd.exist("help")) {
std::cerr << cmd.usage();
return false;
}
if (!isCmdOk) {
std::cerr << cmd.error() << std::endl << cmd.usage();
return false;
}
if (cmd.exist("input")) {
opt.input = cmd.get<std::string>("input");
}
else {
std::cerr << cmd.error() << std::endl << cmd.usage();
return false;
}
if (cmd.exist("output")) {
opt.output = cmd.get<std::string>("output");
}
else {
// TODO
opt.output = "result.sbvh";
}
return true;
}
int main(int argc, char* argv[])
{
aten::window::SetCurrentDirectoryFromExe();
#if 0
{
aten::FbxImporter importer;
importer.setIgnoreTexIdx(0);
importer.open("../../asset/unitychan/unitychan.fbx");
MdlExporter::exportMdl(48, "unitychan.mdl", &importer);
MtrlExporter::exportMaterial("unitychan_mtrl.xml", &importer);
}
#endif
#if 0
{
aten::FbxImporter importer;
importer.open("../../asset/unitychan/unitychan_WAIT00.fbx", true);
importer.readBaseModel("../../asset/unitychan/unitychan.fbx");
AnmExporter::exportAnm("unitychan.anm", 0, &importer);
}
#endif
aten::window::init(
WIDTH, HEIGHT,
TITLE,
onClose,
onMouseBtn,
onMouseMove,
onMouseWheel,
onKey);
aten::DeformableRenderer::init(
WIDTH, HEIGHT,
"../shader/skinning_vs.glsl",
"../shader/skinning_fs.glsl");
g_mdl.read("unitychan.mdl");
g_anm.read("unitychan.anm");
g_timeline.init(g_anm.getDesc().time, real(0));
g_timeline.enableLoop(true);
g_timeline.start();
aten::ImageLoader::setBasePath("../../asset/unitychan/Texture");
aten::MaterialLoader::load("unitychan_mtrl.xml");
auto textures = aten::texture::getTextures();
for (auto tex : textures) {
tex->initAsGLTexture();
}
// TODO
aten::vec3 pos(0, 1, 10);
aten::vec3 at(0, 1, 1);
real vfov = real(45);
g_camera.init(
pos,
at,
aten::vec3(0, 1, 0),
vfov,
WIDTH, HEIGHT);
aten::window::run(onRun);
aten::window::terminate();
return 1;
}
<commit_msg>Implement deform animation.<commit_after>#include "aten.h"
#include "atenscene.h"
#include "FbxImporter.h"
#include "MdlExporter.h"
#include "MtrlExporter.h"
#include "AnmExporter.h"
#include <cmdline.h>
#include <imgui.h>
static const int WIDTH = 1280;
static const int HEIGHT = 720;
static const char* TITLE = "FbxConverter";
struct Options {
std::string input;
std::string output;
std::string inputBasepath;
std::string inputFilename;
} g_opt;
aten::deformable g_mdl;
aten::DeformAnimation g_anm;
aten::Timeline g_timeline;
static aten::PinholeCamera g_camera;
static bool g_isCameraDirty = false;
static uint32_t g_lodTriCnt = 0;
static bool g_isWireFrame = true;
static bool g_isUpdateBuffer = false;
static bool g_displayLOD = true;
static bool g_willShowGUI = true;
static bool g_isMouseLBtnDown = false;
static bool g_isMouseRBtnDown = false;
static int g_prevX = 0;
static int g_prevY = 0;
void onRun()
{
if (g_isCameraDirty) {
g_camera.update();
auto camparam = g_camera.param();
camparam.znear = real(0.1);
camparam.zfar = real(10000.0);
g_isCameraDirty = false;
}
g_timeline.advance(1.0f / 60.0f);
g_mdl.update(aten::mat4(), &g_anm, g_timeline.getTime());
aten::DeformableRenderer::render(&g_camera, &g_mdl);
}
void onClose()
{
}
void onMouseBtn(bool left, bool press, int x, int y)
{
g_isMouseLBtnDown = false;
g_isMouseRBtnDown = false;
if (press) {
g_prevX = x;
g_prevY = y;
g_isMouseLBtnDown = left;
g_isMouseRBtnDown = !left;
}
}
void onMouseMove(int x, int y)
{
if (g_isMouseLBtnDown) {
aten::CameraOperator::rotate(
g_camera,
WIDTH, HEIGHT,
g_prevX, g_prevY,
x, y);
g_isCameraDirty = true;
}
else if (g_isMouseRBtnDown) {
aten::CameraOperator::move(
g_camera,
g_prevX, g_prevY,
x, y,
real(0.001));
g_isCameraDirty = true;
}
g_prevX = x;
g_prevY = y;
}
void onMouseWheel(int delta)
{
aten::CameraOperator::dolly(g_camera, delta * real(0.1));
g_isCameraDirty = true;
}
void onKey(bool press, aten::Key key)
{
static const real offset = real(5);
if (press) {
if (key == aten::Key::Key_F1) {
g_willShowGUI = !g_willShowGUI;
return;
}
}
if (press) {
switch (key) {
case aten::Key::Key_W:
case aten::Key::Key_UP:
aten::CameraOperator::moveForward(g_camera, offset);
break;
case aten::Key::Key_S:
case aten::Key::Key_DOWN:
aten::CameraOperator::moveForward(g_camera, -offset);
break;
case aten::Key::Key_D:
case aten::Key::Key_RIGHT:
aten::CameraOperator::moveRight(g_camera, offset);
break;
case aten::Key::Key_A:
case aten::Key::Key_LEFT:
aten::CameraOperator::moveRight(g_camera, -offset);
break;
case aten::Key::Key_Z:
aten::CameraOperator::moveUp(g_camera, offset);
break;
case aten::Key::Key_X:
aten::CameraOperator::moveUp(g_camera, -offset);
break;
default:
break;
}
g_isCameraDirty = true;
}
}
bool parseOption(
int argc, char* argv[],
cmdline::parser& cmd,
Options& opt)
{
{
cmd.add<std::string>("input", 'i', "input filename", true);
cmd.add<std::string>("output", 'o', "output filename base", false, "result");
cmd.add<std::string>("help", '?', "print usage", false);
}
bool isCmdOk = cmd.parse(argc, argv);
if (cmd.exist("help")) {
std::cerr << cmd.usage();
return false;
}
if (!isCmdOk) {
std::cerr << cmd.error() << std::endl << cmd.usage();
return false;
}
if (cmd.exist("input")) {
opt.input = cmd.get<std::string>("input");
}
else {
std::cerr << cmd.error() << std::endl << cmd.usage();
return false;
}
if (cmd.exist("output")) {
opt.output = cmd.get<std::string>("output");
}
else {
// TODO
opt.output = "result.sbvh";
}
return true;
}
int main(int argc, char* argv[])
{
aten::window::SetCurrentDirectoryFromExe();
#if 0
{
aten::FbxImporter importer;
importer.setIgnoreTexIdx(0);
importer.open("../../asset/unitychan/unitychan.fbx");
MdlExporter::exportMdl(48, "unitychan.mdl", &importer);
MtrlExporter::exportMaterial("unitychan_mtrl.xml", &importer);
}
#endif
#if 0
{
aten::FbxImporter importer;
importer.open("../../asset/unitychan/unitychan_WAIT01.fbx", true);
importer.readBaseModel("../../asset/unitychan/unitychan.fbx");
AnmExporter::exportAnm("unitychan.anm", 0, &importer);
}
#endif
aten::window::init(
WIDTH, HEIGHT,
TITLE,
onClose,
onMouseBtn,
onMouseMove,
onMouseWheel,
onKey);
aten::DeformableRenderer::init(
WIDTH, HEIGHT,
"../shader/skinning_vs.glsl",
"../shader/skinning_fs.glsl");
g_mdl.read("unitychan.mdl");
g_anm.read("unitychan.anm");
g_timeline.init(g_anm.getDesc().time, real(0));
g_timeline.enableLoop(true);
g_timeline.start();
aten::ImageLoader::setBasePath("../../asset/unitychan/Texture");
aten::MaterialLoader::load("unitychan_mtrl.xml");
auto textures = aten::texture::getTextures();
for (auto tex : textures) {
tex->initAsGLTexture();
}
// TODO
aten::vec3 pos(0, 1, 10);
aten::vec3 at(0, 1, 1);
real vfov = real(45);
g_camera.init(
pos,
at,
aten::vec3(0, 1, 0),
vfov,
WIDTH, HEIGHT);
aten::window::run(onRun);
aten::window::terminate();
return 1;
}
<|endoftext|> |
<commit_before>#include <legui/ProgressBar.h>
#include <legui/Config.h>
namespace legui
{
ProgressBar::ProgressBar(Container *parent)
: Widget(parent)
{
m_leftShape = new sf::RectangleShape();
m_rightShape = new sf::RectangleShape();
m_leftShape->setOutlineThickness(Config::getFloat("PROGRESSBAR_OUTLINE_THICKNESS"));
m_rightShape->setOutlineThickness(Config::getFloat("PROGRESSBAR_OUTLINE_THICKNESS"));
m_leftShape->setOutlineColor(Config::getColor("PROGRESSBAR_OUTLINE_COLOR"));
m_rightShape->setOutlineColor(Config::getColor("PROGRESSBAR_OUTLINE_COLOR"));
m_leftShape->setFillColor(Config::getColor("PROGRESSBAR_FILL_COLOR"));
m_rightShape->setFillColor(Config::getColor("PROGRESSBAR_FILL_COLOR"));
}
ProgressBar::~ProgressBar()
{
delete m_leftShape;
delete m_rightShape;
}
void ProgressBar::setBoundingBox(const sf::FloatRect &box)
{
Widget::setBoundingBox(box);
this->updateSize();
}
void ProgressBar::updateSize()
{
m_leftShape->setSize(sf::Vector2f(m_boundingBox.width / 100 * m_percent, m_boundingBox.height));
m_leftShape->setPosition(sf::Vector2f(m_boundingBox.left, m_boundingBox.top));
m_rightShape->setSize(sf::Vector2f(m_boundingBox.width - (m_boundingBox.width / 100 * m_percent), m_boundingBox.height));
m_rightShape->setPosition(sf::Vector2f(m_boundingBox.left + m_leftShape->getSize().x, m_boundingBox.top));
}
void ProgressBar::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(*m_leftShape, states);
target.draw(*m_rightShape, states);
}
void ProgressBar::setPercent(float percent)
{
m_percent = percent;
this->updateSize();
}
float ProgressBar::getPercent()
{
return m_percent;
}
}
<commit_msg>Added a default value of 0 for the percent in the progress bar.<commit_after>#include <legui/ProgressBar.h>
#include <legui/Config.h>
namespace legui
{
ProgressBar::ProgressBar(Container *parent)
: Widget(parent)
{
m_percent = 0;
m_leftShape = new sf::RectangleShape();
m_rightShape = new sf::RectangleShape();
m_leftShape->setOutlineThickness(Config::getFloat("PROGRESSBAR_OUTLINE_THICKNESS"));
m_rightShape->setOutlineThickness(Config::getFloat("PROGRESSBAR_OUTLINE_THICKNESS"));
m_leftShape->setOutlineColor(Config::getColor("PROGRESSBAR_OUTLINE_COLOR"));
m_rightShape->setOutlineColor(Config::getColor("PROGRESSBAR_OUTLINE_COLOR"));
m_leftShape->setFillColor(Config::getColor("PROGRESSBAR_FILL_COLOR"));
m_rightShape->setFillColor(Config::getColor("PROGRESSBAR_FILL_COLOR"));
}
ProgressBar::~ProgressBar()
{
delete m_leftShape;
delete m_rightShape;
}
void ProgressBar::setBoundingBox(const sf::FloatRect &box)
{
Widget::setBoundingBox(box);
this->updateSize();
}
void ProgressBar::updateSize()
{
m_leftShape->setSize(sf::Vector2f(m_boundingBox.width / 100 * m_percent, m_boundingBox.height));
m_leftShape->setPosition(sf::Vector2f(m_boundingBox.left, m_boundingBox.top));
m_rightShape->setSize(sf::Vector2f(m_boundingBox.width - (m_boundingBox.width / 100 * m_percent), m_boundingBox.height));
m_rightShape->setPosition(sf::Vector2f(m_boundingBox.left + m_leftShape->getSize().x, m_boundingBox.top));
}
void ProgressBar::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(*m_leftShape, states);
target.draw(*m_rightShape, states);
}
void ProgressBar::setPercent(float percent)
{
m_percent = percent;
this->updateSize();
}
float ProgressBar::getPercent()
{
return m_percent;
}
}
<|endoftext|> |
<commit_before>#include "RenderformCreator.hpp"
#include <algorithm>
RenderformCreator::RenderformCreator(ModelStore* modelStore, MaterialStore* matStore)
: mMaterialStore(matStore)
, mModelStore(modelStore)
{
}
void RenderformCreator::Update(const Scene::Updates& sceneUpdates)
{
ParseAddNodeUpdates(sceneUpdates.newNodes);
ParseDeleteNodeUpdates(sceneUpdates.deletedNodes);
// Update model transformations
//for (const auto& p : mRenderform)
//{
// for (auto& mesh : p.second.meshes)
// mesh.transformation = mesh.node->GetTransformation();
//}
}
const RenderformCreator::Renderform& RenderformCreator::GetRenderform() const
{
return mRenderform;
}
//--------------------------------------------------
// Private functions
//--------------------------------------------------
void RenderformCreator::ParseAddNodeUpdates(const std::vector<SceneNode*>& added)
{
for (SceneNode* node : added)
{
// Get the transformation
Transform& transformation = node->GetTransformation();
// Get the model
const std::string& modelName = node->GetModel();
ModelDescription* mdl = (*mModelStore)[modelName];
// Get material names per mesh
const auto& materials = node->GetMaterials();
for (const auto& mesh : mdl->meshes)
{
// Get material name
std::string matName = materials[mesh.meshIndex];
// Find if material already exists in renderform
auto matIt = mRenderform.find(matName);
// Set its parameters if it doesn't exist
if (matIt == std::end(mRenderform))
{
// Get the material description
MaterialDescription* matDesc = (*mMaterialStore)[matName];
// Create new material
auto& material = mRenderform[matName];
// Diffuse
material.diffTexId = matDesc->material.UsesDiffuseTexture() ? matDesc->material.GetDiffuseTexture() : 0;
// Specular
material.specTexId = matDesc->material.UsesSpecularTexture() ? matDesc->material.GetSpecularTexture() : 0;
// Normal map
material.useNormalMap = matDesc->material.UsesNormalMapTexture();
material.nmapTexId = material.useNormalMap ? matDesc->material.GetNormalMapTexture() : 0;
}
// Create new renderform mesh and append it to material
mRenderform[matName].meshes.push_back(
{ node
, modelName
, &transformation
, mesh.vaoId
, mesh.eboId
, mesh.numIndices
});
}
}
}
void RenderformCreator::ParseDeleteNodeUpdates(const std::vector<std::unique_ptr<SceneNode>>& deleted)
{
for (auto& uptr : deleted)
{
SceneNode* node = uptr.get();
// Get model name
const std::string& modelName = node->GetModel();
// Erase this model's meshes from renderform
for (auto& p : mRenderform)
{
auto& meshes = p.second.meshes;
const auto meshIt = std::find_if(std::begin(meshes), std::end(meshes),
[&modelName](const Mesh& mesh) -> bool
{
return modelName == mesh.modelName;
});
if (meshIt != std::end(meshes))
meshes.erase(meshIt);
}
}
}
<commit_msg>Removed redundunt comments in RenderformCreator<commit_after>#include "RenderformCreator.hpp"
#include <algorithm>
RenderformCreator::RenderformCreator(ModelStore* modelStore, MaterialStore* matStore)
: mMaterialStore(matStore)
, mModelStore(modelStore)
{
}
void RenderformCreator::Update(const Scene::Updates& sceneUpdates)
{
ParseAddNodeUpdates(sceneUpdates.newNodes);
ParseDeleteNodeUpdates(sceneUpdates.deletedNodes);
}
const RenderformCreator::Renderform& RenderformCreator::GetRenderform() const
{
return mRenderform;
}
//--------------------------------------------------
// Private functions
//--------------------------------------------------
void RenderformCreator::ParseAddNodeUpdates(const std::vector<SceneNode*>& added)
{
for (SceneNode* node : added)
{
// Get the transformation
Transform& transformation = node->GetTransformation();
// Get the model
const std::string& modelName = node->GetModel();
ModelDescription* mdl = (*mModelStore)[modelName];
// Get material names per mesh
const auto& materials = node->GetMaterials();
for (const auto& mesh : mdl->meshes)
{
// Get material name
std::string matName = materials[mesh.meshIndex];
// Find if material already exists in renderform
auto matIt = mRenderform.find(matName);
// Set its parameters if it doesn't exist
if (matIt == std::end(mRenderform))
{
// Get the material description
MaterialDescription* matDesc = (*mMaterialStore)[matName];
// Create new material
auto& material = mRenderform[matName];
// Diffuse
material.diffTexId = matDesc->material.UsesDiffuseTexture() ? matDesc->material.GetDiffuseTexture() : 0;
// Specular
material.specTexId = matDesc->material.UsesSpecularTexture() ? matDesc->material.GetSpecularTexture() : 0;
// Normal map
material.useNormalMap = matDesc->material.UsesNormalMapTexture();
material.nmapTexId = material.useNormalMap ? matDesc->material.GetNormalMapTexture() : 0;
}
// Create new renderform mesh and append it to material
mRenderform[matName].meshes.push_back(
{ node
, modelName
, &transformation
, mesh.vaoId
, mesh.eboId
, mesh.numIndices
});
}
}
}
void RenderformCreator::ParseDeleteNodeUpdates(const std::vector<std::unique_ptr<SceneNode>>& deleted)
{
for (auto& uptr : deleted)
{
SceneNode* node = uptr.get();
// Get model name
const std::string& modelName = node->GetModel();
// Erase this model's meshes from renderform
for (auto& p : mRenderform)
{
auto& meshes = p.second.meshes;
const auto meshIt = std::find_if(std::begin(meshes), std::end(meshes),
[&modelName](const Mesh& mesh) -> bool
{
return modelName == mesh.modelName;
});
if (meshIt != std::end(meshes))
meshes.erase(meshIt);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE source in the root of the Project.
#include <boost/python.hpp>
#include <boost/optional.hpp>
#include <nix.hpp>
#include <accessors.hpp>
#include <transmorgify.hpp>
//we want only the newest and freshest API
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <numpy/ndarrayobject.h>
#include <PyEntity.hpp>
#include <stdexcept>
using namespace nix;
using namespace boost::python;
namespace nixpy {
// Label
void setLabel(DataArray& da, const boost::optional<std::string>& label) {
if (label)
da.label(*label);
else
da.label(boost::none);
}
// Unit
void setUnit(DataArray& da, const boost::optional<std::string> &unit) {
if (unit)
da.unit(*unit);
else
da.unit(boost::none);
}
// Expansion origin
void setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) {
if (eo)
da.expansionOrigin(*eo);
else
da.expansionOrigin(boost::none);
}
// Polynom coefficients
void setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) {
if (!pc.empty())
da.polynomCoefficients(pc);
else
da.polynomCoefficients(boost::none);
}
// Data
std::vector<double> getData(DataArray& da) {
std::vector<double> data;
da.getData(data);
return data;
}
void setData(DataArray& da, const std::vector<double>& data) {
if (!data.empty())
da.setData(data);
else
// TODO How do I remove data?
da.dataExtent(NDSize());
}
static nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype)
{
if (dtype == nullptr) {
return nix::DataType::Nothing;
}
if (dtype->byteorder != '=' && dtype->byteorder != '|') {
//TODO: Handle case where specified byteorder *is*
//the native byteorder (via BOOST_BIG_ENDIAN macros)
return nix::DataType::Nothing;
}
switch (dtype->kind) {
case 'u':
switch (dtype->elsize) {
case 1: return nix::DataType::UInt8;
case 2: return nix::DataType::UInt16;
case 4: return nix::DataType::UInt32;
case 8: return nix::DataType::UInt64;
}
break;
case 'i':
switch (dtype->elsize) {
case 1: return nix::DataType::Int8;
case 2: return nix::DataType::Int16;
case 4: return nix::DataType::Int32;
case 8: return nix::DataType::Int64;
}
break;
case 'f':
switch (dtype->elsize) {
case 4: return nix::DataType::Float;
case 8: return nix::DataType::Double;
}
break;
default:
break;
}
return nix::DataType::Nothing;
}
static void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) {
PyArray_Descr* py_dtype = nullptr;
if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) {
throw std::invalid_argument("Invalid dtype");
}
nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype);
if (nix_dtype == nix::DataType::Nothing) {
throw std::invalid_argument("Unsupported dtype");
}
da.createData(nix_dtype, shape);
if (data != Py_None && PyArray_Check(data)) {
PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data);
nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array));
if (nix_dtype == nix::DataType::Nothing) {
throw std::invalid_argument("Unsupported dtype for data");
}
if (! PyArray_CHKFLAGS(array, NPY_ARRAY_CARRAY_RO)) {
throw std::invalid_argument("data must be c-contiguous and aligned");
}
int array_rank = PyArray_NDIM(array);
npy_intp *array_shape = PyArray_SHAPE(array);
nix::NDSize data_shape(array_rank);
for (int i = 0; i < array_rank; i++) {
data_shape[i] = array_shape[i];
}
nix::NDSize offset(array_rank, 0);
da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset);
}
Py_DECREF(py_dtype);
}
// Dimensions
PyObject* getDimension(const DataArray& da, size_t index) {
Dimension dim = da.getDimension(index);
SetDimension set;
RangeDimension range;
SampledDimension sample;
DimensionType type = dim.dimensionType();
switch(type) {
case DimensionType::Set:
set = dim;
return incref(object(set).ptr());
case DimensionType::Range:
range = dim;
return incref(object(range).ptr());
case DimensionType::Sample:
sample = dim;
return incref(object(sample).ptr());
default:
Py_RETURN_NONE;
}
}
void PyDataArray::do_export() {
// For numpy to work
import_array();
PyEntityWithSources<base::IDataArray>::do_export("DataArray");
class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>("DataArray")
.add_property("label",
OPT_GETTER(std::string, DataArray, label),
setLabel,
doc::data_array_label)
.add_property("unit",
OPT_GETTER(std::string, DataArray, unit),
setUnit,
doc::data_array_unit)
.add_property("expansion_origin",
OPT_GETTER(double, DataArray, expansionOrigin),
setExpansionOrigin,
doc::data_array_expansion_origin)
.add_property("polynom_coefficients",
GETTER(std::vector<double>, DataArray, polynomCoefficients),
setPolynomCoefficients,
doc::data_array_polynom_coefficients)
.add_property("data_extent",
GETTER(NDSize, DataArray, dataExtent),
SETTER(NDSize&, DataArray, dataExtent),
doc::data_array_data_extent)
// Data
.add_property("data_type", &DataArray::dataType,
doc::data_array_data_type)
.add_property("data", getData, setData,
doc::data_array_data)
.def("has_data", &DataArray::hasData,
doc::data_array_has_data)
.def("_create_data", createData)
// Dimensions
.def("create_set_dimension", &DataArray::createSetDimension,
doc::data_array_create_set_dimension)
.def("create_sampled_dimension", &DataArray::createSampledDimension,
doc::data_array_create_sampled_dimension)
.def("create_reange_dimension", &DataArray::createRangeDimension,
doc::data_array_create_range_dimension)
.def("append_set_dimension", &DataArray::appendSetDimension,
doc::data_array_append_set_dimension)
.def("append_sampled_dimension", &DataArray::appendSampledDimension,
doc::data_array_append_sampled_dimension)
.def("append_range_dimension", &DataArray::appendRangeDimension,
doc::data_array_append_range_dimension)
.def("_dimension_count", &DataArray::dimensionCount)
.def("_delete_dimension_by_pos", &DataArray::deleteDimension)
.def("_get_dimension_by_pos", getDimension)
// Other
.def("__str__", &toStr<DataArray>)
.def("__repr__", &toStr<DataArray>)
;
to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>();
vector_transmogrify<DataArray>::register_from_python();
to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>();
}
}
<commit_msg>PyDataArray:_create_data: Extract array writing as writeData<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE source in the root of the Project.
#include <boost/python.hpp>
#include <boost/optional.hpp>
#include <nix.hpp>
#include <accessors.hpp>
#include <transmorgify.hpp>
//we want only the newest and freshest API
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <numpy/ndarrayobject.h>
#include <PyEntity.hpp>
#include <stdexcept>
using namespace nix;
using namespace boost::python;
namespace nixpy {
// Label
void setLabel(DataArray& da, const boost::optional<std::string>& label) {
if (label)
da.label(*label);
else
da.label(boost::none);
}
// Unit
void setUnit(DataArray& da, const boost::optional<std::string> &unit) {
if (unit)
da.unit(*unit);
else
da.unit(boost::none);
}
// Expansion origin
void setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) {
if (eo)
da.expansionOrigin(*eo);
else
da.expansionOrigin(boost::none);
}
// Polynom coefficients
void setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) {
if (!pc.empty())
da.polynomCoefficients(pc);
else
da.polynomCoefficients(boost::none);
}
// Data
std::vector<double> getData(DataArray& da) {
std::vector<double> data;
da.getData(data);
return data;
}
void setData(DataArray& da, const std::vector<double>& data) {
if (!data.empty())
da.setData(data);
else
// TODO How do I remove data?
da.dataExtent(NDSize());
}
static nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype)
{
if (dtype == nullptr) {
return nix::DataType::Nothing;
}
if (dtype->byteorder != '=' && dtype->byteorder != '|') {
//TODO: Handle case where specified byteorder *is*
//the native byteorder (via BOOST_BIG_ENDIAN macros)
return nix::DataType::Nothing;
}
switch (dtype->kind) {
case 'u':
switch (dtype->elsize) {
case 1: return nix::DataType::UInt8;
case 2: return nix::DataType::UInt16;
case 4: return nix::DataType::UInt32;
case 8: return nix::DataType::UInt64;
}
break;
case 'i':
switch (dtype->elsize) {
case 1: return nix::DataType::Int8;
case 2: return nix::DataType::Int16;
case 4: return nix::DataType::Int32;
case 8: return nix::DataType::Int64;
}
break;
case 'f':
switch (dtype->elsize) {
case 4: return nix::DataType::Float;
case 8: return nix::DataType::Double;
}
break;
default:
break;
}
return nix::DataType::Nothing;
}
static void writeData(DataArray& da, PyObject *data) {
if (! PyArray_Check(data)) {
throw std::invalid_argument("Data not a NumPy array");
}
PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data);
nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array));
if (nix_dtype == nix::DataType::Nothing) {
throw std::invalid_argument("Unsupported dtype for data");
}
if (! PyArray_CHKFLAGS(array, NPY_ARRAY_CARRAY_RO)) {
throw std::invalid_argument("data must be c-contiguous and aligned");
}
int array_rank = PyArray_NDIM(array);
npy_intp *array_shape = PyArray_SHAPE(array);
nix::NDSize data_shape(array_rank);
for (int i = 0; i < array_rank; i++) {
data_shape[i] = array_shape[i];
}
nix::NDSize offset(array_rank, 0);
da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset);
}
static void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) {
PyArray_Descr* py_dtype = nullptr;
if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) {
throw std::invalid_argument("Invalid dtype");
}
nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype);
if (nix_dtype == nix::DataType::Nothing) {
throw std::invalid_argument("Unsupported dtype");
}
da.createData(nix_dtype, shape);
if (data != Py_None) {
writeData(da, data);
}
Py_DECREF(py_dtype);
}
// Dimensions
PyObject* getDimension(const DataArray& da, size_t index) {
Dimension dim = da.getDimension(index);
SetDimension set;
RangeDimension range;
SampledDimension sample;
DimensionType type = dim.dimensionType();
switch(type) {
case DimensionType::Set:
set = dim;
return incref(object(set).ptr());
case DimensionType::Range:
range = dim;
return incref(object(range).ptr());
case DimensionType::Sample:
sample = dim;
return incref(object(sample).ptr());
default:
Py_RETURN_NONE;
}
}
void PyDataArray::do_export() {
// For numpy to work
import_array();
PyEntityWithSources<base::IDataArray>::do_export("DataArray");
class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>("DataArray")
.add_property("label",
OPT_GETTER(std::string, DataArray, label),
setLabel,
doc::data_array_label)
.add_property("unit",
OPT_GETTER(std::string, DataArray, unit),
setUnit,
doc::data_array_unit)
.add_property("expansion_origin",
OPT_GETTER(double, DataArray, expansionOrigin),
setExpansionOrigin,
doc::data_array_expansion_origin)
.add_property("polynom_coefficients",
GETTER(std::vector<double>, DataArray, polynomCoefficients),
setPolynomCoefficients,
doc::data_array_polynom_coefficients)
.add_property("data_extent",
GETTER(NDSize, DataArray, dataExtent),
SETTER(NDSize&, DataArray, dataExtent),
doc::data_array_data_extent)
// Data
.add_property("data_type", &DataArray::dataType,
doc::data_array_data_type)
.add_property("data", getData, setData,
doc::data_array_data)
.def("has_data", &DataArray::hasData,
doc::data_array_has_data)
.def("_create_data", createData)
// Dimensions
.def("create_set_dimension", &DataArray::createSetDimension,
doc::data_array_create_set_dimension)
.def("create_sampled_dimension", &DataArray::createSampledDimension,
doc::data_array_create_sampled_dimension)
.def("create_reange_dimension", &DataArray::createRangeDimension,
doc::data_array_create_range_dimension)
.def("append_set_dimension", &DataArray::appendSetDimension,
doc::data_array_append_set_dimension)
.def("append_sampled_dimension", &DataArray::appendSampledDimension,
doc::data_array_append_sampled_dimension)
.def("append_range_dimension", &DataArray::appendRangeDimension,
doc::data_array_append_range_dimension)
.def("_dimension_count", &DataArray::dimensionCount)
.def("_delete_dimension_by_pos", &DataArray::deleteDimension)
.def("_get_dimension_by_pos", getDimension)
// Other
.def("__str__", &toStr<DataArray>)
.def("__repr__", &toStr<DataArray>)
;
to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>();
vector_transmogrify<DataArray>::register_from_python();
to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>();
}
}
<|endoftext|> |
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
//set_MD49_speed(speed_l,speed_r);
last_speed_l=speed_l;
last_speed_r=speed_r;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
// Set nodes looprate 10Hz
// ***********************
ros::Rate loop_rate(10);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
try{ device.open("/dev/ttyAMA0", 38400); }
catch(cereal::Exception& e)
{
ROS_FATAL("Failed to open the serial port!!!");
ROS_BREAK();
}
ROS_INFO("The serial port is opened.");
while(n.ok())
{
// Read encoder and other data from MD49
// (data is read from serial_controller_node
// and avaiable through md49_data.txt)
// *****************************************
read_MD49_Data();
// Publish encoder values to topic /encoders (custom message)
// **********************************************************
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Publish MD49 data to topic /md49data (custom message)
// *****************************************************
md49data.speed_l = reply[8];
md49data.speed_r = reply[9];
md49data.volt = reply[10];
md49data.current_l = reply[11];
md49data.current_r = reply[12];
md49data.error = reply[13];
md49data.acceleration = reply[14];
md49data.mode = reply[15];
md49data.regulator = reply[16];
md49data.timeout = reply[17];
md49data_pub.publish(md49data);
// ****
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Send 'R' over the serial port
device.write("R");
// Get the reply, the last value is the timeout in ms
try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
catch(cereal::TimeoutException& e)
{
ROS_ERROR("Timeout on serialport! No data read");
}
//ROS_INFO("Received MD49 data");
// Put toghether new encodervalues
// *******************************
EncoderL = reply[0] << 24; // Put together first encoder value
EncoderL |= (reply[1] << 16);
EncoderL |= (reply[2] << 8);
EncoderL |= (reply[3]);
EncoderR = reply[4] << 24; // Put together second encoder value
EncoderR |= (reply[5] << 16);
EncoderR |= (reply[6] << 8);
EncoderR |= (reply[7]);
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
/*
char buffer[33];
ofstream myfile;
myfile.open ("md49_commands.txt");
//myfile << "Writing this to a file.\n";
if (speed_l==0){
myfile << "000";
myfile << "\n";
}
else if (speed_l<10){
myfile << "00";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else if (speed_l<100){
myfile << "0";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
if (speed_r==0){
myfile << "000";
myfile << "\n";
}
else if (speed_r<10){
myfile << "00";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else if (speed_r<100){
myfile << "0";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
myfile.close();
*/
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
//set_MD49_speed(speed_l,speed_r);
last_speed_l=speed_l;
last_speed_r=speed_r;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
// Init node
// *********
ros::Rate loop_rate(10);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
try{ device.open("/dev/ttyAMA0", 38400); }
catch(cereal::Exception& e)
{
ROS_FATAL("Failed to open the serial port!!!");
ROS_BREAK();
}
ROS_INFO("The serial port is opened.");
while(n.ok())
{
// Read encoder and other data from MD49
// (data is read from serial_controller_node
// and avaiable through md49_data.txt)
// *****************************************
read_MD49_Data();
// Publish encoder values to topic /encoders (custom message)
// **********************************************************
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Publish MD49 data to topic /md49data (custom message)
// *****************************************************
md49data.speed_l = reply[8];
md49data.speed_r = reply[9];
md49data.volt = reply[10];
md49data.current_l = reply[11];
md49data.current_r = reply[12];
md49data.error = reply[13];
md49data.acceleration = reply[14];
md49data.mode = reply[15];
md49data.regulator = reply[16];
md49data.timeout = reply[17];
md49data_pub.publish(md49data);
// ****
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Send 'R' over the serial port
device.write("R");
// Get the reply, the last value is the timeout in ms
try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
catch(cereal::TimeoutException& e)
{
ROS_ERROR("Timeout on serialport! No data read");
}
//ROS_INFO("Received MD49 data");
// Put toghether new encodervalues
// *******************************
EncoderL = reply[0] << 24; // Put together first encoder value
EncoderL |= (reply[1] << 16);
EncoderL |= (reply[2] << 8);
EncoderL |= (reply[3]);
EncoderR = reply[4] << 24; // Put together second encoder value
EncoderR |= (reply[5] << 16);
EncoderR |= (reply[6] << 8);
EncoderR |= (reply[7]);
// Output MD49 data on screen
// **************************
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("========================================\n");
printf("Encoder1 Byte1: %i ",reply[0]);
printf("Byte2: %i ",reply[1]);
printf("Byte3: % i ",reply[2]);
printf("Byte4: %i \n",reply[3]);
printf("Encoder2 Byte1: %i ",reply[4]);
printf("Byte2: %i ",reply[5]);
printf("Byte3: %i ",reply[6]);
printf("Byte4: %i \n",reply[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("========================================\n");
printf("Speed1: %i ",reply[8]);
printf("Speed2: %i \n",reply[9]);
printf("Volts: %i \n",reply[10]);
printf("Current1: %i ",reply[11]);
printf("Current2: %i \n",reply[12]);
printf("Error: %i \n",reply[13]);
printf("Acceleration: %i \n",reply[14]);
printf("Mode: %i \n",reply[15]);
printf("Regulator: %i \n",reply[16]);
printf("Timeout: %i \n",reply[17]);
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
/*
char buffer[33];
ofstream myfile;
myfile.open ("md49_commands.txt");
//myfile << "Writing this to a file.\n";
if (speed_l==0){
myfile << "000";
myfile << "\n";
}
else if (speed_l<10){
myfile << "00";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else if (speed_l<100){
myfile << "0";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
if (speed_r==0){
myfile << "000";
myfile << "\n";
}
else if (speed_r<10){
myfile << "00";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else if (speed_r<100){
myfile << "0";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
myfile.close();
*/
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_training.H>
#include <lib/utils/count_dimm.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping draminit_training %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::mrw_reset_delay_before_cal(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, false);
mss::ccs::ue_disable(i_target, l_ccs_config, false);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
#ifndef JIM_SAYS_TURN_OFF_ECC
mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
// Leaving these probes in here as we need them from time to time, but they
// take up a lot of sim time, so we like to remove them simply
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// Disable port fails as it doesn't appear the MC handles initial cal timeouts
// correctly (cal_length.) BRS, see conversation with Brad Michael
FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );
// The following registers must be configured to the correct operating environment:
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::rank::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_MRW_RESET_DELAY_BEFORE_CAL_YES) && (i_special_training == 0))
{
FAPI_INF("resetting delay values before cal %s", mss::c_str(p));
FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (auto rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<commit_msg>Changes to limit DLL cal on spare DP8, stop CSS before starting<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_training.H>
#include <lib/utils/count_dimm.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping draminit_training %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::mrw_reset_delay_before_cal(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, mss::LOW);
mss::ccs::ue_disable(i_target, l_ccs_config, mss::LOW);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, mss::HIGH);
mss::ccs::parity_after_cmd(i_target, l_ccs_config, mss::HIGH);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
// Leaving these probes in here as we need them from time to time, but they
// take up a lot of sim time, so we like to remove them simply
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// Disable port fails as it doesn't appear the MC handles initial cal timeouts
// correctly (cal_length.) BRS, see conversation with Brad Michael
FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );
// The following registers must be configured to the correct operating environment:
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::rank::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_MRW_RESET_DELAY_BEFORE_CAL_YES) && (i_special_training == 0))
{
FAPI_INF("resetting delay values before cal %s", mss::c_str(p));
FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (const auto& rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_chiplet_fabric_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_chiplet_scominit.C
///
/// @brief apply fabric SCOM inits
///
//
// *HWP HW Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 2
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_chiplet_fabric_scominit.H>
#include <p9_fbc_no_hp_scom.H>
#include <p9_fbc_ioe_tl_scom.H>
#include <p9_fbc_ioe_dl_scom.H>
#include <p9_xbus_scom_addresses.H>
#include <p9_xbus_scom_addresses_fld.H>
#include <p9_obus_scom_addresses.H>
#include <p9_obus_scom_addresses_fld.H>
#include <p9_misc_scom_addresses.H>
#include <p9_perv_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
const uint64_t FBC_IOE_TL_FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_TL_FIR_ACTION1 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_TL_FIR_MASK = 0xFF6DF0303FFFFF1FULL;
const uint64_t FBC_IOE_DL_FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_DL_FIR_ACTION1 = 0x0303C00000001FFCULL;
const uint64_t FBC_IOE_DL_FIR_MASK = 0xFCFC3FFFFFFFE003ULL;
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_chiplet_fabric_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
fapi2::ReturnCode l_rc;
char l_procTargetStr[fapi2::MAX_ECMD_STRING_LEN];
char l_chipletTargetStr[fapi2::MAX_ECMD_STRING_LEN];
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_XBUS>> l_xbus_chiplets;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_OBUS>> l_obus_chiplets;
fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type l_fbc_optics_cfg_mode = { fapi2::ENUM_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_SMP };
FAPI_DBG("Start");
// Get proc target string
fapi2::toString(i_target, l_procTargetStr, sizeof(l_procTargetStr));
// apply FBC non-hotplug initfile
FAPI_DBG("Invoking p9.fbc.no_hp.scom.initfile on target %s...", l_procTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_no_hp_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_no_hp_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// setup IOE (XBUS FBC IO) TL SCOMs
FAPI_DBG("Invoking p9.fbc.ioe_tl.scom.initfile on target %s...", l_procTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_ioe_tl_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioe_tl_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
l_xbus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_XBUS>();
if (l_xbus_chiplets.size())
{
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_ACTION0_REG, FBC_IOE_TL_FIR_ACTION0),
"Error from putScom (PU_PB_IOE_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_ACTION1_REG, FBC_IOE_TL_FIR_ACTION1),
"Error from putScom (PU_PB_IOE_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_MASK_REG, FBC_IOE_TL_FIR_MASK),
"Error from putScom (PU_PB_IOE_FIR_MASK_REG)");
}
// setup IOE (XBUS FBC IO) DL SCOMs
for (auto l_iter = l_xbus_chiplets.begin();
l_iter != l_xbus_chiplets.end();
l_iter++)
{
fapi2::toString(*l_iter, l_chipletTargetStr, sizeof(l_chipletTargetStr));
FAPI_DBG("Invoking p9.fbc.ioe_dl.scom.initfile on target %s...", l_chipletTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_ioe_dl_scom, *l_iter, i_target);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioe_dl_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// configure action registers & unmask
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_IOEL_FIR_ACTION0_REG, FBC_IOE_DL_FIR_ACTION0),
"Error from putScom (XBUS_LL0_IOEL_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_IOEL_FIR_ACTION1_REG, FBC_IOE_DL_FIR_ACTION1),
"Error from putScom (XBUS_LL0_IOEL_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_LL0_LL0_IOEL_FIR_MASK_REG, FBC_IOE_DL_FIR_MASK),
"Error from putScom (XBUS_LL0_LL0_LL0_IOEL_FIR_MASK_REG)");
}
// set FBC optics config mode attribute
l_obus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_OBUS>();
for (auto l_iter = l_obus_chiplets.begin();
l_iter != l_obus_chiplets.end();
l_iter++)
{
uint8_t l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, *l_iter, l_unit_pos),
"Error from FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS)");
FAPI_INF("Updating index: %d\n", l_unit_pos);
FAPI_INF(" before: %d\n", l_fbc_optics_cfg_mode[l_unit_pos]);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, *l_iter, l_fbc_optics_cfg_mode[l_unit_pos]),
"Error from FAPI_ATTR_GET(ATTR_OPTICS_CONFIG_MODE)");
FAPI_INF(" after: %d\n", l_fbc_optics_cfg_mode[l_unit_pos]);
}
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, i_target, l_fbc_optics_cfg_mode),
"Error from FAPI_ATTR_SET(ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)");
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
<commit_msg>Configure xlink psave settings and enable by default<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_chiplet_fabric_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_chiplet_scominit.C
///
/// @brief apply fabric SCOM inits
///
//
// *HWP HW Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 2
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_chiplet_fabric_scominit.H>
#include <p9_fbc_no_hp_scom.H>
#include <p9_fbc_ioe_tl_scom.H>
#include <p9_fbc_ioe_dl_scom.H>
#include <p9_xbus_scom_addresses.H>
#include <p9_xbus_scom_addresses_fld.H>
#include <p9_obus_scom_addresses.H>
#include <p9_obus_scom_addresses_fld.H>
#include <p9_misc_scom_addresses.H>
#include <p9_perv_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
const uint64_t FBC_IOE_TL_FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_TL_FIR_ACTION1 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_TL_FIR_MASK = 0xFF6DF0303FFFFF1FULL;
const uint64_t FBC_IOE_DL_FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FBC_IOE_DL_FIR_ACTION1 = 0x0303C00000001FFCULL;
const uint64_t FBC_IOE_DL_FIR_MASK = 0xFCFC3FFFFFFFE003ULL;
const uint64_t FBC_IOE_TL_PSAVE_CFG = 0xF1FF01031C000000ULL;
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode p9_chiplet_fabric_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
fapi2::ReturnCode l_rc;
char l_procTargetStr[fapi2::MAX_ECMD_STRING_LEN];
char l_chipletTargetStr[fapi2::MAX_ECMD_STRING_LEN];
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_XBUS>> l_xbus_chiplets;
std::vector<fapi2::Target<fapi2::TARGET_TYPE_OBUS>> l_obus_chiplets;
fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_Type l_fbc_optics_cfg_mode = { fapi2::ENUM_ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE_SMP };
FAPI_DBG("Start");
// Get proc target string
fapi2::toString(i_target, l_procTargetStr, sizeof(l_procTargetStr));
// apply FBC non-hotplug initfile
FAPI_DBG("Invoking p9.fbc.no_hp.scom.initfile on target %s...", l_procTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_no_hp_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_no_hp_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// setup IOE (XBUS FBC IO) TL SCOMs
FAPI_DBG("Invoking p9.fbc.ioe_tl.scom.initfile on target %s...", l_procTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_ioe_tl_scom, i_target, FAPI_SYSTEM);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioe_tl_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
l_xbus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_XBUS>();
if (l_xbus_chiplets.size())
{
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_ACTION0_REG, FBC_IOE_TL_FIR_ACTION0),
"Error from putScom (PU_PB_IOE_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_ACTION1_REG, FBC_IOE_TL_FIR_ACTION1),
"Error from putScom (PU_PB_IOE_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(i_target, PU_PB_IOE_FIR_MASK_REG, FBC_IOE_TL_FIR_MASK),
"Error from putScom (PU_PB_IOE_FIR_MASK_REG)");
FAPI_TRY(fapi2::putScom(i_target, PU_PB_PSAVE_CFG, FBC_IOE_TL_PSAVE_CFG),
"Error from putScom (PU_PB_PSAVE_CFG)");
}
// setup IOE (XBUS FBC IO) DL SCOMs
for (auto l_iter = l_xbus_chiplets.begin();
l_iter != l_xbus_chiplets.end();
l_iter++)
{
fapi2::toString(*l_iter, l_chipletTargetStr, sizeof(l_chipletTargetStr));
FAPI_DBG("Invoking p9.fbc.ioe_dl.scom.initfile on target %s...", l_chipletTargetStr);
FAPI_EXEC_HWP(l_rc, p9_fbc_ioe_dl_scom, *l_iter, i_target);
if (l_rc)
{
FAPI_ERR("Error from p9_fbc_ioe_dl_scom");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// configure action registers & unmask
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_IOEL_FIR_ACTION0_REG, FBC_IOE_DL_FIR_ACTION0),
"Error from putScom (XBUS_LL0_IOEL_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_IOEL_FIR_ACTION1_REG, FBC_IOE_DL_FIR_ACTION1),
"Error from putScom (XBUS_LL0_IOEL_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(*l_iter, XBUS_LL0_LL0_LL0_IOEL_FIR_MASK_REG, FBC_IOE_DL_FIR_MASK),
"Error from putScom (XBUS_LL0_LL0_LL0_IOEL_FIR_MASK_REG)");
}
// set FBC optics config mode attribute
l_obus_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_OBUS>();
for (auto l_iter = l_obus_chiplets.begin();
l_iter != l_obus_chiplets.end();
l_iter++)
{
uint8_t l_unit_pos;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, *l_iter, l_unit_pos),
"Error from FAPI_ATTR_GET(ATTR_CHIP_UNIT_POS)");
FAPI_INF("Updating index: %d\n", l_unit_pos);
FAPI_INF(" before: %d\n", l_fbc_optics_cfg_mode[l_unit_pos]);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, *l_iter, l_fbc_optics_cfg_mode[l_unit_pos]),
"Error from FAPI_ATTR_GET(ATTR_OPTICS_CONFIG_MODE)");
FAPI_INF(" after: %d\n", l_fbc_optics_cfg_mode[l_unit_pos]);
}
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE, i_target, l_fbc_optics_cfg_mode),
"Error from FAPI_ATTR_SET(ATTR_PROC_FABRIC_OPTICS_CONFIG_MODE)");
fapi_try_exit:
FAPI_DBG("End");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#include "SquareFormation.h"
using namespace BWAPI;
SquareFormation::SquareFormation(const SquareFormation& f)
: Formation(f) {}
SquareFormation::SquareFormation(const Vec& center, const Vec& direction)
: Formation(center, direction) {}
SquareFormation::SquareFormation(const Position& p, const Vec& direction)
: Formation(p, direction) {}
void SquareFormation::computeToPositions(const std::vector<pBayesianUnit>& vUnit)
{
end_positions.clear();
unsigned int sizeSide = (unsigned int)sqrt( (double)vUnit.size());
Vec corner = center - Position( (int)(sizeSide/2.0 * space), (int)(sizeSide/2.0 * space));
for( unsigned int i = 0; i < vUnit.size(); i++)
{
Position topos = (corner + Position( int(i/sizeSide) * space, (i%sizeSide) * space)).toPosition();
if (topos.isValid())
end_positions.push_back(topos);
else
{
topos.makeValid();
end_positions.push_back(topos);
}
++i;
}
}
<commit_msg>bug in SquareFormation corrected<commit_after>#include "SquareFormation.h"
using namespace BWAPI;
SquareFormation::SquareFormation(const SquareFormation& f)
: Formation(f) {}
SquareFormation::SquareFormation(const Vec& center, const Vec& direction)
: Formation(center, direction) {}
SquareFormation::SquareFormation(const Position& p, const Vec& direction)
: Formation(p, direction) {}
void SquareFormation::computeToPositions(const std::vector<pBayesianUnit>& vUnit)
{
end_positions.clear();
unsigned int sizeSide = (unsigned int)sqrt( (double)vUnit.size());
Vec corner = center - Position( (int)(sizeSide/2.0 * space), (int)(sizeSide/2.0 * space));
for( unsigned int i = 0; i < vUnit.size(); i++)
{
Position topos = (corner + Position( int(i/sizeSide) * space, (i%sizeSide) * space)).toPosition();
if (topos.isValid())
end_positions.push_back(topos);
else
{
topos.makeValid();
end_positions.push_back(topos);
}
}
}
<|endoftext|> |
<commit_before>#include <Eigen/Core>
USING_PART_OF_NAMESPACE_EIGEN
using namespace std;
int main(int, char **)
{
Matrix<double,2,2> m; // 2x2 fixed-size matrix with uninitialized entries
m(0,0) = 1;
m(0,1) = 2;
m(1,0) = 3;
m(1,1) = 4;
cout << "Here is a 2x2 matrix m:" << endl << m << endl;
cout << "Let us now build a 4x4 matrix m2 by assembling together four 2x2 blocks." << endl;
MatrixXd m2(4,4); // dynamic matrix with initial size 4x4 and uninitialized entries
// notice how we are mixing fixed-size and dynamic-size types.
cout << "In the top-left block, we put the matrix m shown above." << endl;
m2.block<2,2>(0,0) = m;
cout << "In the bottom-left block, we put the matrix m*m, which is:" << endl << m*m << endl;
m2.block<2,2>(2,0) = m * m;
cout << "In the top-right block, we put the matrix m+m, which is:" << endl << m+m << endl;
m2.block<2,2>(0,2) = m + m;
cout << "In the bottom-right block, we put the matrix m-m, which is:" << endl << m-m << endl;
m2.block<2,2>(2,2) = m - m;
cout << "Now the 4x4 matrix m2 is:" << endl << m2 << endl;
cout << "Row 0 of m2 is:" << endl << m2.row(0) << endl;
cout << "The third element in that row is " << m2.row(0)[2] << endl;
cout << "Column 1 of m2 is:" << endl << m2.col(1) << endl;
cout << "The transpose of m2 is:" << endl << m2.transpose() << endl;
cout << "The matrix m2 with row 0 and column 1 removed is:" << endl << m2.minor(0,1) << endl;
return 0;
}
<commit_msg>updated tutorial<commit_after>#include <Eigen/Array>
int main(int argc, char *argv[])
{
std::cout.precision(2);
// demo static functions
Eigen::Matrix3f m3 = Eigen::Matrix3f::Random();
Eigen::Matrix4f m4 = Eigen::Matrix4f::Identity();
std::cout << "*** Step 1 ***\nm3:\n" << m3 << "\nm4:\n" << m4 << std::endl;
// demo non-static set... functions
m4.setZero();
m3.diagonal().setOnes();
std::cout << "*** Step 2 ***\nm3:\n" << m3 << "\nm4:\n" << m4 << std::endl;
// demo fixed-size block() expression as lvalue and as rvalue
m4.block<3,3>(0,1) = m3;
m3.row(2) = m4.block<1,3>(2,0);
std::cout << "*** Step 3 ***\nm3:\n" << m3 << "\nm4:\n" << m4 << std::endl;
// demo dynamic-size block()
{
int rows = 3, cols = 3;
m4.block(0,1,3,3).setIdentity();
std::cout << "*** Step 4 ***\nm4:\n" << m4 << std::endl;
}
// demo vector blocks
m4.diagonal().block(1,2).setOnes();
std::cout << "*** Step 5 ***\nm4.diagonal():\n" << m4.diagonal() << std::endl;
std::cout << "m4.diagonal().start(3)\n" << m4.diagonal().start(3) << std::endl;
// demo coeff-wise operations
m4 = m4.cwise()*m4;
m3 = m3.cwise().cos();
std::cout << "*** Step 6 ***\nm3:\n" << m3 << "\nm4:\n" << m4 << std::endl;
// sums of coefficients
std::cout << "*** Step 7 ***\n m4.sum(): " << m4.sum() << std::endl;
std::cout << "m4.col(2).sum(): " << m4.col(2).sum() << std::endl;
std::cout << "m4.colwise().sum():\n" << m4.colwise().sum() << std::endl;
std::cout << "m4.rowwise().sum():\n" << m4.rowwise().sum() << std::endl;
// demo intelligent auto-evaluation
m4 = m4 * m4; // auto-evaluates so no aliasing problem (performance penalty is low)
Eigen::Matrix4f other = (m4 * m4).lazy(); // forces lazy evaluation
m4 = m4 + m4; // here Eigen goes for lazy evaluation, as with most expressions
m4 = -m4 + m4 + 5 * m4; // same here, Eigen chooses lazy evaluation for all that.
m4 = m4 * (m4 + m4); // here Eigen chooses to first evaluate m4 + m4 into a temporary.
// indeed, here it is an optimization to cache this intermediate result.
m3 = m3 * m4.block<3,3>(1,1); // here Eigen chooses NOT to evaluate transpose() into a temporary
// because accessing coefficients of that block expression is not more costly than accessing
// coefficients of a plain matrix.
m4 = m4 * m4.transpose(); // same here, lazy evaluation of the transpose.
m4 = m4 * m4.transpose().eval(); // forces immediate evaluation of the transpose
std::cout << "*** Step 8 ***\nm3:\n" << m3 << "\nm4:\n" << m4 << std::endl;
}<|endoftext|> |
<commit_before>//
// PlatformSystem.cpp
// Chilli Source
//
// Created by Ian Copland on 24/11/2010.
// Copyright (c) 2014 Tag Games Ltd. All rights reserved.
//
#include <ChilliSource/Backend/Platform/Android/Core/Base/PlatformSystem.h>
#include <ChilliSource/Backend/Platform/Android/Core/Base/CoreJavaInterface.h>
#include <ChilliSource/Backend/Platform/Android/Core/JNI/JavaInterfaceManager.h>
#include <ChilliSource/Core/Image/ETC1ImageProvider.h>
namespace ChilliSource
{
namespace Android
{
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::Init()
{
}
//-------------------------------------------------
//-------------------------------------------------
void PlatformSystem::CreateDefaultSystems(Core::Application* in_application)
{
in_application->AddSystem(Core::ETC1ImageProvider::Create());
}
//-------------------------------------------------
//-------------------------------------------------
void PlatformSystem::PostCreateSystems()
{
}
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::SetMaxFPS(u32 in_fps)
{
JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->SetMaxFPS(in_fps);
}
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::TerminateUpdater()
{
JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->ForceQuit();
}
//---------------------------------------------
//---------------------------------------------
Core::Vector2 PlatformSystem::GetScreenDimensions() const
{
Core::Vector2 dims;
CoreJavaInterfaceSPtr coreJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>();
dims.x = coreJI->GetScreenWidth();
dims.y = coreJI->GetScreenHeight();
s32 orientation = coreJI->GetOrientation();
#ifdef CS_ENABLE_DEBUG
if(orientation < 0)
CS_LOG_ERROR("PlatformSystem::GetScreenDimensions() - Could not get orientation of device!");
#endif
if(Core::ScreenOrientation::k_landscapeRight == (Core::ScreenOrientation)orientation)
{
// Swap round as we want dimensions the other way
std::swap(dims.x, dims.y);
}
return dims;
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceModelName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceModel();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceModelTypeName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceModelType();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceManufacturerName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceManufacturer();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetOSVersion() const
{
return Core::ToString(JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetOSVersionCode());
}
//--------------------------------------------------------------
//--------------------------------------------------------------
Core::Locale PlatformSystem::GetLocale() const
{
//get the locale from android
std::string strLocale = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDefaultLocaleCode();
//break this locale into parts(language/country code/extra)
std::vector<std::string> strLocaleBrokenUp = ChilliSource::Core::StringUtils::Split(strLocale, "_", 0);
if (strLocaleBrokenUp.size() > 1)
{
return Core::Locale(strLocaleBrokenUp[0],strLocaleBrokenUp[1]);
}
else if (strLocaleBrokenUp.size() == 1)
{
return Core::Locale(strLocaleBrokenUp[0]);
}
else
{
return Core::kUnknownLocale;
}
}
//--------------------------------------------------------------
//--------------------------------------------------------------
Core::Locale PlatformSystem::GetLanguage() const
{
return GetLocale();
}
//-------------------------------------------------
//-------------------------------------------------
f32 PlatformSystem::GetScreenDensity() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetScreenDensity();
}
//-------------------------------------------------
//-------------------------------------------------
std::string PlatformSystem::GetAppVersion() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetApplicationVersionName();
}
//-------------------------------------------------
//-------------------------------------------------
std::string PlatformSystem::GetDeviceID()
{
return mUDIDManager.GetUDID();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
u32 PlatformSystem::GetNumberOfCPUCores() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetNumberOfCores();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
TimeIntervalMs PlatformSystem::GetSystemTimeMS() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetSystemTimeInMilliseconds();
}
//-------------------------------------------------
//-------------------------------------------------
f32 PlatformSystem::GetPhysicalScreenSize()
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetPhysicalScreenSize();
}
}
}
<commit_msg>Android compile error with adding old system type<commit_after>//
// PlatformSystem.cpp
// Chilli Source
//
// Created by Ian Copland on 24/11/2010.
// Copyright (c) 2014 Tag Games Ltd. All rights reserved.
//
#include <ChilliSource/Backend/Platform/Android/Core/Base/PlatformSystem.h>
#include <ChilliSource/Backend/Platform/Android/Core/Base/CoreJavaInterface.h>
#include <ChilliSource/Backend/Platform/Android/Core/JNI/JavaInterfaceManager.h>
#include <ChilliSource/Core/Image/ETC1ImageProvider.h>
namespace ChilliSource
{
namespace Android
{
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::Init()
{
}
//-------------------------------------------------
//-------------------------------------------------
void PlatformSystem::CreateDefaultSystems(Core::Application* in_application)
{
in_application->AddSystem_Old(Core::ETC1ImageProvider::Create());
}
//-------------------------------------------------
//-------------------------------------------------
void PlatformSystem::PostCreateSystems()
{
}
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::SetMaxFPS(u32 in_fps)
{
JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->SetMaxFPS(in_fps);
}
//-----------------------------------------
//-----------------------------------------
void PlatformSystem::TerminateUpdater()
{
JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->ForceQuit();
}
//---------------------------------------------
//---------------------------------------------
Core::Vector2 PlatformSystem::GetScreenDimensions() const
{
Core::Vector2 dims;
CoreJavaInterfaceSPtr coreJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>();
dims.x = coreJI->GetScreenWidth();
dims.y = coreJI->GetScreenHeight();
s32 orientation = coreJI->GetOrientation();
#ifdef CS_ENABLE_DEBUG
if(orientation < 0)
CS_LOG_ERROR("PlatformSystem::GetScreenDimensions() - Could not get orientation of device!");
#endif
if(Core::ScreenOrientation::k_landscapeRight == (Core::ScreenOrientation)orientation)
{
// Swap round as we want dimensions the other way
std::swap(dims.x, dims.y);
}
return dims;
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceModelName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceModel();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceModelTypeName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceModelType();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetDeviceManufacturerName() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDeviceManufacturer();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
std::string PlatformSystem::GetOSVersion() const
{
return Core::ToString(JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetOSVersionCode());
}
//--------------------------------------------------------------
//--------------------------------------------------------------
Core::Locale PlatformSystem::GetLocale() const
{
//get the locale from android
std::string strLocale = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetDefaultLocaleCode();
//break this locale into parts(language/country code/extra)
std::vector<std::string> strLocaleBrokenUp = ChilliSource::Core::StringUtils::Split(strLocale, "_", 0);
if (strLocaleBrokenUp.size() > 1)
{
return Core::Locale(strLocaleBrokenUp[0],strLocaleBrokenUp[1]);
}
else if (strLocaleBrokenUp.size() == 1)
{
return Core::Locale(strLocaleBrokenUp[0]);
}
else
{
return Core::kUnknownLocale;
}
}
//--------------------------------------------------------------
//--------------------------------------------------------------
Core::Locale PlatformSystem::GetLanguage() const
{
return GetLocale();
}
//-------------------------------------------------
//-------------------------------------------------
f32 PlatformSystem::GetScreenDensity() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetScreenDensity();
}
//-------------------------------------------------
//-------------------------------------------------
std::string PlatformSystem::GetAppVersion() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetApplicationVersionName();
}
//-------------------------------------------------
//-------------------------------------------------
std::string PlatformSystem::GetDeviceID()
{
return mUDIDManager.GetUDID();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
u32 PlatformSystem::GetNumberOfCPUCores() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetNumberOfCores();
}
//--------------------------------------------------------------
//--------------------------------------------------------------
TimeIntervalMs PlatformSystem::GetSystemTimeMS() const
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetSystemTimeInMilliseconds();
}
//-------------------------------------------------
//-------------------------------------------------
f32 PlatformSystem::GetPhysicalScreenSize()
{
return JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CoreJavaInterface>()->GetPhysicalScreenSize();
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: testapp.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: kz $ $Date: 2007-06-19 14:36:10 $
*
* 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 TESTAPP_HXX
#define TESTAPP_HXX
#include <basic/sbmod.hxx>
#ifndef _BASIC_TESTTOOL_HXX_
#include <basic/testtool.hxx>
#endif
#ifndef _SMARTID_HXX_
#include <vcl/smartid.hxx>
#endif
class CommunicationLink;
class CommunicationManagerClientViaSocketTT;
class CNames;
class ControlItemUId;
class CRevNames;
//class SbxTransportVariableRef;
class ControlsRef;
class CmdStream;
class FloatingLoadConf;
class TestToolObj;
class ControlDef;
class SbxTransportMethod;
class Application;
class SotStorage;
class ImplTestToolObj;
class MyBasic;
class ErrorEntry
{
public:
ErrorEntry(ULONG nNr, String aStr = String()) : nError(nNr),aText(aStr),nLine(0),nCol1(0),nCol2(0) {}
ErrorEntry(ULONG nNr, String aStr, xub_StrLen l, xub_StrLen c1, xub_StrLen c2 )
: nError(nNr),aText(aStr),nLine(l),nCol1(c1),nCol2(c2) {}
ULONG nError;
String aText;
xub_StrLen nLine;
xub_StrLen nCol1;
xub_StrLen nCol2;
};
SV_DECL_PTRARR_DEL(CErrors, ErrorEntry*, 1, 1)
struct ControlDefLoad {
const char* Kurzname;
ULONG nUId;
};
class TestToolObj: public SbxObject
{
friend class TTBasic;
friend class Controls;
public:
TestToolObj( String aName, String aFilePath ); // Alle Dateien in FilePath, Kein IPC
TestToolObj( String aName, MyBasic* pBas ); // Pfade aus INI, IPC benutzen
~TestToolObj();
void LoadIniFile(); // Laden der IniEinstellungen, die durch den ConfigDialog gendert werden knnen
void DebugFindNoErrors( BOOL bDebugFindNoErrors );
private:
BOOL bWasPrecompilerError; // True wenn beim letzten Precompile ein Fehler auftrat
BOOL CError( ULONG, const String&, xub_StrLen, xub_StrLen, xub_StrLen );
void CalcPosition( String const &aSource, xub_StrLen nPos, xub_StrLen &l, xub_StrLen &c );
xub_StrLen ImplSearch( const String &aSource, const xub_StrLen nStart, const xub_StrLen nEnd, const String &aSearch, const xub_StrLen nSearchStart = 0 );
xub_StrLen PreCompilePart( String &aSource, xub_StrLen nStart, xub_StrLen nEnd, String aFinalErrorLabel, USHORT &nLabelCount );
void PreCompileDispatchParts( String &aSource, String aStart, String aEnd, String aFinalLable );
public:
String GetRevision(String const &aSourceIn); // find Revision in the sourcecode
String PreCompile(String const &aSourceIn); // try catch; testcase endcase ..
BOOL WasPrecompilerError(); // True wenn beim letzten Precompile ein Fehler auftrat
void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
virtual SbxVariable* Find( const String&, SbxClassType );
// String aKeyPlusClasses; // Pfad fr keycodes & classes & res_type (Aus Configdatei)
DECL_LINK( ReturnResultsLink, CommunicationLink* );
BOOL ReturnResults( SvStream *pIn ); // Rcklieferung des Antwortstreams ber IPC oder TCP/IP oder direkt
void SetLogHdl( const Link& rLink ) { aLogHdl = rLink; }
const Link& GetLogHdl() const { return aLogHdl; }
void SetWinInfoHdl( const Link& rLink ) { aWinInfoHdl = rLink; }
const Link& GetWinInfoHdl() const { return aWinInfoHdl; }
void SetModuleWinExistsHdl( const Link& rLink ) { aModuleWinExistsHdl = rLink; }
const Link& GetModuleWinExistsHdl() const { return aModuleWinExistsHdl; }
void SetCErrorHdl( const Link& rLink ) { aCErrorHdl = rLink; }
const Link& GetCErrorHdl() const { return aCErrorHdl; }
void SetWriteStringHdl( const Link& rLink ) { aWriteStringHdl = rLink; }
const Link& GetWriteStringHdl() const { return aWriteStringHdl; }
SfxBroadcaster& GetTTBroadcaster();
private:
ImplTestToolObj *pImpl; // Alles was von der Implementation abhngt
static CErrors* const GetFehlerListe() { return pFehlerListe; }
BOOL bUseIPC;
Link aLogHdl; // Zum Logen der Fehlermeldungen im Testtool
Link aWinInfoHdl; // Anzeigen der Windows/Controls der zu testenden App
Link aModuleWinExistsHdl; // Prft ob das Modul schon im Editor geladen ist
Link aCErrorHdl; // Melden von Compilererror
Link aWriteStringHdl; // Schreiben von text (e.g. MakroRecorder)
BOOL bReturnOK; // Bricht WaitForAnswer ab
CRevNames *pShortNames; // Aktuell verwendete Controls, zur gewinnung des Namens aus Fehlermeldung
ULONG nSequence; // Sequence um Antwort und Anfrage zu syncronisieren
SmartId aNextReturnId; // Id des Returnwertes i.e. UId
void ReplaceNumbers(String &aText); // Zahlen im String mit speziellem Format in Namen umwandeln
String aLastRecordedKontext;// Keeps the last kontext recorded by the Macro Recorder
#define FLAT TRUE
String ProgPath; // Dateiname der zu Testenden APP; Gesetzt ber Start
String aLogFileName; // Momentaner Logfilename (Wie Programmdatei aber mit .res)
BOOL IsBlock; // Innerhalb Begin/EndBlock
BOOL SingleCommandBlock; // Implizit um jedes kommando ein Begin/EndBlock
CmdStream *In;
void AddName(String &aBisher, String &aNeu ); // Name eventuell mit / anhngen
void AddToListByNr( CNames *&pControls, ControlItemUId *&pNewItem ); //
CNames *m_pControls;
CNames *m_pNameKontext; // Zeigt auf den aktuellen Namenskontext, der ber 'Kontext' gesetzt wurde
CNames *m_pSIds;
CNames *m_pReverseSlots; // Slots mit Kurznamen nach Nummer
CNames *m_pReverseControls; // Controls mit Kurznamen nach Nummer
CNames *m_pReverseControlsSon;// Controls mit Kurznamen nach Nummer nach Fenstern (Son)
CNames *m_pReverseUIds; // Langnamen nach Nummer
USHORT nMyVar; // Wievielte Var aus Pool ist dran
void InitTestToolObj();
CommunicationManagerClientViaSocketTT *pCommunicationManager;
void SendViaSocket();
BOOL Load( String aFileName, SbModule *pMod );
void ReadNames( String Filename, CNames *&pNames, CNames *&pUIds, BOOL bIsFlat = FALSE );
void ReadFlat( String Filename, CNames *&pNames, BOOL bSortByName );
BOOL ReadNamesBin( String Filename, CNames *&pSIds, CNames *&pControls );
BOOL WriteNamesBin( String Filename, CNames *pSIds, CNames *pControls );
void ReadHidLstByNumber();
void SortControlsByNumber( BOOL bIncludeActive = FALSE );
String GetMethodName( ULONG nMethodId );
String GetKeyName( USHORT nKeyCode );
void WaitForAnswer ();
DECL_LINK( IdleHdl, Application* );
DECL_LINK( CallDialogHandler, Application* );
String aDialogHandlerName;
USHORT nWindowHandlerCallLevel;
USHORT nIdleCount;
// wenn DialogHandler gesetzt wird er im IdleHandler inkrementiert und
// in WaitForAnswer rckgesetzt. bersteigt er einen gewissen wert, gehe ich davon aus,
// da WaitForAnswer still ligt und rufe die DialogHander Sub im BASIC auf.
void BeginBlock();
void EndBlock();
SbTextType GetSymbolType( const String &rSymbol, BOOL bWasControl );
static ControlDefLoad const arR_Cmds[];
static CNames *pRCommands;
static CErrors *pFehlerListe; // Hier werden die Fehler des Testtools gespeichert
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.11.40); FILE MERGED 2008/04/01 15:00:01 thb 1.11.40.2: #i85898# Stripping all external header guards 2008/03/28 16:03:35 rt 1.11.40.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: testapp.hxx,v $
* $Revision: 1.12 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef TESTAPP_HXX
#define TESTAPP_HXX
#include <basic/sbmod.hxx>
#include <basic/testtool.hxx>
#include <vcl/smartid.hxx>
class CommunicationLink;
class CommunicationManagerClientViaSocketTT;
class CNames;
class ControlItemUId;
class CRevNames;
//class SbxTransportVariableRef;
class ControlsRef;
class CmdStream;
class FloatingLoadConf;
class TestToolObj;
class ControlDef;
class SbxTransportMethod;
class Application;
class SotStorage;
class ImplTestToolObj;
class MyBasic;
class ErrorEntry
{
public:
ErrorEntry(ULONG nNr, String aStr = String()) : nError(nNr),aText(aStr),nLine(0),nCol1(0),nCol2(0) {}
ErrorEntry(ULONG nNr, String aStr, xub_StrLen l, xub_StrLen c1, xub_StrLen c2 )
: nError(nNr),aText(aStr),nLine(l),nCol1(c1),nCol2(c2) {}
ULONG nError;
String aText;
xub_StrLen nLine;
xub_StrLen nCol1;
xub_StrLen nCol2;
};
SV_DECL_PTRARR_DEL(CErrors, ErrorEntry*, 1, 1)
struct ControlDefLoad {
const char* Kurzname;
ULONG nUId;
};
class TestToolObj: public SbxObject
{
friend class TTBasic;
friend class Controls;
public:
TestToolObj( String aName, String aFilePath ); // Alle Dateien in FilePath, Kein IPC
TestToolObj( String aName, MyBasic* pBas ); // Pfade aus INI, IPC benutzen
~TestToolObj();
void LoadIniFile(); // Laden der IniEinstellungen, die durch den ConfigDialog gendert werden knnen
void DebugFindNoErrors( BOOL bDebugFindNoErrors );
private:
BOOL bWasPrecompilerError; // True wenn beim letzten Precompile ein Fehler auftrat
BOOL CError( ULONG, const String&, xub_StrLen, xub_StrLen, xub_StrLen );
void CalcPosition( String const &aSource, xub_StrLen nPos, xub_StrLen &l, xub_StrLen &c );
xub_StrLen ImplSearch( const String &aSource, const xub_StrLen nStart, const xub_StrLen nEnd, const String &aSearch, const xub_StrLen nSearchStart = 0 );
xub_StrLen PreCompilePart( String &aSource, xub_StrLen nStart, xub_StrLen nEnd, String aFinalErrorLabel, USHORT &nLabelCount );
void PreCompileDispatchParts( String &aSource, String aStart, String aEnd, String aFinalLable );
public:
String GetRevision(String const &aSourceIn); // find Revision in the sourcecode
String PreCompile(String const &aSourceIn); // try catch; testcase endcase ..
BOOL WasPrecompilerError(); // True wenn beim letzten Precompile ein Fehler auftrat
void SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& );
virtual SbxVariable* Find( const String&, SbxClassType );
// String aKeyPlusClasses; // Pfad fr keycodes & classes & res_type (Aus Configdatei)
DECL_LINK( ReturnResultsLink, CommunicationLink* );
BOOL ReturnResults( SvStream *pIn ); // Rcklieferung des Antwortstreams ber IPC oder TCP/IP oder direkt
void SetLogHdl( const Link& rLink ) { aLogHdl = rLink; }
const Link& GetLogHdl() const { return aLogHdl; }
void SetWinInfoHdl( const Link& rLink ) { aWinInfoHdl = rLink; }
const Link& GetWinInfoHdl() const { return aWinInfoHdl; }
void SetModuleWinExistsHdl( const Link& rLink ) { aModuleWinExistsHdl = rLink; }
const Link& GetModuleWinExistsHdl() const { return aModuleWinExistsHdl; }
void SetCErrorHdl( const Link& rLink ) { aCErrorHdl = rLink; }
const Link& GetCErrorHdl() const { return aCErrorHdl; }
void SetWriteStringHdl( const Link& rLink ) { aWriteStringHdl = rLink; }
const Link& GetWriteStringHdl() const { return aWriteStringHdl; }
SfxBroadcaster& GetTTBroadcaster();
private:
ImplTestToolObj *pImpl; // Alles was von der Implementation abhngt
static CErrors* const GetFehlerListe() { return pFehlerListe; }
BOOL bUseIPC;
Link aLogHdl; // Zum Logen der Fehlermeldungen im Testtool
Link aWinInfoHdl; // Anzeigen der Windows/Controls der zu testenden App
Link aModuleWinExistsHdl; // Prft ob das Modul schon im Editor geladen ist
Link aCErrorHdl; // Melden von Compilererror
Link aWriteStringHdl; // Schreiben von text (e.g. MakroRecorder)
BOOL bReturnOK; // Bricht WaitForAnswer ab
CRevNames *pShortNames; // Aktuell verwendete Controls, zur gewinnung des Namens aus Fehlermeldung
ULONG nSequence; // Sequence um Antwort und Anfrage zu syncronisieren
SmartId aNextReturnId; // Id des Returnwertes i.e. UId
void ReplaceNumbers(String &aText); // Zahlen im String mit speziellem Format in Namen umwandeln
String aLastRecordedKontext;// Keeps the last kontext recorded by the Macro Recorder
#define FLAT TRUE
String ProgPath; // Dateiname der zu Testenden APP; Gesetzt ber Start
String aLogFileName; // Momentaner Logfilename (Wie Programmdatei aber mit .res)
BOOL IsBlock; // Innerhalb Begin/EndBlock
BOOL SingleCommandBlock; // Implizit um jedes kommando ein Begin/EndBlock
CmdStream *In;
void AddName(String &aBisher, String &aNeu ); // Name eventuell mit / anhngen
void AddToListByNr( CNames *&pControls, ControlItemUId *&pNewItem ); //
CNames *m_pControls;
CNames *m_pNameKontext; // Zeigt auf den aktuellen Namenskontext, der ber 'Kontext' gesetzt wurde
CNames *m_pSIds;
CNames *m_pReverseSlots; // Slots mit Kurznamen nach Nummer
CNames *m_pReverseControls; // Controls mit Kurznamen nach Nummer
CNames *m_pReverseControlsSon;// Controls mit Kurznamen nach Nummer nach Fenstern (Son)
CNames *m_pReverseUIds; // Langnamen nach Nummer
USHORT nMyVar; // Wievielte Var aus Pool ist dran
void InitTestToolObj();
CommunicationManagerClientViaSocketTT *pCommunicationManager;
void SendViaSocket();
BOOL Load( String aFileName, SbModule *pMod );
void ReadNames( String Filename, CNames *&pNames, CNames *&pUIds, BOOL bIsFlat = FALSE );
void ReadFlat( String Filename, CNames *&pNames, BOOL bSortByName );
BOOL ReadNamesBin( String Filename, CNames *&pSIds, CNames *&pControls );
BOOL WriteNamesBin( String Filename, CNames *pSIds, CNames *pControls );
void ReadHidLstByNumber();
void SortControlsByNumber( BOOL bIncludeActive = FALSE );
String GetMethodName( ULONG nMethodId );
String GetKeyName( USHORT nKeyCode );
void WaitForAnswer ();
DECL_LINK( IdleHdl, Application* );
DECL_LINK( CallDialogHandler, Application* );
String aDialogHandlerName;
USHORT nWindowHandlerCallLevel;
USHORT nIdleCount;
// wenn DialogHandler gesetzt wird er im IdleHandler inkrementiert und
// in WaitForAnswer rckgesetzt. bersteigt er einen gewissen wert, gehe ich davon aus,
// da WaitForAnswer still ligt und rufe die DialogHander Sub im BASIC auf.
void BeginBlock();
void EndBlock();
SbTextType GetSymbolType( const String &rSymbol, BOOL bWasControl );
static ControlDefLoad const arR_Cmds[];
static CNames *pRCommands;
static CErrors *pFehlerListe; // Hier werden die Fehler des Testtools gespeichert
};
#endif
<|endoftext|> |
<commit_before>/// COMPONENT
#include <csapex/model/node.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex_opencv/cv_mat_message.h>
#include <csapex/model/node_modifier.h>
namespace csapex {
using namespace csapex;
using namespace connection_types;
class BGRToIlluminationInvariant : public csapex::Node
{
public:
BGRToIlluminationInvariant() = default;
virtual ~BGRToIlluminationInvariant() = default;
virtual void process() override
{
CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
if(!in->getEncoding().matches(enc::bgr))
throw std::runtime_error("Image needs to be BGR for fitting conversion.");
CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::unknown, in->frame_id, in->stamp_micro_seconds));
out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());
CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(255));
const cv::Vec3b *src = in->value.ptr<cv::Vec3b>();
float *dst = out->value.ptr<float>();
uchar *mask = out_mask->value.ptr<uchar>();
const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);
for(std::size_t i = 0 ; i < size ; ++i) {
const cv::Vec3b &p = src[i];
if(p[0] == 0 || p[1] == 0 || p[2] == 0) {
mask[i] = 0;
} else {
dst[i] = 0.5 + std::log(p[1]) - alpha_ * std::log(p[0]) - (1.0 - alpha_) * std::log(p[2]);
}
}
msg::publish(output_, out);
msg::publish(output_mask_, out_mask);
}
virtual void setup(csapex::NodeModifier& node_modifier) override
{
input_ = node_modifier.addInput<CvMatMessage>("original");
output_ = node_modifier.addOutput<CvMatMessage>("adjusted");
output_mask_ = node_modifier.addOutput<CvMatMessage>("mask");
}
virtual void setupParameters(Parameterizable ¶meters)
{
parameters.addParameter(param::ParameterFactory::declareRange("alpha", 0.0, 1.0, 1.5, 0.001),
alpha_);
parameters.addParameter(param::ParameterFactory::declareBool("normalize", true),
normalize_);
}
protected:
csapex::Output* output_;
csapex::Output* output_mask_;
csapex::Input* input_;
double alpha_;
bool normalize_;
};
}
CSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)
<commit_msg>stuff<commit_after>/// COMPONENT
#include <csapex/model/node.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex_opencv/cv_mat_message.h>
#include <csapex/model/node_modifier.h>
namespace csapex {
using namespace csapex;
using namespace connection_types;
class BGRToIlluminationInvariant : public csapex::Node
{
public:
BGRToIlluminationInvariant() = default;
virtual ~BGRToIlluminationInvariant() = default;
virtual void process() override
{
CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
if(!in->getEncoding().matches(enc::bgr))
throw std::runtime_error("Image needs to be BGR for fitting conversion.");
CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::unknown, in->frame_id, in->stamp_micro_seconds));
out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());
CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(255));
const cv::Vec3b *src = in->value.ptr<cv::Vec3b>();
float *dst = out->value.ptr<float>();
uchar *mask = out_mask->value.ptr<uchar>();
const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);
for(std::size_t i = 0 ; i < size ; ++i) {
const cv::Vec3b &p = src[i];
if(p[0] == 0 || p[1] == 0 || p[2] == 0) {
mask[i] = 0;
}
dst[i] = 0.5 + std::log(p[1]) - alpha_ * std::log(p[0]) - (1.0 - alpha_) * std::log(p[2]);
}
msg::publish(output_, out);
msg::publish(output_mask_, out_mask);
}
virtual void setup(csapex::NodeModifier& node_modifier) override
{
input_ = node_modifier.addInput<CvMatMessage>("original");
output_ = node_modifier.addOutput<CvMatMessage>("adjusted");
output_mask_ = node_modifier.addOutput<CvMatMessage>("mask");
}
virtual void setupParameters(Parameterizable ¶meters)
{
parameters.addParameter(param::ParameterFactory::declareRange("alpha", 0.0, 1.0, 1.5, 0.001),
alpha_);
parameters.addParameter(param::ParameterFactory::declareBool("normalize", true),
normalize_);
}
protected:
csapex::Output* output_;
csapex::Output* output_mask_;
csapex::Input* input_;
double alpha_;
bool normalize_;
};
}
CSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)
<|endoftext|> |
<commit_before>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate unreachable internal globals from the
// program. It uses an aggressive algorithm, searching out globals that are
// known to be alive. After it finds all of the globals which are needed, it
// deletes whatever is left over. This allows it to delete recursive chunks of
// the program which are unreachable.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
#include <unordered_map>
using namespace llvm;
#define DEBUG_TYPE "globaldce"
STATISTIC(NumAliases , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");
namespace {
struct GlobalDCE : public ModulePass {
static char ID; // Pass identification, replacement for typeid
GlobalDCE() : ModulePass(ID) {
initializeGlobalDCEPass(*PassRegistry::getPassRegistry());
}
// run - Do the GlobalDCE pass on the specified module, optionally updating
// the specified callgraph to reflect the changes.
//
bool runOnModule(Module &M) override;
private:
SmallPtrSet<GlobalValue*, 32> AliveGlobals;
SmallPtrSet<Constant *, 8> SeenConstants;
std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
/// GlobalIsNeeded - mark the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalIsNeeded(GlobalValue *GV);
void MarkUsedGlobalsAsNeeded(Constant *C);
bool RemoveUnusedGlobalValue(GlobalValue &GV);
};
}
/// Returns true if F contains only a single "ret" instruction.
static bool isEmptyFunction(Function *F) {
BasicBlock &Entry = F->getEntryBlock();
if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
return false;
ReturnInst &RI = cast<ReturnInst>(Entry.front());
return RI.getReturnValue() == nullptr;
}
char GlobalDCE::ID = 0;
INITIALIZE_PASS(GlobalDCE, "globaldce",
"Dead Global Elimination", false, false)
ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }
bool GlobalDCE::runOnModule(Module &M) {
bool Changed = false;
// Remove empty functions from the global ctors list.
Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
// Collect the set of members for each comdat.
for (Function &F : M)
if (Comdat *C = F.getComdat())
ComdatMembers.insert(std::make_pair(C, &F));
for (GlobalVariable &GV : M.globals())
if (Comdat *C = GV.getComdat())
ComdatMembers.insert(std::make_pair(C, &GV));
for (GlobalAlias &GA : M.aliases())
if (Comdat *C = GA.getComdat())
ComdatMembers.insert(std::make_pair(C, &GA));
// Loop over the module, adding globals which are obviously necessary.
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Changed |= RemoveUnusedGlobalValue(*I);
// Functions with external linkage are needed if they have a body
if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
if (!I->isDiscardableIfUnused())
GlobalIsNeeded(I);
}
}
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
Changed |= RemoveUnusedGlobalValue(*I);
// Externally visible & appending globals are needed, if they have an
// initializer.
if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
if (!I->isDiscardableIfUnused())
GlobalIsNeeded(I);
}
}
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
I != E; ++I) {
Changed |= RemoveUnusedGlobalValue(*I);
// Externally visible aliases are needed.
if (!I->isDiscardableIfUnused()) {
GlobalIsNeeded(I);
}
}
// Now that all globals which are needed are in the AliveGlobals set, we loop
// through the program, deleting those which are not alive.
//
// The first pass is to drop initializers of global variables which are dead.
std::vector<GlobalVariable*> DeadGlobalVars; // Keep track of dead globals
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
if (!AliveGlobals.count(I)) {
DeadGlobalVars.push_back(I); // Keep track of dead globals
if (I->hasInitializer()) {
Constant *Init = I->getInitializer();
I->setInitializer(nullptr);
if (isSafeToDestroyConstant(Init))
Init->destroyConstant();
}
}
// The second pass drops the bodies of functions which are dead...
std::vector<Function*> DeadFunctions;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!AliveGlobals.count(I)) {
DeadFunctions.push_back(I); // Keep track of dead globals
if (!I->isDeclaration())
I->deleteBody();
}
// The third pass drops targets of aliases which are dead...
std::vector<GlobalAlias*> DeadAliases;
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
++I)
if (!AliveGlobals.count(I)) {
DeadAliases.push_back(I);
I->setAliasee(nullptr);
}
if (!DeadFunctions.empty()) {
// Now that all interferences have been dropped, delete the actual objects
// themselves.
for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
RemoveUnusedGlobalValue(*DeadFunctions[i]);
M.getFunctionList().erase(DeadFunctions[i]);
}
NumFunctions += DeadFunctions.size();
Changed = true;
}
if (!DeadGlobalVars.empty()) {
for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
M.getGlobalList().erase(DeadGlobalVars[i]);
}
NumVariables += DeadGlobalVars.size();
Changed = true;
}
// Now delete any dead aliases.
if (!DeadAliases.empty()) {
for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
RemoveUnusedGlobalValue(*DeadAliases[i]);
M.getAliasList().erase(DeadAliases[i]);
}
NumAliases += DeadAliases.size();
Changed = true;
}
// Make sure that all memory is released
AliveGlobals.clear();
SeenConstants.clear();
ComdatMembers.clear();
return Changed;
}
/// GlobalIsNeeded - the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
// If the global is already in the set, no need to reprocess it.
if (!AliveGlobals.insert(G).second)
return;
if (Comdat *C = G->getComdat()) {
for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
GlobalIsNeeded(CM.second);
}
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
// If this is a global variable, we must make sure to add any global values
// referenced by the initializer to the alive set.
if (GV->hasInitializer())
MarkUsedGlobalsAsNeeded(GV->getInitializer());
} else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
// The target of a global alias is needed.
MarkUsedGlobalsAsNeeded(GA->getAliasee());
} else {
// Otherwise this must be a function object. We have to scan the body of
// the function looking for constants and global values which are used as
// operands. Any operands of these types must be processed to ensure that
// any globals used will be marked as needed.
Function *F = cast<Function>(G);
if (F->hasPrefixData())
MarkUsedGlobalsAsNeeded(F->getPrefixData());
if (F->hasPrologueData())
MarkUsedGlobalsAsNeeded(F->getPrologueData());
if (F->hasPersonalityFn())
MarkUsedGlobalsAsNeeded(F->getPersonalityFn());
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
GlobalIsNeeded(GV);
else if (Constant *C = dyn_cast<Constant>(*U))
MarkUsedGlobalsAsNeeded(C);
}
}
void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
return GlobalIsNeeded(GV);
// Loop over all of the operands of the constant, adding any globals they
// use to the list of needed globals.
for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
// If we've already processed this constant there's no need to do it again.
Constant *Op = dyn_cast<Constant>(*I);
if (Op && SeenConstants.insert(Op).second)
MarkUsedGlobalsAsNeeded(Op);
}
}
// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it. This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
if (GV.use_empty()) return false;
GV.removeDeadConstantUsers();
return GV.use_empty();
}
<commit_msg>Rangify for loops in GlobalDCE, NFC.<commit_after>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate unreachable internal globals from the
// program. It uses an aggressive algorithm, searching out globals that are
// known to be alive. After it finds all of the globals which are needed, it
// deletes whatever is left over. This allows it to delete recursive chunks of
// the program which are unreachable.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
#include <unordered_map>
using namespace llvm;
#define DEBUG_TYPE "globaldce"
STATISTIC(NumAliases , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");
namespace {
struct GlobalDCE : public ModulePass {
static char ID; // Pass identification, replacement for typeid
GlobalDCE() : ModulePass(ID) {
initializeGlobalDCEPass(*PassRegistry::getPassRegistry());
}
// run - Do the GlobalDCE pass on the specified module, optionally updating
// the specified callgraph to reflect the changes.
//
bool runOnModule(Module &M) override;
private:
SmallPtrSet<GlobalValue*, 32> AliveGlobals;
SmallPtrSet<Constant *, 8> SeenConstants;
std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
/// GlobalIsNeeded - mark the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalIsNeeded(GlobalValue *GV);
void MarkUsedGlobalsAsNeeded(Constant *C);
bool RemoveUnusedGlobalValue(GlobalValue &GV);
};
}
/// Returns true if F contains only a single "ret" instruction.
static bool isEmptyFunction(Function *F) {
BasicBlock &Entry = F->getEntryBlock();
if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
return false;
ReturnInst &RI = cast<ReturnInst>(Entry.front());
return RI.getReturnValue() == nullptr;
}
char GlobalDCE::ID = 0;
INITIALIZE_PASS(GlobalDCE, "globaldce",
"Dead Global Elimination", false, false)
ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }
bool GlobalDCE::runOnModule(Module &M) {
bool Changed = false;
// Remove empty functions from the global ctors list.
Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
// Collect the set of members for each comdat.
for (Function &F : M)
if (Comdat *C = F.getComdat())
ComdatMembers.insert(std::make_pair(C, &F));
for (GlobalVariable &GV : M.globals())
if (Comdat *C = GV.getComdat())
ComdatMembers.insert(std::make_pair(C, &GV));
for (GlobalAlias &GA : M.aliases())
if (Comdat *C = GA.getComdat())
ComdatMembers.insert(std::make_pair(C, &GA));
// Loop over the module, adding globals which are obviously necessary.
for (Function &F : M) {
Changed |= RemoveUnusedGlobalValue(F);
// Functions with external linkage are needed if they have a body
if (!F.isDeclaration() && !F.hasAvailableExternallyLinkage())
if (!F.isDiscardableIfUnused())
GlobalIsNeeded(&F);
}
for (GlobalVariable &GV : M.globals()) {
Changed |= RemoveUnusedGlobalValue(GV);
// Externally visible & appending globals are needed, if they have an
// initializer.
if (!GV.isDeclaration() && !GV.hasAvailableExternallyLinkage())
if (!GV.isDiscardableIfUnused())
GlobalIsNeeded(&GV);
}
for (GlobalAlias &GA : M.aliases()) {
Changed |= RemoveUnusedGlobalValue(GA);
// Externally visible aliases are needed.
if (!GA.isDiscardableIfUnused())
GlobalIsNeeded(&GA);
}
// Now that all globals which are needed are in the AliveGlobals set, we loop
// through the program, deleting those which are not alive.
//
// The first pass is to drop initializers of global variables which are dead.
std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
for (GlobalVariable &GV : M.globals())
if (!AliveGlobals.count(&GV)) {
DeadGlobalVars.push_back(&GV); // Keep track of dead globals
if (GV.hasInitializer()) {
Constant *Init = GV.getInitializer();
GV.setInitializer(nullptr);
if (isSafeToDestroyConstant(Init))
Init->destroyConstant();
}
}
// The second pass drops the bodies of functions which are dead...
std::vector<Function *> DeadFunctions;
for (Function &F : M)
if (!AliveGlobals.count(&F)) {
DeadFunctions.push_back(&F); // Keep track of dead globals
if (!F.isDeclaration())
F.deleteBody();
}
// The third pass drops targets of aliases which are dead...
std::vector<GlobalAlias*> DeadAliases;
for (GlobalAlias &GA : M.aliases())
if (!AliveGlobals.count(&GA)) {
DeadAliases.push_back(&GA);
GA.setAliasee(nullptr);
}
if (!DeadFunctions.empty()) {
// Now that all interferences have been dropped, delete the actual objects
// themselves.
for (Function *F : DeadFunctions) {
RemoveUnusedGlobalValue(*F);
M.getFunctionList().erase(F);
}
NumFunctions += DeadFunctions.size();
Changed = true;
}
if (!DeadGlobalVars.empty()) {
for (GlobalVariable *GV : DeadGlobalVars) {
RemoveUnusedGlobalValue(*GV);
M.getGlobalList().erase(GV);
}
NumVariables += DeadGlobalVars.size();
Changed = true;
}
// Now delete any dead aliases.
if (!DeadAliases.empty()) {
for (GlobalAlias *GA : DeadAliases) {
RemoveUnusedGlobalValue(*GA);
M.getAliasList().erase(GA);
}
NumAliases += DeadAliases.size();
Changed = true;
}
// Make sure that all memory is released
AliveGlobals.clear();
SeenConstants.clear();
ComdatMembers.clear();
return Changed;
}
/// GlobalIsNeeded - the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
// If the global is already in the set, no need to reprocess it.
if (!AliveGlobals.insert(G).second)
return;
if (Comdat *C = G->getComdat()) {
for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
GlobalIsNeeded(CM.second);
}
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
// If this is a global variable, we must make sure to add any global values
// referenced by the initializer to the alive set.
if (GV->hasInitializer())
MarkUsedGlobalsAsNeeded(GV->getInitializer());
} else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
// The target of a global alias is needed.
MarkUsedGlobalsAsNeeded(GA->getAliasee());
} else {
// Otherwise this must be a function object. We have to scan the body of
// the function looking for constants and global values which are used as
// operands. Any operands of these types must be processed to ensure that
// any globals used will be marked as needed.
Function *F = cast<Function>(G);
if (F->hasPrefixData())
MarkUsedGlobalsAsNeeded(F->getPrefixData());
if (F->hasPrologueData())
MarkUsedGlobalsAsNeeded(F->getPrologueData());
if (F->hasPersonalityFn())
MarkUsedGlobalsAsNeeded(F->getPersonalityFn());
for (BasicBlock &BB : *F)
for (Instruction &I : BB)
for (Use &U : I.operands())
if (GlobalValue *GV = dyn_cast<GlobalValue>(U))
GlobalIsNeeded(GV);
else if (Constant *C = dyn_cast<Constant>(U))
MarkUsedGlobalsAsNeeded(C);
}
}
void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
return GlobalIsNeeded(GV);
// Loop over all of the operands of the constant, adding any globals they
// use to the list of needed globals.
for (Use &U : C->operands()) {
// If we've already processed this constant there's no need to do it again.
Constant *Op = dyn_cast<Constant>(U);
if (Op && SeenConstants.insert(Op).second)
MarkUsedGlobalsAsNeeded(Op);
}
}
// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it. This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
if (GV.use_empty())
return false;
GV.removeDeadConstantUsers();
return GV.use_empty();
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreGLSLESExtSupport.h"
#include "OgreLogManager.h"
namespace Ogre
{
//-----------------------------------------------------------------------------
String logObjectInfo(const String& msg, const GLuint obj)
{
String logMessage = msg;
if (obj > 0)
{
GLint infologLength = 0;
if(glIsShader(obj))
{
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
#if GL_EXT_separate_shader_objects
else if(glIsProgramPipelineEXT(obj))
{
glValidateProgramPipelineEXT(obj);
glGetProgramPipelineivEXT(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
#endif
else if(glIsProgram(obj))
{
glValidateProgram(obj);
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
if (infologLength > 1)
{
GLint charsWritten = 0;
char * infoLog = new char [infologLength];
infoLog[0] = 0;
if(glIsShader(obj))
{
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
#if GL_EXT_separate_shader_objects
else if(glIsProgramPipelineEXT(obj))
{
glGetProgramPipelineInfoLogEXT(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
#endif
else if(glIsProgram(obj))
{
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
if (strlen(infoLog) > 0)
{
logMessage += "\n" + String(infoLog);
}
OGRE_DELETE [] infoLog;
if (logMessage.size() > 0)
{
// remove ends of line in the end - so there will be no empty lines in the log.
while( logMessage[logMessage.size() - 1] == '\n' )
{
logMessage.erase(logMessage.size() - 1, 1);
}
LogManager::getSingleton().logMessage(logMessage);
}
}
}
return logMessage;
}
} // namespace Ogre
<commit_msg>GLES2: Guard program pipeline checks at runtime to fix running on iOS < 5.0.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreGLSLESExtSupport.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
namespace Ogre
{
//-----------------------------------------------------------------------------
String logObjectInfo(const String& msg, const GLuint obj)
{
String logMessage = msg;
if (obj > 0)
{
GLint infologLength = 0;
if(glIsShader(obj))
{
glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
#if GL_EXT_separate_shader_objects
else if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS) &&
glIsProgramPipelineEXT(obj))
{
glValidateProgramPipelineEXT(obj);
glGetProgramPipelineivEXT(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
#endif
else if(glIsProgram(obj))
{
glValidateProgram(obj);
glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);
GL_CHECK_ERROR
}
if (infologLength > 1)
{
GLint charsWritten = 0;
char * infoLog = new char [infologLength];
infoLog[0] = 0;
if(glIsShader(obj))
{
glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
#if GL_EXT_separate_shader_objects
else if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS) &&
glIsProgramPipelineEXT(obj))
{
glGetProgramPipelineInfoLogEXT(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
#endif
else if(glIsProgram(obj))
{
glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);
GL_CHECK_ERROR
}
if (strlen(infoLog) > 0)
{
logMessage += "\n" + String(infoLog);
}
OGRE_DELETE [] infoLog;
if (logMessage.size() > 0)
{
// remove ends of line in the end - so there will be no empty lines in the log.
while( logMessage[logMessage.size() - 1] == '\n' )
{
logMessage.erase(logMessage.size() - 1, 1);
}
LogManager::getSingleton().logMessage(logMessage);
}
}
}
return logMessage;
}
} // namespace Ogre
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBasicFiltersTests2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkBasicFiltersPrintTest );
REGISTER_TEST(itkBasicFiltersPrintTest2 );
REGISTER_TEST(itkComplexToImaginaryFilterAndAdaptorTest );
REGISTER_TEST(itkComplexToRealFilterAndAdaptorTest );
REGISTER_TEST(itkComplexToModulusFilterAndAdaptorTest );
REGISTER_TEST(itkComplexToPhaseFilterAndAdaptorTest );
REGISTER_TEST(itkConstrainedValueAdditionImageFilterTest );
REGISTER_TEST(itkConstrainedValueDifferenceImageFilterTest );
REGISTER_TEST(itkContourDirectedMeanDistanceImageFilterTest );
REGISTER_TEST(itkContourMeanDistanceImageFilterTest );
REGISTER_TEST(itkDeformationFieldJacobianDeterminantFilterTest );
REGISTER_TEST(itkGrayscaleMorphologicalClosingImageFilterTest );
REGISTER_TEST(itkGrayscaleMorphologicalOpeningImageFilterTest );
REGISTER_TEST(itkJoinSeriesImageFilterPrintTest);
REGISTER_TEST(itkJoinSeriesImageFilterTest );
REGISTER_TEST(itkShiftScaleImageFilterTest );
REGISTER_TEST(itkShiftScaleInPlaceImageFilterTest );
REGISTER_TEST(itkShrinkImageTest );
REGISTER_TEST(itkSigmoidImageFilterTest );
REGISTER_TEST(itkSignedDanielssonDistanceMapImageFilterTest );
REGISTER_TEST(itkSimilarityIndexImageFilterTest );
REGISTER_TEST(itkSimpleContourExtractorImageFilterTest );
REGISTER_TEST(itkSimplexMeshAdaptTopologyFilterTest);
REGISTER_TEST(itkSimplexMeshToTriangleMeshFilterTest);
REGISTER_TEST(itkSinImageFilterAndAdaptorTest );
REGISTER_TEST(itkSmoothingRecursiveGaussianImageFilterTest );
REGISTER_TEST(itkSobelEdgeDetectionImageFilterTest );
REGISTER_TEST(itkSparseFieldFourthOrderLevelSetImageFilterTest );
REGISTER_TEST(itkSparseFieldLayerTest);
REGISTER_TEST(itkSpatialFunctionImageEvaluatorFilterTest );
REGISTER_TEST(itkSpatialObjectToImageFilterTest );
REGISTER_TEST(itkSpatialObjectToImageStatisticsCalculatorTest );
REGISTER_TEST(itkSpatialObjectToPointSetFilterTest );
REGISTER_TEST(itkSqrtImageFilterAndAdaptorTest );
REGISTER_TEST(itkSquareImageFilterTest );
REGISTER_TEST(itkSquaredDifferenceImageFilterTest );
REGISTER_TEST(itkStatisticsImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest );
REGISTER_TEST(itkStreamingImageFilterTest2 );
REGISTER_TEST(itkSubtractImageFilterTest );
REGISTER_TEST(itkTanImageFilterAndAdaptorTest );
REGISTER_TEST(itkTernaryMagnitudeImageFilterTest );
REGISTER_TEST(itkThresholdImageFilterTest );
REGISTER_TEST(itkThresholdLabelerImageFilterTest );
REGISTER_TEST(itkTileImageFilterTest );
REGISTER_TEST(itkTobogganImageFilterTest );
REGISTER_TEST(itkTransformMeshFilterTest );
REGISTER_TEST(itkTriangleMeshToSimplexMeshFilter2Test);
REGISTER_TEST(itkTriangleMeshToSimplexMeshFilterTest);
REGISTER_TEST(itkTwoOutputExampleImageFilterTest );
}
<commit_msg>ENH: added test for 3D rasterization<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBasicFiltersTests2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests
#include <iostream>
#include "itkTestMain.h"
void RegisterTests()
{
REGISTER_TEST(itkBasicFiltersPrintTest );
REGISTER_TEST(itkBasicFiltersPrintTest2 );
REGISTER_TEST(itkComplexToRealFilterAndAdaptorTest );
REGISTER_TEST(itkComplexToImaginaryFilterAndAdaptorTest );
REGISTER_TEST(itkConstrainedValueAdditionImageFilterTest );
REGISTER_TEST(itkConstrainedValueDifferenceImageFilterTest );
REGISTER_TEST(itkContourDirectedMeanDistanceImageFilterTest );
REGISTER_TEST(itkContourMeanDistanceImageFilterTest );
REGISTER_TEST(itkDeformationFieldJacobianDeterminantFilterTest );
REGISTER_TEST(itkGrayscaleMorphologicalClosingImageFilterTest );
REGISTER_TEST(itkGrayscaleMorphologicalOpeningImageFilterTest );
REGISTER_TEST(itkJoinSeriesImageFilterTest );
REGISTER_TEST(itkJoinSeriesImageFilterPrintTest);
REGISTER_TEST(itkSimpleContourExtractorImageFilterTest );
REGISTER_TEST(itkTanImageFilterAndAdaptorTest );
REGISTER_TEST(itkTernaryMagnitudeImageFilterTest );
REGISTER_TEST(itkTileImageFilterTest );
REGISTER_TEST(itkThresholdImageFilterTest );
REGISTER_TEST(itkThresholdLabelerImageFilterTest );
REGISTER_TEST(itkTobogganImageFilterTest );
REGISTER_TEST(itkTransformMeshFilterTest );
REGISTER_TEST(itkTriangleMeshToBinaryImageFilterTest );
REGISTER_TEST(itkTriangleMeshToSimplexMeshFilterTest);
REGISTER_TEST(itkTriangleMeshToSimplexMeshFilter2Test);
REGISTER_TEST(itkTwoOutputExampleImageFilterTest );
REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest );
REGISTER_TEST(itkVectorExpandImageFilterTest );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest1 );
REGISTER_TEST(itkVectorGradientMagnitudeImageFilterTest2 );
REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest );
REGISTER_TEST(itkVectorConfidenceConnectedImageFilterTest );
REGISTER_TEST(itkVectorResampleImageFilterTest );
REGISTER_TEST(itkVectorRescaleIntensityImageFilterTest );
REGISTER_TEST(itkVotingBinaryImageFilterTest );
REGISTER_TEST(itkVotingBinaryHoleFillingImageFilterTest );
REGISTER_TEST(itkVotingBinaryIterativeHoleFillingImageFilterTest );
REGISTER_TEST(itkWarpImageFilterTest );
REGISTER_TEST(itkWarpMeshFilterTest );
REGISTER_TEST(itkWeightedAddImageFilterTest);
REGISTER_TEST(itkWarpVectorImageFilterTest );
REGISTER_TEST(itkWrapPadImageTest );
REGISTER_TEST(itkXorImageFilterTest );
REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest );
REGISTER_TEST(itkZeroCrossingImageFilterTest );
}
<|endoftext|> |
<commit_before>//
// Arduino library for controlling TI's TLC59711
//
// 21 Feb 2016 by Ulrich Stern
//
// open source (see LICENSE file)
//
#include "Tlc59711.h"
#include <SPI.h>
Tlc59711::Tlc59711(uint16_t numTlc, uint8_t clkPin, uint8_t dataPin):
numTlc(numTlc), bufferSz(14*numTlc), clkPin(clkPin), dataPin(dataPin),
buffer((uint16_t*) calloc(bufferSz, 2)), buffer2(0),
beginCalled(false) {
setTmgrst();
}
Tlc59711::~Tlc59711() {
free(buffer);
free(buffer2);
}
void Tlc59711::begin(bool useSpi, unsigned int postXferDelayMicros) {
end();
useSpi_ = useSpi;
postXferDelayMicros_ = postXferDelayMicros;
beginCalled = true;
}
void Tlc59711::beginFast(bool bufferXfer, uint32_t spiClock,
unsigned int postXferDelayMicros) {
begin(true, postXferDelayMicros);
bufferXfer_ = bufferXfer;
SPI.begin();
SPI.beginTransaction(SPISettings(spiClock, MSBFIRST, SPI_MODE0));
if (bufferXfer && !buffer2)
buffer2 = (uint16_t*) malloc(2*bufferSz);
}
void Tlc59711::beginSlow(unsigned int postXferDelayMicros, bool interrupts) {
begin(false, postXferDelayMicros);
noInterrupts = !interrupts;
pinMode(clkPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void Tlc59711::setTmgrst(bool val) {
// OUTTMG = 1, EXTGCK = 0, TMGRST = 0, DSPRPT = 1, BLANK = 0 -> 0x12
fc = 0x12 + (val ? 0x4 : 0);
setBrightness();
}
void Tlc59711::setBrightness(uint16_t tlcIdx,
uint8_t bcr, uint8_t bcg, uint8_t bcb) {
if (tlcIdx < numTlc) {
uint32_t ms32 = (uint32_t)0x25 << 26 | (uint32_t)fc << 21 |
(uint32_t)bcb << 14 | (uint32_t)bcg << 7 | bcr;
uint16_t idx = 14*tlcIdx+12;
buffer[idx] = ms32;
buffer[++idx] = ms32 >> 16;
}
}
void Tlc59711::setBrightness(uint8_t bcr, uint8_t bcg, uint8_t bcb) {
for (uint16_t i=0; i<numTlc; i++)
setBrightness(i, bcr, bcg, bcb);
}
void Tlc59711::setChannel(uint16_t idx, uint16_t val) {
idx = 14*(idx/12) + idx%12;
if (idx < bufferSz)
buffer[idx] = val;
}
void Tlc59711::setRGB(uint16_t idx, uint16_t r, uint16_t g, uint16_t b) {
idx = 3*idx;
setChannel(idx, r);
setChannel(++idx, g);
setChannel(++idx, b);
}
void Tlc59711::setRGB(uint16_t r, uint16_t g, uint16_t b) {
for (uint16_t i=0, n=4*numTlc; i<n; i++)
setRGB(i, r, g, b);
}
static void reverseMemcpy(void *dst, void *src, size_t count) {
uint8_t* s = (uint8_t*)src;
while (count-- > 0)
*((uint8_t*)dst+count) = *s++;
}
void Tlc59711::xferSpi() {
reverseMemcpy(buffer2, buffer, bufferSz*2);
cli();
SPI.transfer(buffer2, bufferSz*2);
}
void Tlc59711::xferSpi16() {
cli();
for (int i=bufferSz-1; i >= 0; i--)
SPI.transfer16(buffer[i]);
}
void Tlc59711::xferShiftOut() {
if (noInterrupts)
cli();
for (int i=bufferSz-1; i >= 0; i--) {
uint16_t val = buffer[i];
shiftOut(dataPin, clkPin, MSBFIRST, val >> 8);
shiftOut(dataPin, clkPin, MSBFIRST, val);
}
}
void Tlc59711::write() {
if (!beginCalled)
return;
if (useSpi_) {
if (bufferXfer_)
xferSpi();
else
xferSpi16();
}
else
xferShiftOut();
sei();
// delay to make sure the TLC59711s read (latch) their shift registers;
// the delay required is 8 times the duration between the last two SCKI
// rising edges (plus 1.34 us); see datasheet pg. 22 for details
delayMicroseconds(postXferDelayMicros_);
}
void Tlc59711::end() {
if (beginCalled && useSpi_) {
SPI.endTransaction();
SPI.end();
}
}
<commit_msg>write() no longer calls sei()<commit_after>//
// Arduino library for controlling TI's TLC59711
//
// 21 Feb 2016 by Ulrich Stern
//
// open source (see LICENSE file)
//
#include "Tlc59711.h"
#include <SPI.h>
Tlc59711::Tlc59711(uint16_t numTlc, uint8_t clkPin, uint8_t dataPin):
numTlc(numTlc), bufferSz(14*numTlc), clkPin(clkPin), dataPin(dataPin),
buffer((uint16_t*) calloc(bufferSz, 2)), buffer2(0),
beginCalled(false) {
setTmgrst();
}
Tlc59711::~Tlc59711() {
free(buffer);
free(buffer2);
}
void Tlc59711::begin(bool useSpi, unsigned int postXferDelayMicros) {
end();
useSpi_ = useSpi;
postXferDelayMicros_ = postXferDelayMicros;
beginCalled = true;
}
void Tlc59711::beginFast(bool bufferXfer, uint32_t spiClock,
unsigned int postXferDelayMicros) {
begin(true, postXferDelayMicros);
bufferXfer_ = bufferXfer;
SPI.begin();
SPI.beginTransaction(SPISettings(spiClock, MSBFIRST, SPI_MODE0));
if (bufferXfer && !buffer2)
buffer2 = (uint16_t*) malloc(2*bufferSz);
}
void Tlc59711::beginSlow(unsigned int postXferDelayMicros, bool interrupts) {
begin(false, postXferDelayMicros);
noInterrupts = !interrupts;
pinMode(clkPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void Tlc59711::setTmgrst(bool val) {
// OUTTMG = 1, EXTGCK = 0, TMGRST = 0, DSPRPT = 1, BLANK = 0 -> 0x12
fc = 0x12 + (val ? 0x4 : 0);
setBrightness();
}
void Tlc59711::setBrightness(uint16_t tlcIdx,
uint8_t bcr, uint8_t bcg, uint8_t bcb) {
if (tlcIdx < numTlc) {
uint32_t ms32 = (uint32_t)0x25 << 26 | (uint32_t)fc << 21 |
(uint32_t)bcb << 14 | (uint32_t)bcg << 7 | bcr;
uint16_t idx = 14*tlcIdx+12;
buffer[idx] = ms32;
buffer[++idx] = ms32 >> 16;
}
}
void Tlc59711::setBrightness(uint8_t bcr, uint8_t bcg, uint8_t bcb) {
for (uint16_t i=0; i<numTlc; i++)
setBrightness(i, bcr, bcg, bcb);
}
void Tlc59711::setChannel(uint16_t idx, uint16_t val) {
idx = 14*(idx/12) + idx%12;
if (idx < bufferSz)
buffer[idx] = val;
}
void Tlc59711::setRGB(uint16_t idx, uint16_t r, uint16_t g, uint16_t b) {
idx = 3*idx;
setChannel(idx, r);
setChannel(++idx, g);
setChannel(++idx, b);
}
void Tlc59711::setRGB(uint16_t r, uint16_t g, uint16_t b) {
for (uint16_t i=0, n=4*numTlc; i<n; i++)
setRGB(i, r, g, b);
}
static void reverseMemcpy(void *dst, void *src, size_t count) {
uint8_t* s = (uint8_t*)src;
while (count-- > 0)
*((uint8_t*)dst+count) = *s++;
}
void Tlc59711::xferSpi() {
reverseMemcpy(buffer2, buffer, bufferSz*2);
cli();
SPI.transfer(buffer2, bufferSz*2);
}
void Tlc59711::xferSpi16() {
cli();
for (int i=bufferSz-1; i >= 0; i--)
SPI.transfer16(buffer[i]);
}
void Tlc59711::xferShiftOut() {
if (noInterrupts)
cli();
for (int i=bufferSz-1; i >= 0; i--) {
uint16_t val = buffer[i];
shiftOut(dataPin, clkPin, MSBFIRST, val >> 8);
shiftOut(dataPin, clkPin, MSBFIRST, val);
}
}
void Tlc59711::write() {
if (!beginCalled)
return;
uint8_t oldSREG = SREG;
if (useSpi_) {
if (bufferXfer_)
xferSpi();
else
xferSpi16();
}
else
xferShiftOut();
SREG = oldSREG;
// delay to make sure the TLC59711s read (latch) their shift registers;
// the delay required is 8 times the duration between the last two SCKI
// rising edges (plus 1.34 us); see datasheet pg. 22 for details
delayMicroseconds(postXferDelayMicros_);
}
void Tlc59711::end() {
if (beginCalled && useSpi_) {
SPI.endTransaction();
SPI.end();
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkFixedArray.h"
#include "otbTimeSeriesLeastSquareFittingFunctor.h"
#include "otbTimeSeries.h"
int otbTimeSeriesLeastSquareFittingFunctorTest(int argc, char* argv[])
{
const unsigned int Degree = 2;
typedef double CoefficientPrecisionType;
typedef otb::PolynomialTimeSeries< Degree, CoefficientPrecisionType > FunctionType;
const unsigned int nbDates = 100;
typedef float PixelType;
typedef unsigned int DoYType;
typedef itk::FixedArray< PixelType, nbDates > SeriesType;
typedef itk::FixedArray< DoYType, nbDates > DatesType;
typedef otb::Functor::TimeSeriesLeastSquareFittingFunctor<SeriesType, FunctionType, DatesType> FunctorType;
DatesType doySeries;
// one acquisition every 2 days
for(unsigned int i = 0; i<nbDates; i++)
doySeries[i] = 2*i;
SeriesType inSeries;
FunctorType::CoefficientsType inCoefs;
inCoefs[0] = ::atof(argv[1]);
inCoefs[1] = ::atof(argv[2]);
inCoefs[2] = ::atof(argv[3]);
// x = a + b * t + c * t^2
for(unsigned int i = 0; i<nbDates; i++)
inSeries[i] = inCoefs[0]+inCoefs[1]*doySeries[i]+inCoefs[2]*vcl_pow(doySeries[i],2.0);
FunctorType f;
f.SetDates( doySeries );
SeriesType outSeries = f(inSeries);
FunctorType::CoefficientsType outCoefs = f.GetCoefficients();
for(unsigned int i=0; i<= Degree; i++)
if(outCoefs[i]!=inCoefs[i])
{
std::cout << outCoefs[i] << " != " << inCoefs[i] << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>TEST: add some tolerance to the comparison<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkFixedArray.h"
#include "otbTimeSeriesLeastSquareFittingFunctor.h"
#include "otbTimeSeries.h"
int otbTimeSeriesLeastSquareFittingFunctorTest(int argc, char* argv[])
{
const unsigned int Degree = 2;
typedef double CoefficientPrecisionType;
typedef otb::PolynomialTimeSeries< Degree, CoefficientPrecisionType > FunctionType;
const unsigned int nbDates = 100;
typedef float PixelType;
typedef unsigned int DoYType;
typedef itk::FixedArray< PixelType, nbDates > SeriesType;
typedef itk::FixedArray< DoYType, nbDates > DatesType;
typedef otb::Functor::TimeSeriesLeastSquareFittingFunctor<SeriesType, FunctionType, DatesType> FunctorType;
DatesType doySeries;
// one acquisition every 2 days
for(unsigned int i = 0; i<nbDates; i++)
doySeries[i] = 2*i;
SeriesType inSeries;
FunctorType::CoefficientsType inCoefs;
inCoefs[0] = ::atof(argv[1]);
inCoefs[1] = ::atof(argv[2]);
inCoefs[2] = ::atof(argv[3]);
// x = a + b * t + c * t^2
for(unsigned int i = 0; i<nbDates; i++)
inSeries[i] = inCoefs[0]+inCoefs[1]*doySeries[i]+inCoefs[2]*vcl_pow(doySeries[i],2.0);
FunctorType f;
f.SetDates( doySeries );
SeriesType outSeries = f(inSeries);
FunctorType::CoefficientsType outCoefs = f.GetCoefficients();
for(unsigned int i=0; i<= Degree; i++)
if(fabs((outCoefs[i]-inCoefs[i])/inCoefs[i])>0.01)
{
std::cout << outCoefs[i] << " != " << inCoefs[i] << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>
// This is just a test.
#include <iostream>
#include <string>
int main(){
std::cout << "Helloooooo test!" << std::endl;
return 0;
}
<commit_msg>Remove test files<commit_after><|endoftext|> |
<commit_before>/* Copyright 2016 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.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/util/cuda_kernel_helper.h"
// TODO(yangzihao): Remove the dependency of conv_2d.h once we move all
// GPU util functions and transpose kernels into separate files.
#include "tensorflow/core/kernels/conv_2d.h"
typedef Eigen::GpuDevice GPUDevice;
namespace tensorflow {
namespace internal {
template <typename T, bool conjugate>
__global__ void TransposeKernel(int nthreads, const T* src, const int32* buf,
const int32 ndims, T* dst) {
const int32* in_strides = buf;
const int32* out_strides = buf + ndims;
const int32* perm = buf + ndims * 2;
CUDA_1D_KERNEL_LOOP(o_idx, nthreads) {
int32 i_idx = 0;
int32 t = o_idx;
for (int32 i = 0; i < ndims; ++i) {
const int32 ratio = t / out_strides[i];
t -= ratio * out_strides[i];
i_idx += ratio * in_strides[perm[i]];
}
if (conjugate) {
dst[o_idx] = Eigen::numext::conj(ldg(src + i_idx));
} else {
dst[o_idx] = ldg(src + i_idx);
}
}
}
template <typename T, bool conjugate>
void TransposeSimple(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
// Ensures we can use 32-bit index.
const int64 nelem = in.NumElements();
CHECK_LT(nelem, kint32max) << "Tensor too large to transpose on GPU";
// Pack strides and permutation into one buffer.
const int32 ndims = in.dims();
gtl::InlinedVector<int32, 24> host_buf(ndims * 3);
gtl::InlinedVector<int32, 8> in_strides = ComputeStride<int32>(in.shape());
gtl::InlinedVector<int32, 8> out_strides = ComputeStride<int32>(out->shape());
// Dimension permutation.
for (int i = 0; i < ndims; ++i) {
host_buf[i] = in_strides[i];
host_buf[ndims + i] = out_strides[i];
host_buf[ndims * 2 + i] = perm[i];
}
// Copies the input strides, output strides and permutation to the device.
auto num_bytes = sizeof(int64) * host_buf.size();
auto dev_buf = d.allocate(num_bytes);
// NOTE: host_buf is not allocated by CudaHostAllocator, and
// therefore we are doing a sync copy effectively.
d.memcpyHostToDevice(dev_buf, host_buf.data(), num_bytes);
// Launch kernel to q[...] = p[...].
const T* p = reinterpret_cast<const T*>(in.tensor_data().data());
T* q = reinterpret_cast<T*>(const_cast<char*>((out->tensor_data().data())));
CudaLaunchConfig cfg = GetCudaLaunchConfig(nelem, d);
TF_CHECK_OK(CudaLaunchKernel(
TransposeKernel<T, conjugate>, cfg.block_count, cfg.thread_per_block, 0,
d.stream(), cfg.virtual_thread_count, p,
reinterpret_cast<const int32*>(dev_buf), ndims, q));
// Safe to deallocate immediately after the kernel launch.
d.deallocate(dev_buf);
}
// TransposeUsingTile tries to reduce the dimension of the input tensor to 3 and
// then call special kernels to swap either dimension 1 and dimension 2 or
// dimension 0 and dimension 2. It returns true if the operation is success,
// false otherwise.
template <typename T, bool conjugate = false>
struct TransposeUsingTile {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
// First try to reduce the dimensions of the input tensor.
TransposePermsVec new_perm;
TransposeDimsVec new_dims;
ReduceTransposeDimensions(in.shape(), perm, &new_perm, &new_dims);
// Only use special GPU kernel when dimension is 2 or 3.
int dims = new_dims.size();
if (dims < 2 || dims > 3) return false;
auto in_data = reinterpret_cast<const T*>(in.tensor_data().data());
auto out_data =
reinterpret_cast<T*>(const_cast<char*>(out->tensor_data().data()));
switch (dims) {
case 2:
if (new_perm[0] == 1 && new_perm[1] == 0) {
// Add the first dimension size as 1.
new_dims.insert(new_dims.begin(), 1);
tensorflow::functor::SwapDimension1And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
}
break;
case 3:
if (new_perm == TransposePermsVec({0, 2, 1})) {
tensorflow::functor::SwapDimension1And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
} else if (new_perm == TransposePermsVec({2, 1, 0})) {
tensorflow::functor::SwapDimension0And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
} else {
// do not handle other 3D permutations
return false;
}
break;
default:
return false;
}
return false;
}
};
template <bool conjugate>
struct TransposeUsingTile<complex64, conjugate> {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
if (!conjugate) {
return TransposeUsingTile<uint64>::run(d, in, perm, out);
} else {
return TransposeUsingTile<float2, true>::run(d, in, perm, out);
}
}
};
template <bool conjugate>
struct TransposeUsingTile<complex128, conjugate> {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
if (!conjugate) {
return TransposeUsingTile<float4>::run(d, in, perm, out);
} else {
return TransposeUsingTile<double2, true>::run(d, in, perm, out);
}
}
};
} // namespace internal
// Transpose kernel specialized for GPU Device.
template <typename T, bool conjugate>
struct Transpose<GPUDevice, T, conjugate> {
static void run(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
switch (in.dims()) {
case 2:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 2>(d, in, perm, conjugate,
out);
}
break;
case 3:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 3>(d, in, perm, conjugate,
out);
}
break;
case 4:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 4>(d, in, perm, conjugate,
out);
}
break;
case 5:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 5>(d, in, perm, conjugate,
out);
}
break;
case 6:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 6>(d, in, perm, conjugate,
out);
}
break;
case 7:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 7>(d, in, perm, conjugate,
out);
}
break;
case 8:
if (!internal::TransposeUsingTile<T, conjugate>::run(d, in, perm,
out)) {
internal::TransposeUsingEigen<GPUDevice, T, 8>(d, in, perm, conjugate,
out);
}
break;
default:
internal::TransposeSimple<T, conjugate>(d, in, perm, out);
break;
}
}
};
template <bool conjugate>
struct Transpose<GPUDevice, string, conjugate> {
static void run(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
LOG(FATAL) << "Transpose of DT_STRING tensor not supported on GPU.";
}
};
// Explicit instantiation.
template struct Transpose<GPUDevice, string, false>;
template <>
Status DoTranspose(const GPUDevice& device, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
return internal::DoTransposeImpl(device, in, perm, /*conjugate=*/false, out);
}
template <>
Status DoConjugateTranspose(const GPUDevice& device, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
return internal::DoTransposeImpl(device, in, perm, /*conjugate=*/true, out);
}
template <>
Status DoMatrixTranspose(const GPUDevice& device, const Tensor& in,
Tensor* out) {
return internal::DoMatrixTransposeImpl(device, in, /*conjugate=*/false, out);
}
template <>
Status DoConjugateMatrixTranspose(const GPUDevice& device, const Tensor& in,
Tensor* out) {
return internal::DoMatrixTransposeImpl(device, in, /*conjugate=*/true, out);
}
} // namespace tensorflow
#endif // GOOGLE_CUDA
<commit_msg>Small cleanup of transpose_functor_gpu.cu.cc.<commit_after>/* Copyright 2016 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.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/util/cuda_kernel_helper.h"
// TODO(yangzihao): Remove the dependency of conv_2d.h once we move all
// GPU util functions and transpose kernels into separate files.
#include "tensorflow/core/kernels/conv_2d.h"
typedef Eigen::GpuDevice GPUDevice;
namespace tensorflow {
namespace internal {
template <typename T, bool conjugate>
__global__ void TransposeKernel(int nthreads, const T* src, const int32* buf,
const int32 ndims, T* dst) {
const int32* in_strides = buf;
const int32* out_strides = buf + ndims;
const int32* perm = buf + ndims * 2;
CUDA_1D_KERNEL_LOOP(o_idx, nthreads) {
int32 i_idx = 0;
int32 t = o_idx;
for (int32 i = 0; i < ndims; ++i) {
const int32 ratio = t / out_strides[i];
t -= ratio * out_strides[i];
i_idx += ratio * in_strides[perm[i]];
}
if (conjugate) {
dst[o_idx] = Eigen::numext::conj(ldg(src + i_idx));
} else {
dst[o_idx] = ldg(src + i_idx);
}
}
}
template <typename T, bool conjugate>
void TransposeSimple(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
// Ensures we can use 32-bit index.
const int64 nelem = in.NumElements();
CHECK_LT(nelem, kint32max) << "Tensor too large to transpose on GPU";
// Pack strides and permutation into one buffer.
const int32 ndims = in.dims();
gtl::InlinedVector<int32, 24> host_buf(ndims * 3);
gtl::InlinedVector<int32, 8> in_strides = ComputeStride<int32>(in.shape());
gtl::InlinedVector<int32, 8> out_strides = ComputeStride<int32>(out->shape());
// Dimension permutation.
for (int i = 0; i < ndims; ++i) {
host_buf[i] = in_strides[i];
host_buf[ndims + i] = out_strides[i];
host_buf[ndims * 2 + i] = perm[i];
}
// Copies the input strides, output strides and permutation to the device.
auto num_bytes = sizeof(int64) * host_buf.size();
auto dev_buf = d.allocate(num_bytes);
// NOTE: host_buf is not allocated by CudaHostAllocator, and
// therefore we are doing a sync copy effectively.
d.memcpyHostToDevice(dev_buf, host_buf.data(), num_bytes);
// Launch kernel to q[...] = p[...].
const T* p = reinterpret_cast<const T*>(in.tensor_data().data());
T* q = reinterpret_cast<T*>(const_cast<char*>((out->tensor_data().data())));
CudaLaunchConfig cfg = GetCudaLaunchConfig(nelem, d);
TF_CHECK_OK(CudaLaunchKernel(
TransposeKernel<T, conjugate>, cfg.block_count, cfg.thread_per_block, 0,
d.stream(), cfg.virtual_thread_count, p,
reinterpret_cast<const int32*>(dev_buf), ndims, q));
// Safe to deallocate immediately after the kernel launch.
d.deallocate(dev_buf);
}
// TransposeUsingTile tries to reduce the dimension of the input tensor to 3 and
// then call special kernels to swap either dimension 1 and dimension 2 or
// dimension 0 and dimension 2. It returns true if the operation is success,
// false otherwise.
template <typename T, bool conjugate = false>
struct TransposeUsingTile {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
// First try to reduce the dimensions of the input tensor.
TransposePermsVec new_perm;
TransposeDimsVec new_dims;
ReduceTransposeDimensions(in.shape(), perm, &new_perm, &new_dims);
// Only use special GPU kernel when dimension is 2 or 3.
int dims = new_dims.size();
if (dims < 2 || dims > 3) return false;
auto in_data = reinterpret_cast<const T*>(in.tensor_data().data());
auto out_data =
reinterpret_cast<T*>(const_cast<char*>(out->tensor_data().data()));
switch (dims) {
case 2:
if (new_perm[0] == 1 && new_perm[1] == 0) {
// Add the first dimension size as 1.
new_dims.insert(new_dims.begin(), 1);
tensorflow::functor::SwapDimension1And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
}
break;
case 3:
if (new_perm == TransposePermsVec({0, 2, 1})) {
tensorflow::functor::SwapDimension1And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
} else if (new_perm == TransposePermsVec({2, 1, 0})) {
tensorflow::functor::SwapDimension0And2InTensor3<GPUDevice, T,
conjugate>()(
d, in_data, new_dims, out_data);
return true;
} else {
// do not handle other 3D permutations
return false;
}
break;
default:
return false;
}
return false;
}
};
template <bool conjugate>
struct TransposeUsingTile<complex64, conjugate> {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
if (!conjugate) {
return TransposeUsingTile<uint64>::run(d, in, perm, out);
} else {
return TransposeUsingTile<float2, true>::run(d, in, perm, out);
}
}
};
template <bool conjugate>
struct TransposeUsingTile<complex128, conjugate> {
static bool run(const Eigen::GpuDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
if (!conjugate) {
return TransposeUsingTile<float4>::run(d, in, perm, out);
} else {
return TransposeUsingTile<double2, true>::run(d, in, perm, out);
}
}
};
} // namespace internal
// Transpose kernel specialized for GPU Device.
#define HANDLE_DIM(DIM) \
case DIM: \
internal::TransposeUsingEigen<GPUDevice, T, DIM>(d, in, perm, conjugate, \
out); \
break
template <typename T, bool conjugate>
struct Transpose<GPUDevice, T, conjugate> {
static void run(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
if (in.dims() < 2) return;
if (internal::TransposeUsingTile<T, conjugate>::run(d, in, perm, out)) {
return;
}
switch (in.dims()) {
HANDLE_DIM(2);
HANDLE_DIM(3);
HANDLE_DIM(4);
HANDLE_DIM(5);
HANDLE_DIM(6);
HANDLE_DIM(7);
HANDLE_DIM(8);
default:
internal::TransposeSimple<T, conjugate>(d, in, perm, out);
break;
}
}
};
#undef HANDLE_DIM
template <bool conjugate>
struct Transpose<GPUDevice, string, conjugate> {
static void run(const GPUDevice& d, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
LOG(FATAL) << "Transpose of DT_STRING tensor not supported on GPU.";
}
};
// Explicit instantiation.
template struct Transpose<GPUDevice, string, false>;
template <>
Status DoTranspose(const GPUDevice& device, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
return internal::DoTransposeImpl(device, in, perm, /*conjugate=*/false, out);
}
template <>
Status DoConjugateTranspose(const GPUDevice& device, const Tensor& in,
const gtl::ArraySlice<int32> perm, Tensor* out) {
return internal::DoTransposeImpl(device, in, perm, /*conjugate=*/true, out);
}
template <>
Status DoMatrixTranspose(const GPUDevice& device, const Tensor& in,
Tensor* out) {
return internal::DoMatrixTransposeImpl(device, in, /*conjugate=*/false, out);
}
template <>
Status DoConjugateMatrixTranspose(const GPUDevice& device, const Tensor& in,
Tensor* out) {
return internal::DoMatrixTransposeImpl(device, in, /*conjugate=*/true, out);
}
} // namespace tensorflow
#endif // GOOGLE_CUDA
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <iostream>
#include <QDateTime>
#include <QTextStream>
#include <QFile>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "RECEIVED";
case QXmppLogger::SentMessage:
return "SENT";
default:
return "";
}
}
static QString formatted(QXmppLogger::MessageType type, const QString& text)
{
return QDateTime::currentDateTime().toString() + " " +
QString::fromLatin1(typeName(type)) + " " +
text;
}
/// Constructs a new QXmppLogger.
///
/// \param parent
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent),
m_loggingType(QXmppLogger::NoLogging),
m_logFilePath("QXmppClientLog.log"),
m_messageTypes(QXmppLogger::AnyMessage)
{
}
/// Returns the default logger.
///
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
m_logger = new QXmppLogger();
return m_logger;
}
/// Returns the handler for logging messages.
///
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
/// Sets the handler for logging messages.
///
/// \param type
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType type)
{
m_loggingType = type;
}
/// Returns the types of messages to log.
///
QXmppLogger::MessageTypes QXmppLogger::messageTypes()
{
return m_messageTypes;
}
/// Sets the types of messages to log.
///
/// \param types
void QXmppLogger::setMessageTypes(QXmppLogger::MessageTypes types)
{
m_messageTypes = types;
}
/// Add a logging message.
///
/// \param type
/// \param text
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& text)
{
// filter messages
if (!m_messageTypes.testFlag(type))
return;
switch(m_loggingType)
{
case QXmppLogger::FileLogging:
{
QFile file(m_logFilePath);
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << formatted(type, text) << "\n\n";
}
break;
case QXmppLogger::StdoutLogging:
std::cout << qPrintable(formatted(type, text)) << std::endl;
break;
case QXmppLogger::SignalLogging:
emit message(type, text);
break;
default:
break;
}
}
/// Returns the path to which logging messages should be written.
///
/// \sa loggingType()
QString QXmppLogger::logFilePath()
{
return m_logFilePath;
}
/// Sets the path to which logging messages should be written.
///
/// \param path
///
/// \sa setLoggingType()
void QXmppLogger::setLogFilePath(const QString &path)
{
m_logFilePath = path;
}
<commit_msg>don't use double end of line in files<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Authors:
* Manjeet Dahiya
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <iostream>
#include <QDateTime>
#include <QTextStream>
#include <QFile>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "RECEIVED";
case QXmppLogger::SentMessage:
return "SENT";
default:
return "";
}
}
static QString formatted(QXmppLogger::MessageType type, const QString& text)
{
return QDateTime::currentDateTime().toString() + " " +
QString::fromLatin1(typeName(type)) + " " +
text;
}
/// Constructs a new QXmppLogger.
///
/// \param parent
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent),
m_loggingType(QXmppLogger::NoLogging),
m_logFilePath("QXmppClientLog.log"),
m_messageTypes(QXmppLogger::AnyMessage)
{
}
/// Returns the default logger.
///
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
m_logger = new QXmppLogger();
return m_logger;
}
/// Returns the handler for logging messages.
///
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
/// Sets the handler for logging messages.
///
/// \param type
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType type)
{
m_loggingType = type;
}
/// Returns the types of messages to log.
///
QXmppLogger::MessageTypes QXmppLogger::messageTypes()
{
return m_messageTypes;
}
/// Sets the types of messages to log.
///
/// \param types
void QXmppLogger::setMessageTypes(QXmppLogger::MessageTypes types)
{
m_messageTypes = types;
}
/// Add a logging message.
///
/// \param type
/// \param text
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& text)
{
// filter messages
if (!m_messageTypes.testFlag(type))
return;
switch(m_loggingType)
{
case QXmppLogger::FileLogging:
{
QFile file(m_logFilePath);
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << formatted(type, text) << "\n";
}
break;
case QXmppLogger::StdoutLogging:
std::cout << qPrintable(formatted(type, text)) << std::endl;
break;
case QXmppLogger::SignalLogging:
emit message(type, text);
break;
default:
break;
}
}
/// Returns the path to which logging messages should be written.
///
/// \sa loggingType()
QString QXmppLogger::logFilePath()
{
return m_logFilePath;
}
/// Sets the path to which logging messages should be written.
///
/// \param path
///
/// \sa setLoggingType()
void QXmppLogger::setLogFilePath(const QString &path)
{
m_logFilePath = path;
}
<|endoftext|> |
<commit_before>/******************************************************************************
SDL_Display.cpp
SDL Display Class Interface Definition
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "SDL_Display.h"
using namespace nom;
SDL_Display::SDL_Display ( void )
{
#ifdef DEBUG_SDL_DISPLAY_OBJ
std::cout << "nom::SDL_Display::SDL_Display(): " << "Hello world!" << std::endl << std::endl;
#endif
if ( SDL_Init ( SDL_INIT_VIDEO ) != 0 )
{
std::cout << "ERR in SDL_Display::SDL_Display() at SDL_Init(): " << SDL_GetError() << std::endl;
}
}
SDL_Display::~SDL_Display ( void )
{
// As per docs, we must not free the publicly available surface, AKA
// SDL_Surface *screen. This is explicitly stated as a role of the SDL_Quit()
// function.
//
// http://sdl.beuc.net/sdl.wiki/SDL_SetVideoMode
#ifdef DEBUG_SDL_DISPLAY_OBJ
std::cout << "nom::SDL::Display::~Display(): " << "Goodbye cruel world!" << "\n" << std::endl;
#endif
}
void SDL_Display::createWindow ( int32_t display_width, int32_t display_height,
int32_t display_colorbit, uint32_t flags )
{
void* screen = nullptr; // Better safe than sorry!
screen = SDL_SetVideoMode ( display_width, display_height,
display_colorbit, flags
);
if ( screen == nullptr )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in SDL_Display::SDL_Display(): " << SDL_GetError() << std::endl;
#endif
}
assert ( screen != nullptr );
}
void* SDL_Display::get ( void ) const
{
return dynamic_cast<SDL_Surface*>( SDL_GetVideoSurface() );
}
int32_t SDL_Display::getDisplayWidth ( void ) const
{
return SDL_GetVideoSurface()->w;
}
int32_t SDL_Display::getDisplayHeight ( void ) const
{
return SDL_GetVideoSurface()->h;
}
int32_t SDL_Display::getDisplayColorBits ( void ) const
{
return SDL_GetVideoSurface()->format->BitsPerPixel;
}
uint32_t SDL_Display::getDisplayFlags ( void ) const
{
return SDL_GetVideoSurface()->flags;
}
uint16_t SDL_Display::getDisplayPitch ( void ) const
{
return SDL_GetVideoSurface()->pitch;
}
void* SDL_Display::getDisplayPixels ( void ) const
{
return SDL_GetVideoSurface()->pixels;
}
void* SDL_Display::getDisplayPixelsFormat ( void ) const
{
return SDL_GetVideoSurface()->format;
}
const nom::Coords SDL_Display::getDisplayBounds ( void ) const
{
SDL_Rect clip = SDL_GetVideoSurface()->clip_rect;
nom::Coords clip_coords ( clip.x, clip.y, clip.w, clip.h );
return clip_coords;
}
void nom::SDL_Display::Update ( void )
{
if ( SDL_Flip ( static_cast<SDL_Surface*> ( this->get() ) ) != 0 )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in nom::SDL_Display::Update(): " << SDL_GetError() << std::endl;
#endif
}
}
void nom::SDL_Display::Update ( void* video_buffer )
{
if ( SDL_Flip ( static_cast<SDL_Surface*> ( video_buffer ) ) != 0 )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in nom::SDL_Display::Update ( void* ): " << SDL_GetError() << std::endl;
#endif
}
}
void SDL_Display::toggleFullScreenWindow ( int32_t width, int32_t height )
{
void* screen = nullptr; // Better safe than sorry!
uint32_t flags = 0; // save our current flags before attempting to switch
flags = this->getDisplayFlags();
screen = SDL_SetVideoMode ( width, height, 0, flags ^ SDL_FULLSCREEN );
// If for whatever reason, we cannot toggle fullscreen, try reverting
// back to our previous configuration
if ( screen == nullptr )
{
screen = SDL_SetVideoMode ( width, height, 0, flags );
}
assert ( screen != nullptr ); // something went terribly wrong here if we
// are still NULL here
}
// FIXME
const std::string SDL_Display::getWindowTitle ( void ) const
{
char *window_title;
SDL_WM_GetCaption ( &window_title, nullptr );
return std::to_string ( *window_title );
}
// TODO
void* SDL_Display::getWindowIcon ( void ) const
{
return nullptr;
}
void SDL_Display::setWindowTitle ( const std::string& app_name )
{
SDL_WM_SetCaption ( app_name.c_str(), nullptr );
}
void SDL_Display::setWindowIcon ( const std::string& app_icon )
{
nom::SDL_Image image; // holds our image in memory during transfer
nom::SDL_Canvas icon; // icon canvas to load our icon file into
if ( this->get() != nullptr )
{
std::cout << "ERR in SDL_Display::setWindowIcon(): " << "SDL video subsystem has already been initiated." << std::endl << std::endl;
}
if ( image.loadFromFile ( app_icon ) == false )
{
#ifdef DEBUG_SDL_CANVAS
std::cout << "ERR in nom::SDL_Display::setWindowIcon(): " << std::endl << std::endl;
#endif
}
// Sets our canvas with our acquired image surface
icon.setCanvas ( image.get() );
icon.setTransparent ( nom::Color ( 0, 0, 0 ), SDL_SRCCOLORKEY ); // FIXME?
SDL_WM_SetIcon ( static_cast<SDL_Surface*> ( icon.get() ), nullptr );
icon.freeCanvas();
}
<commit_msg>Removed duplication of code fragments in toggling FS window method<commit_after>/******************************************************************************
SDL_Display.cpp
SDL Display Class Interface Definition
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#include "SDL_Display.h"
using namespace nom;
SDL_Display::SDL_Display ( void )
{
#ifdef DEBUG_SDL_DISPLAY_OBJ
std::cout << "nom::SDL_Display::SDL_Display(): " << "Hello world!" << std::endl << std::endl;
#endif
if ( SDL_Init ( SDL_INIT_VIDEO ) != 0 )
{
std::cout << "ERR in SDL_Display::SDL_Display() at SDL_Init(): " << SDL_GetError() << std::endl;
}
}
SDL_Display::~SDL_Display ( void )
{
// As per docs, we must not free the publicly available surface, AKA
// SDL_Surface *screen. This is explicitly stated as a role of the SDL_Quit()
// function.
//
// http://sdl.beuc.net/sdl.wiki/SDL_SetVideoMode
#ifdef DEBUG_SDL_DISPLAY_OBJ
std::cout << "nom::SDL::Display::~Display(): " << "Goodbye cruel world!" << "\n" << std::endl;
#endif
}
void SDL_Display::createWindow ( int32_t display_width, int32_t display_height,
int32_t display_colorbit, uint32_t flags )
{
void* screen = nullptr; // Better safe than sorry!
screen = SDL_SetVideoMode ( display_width, display_height,
display_colorbit, flags
);
if ( screen == nullptr )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in SDL_Display::SDL_Display(): " << SDL_GetError() << std::endl;
#endif
}
assert ( screen != nullptr );
}
void* SDL_Display::get ( void ) const
{
return dynamic_cast<SDL_Surface*>( SDL_GetVideoSurface() );
}
int32_t SDL_Display::getDisplayWidth ( void ) const
{
return SDL_GetVideoSurface()->w;
}
int32_t SDL_Display::getDisplayHeight ( void ) const
{
return SDL_GetVideoSurface()->h;
}
int32_t SDL_Display::getDisplayColorBits ( void ) const
{
return SDL_GetVideoSurface()->format->BitsPerPixel;
}
uint32_t SDL_Display::getDisplayFlags ( void ) const
{
return SDL_GetVideoSurface()->flags;
}
uint16_t SDL_Display::getDisplayPitch ( void ) const
{
return SDL_GetVideoSurface()->pitch;
}
void* SDL_Display::getDisplayPixels ( void ) const
{
return SDL_GetVideoSurface()->pixels;
}
void* SDL_Display::getDisplayPixelsFormat ( void ) const
{
return SDL_GetVideoSurface()->format;
}
const nom::Coords SDL_Display::getDisplayBounds ( void ) const
{
SDL_Rect clip = SDL_GetVideoSurface()->clip_rect;
nom::Coords clip_coords ( clip.x, clip.y, clip.w, clip.h );
return clip_coords;
}
void nom::SDL_Display::Update ( void )
{
if ( SDL_Flip ( static_cast<SDL_Surface*> ( this->get() ) ) != 0 )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in nom::SDL_Display::Update(): " << SDL_GetError() << std::endl;
#endif
}
}
void nom::SDL_Display::Update ( void* video_buffer )
{
if ( SDL_Flip ( static_cast<SDL_Surface*> ( video_buffer ) ) != 0 )
{
#ifdef DEBUG_SDL_DISPLAY
std::cout << "ERR in nom::SDL_Display::Update ( void* ): " << SDL_GetError() << std::endl;
#endif
}
}
void SDL_Display::toggleFullScreenWindow ( int32_t width, int32_t height )
{
uint32_t flags = 0; // save our current flags before attempting to switch
flags = this->getDisplayFlags();
this->createWindow ( width, height, 0, flags ^ SDL_FULLSCREEN );
// If for whatever reason, we cannot toggle fullscreen, try reverting
// back to our previous configuration
if ( this->get() == nullptr )
this->createWindow ( width, height, 0, flags );
}
// FIXME
const std::string SDL_Display::getWindowTitle ( void ) const
{
char *window_title;
SDL_WM_GetCaption ( &window_title, nullptr );
return std::to_string ( *window_title );
}
// TODO
void* SDL_Display::getWindowIcon ( void ) const
{
return nullptr;
}
void SDL_Display::setWindowTitle ( const std::string& app_name )
{
SDL_WM_SetCaption ( app_name.c_str(), nullptr );
}
void SDL_Display::setWindowIcon ( const std::string& app_icon )
{
nom::SDL_Image image; // holds our image in memory during transfer
nom::SDL_Canvas icon; // icon canvas to load our icon file into
if ( this->get() != nullptr )
{
std::cout << "ERR in SDL_Display::setWindowIcon(): " << "SDL video subsystem has already been initiated." << std::endl << std::endl;
}
if ( image.loadFromFile ( app_icon ) == false )
{
#ifdef DEBUG_SDL_CANVAS
std::cout << "ERR in nom::SDL_Display::setWindowIcon(): " << std::endl << std::endl;
#endif
}
// Sets our canvas with our acquired image surface
icon.setCanvas ( image.get() );
icon.setTransparent ( nom::Color ( 0, 0, 0 ), SDL_SRCCOLORKEY ); // FIXME?
SDL_WM_SetIcon ( static_cast<SDL_Surface*> ( icon.get() ), nullptr );
icon.freeCanvas();
}
<|endoftext|> |
<commit_before>// Terminal.cpp -- source file
/*
* Author: Ivan Chapkailo (septimomend)
* Date: 30.06.2017
*
* © 2017 Ivan Chapkailo. All rights reserved
* e-mail: [email protected]
*/
#include "stdafx.h"
#include "Terminal.h"
Terminal::Terminal() // cstr
{
ConfigurationController* configObj = all.getConfigObj();
struct termios* termObj = configObj->getTermios();
}
AllControllers* Terminal::getAllControllerObj() const
{
return &all;
}
/*
* 0 - STDIN_FILENO - standard input descriptor
* 1 - STDOUT_FILENO - standard output descriptor
* 2 - STDERR_FILENO - standard errors output descriptor
*/
void Terminal::emergencyDestruction(const char* str)
{
write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file
write(STDOUT_FILENO, "\x1b[H", 3);
perror(str);
exit(1); // exit with error
}
void Terminal::rowModeOff()
{
// the change will occur after all output written to STDIN_FILENO is transmitted,
// and all input so far received but not read will be discarded before the change is made
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1)
emergencyDestruction("tcsetattr");
}
void Terminal::rowModeOn()
{
if (tcgetattr(STDIN_FILENO, termObj) == -1)
emergencyDestruction("tcgetattr");
atexit(rowModeOff);
// setting flags
//
termOb->c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
termOb->c_oflag &= ~(OPOST); // Post-process output
termOb->c_cflag |= (CS8); // Character size 8 bits
termOb->c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
termOb->c_cc[VMIN] = 0;
termOb->c_cc[VTIME] = 1;
}
int Terminal::whatKey() // defines key pressing
{
int countRD;
char c;
while ((countRD = read(STDIN_FILENO, &c, 1)) != 1) // read 1 byte from input device and write to c
{
if (countRD == -1 && errno != EAGAIN)
emergencyDestruction("read");
}
if (c == '\x1b') // if this is the escape key
{
char sequence[3];
if (read(STDIN_FILENO, &sequence[0], 1) != 1) // if no errors
return '\x1b';
if (read(STDIN_FILENO, &sequence[1], 1) != 1)
return '\x1b';
// this is escape-sequence
// \x1b[...m
// where ... is numbers of parameters
// more on https://en.wikipedia.org/wiki/Escape_sequences_in_C
//
if (sequence[0] == '[')
{
if (sequence[1] >= '0' && sequence[1] <= '9')
{
if (read(STDIN_FILENO, &sequence[2], 1) != 1)
return '\x1b'; // if escape calls 3rd time - exit
if (sequence[2] == '~')
{Termios
switch (sequence[1])
{
case '1':
return HOME_KEY;
case '3':
return DELETE_KEY;
case '4':
return END_KEY;
case '5':
return PAGE_UP;
case '6':
return PAGE_DOWN;
case '7':
return HOME_KEY;
case '8':
return END_KEY;
}
}
}
else // else if sequence[1] is not numbers
{
switch (sequence[1])
{
case 'A': ConfigurationController
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
case 'H':
return HOME_KEY;
case 'F':
return END_KEY;
}
}
}
else if (sequence[0] == 'O')
{
switch (sequence[1])
{
case 'H':
return HOME_KEY;
case 'F':
return END_KEY;
}
}
return '\x1b';
}
else
return c;
}
int Terminal::getCursorPosition(int *row, int *column) // returns cursor position
{
char buff[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) // output 4 bytes to standard output device
return -1;
while (i < sizeof(buff) - 1)
{
if (read(STDIN_FILENO, &buff[i], 1) != 1) // read from ouput to buff 1 byte
break;
if (buff[i] == 'R')
break;
i++;
}
buff[i] = '\0';
if (buff[0] != '\x1b' || buff[1] != '[') // if wrong data
return -1;
if (sscanf(&buff[2], "%d;%d", row, column) != 2) // read data from buff and check number of fields
return -1;
return 0;
}
int Terminal::getWindowSize(int *row, int *column) // returns size of window
{
struct winsize ws; // #include <sys/ioctl.h> - http://www.delorie.com/djgpp/doc/libc/libc_495.html
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) // do operation TIOCGWINSZ in standard output and fill
// window's size to ws
{
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return getCursorPosition(row, column);
}
else
{
*column = ws.ws_col;
*row = ws.ws_row;
return 0;
}
}
<commit_msg>getAllControllerObj() returns pointer<commit_after>// Terminal.cpp -- source file
/*
* Author: Ivan Chapkailo (septimomend)
* Date: 30.06.2017
*
* © 2017 Ivan Chapkailo. All rights reserved
* e-mail: [email protected]
*/
#include "stdafx.h"
#include "Terminal.h"
Terminal::Terminal() // cstr
{
configObj = all.getConfigObj();
termObj = configObj->getTermios();
}
AllControllers* Terminal::getAllControllerObj() const
{
return &all;
}
/*
* 0 - STDIN_FILENO - standard input descriptor
* 1 - STDOUT_FILENO - standard output descriptor
* 2 - STDERR_FILENO - standard errors output descriptor
*/
void Terminal::emergencyDestruction(const char* str)
{
write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file
write(STDOUT_FILENO, "\x1b[H", 3);
perror(str);
exit(1); // exit with error
}
void Terminal::rowModeOff()
{
// the change will occur after all output written to STDIN_FILENO is transmitted,
// and all input so far received but not read will be discarded before the change is made
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1)
emergencyDestruction("tcsetattr");
}
void Terminal::rowModeOn()
{
if (tcgetattr(STDIN_FILENO, termObj) == -1)
emergencyDestruction("tcgetattr");
atexit(rowModeOff);
// setting flags
//
termOb->c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
termOb->c_oflag &= ~(OPOST); // Post-process output
termOb->c_cflag |= (CS8); // Character size 8 bits
termOb->c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
termOb->c_cc[VMIN] = 0;
termOb->c_cc[VTIME] = 1;
}
int Terminal::whatKey() // defines key pressing
{
int countRD;
char c;
while ((countRD = read(STDIN_FILENO, &c, 1)) != 1) // read 1 byte from input device and write to c
{
if (countRD == -1 && errno != EAGAIN)
emergencyDestruction("read");
}
if (c == '\x1b') // if this is the escape key
{
char sequence[3];
if (read(STDIN_FILENO, &sequence[0], 1) != 1) // if no errors
return '\x1b';
if (read(STDIN_FILENO, &sequence[1], 1) != 1)
return '\x1b';
// this is escape-sequence
// \x1b[...m
// where ... is numbers of parameters
// more on https://en.wikipedia.org/wiki/Escape_sequences_in_C
//
if (sequence[0] == '[')
{
if (sequence[1] >= '0' && sequence[1] <= '9')
{
if (read(STDIN_FILENO, &sequence[2], 1) != 1)
return '\x1b'; // if escape calls 3rd time - exit
if (sequence[2] == '~')
{Termios
switch (sequence[1])
{
case '1':
return HOME_KEY;
case '3':
return DELETE_KEY;
case '4':
return END_KEY;
case '5':
return PAGE_UP;
case '6':
return PAGE_DOWN;
case '7':
return HOME_KEY;
case '8':
return END_KEY;
}
}
}
else // else if sequence[1] is not numbers
{
switch (sequence[1])
{
case 'A': ConfigurationController
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
case 'H':
return HOME_KEY;
case 'F':
return END_KEY;
}
}
}
else if (sequence[0] == 'O')
{
switch (sequence[1])
{
case 'H':
return HOME_KEY;
case 'F':
return END_KEY;
}
}
return '\x1b';
}
else
return c;
}
int Terminal::getCursorPosition(int *row, int *column) // returns cursor position
{
char buff[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) // output 4 bytes to standard output device
return -1;
while (i < sizeof(buff) - 1)
{
if (read(STDIN_FILENO, &buff[i], 1) != 1) // read from ouput to buff 1 byte
break;
if (buff[i] == 'R')
break;
i++;
}
buff[i] = '\0';
if (buff[0] != '\x1b' || buff[1] != '[') // if wrong data
return -1;
if (sscanf(&buff[2], "%d;%d", row, column) != 2) // read data from buff and check number of fields
return -1;
return 0;
}
int Terminal::getWindowSize(int *row, int *column) // returns size of window
{
struct winsize ws; // #include <sys/ioctl.h> - http://www.delorie.com/djgpp/doc/libc/libc_495.html
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) // do operation TIOCGWINSZ in standard output and fill
// window's size to ws
{
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
return -1;
return getCursorPosition(row, column);
}
else
{
*column = ws.ws_col;
*row = ws.ws_row;
return 0;
}
}
<|endoftext|> |
<commit_before>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiMainMenu.h"
//*****************************************************************************************
//
// nuiMainMenuItemPrivate
//
//*****************************************************************************************
class nuiMainMenuItemPrivate
{
friend class nuiMainMenuItem;
friend class nuiMainMenu;
protected:
nuiMainMenuItemPrivate()
{
mIsMenu = false;
mIsSubMenu = false;
mpMenuRef = NULL;
mMenuID = 0;
};
~nuiMainMenuItemPrivate()
{
};
bool mIsMenu; ///< true if the item is a menu
bool mIsSubMenu; ///< true if the item is a submenu
MenuRef mpMenuRef; ///< the associated MenuRef if the item is a menu or a submenu
MenuID mMenuID; ///< the associated MenuID if the item is a menu or a submenu
};
//*****************************************************************************************
//
// nuiMainMenuItem
//
//*****************************************************************************************
nuiMainMenuItem::nuiMainMenuItem(const nglString& rLabel, nuiMainMenuItemType type)
: nuiValueTree<nglString>(rLabel)
{
mType = type;
mEnabled = true;
mChecked = false;
mIsBeingDeleted = false;
mpPrivate = new nuiMainMenuItemPrivate();
}
nuiMainMenuItem::~nuiMainMenuItem()
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
if (pParent && !pParent->mIsBeingDeleted)
{
if (mpPrivate->mIsMenu)
DeleteMenu(mpPrivate->mMenuID);
else
{
uint32 index = ComputeIndexInParent()+1; // apple's index is one-based
DeleteMenuItem(pParent->mpPrivate->mpMenuRef, index);
}
}
if (pParent)
mIsBeingDeleted = true;
delete mpPrivate;
}
void nuiMainMenuItem::SetEnabled(bool set)
{
mEnabled = set;
if (mpPrivate->mIsMenu || mpPrivate->mIsSubMenu)
{
if (set)
EnableAllMenuItems(mpPrivate->mpMenuRef);
else
DisableAllMenuItems(mpPrivate->mpMenuRef);
}
else
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
uint32 index = ComputeIndexInParent()+1; // apple item's index is one-base
if (set)
EnableMenuItem(pParent->mpPrivate->mpMenuRef, index);
else
DisableMenuItem(pParent->mpPrivate->mpMenuRef, index);
}
}
void nuiMainMenuItem::SetMenuEnabled(bool set)
{
}
void nuiMainMenuItem::SetChecked(bool set)
{
if (mpPrivate->mIsMenu || mpPrivate->mIsSubMenu)
return;
mChecked = set;
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
uint32 index = ComputeIndexInParent()+1; // apple item's index is one-base
CheckMenuItem(pParent->mpPrivate->mpMenuRef, index, mChecked);
// send event
if (mChecked)
Checked();
else
Unchecked();
}
void nuiMainMenuItem::SetText(const nglString& rText)
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
int32 index = ComputeIndexInParent()+1; // apple item's index is one-base
SetMenuItemTextWithCFString(pParent->mpPrivate->mpMenuRef, index, rText.ToCFString());
}
void nuiMainMenuItem::MakeSubMenu(uint32 subMenuID)
{
int32 index = ComputeIndexInParent()+1; // apple item's index is one-base
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
// first, delete the existing system item
DeleteMenuItem(pParent->mpPrivate->mpMenuRef, index);
// then, replace it by a submenu
const nglString& rItemLabel = GetElement();
mpPrivate->mIsSubMenu = true;
mpPrivate->mMenuID = subMenuID;
CreateNewMenu(mpPrivate->mMenuID, 0, &mpPrivate->mpMenuRef);
CFStringRef str = rItemLabel.ToCFString();
SetMenuTitleWithCFString(mpPrivate->mpMenuRef, str);
CFRelease(str);
MenuRef rootMenu = AcquireRootMenu();
SetRootMenu(pParent->mpPrivate->mpMenuRef);
InsertMenu(mpPrivate->mpMenuRef, index-1);
SetRootMenu(rootMenu); // pop back information
// re-apply the enabled state
SetEnabled(mEnabled);
}
//*****************************************************************************************
//
// nuiMainMenuPrivate
//
//*****************************************************************************************
class nuiMainMenuPrivate
{
friend class nuiMainMenu;
protected:
nuiMainMenuPrivate()
{
mEventHandlerRef = NULL;
mEventHandlerUPP = NULL;
mUniqueID = 128;
EventTypeSpec menuEvents[]={ { kEventClassCommand, kEventCommandProcess} };
mEventHandlerUPP = NewEventHandlerUPP(::MainMenuEventHandler);
OSErr err = InstallApplicationEventHandler(mEventHandlerUPP,
GetEventTypeCount(menuEvents),
menuEvents,
(void*) this,
&mEventHandlerRef);
}
~nuiMainMenuPrivate()
{
}
bool IsCommandRegistered(uint32 commandID)
{
std::set<uint32>::iterator it = mCommands.find(commandID);
return (it != mCommands.end());
}
void RegisterCommand(uint32 commandID)
{
mCommands.insert(commandID);
}
void UnregisterCommand(uint32 commandID)
{
std::set<uint32>::iterator it = mCommands.find(commandID);
if (it == mCommands.end())
return;
mCommands.erase(it);
}
private:
uint32 mUniqueID;
friend pascal OSStatus MainMenuEventHandler(EventHandlerCallRef eventHandlerCallRef, EventRef eventRef, void* userData);
EventHandlerRef mEventHandlerRef;
EventHandlerProcPtr mEventHandlerUPP;
std::set<uint32> mCommands;
};
pascal OSStatus MainMenuEventHandler(EventHandlerCallRef eventHandlerCallRef, EventRef eventRef, void* userData)
{
// wprintf(_T("MainMenuEventHandler 0x%x\n"), userData);
nuiMainMenuPrivate* pPrivate = (nuiMainMenuPrivate*)userData;
if (!pPrivate)
return noErr;
UInt32 eventKind = GetEventKind(eventRef);
UInt32 eventClass = GetEventClass (eventRef);
switch (eventClass)
{
case kEventClassCommand:
{
HICommand command;
GetEventParameter(eventRef, kEventParamDirectObject, typeHICommand,
NULL, sizeof(HICommand), NULL, &command);
switch (eventKind)
{
case kEventCommandProcess:
{
// note : Apple's advice for a commandID is a four-char code with a uppercase letter ('Copy', 'Edit', etc...).
//
// But this idea doesn't fit much well with dynamically generated menus (which is our purpose here...).
// Instead of generating weird and abstract four-char codes and linking them to our commands,
// we chose to use our objects' pointers as command ID. This way, getting our objects from the command ID is easy.
//
// All we have to do : check the commandID is one of our commands. If it's not, we just dispatch the event to the default event handler.
if (!pPrivate->IsCommandRegistered(command.commandID))
return CallNextEventHandler(eventHandlerCallRef, eventRef);
// retrieve the associated item from the command ID
nuiMainMenuItem* pItem = (nuiMainMenuItem*)command.commandID;
// check/uncheck the item if the check flag has been set
if (pItem->GetType() == eItemCheck)
pItem->SetChecked(!pItem->IsChecked());
//NGL_OUT(_T("Command Processed: 0x%x\n"), pItem);
// and send the item activation signal
pItem->Activated();
}
break;
default:
{
return CallNextEventHandler(eventHandlerCallRef, eventRef);
}
}
}
}
return noErr;
}
//*****************************************************************************************
//
// nuiMainMenu
//
//*****************************************************************************************
void nuiMainMenu::Init()
{
mRefCount++;
// a single menu per session on Carbon (on Carbon, the menu is common for all windows)
if (mRefCount > 1)
return;
mpPrivate = new nuiMainMenuPrivate();
}
bool nuiMainMenu::RegisterFromWindow(nglWindow* pWindow)
{
// carbon don't do anything for now, since the menu is global for the application
return true;
}
bool nuiMainMenu::UnregisterFromWindow(nglWindow* pWindow)
{
// carbon don't do anything for now, since the menu is global for the application
return true;
}
nuiMainMenu::~nuiMainMenu()
{
mRefCount--;
// don't delete anything if this is not the first instance
if (mRefCount != 0)
return;
delete mpPrivate;
// and now, 'cause nuiMainMenu is not a widget, we have to do the house cleaning ourselves
delete mpRoot;
}
// an item has been added in the widget tree. Do the system-side of the operation (add a menu or add a menu item)
bool nuiMainMenu::OnItemAdded(const nuiEvent& rEvent)
{
const nuiTreeEvent<nuiTreeBase>* pTreeEvent = dynamic_cast<const nuiTreeEvent<nuiTreeBase>*>(&rEvent);
nuiMainMenuItem* pParent = (nuiMainMenuItem*)pTreeEvent->mpParent;
nuiMainMenuItem* pItem = (nuiMainMenuItem*)pTreeEvent->mpChild;
if (pParent == mpRoot)
{
InsertMenu(pItem);
}
else
{
if (pParent->mpPrivate->mIsMenu)
{
InsertItem(pParent, pItem);
mpPrivate->RegisterCommand((uint32)pItem);
}
else
{
if (!pParent->mpPrivate->mIsSubMenu)
{
int32 newID = mpPrivate->mUniqueID;
mpPrivate->mUniqueID++;
pParent->MakeSubMenu(newID);
mpPrivate->UnregisterCommand((uint32)pParent);
}
InsertItem(pParent, pItem);
mpPrivate->RegisterCommand((uint32)pItem);
}
}
return true;
}
void nuiMainMenu::InsertMenu(nuiMainMenuItem* pItem)
{
const nglString& rItemLabel = pItem->GetElement();
pItem->mpPrivate->mMenuID = mpPrivate->mUniqueID;
mpPrivate->mUniqueID++;
pItem->mpPrivate->mIsMenu = true;
CreateNewMenu(pItem->mpPrivate->mMenuID, 0, &(pItem->mpPrivate->mpMenuRef));
MenuRef menuRef = pItem->mpPrivate->mpMenuRef;
CFStringRef str = rItemLabel.ToCFString();
SetMenuTitleWithCFString(menuRef, str);
CFRelease(str);
::InsertMenu(menuRef, 0);
}
void nuiMainMenu::InsertItem(nuiMainMenuItem* pParent, nuiMainMenuItem* pItem)
{
const nglString& rItemLabel = pItem->GetElement();
MenuRef menuRef = pParent->mpPrivate->mpMenuRef;
uint32 index = pItem->ComputeIndexInParent()+1; // Carbon item's index is one-based
// insert the menu item
CFStringRef str = rItemLabel.ToCFString();
if (pItem->mType == eItemSeparator)
{
InsertMenuItemTextWithCFString(menuRef, str, index-1/*previous index*/, kMenuItemAttrSeparator/* attributes */, 0);
}
else
{
// use the nuiMainMenuItem pointer as the command ID, it'll be easy to retrieve the object in the event handler then
MenuCommand command = (MenuCommand)pItem;
InsertMenuItemTextWithCFString(menuRef, str, index-1/*previous index*/, 0/* attributes */, command);
}
CFRelease(str);
// hack for Carbon implementation : 'til we find out how disable a whole menu, we have to use "DisableAllMenuItems" as a "DisableMenu" function, and therefore, we have to force this state after each item insertion
if (!pParent->mEnabled)
pParent->SetEnabled(false);
}
<commit_msg>Fixed OSX build following latest nuiMainMenu changes<commit_after>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiMainMenu.h"
//*****************************************************************************************
//
// nuiMainMenuItemPrivate
//
//*****************************************************************************************
class nuiMainMenuItemPrivate
{
friend class nuiMainMenuItem;
friend class nuiMainMenu;
protected:
nuiMainMenuItemPrivate()
{
mIsMenu = false;
mIsSubMenu = false;
mpMenuRef = NULL;
mMenuID = 0;
};
~nuiMainMenuItemPrivate()
{
};
bool mIsMenu; ///< true if the item is a menu
bool mIsSubMenu; ///< true if the item is a submenu
MenuRef mpMenuRef; ///< the associated MenuRef if the item is a menu or a submenu
MenuID mMenuID; ///< the associated MenuID if the item is a menu or a submenu
};
//*****************************************************************************************
//
// nuiMainMenuItem
//
//*****************************************************************************************
nuiMainMenuItem::nuiMainMenuItem(const nglString& rLabel, nuiMainMenuItemType type)
: nuiValueTree<nglString>(rLabel)
{
mType = type;
mEnabled = true;
mChecked = false;
mIsBeingDeleted = false;
mpPrivate = new nuiMainMenuItemPrivate();
}
nuiMainMenuItem::~nuiMainMenuItem()
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
if (pParent && !pParent->mIsBeingDeleted)
{
if (mpPrivate->mIsMenu)
DeleteMenu(mpPrivate->mMenuID);
else
{
uint32 index = ComputeIndexInParent()+1; // apple's index is one-based
DeleteMenuItem(pParent->mpPrivate->mpMenuRef, index);
}
}
if (pParent)
mIsBeingDeleted = true;
delete mpPrivate;
}
void nuiMainMenuItem::SetEnabled(bool set)
{
mEnabled = set;
if (mpPrivate->mIsMenu || mpPrivate->mIsSubMenu)
{
if (set)
EnableAllMenuItems(mpPrivate->mpMenuRef);
else
DisableAllMenuItems(mpPrivate->mpMenuRef);
}
else
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
uint32 index = ComputeIndexInParent()+1; // apple item's index is one-base
if (set)
EnableMenuItem(pParent->mpPrivate->mpMenuRef, index);
else
DisableMenuItem(pParent->mpPrivate->mpMenuRef, index);
}
}
void nuiMainMenuItem::SetMenuEnabled(bool set)
{
}
void nuiMainMenuItem::SetChecked(bool set)
{
if (mpPrivate->mIsMenu || mpPrivate->mIsSubMenu)
return;
mChecked = set;
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
uint32 index = ComputeIndexInParent()+1; // apple item's index is one-base
CheckMenuItem(pParent->mpPrivate->mpMenuRef, index, mChecked);
// send event
if (mChecked)
Checked();
else
Unchecked();
}
void nuiMainMenuItem::SetText(const nglString& rText)
{
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
int32 index = ComputeIndexInParent()+1; // apple item's index is one-base
SetMenuItemTextWithCFString(pParent->mpPrivate->mpMenuRef, index, rText.ToCFString());
}
void nuiMainMenuItem::MakeSubMenu(uint32 subMenuID)
{
int32 index = ComputeIndexInParent()+1; // apple item's index is one-base
nuiMainMenuItem* pParent = (nuiMainMenuItem*)GetParent();
// first, delete the existing system item
DeleteMenuItem(pParent->mpPrivate->mpMenuRef, index);
// then, replace it by a submenu
const nglString& rItemLabel = GetElement();
mpPrivate->mIsSubMenu = true;
mpPrivate->mMenuID = subMenuID;
CreateNewMenu(mpPrivate->mMenuID, 0, &mpPrivate->mpMenuRef);
CFStringRef str = rItemLabel.ToCFString();
SetMenuTitleWithCFString(mpPrivate->mpMenuRef, str);
CFRelease(str);
MenuRef rootMenu = AcquireRootMenu();
SetRootMenu(pParent->mpPrivate->mpMenuRef);
InsertMenu(mpPrivate->mpMenuRef, index-1);
SetRootMenu(rootMenu); // pop back information
// re-apply the enabled state
SetEnabled(mEnabled);
}
//*****************************************************************************************
//
// nuiMainMenuPrivate
//
//*****************************************************************************************
class nuiMainMenuPrivate
{
friend class nuiMainMenu;
protected:
nuiMainMenuPrivate()
{
mEventHandlerRef = NULL;
mEventHandlerUPP = NULL;
mUniqueID = 128;
EventTypeSpec menuEvents[]={ { kEventClassCommand, kEventCommandProcess} };
mEventHandlerUPP = NewEventHandlerUPP(::MainMenuEventHandler);
OSErr err = InstallApplicationEventHandler(mEventHandlerUPP,
GetEventTypeCount(menuEvents),
menuEvents,
(void*) this,
&mEventHandlerRef);
}
~nuiMainMenuPrivate()
{
}
bool IsCommandRegistered(uint32 commandID)
{
std::set<uint32>::iterator it = mCommands.find(commandID);
return (it != mCommands.end());
}
void RegisterCommand(uint32 commandID)
{
mCommands.insert(commandID);
}
void UnregisterCommand(uint32 commandID)
{
std::set<uint32>::iterator it = mCommands.find(commandID);
if (it == mCommands.end())
return;
mCommands.erase(it);
}
private:
uint32 mUniqueID;
friend pascal OSStatus MainMenuEventHandler(EventHandlerCallRef eventHandlerCallRef, EventRef eventRef, void* userData);
EventHandlerRef mEventHandlerRef;
EventHandlerProcPtr mEventHandlerUPP;
std::set<uint32> mCommands;
};
pascal OSStatus MainMenuEventHandler(EventHandlerCallRef eventHandlerCallRef, EventRef eventRef, void* userData)
{
// wprintf(_T("MainMenuEventHandler 0x%x\n"), userData);
nuiMainMenuPrivate* pPrivate = (nuiMainMenuPrivate*)userData;
if (!pPrivate)
return noErr;
UInt32 eventKind = GetEventKind(eventRef);
UInt32 eventClass = GetEventClass (eventRef);
switch (eventClass)
{
case kEventClassCommand:
{
HICommand command;
GetEventParameter(eventRef, kEventParamDirectObject, typeHICommand,
NULL, sizeof(HICommand), NULL, &command);
switch (eventKind)
{
case kEventCommandProcess:
{
// note : Apple's advice for a commandID is a four-char code with a uppercase letter ('Copy', 'Edit', etc...).
//
// But this idea doesn't fit much well with dynamically generated menus (which is our purpose here...).
// Instead of generating weird and abstract four-char codes and linking them to our commands,
// we chose to use our objects' pointers as command ID. This way, getting our objects from the command ID is easy.
//
// All we have to do : check the commandID is one of our commands. If it's not, we just dispatch the event to the default event handler.
if (!pPrivate->IsCommandRegistered(command.commandID))
return CallNextEventHandler(eventHandlerCallRef, eventRef);
// retrieve the associated item from the command ID
nuiMainMenuItem* pItem = (nuiMainMenuItem*)command.commandID;
// check/uncheck the item if the check flag has been set
if (pItem->GetType() == eItemCheck)
pItem->SetChecked(!pItem->IsChecked());
//NGL_OUT(_T("Command Processed: 0x%x\n"), pItem);
// and send the item activation signal
pItem->Activated();
}
break;
default:
{
return CallNextEventHandler(eventHandlerCallRef, eventRef);
}
}
}
}
return noErr;
}
//*****************************************************************************************
//
// nuiMainMenu
//
//*****************************************************************************************
void nuiMainMenu::Init()
{
mRefCount++;
// a single menu per session on Carbon (on Carbon, the menu is common for all windows)
if (mRefCount > 1)
return;
mpPrivate = new nuiMainMenuPrivate();
}
bool nuiMainMenu::RegisterFromWindow(nglWindow* pWindow)
{
// carbon don't do anything for now, since the menu is global for the application
return true;
}
bool nuiMainMenu::UnregisterFromWindow(nglWindow* pWindow)
{
// carbon don't do anything for now, since the menu is global for the application
return true;
}
nuiMainMenu::~nuiMainMenu()
{
mRefCount--;
// don't delete anything if this is not the first instance
if (mRefCount != 0)
return;
delete mpPrivate;
// and now, 'cause nuiMainMenu is not a widget, we have to do the house cleaning ourselves
delete mpRoot;
}
// an item has been added in the widget tree. Do the system-side of the operation (add a menu or add a menu item)
bool nuiMainMenu::OnItemAdded(const nuiEvent& rEvent)
{
const nuiTreeEvent<nuiTreeBase>* pTreeEvent = dynamic_cast<const nuiTreeEvent<nuiTreeBase>*>(&rEvent);
nuiMainMenuItem* pParent = (nuiMainMenuItem*)pTreeEvent->mpParent;
nuiMainMenuItem* pItem = (nuiMainMenuItem*)pTreeEvent->mpChild;
if (pParent == mpRoot)
{
InsertMenu(pItem);
}
else
{
if (pParent->mpPrivate->mIsMenu)
{
InsertItem(pParent, pItem);
mpPrivate->RegisterCommand((uint32)pItem);
}
else
{
if (!pParent->mpPrivate->mIsSubMenu)
{
int32 newID = mpPrivate->mUniqueID;
mpPrivate->mUniqueID++;
pParent->MakeSubMenu(newID);
mpPrivate->UnregisterCommand((uint32)pParent);
}
InsertItem(pParent, pItem);
mpPrivate->RegisterCommand((uint32)pItem);
}
}
return true;
}
void nuiMainMenu::InsertMenu(nuiMainMenuItem* pItem)
{
const nglString& rItemLabel = pItem->GetElement();
pItem->mpPrivate->mMenuID = mpPrivate->mUniqueID;
mpPrivate->mUniqueID++;
pItem->mpPrivate->mIsMenu = true;
CreateNewMenu(pItem->mpPrivate->mMenuID, 0, &(pItem->mpPrivate->mpMenuRef));
MenuRef menuRef = pItem->mpPrivate->mpMenuRef;
CFStringRef str = rItemLabel.ToCFString();
SetMenuTitleWithCFString(menuRef, str);
CFRelease(str);
::InsertMenu(menuRef, 0);
}
void nuiMainMenu::InsertItem(nuiMainMenuItem* pParent, nuiMainMenuItem* pItem)
{
const nglString& rItemLabel = pItem->GetElement();
MenuRef menuRef = pParent->mpPrivate->mpMenuRef;
uint32 index = pItem->ComputeIndexInParent()+1; // Carbon item's index is one-based
// insert the menu item
CFStringRef str = rItemLabel.ToCFString();
if (pItem->mType == eItemSeparator)
{
InsertMenuItemTextWithCFString(menuRef, str, index-1/*previous index*/, kMenuItemAttrSeparator/* attributes */, 0);
}
else
{
// use the nuiMainMenuItem pointer as the command ID, it'll be easy to retrieve the object in the event handler then
MenuCommand command = (MenuCommand)pItem;
InsertMenuItemTextWithCFString(menuRef, str, index-1/*previous index*/, 0/* attributes */, command);
}
CFRelease(str);
// hack for Carbon implementation : 'til we find out how disable a whole menu, we have to use "DisableAllMenuItems" as a "DisableMenu" function, and therefore, we have to force this state after each item insertion
if (!pParent->mEnabled)
pParent->SetEnabled(false);
}
void nuiMainMenu::SetItemText(nuiMainMenuItem* pItem, const nglString& rText)
{
if (pItem->GetType() != eItemString)
return;
pItem->SetText(rText);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/adaptor/common/framework.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/integration-api/adaptor-framework/android/android-framework.h>
#include <dali/public-api/adaptor-framework/application.h>
#include <dali/devel-api/adaptor-framework/application-devel.h>
// INTERNAL INCLUDES
#include <dali/internal/adaptor/common/application-impl.h>
#include <dali/internal/adaptor/android/android-framework-impl.h>
#include <dali/internal/system/common/callback-manager.h>
using namespace Dali;
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
/**
* Impl to hide android data members
*/
struct Framework::Impl
{
// Constructor
Impl( Framework* framework )
: mAbortCallBack( nullptr ),
mCallbackManager( CallbackManager::New() ),
mLanguage( "NOT_SUPPORTED" ),
mRegion( "NOT_SUPPORTED" )
{
AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( framework );
}
~Impl()
{
AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( nullptr );
delete mAbortCallBack;
mAbortCallBack = nullptr;
// we're quiting the main loop so
// mCallbackManager->RemoveAllCallBacks() does not need to be called
// to delete our abort handler
delete mCallbackManager;
mCallbackManager = nullptr;
}
std::string GetLanguage() const
{
return mLanguage;
}
std::string GetRegion() const
{
return mRegion;
}
CallbackBase* mAbortCallBack;
CallbackManager* mCallbackManager;
std::string mLanguage;
std::string mRegion;
};
Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
: mObserver( observer ),
mInitialised( false ),
mPaused( false ),
mRunning( false ),
mArgc( argc ),
mArgv( argv ),
mBundleName( "" ),
mBundleId( "" ),
mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
mImpl( NULL )
{
mImpl = new Impl( this );
}
Framework::~Framework()
{
if( mRunning )
{
Quit();
}
delete mImpl;
mImpl = nullptr;
}
void Framework::Run()
{
mRunning = true;
}
unsigned int Framework::AddIdle( int timeout, void* data, bool ( *callback )( void *data ) )
{
JNIEnv *env = nullptr;
JavaVM* javaVM = AndroidFramework::Get().GetJVM();
if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast<void **>( &env ), JNI_VERSION_1_6 ) != JNI_OK )
{
DALI_LOG_ERROR("Couldn't get JNI env.");
return -1;
}
jclass clazz = env->FindClass( "com/sec/daliview/DaliView" );
if ( !clazz )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.");
return -1;
}
jmethodID addIdle = env->GetStaticMethodID( clazz, "addIdle", "(JJJ)I" );
if (!addIdle)
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.addIdle.");
return -1;
}
jint id = env->CallStaticIntMethod( clazz, addIdle, reinterpret_cast<jlong>( callback ), reinterpret_cast<jlong>( data ), static_cast<jlong>( timeout ) );
return static_cast<unsigned int>( id );
}
void Framework::RemoveIdle( unsigned int id )
{
JNIEnv *env = nullptr;
JavaVM* javaVM = AndroidFramework::Get().GetJVM();
if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast<void **>( &env ), JNI_VERSION_1_6 ) != JNI_OK )
{
DALI_LOG_ERROR("Couldn't get JNI env.");
return;
}
jclass clazz = env->FindClass( "com/sec/daliview/DaliView" );
if( !clazz )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.");
return;
}
jmethodID removeIdle = env->GetStaticMethodID( clazz, "removeIdle", "(I)V" );
if( !removeIdle )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.removeIdle.");
return;
}
env->CallStaticVoidMethod( clazz, removeIdle, static_cast<jint>( id ) );
}
void Framework::Quit()
{
DALI_LOG_ERROR("Quit does nothing for DaliView!");
}
bool Framework::IsMainLoopRunning()
{
return mRunning;
}
void Framework::AddAbortCallback( CallbackBase* callback )
{
mImpl->mAbortCallBack = callback;
}
std::string Framework::GetBundleName() const
{
return mBundleName;
}
void Framework::SetBundleName(const std::string& name)
{
mBundleName = name;
}
std::string Framework::GetBundleId() const
{
return mBundleId;
}
std::string Framework::GetResourcePath()
{
return APPLICATION_RESOURCE_PATH;
}
std::string Framework::GetDataPath()
{
return "";
}
void Framework::SetBundleId(const std::string& id)
{
mBundleId = id;
}
void Framework::AbortCallback( )
{
// if an abort call back has been installed run it.
if (mImpl->mAbortCallBack)
{
CallbackBase::Execute( *mImpl->mAbortCallBack );
}
else
{
Quit();
}
}
bool Framework::AppStatusHandler(int type, void* data)
{
switch (type)
{
case APP_WINDOW_CREATED:
if( !mInitialised )
{
mObserver.OnInit();
mInitialised = true;
}
mObserver.OnSurfaceCreated( data );
break;
case APP_WINDOW_DESTROYED:
mObserver.OnSurfaceDestroyed( data );
break;
case APP_RESET:
mObserver.OnReset();
break;
case APP_RESUME:
mObserver.OnResume();
break;
case APP_PAUSE:
mObserver.OnPause();
break;
case APP_LANGUAGE_CHANGE:
mObserver.OnLanguageChanged();
break;
case APP_DESTROYED:
mObserver.OnTerminate();
mInitialised = false;
break;
default:
break;
}
return true;
}
void Framework::InitThreads()
{
}
std::string Framework::GetLanguage() const
{
return mImpl->GetLanguage();
}
std::string Framework::GetRegion() const
{
return mImpl->GetRegion();
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<commit_msg>Fix Framework::GetResourcePath() for androidjni to return DALI_DATA_RO_DIR.<commit_after>/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali/internal/adaptor/common/framework.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/integration-api/adaptor-framework/android/android-framework.h>
#include <dali/public-api/adaptor-framework/application.h>
#include <dali/devel-api/adaptor-framework/application-devel.h>
// INTERNAL INCLUDES
#include <dali/internal/adaptor/common/application-impl.h>
#include <dali/internal/adaptor/android/android-framework-impl.h>
#include <dali/internal/system/common/callback-manager.h>
using namespace Dali;
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
/**
* Impl to hide android data members
*/
struct Framework::Impl
{
// Constructor
Impl( Framework* framework )
: mAbortCallBack( nullptr ),
mCallbackManager( CallbackManager::New() ),
mLanguage( "NOT_SUPPORTED" ),
mRegion( "NOT_SUPPORTED" )
{
AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( framework );
}
~Impl()
{
AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( nullptr );
delete mAbortCallBack;
mAbortCallBack = nullptr;
// we're quiting the main loop so
// mCallbackManager->RemoveAllCallBacks() does not need to be called
// to delete our abort handler
delete mCallbackManager;
mCallbackManager = nullptr;
}
std::string GetLanguage() const
{
return mLanguage;
}
std::string GetRegion() const
{
return mRegion;
}
CallbackBase* mAbortCallBack;
CallbackManager* mCallbackManager;
std::string mLanguage;
std::string mRegion;
};
Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type )
: mObserver( observer ),
mInitialised( false ),
mPaused( false ),
mRunning( false ),
mArgc( argc ),
mArgv( argv ),
mBundleName( "" ),
mBundleId( "" ),
mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ),
mImpl( NULL )
{
mImpl = new Impl( this );
}
Framework::~Framework()
{
if( mRunning )
{
Quit();
}
delete mImpl;
mImpl = nullptr;
}
void Framework::Run()
{
mRunning = true;
}
unsigned int Framework::AddIdle( int timeout, void* data, bool ( *callback )( void *data ) )
{
JNIEnv *env = nullptr;
JavaVM* javaVM = AndroidFramework::Get().GetJVM();
if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast<void **>( &env ), JNI_VERSION_1_6 ) != JNI_OK )
{
DALI_LOG_ERROR("Couldn't get JNI env.");
return -1;
}
jclass clazz = env->FindClass( "com/sec/daliview/DaliView" );
if ( !clazz )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.");
return -1;
}
jmethodID addIdle = env->GetStaticMethodID( clazz, "addIdle", "(JJJ)I" );
if (!addIdle)
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.addIdle.");
return -1;
}
jint id = env->CallStaticIntMethod( clazz, addIdle, reinterpret_cast<jlong>( callback ), reinterpret_cast<jlong>( data ), static_cast<jlong>( timeout ) );
return static_cast<unsigned int>( id );
}
void Framework::RemoveIdle( unsigned int id )
{
JNIEnv *env = nullptr;
JavaVM* javaVM = AndroidFramework::Get().GetJVM();
if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast<void **>( &env ), JNI_VERSION_1_6 ) != JNI_OK )
{
DALI_LOG_ERROR("Couldn't get JNI env.");
return;
}
jclass clazz = env->FindClass( "com/sec/daliview/DaliView" );
if( !clazz )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.");
return;
}
jmethodID removeIdle = env->GetStaticMethodID( clazz, "removeIdle", "(I)V" );
if( !removeIdle )
{
DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.removeIdle.");
return;
}
env->CallStaticVoidMethod( clazz, removeIdle, static_cast<jint>( id ) );
}
void Framework::Quit()
{
DALI_LOG_ERROR("Quit does nothing for DaliView!");
}
bool Framework::IsMainLoopRunning()
{
return mRunning;
}
void Framework::AddAbortCallback( CallbackBase* callback )
{
mImpl->mAbortCallBack = callback;
}
std::string Framework::GetBundleName() const
{
return mBundleName;
}
void Framework::SetBundleName(const std::string& name)
{
mBundleName = name;
}
std::string Framework::GetBundleId() const
{
return mBundleId;
}
std::string Framework::GetResourcePath()
{
return DALI_DATA_RO_DIR;
}
std::string Framework::GetDataPath()
{
return "";
}
void Framework::SetBundleId(const std::string& id)
{
mBundleId = id;
}
void Framework::AbortCallback( )
{
// if an abort call back has been installed run it.
if (mImpl->mAbortCallBack)
{
CallbackBase::Execute( *mImpl->mAbortCallBack );
}
else
{
Quit();
}
}
bool Framework::AppStatusHandler(int type, void* data)
{
switch (type)
{
case APP_WINDOW_CREATED:
if( !mInitialised )
{
mObserver.OnInit();
mInitialised = true;
}
mObserver.OnSurfaceCreated( data );
break;
case APP_WINDOW_DESTROYED:
mObserver.OnSurfaceDestroyed( data );
break;
case APP_RESET:
mObserver.OnReset();
break;
case APP_RESUME:
mObserver.OnResume();
break;
case APP_PAUSE:
mObserver.OnPause();
break;
case APP_LANGUAGE_CHANGE:
mObserver.OnLanguageChanged();
break;
case APP_DESTROYED:
mObserver.OnTerminate();
mInitialised = false;
break;
default:
break;
}
return true;
}
void Framework::InitThreads()
{
}
std::string Framework::GetLanguage() const
{
return mImpl->GetLanguage();
}
std::string Framework::GetRegion() const
{
return mImpl->GetRegion();
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
<|endoftext|> |
<commit_before>#include "StateMachine.hh"
#include "Exception.hh"
#include "State.hh"
State * ansi_next_state;
State * ansi_internal_state;
void ansi_state_process( char c ) {
bool incomplete = false;
try {
ansi_next_state->feed( c );
} catch ( IncompleteParse * e ) {
incomplete = true;
}
if ( ansi_next_state != ansi_internal_state ) {
ansi_state_flip();
}
if ( incomplete ) {
ansi_state_process(c);
}
}
void ansi_state_init() {
ansi_internal_state = ansi_next_state;
ansi_internal_state->enter();
}
void ansi_state_flip() {
ansi_internal_state->exit();
ansi_internal_state = ansi_next_state;
ansi_internal_state->enter();
}
<commit_msg>Doing a light amount of documentation<commit_after>#include "StateMachine.hh"
#include "Exception.hh"
#include "State.hh"
State * ansi_next_state;
State * ansi_internal_state;
void ansi_state_process( char c ) {
bool incomplete = false;
try {
ansi_next_state->feed( c );
} catch ( IncompleteParse * e ) {
/* The state at hand doesn't know how to
deal with the current char, and it should
be passed to the next state. */
incomplete = true;
}
if ( ansi_next_state != ansi_internal_state ) {
/* One of the states has requested a state change.
Let's action it on their behalf */
ansi_state_flip();
}
if ( incomplete ) {
/* Right now, recursion is the best way to do this
without keeping a char queue. Perhaps I should turn
it into a queue / stack later on. */
ansi_state_process(c);
}
}
void ansi_state_init() {
/* Remember: internal_state is uninit'd */
ansi_internal_state = ansi_next_state;
ansi_internal_state->enter();
}
void ansi_state_flip() {
ansi_internal_state->exit();
ansi_internal_state = ansi_next_state;
ansi_internal_state->enter();
}
<|endoftext|> |
<commit_before>#include "SGComputeResponser.h"
#include "SGMacro.h"
#include "SGHdfsStreamFactory.h"
#include "core/GPStreamFactory.h"
#include <fstream>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char* argv[])
{
if (argc < 2)
{
GPPRINT_FL("Usage: ./compute-responser port");
return 0;
}
int number = 1;
if (argc >= 3)
{
number = atoi(argv[2]);
}
auto responserPort = atoi(argv[1]);
std::string mastPort;
{
std::ifstream input("conf/responser.conf");
getline(input, mastPort);
}
for (int i=1; i<number; ++i)
{
if (0 == fork())
{
break;
}
responserPort++;
}
char portName[100];
sprintf(portName, "%d", responserPort);
printf("In %0x, portName is %s\n", getpid(), portName);
SGComputeResponser::init(portName, mastPort.c_str());
SGComputeResponser::getInstance()->install("func.xml");
SGHdfsStreamFactory::initWithConf("/home/jxt/InWork/secret/hdfs.txt");
GPStreamFactory::setStreamCreator(SGHdfsStreamFactory::getInstance());
SGComputeResponser::getInstance()->runLoop();
return 1;
}
<commit_msg>Update compute-responser.cpp<commit_after>#include "SGComputeResponser.h"
#include "SGMacro.h"
#include "SGHdfsStreamFactory.h"
#include "core/GPStreamFactory.h"
#include <fstream>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char* argv[])
{
if (argc < 2)
{
GPPRINT_FL("Usage: ./compute-responser port");
return 0;
}
int number = 1;
if (argc >= 3)
{
number = atoi(argv[2]);
}
auto responserPort = atoi(argv[1]);
std::string mastPort;
{
std::ifstream input("conf/responser.conf");
getline(input, mastPort);
}
for (int i=1; i<number; ++i)
{
if (0 == fork())
{
break;
}
responserPort++;
}
char portName[100];
sprintf(portName, "%d", responserPort);
printf("In %0x, portName is %s\n", getpid(), portName);
SGComputeResponser::init(portName, mastPort.c_str());
SGComputeResponser::getInstance()->install("func.xml");
{
std::ifstream input("./conf/hdfs.conf");
std::string hdfsConf;
getline(input, hdfsConf);
SGHdfsStreamFactory::initWithConf(hdfsConf.c_str());
}
GPStreamFactory::setStreamCreator(SGHdfsStreamFactory::getInstance());
SGComputeResponser::getInstance()->runLoop();
return 1;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: idlc.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-03-30 16:47:07 $
*
* 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 _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _IDLC_ERRORHANDLER_HXX_
#include <idlc/errorhandler.hxx>
#endif
#ifndef _IDLC_ASTSCOPE_HXX_
#include <idlc/astscope.hxx>
#endif
#ifndef _IDLC_ASTMODULE_HXX_
#include <idlc/astmodule.hxx>
#endif
#ifndef _IDLC_ASTSERVICE_HXX_
#include <idlc/astservice.hxx>
#endif
#ifndef _IDLC_ASTCONSTANTS_HXX_
#include <idlc/astconstants.hxx>
#endif
#ifndef _IDLC_ASTEXCEPTION_HXX_
#include <idlc/astexception.hxx>
#endif
#ifndef _IDLC_ASTUNION_HXX_
#include <idlc/astunion.hxx>
#endif
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif
#ifndef _IDLC_ASTINTERFACE_HXX_
#include <idlc/astinterface.hxx>
#endif
#ifndef _IDLC_ASTOPERATION_HXX_
#include <idlc/astoperation.hxx>
#endif
#ifndef _IDLC_ASTBASETYPE_HXX_
#include <idlc/astbasetype.hxx>
#endif
#include "idlc/astdeclaration.hxx"
#include "idlc/asttype.hxx"
#include "idlc/asttypedef.hxx"
using namespace ::rtl;
AstDeclaration* SAL_CALL scopeAsDecl(AstScope* pScope)
{
if (pScope == NULL) return NULL;
switch( pScope->getScopeNodeType() )
{
case NT_service:
case NT_singleton:
return (AstService*)(pScope);
case NT_module:
case NT_root:
return (AstModule*)(pScope);
case NT_constants:
return (AstConstants*)(pScope);
case NT_interface:
return (AstInterface*)(pScope);
case NT_operation:
return (AstOperation*)(pScope);
case NT_exception:
return (AstException*)(pScope);
case NT_union:
return (AstUnion*)(pScope);
case NT_struct:
return (AstStruct*)(pScope);
case NT_enum:
return (AstEnum*)(pScope);
default:
return NULL;
}
}
AstScope* SAL_CALL declAsScope(AstDeclaration* pDecl)
{
if (pDecl == NULL) return NULL;
switch(pDecl->getNodeType())
{
case NT_interface:
return (AstInterface*)(pDecl);
case NT_service:
case NT_singleton:
return (AstService*)(pDecl);
case NT_module:
case NT_root:
return (AstModule*)(pDecl);
case NT_constants:
return (AstConstants*)(pDecl);
case NT_exception:
return (AstException*)(pDecl);
case NT_union:
return (AstUnion*)(pDecl);
case NT_struct:
return (AstStruct*)(pDecl);
case NT_enum:
return (AstEnum*)(pDecl);
case NT_operation:
return (AstOperation*)(pDecl);
default:
return NULL;
}
}
static void SAL_CALL initializePredefinedTypes(AstModule* pRoot)
{
AstBaseType* pPredefined = NULL;
if ( pRoot )
{
pPredefined = new AstBaseType(ET_long, OString("long"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_ulong, OString("unsigned long"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_hyper, OString("hyper"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_uhyper, OString("unsigned hyper"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_short, OString("short"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_ushort, OString("unsigned short"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_float, OString("float"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_double, OString("double"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_char, OString("char"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_byte, OString("byte"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_any, OString("any"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_string, OString("string"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_type, OString("type"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_boolean, OString("boolean"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_void, OString("void"), pRoot);
pRoot->addDeclaration(pPredefined);
}
}
Idlc::Idlc(Options* pOptions)
: m_pOptions(pOptions)
, m_bIsInMainfile(sal_True)
, m_errorCount(0)
, m_warningCount(0)
, m_lineNumber(0)
, m_parseState(PS_NoState)
, m_bIsDocValid(sal_False)
{
m_pScopes = new AstStack();
// init root object after construction
m_pRoot = NULL;
m_pErrorHandler = new ErrorHandler();
m_bGenerateDoc = m_pOptions->isValid("-C");
}
Idlc::~Idlc()
{
if (m_pRoot)
delete m_pRoot;
if (m_pScopes)
delete m_pScopes;
if (m_pErrorHandler)
delete m_pErrorHandler;
}
void Idlc::init()
{
if ( m_pRoot )
delete m_pRoot;
m_pRoot = new AstModule(NT_root, OString(), NULL);
// push the root node on the stack
m_pScopes->push(m_pRoot);
initializePredefinedTypes(m_pRoot);
}
void Idlc::reset()
{
m_errorCount = 0;
m_warningCount = 0;
m_lineNumber = 0;
m_parseState = PS_NoState;
m_fileName = OString();
m_mainFileName = OString();
m_realFileName = OString();
m_documentation = OString();
m_pScopes->clear();
if ( m_pRoot)
delete m_pRoot;
m_pRoot = new AstModule(NT_root, OString(), NULL);
// push the root node on the stack
m_pScopes->push(m_pRoot);
initializePredefinedTypes(m_pRoot);
}
sal_Bool Idlc::isDocValid()
{
if ( m_bGenerateDoc )
return m_bIsDocValid;
return sal_False;;
}
static Idlc* pStaticIdlc = NULL;
Idlc* SAL_CALL idlc()
{
return pStaticIdlc;
}
Idlc* SAL_CALL setIdlc(Options* pOptions)
{
if ( pStaticIdlc )
{
delete pStaticIdlc;
}
pStaticIdlc = new Idlc(pOptions);
pStaticIdlc->init();
return pStaticIdlc;
}
sal_Bool SAL_CALL canBeRedefined(AstDeclaration *pDecl)
{
switch (pDecl->getNodeType())
{
case NT_module:
case NT_constants:
case NT_interface:
case NT_const:
case NT_exception:
case NT_parameter:
case NT_enum_val:
case NT_array:
case NT_sequence:
case NT_union:
case NT_struct:
case NT_enum:
case NT_typedef:
// return sal_True;
case NT_union_branch:
case NT_member:
case NT_attribute:
case NT_operation:
case NT_predefined:
default:
return sal_False;
}
}
AstType const * resolveTypedefs(AstType const * type) {
while (type->getNodeType() == NT_typedef) {
type = static_cast< AstTypeDef const * >(type)->getBaseType();
}
return type;
}
<commit_msg>INTEGRATION: CWS sb18 (1.4.4); FILE MERGED 2004/04/08 14:37:17 sb 1.4.4.1: #i21150# Fixed UNOIDL typedef support; initial support for polymorphic struct types.<commit_after>/*************************************************************************
*
* $RCSfile: idlc.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-06-03 15:10:36 $
*
* 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 _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _IDLC_ERRORHANDLER_HXX_
#include <idlc/errorhandler.hxx>
#endif
#ifndef _IDLC_ASTSCOPE_HXX_
#include <idlc/astscope.hxx>
#endif
#ifndef _IDLC_ASTMODULE_HXX_
#include <idlc/astmodule.hxx>
#endif
#ifndef _IDLC_ASTSERVICE_HXX_
#include <idlc/astservice.hxx>
#endif
#ifndef _IDLC_ASTCONSTANTS_HXX_
#include <idlc/astconstants.hxx>
#endif
#ifndef _IDLC_ASTEXCEPTION_HXX_
#include <idlc/astexception.hxx>
#endif
#ifndef _IDLC_ASTUNION_HXX_
#include <idlc/astunion.hxx>
#endif
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif
#ifndef _IDLC_ASTINTERFACE_HXX_
#include <idlc/astinterface.hxx>
#endif
#ifndef _IDLC_ASTOPERATION_HXX_
#include <idlc/astoperation.hxx>
#endif
#ifndef _IDLC_ASTBASETYPE_HXX_
#include <idlc/astbasetype.hxx>
#endif
#include "idlc/astdeclaration.hxx"
#include "idlc/asttype.hxx"
#include "idlc/asttypedef.hxx"
#include "osl/diagnose.h"
using namespace ::rtl;
AstDeclaration* SAL_CALL scopeAsDecl(AstScope* pScope)
{
if (pScope == NULL) return NULL;
switch( pScope->getScopeNodeType() )
{
case NT_service:
case NT_singleton:
return (AstService*)(pScope);
case NT_module:
case NT_root:
return (AstModule*)(pScope);
case NT_constants:
return (AstConstants*)(pScope);
case NT_interface:
return (AstInterface*)(pScope);
case NT_operation:
return (AstOperation*)(pScope);
case NT_exception:
return (AstException*)(pScope);
case NT_union:
return (AstUnion*)(pScope);
case NT_struct:
return (AstStruct*)(pScope);
case NT_enum:
return (AstEnum*)(pScope);
default:
return NULL;
}
}
AstScope* SAL_CALL declAsScope(AstDeclaration* pDecl)
{
if (pDecl == NULL) return NULL;
switch(pDecl->getNodeType())
{
case NT_interface:
return (AstInterface*)(pDecl);
case NT_service:
case NT_singleton:
return (AstService*)(pDecl);
case NT_module:
case NT_root:
return (AstModule*)(pDecl);
case NT_constants:
return (AstConstants*)(pDecl);
case NT_exception:
return (AstException*)(pDecl);
case NT_union:
return (AstUnion*)(pDecl);
case NT_struct:
return (AstStruct*)(pDecl);
case NT_enum:
return (AstEnum*)(pDecl);
case NT_operation:
return (AstOperation*)(pDecl);
default:
return NULL;
}
}
static void SAL_CALL initializePredefinedTypes(AstModule* pRoot)
{
AstBaseType* pPredefined = NULL;
if ( pRoot )
{
pPredefined = new AstBaseType(ET_long, OString("long"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_ulong, OString("unsigned long"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_hyper, OString("hyper"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_uhyper, OString("unsigned hyper"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_short, OString("short"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_ushort, OString("unsigned short"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_float, OString("float"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_double, OString("double"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_char, OString("char"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_byte, OString("byte"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_any, OString("any"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_string, OString("string"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_type, OString("type"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_boolean, OString("boolean"), pRoot);
pRoot->addDeclaration(pPredefined);
pPredefined = new AstBaseType(ET_void, OString("void"), pRoot);
pRoot->addDeclaration(pPredefined);
}
}
Idlc::Idlc(Options* pOptions)
: m_pOptions(pOptions)
, m_bIsInMainfile(sal_True)
, m_errorCount(0)
, m_warningCount(0)
, m_lineNumber(0)
, m_parseState(PS_NoState)
, m_bIsDocValid(sal_False)
{
m_pScopes = new AstStack();
// init root object after construction
m_pRoot = NULL;
m_pErrorHandler = new ErrorHandler();
m_bGenerateDoc = m_pOptions->isValid("-C");
}
Idlc::~Idlc()
{
if (m_pRoot)
delete m_pRoot;
if (m_pScopes)
delete m_pScopes;
if (m_pErrorHandler)
delete m_pErrorHandler;
}
void Idlc::init()
{
if ( m_pRoot )
delete m_pRoot;
m_pRoot = new AstModule(NT_root, OString(), NULL);
// push the root node on the stack
m_pScopes->push(m_pRoot);
initializePredefinedTypes(m_pRoot);
}
void Idlc::reset()
{
m_errorCount = 0;
m_warningCount = 0;
m_lineNumber = 0;
m_parseState = PS_NoState;
m_fileName = OString();
m_mainFileName = OString();
m_realFileName = OString();
m_documentation = OString();
m_pScopes->clear();
if ( m_pRoot)
delete m_pRoot;
m_pRoot = new AstModule(NT_root, OString(), NULL);
// push the root node on the stack
m_pScopes->push(m_pRoot);
initializePredefinedTypes(m_pRoot);
}
sal_Bool Idlc::isDocValid()
{
if ( m_bGenerateDoc )
return m_bIsDocValid;
return sal_False;;
}
static Idlc* pStaticIdlc = NULL;
Idlc* SAL_CALL idlc()
{
return pStaticIdlc;
}
Idlc* SAL_CALL setIdlc(Options* pOptions)
{
if ( pStaticIdlc )
{
delete pStaticIdlc;
}
pStaticIdlc = new Idlc(pOptions);
pStaticIdlc->init();
return pStaticIdlc;
}
AstDeclaration const * resolveTypedefs(AstDeclaration const * type) {
if (type != 0) {
while (type->getNodeType() == NT_typedef) {
type = static_cast< AstTypeDef const * >(type)->getBaseType();
}
}
return type;
}
AstInterface const * resolveInterfaceTypedefs(AstType const * type) {
AstDeclaration const * decl = resolveTypedefs(type);
OSL_ASSERT(decl->getNodeType() == NT_interface);
return static_cast< AstInterface const * >(decl);
}
<|endoftext|> |
<commit_before>
// Copyright Casa Jasmina 2016
// LGPL License
//
// TelegramBot library
// https://github.com/CasaJasmina/TelegramBot-Library
#include "TelegramBot.h"
TelegramBot::TelegramBot(const char* token, Client &client) {
this->client = &client;
this->token=token;
}
void TelegramBot::begin() {
while(!client->connected()){
client->connect(HOST, SSL_PORT);
delay (2000);
}
}
/************************************************************************************
* GetUpdates - function to receive messages from telegram as a Json and parse them *
************************************************************************************/
message TelegramBot::getUpdates() {
begin();
//Send your request to api.telegram.org
String getRequest = "GET /bot"+String(token)+"/getUpdates?offset="+String(last_message_recived)+" HTTP/1.1";
client->println(getRequest);
client->println("User-Agent: curl/7.37.1");
client->println("Host: api.telegram.org");
client->println("Accept: */*");
client->println();
String payload = readPayload();
if (payload != "") {
message m;
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject & root = jsonBuffer.parseObject(payload);
int update_id = root["result"][1]["update_id"];
if(last_message_recived != update_id){
String sender = root["result"][1]["message"]["from"]["username"];
String text = root["result"][1]["message"]["text"];
String chat_id = root["result"][1]["message"]["chat"]["id"];
String date = root["result"][1]["message"]["date"];
m.sender = sender;
m.text = text;
m.chat_id = chat_id;
m.date = date;
last_message_recived=update_id;
return m;
}else{
m.chat_id = "";
return m;
}
}
}
// send message function
// send a simple text message to a telegram char
String TelegramBot::sendMessage(String chat_id, String text) {
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject& buff = jsonBuffer.createObject();
buff["chat_id"] = chat_id;
buff["text"] = text;
String msg;
buff.printTo(msg);
return postMessage(msg);
}
// send a message to a telegram chat with a reply markup
String TelegramBot::sendMessage(String chat_id, String text, TelegramKeyboard &keyboard_markup, bool one_time_keyboard, bool resize_keyboard) {
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject& buff = jsonBuffer.createObject();
buff["chat_id"] = chat_id;
buff["text"] = text;
JsonObject& reply_markup = buff.createNestedObject("reply_markup");
JsonArray& keyboard = reply_markup.createNestedArray("keyboard");
for (int a = 1 ; a <= keyboard_markup.length() ; a++){
JsonArray& row = keyboard.createNestedArray();
for( int b = 1; b <= keyboard_markup.rowSize(a) ; b++){
row.add(keyboard_markup.getButton(a,b));
Serial.println(b);
}
}
reply_markup.set<bool>("one_time_keyboard", one_time_keyboard);
reply_markup.set<bool>("resize_keyboard", resize_keyboard);
reply_markup.set<bool>("selective", false);
String msg;
buff.printTo(msg);
// Serial.println(msg);
return postMessage(msg);
}
// gets the telegram json string
// posts the message to telegram
// returns the payload
String TelegramBot::postMessage(String msg) {
begin();
client->println("POST /bot"+String(token)+"/sendMessage"+" HTTP/1.1");
client->println("Host: api.telegram.org");
client->println("Content-Type: application/json");
client->println("Connection: close");
client->print("Content-Length: ");
client->println(msg.length());
client->println();
client->println(msg);
return readPayload();
}
// reads the payload coming from telegram server
// returns the payload string
String TelegramBot::readPayload(){
char c;
String payload="";
//Read the answer and save it in String payload
while (client->connected()) {
payload = client->readStringUntil('\n');
if (payload == "\r") {
break;
}
}
payload = client->readStringUntil('\r');
// Serial.println(payload);
return payload;
}
<commit_msg>fixed bad while loops<commit_after>
// Copyright Casa Jasmina 2016
// LGPL License
//
// TelegramBot library
// https://github.com/CasaJasmina/TelegramBot-Library
#include "TelegramBot.h"
TelegramBot::TelegramBot(const char* token, Client &client) {
this->client = &client;
this->token=token;
}
void TelegramBot::begin() {
if(!client->connected()){
client->connect(HOST, SSL_PORT);
}
}
/************************************************************************************
* GetUpdates - function to receive messages from telegram as a Json and parse them *
************************************************************************************/
message TelegramBot::getUpdates() {
begin();
//Send your request to api.telegram.org
String getRequest = "GET /bot"+String(token)+"/getUpdates?offset="+String(last_message_recived)+" HTTP/1.1";
client->println(getRequest);
client->println("User-Agent: curl/7.37.1");
client->println("Host: api.telegram.org");
client->println("Accept: */*");
client->println();
String payload = readPayload();
if (payload != "") {
message m;
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject & root = jsonBuffer.parseObject(payload);
int update_id = root["result"][1]["update_id"];
if(last_message_recived != update_id){
String sender = root["result"][1]["message"]["from"]["username"];
String text = root["result"][1]["message"]["text"];
String chat_id = root["result"][1]["message"]["chat"]["id"];
String date = root["result"][1]["message"]["date"];
m.sender = sender;
m.text = text;
m.chat_id = chat_id;
m.date = date;
last_message_recived=update_id;
return m;
}else{
m.chat_id = "";
return m;
}
}
}
// send message function
// send a simple text message to a telegram char
String TelegramBot::sendMessage(String chat_id, String text) {
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject& buff = jsonBuffer.createObject();
buff["chat_id"] = chat_id;
buff["text"] = text;
String msg;
buff.printTo(msg);
return postMessage(msg);
}
// send a message to a telegram chat with a reply markup
String TelegramBot::sendMessage(String chat_id, String text, TelegramKeyboard &keyboard_markup, bool one_time_keyboard, bool resize_keyboard) {
StaticJsonBuffer<JSON_BUFF_SIZE> jsonBuffer;
JsonObject& buff = jsonBuffer.createObject();
buff["chat_id"] = chat_id;
buff["text"] = text;
JsonObject& reply_markup = buff.createNestedObject("reply_markup");
JsonArray& keyboard = reply_markup.createNestedArray("keyboard");
for (int a = 1 ; a <= keyboard_markup.length() ; a++){
JsonArray& row = keyboard.createNestedArray();
for( int b = 1; b <= keyboard_markup.rowSize(a) ; b++){
row.add(keyboard_markup.getButton(a,b));
}
}
reply_markup.set<bool>("one_time_keyboard", one_time_keyboard);
reply_markup.set<bool>("resize_keyboard", resize_keyboard);
reply_markup.set<bool>("selective", false);
String msg;
buff.printTo(msg);
// Serial.println(msg);
return postMessage(msg);
}
// gets the telegram json string
// posts the message to telegram
// returns the payload
String TelegramBot::postMessage(String msg) {
begin();
client->println("POST /bot"+String(token)+"/sendMessage"+" HTTP/1.1");
client->println("Host: api.telegram.org");
client->println("Content-Type: application/json");
client->println("Connection: close");
client->print("Content-Length: ");
client->println(msg.length());
client->println();
client->println(msg);
return readPayload();
}
// reads the payload coming from telegram server
// returns the payload string
String TelegramBot::readPayload(){
char c;
String payload="";
//Read the answer and save it in String payload
while (client->connected()) {
payload = client->readStringUntil('\n');
if (payload == "\r") {
break;
}
}
payload = client->readStringUntil('\r');
// Serial.println(payload);
return payload;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/sendconfirmdialog.h"
#include "qt/pivx/forms/ui_sendconfirmdialog.h"
#include "bitcoinunits.h"
#include "walletmodel.h"
#include "transactiontablemodel.h"
#include "transactionrecord.h"
#include "wallet/wallet.h"
#include "guiutil.h"
#include "qt/pivx/qtutils.h"
#include <QList>
#include <QDateTime>
TxDetailDialog::TxDetailDialog(QWidget *parent, bool isConfirmDialog, QString warningStr) :
QDialog(parent),
ui(new Ui::TxDetailDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
// Container
setCssProperty(ui->frame, "container-dialog");
setCssProperty(ui->labelTitle, "text-title-dialog");
// Labels
setCssProperty(ui->labelWarning, "text-title2-dialog");
setCssTextBodyDialog({ui->labelAmount, ui->labelSend, ui->labelInputs, ui->labelFee, ui->labelChange, ui->labelId, ui->labelSize, ui->labelStatus, ui->labelConfirmations, ui->labelDate});
setCssProperty({ui->labelDivider1, ui->labelDivider2, ui->labelDivider3, ui->labelDivider4, ui->labelDivider5, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8, ui->labelDivider9}, "container-divider");
setCssTextBodyDialog({ui->textAmount, ui->textSend, ui->textInputs, ui->textFee, ui->textChange, ui->textId, ui->textSize, ui->textStatus, ui->textConfirmations, ui->textDate});
setCssProperty(ui->pushCopy, "ic-copy-big");
setCssProperty({ui->pushInputs, ui->pushOutputs}, "ic-arrow-down");
setCssProperty(ui->btnEsc, "ic-close");
ui->labelWarning->setVisible(false);
ui->gridInputs->setVisible(false);
ui->outputsScrollArea->setVisible(false);
ui->contentChangeAddress->setVisible(false);
ui->labelDivider4->setVisible(false);
setCssProperty({ui->labelOutputIndex, ui->labelTitlePrevTx}, "text-body2-dialog");
if(isConfirmDialog){
ui->labelTitle->setText(tr("Confirm Your Transaction"));
setCssProperty(ui->btnCancel, "btn-dialog-cancel");
ui->btnSave->setText(tr("SEND"));
setCssBtnPrimary(ui->btnSave);
if (!warningStr.isEmpty()) {
ui->labelWarning->setVisible(true);
ui->labelWarning->setText(warningStr);
} else {
ui->labelWarning->setVisible(false);
}
// hide change address for now
ui->contentConfirmations->setVisible(false);
ui->contentStatus->setVisible(false);
ui->contentDate->setVisible(false);
ui->contentSize->setVisible(false);
ui->contentConfirmations->setVisible(false);
ui->contentID->setVisible(false);
ui->labelDivider7->setVisible(false);
ui->labelDivider5->setVisible(false);
ui->labelDivider3->setVisible(false);
ui->labelDivider9->setVisible(false);
connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->btnSave, &QPushButton::clicked, [this](){acceptTx();});
}else{
ui->labelTitle->setText(tr("Transaction Details"));
ui->containerButtons->setVisible(false);
}
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(closeDialog()));
connect(ui->pushInputs, SIGNAL(clicked()), this, SLOT(onInputsClicked()));
connect(ui->pushOutputs, SIGNAL(clicked()), this, SLOT(onOutputsClicked()));
}
void TxDetailDialog::setData(WalletModel *model, const QModelIndex &index){
this->model = model;
TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer());
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
QString amountText = BitcoinUnits::formatWithUnit(nDisplayUnit, amount, true, BitcoinUnits::separatorAlways);
ui->textAmount->setText(amountText);
const CWalletTx* tx = model->getTx(rec->hash);
if(tx) {
this->txHash = rec->hash;
QString hash = QString::fromStdString(tx->GetHash().GetHex());
ui->textId->setText(hash.left(20) + "..." + hash.right(20));
ui->textId->setTextInteractionFlags(Qt::TextSelectableByMouse);
if (tx->vout.size() == 1) {
ui->textSend->setText(address);
} else {
ui->textSend->setText(QString::number(tx->vout.size()) + " recipients");
}
ui->textInputs->setText(QString::number(tx->vin.size()));
ui->textConfirmations->setText(QString::number(rec->status.depth));
ui->textDate->setText(GUIUtil::dateTimeStrWithSeconds(date));
ui->textStatus->setText(QString::fromStdString(rec->statusToString()));
ui->textSize->setText(QString::number(rec->size) + " bytes");
connect(ui->pushCopy, &QPushButton::clicked, [this](){
GUIUtil::setClipboard(QString::fromStdString(this->txHash.GetHex()));
if (!snackBar) snackBar = new SnackBar(nullptr, this);
snackBar->setText(tr("ID copied"));
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
});
}
}
void TxDetailDialog::setData(WalletModel *model, WalletModelTransaction &tx){
this->model = model;
this->tx = &tx;
CAmount txFee = tx.getTransactionFee();
CAmount totalAmount = tx.getTotalTransactionAmount() + txFee;
ui->textAmount->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, totalAmount, false, BitcoinUnits::separatorAlways) + " (Fee included)");
if(tx.getRecipients().size() == 1){
ui->textSend->setText(tx.getRecipients().at(0).address);
ui->pushOutputs->setVisible(false);
}else{
ui->textSend->setText(QString::number(tx.getRecipients().size()) + " recipients");
}
ui->textInputs->setText(QString::number(tx.getTransaction()->vin.size()));
ui->textFee->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, txFee, false, BitcoinUnits::separatorAlways));
}
void TxDetailDialog::acceptTx(){
this->confirm = true;
this->sendStatus = model->sendCoins(*this->tx);
accept();
}
void TxDetailDialog::onInputsClicked() {
if (ui->gridInputs->isVisible()) {
ui->gridInputs->setVisible(false);
ui->contentInputs->layout()->setContentsMargins(0,9,12,9);
} else {
ui->gridInputs->setVisible(true);
ui->contentInputs->layout()->setContentsMargins(0,9,12,0);
if (!inputsLoaded) {
inputsLoaded = true;
const CWalletTx* tx = (this->tx) ? this->tx->getTransaction() : model->getTx(this->txHash);
if(tx) {
ui->gridInputs->setMinimumHeight(50 + (50 * tx->vin.size()));
int i = 1;
for (const CTxIn &in : tx->vin) {
QString hash = QString::fromStdString(in.prevout.hash.GetHex());
QLabel *label = new QLabel(hash.left(18) + "..." + hash.right(18));
QLabel *label1 = new QLabel(QString::number(in.prevout.n));
label1->setAlignment(Qt::AlignCenter);
setCssProperty({label, label1}, "text-body2-dialog");
ui->gridLayoutInput->addWidget(label,i,0);
ui->gridLayoutInput->addWidget(label1,i,1, Qt::AlignCenter);
i++;
}
}
}
}
}
void TxDetailDialog::onOutputsClicked() {
if (ui->outputsScrollArea->isVisible()) {
ui->outputsScrollArea->setVisible(false);
} else {
ui->outputsScrollArea->setVisible(true);
if (!outputsLoaded) {
outputsLoaded = true;
QVBoxLayout* layoutVertical = new QVBoxLayout();
layoutVertical->setContentsMargins(0,0,12,0);
layoutVertical->setSpacing(6);
ui->container_outputs_base->setLayout(layoutVertical);
const CWalletTx* tx = model->getTx(this->txHash);
if(tx) {
for (const CTxOut &out : tx->vout) {
QFrame *frame = new QFrame(ui->container_outputs_base);
QHBoxLayout *layout = new QHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(12);
frame->setLayout(layout);
QLabel *label = nullptr;
QString labelRes;
CTxDestination dest;
bool isCsAddress = out.scriptPubKey.IsPayToColdStaking();
if (ExtractDestination(out.scriptPubKey, dest, isCsAddress)) {
std::string address = ((isCsAddress) ? CBitcoinAddress::newCSInstance(dest) : CBitcoinAddress::newInstance(dest)).ToString();
labelRes = QString::fromStdString(address);
labelRes = labelRes.left(16) + "..." + labelRes.right(16);
} else {
labelRes = tr("Unknown");
}
label = new QLabel(labelRes);
QLabel *label1 = new QLabel(BitcoinUnits::formatWithUnit(nDisplayUnit, out.nValue, false, BitcoinUnits::separatorAlways));
label1->setAlignment(Qt::AlignCenter | Qt::AlignRight);
setCssProperty({label, label1}, "text-body2-dialog");
layout->addWidget(label);
layout->addWidget(label1);
layoutVertical->addWidget(frame);
}
}
}
}
}
void TxDetailDialog::closeDialog(){
if(snackBar && snackBar->isVisible()) snackBar->hide();
close();
}
TxDetailDialog::~TxDetailDialog(){
if(snackBar) delete snackBar;
delete ui;
}
<commit_msg>[GUI] Fix send transaction detail not showing the destinations.<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/sendconfirmdialog.h"
#include "qt/pivx/forms/ui_sendconfirmdialog.h"
#include "bitcoinunits.h"
#include "walletmodel.h"
#include "transactiontablemodel.h"
#include "transactionrecord.h"
#include "wallet/wallet.h"
#include "guiutil.h"
#include "qt/pivx/qtutils.h"
#include <QList>
#include <QDateTime>
TxDetailDialog::TxDetailDialog(QWidget *parent, bool isConfirmDialog, QString warningStr) :
QDialog(parent),
ui(new Ui::TxDetailDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
// Container
setCssProperty(ui->frame, "container-dialog");
setCssProperty(ui->labelTitle, "text-title-dialog");
// Labels
setCssProperty(ui->labelWarning, "text-title2-dialog");
setCssTextBodyDialog({ui->labelAmount, ui->labelSend, ui->labelInputs, ui->labelFee, ui->labelChange, ui->labelId, ui->labelSize, ui->labelStatus, ui->labelConfirmations, ui->labelDate});
setCssProperty({ui->labelDivider1, ui->labelDivider2, ui->labelDivider3, ui->labelDivider4, ui->labelDivider5, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8, ui->labelDivider9}, "container-divider");
setCssTextBodyDialog({ui->textAmount, ui->textSend, ui->textInputs, ui->textFee, ui->textChange, ui->textId, ui->textSize, ui->textStatus, ui->textConfirmations, ui->textDate});
setCssProperty(ui->pushCopy, "ic-copy-big");
setCssProperty({ui->pushInputs, ui->pushOutputs}, "ic-arrow-down");
setCssProperty(ui->btnEsc, "ic-close");
ui->labelWarning->setVisible(false);
ui->gridInputs->setVisible(false);
ui->outputsScrollArea->setVisible(false);
ui->contentChangeAddress->setVisible(false);
ui->labelDivider4->setVisible(false);
setCssProperty({ui->labelOutputIndex, ui->labelTitlePrevTx}, "text-body2-dialog");
if(isConfirmDialog){
ui->labelTitle->setText(tr("Confirm Your Transaction"));
setCssProperty(ui->btnCancel, "btn-dialog-cancel");
ui->btnSave->setText(tr("SEND"));
setCssBtnPrimary(ui->btnSave);
if (!warningStr.isEmpty()) {
ui->labelWarning->setVisible(true);
ui->labelWarning->setText(warningStr);
} else {
ui->labelWarning->setVisible(false);
}
// hide change address for now
ui->contentConfirmations->setVisible(false);
ui->contentStatus->setVisible(false);
ui->contentDate->setVisible(false);
ui->contentSize->setVisible(false);
ui->contentConfirmations->setVisible(false);
ui->contentID->setVisible(false);
ui->labelDivider7->setVisible(false);
ui->labelDivider5->setVisible(false);
ui->labelDivider3->setVisible(false);
ui->labelDivider9->setVisible(false);
connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->btnSave, &QPushButton::clicked, [this](){acceptTx();});
}else{
ui->labelTitle->setText(tr("Transaction Details"));
ui->containerButtons->setVisible(false);
}
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(closeDialog()));
connect(ui->pushInputs, SIGNAL(clicked()), this, SLOT(onInputsClicked()));
connect(ui->pushOutputs, SIGNAL(clicked()), this, SLOT(onOutputsClicked()));
}
void TxDetailDialog::setData(WalletModel *model, const QModelIndex &index){
this->model = model;
TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer());
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
QString amountText = BitcoinUnits::formatWithUnit(nDisplayUnit, amount, true, BitcoinUnits::separatorAlways);
ui->textAmount->setText(amountText);
const CWalletTx* tx = model->getTx(rec->hash);
if(tx) {
this->txHash = rec->hash;
QString hash = QString::fromStdString(tx->GetHash().GetHex());
ui->textId->setText(hash.left(20) + "..." + hash.right(20));
ui->textId->setTextInteractionFlags(Qt::TextSelectableByMouse);
if (tx->vout.size() == 1) {
ui->textSend->setText(address);
} else {
ui->textSend->setText(QString::number(tx->vout.size()) + " recipients");
}
ui->textInputs->setText(QString::number(tx->vin.size()));
ui->textConfirmations->setText(QString::number(rec->status.depth));
ui->textDate->setText(GUIUtil::dateTimeStrWithSeconds(date));
ui->textStatus->setText(QString::fromStdString(rec->statusToString()));
ui->textSize->setText(QString::number(rec->size) + " bytes");
connect(ui->pushCopy, &QPushButton::clicked, [this](){
GUIUtil::setClipboard(QString::fromStdString(this->txHash.GetHex()));
if (!snackBar) snackBar = new SnackBar(nullptr, this);
snackBar->setText(tr("ID copied"));
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
});
}
}
void TxDetailDialog::setData(WalletModel *model, WalletModelTransaction &tx){
this->model = model;
this->tx = &tx;
CAmount txFee = tx.getTransactionFee();
CAmount totalAmount = tx.getTotalTransactionAmount() + txFee;
ui->textAmount->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, totalAmount, false, BitcoinUnits::separatorAlways) + " (Fee included)");
if(tx.getRecipients().size() == 1){
ui->textSend->setText(tx.getRecipients().at(0).address);
ui->pushOutputs->setVisible(false);
}else{
ui->textSend->setText(QString::number(tx.getRecipients().size()) + " recipients");
}
ui->textInputs->setText(QString::number(tx.getTransaction()->vin.size()));
ui->textFee->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, txFee, false, BitcoinUnits::separatorAlways));
}
void TxDetailDialog::acceptTx(){
this->confirm = true;
this->sendStatus = model->sendCoins(*this->tx);
accept();
}
void TxDetailDialog::onInputsClicked() {
if (ui->gridInputs->isVisible()) {
ui->gridInputs->setVisible(false);
ui->contentInputs->layout()->setContentsMargins(0,9,12,9);
} else {
ui->gridInputs->setVisible(true);
ui->contentInputs->layout()->setContentsMargins(0,9,12,0);
if (!inputsLoaded) {
inputsLoaded = true;
const CWalletTx* tx = (this->tx) ? this->tx->getTransaction() : model->getTx(this->txHash);
if(tx) {
ui->gridInputs->setMinimumHeight(50 + (50 * tx->vin.size()));
int i = 1;
for (const CTxIn &in : tx->vin) {
QString hash = QString::fromStdString(in.prevout.hash.GetHex());
QLabel *label = new QLabel(hash.left(18) + "..." + hash.right(18));
QLabel *label1 = new QLabel(QString::number(in.prevout.n));
label1->setAlignment(Qt::AlignCenter);
setCssProperty({label, label1}, "text-body2-dialog");
ui->gridLayoutInput->addWidget(label,i,0);
ui->gridLayoutInput->addWidget(label1,i,1, Qt::AlignCenter);
i++;
}
}
}
}
}
void TxDetailDialog::onOutputsClicked() {
if (ui->outputsScrollArea->isVisible()) {
ui->outputsScrollArea->setVisible(false);
} else {
ui->outputsScrollArea->setVisible(true);
if (!outputsLoaded) {
outputsLoaded = true;
QVBoxLayout* layoutVertical = new QVBoxLayout();
layoutVertical->setContentsMargins(0,0,12,0);
layoutVertical->setSpacing(6);
ui->container_outputs_base->setLayout(layoutVertical);
const CWalletTx* tx = (this->tx) ? this->tx->getTransaction() : model->getTx(this->txHash);
if(tx) {
for (const CTxOut &out : tx->vout) {
QFrame *frame = new QFrame(ui->container_outputs_base);
QHBoxLayout *layout = new QHBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(12);
frame->setLayout(layout);
QLabel *label = nullptr;
QString labelRes;
CTxDestination dest;
bool isCsAddress = out.scriptPubKey.IsPayToColdStaking();
if (ExtractDestination(out.scriptPubKey, dest, isCsAddress)) {
std::string address = ((isCsAddress) ? CBitcoinAddress::newCSInstance(dest) : CBitcoinAddress::newInstance(dest)).ToString();
labelRes = QString::fromStdString(address);
labelRes = labelRes.left(16) + "..." + labelRes.right(16);
} else {
labelRes = tr("Unknown");
}
label = new QLabel(labelRes);
QLabel *label1 = new QLabel(BitcoinUnits::formatWithUnit(nDisplayUnit, out.nValue, false, BitcoinUnits::separatorAlways));
label1->setAlignment(Qt::AlignCenter | Qt::AlignRight);
setCssProperty({label, label1}, "text-body2-dialog");
layout->addWidget(label);
layout->addWidget(label1);
layoutVertical->addWidget(frame);
}
}
}
}
}
void TxDetailDialog::closeDialog(){
if(snackBar && snackBar->isVisible()) snackBar->hide();
close();
}
TxDetailDialog::~TxDetailDialog(){
if(snackBar) delete snackBar;
delete ui;
}
<|endoftext|> |
<commit_before>//
// UI3DProject.cpp
//
// Created by Patricio Gonzalez Vivo on 10/15/13.
//
//
#include "UI3DProject.h"
void UI3DProject::play(){
if (!bPlaying){
camera.enableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->play();
}
selectedLigth = "NULL";
UI2DProject::play();
}
}
void UI3DProject::stop(){
if(bPlaying){
camera.disableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->stop();
}
UI2DProject::stop();
}
}
void UI3DProject::draw(ofEventArgs & args){
if(bRenderSystem){
ofPushStyle();
#ifdef TARGET_RASPBERRY_PI
#else
getRenderTarget().begin();
#endif
// Background
//
if ( background != NULL ){
background->draw();
}
// 2D scene
//
ofPushStyle();
ofPushMatrix();
selfDrawBackground();
ofPopMatrix();
ofPopStyle();
// Start 3D scene
//
{
getCameraRef().begin();
fog.begin();
// Scene Setup
//
selfSceneTransformation();
glEnable(GL_DEPTH_TEST);
if (bEdit){
lightsDraw();
}
// Draw Debug
//
if( bDebug ){
ofPushStyle();
ofPushMatrix();
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
selfDrawDebug();
ofPopMatrix();
ofPopStyle();
}
// Draw Scene
//
{
lightsBegin();
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
lightsEnd();
}
glDisable(GL_DEPTH_TEST);
fog.end();
getCameraRef().end();
}
// Draw Overlay
//
{
ofPushStyle();
ofPushMatrix();
selfDrawOverlay();
ofPopMatrix();
ofPopStyle();
}
#ifdef TARGET_RASPBERRY_PI
#else
getRenderTarget().end();
// Post-Draw ( shader time )
//
ofDisableLighting();
selfPostDraw();
#endif
if(bRecording){
ofPushStyle();
ofFill();
ofSetColor(255, 0, 0,abs(sin(ofGetElapsedTimef()))*255);
ofCircle(ofGetWidth()-20, 20, 5);
ofPopStyle();
}
ofPopStyle();
}
}
void UI3DProject::exit(ofEventArgs & args){
if(bRecording){
recordingEnd();
}
guiSave();
lights.clear();
materials.clear();
guis.clear();
selfExit();
}
//-------------------- Mouse events + camera interaction
//
void UI3DProject::mousePressed(ofMouseEventArgs & args){
if(bGui && cursorIsOverGUI()){
camera.disableMouseInput();
} else if(bEdit && cursorIsOverLight() != "NULL"){
camera.disableMouseInput();
selectedLigth = cursorIsOverLight();
if(ofGetElapsedTimef()-lastClick<doublClickThreshold){
if(!bGui){
guiShow();
}
for (int i = 0; i<guis.size(); i++) {
if(guis[i]->getName()==selectedLigth){
guis[i]->setMinified(false);
guis[i]->getRect()->setX(1);
guis[i]->setPosition(args.x+25,
args.y-guis[i]->getRect()->getHalfHeight());
}
}
}
} else {
selfMousePressed(args);
}
}
void UI3DProject::mouseDragged(ofMouseEventArgs & args){
if(bEdit && selectedLigth != "NULL"){
ofPoint pmouse(ofGetPreviousMouseX(),-ofGetPreviousMouseY());
ofPoint mouse(ofGetMouseX(),-ofGetMouseY());
ofPoint diff = getCameraRef().cameraToWorld(mouse)-getCameraRef().cameraToWorld(pmouse);
*lights[selectedLigth]+=diff*0.1;
} else {
UI2DProject::mouseDragged(args);
}
};
void UI3DProject::mouseReleased(ofMouseEventArgs & args){
camera.enableMouseInput();
selfMouseReleased(args);
selectedLigth = "NULL";
lastClick = ofGetElapsedTimef();
}
//------------------------------------------------------------ CORE SETUP
void UI3DProject::setupCoreGuis(){
UI2DProject::setupCoreGuis();
guiAdd(camera);
camera.loadLocations(getDataPath()+"cameras/");
guiAdd(fog);
materialAdd( "MATERIAL" );
setupLightingGui();
lightAdd("POINT LIGHT 1", OF_LIGHT_POINT);
}
//------------------------------------------------------------ 3D SPECIFIC SETUP
void UI3DProject::backgroundSet(UIBackground *_bg){
UI2DProject::backgroundSet(_bg);
fog.linkColor(background);
}
void UI3DProject::setupLightingGui(){
bSmoothLighting = true;
bEnableLights = true;
globalAmbientColor = new float[4];
globalAmbientColor[0] = 0.5;
globalAmbientColor[1] = 0.5;
globalAmbientColor[2] = 0.5;
globalAmbientColor[3] = 1.0;
UIReference tmp( new ofxUISuperCanvas("LIGHT", guiTemplate) );
lightsGui = tmp;
lightsGui->copyCanvasStyle(guiTemplate);
lightsGui->copyCanvasProperties(guiTemplate);
lightsGui->setName("LightSettings");
lightsGui->setPosition(guis[guis.size()-1]->getRect()->x+guis[guis.size()-1]->getRect()->getWidth()+1, 0);
lightsGui->setWidgetFontSize(OFX_UI_FONT_SMALL);
ofxUIToggle *toggle = lightsGui->addToggle("ENABLE", &bEnableLights);
toggle->setLabelPosition(OFX_UI_WIDGET_POSITION_LEFT);
lightsGui->resetPlacer();
lightsGui->addWidgetDown(toggle, OFX_UI_ALIGN_RIGHT, true);
lightsGui->addWidgetToHeader(toggle);
lightsGui->addSpacer();
lightsGui->addToggle("SMOOTH", &bSmoothLighting);
lightsGui->addSpacer();
float length = (lightsGui->getGlobalCanvasWidth()-lightsGui->getWidgetSpacing()*5)/3.;
float dim = lightsGui->getGlobalSliderHeight();
lightsGui->addLabel("GLOBAL AMBIENT COLOR", OFX_UI_FONT_SMALL);
lightsGui->addMinimalSlider("R", 0.0, 1.0, &globalAmbientColor[0], length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
lightsGui->addMinimalSlider("G", 0.0, 1.0, &globalAmbientColor[1], length, dim)->setShowValue(false);
lightsGui->addMinimalSlider("B", 0.0, 1.0, &globalAmbientColor[2], length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
lightsGui->autoSizeToFitWidgets();
ofAddListener(lightsGui->newGUIEvent,this,&UI3DProject::guiLightingEvent);
guis.push_back(lightsGui);
}
void UI3DProject::guiLightingEvent(ofxUIEventArgs &e){
string name = e.widget->getName();
if(name == "R"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
} else if(name == "G"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
} else if(name == "B"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
}
}
void UI3DProject::lightAdd( string _name, ofLightType _type ){
UILightReference newLight(new UILight(_name, _type));
lights[_name] = newLight;
guis.push_back(newLight->getUIReference(guiTemplate));
}
string UI3DProject::cursorIsOverLight(){
if(bEnableLights){
ofPoint mouse(ofGetMouseX(),ofGetMouseY());
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
ofPoint pos3D( it->second->x, it->second->y, it->second->z);
ofPoint pos2D = getCameraRef().worldToScreen(pos3D);
if ( pos2D.distance(mouse) < 50 ){
return it->first;
}
}
}
return "NULL";
}
void UI3DProject::lightsBegin(){
ofSetSmoothLighting(bSmoothLighting);
if(bEnableLights){
ofEnableLighting();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
// ofEnableLighting();
it->second->enable();
}
}
}
void UI3DProject::lightsEnd(){
if(!bEnableLights){
// ofDisableLighting();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->disable();
}
ofDisableLighting();
}
}
void UI3DProject::lightsDraw(){
if(bEnableLights){
ofPushStyle();
ofDisableLighting();
string overLight = cursorIsOverLight();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->draw();
if( overLight == it->first){
ofPushMatrix();
ofPopStyle();
ofNoFill();
float pulse = abs(sin(ofGetElapsedTimef()));
ofColor color = it->second->getColor();
color.setBrightness(background->getUIBrightness()*255);
ofSetColor( color, pulse*255);
ofTranslate( it->second->getPosition() );
float size = it->second->getPosition().distance(getCameraRef().getPosition())*0.1;
camera.billboard();
ofSetLineWidth(2);
ofEllipse(0,0, size, size);
ofPopStyle();
ofPopMatrix();
}
}
ofPopStyle();
}
}
void UI3DProject::materialAdd( string _name ){
UIMaterialReference newMaterial( new UIMaterial() );
if ( newMaterial->getClassName() == "MATERIAL" ){
newMaterial->setName("MATERIAL " + ofToString( materials.size() + 1));
}
materials[ newMaterial->getClassName() ] = newMaterial;
guis.push_back( newMaterial->getUIReference(guiTemplate) );
}
//------------------------------------------------------ Save & Load + Camera
void UI3DProject::guiLoad(){
UI2DProject::guiLoad();
camera.load(getDataPath()+"Presets/Working/"+"ofEasyCamSettings");
}
void UI3DProject::guiSave(){
UI2DProject::guiSave();
camera.save(getDataPath()+"Presets/Working/"+"ofEasyCamSettings");
}
void UI3DProject::guiLoadPresetFromPath(string presetPath){
cout << "PRESET PATH: " << presetPath << endl;
UI2DProject::guiLoadPresetFromPath(presetPath);
camera.load(presetPath+"/ofEasyCamSettings");
UI2DProject::guiLoadPresetFromPath(presetPath);
}
void UI3DProject::guiSavePreset(string presetName){
UI2DProject::guiSavePreset(presetName);
camera.save(getDataPath()+"Presets/"+presetName+"/ofEasyCamSettings");
camera.enableMouseInput();
}
ofCamera& UI3DProject::getCameraRef(){
return (*camera.getCameraPtn());
}<commit_msg>pushStyle open<commit_after>//
// UI3DProject.cpp
//
// Created by Patricio Gonzalez Vivo on 10/15/13.
//
//
#include "UI3DProject.h"
void UI3DProject::play(){
if (!bPlaying){
camera.enableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->play();
}
selectedLigth = "NULL";
UI2DProject::play();
}
}
void UI3DProject::stop(){
if(bPlaying){
camera.disableMouseInput();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->stop();
}
UI2DProject::stop();
}
}
void UI3DProject::draw(ofEventArgs & args){
if(bRenderSystem){
ofPushStyle();
#ifdef TARGET_RASPBERRY_PI
#else
getRenderTarget().begin();
#endif
// Background
//
if ( background != NULL ){
background->draw();
}
// 2D scene
//
ofPushStyle();
ofPushMatrix();
selfDrawBackground();
ofPopMatrix();
ofPopStyle();
// Start 3D scene
//
{
getCameraRef().begin();
fog.begin();
// Scene Setup
//
selfSceneTransformation();
glEnable(GL_DEPTH_TEST);
if (bEdit){
lightsDraw();
}
// Draw Debug
//
if( bDebug ){
ofPushStyle();
ofPushMatrix();
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
selfDrawDebug();
ofPopMatrix();
ofPopStyle();
}
// Draw Scene
//
{
lightsBegin();
ofPushStyle();
ofPushMatrix();
selfDraw();
ofPopMatrix();
ofPopStyle();
lightsEnd();
}
glDisable(GL_DEPTH_TEST);
fog.end();
getCameraRef().end();
}
// Draw Overlay
//
{
ofPushStyle();
ofPushMatrix();
selfDrawOverlay();
ofPopMatrix();
ofPopStyle();
}
#ifdef TARGET_RASPBERRY_PI
#else
getRenderTarget().end();
// Post-Draw ( shader time )
//
ofDisableLighting();
selfPostDraw();
#endif
if(bRecording){
ofPushStyle();
ofFill();
ofSetColor(255, 0, 0,abs(sin(ofGetElapsedTimef()))*255);
ofCircle(ofGetWidth()-20, 20, 5);
ofPopStyle();
}
ofPopStyle();
}
}
void UI3DProject::exit(ofEventArgs & args){
if(bRecording){
recordingEnd();
}
guiSave();
lights.clear();
materials.clear();
guis.clear();
selfExit();
}
//-------------------- Mouse events + camera interaction
//
void UI3DProject::mousePressed(ofMouseEventArgs & args){
if(bGui && cursorIsOverGUI()){
camera.disableMouseInput();
} else if(bEdit && cursorIsOverLight() != "NULL"){
camera.disableMouseInput();
selectedLigth = cursorIsOverLight();
if(ofGetElapsedTimef()-lastClick<doublClickThreshold){
if(!bGui){
guiShow();
}
for (int i = 0; i<guis.size(); i++) {
if(guis[i]->getName()==selectedLigth){
guis[i]->setMinified(false);
guis[i]->getRect()->setX(1);
guis[i]->setPosition(args.x+25,
args.y-guis[i]->getRect()->getHalfHeight());
}
}
}
} else {
selfMousePressed(args);
}
}
void UI3DProject::mouseDragged(ofMouseEventArgs & args){
if(bEdit && selectedLigth != "NULL"){
ofPoint pmouse(ofGetPreviousMouseX(),-ofGetPreviousMouseY());
ofPoint mouse(ofGetMouseX(),-ofGetMouseY());
ofPoint diff = getCameraRef().cameraToWorld(mouse)-getCameraRef().cameraToWorld(pmouse);
*lights[selectedLigth]+=diff*0.1;
} else {
UI2DProject::mouseDragged(args);
}
};
void UI3DProject::mouseReleased(ofMouseEventArgs & args){
camera.enableMouseInput();
selfMouseReleased(args);
selectedLigth = "NULL";
lastClick = ofGetElapsedTimef();
}
//------------------------------------------------------------ CORE SETUP
void UI3DProject::setupCoreGuis(){
UI2DProject::setupCoreGuis();
guiAdd(camera);
camera.loadLocations(getDataPath()+"cameras/");
guiAdd(fog);
materialAdd( "MATERIAL" );
setupLightingGui();
lightAdd("POINT LIGHT 1", OF_LIGHT_POINT);
}
//------------------------------------------------------------ 3D SPECIFIC SETUP
void UI3DProject::backgroundSet(UIBackground *_bg){
UI2DProject::backgroundSet(_bg);
fog.linkColor(background);
}
void UI3DProject::setupLightingGui(){
bSmoothLighting = true;
bEnableLights = true;
globalAmbientColor = new float[4];
globalAmbientColor[0] = 0.5;
globalAmbientColor[1] = 0.5;
globalAmbientColor[2] = 0.5;
globalAmbientColor[3] = 1.0;
UIReference tmp( new ofxUISuperCanvas("LIGHT", guiTemplate) );
lightsGui = tmp;
lightsGui->copyCanvasStyle(guiTemplate);
lightsGui->copyCanvasProperties(guiTemplate);
lightsGui->setName("LightSettings");
lightsGui->setPosition(guis[guis.size()-1]->getRect()->x+guis[guis.size()-1]->getRect()->getWidth()+1, 0);
lightsGui->setWidgetFontSize(OFX_UI_FONT_SMALL);
ofxUIToggle *toggle = lightsGui->addToggle("ENABLE", &bEnableLights);
toggle->setLabelPosition(OFX_UI_WIDGET_POSITION_LEFT);
lightsGui->resetPlacer();
lightsGui->addWidgetDown(toggle, OFX_UI_ALIGN_RIGHT, true);
lightsGui->addWidgetToHeader(toggle);
lightsGui->addSpacer();
lightsGui->addToggle("SMOOTH", &bSmoothLighting);
lightsGui->addSpacer();
float length = (lightsGui->getGlobalCanvasWidth()-lightsGui->getWidgetSpacing()*5)/3.;
float dim = lightsGui->getGlobalSliderHeight();
lightsGui->addLabel("GLOBAL AMBIENT COLOR", OFX_UI_FONT_SMALL);
lightsGui->addMinimalSlider("R", 0.0, 1.0, &globalAmbientColor[0], length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
lightsGui->addMinimalSlider("G", 0.0, 1.0, &globalAmbientColor[1], length, dim)->setShowValue(false);
lightsGui->addMinimalSlider("B", 0.0, 1.0, &globalAmbientColor[2], length, dim)->setShowValue(false);
lightsGui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
lightsGui->autoSizeToFitWidgets();
ofAddListener(lightsGui->newGUIEvent,this,&UI3DProject::guiLightingEvent);
guis.push_back(lightsGui);
}
void UI3DProject::guiLightingEvent(ofxUIEventArgs &e){
string name = e.widget->getName();
if(name == "R"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
} else if(name == "G"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
} else if(name == "B"){
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbientColor);
}
}
void UI3DProject::lightAdd( string _name, ofLightType _type ){
UILightReference newLight(new UILight(_name, _type));
lights[_name] = newLight;
guis.push_back(newLight->getUIReference(guiTemplate));
}
string UI3DProject::cursorIsOverLight(){
if(bEnableLights){
ofPoint mouse(ofGetMouseX(),ofGetMouseY());
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
ofPoint pos3D( it->second->x, it->second->y, it->second->z);
ofPoint pos2D = getCameraRef().worldToScreen(pos3D);
if ( pos2D.distance(mouse) < 50 ){
return it->first;
}
}
}
return "NULL";
}
void UI3DProject::lightsBegin(){
ofSetSmoothLighting(bSmoothLighting);
if(bEnableLights){
ofEnableLighting();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
// ofEnableLighting();
it->second->enable();
}
}
}
void UI3DProject::lightsEnd(){
if(!bEnableLights){
// ofDisableLighting();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->disable();
}
ofDisableLighting();
}
}
void UI3DProject::lightsDraw(){
if(bEnableLights){
ofPushStyle();
ofDisableLighting();
string overLight = cursorIsOverLight();
for(map<string, UILightReference>::iterator it = lights.begin(); it != lights.end(); ++it){
it->second->draw();
if( overLight == it->first){
ofPushMatrix();
ofPushStyle();
ofNoFill();
float pulse = abs(sin(ofGetElapsedTimef()));
ofColor color = it->second->getColor();
color.setBrightness(background->getUIBrightness()*255);
ofSetColor( color, pulse*255);
ofTranslate( it->second->getPosition() );
float size = it->second->getPosition().distance(getCameraRef().getPosition())*0.1;
camera.billboard();
ofSetLineWidth(2);
ofEllipse(0,0, size, size);
ofPopStyle();
ofPopMatrix();
}
}
ofPopStyle();
}
}
void UI3DProject::materialAdd( string _name ){
UIMaterialReference newMaterial( new UIMaterial() );
if ( newMaterial->getClassName() == "MATERIAL" ){
newMaterial->setName("MATERIAL " + ofToString( materials.size() + 1));
}
materials[ newMaterial->getClassName() ] = newMaterial;
guis.push_back( newMaterial->getUIReference(guiTemplate) );
}
//------------------------------------------------------ Save & Load + Camera
void UI3DProject::guiLoad(){
UI2DProject::guiLoad();
camera.load(getDataPath()+"Presets/Working/"+"ofEasyCamSettings");
}
void UI3DProject::guiSave(){
UI2DProject::guiSave();
camera.save(getDataPath()+"Presets/Working/"+"ofEasyCamSettings");
}
void UI3DProject::guiLoadPresetFromPath(string presetPath){
cout << "PRESET PATH: " << presetPath << endl;
UI2DProject::guiLoadPresetFromPath(presetPath);
camera.load(presetPath+"/ofEasyCamSettings");
UI2DProject::guiLoadPresetFromPath(presetPath);
}
void UI3DProject::guiSavePreset(string presetName){
UI2DProject::guiSavePreset(presetName);
camera.save(getDataPath()+"Presets/"+presetName+"/ofEasyCamSettings");
camera.enableMouseInput();
}
ofCamera& UI3DProject::getCameraRef(){
return (*camera.getCameraPtn());
}<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <ctime>
#include <glm/glm.hpp>
#include "linking.hpp"
/// Logging class.
/**
* Usage:
* @code{.cpp}
* Log() << "Testing: " << 5 << "\n";
* @endcode
*/
class Log {
public:
UTILITY_API enum Channel {
DEFAULT, ///< Default channel.
INFO, ///< Information.
WARNING, ///< Warnings.
ERR, ///< Error.
CONSOLE ///< Console.
};
/// Destructor.
UTILITY_API ~Log();
/// Output some text to stderr.
/**
* @param text Text to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(std::string text);
/// Output an integer to stderr.
/**
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(int value);
/// Output an unsigned integer to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(unsigned int value);
/// Output a float to stderr.
/**
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(float value);
/// Output a double to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(double value);
/// Output a time to stderr.
/**
* Formatted Y-m-d H:M:S.
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(time_t value);
/// Output a vec2 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec2& value);
/// Output a vec3 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec3& value);
/// Output a vec4 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec4& value);
};
<commit_msg>Added max value for error checking.<commit_after>#pragma once
#include <string>
#include <ctime>
#include <glm/glm.hpp>
#include "linking.hpp"
/// Logging class.
/**
* Usage:
* @code{.cpp}
* Log() << "Testing: " << 5 << "\n";
* @endcode
*/
class Log {
public:
UTILITY_API const enum Channel {
DEFAULT = 0, ///< Default channel.
INFO, ///< Information.
WARNING, ///< Warnings.
ERR, ///< Error.
CONSOLE, ///< Console.
MAX ///< Maximum number of channels, ensure this is the last element of the enum if adding channels.
};
/// Destructor.
UTILITY_API ~Log();
/// Output some text to stderr.
/**
* @param text Text to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(std::string text);
/// Output an integer to stderr.
/**
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(int value);
/// Output an unsigned integer to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(unsigned int value);
/// Output a float to stderr.
/**
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(float value);
/// Output a double to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(double value);
/// Output a time to stderr.
/**
* Formatted Y-m-d H:M:S.
* @param value Value to output.
* @return The %Log instance
*/
UTILITY_API Log& operator<<(time_t value);
/// Output a vec2 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec2& value);
/// Output a vec3 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec3& value);
/// Output a vec4 to stderr.
/**
* @param value Value to output.
* @return The %Log instance.
*/
UTILITY_API Log& operator<<(const glm::vec4& value);
};
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include <algorithm>
#include <functional>
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/message_bubble.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "gfx/native_widget_types.h"
#include "grit/theme_resources.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
#include "views/window/window.h"
namespace chromeos {
namespace {
// Max number of users we'll show. The true max is the min of this and the
// number of windows that fit on the screen.
const size_t kMaxUsers = 6;
// Used to indicate no user has been selected.
const size_t kNotSelected = -1;
// ClientLogin response parameters.
const char kError[] = "Error=";
const char kCaptchaError[] = "CaptchaRequired";
const char kCaptchaUrlParam[] = "CaptchaUrl=";
const char kCaptchaTokenParam[] = "CaptchaToken=";
const char kParamSuffix[] = "\n";
// URL prefix for CAPTCHA image.
const char kCaptchaUrlPrefix[] = "http://www.google.com/accounts/";
// Checks if display names are unique. If there are duplicates, enables
// tooltips with full emails to let users distinguish their accounts.
// Otherwise, disables the tooltips.
void EnableTooltipsIfNeeded(const std::vector<UserController*>& controllers) {
std::map<std::string, int> visible_display_names;
for (size_t i = 0; i + 1 < controllers.size(); ++i) {
const std::string& display_name =
controllers[i]->user().GetDisplayName();
++visible_display_names[display_name];
}
for (size_t i = 0; i + 1 < controllers.size(); ++i) {
const std::string& display_name =
controllers[i]->user().GetDisplayName();
bool show_tooltip = visible_display_names[display_name] > 1;
controllers[i]->EnableNameTooltip(show_tooltip);
}
}
} // namespace
ExistingUserController*
ExistingUserController::delete_scheduled_instance_ = NULL;
ExistingUserController::ExistingUserController(
const std::vector<UserManager::User>& users,
const gfx::Rect& background_bounds)
: background_bounds_(background_bounds),
background_window_(NULL),
background_view_(NULL),
selected_view_index_(kNotSelected),
bubble_(NULL) {
if (delete_scheduled_instance_)
delete_scheduled_instance_->Delete();
// Caclulate the max number of users from available screen size.
size_t max_users = kMaxUsers;
int screen_width = background_bounds.width();
if (screen_width > 0) {
max_users = std::max(static_cast<size_t>(2), std::min(kMaxUsers,
static_cast<size_t>((screen_width - login::kUserImageSize)
/ (UserController::kUnselectedSize +
UserController::kPadding))));
}
size_t visible_users_count = std::min(users.size(), max_users - 1);
for (size_t i = 0; i < visible_users_count; ++i)
controllers_.push_back(new UserController(this, users[i]));
// Add the view representing the guest user last.
controllers_.push_back(new UserController(this));
}
void ExistingUserController::Init() {
if (!background_window_) {
background_window_ = BackgroundView::CreateWindowContainingView(
background_bounds_,
&background_view_);
if (!WizardController::IsOobeCompleted()) {
background_view_->SetOobeProgressBarVisible(true);
background_view_->SetOobeProgress(chromeos::BackgroundView::SIGNIN);
}
background_window_->Show();
}
for (size_t i = 0; i < controllers_.size(); ++i) {
(controllers_[i])->Init(static_cast<int>(i),
static_cast<int>(controllers_.size()));
}
EnableTooltipsIfNeeded(controllers_);
WmMessageListener::instance()->AddObserver(this);
if (CrosLibrary::Get()->EnsureLoaded())
CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptReady();
}
void ExistingUserController::OwnBackground(
views::Widget* background_widget,
chromeos::BackgroundView* background_view) {
DCHECK(!background_window_);
background_window_ = background_widget;
background_view_ = background_view;
}
void ExistingUserController::LoginNewUser(const std::string& username,
const std::string& password) {
SelectNewUser();
UserController* new_user = controllers_.back();
if (!new_user->is_guest())
return;
NewUserView* new_user_view = new_user->new_user_view();
new_user_view->SetUsername(username);
if (password.empty())
return;
new_user_view->SetPassword(password);
LOG(INFO) << "Password: " << password;
new_user_view->Login();
}
void ExistingUserController::SelectNewUser() {
SelectUser(controllers_.size() - 1);
}
ExistingUserController::~ExistingUserController() {
ClearErrors();
if (background_window_)
background_window_->Close();
WmMessageListener::instance()->RemoveObserver(this);
STLDeleteElements(&controllers_);
}
void ExistingUserController::Delete() {
delete_scheduled_instance_ = NULL;
delete this;
}
void ExistingUserController::ProcessWmMessage(const WmIpc::Message& message,
GdkWindow* window) {
if (message.type() != WM_IPC_MESSAGE_CHROME_CREATE_GUEST_WINDOW)
return;
ActivateWizard(std::string());
}
void ExistingUserController::SendSetLoginState(bool is_enabled) {
WmIpc::Message message(WM_IPC_MESSAGE_WM_SET_LOGIN_STATE);
message.set_param(0, is_enabled);
WmIpc::instance()->SendMessage(message);
}
void ExistingUserController::Login(UserController* source,
const string16& password) {
BootTimesLoader::Get()->RecordLoginAttempted();
std::vector<UserController*>::const_iterator i =
std::find(controllers_.begin(), controllers_.end(), source);
DCHECK(i != controllers_.end());
selected_view_index_ = i - controllers_.begin();
authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
Profile* profile = g_browser_process->profile_manager()->GetDefaultProfile();
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::AuthenticateToLogin,
profile,
controllers_[selected_view_index_]->user().email(),
UTF16ToUTF8(password),
login_token_,
login_captcha_));
// Disable clicking on other windows.
SendSetLoginState(false);
}
void ExistingUserController::LoginOffTheRecord() {
authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::LoginOffTheRecord));
// Disable clicking on other windows.
SendSetLoginState(false);
}
void ExistingUserController::ClearErrors() {
// bubble_ will be set to NULL in callback.
if (bubble_)
bubble_->Close();
}
void ExistingUserController::OnUserSelected(UserController* source) {
std::vector<UserController*>::const_iterator i =
std::find(controllers_.begin(), controllers_.end(), source);
DCHECK(i != controllers_.end());
size_t new_selected_index = i - controllers_.begin();
if (new_selected_index != selected_view_index_ &&
selected_view_index_ != kNotSelected) {
controllers_[selected_view_index_]->ClearAndEnablePassword();
ClearCaptchaState();
}
selected_view_index_ = new_selected_index;
}
void ExistingUserController::ActivateWizard(const std::string& screen_name) {
// WizardController takes care of deleting itself when done.
WizardController* controller = new WizardController();
controller->Init(screen_name, background_bounds_);
controller->Show();
// Give the background window to the controller.
controller->OwnBackground(background_window_, background_view_);
background_window_ = NULL;
// And schedule us for deletion. We delay for a second as the window manager
// is doing an animation with our windows.
DCHECK(!delete_scheduled_instance_);
delete_scheduled_instance_ = this;
delete_timer_.Start(base::TimeDelta::FromSeconds(1), this,
&ExistingUserController::Delete);
}
void ExistingUserController::RemoveUser(UserController* source) {
ClearErrors();
UserManager::Get()->RemoveUser(source->user().email());
// We need to unmap entry windows, the windows will be unmapped in destructor.
controllers_.erase(controllers_.begin() + source->user_index());
delete source;
EnableTooltipsIfNeeded(controllers_);
int new_size = static_cast<int>(controllers_.size());
for (int i = 0; i < new_size; ++i)
controllers_[i]->UpdateUserCount(i, new_size);
}
void ExistingUserController::SelectUser(int index) {
if (index >= 0 && index < static_cast<int>(controllers_.size()) &&
index != static_cast<int>(selected_view_index_)) {
WmIpc::Message message(WM_IPC_MESSAGE_WM_SELECT_LOGIN_USER);
message.set_param(0, index);
WmIpc::instance()->SendMessage(message);
}
}
void ExistingUserController::OnLoginFailure(const std::string& error) {
LOG(INFO) << "OnLoginFailure";
ClearCaptchaState();
// Check networking after trying to login in case user is
// cached locally or the local admin account.
NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary();
if (!network || !CrosLibrary::Get()->EnsureLoaded()) {
ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY, error);
} else if (!network->Connected()) {
ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED, error);
} else {
std::string error_code = LoginUtils::ExtractClientLoginParam(error,
kError,
kParamSuffix);
std::string captcha_url;
if (error_code == kCaptchaError)
captcha_url = LoginUtils::ExtractClientLoginParam(error,
kCaptchaUrlParam,
kParamSuffix);
if (captcha_url.empty()) {
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING, error);
} else {
// Save token for next login retry.
login_token_ = LoginUtils::ExtractClientLoginParam(error,
kCaptchaTokenParam,
kParamSuffix);
CaptchaView* view =
new CaptchaView(GURL(kCaptchaUrlPrefix + captcha_url));
view->set_delegate(this);
views::Window* window = views::Window::CreateChromeWindow(
GetNativeWindow(), gfx::Rect(), view);
window->SetIsAlwaysOnTop(true);
window->Show();
}
}
controllers_[selected_view_index_]->ClearAndEnablePassword();
// Reenable clicking on other windows.
SendSetLoginState(true);
}
void ExistingUserController::AppendStartUrlToCmdline() {
if (start_url_.is_valid()) {
CommandLine::ForCurrentProcess()->AppendLooseValue(
UTF8ToWide(start_url_.spec()));
}
}
void ExistingUserController::ClearCaptchaState() {
login_token_.clear();
login_captcha_.clear();
}
gfx::NativeWindow ExistingUserController::GetNativeWindow() const {
return GTK_WINDOW(
static_cast<views::WidgetGtk*>(background_window_)->GetNativeView());
}
void ExistingUserController::ShowError(int error_id,
const std::string& details) {
ClearErrors();
std::wstring error_text = l10n_util::GetString(error_id);
if (!details.empty())
error_text += L"\n" + ASCIIToWide(details);
bubble_ = MessageBubble::Show(
controllers_[selected_view_index_]->controls_window(),
controllers_[selected_view_index_]->GetScreenBounds(),
BubbleBorder::BOTTOM_LEFT,
ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING),
error_text,
this);
}
void ExistingUserController::OnLoginSuccess(const std::string& username,
const GaiaAuthConsumer::ClientLoginResult& credentials) {
AppendStartUrlToCmdline();
if (selected_view_index_ + 1 == controllers_.size()) {
// For new user login don't launch browser until we pass image screen.
LoginUtils::Get()->EnableBrowserLaunch(false);
LoginUtils::Get()->CompleteLogin(username, credentials);
ActivateWizard(WizardController::kUserImageScreenName);
} else {
// Hide the login windows now.
WmIpc::Message message(WM_IPC_MESSAGE_WM_HIDE_LOGIN);
WmIpc::instance()->SendMessage(message);
LoginUtils::Get()->CompleteLogin(username, credentials);
// Delay deletion as we're on the stack.
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
}
void ExistingUserController::OnOffTheRecordLoginSuccess() {
AppendStartUrlToCmdline();
LoginUtils::Get()->CompleteOffTheRecordLogin();
}
void ExistingUserController::OnPasswordChangeDetected(
const GaiaAuthConsumer::ClientLoginResult& credentials) {
// When signing in as a "New user" always remove old cryptohome.
if (selected_view_index_ == controllers_.size() - 1) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::ResyncEncryptedData,
credentials));
return;
}
cached_credentials_ = credentials;
PasswordChangedView* view = new PasswordChangedView(this);
views::Window* window = views::Window::CreateChromeWindow(GetNativeWindow(),
gfx::Rect(),
view);
window->SetIsAlwaysOnTop(true);
window->Show();
}
void ExistingUserController::OnCaptchaEntered(const std::string& captcha) {
login_captcha_ = captcha;
}
void ExistingUserController::RecoverEncryptedData(
const std::string& old_password) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::RecoverEncryptedData,
old_password,
cached_credentials_));
cached_credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
void ExistingUserController::ResyncEncryptedData() {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::ResyncEncryptedData,
cached_credentials_));
cached_credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
} // namespace chromeos
<commit_msg>Pass background to WizardController after new user login. This fixes SEGFAULT after new user login.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include <algorithm>
#include <functional>
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/message_bubble.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "gfx/native_widget_types.h"
#include "grit/theme_resources.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"
#include "views/window/window.h"
namespace chromeos {
namespace {
// Max number of users we'll show. The true max is the min of this and the
// number of windows that fit on the screen.
const size_t kMaxUsers = 6;
// Used to indicate no user has been selected.
const size_t kNotSelected = -1;
// ClientLogin response parameters.
const char kError[] = "Error=";
const char kCaptchaError[] = "CaptchaRequired";
const char kCaptchaUrlParam[] = "CaptchaUrl=";
const char kCaptchaTokenParam[] = "CaptchaToken=";
const char kParamSuffix[] = "\n";
// URL prefix for CAPTCHA image.
const char kCaptchaUrlPrefix[] = "http://www.google.com/accounts/";
// Checks if display names are unique. If there are duplicates, enables
// tooltips with full emails to let users distinguish their accounts.
// Otherwise, disables the tooltips.
void EnableTooltipsIfNeeded(const std::vector<UserController*>& controllers) {
std::map<std::string, int> visible_display_names;
for (size_t i = 0; i + 1 < controllers.size(); ++i) {
const std::string& display_name =
controllers[i]->user().GetDisplayName();
++visible_display_names[display_name];
}
for (size_t i = 0; i + 1 < controllers.size(); ++i) {
const std::string& display_name =
controllers[i]->user().GetDisplayName();
bool show_tooltip = visible_display_names[display_name] > 1;
controllers[i]->EnableNameTooltip(show_tooltip);
}
}
} // namespace
ExistingUserController*
ExistingUserController::delete_scheduled_instance_ = NULL;
ExistingUserController::ExistingUserController(
const std::vector<UserManager::User>& users,
const gfx::Rect& background_bounds)
: background_bounds_(background_bounds),
background_window_(NULL),
background_view_(NULL),
selected_view_index_(kNotSelected),
bubble_(NULL) {
if (delete_scheduled_instance_)
delete_scheduled_instance_->Delete();
// Caclulate the max number of users from available screen size.
size_t max_users = kMaxUsers;
int screen_width = background_bounds.width();
if (screen_width > 0) {
max_users = std::max(static_cast<size_t>(2), std::min(kMaxUsers,
static_cast<size_t>((screen_width - login::kUserImageSize)
/ (UserController::kUnselectedSize +
UserController::kPadding))));
}
size_t visible_users_count = std::min(users.size(), max_users - 1);
for (size_t i = 0; i < visible_users_count; ++i)
controllers_.push_back(new UserController(this, users[i]));
// Add the view representing the guest user last.
controllers_.push_back(new UserController(this));
}
void ExistingUserController::Init() {
if (!background_window_) {
background_window_ = BackgroundView::CreateWindowContainingView(
background_bounds_,
&background_view_);
if (!WizardController::IsOobeCompleted()) {
background_view_->SetOobeProgressBarVisible(true);
background_view_->SetOobeProgress(chromeos::BackgroundView::SIGNIN);
}
background_window_->Show();
}
for (size_t i = 0; i < controllers_.size(); ++i) {
(controllers_[i])->Init(static_cast<int>(i),
static_cast<int>(controllers_.size()));
}
EnableTooltipsIfNeeded(controllers_);
WmMessageListener::instance()->AddObserver(this);
if (CrosLibrary::Get()->EnsureLoaded())
CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptReady();
}
void ExistingUserController::OwnBackground(
views::Widget* background_widget,
chromeos::BackgroundView* background_view) {
DCHECK(!background_window_);
background_window_ = background_widget;
background_view_ = background_view;
}
void ExistingUserController::LoginNewUser(const std::string& username,
const std::string& password) {
SelectNewUser();
UserController* new_user = controllers_.back();
if (!new_user->is_guest())
return;
NewUserView* new_user_view = new_user->new_user_view();
new_user_view->SetUsername(username);
if (password.empty())
return;
new_user_view->SetPassword(password);
LOG(INFO) << "Password: " << password;
new_user_view->Login();
}
void ExistingUserController::SelectNewUser() {
SelectUser(controllers_.size() - 1);
}
ExistingUserController::~ExistingUserController() {
ClearErrors();
if (background_window_)
background_window_->Close();
WmMessageListener::instance()->RemoveObserver(this);
STLDeleteElements(&controllers_);
}
void ExistingUserController::Delete() {
delete_scheduled_instance_ = NULL;
delete this;
}
void ExistingUserController::ProcessWmMessage(const WmIpc::Message& message,
GdkWindow* window) {
if (message.type() != WM_IPC_MESSAGE_CHROME_CREATE_GUEST_WINDOW)
return;
ActivateWizard(std::string());
}
void ExistingUserController::SendSetLoginState(bool is_enabled) {
WmIpc::Message message(WM_IPC_MESSAGE_WM_SET_LOGIN_STATE);
message.set_param(0, is_enabled);
WmIpc::instance()->SendMessage(message);
}
void ExistingUserController::Login(UserController* source,
const string16& password) {
BootTimesLoader::Get()->RecordLoginAttempted();
std::vector<UserController*>::const_iterator i =
std::find(controllers_.begin(), controllers_.end(), source);
DCHECK(i != controllers_.end());
selected_view_index_ = i - controllers_.begin();
authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
Profile* profile = g_browser_process->profile_manager()->GetDefaultProfile();
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::AuthenticateToLogin,
profile,
controllers_[selected_view_index_]->user().email(),
UTF16ToUTF8(password),
login_token_,
login_captcha_));
// Disable clicking on other windows.
SendSetLoginState(false);
}
void ExistingUserController::LoginOffTheRecord() {
authenticator_ = LoginUtils::Get()->CreateAuthenticator(this);
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::LoginOffTheRecord));
// Disable clicking on other windows.
SendSetLoginState(false);
}
void ExistingUserController::ClearErrors() {
// bubble_ will be set to NULL in callback.
if (bubble_)
bubble_->Close();
}
void ExistingUserController::OnUserSelected(UserController* source) {
std::vector<UserController*>::const_iterator i =
std::find(controllers_.begin(), controllers_.end(), source);
DCHECK(i != controllers_.end());
size_t new_selected_index = i - controllers_.begin();
if (new_selected_index != selected_view_index_ &&
selected_view_index_ != kNotSelected) {
controllers_[selected_view_index_]->ClearAndEnablePassword();
ClearCaptchaState();
}
selected_view_index_ = new_selected_index;
}
void ExistingUserController::ActivateWizard(const std::string& screen_name) {
// WizardController takes care of deleting itself when done.
WizardController* controller = new WizardController();
// Give the background window to the controller.
controller->OwnBackground(background_window_, background_view_);
background_window_ = NULL;
controller->Init(screen_name, background_bounds_);
controller->Show();
// And schedule us for deletion. We delay for a second as the window manager
// is doing an animation with our windows.
DCHECK(!delete_scheduled_instance_);
delete_scheduled_instance_ = this;
delete_timer_.Start(base::TimeDelta::FromSeconds(1), this,
&ExistingUserController::Delete);
}
void ExistingUserController::RemoveUser(UserController* source) {
ClearErrors();
UserManager::Get()->RemoveUser(source->user().email());
// We need to unmap entry windows, the windows will be unmapped in destructor.
controllers_.erase(controllers_.begin() + source->user_index());
delete source;
EnableTooltipsIfNeeded(controllers_);
int new_size = static_cast<int>(controllers_.size());
for (int i = 0; i < new_size; ++i)
controllers_[i]->UpdateUserCount(i, new_size);
}
void ExistingUserController::SelectUser(int index) {
if (index >= 0 && index < static_cast<int>(controllers_.size()) &&
index != static_cast<int>(selected_view_index_)) {
WmIpc::Message message(WM_IPC_MESSAGE_WM_SELECT_LOGIN_USER);
message.set_param(0, index);
WmIpc::instance()->SendMessage(message);
}
}
void ExistingUserController::OnLoginFailure(const std::string& error) {
LOG(INFO) << "OnLoginFailure";
ClearCaptchaState();
// Check networking after trying to login in case user is
// cached locally or the local admin account.
NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary();
if (!network || !CrosLibrary::Get()->EnsureLoaded()) {
ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY, error);
} else if (!network->Connected()) {
ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED, error);
} else {
std::string error_code = LoginUtils::ExtractClientLoginParam(error,
kError,
kParamSuffix);
std::string captcha_url;
if (error_code == kCaptchaError)
captcha_url = LoginUtils::ExtractClientLoginParam(error,
kCaptchaUrlParam,
kParamSuffix);
if (captcha_url.empty()) {
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING, error);
} else {
// Save token for next login retry.
login_token_ = LoginUtils::ExtractClientLoginParam(error,
kCaptchaTokenParam,
kParamSuffix);
CaptchaView* view =
new CaptchaView(GURL(kCaptchaUrlPrefix + captcha_url));
view->set_delegate(this);
views::Window* window = views::Window::CreateChromeWindow(
GetNativeWindow(), gfx::Rect(), view);
window->SetIsAlwaysOnTop(true);
window->Show();
}
}
controllers_[selected_view_index_]->ClearAndEnablePassword();
// Reenable clicking on other windows.
SendSetLoginState(true);
}
void ExistingUserController::AppendStartUrlToCmdline() {
if (start_url_.is_valid()) {
CommandLine::ForCurrentProcess()->AppendLooseValue(
UTF8ToWide(start_url_.spec()));
}
}
void ExistingUserController::ClearCaptchaState() {
login_token_.clear();
login_captcha_.clear();
}
gfx::NativeWindow ExistingUserController::GetNativeWindow() const {
return GTK_WINDOW(
static_cast<views::WidgetGtk*>(background_window_)->GetNativeView());
}
void ExistingUserController::ShowError(int error_id,
const std::string& details) {
ClearErrors();
std::wstring error_text = l10n_util::GetString(error_id);
if (!details.empty())
error_text += L"\n" + ASCIIToWide(details);
bubble_ = MessageBubble::Show(
controllers_[selected_view_index_]->controls_window(),
controllers_[selected_view_index_]->GetScreenBounds(),
BubbleBorder::BOTTOM_LEFT,
ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING),
error_text,
this);
}
void ExistingUserController::OnLoginSuccess(const std::string& username,
const GaiaAuthConsumer::ClientLoginResult& credentials) {
AppendStartUrlToCmdline();
if (selected_view_index_ + 1 == controllers_.size()) {
// For new user login don't launch browser until we pass image screen.
LoginUtils::Get()->EnableBrowserLaunch(false);
LoginUtils::Get()->CompleteLogin(username, credentials);
ActivateWizard(WizardController::kUserImageScreenName);
} else {
// Hide the login windows now.
WmIpc::Message message(WM_IPC_MESSAGE_WM_HIDE_LOGIN);
WmIpc::instance()->SendMessage(message);
LoginUtils::Get()->CompleteLogin(username, credentials);
// Delay deletion as we're on the stack.
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
}
void ExistingUserController::OnOffTheRecordLoginSuccess() {
AppendStartUrlToCmdline();
LoginUtils::Get()->CompleteOffTheRecordLogin();
}
void ExistingUserController::OnPasswordChangeDetected(
const GaiaAuthConsumer::ClientLoginResult& credentials) {
// When signing in as a "New user" always remove old cryptohome.
if (selected_view_index_ == controllers_.size() - 1) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::ResyncEncryptedData,
credentials));
return;
}
cached_credentials_ = credentials;
PasswordChangedView* view = new PasswordChangedView(this);
views::Window* window = views::Window::CreateChromeWindow(GetNativeWindow(),
gfx::Rect(),
view);
window->SetIsAlwaysOnTop(true);
window->Show();
}
void ExistingUserController::OnCaptchaEntered(const std::string& captcha) {
login_captcha_ = captcha;
}
void ExistingUserController::RecoverEncryptedData(
const std::string& old_password) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::RecoverEncryptedData,
old_password,
cached_credentials_));
cached_credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
void ExistingUserController::ResyncEncryptedData() {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(authenticator_.get(),
&Authenticator::ResyncEncryptedData,
cached_credentials_));
cached_credentials_ = GaiaAuthConsumer::ClientLoginResult();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/*
* SessionRmdNotebook.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookPlots.hpp"
#include "NotebookPlotReplay.hpp"
#include "NotebookCache.hpp"
#include "NotebookChunkDefs.hpp"
#include "NotebookData.hpp"
#include "NotebookOutput.hpp"
#include "NotebookHtmlWidgets.hpp"
#include "NotebookExec.hpp"
#include "NotebookErrors.hpp"
#include "NotebookQueue.hpp"
#include "NotebookAlternateEngines.hpp"
#include "NotebookConditions.hpp"
#include <iostream>
#include <boost/format.hpp>
#include <r/RJson.hpp>
#include <r/RExec.hpp>
#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <shared_core/json/Json.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionOptions.hpp>
#include <session/prefs/UserState.hpp>
#define kFinishedReplay 0
#define kFinishedInteractive 1
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
// the currently active console ID and chunk execution context
std::string s_activeConsole;
boost::shared_ptr<ChunkExecContext> s_execContext;
void replayChunkOutputs(const std::string& docPath, const std::string& docId,
const std::string& requestId, const std::string& singleChunkId,
const json::Array& chunkOutputs)
{
std::vector<std::string> chunkIds;
extractChunkIds(chunkOutputs, &chunkIds);
if (singleChunkId.empty())
{
// find all the chunks and play them back to the client
for (const std::string& chunkId : chunkIds)
{
enqueueChunkOutput(docPath, docId, chunkId, notebookCtxId(), requestId);
}
}
else
{
// play back a specific chunk
enqueueChunkOutput(docPath, docId, singleChunkId, notebookCtxId(),
requestId);
}
json::Object result;
result["doc_id"] = docId;
result["request_id"] = requestId;
result["chunk_id"] = singleChunkId.empty() ? "" : singleChunkId;
result["type"] = kFinishedReplay;
ClientEvent event(client_events::kChunkOutputFinished, result);
module_context::enqueClientEvent(event);
}
// called by the client to inject output into a recently opened document
Error refreshChunkOutput(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// extract path to doc to be refreshed
std::string docPath, docId, nbCtxId, requestId, chunkId;
Error error = json::readParams(request.params, &docPath, &docId, &nbCtxId,
&requestId, &chunkId);
if (error)
return error;
json::Object result;
json::Array chunkDefs;
// use our own context ID if none supplied
if (nbCtxId.empty())
error = getChunkValue(docPath, docId, kChunkDefs, &chunkDefs);
else
error = getChunkValue(docPath, docId, nbCtxId, kChunkDefs, &chunkDefs);
// schedule the work to play back the chunks
if (!error)
{
pResponse->setAfterResponse(
boost::bind(replayChunkOutputs, docPath, docId, requestId, chunkId,
chunkDefs));
}
// send back the execution queue, if any
pResponse->setResult(getDocQueue(docId));
return Success();
}
void emitOutputFinished(const std::string& docId, const std::string& chunkId,
const std::string& htmlCallback, int scope)
{
json::Object result;
result["doc_id"] = docId;
result["request_id"] = "";
result["chunk_id"] = chunkId;
result["html_callback"] = htmlCallback;
result["type"] = kFinishedInteractive;
result["scope"] = scope;
ClientEvent event(client_events::kChunkOutputFinished, result);
module_context::enqueClientEvent(event);
}
bool fixChunkFilename(int, const core::FilePath& path)
{
std::string name = path.getFilename();
if (name.empty())
return true;
// replace spaces at start of name with '0'
std::string transformed = name;
for (std::size_t i = 0, n = transformed.size(); i < n; ++i)
{
if (transformed[i] != ' ')
break;
transformed[i] = '0';
}
// rename file if we had to change it
if (transformed != name)
{
FilePath target = path.getParent().completeChildPath(transformed);
Error error = path.move(target);
if (error)
LOG_ERROR(error);
}
// return true to continue traversal
return true;
}
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId,
const std::string& code,
const std::string& label,
const std::string& nbCtxId)
{
r::sexp::Protect rProtect;
SEXP resultSEXP = R_NilValue;
std::string callback;
r::exec::RFunction func(".rs.executeChunkCallback");
func.addParam(label);
func.addParam(code);
core::Error error = func.call(&resultSEXP, &rProtect);
if (error)
LOG_ERROR(error);
else if (!r::sexp::isNull(resultSEXP))
{
json::Object results;
Error error = r::json::jsonValueFromList(resultSEXP, &results);
if (error)
LOG_ERROR(error);
else
{
if (results.hasMember("html"))
{
// assumes only one callback is returned
if (results["html"].isString())
callback = results["html"].getString();
else if (results["html"].isArray() &&
results["html"].getArray().getValueAt(0).isString())
callback = results["html"].getArray().getValueAt(0).getString();
}
}
}
emitOutputFinished(docId, chunkId, callback, ExecScopeChunk);
}
void onDeferredInit(bool)
{
FilePath root = notebookCacheRoot();
root.ensureDirectory();
// Fix up chunk entries in the cache that were generated
// with leading spaces on Windows
FilePath patchPath = root.completePath("patch-chunk-names");
if (!patchPath.exists())
{
patchPath.ensureFile();
Error error = root.getChildrenRecursive(fixChunkFilename);
if (error)
LOG_ERROR(error);
}
}
} // anonymous namespace
Events& events()
{
static Events instance;
return instance;
}
// a notebook context is scoped to both a user and a session (which are only
// guaranteed unique per user); it must be unique since there are currently no
// concurrency mechanisms in place to guard multi-session writes to the file.
// the notebook context ID may be shared with other users/sessions for read
// access during collaborative editing, but only a notebook context's own
// session should write to it.
std::string notebookCtxId()
{
return prefs::userState().contextId() + module_context::activeSession().id();
}
Error initialize()
{
using boost::bind;
using namespace module_context;
events().onChunkExecCompleted.connect(onChunkExecCompleted);
module_context::events().onDeferredInit.connect(onDeferredInit);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "refresh_chunk_output", refreshChunkOutput))
(bind(module_context::sourceModuleRFile, "SessionRmdNotebook.R"))
(bind(initOutput))
(bind(initCache))
(bind(initData))
(bind(initHtmlWidgets))
(bind(initErrors))
(bind(initPlots))
(bind(initPlotReplay))
(bind(initQueue))
(bind(initAlternateEngines))
(bind(initChunkDefs))
(bind(initConditions));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>escape chunk name and code before passing to executeChunkCallback<commit_after>/*
* SessionRmdNotebook.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRmdNotebook.hpp"
#include "NotebookPlots.hpp"
#include "NotebookPlotReplay.hpp"
#include "NotebookCache.hpp"
#include "NotebookChunkDefs.hpp"
#include "NotebookData.hpp"
#include "NotebookOutput.hpp"
#include "NotebookHtmlWidgets.hpp"
#include "NotebookExec.hpp"
#include "NotebookErrors.hpp"
#include "NotebookQueue.hpp"
#include "NotebookAlternateEngines.hpp"
#include "NotebookConditions.hpp"
#include <iostream>
#include <boost/format.hpp>
#include <r/RJson.hpp>
#include <r/RExec.hpp>
#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <shared_core/json/Json.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionOptions.hpp>
#include <session/prefs/UserState.hpp>
#define kFinishedReplay 0
#define kFinishedInteractive 1
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
namespace notebook {
namespace {
// the currently active console ID and chunk execution context
std::string s_activeConsole;
boost::shared_ptr<ChunkExecContext> s_execContext;
void replayChunkOutputs(const std::string& docPath, const std::string& docId,
const std::string& requestId, const std::string& singleChunkId,
const json::Array& chunkOutputs)
{
std::vector<std::string> chunkIds;
extractChunkIds(chunkOutputs, &chunkIds);
if (singleChunkId.empty())
{
// find all the chunks and play them back to the client
for (const std::string& chunkId : chunkIds)
{
enqueueChunkOutput(docPath, docId, chunkId, notebookCtxId(), requestId);
}
}
else
{
// play back a specific chunk
enqueueChunkOutput(docPath, docId, singleChunkId, notebookCtxId(),
requestId);
}
json::Object result;
result["doc_id"] = docId;
result["request_id"] = requestId;
result["chunk_id"] = singleChunkId.empty() ? "" : singleChunkId;
result["type"] = kFinishedReplay;
ClientEvent event(client_events::kChunkOutputFinished, result);
module_context::enqueClientEvent(event);
}
// called by the client to inject output into a recently opened document
Error refreshChunkOutput(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
// extract path to doc to be refreshed
std::string docPath, docId, nbCtxId, requestId, chunkId;
Error error = json::readParams(request.params, &docPath, &docId, &nbCtxId,
&requestId, &chunkId);
if (error)
return error;
json::Object result;
json::Array chunkDefs;
// use our own context ID if none supplied
if (nbCtxId.empty())
error = getChunkValue(docPath, docId, kChunkDefs, &chunkDefs);
else
error = getChunkValue(docPath, docId, nbCtxId, kChunkDefs, &chunkDefs);
// schedule the work to play back the chunks
if (!error)
{
pResponse->setAfterResponse(
boost::bind(replayChunkOutputs, docPath, docId, requestId, chunkId,
chunkDefs));
}
// send back the execution queue, if any
pResponse->setResult(getDocQueue(docId));
return Success();
}
void emitOutputFinished(const std::string& docId, const std::string& chunkId,
const std::string& htmlCallback, int scope)
{
json::Object result;
result["doc_id"] = docId;
result["request_id"] = "";
result["chunk_id"] = chunkId;
result["html_callback"] = htmlCallback;
result["type"] = kFinishedInteractive;
result["scope"] = scope;
ClientEvent event(client_events::kChunkOutputFinished, result);
module_context::enqueClientEvent(event);
}
bool fixChunkFilename(int, const core::FilePath& path)
{
std::string name = path.getFilename();
if (name.empty())
return true;
// replace spaces at start of name with '0'
std::string transformed = name;
for (std::size_t i = 0, n = transformed.size(); i < n; ++i)
{
if (transformed[i] != ' ')
break;
transformed[i] = '0';
}
// rename file if we had to change it
if (transformed != name)
{
FilePath target = path.getParent().completeChildPath(transformed);
Error error = path.move(target);
if (error)
LOG_ERROR(error);
}
// return true to continue traversal
return true;
}
void onChunkExecCompleted(const std::string& docId,
const std::string& chunkId,
const std::string& code,
const std::string& label,
const std::string& nbCtxId)
{
r::sexp::Protect rProtect;
SEXP resultSEXP = R_NilValue;
std::string callback;
std::string escapedLabel =
core::string_utils::jsLiteralEscape(
core::string_utils::htmlEscape(label, true));
std::string escapedCode =
core::string_utils::jsLiteralEscape(
core::string_utils::htmlEscape(code, true));
boost::algorithm::replace_all(escapedLabel, "-", "_");
boost::algorithm::replace_all(escapedCode, "-", "_");
r::exec::RFunction func(".rs.executeChunkCallback");
func.addParam(escapedLabel);
func.addParam(escapedCode);
core::Error error = func.call(&resultSEXP, &rProtect);
if (error)
LOG_ERROR(error);
else if (!r::sexp::isNull(resultSEXP))
{
json::Object results;
Error error = r::json::jsonValueFromList(resultSEXP, &results);
if (error)
LOG_ERROR(error);
else
{
if (results.hasMember("html"))
{
// assumes only one callback is returned
if (results["html"].isString())
callback = results["html"].getString();
else if (results["html"].isArray() &&
results["html"].getArray().getValueAt(0).isString())
callback = results["html"].getArray().getValueAt(0).getString();
}
}
}
emitOutputFinished(docId, chunkId, callback, ExecScopeChunk);
}
void onDeferredInit(bool)
{
FilePath root = notebookCacheRoot();
root.ensureDirectory();
// Fix up chunk entries in the cache that were generated
// with leading spaces on Windows
FilePath patchPath = root.completePath("patch-chunk-names");
if (!patchPath.exists())
{
patchPath.ensureFile();
Error error = root.getChildrenRecursive(fixChunkFilename);
if (error)
LOG_ERROR(error);
}
}
} // anonymous namespace
Events& events()
{
static Events instance;
return instance;
}
// a notebook context is scoped to both a user and a session (which are only
// guaranteed unique per user); it must be unique since there are currently no
// concurrency mechanisms in place to guard multi-session writes to the file.
// the notebook context ID may be shared with other users/sessions for read
// access during collaborative editing, but only a notebook context's own
// session should write to it.
std::string notebookCtxId()
{
return prefs::userState().contextId() + module_context::activeSession().id();
}
Error initialize()
{
using boost::bind;
using namespace module_context;
events().onChunkExecCompleted.connect(onChunkExecCompleted);
module_context::events().onDeferredInit.connect(onDeferredInit);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(registerRpcMethod, "refresh_chunk_output", refreshChunkOutput))
(bind(module_context::sourceModuleRFile, "SessionRmdNotebook.R"))
(bind(initOutput))
(bind(initCache))
(bind(initData))
(bind(initHtmlWidgets))
(bind(initErrors))
(bind(initPlots))
(bind(initPlotReplay))
(bind(initQueue))
(bind(initAlternateEngines))
(bind(initChunkDefs))
(bind(initConditions));
return initBlock.execute();
}
} // namespace notebook
} // namespace rmarkdown
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>#include "VortexSheet.hpp"
VortexSheet::VortexSheet()
{
}
VortexSheet::VortexSheet(const XmlHandler &xml)
{
m_rho = xml.getValueAttribute("constants", "density");
m_nu = xml.getValueAttribute("constants", "nu");
m_dt = xml.getValueAttribute("time", "dt");
m_maxGamma= xml.getValueAttribute("constants", "max_Gamma");
m_maxNumPanelVort= xml.getValueAttribute("constants", "max_NumPanelVort");
m_cutoff_exp = xml.getValueAttribute("constants", "cutoff_exp");
}
void VortexSheet::resize(unsigned size)
{
gamma.set_size(size);
x.set_size(size+1);
z.set_size(size+1);
xc.set_size(size);
zc.set_size(size);
theta.set_size(size);
ds.set_size(size);
enx.set_size(size);
enz.set_size(size);
etx.set_size(size);
etz.set_size(size);
}
VortexBlobs VortexSheet::release_nascent_vortices_rw(Random& _rand)
{
//double x, z, circ, sigma;
auto Nvs = size();
double R, rrw;
// First we need to determine how many of these vortices will be created at each
// panel. This is in accordance with Morgenthal PhD 4.3.6 Vortex release algorithm (eq. 4.108)
Vector_un PanelNewVort(Nvs); // Panel's new vortices
Vector PanelCirc = gamma%ds; // Panel's total circulation
Vector AbsPanelCirc = arma::abs(PanelCirc/arma::max(PanelCirc)*m_maxNumPanelVort); // Absolute value of the panel vorticity
Vector Circ_new(Nvs);
//GD---> Should not need to do a loop here. Unfortunately for some reason armadillo does not allow me to do
// PanelNewVort=arma::round(AbsPanelCirc)+arma::ones(Nvs,1), perhaps MAB can fix this.
for (unsigned i=0;i<Nvs;i++)
{
PanelNewVort(i) = std::floor(AbsPanelCirc(i))+1; // Number of released vortices per panel
assert(PanelNewVort(i)>0);
Circ_new(i)=PanelCirc(i)/PanelNewVort(i); // Circulation of each vortex we release from the ith panel
}
unsigned Nrv=arma::sum(PanelNewVort); //Number of the new vortices.
// if we set the maximum number of vortices from each panel=1, then Nrv=Nsv
// Initialize the vortexblobs ready for release
VortexBlobs nascentVort(Nrv);
//Calculating the position of the newelly released vortices
double xm,zm;
unsigned counter=0;
for (unsigned i=0; i<Nvs;i++){
unsigned j=0;
while (j<PanelNewVort(i))
{
//Find locations at the ith panel from which the vortices should be released
xm=x(i)+ds(i)*etx(i)/(PanelNewVort(i)+1);
zm=z(i)+ds(i)*etz(i)/(PanelNewVort(i)+1);
//Here is the tricky bit !!! Morgenthal shows in figure 4.7 that the particles may be released with
//some random walk in both the normal (to the panel) and the tangential directions. This is
//wrong according to Chorin 1978. Since we are in the boundary layer, the diffusion process takes place only
//in the normal direction and not the streamwise. This also according to Prandtl's boundary layer approximation.
//I will implement the Chorin 1978 here and not the Morgenthal one. In the end, this should not make
//a huge difference.
//Create Random walk values
R=_rand.rand();
rrw=std::abs(std::sqrt(4.0*m_nu*m_dt*std::log(1.0/R))); //This is half normal distribution only in the ourwards direction
// Add the released vortex
nascentVort.m_x(counter)=xm+rrw*enx(i);
nascentVort.m_z(counter)=zm+rrw*enz(i);
nascentVort.m_circ(counter)=Circ_new(i);
//Now for the cut-off kernel we implement things as suggested by Mirta Perlman 1985 (JCP)
//using sigma=ds^q where 0.5<q<1. She suggests using q=0.625! This q parameter is the coefficient not the cutoff
//parameter the inputs file.
nascentVort.m_sigma(counter)=std::pow(ds(i),m_cutoff_exp);
counter++;
assert(counter<=Nrv);
j++;
}
}
return nascentVort;
}
void VortexSheet::reflect(VortexBlobs& vortex)
{
Vector_un closest_panel(size());
Vector min_dist(size());
Vector _mirror(2);
double x_init, z_init, x_0, z_0, x_1, z_1;
double dx, dz, dr, min_prev;
for (unsigned i = 0; i < size(); i++) {
min_dist(i) = 0;
closest_panel(i) = 0;
if (inside_body(vortex.m_x(i), vortex.m_z(i))<0) {
// Find which panel is closest to the vortex
min_prev = 10E6;
for (unsigned j = 0; j < size(); j++) {
dx = xc(j) - vortex.m_x(i);
dz = zc(j) - vortex.m_z(i);
dr = std::sqrt(std::pow(dx, 2.0) + std::pow(dz, 2.0));
if (dr < min_prev) {
closest_panel(i) = j;
min_prev = dr;
}
}
// Find the mirror image vortex blob
x_init = vortex.m_x(i);
z_init = vortex.m_z(i);
x_0 = x(closest_panel(i));
z_0 = z(closest_panel(i));
x_1 = x(closest_panel(i) + 1);
z_1 = z(closest_panel(i) + 1);
_mirror = mirror(x_init, z_init, x_0, z_0, x_1, z_1);
vortex.m_x(i) = _mirror(0);
vortex.m_z(i) = _mirror(1);
// All other properties of the vortices
}
}
}
int VortexSheet::inside_body(const double& xcoor, const double& zcoor)
{
// Checks whether a vortex is inside the body following the crossing rule method
// The algorithm reports the panel number that this particular vortex crossed
// which is then used in the absorb algorithm if it is inside the body and gives
// the satanic -666 if the goddam vortex is still free !!!
int cn = -666;
for (unsigned i = 0; i < size(); i++) {
if (((z(i) <= zcoor) && (z(i + 1) > zcoor))
|| ((z(i) > zcoor) && (z(i + 1) <= zcoor))) {
float vt =
(float)(zcoor - z(i)) / (z(i + 1) - z(i));
if (xcoor < x(i) + vt * (x(i + 1) - x(i))) {
cn=i; //This the number of the panel that the particle crossed
}
}
}
return (cn);
}
Vector VortexSheet::mirror(const double &x_init,
const double &z_init,
const double &x_0,
const double &z_0,
const double &x_1,
const double &z_1)
{
Vector p2(2);
double dx, dz, a, b;
dx = x_1 - x_0;
dz = z_1 - z_0;
a = (dx * dx - dz * dz) / (dx * dx + dz * dz);
b = 2.0 * dx * dz / (dx * dx + dz * dz);
p2(0) = a * (x_init - x_0) + b * (z_init - z_0) + x_0;
p2(1) = b * (x_init - x_0) - a * (z_init - z_0) + z_0;
return p2;
}
void VortexSheet::compute_loads(double Ur)
{
Vector P(size());
Vector Dp = -m_rho / m_dt * (gamma % ds);
for (unsigned i=0;i<size()-1;i++)
{
P(i+1)=P(i)+Dp(i);
}
// Finding the average of the two pressures at the boundary
for (unsigned i=0;i<size()-1;i++)
{
P(i)=0.5*(P(i)+P(i+1));
}
P(size()-1)=0.5*(P(size()-1)+P(0));
double pmax=arma::max(P);
double pref=0.5*m_rho*Ur*Ur;
P += (pref-pmax)*arma::ones(size(),1);
// To find the forces we need to measure on the particle
// we need to change sign
m_fx = -arma::sum(P % enx % ds);
m_fz = -arma::sum(P % enz % ds);
std::cout<<"C_D = "<<m_fx/(0.5*m_rho*1.0*Ur*Ur)<<"\t"<<"C_L = "<<m_fz/(0.5*m_rho*1.0*Ur*Ur)<<std::endl;
}
unsigned VortexSheet::size()
{
if ((gamma.size() != xc.size())
&& (gamma.size() != zc.size())
&& (gamma.size() != x.size()-1)
&& (gamma.size() != z.size()-1)
&& (gamma.size() != ds.size())
&& (gamma.size() != theta.size())
&& (gamma.size() != enx.size())
&& (gamma.size() != enz.size())
&& (gamma.size() != etx.size())
&& (gamma.size() != etz.size())) {
throw std::string("Size mismatch in VortexSheet");
}
return gamma.size();
}
void VortexSheet::print_collocation()
{
for (unsigned i = 0; i < size(); i++) {
std::cout << "(xc,zc) = (" << xc(i) << "," << zc(i) << ")" << std::endl;
}
}
void VortexSheet::print_unit_vectors()
{
for (unsigned i = 0; i < size(); i++) {
std::cout << "For panel No " << i << "the normal vectors are en = ("
<< enx(i) << "," << enz(i) << ") and et = (" << etx(i) << ","
<< etz(i) << ")" << std::endl;
}
}
void VortexSheet::print_gamma()
{
gamma.print();
}
std::tuple<double, double> VortexSheet::get_forces()
{
return std::make_tuple(m_fx, m_fz);
}
<commit_msg>fix inside body<commit_after>#include "VortexSheet.hpp"
VortexSheet::VortexSheet()
{
}
VortexSheet::VortexSheet(const XmlHandler &xml)
{
m_rho = xml.getValueAttribute("constants", "density");
m_nu = xml.getValueAttribute("constants", "nu");
m_dt = xml.getValueAttribute("time", "dt");
m_maxGamma= xml.getValueAttribute("constants", "max_Gamma");
m_maxNumPanelVort= xml.getValueAttribute("constants", "max_NumPanelVort");
m_cutoff_exp = xml.getValueAttribute("constants", "cutoff_exp");
}
void VortexSheet::resize(unsigned size)
{
gamma.set_size(size);
x.set_size(size+1);
z.set_size(size+1);
xc.set_size(size);
zc.set_size(size);
theta.set_size(size);
ds.set_size(size);
enx.set_size(size);
enz.set_size(size);
etx.set_size(size);
etz.set_size(size);
}
VortexBlobs VortexSheet::release_nascent_vortices_rw(Random& _rand)
{
//double x, z, circ, sigma;
auto Nvs = size();
double R, rrw;
// First we need to determine how many of these vortices will be created at each
// panel. This is in accordance with Morgenthal PhD 4.3.6 Vortex release algorithm (eq. 4.108)
Vector_un PanelNewVort(Nvs); // Panel's new vortices
Vector PanelCirc = gamma%ds; // Panel's total circulation
Vector AbsPanelCirc = arma::abs(PanelCirc/arma::max(PanelCirc)*m_maxNumPanelVort); // Absolute value of the panel vorticity
Vector Circ_new(Nvs);
//GD---> Should not need to do a loop here. Unfortunately for some reason armadillo does not allow me to do
// PanelNewVort=arma::round(AbsPanelCirc)+arma::ones(Nvs,1), perhaps MAB can fix this.
for (unsigned i=0;i<Nvs;i++)
{
PanelNewVort(i) = std::floor(AbsPanelCirc(i))+1; // Number of released vortices per panel
assert(PanelNewVort(i)>0);
Circ_new(i)=PanelCirc(i)/PanelNewVort(i); // Circulation of each vortex we release from the ith panel
}
unsigned Nrv=arma::sum(PanelNewVort); //Number of the new vortices.
// if we set the maximum number of vortices from each panel=1, then Nrv=Nsv
// Initialize the vortexblobs ready for release
VortexBlobs nascentVort(Nrv);
//Calculating the position of the newelly released vortices
double xm,zm;
unsigned counter=0;
for (unsigned i=0; i<Nvs;i++){
unsigned j=0;
while (j<PanelNewVort(i))
{
//Find locations at the ith panel from which the vortices should be released
xm=x(i)+ds(i)*etx(i)/(PanelNewVort(i)+1);
zm=z(i)+ds(i)*etz(i)/(PanelNewVort(i)+1);
//Here is the tricky bit !!! Morgenthal shows in figure 4.7 that the particles may be released with
//some random walk in both the normal (to the panel) and the tangential directions. This is
//wrong according to Chorin 1978. Since we are in the boundary layer, the diffusion process takes place only
//in the normal direction and not the streamwise. This also according to Prandtl's boundary layer approximation.
//I will implement the Chorin 1978 here and not the Morgenthal one. In the end, this should not make
//a huge difference.
//Create Random walk values
R=_rand.rand();
rrw=std::abs(std::sqrt(4.0*m_nu*m_dt*std::log(1.0/R))); //This is half normal distribution only in the ourwards direction
// Add the released vortex
nascentVort.m_x(counter)=xm+rrw*enx(i);
nascentVort.m_z(counter)=zm+rrw*enz(i);
nascentVort.m_circ(counter)=Circ_new(i);
//Now for the cut-off kernel we implement things as suggested by Mirta Perlman 1985 (JCP)
//using sigma=ds^q where 0.5<q<1. She suggests using q=0.625! This q parameter is the coefficient not the cutoff
//parameter the inputs file.
nascentVort.m_sigma(counter)=std::pow(ds(i),m_cutoff_exp);
counter++;
assert(counter<=Nrv);
j++;
}
}
return nascentVort;
}
void VortexSheet::reflect(VortexBlobs& vortex)
{
Vector_un closest_panel(size());
Vector min_dist(size());
Vector _mirror(2);
double x_init, z_init, x_0, z_0, x_1, z_1;
double dx, dz, dr, min_prev;
for (unsigned i = 0; i < size(); i++) {
min_dist(i) = 0;
closest_panel(i) = 0;
if (inside_body(vortex.m_x(i), vortex.m_z(i))) {
// Find which panel is closest to the vortex
min_prev = 10E6;
for (unsigned j = 0; j < size(); j++) {
dx = xc(j) - vortex.m_x(i);
dz = zc(j) - vortex.m_z(i);
dr = std::sqrt(std::pow(dx, 2.0) + std::pow(dz, 2.0));
if (dr < min_prev) {
closest_panel(i) = j;
min_prev = dr;
}
}
// Find the mirror image vortex blob
x_init = vortex.m_x(i);
z_init = vortex.m_z(i);
x_0 = x(closest_panel(i));
z_0 = z(closest_panel(i));
x_1 = x(closest_panel(i) + 1);
z_1 = z(closest_panel(i) + 1);
_mirror = mirror(x_init, z_init, x_0, z_0, x_1, z_1);
vortex.m_x(i) = _mirror(0);
vortex.m_z(i) = _mirror(1);
// All other properties of the vortices
}
}
}
int VortexSheet::inside_body(const double& xcoor, const double& zcoor)
{
int cn = 0;
for (unsigned i = 0; i < size(); i++) {
if (((z(i) <= zcoor) && (z(i + 1) > zcoor))
|| ((z(i) > zcoor) && (z(i + 1) <= zcoor))) {
float vt =
(float)(zcoor - z(i)) / (z(i + 1) - z(i));
if (xcoor < x(i) + vt * (x(i + 1) - x(i))) {
++cn; //This the number of the panel that the particle crossed
}
}
}
return (cn & 1);
}
Vector VortexSheet::mirror(const double &x_init,
const double &z_init,
const double &x_0,
const double &z_0,
const double &x_1,
const double &z_1)
{
Vector p2(2);
double dx, dz, a, b;
dx = x_1 - x_0;
dz = z_1 - z_0;
a = (dx * dx - dz * dz) / (dx * dx + dz * dz);
b = 2.0 * dx * dz / (dx * dx + dz * dz);
p2(0) = a * (x_init - x_0) + b * (z_init - z_0) + x_0;
p2(1) = b * (x_init - x_0) - a * (z_init - z_0) + z_0;
return p2;
}
void VortexSheet::compute_loads(double Ur)
{
Vector P(size());
Vector Dp = -m_rho / m_dt * (gamma % ds);
for (unsigned i=0;i<size()-1;i++)
{
P(i+1)=P(i)+Dp(i);
}
// Finding the average of the two pressures at the boundary
for (unsigned i=0;i<size()-1;i++)
{
P(i)=0.5*(P(i)+P(i+1));
}
P(size()-1)=0.5*(P(size()-1)+P(0));
double pmax=arma::max(P);
double pref=0.5*m_rho*Ur*Ur;
P += (pref-pmax)*arma::ones(size(),1);
// To find the forces we need to measure on the particle
// we need to change sign
m_fx = -arma::sum(P % enx % ds);
m_fz = -arma::sum(P % enz % ds);
std::cout<<"C_D = "<<m_fx/(0.5*m_rho*1.0*Ur*Ur)<<"\t"<<"C_L = "<<m_fz/(0.5*m_rho*1.0*Ur*Ur)<<std::endl;
}
unsigned VortexSheet::size()
{
if ((gamma.size() != xc.size())
&& (gamma.size() != zc.size())
&& (gamma.size() != x.size()-1)
&& (gamma.size() != z.size()-1)
&& (gamma.size() != ds.size())
&& (gamma.size() != theta.size())
&& (gamma.size() != enx.size())
&& (gamma.size() != enz.size())
&& (gamma.size() != etx.size())
&& (gamma.size() != etz.size())) {
throw std::string("Size mismatch in VortexSheet");
}
return gamma.size();
}
void VortexSheet::print_collocation()
{
for (unsigned i = 0; i < size(); i++) {
std::cout << "(xc,zc) = (" << xc(i) << "," << zc(i) << ")" << std::endl;
}
}
void VortexSheet::print_unit_vectors()
{
for (unsigned i = 0; i < size(); i++) {
std::cout << "For panel No " << i << "the normal vectors are en = ("
<< enx(i) << "," << enz(i) << ") and et = (" << etx(i) << ","
<< etz(i) << ")" << std::endl;
}
}
void VortexSheet::print_gamma()
{
gamma.print();
}
std::tuple<double, double> VortexSheet::get_forces()
{
return std::make_tuple(m_fx, m_fz);
}
<|endoftext|> |
<commit_before>#pragma once
#include <optional>
// #include <type_traits>
#include "acmacs-base/float.hh"
// ----------------------------------------------------------------------
namespace acmacs::internal
{
template <typename T> class field_optional_with_default
{
public:
inline field_optional_with_default() = default;
inline field_optional_with_default(const T aDefault) : mDefault{aDefault} {}
inline field_optional_with_default(const field_optional_with_default&) = default;
inline field_optional_with_default& operator=(const field_optional_with_default& aOther)
{
if (aOther.present())
mValue = aOther.mValue;
return *this;
}
inline field_optional_with_default& operator=(const T aValue) { mValue = aValue; return *this; }
[[nodiscard]] inline bool operator==(const field_optional_with_default<T>& f) const { return mValue == f.mValue && mDefault == f.mDefault; }
inline bool is_default() const { return !mValue.has_value() || mValue.value() == mDefault; }
inline bool not_default() const { return mValue.has_value() && mValue.value() != mDefault; }
inline bool present() const { return mValue.has_value(); }
inline operator const T() const { return mValue.value_or(mDefault); }
inline const T operator*() const { return *this; }
inline const std::decay_t<T>* operator->() const
{
if (present())
return &mValue.value();
else
return &mDefault;
}
private:
std::optional<std::decay_t<T>> mValue;
const T mDefault;
}; // class field_optional_with_default<>
template <> inline bool field_optional_with_default<double>::operator==(const field_optional_with_default<double>& f) const
{
return ((mValue.has_value() && f.mValue.has_value() && float_equal(mValue.value(), f.mValue.value())) || (!mValue.has_value() && !f.mValue.has_value())) && float_equal(mDefault, f.mDefault);
}
template <> inline bool field_optional_with_default<double>::is_default() const
{
return !mValue.has_value() || float_equal(mValue.value(), mDefault);
}
template <> inline bool field_optional_with_default<double>::not_default() const
{
return mValue.has_value() && ! float_equal(mValue.value(), mDefault);
}
} // namespace acmacs::internal
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>field_optional_with_default improvement<commit_after>#pragma once
#include <optional>
// #include <type_traits>
#include "acmacs-base/float.hh"
// ----------------------------------------------------------------------
namespace acmacs::internal
{
template <typename T> class field_optional_with_default
{
public:
inline field_optional_with_default() = default;
inline field_optional_with_default(const T aDefault) : mDefault{aDefault} {}
inline field_optional_with_default(const field_optional_with_default&) = default;
inline field_optional_with_default& operator=(const field_optional_with_default& aOther)
{
if (aOther.present())
mValue = aOther.mValue;
return *this;
}
inline field_optional_with_default& operator=(const T aValue) { mValue = aValue; return *this; }
[[nodiscard]] inline bool operator==(const field_optional_with_default<T>& f) const { return mValue == f.mValue && mDefault == f.mDefault; }
inline bool is_default() const { return !mValue.has_value() || mValue.value() == mDefault; }
inline bool not_default() const { return mValue.has_value() && mValue.value() != mDefault; }
inline bool present() const { return mValue.has_value(); }
inline operator const T() const { return mValue.value_or(mDefault); }
inline const T operator*() const { return *this; }
inline const std::decay_t<T>* operator->() const
{
if (present())
return &mValue.value();
else
return &mDefault;
}
inline std::decay_t<T>& set() { if (!mValue.has_value()) mValue = mDefault; return mValue.value(); }
private:
std::optional<std::decay_t<T>> mValue;
const T mDefault;
}; // class field_optional_with_default<>
template <> inline bool field_optional_with_default<double>::operator==(const field_optional_with_default<double>& f) const
{
return ((mValue.has_value() && f.mValue.has_value() && float_equal(mValue.value(), f.mValue.value())) || (!mValue.has_value() && !f.mValue.has_value())) && float_equal(mDefault, f.mDefault);
}
template <> inline bool field_optional_with_default<double>::is_default() const
{
return !mValue.has_value() || float_equal(mValue.value(), mDefault);
}
template <> inline bool field_optional_with_default<double>::not_default() const
{
return mValue.has_value() && ! float_equal(mValue.value(), mDefault);
}
} // namespace acmacs::internal
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (C) 2015 *
* *
* This file is part of RC CAR *
* *
* Box 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. *
* *
* Box 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 Box. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/**
* @file ProjectMain.cpp
* @author Adrian
* @date 26/05/2015
* @brief File containing functions for IO External
*
* Here typically goes a more extensive explanation of what the header
* defines. Doxygens tags are words preceeded by either a backslash @\
* or by an at symbol @@.
* @see http://www.stack.nl/~dimitri/doxygen/docblocks.html
* @see http://www.stack.nl/~dimitri/doxygen/commands.html
*/
/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>
#include <PWM.h>
/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>
/*Include C Files*/
#include "TaskFunctions.h"
/**
* @brief Implementation of function that handle the 20ms requests
*
* Implementation of function that handle the 20ms requests
* @return void
* @note Void function with no return.
*/
void task20ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(13, flag);
};
/**
* @brief Implementation of function that handle the 40ms requests
*
* Implementation of function that handle the 40ms requests
* @return void
* @note Void function with no return.
*/
void task40ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(12, flag);
};
/**
* @brief Implementation of function that handle the 60ms requests
*
* Implementation of function that handle the 60ms requests
* @return void
* @note Void function with no return.
*/
void task60ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(11, flag);
};
/**
* @brief Implementation of function that handle the 100ms requests
*
* Implementation of function that handle the 100ms requests
* @return void
* @note Void function with no return.
*/
void task100ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(10, flag);
};
/**
* @brief Implementation of function that handle the 1000ms requests
*
* Implementation of function that handle the 1000ms requests
* @return void
* @note Void function with no return.
*/
void task1000ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(9, flag);
};
void InitPWM(char pin);
/*
* Main code called on reset is in Arduino.h
*/
/**
* @brief Array of tasks and interval of execution
*
* Array of tasks and interval of execution
*/
static TaskType_stType tasks_st[] = {
{ T_INTERVAL_20MS, task20ms },
{ T_INTERVAL_40MS, task40ms },
{ T_INTERVAL_60MS, task60ms },
{ T_INTERVAL_100MS, task100ms },
{ T_INTERVAL_1000MS,task1000ms},
};
/**
* @brief Implementation of the function that returns a pointer to the tasks array
*
* @return A pointer to the array of tasks
* @see tasks_st[];
*/
TaskType_stType *taskGetConfigPtr(void) {
return tasks_st;
}
/**
* @brief Implementation of the function that returns the number of current tasks cheduled to run
*
* @return number of tasks
*/
uint8_t getNrTasks(void) {
return sizeof(tasks_st) / sizeof(*tasks_st);
}
/**
* @brief Implementation of the function that initialize the timer
*
* Implementation of the function that initialize the timer 1 used in task scheduler
* @return void
*
*/
void timer1_init() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
// initialize Timer1
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0;
// initialize counter
TCNT1 = T_TIMER_START;
// enable Timer1 overflow interrupt:
TIMSK1 = (1 << TOIE1);
// set the timer with a prescaller of 256
TCCR1B |= (1 << CS12);
// enable global interrupts:
sei();
}
uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();
static TaskType_stType *taskPtr;
/**
* @brief Implementation of the function that thandle timer overflow ISR
*
* Implementation of the function that thandle timer overflow ISR
* @return void
*
*/
ISR(TIMER1_OVF_vect) {
TCNT1 = T_TIMER_START;
taskTimeCounterFlag_u8 = 1;
taskTimeCounter_u8++;
}
void PWM_Init() {
//PWM setup
DDRD |= (1 << DDD5) | (1 << DDD6 );
// PD6 is now an output
//OCR2A = PWM_DC_Max/(100/PWM_DC);
//OCR2B = PWM_DC_Max/(100/PWM_DC);
//functie apelata ciclic cu request-ul respectiv
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22); //????
// set prescaler to ??? and starts PWM*/
}
void setup()
{
char pin = 12;
taskTimeCounterFlag_u8 = 0;
taskTimeCounter_u8 = 0;
InitPWM(pin); /*Functia de initializare pwm*/
timer1_init();
stui_tick = 0; // System tick
stui_TaskIndex = 0;
taskPtr = taskGetConfigPtr();
}
void loop()
{
// if 20ms have passed
if(taskTimeCounterFlag_u8==1) {
for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {
if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
(*taskPtr[stui_TaskIndex].ptrFunc)();
digitalWrite(taskPtr[stui_TaskIndex].led, HIGH);
} else {
// do nothing
}
}
}
taskTimeCounterFlag_u8 = 0;
}
}
//------------------------Cod pentru Citire IMPUTS---------------
#define CHECK_BIT(var,pos) ((var) & (1<<(pos))) //macro care verifica o pozitie din registru daca e pe 1 logic
//functia pentru citirea unui pin
int getValue(uint8_t pin){
uint8_t Register; // variabila in care stocam valoarea registrului din care citim
//cautam registrul aferent piniului selectat, PINx de unde citim starea pinului
if ((0 <=pin)||(pin <=7))
{
Register = PIND; //Registrii PINx sunt Read Only
}
else if((8 >=pin)||(pin <=13))
{
Register = PINB;
//pin= pin-7; resetam pinul astfel incat sa putem citi din registrul pinB daca acesta nu e setat in memorie in continuare la PIND
}
else if((14 >=pin)||(pin <=19))
{
Register = PINC;
//pin= pin-13;
}
else
Register=NOT_A_PIN;
//cautam pinul din registrul aferent,de aici putem afla starea pinilor daca sunt Input (1), sau Output (0);
if(CHECK_BIT(Register,pin)==1)
{ return true;}
else
{return false;}
}
//-------------Cod pentru Setare Output PWM-----------------
int DOPWM_setValue(char pin, int duty)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
char value;
//formula pentru duty cycle in procente
value = (duty*256)/100;
//Setam duty cycle pentru fiecare pin cu registrii OCR2A, OCR2B
OCR2A = value;
return 0;
}
//functie de initializare pwm
void InitPWM(char pin)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
/* SETAM TIMERUL 2 PENTRU Modul PHASE CORRECTED PWM*/
//setam Timer Counter Control Register A pe None-inverting mode si PWM Phase Corrected Mode
TCCR2A |= (1 << COM2A1) | (0 << COM2A0) | (1 << COM2B1)| (0 << COM2B0);
// set none-inverting mode on bytes (7,6,5,4) for timer 2
TCCR2A |= (0 << WGM21) | (1 << WGM20);
// set PWM Phase Corrected Mode using OCR2A TOP value on bytes (1,0)
// setam Timer Counter Control Register B pe PWM Phase Corrected Mode si cu un prescaler de 64
TCCR2B |= (1 << CS22) | (1 << WGM22);
// set prescaler to 64 and starts PWM and sets PWM Phase Corrected Mode
}
<commit_msg>stui_tick remove<commit_after>/****************************************************************************
* Copyright (C) 2015 *
* *
* This file is part of RC CAR *
* *
* Box 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. *
* *
* Box 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 Box. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/**
* @file ProjectMain.cpp
* @author Adrian
* @date 26/05/2015
* @brief File containing functions for IO External
*
* Here typically goes a more extensive explanation of what the header
* defines. Doxygens tags are words preceeded by either a backslash @\
* or by an at symbol @@.
* @see http://www.stack.nl/~dimitri/doxygen/docblocks.html
* @see http://www.stack.nl/~dimitri/doxygen/commands.html
*/
/*Include Header files*/
#include <ProjectMain.h>
#include <schedulerConfig.h>
#include <PWM.h>
/*FOR PWM*/
#include <avr/io.h>
#include <avr/interrupt.h>
/*Include C Files*/
#include "TaskFunctions.h"
/**
* @brief Implementation of function that handle the 20ms requests
*
* Implementation of function that handle the 20ms requests
* @return void
* @note Void function with no return.
*/
void task20ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(13, flag);
};
/**
* @brief Implementation of function that handle the 40ms requests
*
* Implementation of function that handle the 40ms requests
* @return void
* @note Void function with no return.
*/
void task40ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(12, flag);
};
/**
* @brief Implementation of function that handle the 60ms requests
*
* Implementation of function that handle the 60ms requests
* @return void
* @note Void function with no return.
*/
void task60ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(11, flag);
};
/**
* @brief Implementation of function that handle the 100ms requests
*
* Implementation of function that handle the 100ms requests
* @return void
* @note Void function with no return.
*/
void task100ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(10, flag);
};
/**
* @brief Implementation of function that handle the 1000ms requests
*
* Implementation of function that handle the 1000ms requests
* @return void
* @note Void function with no return.
*/
void task1000ms(void) {
static uint8_t flag = 0;
flag = 1 - flag;
digitalWrite(9, flag);
};
void InitPWM(char pin);
/*
* Main code called on reset is in Arduino.h
*/
/**
* @brief Array of tasks and interval of execution
*
* Array of tasks and interval of execution
*/
static TaskType_stType tasks_st[] = {
{ T_INTERVAL_20MS, task20ms },
{ T_INTERVAL_40MS, task40ms },
{ T_INTERVAL_60MS, task60ms },
{ T_INTERVAL_100MS, task100ms },
{ T_INTERVAL_1000MS,task1000ms},
};
/**
* @brief Implementation of the function that returns a pointer to the tasks array
*
* @return A pointer to the array of tasks
* @see tasks_st[];
*/
TaskType_stType *taskGetConfigPtr(void) {
return tasks_st;
}
/**
* @brief Implementation of the function that returns the number of current tasks cheduled to run
*
* @return number of tasks
*/
uint8_t getNrTasks(void) {
return sizeof(tasks_st) / sizeof(*tasks_st);
}
/**
* @brief Implementation of the function that initialize the timer
*
* Implementation of the function that initialize the timer 1 used in task scheduler
* @return void
*
*/
void timer1_init() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
// initialize Timer1
cli(); // disable global interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0;
// initialize counter
TCNT1 = T_TIMER_START;
// enable Timer1 overflow interrupt:
TIMSK1 = (1 << TOIE1);
// set the timer with a prescaller of 256
TCCR1B |= (1 << CS12);
// enable global interrupts:
sei();
}
uint8_t stui_TaskIndex;
volatile uint8_t taskTimeCounterFlag_u8;
volatile uint8_t taskTimeCounter_u8;
const uint8_t cui_numberOfTasks = getNrTasks();
static TaskType_stType *taskPtr;
/**
* @brief Implementation of the function that thandle timer overflow ISR
*
* Implementation of the function that thandle timer overflow ISR
* @return void
*
*/
ISR(TIMER1_OVF_vect) {
TCNT1 = T_TIMER_START;
taskTimeCounterFlag_u8 = 1;
taskTimeCounter_u8++;
}
void PWM_Init() {
//PWM setup
DDRD |= (1 << DDD5) | (1 << DDD6 );
// PD6 is now an output
//OCR2A = PWM_DC_Max/(100/PWM_DC);
//OCR2B = PWM_DC_Max/(100/PWM_DC);
//functie apelata ciclic cu request-ul respectiv
// set PWM for 50% duty cycle
TCCR2A |= (1 << COM2A1);
// set none-inverting mode
TCCR2A |= (1 << WGM21) | (1 << WGM20);
// set fast PWM Mode
TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22); //????
// set prescaler to ??? and starts PWM*/
}
void setup()
{
char pin = 12;
taskTimeCounterFlag_u8 = 0;
taskTimeCounter_u8 = 0;
InitPWM(pin); /*Functia de initializare pwm*/
timer1_init();
stui_TaskIndex = 0;
taskPtr = taskGetConfigPtr();
}
void loop()
{
// if 20ms have passed
if(taskTimeCounterFlag_u8==1) {
for(stui_TaskIndex=0; stui_TaskIndex < cui_numberOfTasks; stui_TaskIndex++) {
if((taskTimeCounter_u8 % taskPtr[stui_TaskIndex].interval_u16) == 0 ) {
if((taskPtr[stui_TaskIndex].ptrFunc) != NULL) {
(*taskPtr[stui_TaskIndex].ptrFunc)();
digitalWrite(taskPtr[stui_TaskIndex].led, HIGH);
} else {
// do nothing
}
}
}
taskTimeCounterFlag_u8 = 0;
}
}
//------------------------Cod pentru Citire IMPUTS---------------
#define CHECK_BIT(var,pos) ((var) & (1<<(pos))) //macro care verifica o pozitie din registru daca e pe 1 logic
//functia pentru citirea unui pin
int getValue(uint8_t pin){
uint8_t Register; // variabila in care stocam valoarea registrului din care citim
//cautam registrul aferent piniului selectat, PINx de unde citim starea pinului
if ((0 <=pin)||(pin <=7))
{
Register = PIND; //Registrii PINx sunt Read Only
}
else if((8 >=pin)||(pin <=13))
{
Register = PINB;
//pin= pin-7; resetam pinul astfel incat sa putem citi din registrul pinB daca acesta nu e setat in memorie in continuare la PIND
}
else if((14 >=pin)||(pin <=19))
{
Register = PINC;
//pin= pin-13;
}
else
Register=NOT_A_PIN;
//cautam pinul din registrul aferent,de aici putem afla starea pinilor daca sunt Input (1), sau Output (0);
if(CHECK_BIT(Register,pin)==1)
{ return true;}
else
{return false;}
}
//-------------Cod pentru Setare Output PWM-----------------
int DOPWM_setValue(char pin, int duty)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
char value;
//formula pentru duty cycle in procente
value = (duty*256)/100;
//Setam duty cycle pentru fiecare pin cu registrii OCR2A, OCR2B
OCR2A = value;
return 0;
}
//functie de initializare pwm
void InitPWM(char pin)
{
//setam pinii ca si output
if (pin == 3)
{
//setam pinul 3 ca output
DDRD |= (1 << DDD3);
// PD3 is now an output, pin Digital 3
}
else if (pin == 11)
{
DDRB |= (1 <<DDB3); // DDRB l-am gasit in fisierul iom328p.h ???
// PB3 is now an output, pin Digital 11
}
/* SETAM TIMERUL 2 PENTRU Modul PHASE CORRECTED PWM*/
//setam Timer Counter Control Register A pe None-inverting mode si PWM Phase Corrected Mode
TCCR2A |= (1 << COM2A1) | (0 << COM2A0) | (1 << COM2B1)| (0 << COM2B0);
// set none-inverting mode on bytes (7,6,5,4) for timer 2
TCCR2A |= (0 << WGM21) | (1 << WGM20);
// set PWM Phase Corrected Mode using OCR2A TOP value on bytes (1,0)
// setam Timer Counter Control Register B pe PWM Phase Corrected Mode si cu un prescaler de 64
TCCR2B |= (1 << CS22) | (1 << WGM22);
// set prescaler to 64 and starts PWM and sets PWM Phase Corrected Mode
}
<|endoftext|> |
<commit_before>
// WinUI.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "LogCC.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "LogCCDoc.h"
#include "LogMainView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLogCCApp
BEGIN_MESSAGE_MAP(CLogCCApp, CWinAppEx)
ON_COMMAND(ID_APP_ABOUT, &CLogCCApp::OnAppAbout)
// 基于文件的标准文档命令
ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
// 标准打印设置命令
ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup)
END_MESSAGE_MAP()
// CLogCCApp 构造
CLogCCApp::CLogCCApp()
{
m_bHiColorIcons = TRUE;
// 支持重新启动管理器
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// 如果应用程序是利用公共语言运行时支持(/clr)构建的,则:
// 1) 必须有此附加设置,“重新启动管理器”支持才能正常工作。
// 2) 在您的项目中,您必须按照生成顺序向 System.Windows.Forms 添加引用。
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: 将以下应用程序 ID 字符串替换为唯一的 ID 字符串;建议的字符串格式
//为 CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("WinUI.AppID.NoVersion"));
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CLogCCApp 对象
CLogCCApp theApp;
// CLogCCApp 初始化
BOOL CLogCCApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
// 初始化 OLE 库
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
EnableTaskbarInteraction();
// 使用 RichEdit 控件需要 AfxInitRichEdit2()
// AfxInitRichEdit2();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
LoadStdProfileSettings(10); // 加载标准 INI 文件选项(包括 MRU)
InitContextMenuManager();
InitKeyboardManager();
InitTooltipManager();
CMFCToolTipInfo ttParams;
ttParams.m_bVislManagerTheme = TRUE;
theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);
// 注册应用程序的文档模板。文档模板
// 将用作文档、框架窗口和视图之间的连接
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(IDR_LogCCTYPE,
RUNTIME_CLASS(CLogCCDoc),
RUNTIME_CLASS(CChildFrame), // 自定义 MDI 子框架
RUNTIME_CLASS(CLogMainView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// 创建主 MDI 框架窗口
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
{
delete pMainFrame;
return FALSE;
}
m_pMainWnd = pMainFrame;
// 仅当具有后缀时才调用 DragAcceptFiles
// 在 MDI 应用程序中,这应在设置 m_pMainWnd 之后立即发生
// 启用拖/放
m_pMainWnd->DragAcceptFiles();
// 分析标准 shell 命令、DDE、打开文件操作的命令行
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// 启用“DDE 执行”
EnableShellOpen();
RegisterShellFileTypes(TRUE);
// 默认不新建文档
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
// 调度在命令行中指定的命令。如果
// 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// 主窗口已初始化,因此显示它并对其进行更新
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
return TRUE;
}
int CLogCCApp::ExitInstance()
{
//TODO: 处理可能已添加的附加资源
AfxOleTerm(FALSE);
return CWinAppEx::ExitInstance();
}
// CLogCCApp 消息处理程序
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// 用于运行对话框的应用程序命令
void CLogCCApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CLogCCApp 自定义加载/保存方法
void CLogCCApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
void CLogCCApp::LoadCustomState()
{
}
void CLogCCApp::SaveCustomState()
{
}
// CLogCCApp 消息处理程序
<commit_msg>App类删除无用消息映射<commit_after>
// WinUI.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "afxdialogex.h"
#include "LogCC.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "LogCCDoc.h"
#include "LogMainView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CLogCCApp
BEGIN_MESSAGE_MAP(CLogCCApp, CWinAppEx)
ON_COMMAND(ID_APP_ABOUT, &CLogCCApp::OnAppAbout)
//// 基于文件的标准文档命令
ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
END_MESSAGE_MAP()
// CLogCCApp 构造
CLogCCApp::CLogCCApp()
{
m_bHiColorIcons = TRUE;
// 支持重新启动管理器
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS;
#ifdef _MANAGED
// 如果应用程序是利用公共语言运行时支持(/clr)构建的,则:
// 1) 必须有此附加设置,“重新启动管理器”支持才能正常工作。
// 2) 在您的项目中,您必须按照生成顺序向 System.Windows.Forms 添加引用。
System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException);
#endif
// TODO: 将以下应用程序 ID 字符串替换为唯一的 ID 字符串;建议的字符串格式
//为 CompanyName.ProductName.SubProduct.VersionInformation
SetAppID(_T("WinUI.AppID.NoVersion"));
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CLogCCApp 对象
CLogCCApp theApp;
// CLogCCApp 初始化
BOOL CLogCCApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
// 初始化 OLE 库
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
EnableTaskbarInteraction();
// 使用 RichEdit 控件需要 AfxInitRichEdit2()
// AfxInitRichEdit2();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
LoadStdProfileSettings(10); // 加载标准 INI 文件选项(包括 MRU)
InitContextMenuManager();
InitKeyboardManager();
InitTooltipManager();
CMFCToolTipInfo ttParams;
ttParams.m_bVislManagerTheme = TRUE;
theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);
// 注册应用程序的文档模板。文档模板
// 将用作文档、框架窗口和视图之间的连接
CMultiDocTemplate* pDocTemplate;
pDocTemplate = new CMultiDocTemplate(IDR_LogCCTYPE,
RUNTIME_CLASS(CLogCCDoc),
RUNTIME_CLASS(CChildFrame), // 自定义 MDI 子框架
RUNTIME_CLASS(CLogMainView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// 创建主 MDI 框架窗口
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
{
delete pMainFrame;
return FALSE;
}
m_pMainWnd = pMainFrame;
// 仅当具有后缀时才调用 DragAcceptFiles
// 在 MDI 应用程序中,这应在设置 m_pMainWnd 之后立即发生
// 启用拖/放
m_pMainWnd->DragAcceptFiles();
// 分析标准 shell 命令、DDE、打开文件操作的命令行
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// 启用“DDE 执行”
EnableShellOpen();
RegisterShellFileTypes(TRUE);
// 默认不新建文档
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
// 调度在命令行中指定的命令。如果
// 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// 主窗口已初始化,因此显示它并对其进行更新
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
return TRUE;
}
int CLogCCApp::ExitInstance()
{
//TODO: 处理可能已添加的附加资源
AfxOleTerm(FALSE);
return CWinAppEx::ExitInstance();
}
// CLogCCApp 消息处理程序
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// 用于运行对话框的应用程序命令
void CLogCCApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CLogCCApp 自定义加载/保存方法
void CLogCCApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
void CLogCCApp::LoadCustomState()
{
}
void CLogCCApp::SaveCustomState()
{
}
// CLogCCApp 消息处理程序
<|endoftext|> |
<commit_before>#include "EntityInterfaceCallback.hpp"
#include "EntityInterface.hpp"
#include "MainPluginInstance.hpp"
#include "../inanity/script/Any.hpp"
BEGIN_INANITY_OIL
EntityInterfaceCallback::EntityInterfaceCallback(ptr<EntityInterface> entityInterface, ptr<Script::Any> callback)
: entityInterface(entityInterface), callback(callback)
{
entityInterface->OnNewCallback(this);
}
EntityInterfaceCallback::~EntityInterfaceCallback()
{
entityInterface->OnFreeCallback(this);
}
void EntityInterfaceCallback::Fire()
{
MainPluginInstance::instance->AsyncCall(
Handler::Bind<EntityInterfaceCallback>(this, &EntityInterfaceCallback::FireCallback));
}
void EntityInterfaceCallback::FireCallback()
{
ptr<Script::Any> result = entityInterface->GetResult();
if(result)
callback->Call(result);
else
callback->Call();
}
END_INANITY_OIL
<commit_msg>catch exceptions when firing entity interface callback<commit_after>#include "EntityInterfaceCallback.hpp"
#include "EntityInterface.hpp"
#include "MainPluginInstance.hpp"
#include "../inanity/script/Any.hpp"
#include "../inanity/Exception.hpp"
BEGIN_INANITY_OIL
EntityInterfaceCallback::EntityInterfaceCallback(ptr<EntityInterface> entityInterface, ptr<Script::Any> callback)
: entityInterface(entityInterface), callback(callback)
{
entityInterface->OnNewCallback(this);
}
EntityInterfaceCallback::~EntityInterfaceCallback()
{
entityInterface->OnFreeCallback(this);
}
void EntityInterfaceCallback::Fire()
{
MainPluginInstance::instance->AsyncCall(
Handler::Bind<EntityInterfaceCallback>(this, &EntityInterfaceCallback::FireCallback));
}
void EntityInterfaceCallback::FireCallback()
{
BEGIN_TRY();
ptr<Script::Any> result = entityInterface->GetResult();
if(result)
callback->Call(result);
else
callback->Call();
END_TRY("Can't fire entity interface callback");
}
END_INANITY_OIL
<|endoftext|> |
<commit_before>#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <stdexcept>
#include <string>
namespace generic
{
//////////////////////////////////////////////////////////////////////////////
struct cformat_error : ::std::runtime_error
{
cformat_error() : ::std::runtime_error(::std::string("formatting error: ") +
::std::strerror(errno))
{
}
};
typedef cformat_error wcformat_error;
//////////////////////////////////////////////////////////////////////////////
inline ::std::string cformat(char const* format, ...)
{
va_list ap;
va_start(ap, format);
::std::string::size_type const len(::std::vsnprintf(0, 0, format, ap) + 1);
#ifdef _MSC_VER
#include "alloca.h"
char* const s(static_cast<char*>(_malloca(len)));
#else
char s[len];
#endif
va_end(ap);
va_start(ap, format);
if (::std::vsprintf(s, format, ap) < 0)
{
va_end(ap);
throw cformat_error();
}
else
{
va_end(ap);
return {s, len - 1};
}
}
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::wstring wcformat(wchar_t const* format, ...)
{
static_assert(buffer_size > 0, "buffer_size must be greater than 0");
wchar_t s[buffer_size];
va_list ap;
va_start(ap, format);
if (::std::vswprintf(s, buffer_size, format, ap) >= 0)
{
va_end(ap);
return s;
}
else
{
va_end(ap);
throw wcformat_error();
}
}
//////////////////////////////////////////////////////////////////////////////
struct strftime_array_undefined : ::std::runtime_error
{
strftime_array_undefined() :
::std::runtime_error("::std::strftime() or ::std::wcsftime() returned zero")
{
}
};
typedef strftime_array_undefined wcsftime_array_undefined;
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::string cstrftime(char const* format,
struct ::std::tm const* time)
{
static_assert(buffer_size > 0, "buffer_size must be greater than 0");
char s[buffer_size];
if (!::std::strftime(s, buffer_size, format, time))
{
throw strftime_array_undefined();
}
// else do nothing
return s;
}
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::wstring wcstrftime(wchar_t const* format,
struct ::std::tm const* time)
{
//static_assert(buffer_size > 0, "buffer_size must be greater than 0");
wchar_t s[buffer_size];
if (!::std::wcsftime(s, buffer_size, format, time))
{
throw wcsftime_array_undefined();
}
// else do nothing
return s;
}
}
<commit_msg>some fixes<commit_after>#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <stdexcept>
#include <string>
namespace generic
{
//////////////////////////////////////////////////////////////////////////////
struct cformat_error : ::std::runtime_error
{
cformat_error() : ::std::runtime_error(::std::string("formatting error: ") +
::std::strerror(errno))
{
}
};
typedef cformat_error wcformat_error;
//////////////////////////////////////////////////////////////////////////////
inline ::std::string cformat(char const* format, ...)
{
va_list ap;
va_start(ap, format);
auto const len(::std::vsnprintf(0, 0, format, ap) + 1);
#ifdef _MSC_VER
#include "alloca.h"
char* const s(static_cast<char*>(_malloca(len)));
#else
char s[len];
#endif
va_end(ap);
va_start(ap, format);
if (::std::vsnprintf(s, len, format, ap) < 0)
{
va_end(ap);
throw cformat_error();
}
else
{
va_end(ap);
return {s, ::std::string::size_type(len - 1)};
}
}
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::wstring wcformat(wchar_t const* format, ...)
{
static_assert(buffer_size > 0, "buffer_size must be greater than 0");
wchar_t s[buffer_size];
va_list ap;
va_start(ap, format);
if (::std::vswprintf(s, buffer_size, format, ap) >= 0)
{
va_end(ap);
return s;
}
else
{
va_end(ap);
throw wcformat_error();
}
}
//////////////////////////////////////////////////////////////////////////////
struct strftime_array_undefined : ::std::runtime_error
{
strftime_array_undefined() :
::std::runtime_error("::std::strftime() or ::std::wcsftime() returned zero")
{
}
};
typedef strftime_array_undefined wcsftime_array_undefined;
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::string cstrftime(char const* format,
struct ::std::tm const* time)
{
static_assert(buffer_size > 0, "buffer_size must be greater than 0");
char s[buffer_size];
if (!::std::strftime(s, buffer_size, format, time))
{
throw strftime_array_undefined();
}
// else do nothing
return s;
}
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t buffer_size = 128>
inline ::std::wstring wcstrftime(wchar_t const* format,
struct ::std::tm const* time)
{
//static_assert(buffer_size > 0, "buffer_size must be greater than 0");
wchar_t s[buffer_size];
if (!::std::wcsftime(s, buffer_size, format, time))
{
throw wcsftime_array_undefined();
}
// else do nothing
return s;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <Utility/MemoryManager/Include/MemorySpecification.hpp>
#include <cstdint>
namespace Utility
{
namespace MemoryManager
{
class MemoryAllocator
{
public:
/**
TODORT docs
*/
MemoryAllocator();
/**
TODORT docs
*/
virtual ~MemoryAllocator();
/**
TODORT docs
*/
virtual void Clear() = 0;
/**
Gets the some specifications about this memorystack.
*/
MemorySpecification GetMemorySpecification();
protected:
void Initialize(const size_t& p_memorySize, const uint8_t& p_alignment);
void AllocateFirstTime();
uint8_t ComputeAdjustment(void* p_adress, const uint8_t& p_alignment);
bool AssertAdresstInside(void* p_adressToAssert) const;
void* GetAdressStartRaw() const { return m_memoryStartRaw; }
void* GetAdressEndRaw() const { return m_memoryEndRaw; }
void* GetAdressStartAligned() const { return m_memoryStartRaw; }
// Variables
size_t m_occupiedMemory;
size_t m_totalMemory;
uint8_t m_alignment;
uint8_t m_adjustment;
private:
void* m_memoryStartRaw;
void* m_memoryEndRaw;
void* m_memoryStartAligned;
};
}
}<commit_msg>Fixed Clear bug in memory pool<commit_after>#pragma once
#include <Utility/MemoryManager/Include/MemorySpecification.hpp>
#include <cstdint>
namespace Utility
{
namespace MemoryManager
{
class MemoryAllocator
{
public:
/**
TODORT docs
*/
MemoryAllocator();
/**
TODORT docs
*/
virtual ~MemoryAllocator();
/**
TODORT docs
*/
virtual void Clear() = 0;
/**
Gets the some specifications about this memorystack.
*/
MemorySpecification GetMemorySpecification();
protected:
void Initialize(const size_t& p_memorySize, const uint8_t& p_alignment);
void AllocateFirstTime();
uint8_t ComputeAdjustment(void* p_adress, const uint8_t& p_alignment);
bool AssertAdresstInside(void* p_adressToAssert) const;
void* GetAdressStartRaw() const { return m_memoryStartRaw; }
void* GetAdressEndRaw() const { return m_memoryEndRaw; }
void* GetAdressStartAligned() const { return m_memoryStartAligned; }
// Variables
size_t m_occupiedMemory;
size_t m_totalMemory;
uint8_t m_alignment;
uint8_t m_adjustment;
private:
void* m_memoryStartRaw;
void* m_memoryEndRaw;
void* m_memoryStartAligned;
};
}
}<|endoftext|> |
<commit_before>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkImageFunction.h>
#include <irtkLinearInterpolateImageFunction.h>
irtkLinearInterpolateImageFunction::irtkLinearInterpolateImageFunction()
{}
irtkLinearInterpolateImageFunction::~irtkLinearInterpolateImageFunction(void)
{}
const char *irtkLinearInterpolateImageFunction::NameOfClass()
{
return "irtkLinearInterpolateImageFunction";
}
void irtkLinearInterpolateImageFunction::Initialize()
{
/// Initialize baseclass
this->irtkImageFunction::Initialize();
// Compute size of image
this->_x = this->_input->GetX();
this->_y = this->_input->GetY();
this->_z = this->_input->GetZ();
// Compute domain on which the linear interpolation is defined
this->_x1 = 0;
this->_y1 = 0;
this->_z1 = 0;
this->_x2 = this->_input->GetX() - 1;
this->_y2 = this->_input->GetY() - 1;
this->_z2 = this->_input->GetZ() - 1;
// Calculate offsets for fast pixel access
this->_offset1 = 0;
this->_offset2 = 1;
this->_offset3 = this->_input->GetX();
this->_offset4 = this->_input->GetX()+1;
this->_offset5 = this->_input->GetX()*this->_input->GetY();
this->_offset6 = this->_input->GetX()*this->_input->GetY()+1;
this->_offset7 = this->_input->GetX()*this->_input->GetY()+this->_input->GetX();
this->_offset8 = this->_input->GetX()*this->_input->GetY()+this->_input->GetX()+1;
}
double irtkLinearInterpolateImageFunction::EvaluateInside(double x, double y, double z, double time)
{
int i, j, k;
double t1, t2, u1, u2, v1, v2;
// Calculated integer coordinates
i = int(x);
j = int(y);
k = int(z);
// Calculated fractional coordinates
t1 = x - i;
u1 = y - j;
v1 = z - k;
t2 = 1 - t1;
u2 = 1 - u1;
v2 = 1 - v1;
// Get pointer to data
switch (this->_input->GetScalarType()) {
case IRTK_VOXEL_UNSIGNED_SHORT: {
unsigned short *ptr = (unsigned short *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_SHORT: {
short *ptr = (short *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_FLOAT: {
float *ptr = (float *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_DOUBLE: {
double *ptr = (double *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
default:
cerr << "irtkLinearInterpolateImageFunction::EvaluateInside: Unknown scalar type" << endl;
exit(1);
}
}
double irtkLinearInterpolateImageFunction::Evaluate(double x, double y, double z, double time)
{
double val;
int i, j, k, l, m, n, t;
i = (int)floor(x);
j = (int)floor(y);
k = (int)floor(z);
t = round(time);
val = 0;
for (l = i; l <= i+1; l++) {
if ((l >= 0) && (l < this->_x)) {
for (m = j; m <= j+1; m++) {
if ((m >= 0) && (m < this->_y)) {
for (n = k; n <= k+1; n++) {
if ((n >= 0) && (n < this->_z)) {
val += (1 - fabs(l - x))*(1 - fabs(m - y))*(1 - fabs(n - z))*this->_input->GetAsDouble(l, m, n, t);
}
}
}
}
}
}
switch (this->_input->GetScalarType()) {
case IRTK_VOXEL_UNSIGNED_SHORT: {
val = round(val);
break;
}
case IRTK_VOXEL_SHORT: {
val = round(val);
break;
}
default: break;
}
return val;
}<commit_msg>updated linear interpolation to better handle boundaries<commit_after>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkImageFunction.h>
#include <irtkLinearInterpolateImageFunction.h>
irtkLinearInterpolateImageFunction::irtkLinearInterpolateImageFunction()
{}
irtkLinearInterpolateImageFunction::~irtkLinearInterpolateImageFunction(void)
{}
const char *irtkLinearInterpolateImageFunction::NameOfClass()
{
return "irtkLinearInterpolateImageFunction";
}
void irtkLinearInterpolateImageFunction::Initialize()
{
/// Initialize baseclass
this->irtkImageFunction::Initialize();
// Compute size of image
this->_x = this->_input->GetX();
this->_y = this->_input->GetY();
this->_z = this->_input->GetZ();
// Compute domain on which the linear interpolation is defined
this->_x1 = 0;
this->_y1 = 0;
this->_z1 = 0;
this->_x2 = this->_input->GetX() - 1;
this->_y2 = this->_input->GetY() - 1;
this->_z2 = this->_input->GetZ() - 1;
// Calculate offsets for fast pixel access
this->_offset1 = 0;
this->_offset2 = 1;
this->_offset3 = this->_input->GetX();
this->_offset4 = this->_input->GetX()+1;
this->_offset5 = this->_input->GetX()*this->_input->GetY();
this->_offset6 = this->_input->GetX()*this->_input->GetY()+1;
this->_offset7 = this->_input->GetX()*this->_input->GetY()+this->_input->GetX();
this->_offset8 = this->_input->GetX()*this->_input->GetY()+this->_input->GetX()+1;
}
double irtkLinearInterpolateImageFunction::EvaluateInside(double x, double y, double z, double time)
{
int i, j, k;
double t1, t2, u1, u2, v1, v2;
// Calculated integer coordinates
i = int(x);
j = int(y);
k = int(z);
// Calculated fractional coordinates
t1 = x - i;
u1 = y - j;
v1 = z - k;
t2 = 1 - t1;
u2 = 1 - u1;
v2 = 1 - v1;
// Get pointer to data
switch (this->_input->GetScalarType()) {
case IRTK_VOXEL_UNSIGNED_SHORT: {
unsigned short *ptr = (unsigned short *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_SHORT: {
short *ptr = (short *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_FLOAT: {
float *ptr = (float *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
case IRTK_VOXEL_DOUBLE: {
double *ptr = (double *)this->_input->GetScalarPointer(i, j, k, round(time));
// Linear interpolation
return (t1 * (u2 * (v2 * ptr[this->_offset2] + v1 * ptr[this->_offset6]) +
u1 * (v2 * ptr[this->_offset4] + v1 * ptr[this->_offset8])) +
t2 * (u2 * (v2 * ptr[this->_offset1] + v1 * ptr[this->_offset5]) +
u1 * (v2 * ptr[this->_offset3] + v1 * ptr[this->_offset7])));
break;
}
default:
cerr << "irtkLinearInterpolateImageFunction::EvaluateInside: Unknown scalar type" << endl;
exit(1);
}
}
double irtkLinearInterpolateImageFunction::Evaluate(double x, double y, double z, double time)
{
double val;
double weight;
int i, j, k, l, m, n, t;
i = (int)floor(x);
j = (int)floor(y);
k = (int)floor(z);
t = round(time);
val = 0;
weight = 0;
for (l = i; l <= i+1; l++) {
if ((l >= 0) && (l < this->_x)) {
for (m = j; m <= j+1; m++) {
if ((m >= 0) && (m < this->_y)) {
for (n = k; n <= k+1; n++) {
if ((n >= 0) && (n < this->_z)) {
val += (1 - fabs(l - x))*(1 - fabs(m - y))*(1 - fabs(n - z))*this->_input->GetAsDouble(l, m, n, t);
weight += (1 - fabs(l - x))*(1 - fabs(m - y))*(1 - fabs(n - z));
}
}
}
}
}
}
if (weight > 0)
val /= weight;
switch (this->_input->GetScalarType()) {
case IRTK_VOXEL_UNSIGNED_SHORT: {
val = round(val);
break;
}
case IRTK_VOXEL_SHORT: {
val = round(val);
break;
}
default: break;
}
return val;
}
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <mapnik/transform_path_adapter.hpp>
#include <mapnik/geometry/correct.hpp>
#include <mapnik/vertex_adapters.hpp>
#include <mapnik/transform_path_adapter.hpp>
#include <mapnik/view_transform.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
TEST_CASE("transform_path_adapter") {
#ifdef MAPNIK_USE_PROJ4
SECTION("polygon closing - epsg 2330") {
mapnik::geometry::polygon<double> g;
g.emplace_back();
auto & exterior = g.back();
exterior.emplace_back(88.1844308217992, 69.3553916041731);
exterior.emplace_back(88.1846166524913, 69.3552821191223);
exterior.emplace_back(88.1845090893871, 69.3553454342903);
exterior.emplace_back(88.1844308217992, 69.3553916041731);
using va_type = mapnik::geometry::polygon_vertex_adapter<double>;
using path_type = mapnik::transform_path_adapter<mapnik::view_transform, va_type>;
va_type va(g);
mapnik::box2d<double> extent(16310607, 7704513, 16310621, 7704527);
mapnik::view_transform tr(512, 512, extent);
mapnik::projection proj1("+init=epsg:2330");
mapnik::projection proj2("+init=epsg:4326");
mapnik::proj_transform prj_trans(proj1, proj2);
path_type path(tr, va, prj_trans);
double x,y;
unsigned cmd;
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_MOVETO );
CHECK( x == Approx(110.4328050613) );
CHECK( y == Approx(20.2204537392) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(342.1220560074) );
CHECK( y == Approx(486.732225963) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(207.9962329183) );
CHECK( y == Approx(216.9376912798) );
// close
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_CLOSE );
CHECK( x == 0 );
CHECK( y == 0 );
// end
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_END );
CHECK( x == 0 );
CHECK( y == 0 );
}
SECTION("polygon closing - epsg 32633") {
mapnik::geometry::polygon<double> g;
g.emplace_back();
auto & exterior = g.back();
exterior.emplace_back(13, 13);
exterior.emplace_back(14, 13);
exterior.emplace_back(14, 14);
exterior.emplace_back(14, 14);
using va_type = mapnik::geometry::polygon_vertex_adapter<double>;
using path_type = mapnik::transform_path_adapter<mapnik::view_transform, va_type>;
va_type va(g);
mapnik::box2d<double> extent(166022, 0, 833978, 9329005);
mapnik::view_transform tr(512, 512, extent);
mapnik::projection proj1("+init=epsg:32633");
mapnik::projection proj2("+init=epsg:4326");
mapnik::proj_transform prj_trans(proj1, proj2);
path_type path(tr, va, prj_trans);
double x,y;
unsigned cmd;
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_MOVETO );
CHECK( x == Approx(89.7250280748) );
CHECK( y == Approx(433.0795069885) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(172.873973465) );
CHECK( y == Approx(433.1145779929) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(173.2194366775) );
CHECK( y == Approx(427.0442504759) );
// close
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_CLOSE );
CHECK( x == 0 );
CHECK( y == 0 );
// end
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_END );
CHECK( x == 0 );
CHECK( y == 0 );
}
#endif MAPNIK_USE_PROJ4
}
<commit_msg>remove extract token<commit_after>#include "catch.hpp"
#include <mapnik/transform_path_adapter.hpp>
#include <mapnik/geometry/correct.hpp>
#include <mapnik/vertex_adapters.hpp>
#include <mapnik/transform_path_adapter.hpp>
#include <mapnik/view_transform.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
TEST_CASE("transform_path_adapter") {
#ifdef MAPNIK_USE_PROJ4
SECTION("polygon closing - epsg 2330") {
mapnik::geometry::polygon<double> g;
g.emplace_back();
auto & exterior = g.back();
exterior.emplace_back(88.1844308217992, 69.3553916041731);
exterior.emplace_back(88.1846166524913, 69.3552821191223);
exterior.emplace_back(88.1845090893871, 69.3553454342903);
exterior.emplace_back(88.1844308217992, 69.3553916041731);
using va_type = mapnik::geometry::polygon_vertex_adapter<double>;
using path_type = mapnik::transform_path_adapter<mapnik::view_transform, va_type>;
va_type va(g);
mapnik::box2d<double> extent(16310607, 7704513, 16310621, 7704527);
mapnik::view_transform tr(512, 512, extent);
mapnik::projection proj1("+init=epsg:2330");
mapnik::projection proj2("+init=epsg:4326");
mapnik::proj_transform prj_trans(proj1, proj2);
path_type path(tr, va, prj_trans);
double x,y;
unsigned cmd;
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_MOVETO );
CHECK( x == Approx(110.4328050613) );
CHECK( y == Approx(20.2204537392) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(342.1220560074) );
CHECK( y == Approx(486.732225963) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(207.9962329183) );
CHECK( y == Approx(216.9376912798) );
// close
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_CLOSE );
CHECK( x == 0 );
CHECK( y == 0 );
// end
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_END );
CHECK( x == 0 );
CHECK( y == 0 );
}
SECTION("polygon closing - epsg 32633") {
mapnik::geometry::polygon<double> g;
g.emplace_back();
auto & exterior = g.back();
exterior.emplace_back(13, 13);
exterior.emplace_back(14, 13);
exterior.emplace_back(14, 14);
exterior.emplace_back(14, 14);
using va_type = mapnik::geometry::polygon_vertex_adapter<double>;
using path_type = mapnik::transform_path_adapter<mapnik::view_transform, va_type>;
va_type va(g);
mapnik::box2d<double> extent(166022, 0, 833978, 9329005);
mapnik::view_transform tr(512, 512, extent);
mapnik::projection proj1("+init=epsg:32633");
mapnik::projection proj2("+init=epsg:4326");
mapnik::proj_transform prj_trans(proj1, proj2);
path_type path(tr, va, prj_trans);
double x,y;
unsigned cmd;
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_MOVETO );
CHECK( x == Approx(89.7250280748) );
CHECK( y == Approx(433.0795069885) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(172.873973465) );
CHECK( y == Approx(433.1145779929) );
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_LINETO );
CHECK( x == Approx(173.2194366775) );
CHECK( y == Approx(427.0442504759) );
// close
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_CLOSE );
CHECK( x == 0 );
CHECK( y == 0 );
// end
cmd = path.vertex(&x, &y);
CHECK( cmd == mapnik::SEG_END );
CHECK( x == 0 );
CHECK( y == 0 );
}
#endif //MAPNIK_USE_PROJ4
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwBitArray.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-10-11 08:47:55 $
*
* 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 <string.h>
#include "SwBitArray.hxx"
using namespace std;
SwBitArray::SwBitArray(sal_uInt32 _nSize)
{
nSize = _nSize;
mArray = new sal_uInt32[(nSize - 1)/ mGroupSize + 1];
Reset();
}
SwBitArray::SwBitArray(const SwBitArray & rArray)
: nSize(rArray.nSize)
{
mArray = new sal_uInt32[calcSize()];
memcpy(mArray, rArray.mArray, calcSize());
}
SwBitArray::~SwBitArray()
{
delete [] mArray;
}
BOOL SwBitArray::IsValid(sal_uInt32 n) const
{
return n < nSize;
}
void SwBitArray::Set(sal_uInt32 n, BOOL nValue)
{
sal_uInt32 * pGroup = NULL;
if (IsValid(n))
{
pGroup = GetGroup(n);
if (nValue)
*pGroup |= 1 << (n % mGroupSize);
else
*pGroup &= ~(1 << (n % mGroupSize));
}
}
void SwBitArray::Reset()
{
memset(mArray, 0, mGroupSize * (nSize / mGroupSize + 1));
}
BOOL SwBitArray::Get(sal_uInt32 n) const
{
BOOL bResult = FALSE;
sal_uInt32 * pGroup = NULL;
if (IsValid(n))
{
pGroup = GetGroup(n);
bResult = 0 != (*pGroup & (1 << (n % mGroupSize)));
}
return bResult;
}
SwBitArray & SwBitArray::operator = (const SwBitArray & rArray)
{
if (Size() == rArray.Size())
{
memcpy(mArray, rArray.mArray, calcSize());
}
return *this;
}
SwBitArray operator & (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] &= rB.mArray[i];
}
return aResult;
}
SwBitArray operator | (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] |= rB.mArray[i];
}
return aResult;
}
SwBitArray operator ^ (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] ^= rB.mArray[i];
}
return aResult;
}
SwBitArray operator ~ (const SwBitArray & rA)
{
SwBitArray aResult(rA);
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] = ~ rA.mArray[i];
return aResult;
}
#if OSL_DEBUG_LEVEL > 1
ostream & operator << (ostream & o, const SwBitArray & rBitArray)
{
char buffer[256];
sprintf(buffer, "%p", &rBitArray);
o << "[ " << buffer << " ";
for (sal_uInt32 n = 0; n < rBitArray.Size(); n++)
{
if (rBitArray.Get(n))
o << "1";
else
o << "0";
}
o << " ]";
return o;
}
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.694); FILE MERGED 2008/03/31 16:53:42 rt 1.6.694.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: SwBitArray.cxx,v $
* $Revision: 1.7 $
*
* 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 <string.h>
#include "SwBitArray.hxx"
using namespace std;
SwBitArray::SwBitArray(sal_uInt32 _nSize)
{
nSize = _nSize;
mArray = new sal_uInt32[(nSize - 1)/ mGroupSize + 1];
Reset();
}
SwBitArray::SwBitArray(const SwBitArray & rArray)
: nSize(rArray.nSize)
{
mArray = new sal_uInt32[calcSize()];
memcpy(mArray, rArray.mArray, calcSize());
}
SwBitArray::~SwBitArray()
{
delete [] mArray;
}
BOOL SwBitArray::IsValid(sal_uInt32 n) const
{
return n < nSize;
}
void SwBitArray::Set(sal_uInt32 n, BOOL nValue)
{
sal_uInt32 * pGroup = NULL;
if (IsValid(n))
{
pGroup = GetGroup(n);
if (nValue)
*pGroup |= 1 << (n % mGroupSize);
else
*pGroup &= ~(1 << (n % mGroupSize));
}
}
void SwBitArray::Reset()
{
memset(mArray, 0, mGroupSize * (nSize / mGroupSize + 1));
}
BOOL SwBitArray::Get(sal_uInt32 n) const
{
BOOL bResult = FALSE;
sal_uInt32 * pGroup = NULL;
if (IsValid(n))
{
pGroup = GetGroup(n);
bResult = 0 != (*pGroup & (1 << (n % mGroupSize)));
}
return bResult;
}
SwBitArray & SwBitArray::operator = (const SwBitArray & rArray)
{
if (Size() == rArray.Size())
{
memcpy(mArray, rArray.mArray, calcSize());
}
return *this;
}
SwBitArray operator & (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] &= rB.mArray[i];
}
return aResult;
}
SwBitArray operator | (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] |= rB.mArray[i];
}
return aResult;
}
SwBitArray operator ^ (const SwBitArray & rA, const SwBitArray & rB)
{
SwBitArray aResult(rA);
if (rA.Size() == rB.Size())
{
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] ^= rB.mArray[i];
}
return aResult;
}
SwBitArray operator ~ (const SwBitArray & rA)
{
SwBitArray aResult(rA);
for (size_t i = 0; i < rA.calcSize(); i++)
aResult.mArray[i] = ~ rA.mArray[i];
return aResult;
}
#if OSL_DEBUG_LEVEL > 1
ostream & operator << (ostream & o, const SwBitArray & rBitArray)
{
char buffer[256];
sprintf(buffer, "%p", &rBitArray);
o << "[ " << buffer << " ";
for (sal_uInt32 n = 0; n < rBitArray.Size(); n++)
{
if (rBitArray.Get(n))
o << "1";
else
o << "0";
}
o << " ]";
return o;
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright 2011 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "state_assignment_statement.hpp"
#include <cassert>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expression.hpp>
#include <engine/state.hpp>
#include <engine/state_assignment.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
std::string identifier,
std::unique_ptr< Expression > expression )
:m_identifier( std::move(identifier) )
,m_expression( std::move(expression) )
{
assert( !m_identifier.empty() &&
"Trying to create a StateAssignmentStatement with an empty state "
"name" );
assert( m_expression &&
"Trying to create a StateAssignmentStatement with a null "
"expression" );
}
StateAssignmentStatement::~StateAssignmentStatement()
{
}
void StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
// create a scope for the enumerants
sema.EnterScope();
// Try and get the state to which we are assigning
m_state = sema.GetState( m_identifier );
if( !m_state )
sema.Error( "Undeclared state: " + m_identifier );
else
sema.LoadStateEnumerants( *m_state );
m_expression->ResolveIdentifiers( sema );
// only create the cast if we have a type to cast it to
if( m_state )
m_expression = CastExpression::Create( m_state->GetType(),
std::move(m_expression) );
m_expression->PerformSema( sema );
m_expression->FoldConstants( m_expression );
sema.LeaveScope();
}
std::unique_ptr<StateAssignmentBase>
StateAssignmentStatement::GenerateStateAssignment(
CodeGenerator& code_gen ) const
{
Type t = m_state->GetType();
assert( m_expression->GetReturnType() == t &&
"Trying to create a state assignment with mismatched types" );
LiteralExpression* l = Expression::GetLiteral( m_expression );
//TODO remove this, just for testing
l = nullptr;
// If this is just a constant return a ConstStateAssignment
if( l )
{
GenericValue v( l->GetValue() );
switch( t )
{
case Type::BOOL:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_bool>(
static_cast<const State<jl_bool>&>(*m_state),
v.GetBool() ) );
case Type::I8:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i8>(
static_cast<const State<jl_i8>&>(*m_state),
v.GetI8() ) );
case Type::I16:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i16>(
static_cast<const State<jl_i16>&>(*m_state),
v.GetI16() ) );
case Type::I32:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i32>(
static_cast<const State<jl_i32>&>(*m_state),
v.GetI32() ) );
case Type::I64:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i64>(
static_cast<const State<jl_i64>&>(*m_state),
v.GetI64() ) );
case Type::U8:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u8>(
static_cast<const State<jl_u8>&>(*m_state),
v.GetU8() ) );
case Type::U16:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u16>(
static_cast<const State<jl_u16>&>(*m_state),
v.GetU16() ) );
case Type::U32:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u32>(
static_cast<const State<jl_u32>&>(*m_state),
v.GetU32() ) );
case Type::U64:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u64>(
static_cast<const State<jl_u64>&>(*m_state),
v.GetU64() ) );
case Type::FLOAT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float>(
static_cast<const State<jl_float>&>(*m_state),
v.GetFloat() ) );
case Type::DOUBLE:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_double>(
static_cast<const State<jl_double>&>(*m_state),
v.GetDouble() ) );
case Type::STRING:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_string>(
static_cast<const State<jl_string>&>(*m_state),
v.GetString() ) );
default:
assert( false &&
"Trying to create a ConstStateAssignment with an unhandled type" );
return nullptr;
}
}
return code_gen.GenerateStateAssignment( *m_state, *m_expression );
}
void StateAssignmentStatement::Print( int depth ) const
{
for( int i = 0; i < depth * 4; ++i )
std::cout << " ";
std::cout << "State Assignment to " << m_identifier << "\n";
m_expression->Print( depth + 1 );
}
bool StateAssignmentStatement::Parse(
Parser& parser,
std::unique_ptr<StateAssignmentStatement>& token )
{
// Read the state identifier
std::string identifier;
if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
return false;
// The assignment operator
if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
return false;
// And the expression
std::unique_ptr< Expression > expression;
if( !parser.Expect< Expression >( expression ) )
return false;
// Closing semicolon
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
return false;
token.reset( new StateAssignmentStatement( std::move(identifier),
std::move(expression) ) );
return true;
}
} // namespace Compiler
} // namespace JoeLang
<commit_msg>[-] removed testing code<commit_after>/*
Copyright 2011 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "state_assignment_statement.hpp"
#include <cassert>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expression.hpp>
#include <engine/state.hpp>
#include <engine/state_assignment.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
std::string identifier,
std::unique_ptr< Expression > expression )
:m_identifier( std::move(identifier) )
,m_expression( std::move(expression) )
{
assert( !m_identifier.empty() &&
"Trying to create a StateAssignmentStatement with an empty state "
"name" );
assert( m_expression &&
"Trying to create a StateAssignmentStatement with a null "
"expression" );
}
StateAssignmentStatement::~StateAssignmentStatement()
{
}
void StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
// create a scope for the enumerants
sema.EnterScope();
// Try and get the state to which we are assigning
m_state = sema.GetState( m_identifier );
if( !m_state )
sema.Error( "Undeclared state: " + m_identifier );
else
sema.LoadStateEnumerants( *m_state );
m_expression->ResolveIdentifiers( sema );
// only create the cast if we have a type to cast it to
if( m_state )
m_expression = CastExpression::Create( m_state->GetType(),
std::move(m_expression) );
m_expression->PerformSema( sema );
m_expression->FoldConstants( m_expression );
sema.LeaveScope();
}
std::unique_ptr<StateAssignmentBase>
StateAssignmentStatement::GenerateStateAssignment(
CodeGenerator& code_gen ) const
{
Type t = m_state->GetType();
assert( m_expression->GetReturnType() == t &&
"Trying to create a state assignment with mismatched types" );
LiteralExpression* l = Expression::GetLiteral( m_expression );
// If this is just a constant return a ConstStateAssignment
if( l )
{
GenericValue v( l->GetValue() );
switch( t )
{
case Type::BOOL:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_bool>(
static_cast<const State<jl_bool>&>(*m_state),
v.GetBool() ) );
case Type::I8:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i8>(
static_cast<const State<jl_i8>&>(*m_state),
v.GetI8() ) );
case Type::I16:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i16>(
static_cast<const State<jl_i16>&>(*m_state),
v.GetI16() ) );
case Type::I32:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i32>(
static_cast<const State<jl_i32>&>(*m_state),
v.GetI32() ) );
case Type::I64:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_i64>(
static_cast<const State<jl_i64>&>(*m_state),
v.GetI64() ) );
case Type::U8:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u8>(
static_cast<const State<jl_u8>&>(*m_state),
v.GetU8() ) );
case Type::U16:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u16>(
static_cast<const State<jl_u16>&>(*m_state),
v.GetU16() ) );
case Type::U32:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u32>(
static_cast<const State<jl_u32>&>(*m_state),
v.GetU32() ) );
case Type::U64:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_u64>(
static_cast<const State<jl_u64>&>(*m_state),
v.GetU64() ) );
case Type::FLOAT:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_float>(
static_cast<const State<jl_float>&>(*m_state),
v.GetFloat() ) );
case Type::DOUBLE:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_double>(
static_cast<const State<jl_double>&>(*m_state),
v.GetDouble() ) );
case Type::STRING:
return std::unique_ptr<StateAssignmentBase>(
new ConstStateAssignment<jl_string>(
static_cast<const State<jl_string>&>(*m_state),
v.GetString() ) );
default:
assert( false &&
"Trying to create a ConstStateAssignment with an unhandled type" );
return nullptr;
}
}
return code_gen.GenerateStateAssignment( *m_state, *m_expression );
}
void StateAssignmentStatement::Print( int depth ) const
{
for( int i = 0; i < depth * 4; ++i )
std::cout << " ";
std::cout << "State Assignment to " << m_identifier << "\n";
m_expression->Print( depth + 1 );
}
bool StateAssignmentStatement::Parse(
Parser& parser,
std::unique_ptr<StateAssignmentStatement>& token )
{
// Read the state identifier
std::string identifier;
if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
return false;
// The assignment operator
if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
return false;
// And the expression
std::unique_ptr< Expression > expression;
if( !parser.Expect< Expression >( expression ) )
return false;
// Closing semicolon
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
return false;
token.reset( new StateAssignmentStatement( std::move(identifier),
std::move(expression) ) );
return true;
}
} // namespace Compiler
} // namespace JoeLang
<|endoftext|> |
<commit_before>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Good random numbers from Boost
* Provides a common class for all random number requirements to test Bayes++
*/
#include <boost/version.hpp>
#include <boost/random.hpp>
namespace Bayesian_filter_test
{
#if (BOOST_VERSION >= 103100)
/*
* Random numbers from Boost 1_31_0
*/
namespace
{
// ISSUE variate_generator cannot be used without Partial template specialistion
template<class Engine, class Distribution>
class simple_generator
{
public:
typedef typename Distribution::result_type result_type;
simple_generator(Engine& e, Distribution& d)
: _eng(e), _dist(d)
{}
result_type operator()()
{ return _dist(_eng); }
private:
Engine& _eng;
Distribution& _dist;
};
}//namespace
class Boost_random
{
public:
typedef Bayesian_filter_matrix::Float Float;
typedef boost::uniform_01<boost::mt19937, Float> UGen;
Boost_random() : gen01(boost::mt19937()), dist_normal()
{}
Bayesian_filter_matrix::Float normal(const Float mean, const Float sigma)
{
boost::normal_distribution<Float> dist(mean, sigma);
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist);
return gen();
}
void normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<Float> dist(mean, sigma);
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist);
std::generate (v.begin(), v.end(), gen);
}
void normal(Bayesian_filter_matrix::DenseVec& v)
{
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist_normal);
std::generate (v.begin(), v.end(), gen);
}
void uniform_01(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen01);
}
void seed()
{
gen01.base().seed();
}
private:
UGen gen01;
boost::normal_distribution<Float> dist_normal;
};
#else
/*
* Random numbers from Boost 1_30_0 or earlier
*/
class Boost_random
{
public:
typedef Bayesian_filter_matrix::Float Float;
Boost_random() : gen_normal(rng), gen_uniform(rng)
{}
double normal(const double mean, const double sigma)
{
boost::normal_distribution<boost::mt19937,Float> gen(rng, mean, sigma);
return gen();
}
void normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<boost::mt19937,Float> gen(rng, mean, sigma);
std::generate (v.begin(), v.end(), gen);
}
void normal(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen_normal);
}
void uniform_01(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen_uniform);
}
void seed()
{
rng.seed();
}
private:
boost::mt19937 rng;
boost::normal_distribution<boost::mt19937,Float> gen_normal;
boost::uniform_01<boost::mt19937,Float> gen_uniform;
};
#endif
}//namespace
<commit_msg>Gappy support<commit_after>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Good random numbers from Boost
* Provides a common class for all random number requirements to test Bayes++
*/
#include <boost/version.hpp>
#include <boost/random.hpp>
namespace Bayesian_filter_test
{
#if (BOOST_VERSION >= 103100)
/*
* Random numbers from Boost 1_31_0
*/
namespace
{
// ISSUE variate_generator cannot be used without Partial template specialistion
template<class Engine, class Distribution>
class simple_generator
{
public:
typedef typename Distribution::result_type result_type;
simple_generator(Engine& e, Distribution& d)
: _eng(e), _dist(d)
{}
result_type operator()()
{ return _dist(_eng); }
private:
Engine& _eng;
Distribution& _dist;
};
}//namespace
class Boost_random
{
public:
typedef Bayesian_filter_matrix::Float Float;
typedef boost::uniform_01<boost::mt19937, Float> UGen;
Boost_random() : gen01(boost::mt19937()), dist_normal()
{}
Bayesian_filter_matrix::Float normal(const Float mean, const Float sigma)
{
boost::normal_distribution<Float> dist(mean, sigma);
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist);
return gen();
}
void normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<Float> dist(mean, sigma);
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist);
std::generate (v.begin(), v.end(), gen);
}
void normal(Bayesian_filter_matrix::DenseVec& v)
{
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist_normal);
std::generate (v.begin(), v.end(), gen);
}
void uniform_01(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen01);
}
#ifdef BAYES_FILTER_GAPPY
void normal(Bayesian_filter_matrix::Vec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<Float> dist(mean, sigma);
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist);
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen();
}
void normal(Bayesian_filter_matrix::Vec& v)
{
simple_generator<UGen, boost::normal_distribution<Float> > gen(gen01, dist_normal);
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen();
}
void uniform_01(Bayesian_filter_matrix::Vec& v)
{
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen01();
}
#endif
void seed()
{
gen01.base().seed();
}
private:
UGen gen01;
boost::normal_distribution<Float> dist_normal;
};
#else
/*
* Random numbers from Boost 1_30_0 or earlier
*/
class Boost_random
{
public:
typedef Bayesian_filter_matrix::Float Float;
Boost_random() : gen_normal(rng), gen_uniform(rng)
{}
double normal(const double mean, const double sigma)
{
boost::normal_distribution<boost::mt19937,Float> gen(rng, mean, sigma);
return gen();
}
void normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<boost::mt19937,Float> gen(rng, mean, sigma);
std::generate (v.begin(), v.end(), gen);
}
void normal(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen_normal);
}
void uniform_01(Bayesian_filter_matrix::DenseVec& v)
{
std::generate (v.begin(), v.end(), gen_uniform);
}
#ifdef BAYES_FILTER_GAPPY
void normal(Bayesian_filter_matrix::Vec& v, const Float mean, const Float sigma)
{
boost::normal_distribution<boost::mt19937,Float> gen(rng, mean, sigma);
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen();
}
void normal(Bayesian_filter_matrix::Vec& v)
{
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen_normal();
}
void uniform_01(Bayesian_filter_matrix::Vec& v)
{
for (size_t i = 0, iend=v.size(); i < iend; ++i)
v[i] = gen_uniform();
}
#endif
void seed()
{
rng.seed();
}
private:
boost::mt19937 rng;
boost::normal_distribution<boost::mt19937,Float> gen_normal;
boost::uniform_01<boost::mt19937,Float> gen_uniform;
};
#endif
}//namespace
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 2016 Christian Surlykke
*
* This file is part of the Restful Inter Process Communication (Ripc) project.
* It is distributed under the LGPL 2.1 license.
* Please refer to the LICENSE file for a copy of the license.
*/
#include <string.h>
#include <unistd.h>
#include <iosfwd>
#include "httpmessage.h"
#include "errorhandling.h"
namespace org_restfulipc
{
HttpMessage::HttpMessage()
{
}
HttpMessage::~HttpMessage()
{
}
const char* HttpMessage::header(const char* headerName)
{
int index = headers.find(headerName);
return index == -1 ? NULL : headers.valueAt(index);
}
void HttpMessage::clear()
{
method = Method::UNKNOWN;
status = 0;
path = 0;
queryParameterMap.clear();
headers.clear();
contentLength = 0;
body = 0;
}
HttpMessageReader::HttpMessageReader(int socket, HttpMessage& message, bool dumpRequest) :
dumpRequest(dumpRequest),
_socket(socket),
_message(message),
_bufferEnd(0),
_currentPos(-1)
{
}
void HttpMessageReader::readRequest()
{
clear();
readRequestLine();
readHeaders();
if (_message.header(Header::content_length)) {
readBody();
}
}
void HttpMessageReader::readResponse()
{
clear();
readStatusLine();
readHeaders();
if (_message.status >= 200 &&
_message.status != 204 &&
_message.status != 304) {
if (_message.header(Header::content_length)) {
readBody();
}
}
}
void HttpMessageReader::clear()
{
_message.clear();
_bufferEnd = 0;
_currentPos = -1;
}
void HttpMessageReader::readRequestLine()
{
while (nextChar() != ' ');
_message.method = string2Method(_message.buffer);
if (_message.method == Method::UNKNOWN) throw HttpCode::Http406;
_message.path = _message.buffer + _currentPos + 1;
for (nextChar(); currentChar() != '?' && !isspace(currentChar()); nextChar());
if (currentChar() == '?') {
readQueryString();
}
_message.buffer[_currentPos] = '\0';
int protocolStart = _currentPos + 1;
while (!isspace(nextChar()));
if (_message.buffer[_currentPos] != '\r' || nextChar() != '\n') throw HttpCode::Http400;
}
void HttpMessageReader::readQueryString()
{
while (!isspace(currentChar())) {
_message.buffer[_currentPos++] = '\0';
char* parameterName = _message.buffer + _currentPos;
char* parameterValue = NULL;
while (currentChar() != '=' && currentChar() != '&' && !isspace(currentChar())) {
nextChar();
}
if (currentChar() == '=') {
_message.buffer[_currentPos++] = '\0';
parameterValue = _message.buffer + _currentPos;
while (currentChar() != '&' && !isspace(currentChar())) {
nextChar();
}
}
if (parameterValue) {
_message.queryParameterMap[parameterName].push_back(parameterValue);
}
else {
_message.queryParameterMap[parameterName].push_back("");
}
}
}
void HttpMessageReader::readStatusLine()
{
while (!isspace(nextChar()));
if (_currentPos <= 0) throw HttpCode::Http400;
if (strncmp("HTTP/1.1", _message.buffer, 8) != 0) throw HttpCode::Http400;
while (isspace(nextChar()));
int statuscodeStart = _currentPos;
if (!isdigit(currentChar())) throw HttpCode::Http400;
while (isdigit(nextChar()));
errno = 0;
long int status = strtol(_message.buffer + statuscodeStart, 0, 10);
if (status <= 100 || status >= 600) throw HttpCode::Http400;
_message.status = (int) status;
// We ignore what follows the status code. This means that a message like
// 'HTTP/1.1 200 Completely f**cked up' will be interpreted as
// 'HTTP/1.1 200 Ok'
// (Why does the http protocol specify that both the code and the text is sent?)
while (currentChar() != '\r') {
if (currentChar() == '\n') throw HttpCode::Http400;
nextChar();
}
if (nextChar() != '\n') throw HttpCode::Http400;
}
// On entry: currentPos points to character just before next header line
void HttpMessageReader::readHeaders()
{
while (true) {
if (nextChar() == '\r') {
if (nextChar() != '\n') throw HttpCode::Http400;
return;
}
readHeaderLine();
}
}
/* On entry - _currentPos points to first character of line
*
* TODO: Full implementation of spec
* - multiline header definitions
* - Illegal chars in names/values
*/
void HttpMessageReader::readHeaderLine()
{
int startOfHeaderLine = _currentPos;
int startOfHeaderValue = -1;
int endOfHeaderValue = -1;
while (isTChar(currentChar())) {
_message.buffer[_currentPos] = tolower(_message.buffer[_currentPos]);
nextChar();
}
if (currentChar() != ':') throw HttpCode::Http400;
if (_currentPos <= startOfHeaderLine) throw HttpCode::Http400;
_message.buffer[_currentPos] = '\0';
while (isblank(nextChar()));
endOfHeaderValue = startOfHeaderValue = _currentPos;
while (currentChar() != '\r') {
if (!isblank(currentChar())) {
endOfHeaderValue = _currentPos + 1;
}
nextChar();
}
if (nextChar() != '\n') throw HttpCode::Http400;
_message.buffer[endOfHeaderValue] = '\0';
_message.headers.add(_message.buffer + startOfHeaderLine, _message.buffer + startOfHeaderValue);
}
bool HttpMessageReader::isTChar(char c)
{
return c != ':'; // FIXME
}
void HttpMessageReader::readBody()
{
errno = 0;
_message.contentLength = strtoul(_message.header(Header::content_length), 0, 10);
if (errno != 0) throw C_Error();
int bodyStart = _currentPos + 1;
while (bodyStart + _message.contentLength > _bufferEnd) {
receive();
}
_message.buffer[bodyStart + _message.contentLength] = '\0';
_message.body = _message.buffer + bodyStart;
}
char HttpMessageReader::currentChar()
{
return _message.buffer[_currentPos];
}
char HttpMessageReader::nextChar()
{
_currentPos++;
while (_currentPos >= _bufferEnd) {
receive();
}
return _message.buffer[_currentPos];
}
void HttpMessageReader::receive()
{
int bytesRead = read(_socket, _message.buffer + _bufferEnd, 8190 - _bufferEnd);
if (bytesRead > 0) {
_message.buffer[_bufferEnd + bytesRead] = '\0';
if (dumpRequest) {
printf(_message.buffer + _bufferEnd);
}
_bufferEnd += bytesRead;
}
else {
throw C_Error();
}
}
Buffer HttpMessage::toBuf()
{
Buffer buf;
if (path) {
buf << "HTTP " << method2String(method) << " " << path;
if (queryParameterMap.size() > 0) {
char separator = '?';
for (int i = 0; i < queryParameterMap.size(); i++) {
for (const char* value : queryParameterMap.valueAt(i)) {
buf << separator << queryParameterMap.keyAt(i) << "=" << value;
separator = '&';
}
}
}
}
else {
buf << status;
}
buf << "\n";
for (int i = 0; i < headers.size(); i++) {
buf << headers.keyAt(i) << ": " << headers.valueAt(i) << "\n";
}
buf << "\n";
if (body) {
buf << body << "\n";
}
return buf;
}
}
//Method method;
//char* path;
//char* remainingPath;
//char* queryString;
//int status;
//const char* headers[(int) Header::unknown];
//char* body;
//int contentLength;status
//
//char buffer[8192];
<commit_msg>Add newline at end when dumping http requests<commit_after>/*
* Copyright (c) 2015, 2016 Christian Surlykke
*
* This file is part of the Restful Inter Process Communication (Ripc) project.
* It is distributed under the LGPL 2.1 license.
* Please refer to the LICENSE file for a copy of the license.
*/
#include <string.h>
#include <unistd.h>
#include <iosfwd>
#include "httpmessage.h"
#include "errorhandling.h"
namespace org_restfulipc
{
HttpMessage::HttpMessage()
{
}
HttpMessage::~HttpMessage()
{
}
const char* HttpMessage::header(const char* headerName)
{
int index = headers.find(headerName);
return index == -1 ? NULL : headers.valueAt(index);
}
void HttpMessage::clear()
{
method = Method::UNKNOWN;
status = 0;
path = 0;
queryParameterMap.clear();
headers.clear();
contentLength = 0;
body = 0;
}
HttpMessageReader::HttpMessageReader(int socket, HttpMessage& message, bool dumpRequest) :
dumpRequest(dumpRequest),
_socket(socket),
_message(message),
_bufferEnd(0),
_currentPos(-1)
{
}
void HttpMessageReader::readRequest()
{
clear();
readRequestLine();
readHeaders();
if (_message.header(Header::content_length)) {
readBody();
}
if (dumpRequest) {
printf("\n");
}
}
void HttpMessageReader::readResponse()
{
clear();
readStatusLine();
readHeaders();
if (_message.status >= 200 &&
_message.status != 204 &&
_message.status != 304) {
if (_message.header(Header::content_length)) {
readBody();
}
}
}
void HttpMessageReader::clear()
{
_message.clear();
_bufferEnd = 0;
_currentPos = -1;
}
void HttpMessageReader::readRequestLine()
{
while (nextChar() != ' ');
_message.method = string2Method(_message.buffer);
if (_message.method == Method::UNKNOWN) throw HttpCode::Http406;
_message.path = _message.buffer + _currentPos + 1;
for (nextChar(); currentChar() != '?' && !isspace(currentChar()); nextChar());
if (currentChar() == '?') {
readQueryString();
}
_message.buffer[_currentPos] = '\0';
int protocolStart = _currentPos + 1;
while (!isspace(nextChar()));
if (_message.buffer[_currentPos] != '\r' || nextChar() != '\n') throw HttpCode::Http400;
}
void HttpMessageReader::readQueryString()
{
while (!isspace(currentChar())) {
_message.buffer[_currentPos++] = '\0';
char* parameterName = _message.buffer + _currentPos;
char* parameterValue = NULL;
while (currentChar() != '=' && currentChar() != '&' && !isspace(currentChar())) {
nextChar();
}
if (currentChar() == '=') {
_message.buffer[_currentPos++] = '\0';
parameterValue = _message.buffer + _currentPos;
while (currentChar() != '&' && !isspace(currentChar())) {
nextChar();
}
}
if (parameterValue) {
_message.queryParameterMap[parameterName].push_back(parameterValue);
}
else {
_message.queryParameterMap[parameterName].push_back("");
}
}
}
void HttpMessageReader::readStatusLine()
{
while (!isspace(nextChar()));
if (_currentPos <= 0) throw HttpCode::Http400;
if (strncmp("HTTP/1.1", _message.buffer, 8) != 0) throw HttpCode::Http400;
while (isspace(nextChar()));
int statuscodeStart = _currentPos;
if (!isdigit(currentChar())) throw HttpCode::Http400;
while (isdigit(nextChar()));
errno = 0;
long int status = strtol(_message.buffer + statuscodeStart, 0, 10);
if (status <= 100 || status >= 600) throw HttpCode::Http400;
_message.status = (int) status;
// We ignore what follows the status code. This means that a message like
// 'HTTP/1.1 200 Completely f**cked up' will be interpreted as
// 'HTTP/1.1 200 Ok'
// (Why does the http protocol specify that both the code and the text is sent?)
while (currentChar() != '\r') {
if (currentChar() == '\n') throw HttpCode::Http400;
nextChar();
}
if (nextChar() != '\n') throw HttpCode::Http400;
}
// On entry: currentPos points to character just before next header line
void HttpMessageReader::readHeaders()
{
while (true) {
if (nextChar() == '\r') {
if (nextChar() != '\n') throw HttpCode::Http400;
return;
}
readHeaderLine();
}
}
/* On entry - _currentPos points to first character of line
*
* TODO: Full implementation of spec
* - multiline header definitions
* - Illegal chars in names/values
*/
void HttpMessageReader::readHeaderLine()
{
int startOfHeaderLine = _currentPos;
int startOfHeaderValue = -1;
int endOfHeaderValue = -1;
while (isTChar(currentChar())) {
_message.buffer[_currentPos] = tolower(_message.buffer[_currentPos]);
nextChar();
}
if (currentChar() != ':') throw HttpCode::Http400;
if (_currentPos <= startOfHeaderLine) throw HttpCode::Http400;
_message.buffer[_currentPos] = '\0';
while (isblank(nextChar()));
endOfHeaderValue = startOfHeaderValue = _currentPos;
while (currentChar() != '\r') {
if (!isblank(currentChar())) {
endOfHeaderValue = _currentPos + 1;
}
nextChar();
}
if (nextChar() != '\n') throw HttpCode::Http400;
_message.buffer[endOfHeaderValue] = '\0';
_message.headers.add(_message.buffer + startOfHeaderLine, _message.buffer + startOfHeaderValue);
}
bool HttpMessageReader::isTChar(char c)
{
return c != ':'; // FIXME
}
void HttpMessageReader::readBody()
{
errno = 0;
_message.contentLength = strtoul(_message.header(Header::content_length), 0, 10);
if (errno != 0) throw C_Error();
int bodyStart = _currentPos + 1;
while (bodyStart + _message.contentLength > _bufferEnd) {
receive();
}
_message.buffer[bodyStart + _message.contentLength] = '\0';
_message.body = _message.buffer + bodyStart;
}
char HttpMessageReader::currentChar()
{
return _message.buffer[_currentPos];
}
char HttpMessageReader::nextChar()
{
_currentPos++;
while (_currentPos >= _bufferEnd) {
receive();
}
return _message.buffer[_currentPos];
}
void HttpMessageReader::receive()
{
int bytesRead = read(_socket, _message.buffer + _bufferEnd, 8190 - _bufferEnd);
if (bytesRead > 0) {
_message.buffer[_bufferEnd + bytesRead] = '\0';
if (dumpRequest) {
printf(_message.buffer + _bufferEnd);
}
_bufferEnd += bytesRead;
}
else {
throw C_Error();
}
}
Buffer HttpMessage::toBuf()
{
Buffer buf;
if (path) {
buf << "HTTP " << method2String(method) << " " << path;
if (queryParameterMap.size() > 0) {
char separator = '?';
for (int i = 0; i < queryParameterMap.size(); i++) {
for (const char* value : queryParameterMap.valueAt(i)) {
buf << separator << queryParameterMap.keyAt(i) << "=" << value;
separator = '&';
}
}
}
}
else {
buf << status;
}
buf << "\n";
for (int i = 0; i < headers.size(); i++) {
buf << headers.keyAt(i) << ": " << headers.valueAt(i) << "\n";
}
buf << "\n";
if (body) {
buf << body << "\n";
}
return buf;
}
}
//Method method;
//char* path;
//char* remainingPath;
//char* queryString;
//int status;
//const char* headers[(int) Header::unknown];
//char* body;
//int contentLength;status
//
//char buffer[8192];
<|endoftext|> |
<commit_before>#include "Workspace.h"
#include <memory>
#include <stdio.h>
#include <future>
#include "utils.h"
#include "git.h"
#include "estd.h"
#include "graph.h"
using namespace aBuild;
static void checkingMissingPackages(Workspace& ws) {
// Checking missing packages
auto missingPackages = ws.getAllMissingPackages();
while (not missingPackages.empty()) {
for (auto const& p : missingPackages) {
PackageURL url(p);
utils::mkdir(".aBuild/tmp");
utils::rm(".aBuild/tmp/Repo.git", true, true);
git::clone(url.getURL(), url.getBranch(), std::string(".aBuild/tmp/Repo.git"));
Package package(url);
jsonSerializer::read(".aBuild/tmp/Repo.git/aBuild.json", package);
std::string call = std::string("mv .aBuild/tmp/Repo.git packages/")+package.getName();
system(call.c_str());
}
missingPackages = ws.getAllMissingPackages();
}
}
static void checkingNotNeededPackages(Workspace& ws) {
// Checking not needed packages
auto notRequiredPackages = ws.getAllNotRequiredPackages();
while (not notRequiredPackages.empty()) {
for (auto const& s : notRequiredPackages) {
std::cout<<"Not Required "<<s<<std::endl;
utils::rm(std::string("packages/")+s, true, true);
}
notRequiredPackages = ws.getAllNotRequiredPackages();
}
}
static void checkingInvalidPackages(Workspace& ws) {
// checking invalid packages
auto invalidPackages = ws.getAllInvalidPackages();
for (auto const& p : invalidPackages) {
std::cout<<"Package is ill formed: "<<p<<std::endl;
}
}
static void checkingRequiredPackages(Workspace& ws) {
// check branches (if the correct ones are checked out
auto requiredPackages = ws.getAllRequiredPackages();
for (auto const& _url : requiredPackages) {
PackageURL url {_url};
utils::Cwd cwd(url.getPath());
if (not git::isDirty()) {
if (url.getBranch() != git::getBranch()) {
std::cout<<"Changing branch of "<<url.getName()<<std::endl;
git::checkout(url.getBranch());
}
}
}
}
using Action = std::function<void()>;
int main(int argc, char** argv) {
try {
if (argc == 1) {
Workspace ws(".");
checkingMissingPackages(ws);
checkingNotNeededPackages(ws);
checkingInvalidPackages(ws);
checkingRequiredPackages(ws);
Graph graph;
std::function<void(Project*)> linkingLibFunc = [&graph](Project* project) {
utils::mkdir(".aBuild/lib/");
std::string call = "ar rcs .aBuild/lib/"+project->getName()+".a";
// Get file dependencies
{
auto ingoing = graph.getIngoing<std::string, Project>(project, false);
for (auto const& f : ingoing) {
call += " .aBuild/obj/"+ *f + ".o";
}
}
utils::runProcess(call);
// std::cout<<call<<std::endl;
};
std::function<void(Project*)> linkingExecFunc = [&graph](Project* project) {
utils::mkdir("bin");
utils::mkdir("bin/tests");
std::string outFile = std::string("bin/")+project->getName();
if (utils::isStartingWith(project->getName(), "test")) {
outFile = std::string("bin/tests/")+project->getName();
}
std::string call = "ccache clang++ -o "+outFile;
// Set all depLibraries libraries
for (auto const& l : project->getDepLibraries()) {
call += " -l"+l;
}
// Get file dependencies
{
auto ingoing = graph.getIngoing<std::string, Project>(project, false);
for (auto const& f : ingoing) {
call += " .aBuild/obj/"+ *f + ".o";
}
}
// Get project dependencies
{
auto outgoing = graph.getIngoing<Project, Project>(project, true);
for (auto const& f : outgoing) {
call += " .aBuild/lib/"+f->getName()+".a";
// Set all depLibraries libraries
for (auto const& l : f->getDepLibraries()) {
call += " -l"+l;
}
}
}
// std::cout<<call<<std::endl;
utils::runProcess(call);
};
std::function<void(std::string*)> compileFileFunc = [&graph](std::string* f) {
auto l = utils::explode(*f, "/");
utils::mkdir(".aBuild/obj/" + utils::dirname(*f));
std::string call = "ccache clang++ -Qunused-arguments -ggdb -O0 --std=c++11 "
"-c " + *f + " "
"-o .aBuild/obj/" + *f + ".o";
// Get include dependencies
{
Project* project = *graph.getOutgoing<Project, std::string>(f, false).begin();
for (auto const& i : project->getLegacy().includes) {
call += " -I "+project->getPackagePath()+"/"+i;
}
call += " -I "+project->getPackagePath()+"/src/"+project->getPath();
call += " -I "+project->getPackagePath()+"/src/";
auto ingoing = graph.getIngoing<Project, Project>(project, true);
for (auto const& f : ingoing) {
call += " -isystem "+f->getPackagePath()+"/src";
for (auto const& i : f->getLegacy().includes) {
call += " -isystem "+f->getPackagePath()+"/"+i;
}
}
}
utils::runProcess(call);
// std::cout<<call<<std::endl;
};
// Create dependency tree
auto projects = ws.getAllRequiredProjects();
for (auto& e : projects) {
auto& project = e.second;
// Adding linking
if (project.getType() == "library") {
graph.addNode(&project, linkingLibFunc);
} else if (project.getType() == "executable") {
graph.addNode(&project, linkingExecFunc);
} else {
std::cout<<"invalid type: "<<project.getType()<<std::endl;
}
// Adding compile files
for (auto& f : project.getAllCppFiles()) {
graph.addNode(&f, compileFileFunc);
graph.addEdge(&f, &project);
}
for (auto const& dep : project.getDependencies()) {
auto l = utils::explode(dep, "/");
graph.addEdge(&projects.at(l[1]), &project);
}
}
graph.visitAllNodes();
} else if (argc == 2 && std::string(argv[1]) == "pull") {
auto allPackages = utils::listDirs("./packages", true);
for (auto& p : allPackages) { p = "./packages/"+p; }
allPackages.push_back(".");
utils::runParallel<std::string>(allPackages, [](std::string const& file) {
utils::Cwd cwd(file);
if (git::isDirty()) {
std::cout<<"ignore " << file << ": Dirty repository"<<std::endl;
} else {
git::pull();
}
});
} else if (argc == 2 && std::string(argv[1]) == "push") {
auto allPackages = utils::listDirs("./packages", true);
for (auto& p : allPackages) { p = "./packages/"+p; }
allPackages.push_back(".");
utils::runParallel<std::string>(allPackages, [](std::string const& file) {
utils::Cwd cwd(file);
git::push();
});
} else if (argc == 2 && std::string(argv[1]) == "test") {
auto allTests = utils::listFiles("./bin/tests/");
std::cout<<"===Start testing==="<<std::endl;
for (auto const& t : allTests) {
auto p = std::string("./bin/tests/")+t;
system(p.c_str());
std::cout<<" • running "<<p<<std::endl;
}
std::cout<<"ran "<<allTests.size()<<" test(s)"<<std::endl;
std::cout<<"===Ended testing==="<<std::endl;
} else if (argc == 2 && std::string(argv[1]) == "install") {
auto allFiles = utils::listFiles("./bin/");
for (auto const& f : allFiles) {
std::cout<<"installing "<<f<<"; Error Code: ";
auto oldFile = std::string("./bin/")+f;
auto newFile = std::string("/usr/bin/")+f;
auto cpFile = std::string("cp ")+newFile+" "+oldFile;
auto error = rename(oldFile.c_str(), newFile.c_str());
std::cout<<error<<std::endl;
system(cpFile.c_str());
}
}
} catch(std::exception const& e) {
std::cerr<<"exception: "<<e.what()<<std::endl;
}
return 0;
}
<commit_msg>adding clone command that downloads, compiles and runs tests<commit_after>#include "Workspace.h"
#include <memory>
#include <stdio.h>
#include <future>
#include "utils.h"
#include "git.h"
#include "estd.h"
#include "graph.h"
using namespace aBuild;
static void checkingMissingPackages(Workspace& ws) {
// Checking missing packages
auto missingPackages = ws.getAllMissingPackages();
while (not missingPackages.empty()) {
for (auto const& p : missingPackages) {
PackageURL url(p);
utils::mkdir(".aBuild/tmp");
utils::rm(".aBuild/tmp/Repo.git", true, true);
git::clone(url.getURL(), url.getBranch(), std::string(".aBuild/tmp/Repo.git"));
Package package(url);
jsonSerializer::read(".aBuild/tmp/Repo.git/aBuild.json", package);
std::string call = std::string("mv .aBuild/tmp/Repo.git packages/")+package.getName();
system(call.c_str());
}
missingPackages = ws.getAllMissingPackages();
}
}
static void checkingNotNeededPackages(Workspace& ws) {
// Checking not needed packages
auto notRequiredPackages = ws.getAllNotRequiredPackages();
while (not notRequiredPackages.empty()) {
for (auto const& s : notRequiredPackages) {
std::cout<<"Not Required "<<s<<std::endl;
utils::rm(std::string("packages/")+s, true, true);
}
notRequiredPackages = ws.getAllNotRequiredPackages();
}
}
static void checkingInvalidPackages(Workspace& ws) {
// checking invalid packages
auto invalidPackages = ws.getAllInvalidPackages();
for (auto const& p : invalidPackages) {
std::cout<<"Package is ill formed: "<<p<<std::endl;
}
}
static void checkingRequiredPackages(Workspace& ws) {
// check branches (if the correct ones are checked out
auto requiredPackages = ws.getAllRequiredPackages();
for (auto const& _url : requiredPackages) {
PackageURL url {_url};
utils::Cwd cwd(url.getPath());
if (not git::isDirty()) {
if (url.getBranch() != git::getBranch()) {
std::cout<<"Changing branch of "<<url.getName()<<std::endl;
git::checkout(url.getBranch());
}
}
}
}
using Action = std::function<void()>;
int main(int argc, char** argv) {
try {
if (argc == 1) {
Workspace ws(".");
checkingMissingPackages(ws);
checkingNotNeededPackages(ws);
checkingInvalidPackages(ws);
checkingRequiredPackages(ws);
Graph graph;
std::function<void(Project*)> linkingLibFunc = [&graph](Project* project) {
utils::mkdir(".aBuild/lib/");
std::string call = "ar rcs .aBuild/lib/"+project->getName()+".a";
// Get file dependencies
{
auto ingoing = graph.getIngoing<std::string, Project>(project, false);
for (auto const& f : ingoing) {
call += " .aBuild/obj/"+ *f + ".o";
}
}
utils::runProcess(call);
// std::cout<<call<<std::endl;
};
std::function<void(Project*)> linkingExecFunc = [&graph](Project* project) {
utils::mkdir("bin");
utils::mkdir("bin/tests");
std::string outFile = std::string("bin/")+project->getName();
if (utils::isStartingWith(project->getName(), "test")) {
outFile = std::string("bin/tests/")+project->getName();
}
std::string call = "ccache clang++ -o "+outFile;
// Set all depLibraries libraries
for (auto const& l : project->getDepLibraries()) {
call += " -l"+l;
}
// Get file dependencies
{
auto ingoing = graph.getIngoing<std::string, Project>(project, false);
for (auto const& f : ingoing) {
call += " .aBuild/obj/"+ *f + ".o";
}
}
// Get project dependencies
{
auto outgoing = graph.getIngoing<Project, Project>(project, true);
for (auto const& f : outgoing) {
call += " .aBuild/lib/"+f->getName()+".a";
// Set all depLibraries libraries
for (auto const& l : f->getDepLibraries()) {
call += " -l"+l;
}
}
}
// std::cout<<call<<std::endl;
utils::runProcess(call);
};
std::function<void(std::string*)> compileFileFunc = [&graph](std::string* f) {
auto l = utils::explode(*f, "/");
utils::mkdir(".aBuild/obj/" + utils::dirname(*f));
std::string call = "ccache clang++ -Qunused-arguments -ggdb -O0 --std=c++11 "
"-c " + *f + " "
"-o .aBuild/obj/" + *f + ".o";
// Get include dependencies
{
Project* project = *graph.getOutgoing<Project, std::string>(f, false).begin();
for (auto const& i : project->getLegacy().includes) {
call += " -I "+project->getPackagePath()+"/"+i;
}
call += " -I "+project->getPackagePath()+"/src/"+project->getPath();
call += " -I "+project->getPackagePath()+"/src/";
auto ingoing = graph.getIngoing<Project, Project>(project, true);
for (auto const& f : ingoing) {
call += " -isystem "+f->getPackagePath()+"/src";
for (auto const& i : f->getLegacy().includes) {
call += " -isystem "+f->getPackagePath()+"/"+i;
}
}
}
utils::runProcess(call);
// std::cout<<call<<std::endl;
};
// Create dependency tree
auto projects = ws.getAllRequiredProjects();
for (auto& e : projects) {
auto& project = e.second;
// Adding linking
if (project.getType() == "library") {
graph.addNode(&project, linkingLibFunc);
} else if (project.getType() == "executable") {
graph.addNode(&project, linkingExecFunc);
} else {
std::cout<<"invalid type: "<<project.getType()<<std::endl;
}
// Adding compile files
for (auto& f : project.getAllCppFiles()) {
graph.addNode(&f, compileFileFunc);
graph.addEdge(&f, &project);
}
for (auto const& dep : project.getDependencies()) {
auto l = utils::explode(dep, "/");
graph.addEdge(&projects.at(l[1]), &project);
}
}
graph.visitAllNodes();
} else if (argc == 4 && std::string(argv[1]) == "clone") {
std::string dir = std::string(argv[3]) + "/";
git::clone(std::string(argv[2]), "master", dir);
utils::Cwd cwd {dir};
std::string call = std::string(argv[0]);
system(call.c_str());
call += " test";
system(call.c_str());
} else if (argc == 2 && std::string(argv[1]) == "pull") {
auto allPackages = utils::listDirs("./packages", true);
for (auto& p : allPackages) { p = "./packages/"+p; }
allPackages.push_back(".");
utils::runParallel<std::string>(allPackages, [](std::string const& file) {
utils::Cwd cwd(file);
if (git::isDirty()) {
std::cout<<"ignore " << file << ": Dirty repository"<<std::endl;
} else {
git::pull();
}
});
} else if (argc == 2 && std::string(argv[1]) == "push") {
auto allPackages = utils::listDirs("./packages", true);
for (auto& p : allPackages) { p = "./packages/"+p; }
allPackages.push_back(".");
utils::runParallel<std::string>(allPackages, [](std::string const& file) {
utils::Cwd cwd(file);
git::push();
});
} else if (argc == 2 && std::string(argv[1]) == "test") {
auto allTests = utils::listFiles("./bin/tests/");
std::cout<<"===Start testing==="<<std::endl;
for (auto const& t : allTests) {
auto p = std::string("./bin/tests/")+t;
system(p.c_str());
std::cout<<" • running "<<p<<std::endl;
}
std::cout<<"ran "<<allTests.size()<<" test(s)"<<std::endl;
std::cout<<"===Ended testing==="<<std::endl;
} else if (argc == 2 && std::string(argv[1]) == "install") {
auto allFiles = utils::listFiles("./bin/");
for (auto const& f : allFiles) {
std::cout<<"installing "<<f<<"; Error Code: ";
auto oldFile = std::string("./bin/")+f;
auto newFile = std::string("/usr/bin/")+f;
auto cpFile = std::string("cp ")+newFile+" "+oldFile;
auto error = rename(oldFile.c_str(), newFile.c_str());
std::cout<<error<<std::endl;
system(cpFile.c_str());
}
}
} catch(std::exception const& e) {
std::cerr<<"exception: "<<e.what()<<std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- c-style: gnu -*-
Copyright (c) 2013 John Harper <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
#include "act-gps-activity.h"
#include "act-gps-parser.h"
#include "act-gps-fit-parser.h"
#include "act-gps-tcx-parser.h"
#include <getopt.h>
#include <math.h>
using namespace act;
static const struct option long_options[] =
{
{"fit", no_argument, 0, 'f'},
{"tcx", no_argument, 0, 't'},
{"print-summary", no_argument, 0, 's'},
{"print-laps", no_argument, 0, 'l'},
{"print-points", no_argument, 0, 'p'},
{"print-date", optional_argument, 0, 'd'},
{"global-time", no_argument, 0, 'g'},
};
static const char short_options[] = "ftslpd:g";
static void
usage_and_exit(int ret)
{
fprintf(stderr, "usage: gps-test [OPTIONS] FILES...\n");
exit(ret);
}
int
main(int argc, char **argv)
{
bool opt_fit = false;
bool opt_tcx = false;
bool opt_print_summary = false;
bool opt_print_laps = false;
bool opt_print_points = false;
const char *opt_print_date = nullptr;
bool opt_global_time = false;
while (1)
{
int opt = getopt_long(argc, argv, short_options, long_options, 0);
if (opt == -1)
break;
switch (opt)
{
case 'f':
opt_fit = true;
break;
case 't':
opt_tcx = true;
break;
case 's':
opt_print_summary = true;
break;
case 'l':
opt_print_laps = true;
break;
case 'p':
opt_print_points = true;
break;
case 'd':
if (optarg)
opt_print_date = optarg;
else
opt_print_date = "%a, %d %b %Y %H:%M:%S %z";
break;
case 'g':
opt_global_time = true;
break;
default:
usage_and_exit(1);
}
}
for (int i = optind; i < argc; i++)
{
gps::activity test_activity;
if (opt_fit)
test_activity.read_fit_file(argv[i]);
else if (opt_tcx)
test_activity.read_tcx_file(argv[i]);
else
test_activity.read_file(argv[i]);
if (opt_print_date)
{
time_t d = (time_t) test_activity.start_time();
if (d == 0)
continue;
struct tm tm = {0};
if (opt_global_time)
gmtime_r(&d, &tm);
else
localtime_r(&d, &tm);
char buf[1024];
strftime(buf, sizeof(buf), opt_print_date, &tm);
printf("%s\n", buf);
}
if (opt_print_summary)
test_activity.print_summary(stdout);
if (opt_print_laps)
{
fputc('\n', stdout);
test_activity.print_laps(stdout);
}
if (opt_print_points)
{
fputc('\n', stdout);
test_activity.print_points(stdout);
}
}
return 0;
}
<commit_msg>act-gps-info uses act::arguments; added --print-smoothed=WIDTH option<commit_after>/* -*- c-style: gnu -*-
Copyright (c) 2013 John Harper <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
#include "act-arguments.h"
#include "act-gps-activity.h"
#include "act-gps-parser.h"
#include "act-gps-fit-parser.h"
#include "act-gps-tcx-parser.h"
#include <getopt.h>
#include <math.h>
using namespace act;
enum option_id
{
opt_fit,
opt_tcx,
opt_print_summary,
opt_print_laps,
opt_print_points,
opt_print_smoothed,
opt_print_date,
opt_global_time,
};
static const arguments::option options[] =
{
{opt_fit, "fit", 'f', nullptr, "Treat as FIT data."},
{opt_tcx, "tcx", 't', nullptr, "Treat as XML TCX data." },
{opt_print_summary, "print-summary", 's', nullptr,
"Print activity summary."},
{opt_print_laps, "print-laps", 'l', nullptr, "Print lap summaries."},
{opt_print_points, "print-points", 'p', nullptr, "Print raw GPS track."},
{opt_print_smoothed, "print-smoothed", 'S', "SECONDS",
"Print smoothed GPS track."},
{opt_print_date, "print-date", 'd', "DATE-FORMAT", "Print activity date."},
{opt_global_time, "global-time", 'g', nullptr, "Print date as UTC."},
{arguments::opt_eof},
};
static void
print_usage(const arguments &args)
{
fprintf(stderr, "usage: %s [OPTION...] FILE...\n\n", args.program_name());
fputs("where OPTION is any of:\n\n", stderr);
arguments::print_options(options, stderr);
fputs("\n", stderr);
}
int
main(int argc, const char **argv)
{
arguments args(argc, argv);
bool fit_data = false;
bool tcx_data = false;
bool print_summary = false;
bool print_laps = false;
bool print_points = false;
int print_smoothed = 0;
const char *print_date = nullptr;
bool global_time = false;
while (1)
{
const char *opt_arg = nullptr;
int opt = args.getopt(options, &opt_arg);
if (opt == arguments::opt_eof)
break;
switch (opt)
{
case opt_fit:
fit_data = true;
break;
case opt_tcx:
tcx_data = true;
break;
case opt_print_summary:
print_summary = true;
break;
case opt_print_laps:
print_laps = true;
break;
case opt_print_points:
print_points = true;
break;
case opt_print_smoothed:
print_smoothed = atoi(opt_arg);
break;
case opt_print_date:
if (opt_arg != nullptr)
print_date = opt_arg;
else
print_date = "%a, %d %b %Y %H:%M:%S %z";
break;
case opt_global_time:
global_time = true;
break;
default:
print_usage(args);
exit(1);
}
}
for (const std::string &s : args.args())
{
gps::activity activity;
if (fit_data)
activity.read_fit_file(s.c_str());
else if (tcx_data)
activity.read_tcx_file(s.c_str());
else
activity.read_file(s.c_str());
if (print_date)
{
time_t d = (time_t) activity.start_time();
if (d == 0)
continue;
struct tm tm = {0};
if (global_time)
gmtime_r(&d, &tm);
else
localtime_r(&d, &tm);
char buf[1024];
strftime(buf, sizeof(buf), print_date, &tm);
printf("%s\n", buf);
}
if (print_summary)
activity.print_summary(stdout);
if (print_laps)
{
fputc('\n', stdout);
activity.print_laps(stdout);
}
if (print_points)
{
printf("\nRAW track data:\n\n");
activity.print_points(stdout);
}
if (print_smoothed > 0)
{
gps::activity smoothed;
smoothed.smooth(activity, print_smoothed);
printf("\nSmoothed track data (%ds):\n\n", print_smoothed);
smoothed.print_points(stdout);
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "include/cef_download_handler.h"
#include "DownloadAdapter.h"
using namespace System;
using namespace CefSharp;
namespace CefSharp
{
namespace Internals
{
DownloadAdapter::~DownloadAdapter()
{
_handler = nullptr;
}
void DownloadAdapter::OnBeforeDownload(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback)
{
String^ download_path;
bool show_dialog;
auto downloadItem = GetDownloadItem(download_item);
downloadItem->SuggestedFileName = StringUtils::ToClr(suggested_name);
if (_handler->OnBeforeDownload(downloadItem, download_path, show_dialog))
{
callback->Continue(StringUtils::ToNative(download_path), show_dialog);
}
};
void DownloadAdapter::OnDownloadUpdated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
CefRefPtr<CefDownloadItemCallback> callback)
{
if (_handler->OnDownloadUpdated(GetDownloadItem(download_item)))
{
callback->Cancel();
}
}
CefSharp::DownloadItem^ DownloadAdapter::GetDownloadItem(CefRefPtr<CefDownloadItem> download_item)
{
auto item = gcnew CefSharp::DownloadItem();
item->IsValid = download_item->IsValid();
//NOTE: Description for IsValid says `Do not call any other methods if this function returns false.` so only load if IsValid = true
if(item->IsValid)
{
item->IsInProgress = download_item->IsInProgress();
item->IsComplete = download_item->IsComplete();
item->IsCancelled = download_item->IsCanceled();
item->CurrentSpeed = download_item->GetCurrentSpeed();
item->PercentComplete = download_item->GetPercentComplete();
item->TotalBytes = download_item->GetTotalBytes();
item->ReceivedBytes = download_item->GetReceivedBytes();
item->StartTime = ConvertCefTimeToNullableDateTime(download_item->GetStartTime());
item->EndTime = ConvertCefTimeToNullableDateTime(download_item->GetEndTime());
item->FullPath = StringUtils::ToClr(download_item->GetFullPath());
item->Id = download_item->GetId();
item->Url = StringUtils::ToClr(download_item->GetURL());
item->SuggestedFileName = StringUtils::ToClr(download_item->GetSuggestedFileName());
item->ContentDisposition = StringUtils::ToClr(download_item->GetContentDisposition());
item->MimeType = StringUtils::ToClr(download_item->GetMimeType());
}
return item;
}
Nullable<DateTime> DownloadAdapter::ConvertCefTimeToNullableDateTime(CefTime time)
{
auto epoch = time.GetDoubleT();
if(epoch == 0)
{
return Nullable<DateTime>();
}
return Nullable<DateTime>(DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(epoch));
}
}
}
<commit_msg>Modify DownloadAdapter::ConvertCefTimeToNullableDateTime to return local time<commit_after>// Copyright 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "include/cef_download_handler.h"
#include "DownloadAdapter.h"
using namespace System;
using namespace CefSharp;
namespace CefSharp
{
namespace Internals
{
DownloadAdapter::~DownloadAdapter()
{
_handler = nullptr;
}
void DownloadAdapter::OnBeforeDownload(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback)
{
String^ download_path;
bool show_dialog;
auto downloadItem = GetDownloadItem(download_item);
downloadItem->SuggestedFileName = StringUtils::ToClr(suggested_name);
if (_handler->OnBeforeDownload(downloadItem, download_path, show_dialog))
{
callback->Continue(StringUtils::ToNative(download_path), show_dialog);
}
};
void DownloadAdapter::OnDownloadUpdated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,
CefRefPtr<CefDownloadItemCallback> callback)
{
if (_handler->OnDownloadUpdated(GetDownloadItem(download_item)))
{
callback->Cancel();
}
}
CefSharp::DownloadItem^ DownloadAdapter::GetDownloadItem(CefRefPtr<CefDownloadItem> download_item)
{
auto item = gcnew CefSharp::DownloadItem();
item->IsValid = download_item->IsValid();
//NOTE: Description for IsValid says `Do not call any other methods if this function returns false.` so only load if IsValid = true
if(item->IsValid)
{
item->IsInProgress = download_item->IsInProgress();
item->IsComplete = download_item->IsComplete();
item->IsCancelled = download_item->IsCanceled();
item->CurrentSpeed = download_item->GetCurrentSpeed();
item->PercentComplete = download_item->GetPercentComplete();
item->TotalBytes = download_item->GetTotalBytes();
item->ReceivedBytes = download_item->GetReceivedBytes();
item->StartTime = ConvertCefTimeToNullableDateTime(download_item->GetStartTime());
item->EndTime = ConvertCefTimeToNullableDateTime(download_item->GetEndTime());
item->FullPath = StringUtils::ToClr(download_item->GetFullPath());
item->Id = download_item->GetId();
item->Url = StringUtils::ToClr(download_item->GetURL());
item->SuggestedFileName = StringUtils::ToClr(download_item->GetSuggestedFileName());
item->ContentDisposition = StringUtils::ToClr(download_item->GetContentDisposition());
item->MimeType = StringUtils::ToClr(download_item->GetMimeType());
}
return item;
}
Nullable<DateTime> DownloadAdapter::ConvertCefTimeToNullableDateTime(CefTime time)
{
auto epoch = time.GetDoubleT();
if(epoch == 0)
{
return Nullable<DateTime>();
}
return Nullable<DateTime>(DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(epoch).ToLocalTime());
}
}
}
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_RANGE_HXX
#define _ABACLADE_RANGE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::range
namespace abc {
/*! Represents an iterable interval of values defined by a beginning and an end, inclusive and
exclusive respectively. */
template <typename T>
class range : public support_explicit_operator_bool<range<T>> {
public:
//! Iterator for range values.
class iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
public:
/*! Constructor.
@param t
Current value.
*/
explicit iterator(T t) :
m_t(std::move(t)) {
}
/*! Dereferencing operator.
@return
Reference to the current node.
*/
T operator*() const {
return m_t;
}
/*! Dereferencing member access operator.
@return
Pointer to the current value.
*/
T * operator->() {
return &m_t;
}
T const * operator->() const {
return &m_t;
}
/*! Preincrement operator.
@return
*this after it’s moved to the value following the one currently referenced.
*/
iterator & operator++() {
++m_t;
return *this;
}
/*! Postincrement operator.
@return
Iterator to the value following the one referenced by this iterator.
*/
iterator operator++(int) {
return iterator(m_t++);
}
/*! Predecrement operator.
@return
*this after it’s moved to the value preceding the one currently referenced.
*/
iterator & operator--() {
--m_t;
return *this;
}
/*! Postdecrement operator.
@return
Iterator to the value preceding the one referenced by this iterator.
*/
iterator operator--(int) {
return iterator(m_t--);
}
/*! Equality relational operator.
@param it
Object to compare to *this.
@return
true if *this has the same value as it, or false otherwise.
*/
bool operator==(iterator const & it) const {
return m_t == it.m_t;
}
/*! Inequality relational operator.
@param it
Object to compare to *this.
@return
true if *this has a different value than it, or false otherwise.
*/
bool operator!=(iterator const & it) const {
return !operator==(it);
}
/*! Returns the underlying value.
@return
Reference to the current value.
*/
T & base() {
return m_t;
}
T const & base() const {
return m_t;
}
private:
//! Current value.
T m_t;
};
typedef std::reverse_iterator<iterator> reverse_iterator;
public:
/*! Constructor.
@param tBegin
First value in the range.
@param tEnd
Value beyond the last one in the range.
*/
range() :
m_tBegin(),
m_tEnd() {
}
range(T tBegin, T tEnd) :
m_tBegin(std::move(tBegin)),
m_tEnd(std::move(tEnd)) {
}
/*! Boolean evaluation operator.
@return
true if the range is non-empty, or false if it’s empty.
*/
explicit_operator_bool() const {
return m_tBegin != m_tEnd;
}
/*! Right-shift-assignment operator.
@param t
Amount by which to shift/translate the range towards positive infinity.
@return
*this after its begin() and end() have been increased by t.
*/
range & operator>>=(T const & t) {
m_tBegin += t;
m_tEnd += t;
return *this;
}
/*! Left-shift-assignment operator.
@param t
Amount by which to shift/translate the range towards negative infinity.
@return
*this after its begin() and end() have been decreased by t.
*/
range & operator<<=(T const & t) {
m_tBegin -= t;
m_tEnd -= t;
return *this;
}
/*! Right-shift operator.
@param t
Amount by which to shift/translate the range towards positive infinity.
@return
Range covering *this with begin() and end() increased by t.
*/
range operator>>(T const & t) const {
return range(*this) >>= t;
}
/*! Left-shift operator.
@param t
Amount by which to shift/translate the range towards negative infinity.
@return
Range covering *this with begin() and end() decreased by t.
*/
range operator<<(T const & t) const {
return range(*this) <<= t;
}
/*! Equality relational operator.
@param r
Object to compare to *this.
@return
true if *this has the same begin and end as r, or false otherwise.
*/
bool operator==(range const & r) const {
return m_tBegin == r.m_tBegin && m_tEnd == r.m_tEnd;
}
/*! Inequality relational operator.
@param r
Object to compare to *this.
@return
true if *this has a different begin and/or end than r, or false otherwise.
*/
bool operator!=(range const & r) const {
return !operator==(r);
}
/*! Returns an iterator to the start of the range.
@return
Iterator to the first value in the range.
*/
iterator begin() const {
return iterator(m_tBegin);
}
/*! Returns true if the specified value is included in the range.
@param t
Value to check for inclusion.
@return
true if t is included in [begin(), end()), or false otherwise.
*/
bool contains(T const & t) const {
return t >= m_tBegin && t < m_tEnd;
}
/*! Returns an iterator to the end of the range.
@return
Value beyond the last in the range.
*/
iterator end() const {
return iterator(m_tEnd);
}
/*! Returns the count of values included in the range.
@return
Count of values.
*/
std::size_t size() const {
return m_tBegin < m_tEnd ? static_cast<std::size_t>(m_tEnd - m_tBegin) : 0;
}
private:
//! First value in the range.
T m_tBegin;
//! Value beyond the last one in the range.
T m_tEnd;
};
/*! Creates an abc::range by inferring the range type from its arguments.
@param tBegin
First value in the range.
@param tEnd
Value beyond the last one in the range.
@return
Range covering [begin, end).
*/
template <typename T>
range<T> make_range(T tBegin, T tEnd) {
return range<T>(std::move(tBegin), std::move(tEnd));
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_RANGE_HXX
<commit_msg>Remove semantically wrong abc::range::iterator::base()<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_RANGE_HXX
#define _ABACLADE_RANGE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::range
namespace abc {
/*! Represents an iterable interval of values defined by a beginning and an end, inclusive and
exclusive respectively. */
template <typename T>
class range : public support_explicit_operator_bool<range<T>> {
public:
//! Iterator for range values.
class iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
public:
/*! Constructor.
@param t
Current value.
*/
explicit iterator(T t) :
m_t(std::move(t)) {
}
/*! Dereferencing operator.
@return
Reference to the current node.
*/
T operator*() const {
return m_t;
}
/*! Dereferencing member access operator.
@return
Pointer to the current value.
*/
T * operator->() {
return &m_t;
}
T const * operator->() const {
return &m_t;
}
/*! Preincrement operator.
@return
*this after it’s moved to the value following the one currently referenced.
*/
iterator & operator++() {
++m_t;
return *this;
}
/*! Postincrement operator.
@return
Iterator to the value following the one referenced by this iterator.
*/
iterator operator++(int) {
return iterator(m_t++);
}
/*! Predecrement operator.
@return
*this after it’s moved to the value preceding the one currently referenced.
*/
iterator & operator--() {
--m_t;
return *this;
}
/*! Postdecrement operator.
@return
Iterator to the value preceding the one referenced by this iterator.
*/
iterator operator--(int) {
return iterator(m_t--);
}
/*! Equality relational operator.
@param it
Object to compare to *this.
@return
true if *this has the same value as it, or false otherwise.
*/
bool operator==(iterator const & it) const {
return m_t == it.m_t;
}
/*! Inequality relational operator.
@param it
Object to compare to *this.
@return
true if *this has a different value than it, or false otherwise.
*/
bool operator!=(iterator const & it) const {
return !operator==(it);
}
private:
//! Current value.
T m_t;
};
typedef std::reverse_iterator<iterator> reverse_iterator;
public:
/*! Constructor.
@param tBegin
First value in the range.
@param tEnd
Value beyond the last one in the range.
*/
range() :
m_tBegin(),
m_tEnd() {
}
range(T tBegin, T tEnd) :
m_tBegin(std::move(tBegin)),
m_tEnd(std::move(tEnd)) {
}
/*! Boolean evaluation operator.
@return
true if the range is non-empty, or false if it’s empty.
*/
explicit_operator_bool() const {
return m_tBegin != m_tEnd;
}
/*! Right-shift-assignment operator.
@param t
Amount by which to shift/translate the range towards positive infinity.
@return
*this after its begin() and end() have been increased by t.
*/
range & operator>>=(T const & t) {
m_tBegin += t;
m_tEnd += t;
return *this;
}
/*! Left-shift-assignment operator.
@param t
Amount by which to shift/translate the range towards negative infinity.
@return
*this after its begin() and end() have been decreased by t.
*/
range & operator<<=(T const & t) {
m_tBegin -= t;
m_tEnd -= t;
return *this;
}
/*! Right-shift operator.
@param t
Amount by which to shift/translate the range towards positive infinity.
@return
Range covering *this with begin() and end() increased by t.
*/
range operator>>(T const & t) const {
return range(*this) >>= t;
}
/*! Left-shift operator.
@param t
Amount by which to shift/translate the range towards negative infinity.
@return
Range covering *this with begin() and end() decreased by t.
*/
range operator<<(T const & t) const {
return range(*this) <<= t;
}
/*! Equality relational operator.
@param r
Object to compare to *this.
@return
true if *this has the same begin and end as r, or false otherwise.
*/
bool operator==(range const & r) const {
return m_tBegin == r.m_tBegin && m_tEnd == r.m_tEnd;
}
/*! Inequality relational operator.
@param r
Object to compare to *this.
@return
true if *this has a different begin and/or end than r, or false otherwise.
*/
bool operator!=(range const & r) const {
return !operator==(r);
}
/*! Returns an iterator to the start of the range.
@return
Iterator to the first value in the range.
*/
iterator begin() const {
return iterator(m_tBegin);
}
/*! Returns true if the specified value is included in the range.
@param t
Value to check for inclusion.
@return
true if t is included in [begin(), end()), or false otherwise.
*/
bool contains(T const & t) const {
return t >= m_tBegin && t < m_tEnd;
}
/*! Returns an iterator to the end of the range.
@return
Value beyond the last in the range.
*/
iterator end() const {
return iterator(m_tEnd);
}
/*! Returns the count of values included in the range.
@return
Count of values.
*/
std::size_t size() const {
return m_tBegin < m_tEnd ? static_cast<std::size_t>(m_tEnd - m_tBegin) : 0;
}
private:
//! First value in the range.
T m_tBegin;
//! Value beyond the last one in the range.
T m_tEnd;
};
/*! Creates an abc::range by inferring the range type from its arguments.
@param tBegin
First value in the range.
@param tEnd
Value beyond the last one in the range.
@return
Range covering [begin, end).
*/
template <typename T>
range<T> make_range(T tBegin, T tEnd) {
return range<T>(std::move(tBegin), std::move(tEnd));
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_RANGE_HXX
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2017, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <Array.hpp>
#include <arith.hpp>
#include <backend.hpp>
#include <canny.hpp>
#include <common/err_common.hpp>
#include <complex.hpp>
#include <convolve.hpp>
#include <copy.hpp>
#include <handle.hpp>
#include <histogram.hpp>
#include <iota.hpp>
#include <ireduce.hpp>
#include <logic.hpp>
#include <reduce.hpp>
#include <sobel.hpp>
#include <tile.hpp>
#include <transpose.hpp>
#include <unary.hpp>
#include <af/defines.h>
#include <af/dim4.hpp>
#include <af/image.h>
#include <af/seq.h>
#include <utility>
#include <vector>
using af::dim4;
using detail::arithOp;
using detail::Array;
using detail::cast;
using detail::convolve2;
using detail::createEmptyArray;
using detail::createHostDataArray;
using detail::createSubArray;
using detail::createValueArray;
using detail::histogram;
using detail::iota;
using detail::ireduce;
using detail::logicOp;
using detail::reduce;
using detail::reduce_all;
using detail::sobelDerivatives;
using detail::uchar;
using detail::uint;
using detail::unaryOp;
using detail::ushort;
using std::make_pair;
using std::pair;
using std::vector;
Array<float> gradientMagnitude(const Array<float>& gx, const Array<float>& gy,
const bool& isf) {
using detail::abs;
if (isf) {
Array<float> gx2 = abs<float, float>(gx);
Array<float> gy2 = abs<float, float>(gy);
return arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
} else {
Array<float> gx2 = arithOp<float, af_mul_t>(gx, gx, gx.dims());
Array<float> gy2 = arithOp<float, af_mul_t>(gy, gy, gy.dims());
Array<float> sg = arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
return unaryOp<float, af_sqrt_t>(sg);
}
}
Array<float> otsuThreshold(const Array<float>& supEdges,
const unsigned NUM_BINS, const float maxVal) {
Array<uint> hist = histogram<float>(supEdges, NUM_BINS, 0, maxVal, false);
const dim4& hDims = hist.dims();
// reduce along histogram dimension i.e. 0th dimension
auto totals = reduce<af_add_t, uint, float>(hist, 0);
// tile histogram total along 0th dimension
auto ttotals = tile(totals, dim4(hDims[0]));
// pixel frequency probabilities
auto probability =
arithOp<float, af_div_t>(cast<float, uint>(hist), ttotals, hDims);
vector<af_seq> seqBegin(4, af_span);
vector<af_seq> seqRest(4, af_span);
seqBegin[0] = af_make_seq(0, static_cast<double>(hDims[0] - 1), 1);
seqRest[0] = af_make_seq(0, static_cast<double>(hDims[0] - 1), 1);
const dim4& iDims = supEdges.dims();
Array<float> sigmas = createEmptyArray<float>(hDims);
for (unsigned b = 0; b < (NUM_BINS - 1); ++b) {
seqBegin[0].end = static_cast<double>(b);
seqRest[0].begin = static_cast<double>(b + 1);
auto frontPartition = createSubArray(probability, seqBegin, false);
auto endPartition = createSubArray(probability, seqRest, false);
auto qL = reduce<af_add_t, float, float>(frontPartition, 0);
auto qH = reduce<af_add_t, float, float>(endPartition, 0);
const dim4 fdims(b + 1, hDims[1], hDims[2], hDims[3]);
const dim4 edims(NUM_BINS - 1 - b, hDims[1], hDims[2], hDims[3]);
const dim4 tdims(1, hDims[1], hDims[2], hDims[3]);
auto frontWeights = iota<float>(dim4(b + 1), tdims);
auto endWeights = iota<float>(dim4(NUM_BINS - 1 - b), tdims);
auto offsetValues = createValueArray<float>(edims, b + 1);
endWeights = arithOp<float, af_add_t>(endWeights, offsetValues, edims);
auto __muL =
arithOp<float, af_mul_t>(frontPartition, frontWeights, fdims);
auto __muH = arithOp<float, af_mul_t>(endPartition, endWeights, edims);
auto _muL = reduce<af_add_t, float, float>(__muL, 0);
auto _muH = reduce<af_add_t, float, float>(__muH, 0);
auto muL = arithOp<float, af_div_t>(_muL, qL, tdims);
auto muH = arithOp<float, af_div_t>(_muH, qH, tdims);
auto TWOS = createValueArray<float>(tdims, 2.0f);
auto diff = arithOp<float, af_sub_t>(muL, muH, tdims);
auto sqrd = arithOp<float, af_pow_t>(diff, TWOS, tdims);
auto op2 = arithOp<float, af_mul_t>(qL, qH, tdims);
auto sigma = arithOp<float, af_mul_t>(sqrd, op2, tdims);
vector<af_seq> sliceIndex(4, af_span);
sliceIndex[0] = {double(b), double(b), 1};
auto binRes = createSubArray<float>(sigmas, sliceIndex, false);
copyArray(binRes, sigma);
}
dim4 odims = sigmas.dims();
odims[0] = 1;
Array<float> thresh = createEmptyArray<float>(odims);
Array<uint> locs = createEmptyArray<uint>(odims);
ireduce<af_max_t, float>(thresh, locs, sigmas, 0);
return cast<float, uint>(tile(locs, dim4(iDims[0], iDims[1], 1, 1)));
}
Array<float> normalize(const Array<float>& supEdges, const float minVal,
const float maxVal) {
auto minArray = createValueArray<float>(supEdges.dims(), minVal);
auto diff = arithOp<float, af_sub_t>(supEdges, minArray, supEdges.dims());
auto denom = createValueArray<float>(supEdges.dims(), (maxVal - minVal));
return arithOp<float, af_div_t>(diff, denom, supEdges.dims());
}
pair<Array<char>, Array<char>> computeCandidates(const Array<float>& supEdges,
const float t1,
const af_canny_threshold ct,
const float t2) {
float maxVal = reduce_all<af_max_t, float, float>(supEdges);
auto NUM_BINS = static_cast<unsigned>(maxVal);
auto lowRatio = createValueArray<float>(supEdges.dims(), t1);
switch (ct) { // NOLINT(hicpp-multiway-paths-covered)
case AF_CANNY_THRESHOLD_AUTO_OTSU: {
auto T2 = otsuThreshold(supEdges, NUM_BINS, maxVal);
auto T1 = arithOp<float, af_mul_t>(T2, lowRatio, T2.dims());
Array<char> weak1 =
logicOp<float, af_ge_t>(supEdges, T1, supEdges.dims());
Array<char> weak2 =
logicOp<float, af_lt_t>(supEdges, T2, supEdges.dims());
Array<char> weak =
logicOp<char, af_and_t>(weak1, weak2, weak1.dims());
Array<char> strong =
logicOp<float, af_ge_t>(supEdges, T2, supEdges.dims());
return make_pair(strong, weak);
};
default: {
float minVal = reduce_all<af_min_t, float, float>(supEdges);
auto normG = normalize(supEdges, minVal, maxVal);
auto T2 = createValueArray<float>(supEdges.dims(), t2);
auto T1 = createValueArray<float>(supEdges.dims(), t1);
Array<char> weak1 =
logicOp<float, af_ge_t>(normG, T1, normG.dims());
Array<char> weak2 =
logicOp<float, af_lt_t>(normG, T2, normG.dims());
Array<char> weak =
logicOp<char, af_and_t>(weak1, weak2, weak1.dims());
Array<char> strong =
logicOp<float, af_ge_t>(normG, T2, normG.dims());
return std::make_pair(strong, weak);
};
}
}
template<typename T>
af_array cannyHelper(const Array<T>& in, const float t1,
const af_canny_threshold ct, const float t2,
const unsigned sw, const bool isf) {
static const vector<float> v{-0.11021f, -0.23691f, -0.30576f, -0.23691f,
-0.11021f};
Array<float> cFilter = createHostDataArray<float>(dim4(5, 1), v.data());
Array<float> rFilter = createHostDataArray<float>(dim4(1, 5), v.data());
// Run separable convolution to smooth the input image
Array<float> smt =
convolve2<float, float>(cast<float, T>(in), cFilter, rFilter, false);
auto g = sobelDerivatives<float, float>(smt, sw);
Array<float> gx = g.first;
Array<float> gy = g.second;
Array<float> gmag = gradientMagnitude(gx, gy, isf);
Array<float> supEdges = nonMaximumSuppression(gmag, gx, gy);
auto swpair = computeCandidates(supEdges, t1, ct, t2);
return getHandle(edgeTrackingByHysteresis(swpair.first, swpair.second));
}
af_err af_canny(af_array* out, const af_array in, const af_canny_threshold ct,
const float t1, const float t2, const unsigned sw,
const bool isf) {
try {
const ArrayInfo& info = getInfo(in);
af::dim4 dims = info.dims();
DIM_ASSERT(2, (dims.ndims() >= 2));
// Input should be a minimum of 5x5 image
// since the gaussian filter used for smoothing
// the input is of 5x5 size. It's not mandatory but
// it is essentially of no use if image is less than 5x5
DIM_ASSERT(2, (dims[0] >= 5 && dims[1] >= 5));
ARG_ASSERT(5, (sw == 3));
af_array output;
af_dtype type = info.getType();
switch (type) {
case f32:
output = cannyHelper<float>(getArray<float>(in), t1, ct, t2, sw,
isf);
break;
case f64:
output = cannyHelper<double>(getArray<double>(in), t1, ct, t2,
sw, isf);
break;
case s32:
output =
cannyHelper<int>(getArray<int>(in), t1, ct, t2, sw, isf);
break;
case u32:
output =
cannyHelper<uint>(getArray<uint>(in), t1, ct, t2, sw, isf);
break;
case s16:
output = cannyHelper<short>(getArray<short>(in), t1, ct, t2, sw,
isf);
break;
case u16:
output = cannyHelper<ushort>(getArray<ushort>(in), t1, ct, t2,
sw, isf);
break;
case u8:
output = cannyHelper<uchar>(getArray<uchar>(in), t1, ct, t2, sw,
isf);
break;
default: TYPE_ERROR(1, type);
}
// output array is binary array
std::swap(output, *out);
}
CATCHALL;
return AF_SUCCESS;
}
<commit_msg>Fix canny by resizing the sigma array to the correct size<commit_after>/*******************************************************
* Copyright (c) 2017, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <Array.hpp>
#include <arith.hpp>
#include <backend.hpp>
#include <canny.hpp>
#include <common/err_common.hpp>
#include <complex.hpp>
#include <convolve.hpp>
#include <copy.hpp>
#include <handle.hpp>
#include <histogram.hpp>
#include <iota.hpp>
#include <ireduce.hpp>
#include <logic.hpp>
#include <reduce.hpp>
#include <sobel.hpp>
#include <tile.hpp>
#include <transpose.hpp>
#include <unary.hpp>
#include <af/defines.h>
#include <af/dim4.hpp>
#include <af/image.h>
#include <af/seq.h>
#include <utility>
#include <vector>
using af::dim4;
using detail::arithOp;
using detail::Array;
using detail::cast;
using detail::convolve2;
using detail::createEmptyArray;
using detail::createHostDataArray;
using detail::createSubArray;
using detail::createValueArray;
using detail::histogram;
using detail::iota;
using detail::ireduce;
using detail::logicOp;
using detail::reduce;
using detail::reduce_all;
using detail::sobelDerivatives;
using detail::uchar;
using detail::uint;
using detail::unaryOp;
using detail::ushort;
using std::make_pair;
using std::pair;
using std::vector;
Array<float> gradientMagnitude(const Array<float>& gx, const Array<float>& gy,
const bool& isf) {
using detail::abs;
if (isf) {
Array<float> gx2 = abs<float, float>(gx);
Array<float> gy2 = abs<float, float>(gy);
return arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
} else {
Array<float> gx2 = arithOp<float, af_mul_t>(gx, gx, gx.dims());
Array<float> gy2 = arithOp<float, af_mul_t>(gy, gy, gy.dims());
Array<float> sg = arithOp<float, af_add_t>(gx2, gy2, gx2.dims());
return unaryOp<float, af_sqrt_t>(sg);
}
}
Array<float> otsuThreshold(const Array<float>& supEdges,
const unsigned NUM_BINS, const float maxVal) {
Array<uint> hist = histogram<float>(supEdges, NUM_BINS, 0, maxVal, false);
const dim4& hDims = hist.dims();
// reduce along histogram dimension i.e. 0th dimension
auto totals = reduce<af_add_t, uint, float>(hist, 0);
// tile histogram total along 0th dimension
auto ttotals = tile(totals, dim4(hDims[0]));
// pixel frequency probabilities
auto probability =
arithOp<float, af_div_t>(cast<float, uint>(hist), ttotals, hDims);
vector<af_seq> seqBegin(4, af_span);
vector<af_seq> seqRest(4, af_span);
seqBegin[0] = af_make_seq(0, static_cast<double>(hDims[0] - 1), 1);
seqRest[0] = af_make_seq(0, static_cast<double>(hDims[0] - 1), 1);
const dim4& iDims = supEdges.dims();
dim4 sigmaDims(NUM_BINS - 1, hDims[1], hDims[2], hDims[3]);
Array<float> sigmas = createEmptyArray<float>(sigmaDims);
for (unsigned b = 0; b < (NUM_BINS - 1); ++b) {
seqBegin[0].end = static_cast<double>(b);
seqRest[0].begin = static_cast<double>(b + 1);
auto frontPartition = createSubArray(probability, seqBegin, false);
auto endPartition = createSubArray(probability, seqRest, false);
auto qL = reduce<af_add_t, float, float>(frontPartition, 0);
auto qH = reduce<af_add_t, float, float>(endPartition, 0);
const dim4 fdims(b + 1, hDims[1], hDims[2], hDims[3]);
const dim4 edims(NUM_BINS - 1 - b, hDims[1], hDims[2], hDims[3]);
const dim4 tdims(1, hDims[1], hDims[2], hDims[3]);
auto frontWeights = iota<float>(dim4(b + 1), tdims);
auto endWeights = iota<float>(dim4(NUM_BINS - 1 - b), tdims);
auto offsetValues = createValueArray<float>(edims, b + 1);
endWeights = arithOp<float, af_add_t>(endWeights, offsetValues, edims);
auto __muL =
arithOp<float, af_mul_t>(frontPartition, frontWeights, fdims);
auto __muH = arithOp<float, af_mul_t>(endPartition, endWeights, edims);
auto _muL = reduce<af_add_t, float, float>(__muL, 0);
auto _muH = reduce<af_add_t, float, float>(__muH, 0);
auto muL = arithOp<float, af_div_t>(_muL, qL, tdims);
auto muH = arithOp<float, af_div_t>(_muH, qH, tdims);
auto TWOS = createValueArray<float>(tdims, 2.0f);
auto diff = arithOp<float, af_sub_t>(muL, muH, tdims);
auto sqrd = arithOp<float, af_pow_t>(diff, TWOS, tdims);
auto op2 = arithOp<float, af_mul_t>(qL, qH, tdims);
auto sigma = arithOp<float, af_mul_t>(sqrd, op2, tdims);
vector<af_seq> sliceIndex(4, af_span);
sliceIndex[0] = {double(b), double(b), 1};
auto binRes = createSubArray<float>(sigmas, sliceIndex, false);
copyArray(binRes, sigma);
}
dim4 odims = sigmas.dims();
odims[0] = 1;
Array<float> thresh = createEmptyArray<float>(odims);
Array<uint> locs = createEmptyArray<uint>(odims);
ireduce<af_max_t, float>(thresh, locs, sigmas, 0);
return cast<float, uint>(tile(locs, dim4(iDims[0], iDims[1], 1, 1)));
}
Array<float> normalize(const Array<float>& supEdges, const float minVal,
const float maxVal) {
auto minArray = createValueArray<float>(supEdges.dims(), minVal);
auto diff = arithOp<float, af_sub_t>(supEdges, minArray, supEdges.dims());
auto denom = createValueArray<float>(supEdges.dims(), (maxVal - minVal));
return arithOp<float, af_div_t>(diff, denom, supEdges.dims());
}
pair<Array<char>, Array<char>> computeCandidates(const Array<float>& supEdges,
const float t1,
const af_canny_threshold ct,
const float t2) {
float maxVal = reduce_all<af_max_t, float, float>(supEdges);
auto NUM_BINS = static_cast<unsigned>(maxVal);
auto lowRatio = createValueArray<float>(supEdges.dims(), t1);
switch (ct) { // NOLINT(hicpp-multiway-paths-covered)
case AF_CANNY_THRESHOLD_AUTO_OTSU: {
auto T2 = otsuThreshold(supEdges, NUM_BINS, maxVal);
auto T1 = arithOp<float, af_mul_t>(T2, lowRatio, T2.dims());
Array<char> weak1 =
logicOp<float, af_ge_t>(supEdges, T1, supEdges.dims());
Array<char> weak2 =
logicOp<float, af_lt_t>(supEdges, T2, supEdges.dims());
Array<char> weak =
logicOp<char, af_and_t>(weak1, weak2, weak1.dims());
Array<char> strong =
logicOp<float, af_ge_t>(supEdges, T2, supEdges.dims());
return make_pair(strong, weak);
};
default: {
float minVal = reduce_all<af_min_t, float, float>(supEdges);
auto normG = normalize(supEdges, minVal, maxVal);
auto T2 = createValueArray<float>(supEdges.dims(), t2);
auto T1 = createValueArray<float>(supEdges.dims(), t1);
Array<char> weak1 =
logicOp<float, af_ge_t>(normG, T1, normG.dims());
Array<char> weak2 =
logicOp<float, af_lt_t>(normG, T2, normG.dims());
Array<char> weak =
logicOp<char, af_and_t>(weak1, weak2, weak1.dims());
Array<char> strong =
logicOp<float, af_ge_t>(normG, T2, normG.dims());
return std::make_pair(strong, weak);
};
}
}
template<typename T>
af_array cannyHelper(const Array<T>& in, const float t1,
const af_canny_threshold ct, const float t2,
const unsigned sw, const bool isf) {
static const vector<float> v{-0.11021f, -0.23691f, -0.30576f, -0.23691f,
-0.11021f};
Array<float> cFilter = createHostDataArray<float>(dim4(5, 1), v.data());
Array<float> rFilter = createHostDataArray<float>(dim4(1, 5), v.data());
// Run separable convolution to smooth the input image
Array<float> smt =
convolve2<float, float>(cast<float, T>(in), cFilter, rFilter, false);
auto g = sobelDerivatives<float, float>(smt, sw);
Array<float> gx = g.first;
Array<float> gy = g.second;
Array<float> gmag = gradientMagnitude(gx, gy, isf);
Array<float> supEdges = nonMaximumSuppression(gmag, gx, gy);
auto swpair = computeCandidates(supEdges, t1, ct, t2);
return getHandle(edgeTrackingByHysteresis(swpair.first, swpair.second));
}
af_err af_canny(af_array* out, const af_array in, const af_canny_threshold ct,
const float t1, const float t2, const unsigned sw,
const bool isf) {
try {
const ArrayInfo& info = getInfo(in);
af::dim4 dims = info.dims();
DIM_ASSERT(2, (dims.ndims() >= 2));
// Input should be a minimum of 5x5 image
// since the gaussian filter used for smoothing
// the input is of 5x5 size. It's not mandatory but
// it is essentially of no use if image is less than 5x5
DIM_ASSERT(2, (dims[0] >= 5 && dims[1] >= 5));
ARG_ASSERT(5, (sw == 3));
af_array output;
af_dtype type = info.getType();
switch (type) {
case f32:
output = cannyHelper<float>(getArray<float>(in), t1, ct, t2, sw,
isf);
break;
case f64:
output = cannyHelper<double>(getArray<double>(in), t1, ct, t2,
sw, isf);
break;
case s32:
output =
cannyHelper<int>(getArray<int>(in), t1, ct, t2, sw, isf);
break;
case u32:
output =
cannyHelper<uint>(getArray<uint>(in), t1, ct, t2, sw, isf);
break;
case s16:
output = cannyHelper<short>(getArray<short>(in), t1, ct, t2, sw,
isf);
break;
case u16:
output = cannyHelper<ushort>(getArray<ushort>(in), t1, ct, t2,
sw, isf);
break;
case u8:
output = cannyHelper<uchar>(getArray<uchar>(in), t1, ct, t2, sw,
isf);
break;
default: TYPE_ERROR(1, type);
}
// output array is binary array
std::swap(output, *out);
}
CATCHALL;
return AF_SUCCESS;
}
<|endoftext|> |
<commit_before><commit_msg>Added a single test for MemoryArena, just to get things started.<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2012-2013 Twitter4QML Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Twitter4QML 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 TWITTER4QML 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 "abstracttwitter4qmltest.h"
#include <hometimeline.h>
#include <QtCore/QDateTime>
class tst_ratelimit : public AbstractTwitter4QMLTest
{
Q_OBJECT
private Q_SLOTS:
void run();
};
void tst_ratelimit::run()
{
HomeTimeline timeline;
QVERIFY2(reload(&timeline), "HomeTimeline::reload()");
QVERIFY2(timeline.xrlLimit() > 0, "AbstractTwitterModel::xrlLimit()");
QVERIFY2(timeline.xrlRemaining() > 0, "AbstractTwitterModel::xrlRemaining()");
//RateLimitReset of hometimeline is always within 15min(900sec).
qDebug() << timeline.xrlReset() << QDateTime::currentDateTime().secsTo(timeline.xrlReset());
QVERIFY2(QDateTime::currentDateTime().secsTo(timeline.xrlReset()) < 60 * 15, "AbstractTwitterModel::xrlReset()");
}
QTEST_MAIN(tst_ratelimit)
#include "tst_ratelimit.moc"
<commit_msg>fix tst_ratelimit failure<commit_after>/* Copyright (c) 2012-2013 Twitter4QML Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Twitter4QML 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 TWITTER4QML 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 "abstracttwitter4qmltest.h"
#include <hometimeline.h>
#include <QtCore/QDateTime>
class tst_ratelimit : public AbstractTwitter4QMLTest
{
Q_OBJECT
private Q_SLOTS:
void run();
};
void tst_ratelimit::run()
{
HomeTimeline timeline;
QVERIFY2(reload(&timeline), "HomeTimeline::reload()");
QVERIFY2(timeline.xrlLimit() > 0, "AbstractTwitterModel::xrlLimit()");
QVERIFY2(timeline.xrlRemaining() > 0, "AbstractTwitterModel::xrlRemaining()");
//RateLimitReset of hometimeline is always within 15min(900sec).
qDebug() << timeline.xrlReset() << QDateTime::currentDateTime().secsTo(timeline.xrlReset());
QVERIFY2(QDateTime::currentDateTime().secsTo(timeline.xrlReset()) <= 60 * 15, "AbstractTwitterModel::xrlReset()");
}
QTEST_MAIN(tst_ratelimit)
#include "tst_ratelimit.moc"
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include <memory>
#include <vector>
#include "blackhole/logger.hpp"
namespace blackhole {
class handler_t;
class record_t;
class scoped_t;
} // namespace blackhole
namespace blackhole {
class root_logger_t : public logger_t {
public:
typedef std::function<auto(const record_t&) -> bool> filter_t;
private:
struct sync_t;
std::unique_ptr<sync_t> sync;
struct inner_t;
std::shared_ptr<inner_t> inner;
public:
/// \note you can create a logger with no handlers, it'll just drop all messages.
root_logger_t(std::vector<std::unique_ptr<handler_t>> handlers);
root_logger_t(filter_t filter, std::vector<std::unique_ptr<handler_t>> handlers);
root_logger_t(const root_logger_t& other) = delete;
root_logger_t(root_logger_t&& other);
~root_logger_t();
auto operator=(const root_logger_t& other) -> root_logger_t& = delete;
auto operator=(root_logger_t&& other) noexcept -> root_logger_t&;
/// Replaces the current logger filter function with the given one.
///
/// Any logging event for which the filter function returns `false` is rejected.
///
/// \warning the function must be thread-safe.
auto filter(filter_t fn) -> void;
auto log(int severity, string_view pattern) -> void;
auto log(int severity, string_view pattern, attribute_pack& pack) -> void;
auto log(int severity, string_view pattern, attribute_pack& pack, const format_t& fn) -> void;
};
} // namespace blackhole
<commit_msg>refactor(root): make move constructor noexcept<commit_after>#pragma once
#include <functional>
#include <memory>
#include <vector>
#include "blackhole/logger.hpp"
namespace blackhole {
class handler_t;
class record_t;
class scoped_t;
} // namespace blackhole
namespace blackhole {
class root_logger_t : public logger_t {
public:
typedef std::function<auto(const record_t&) -> bool> filter_t;
private:
struct sync_t;
std::unique_ptr<sync_t> sync;
struct inner_t;
std::shared_ptr<inner_t> inner;
public:
/// \note you can create a logger with no handlers, it'll just drop all messages.
root_logger_t(std::vector<std::unique_ptr<handler_t>> handlers);
root_logger_t(filter_t filter, std::vector<std::unique_ptr<handler_t>> handlers);
root_logger_t(const root_logger_t& other) = delete;
root_logger_t(root_logger_t&& other) noexcept;
~root_logger_t();
auto operator=(const root_logger_t& other) -> root_logger_t& = delete;
auto operator=(root_logger_t&& other) noexcept -> root_logger_t&;
/// Replaces the current logger filter function with the given one.
///
/// Any logging event for which the filter function returns `false` is rejected.
///
/// \warning the function must be thread-safe.
auto filter(filter_t fn) -> void;
auto log(int severity, string_view pattern) -> void;
auto log(int severity, string_view pattern, attribute_pack& pack) -> void;
auto log(int severity, string_view pattern, attribute_pack& pack, const format_t& fn) -> void;
};
} // namespace blackhole
<|endoftext|> |
<commit_before>/* $Id: OutputFormat.C,v 1.34 2008-07-31 18:07:52 phruksar Exp $ */
#include "OutputFormat.h"
#include "GammaSrc.h"
#include "Input/CoolingTime.h"
#include "Input/Volume.h"
#include "Input/Mixture.h"
#include "Input/Loading.h"
#include "Chains/Node.h"
const char *Out_Types = "ucnstabgpdfew";
const int nOutTypes = 14;
const int firstResponse = 2;
const int lastSingularResponse = 13;
const char *Out_Types_Str[nOutTypes] = {
"Response Units",
"Break-down by Constituent",
"Number Density [atoms%s]",
"Specific Activity [%s%s]",
"Total Decay Heat [W%s]",
"Alpha Decay Heat [W%s]",
"Beta Decay Heat [W%s]",
"Gamma Decay Heat [W%s]",
"Photon Source Distribution [gammas/s%s] : %s\n\t with Specific Activity [%s%s]",
"Contact Dose [ Sv/hr] : %s",
"Folded (Adjoint/Biological) Dose [Sv/hr] : %s",
"Exposure Rate [mR/hr] - Infinite Line Approximation: %s",
"Exposure Rate [mR/hr] - Cylindrical Volume Source: %s",
"WDR/Clearance index"};
/***************************
********* Service *********
**************************/
/** When called without arguments, the default constructor creates a
blank list head with no problem data. Otherwise, it sets the
'resolution' to the first argument and initializes the 'next'
pointer to NULL. */
OutputFormat::OutputFormat(int type)
{
resolution = type;
outTypes = 0;
actUnits = new char[3];
strcpy(actUnits,"Bq");
actMult = 1;
normUnits = new char[4];
strcpy(normUnits,"/cm3");
normType = 1;
gammaSrc = NULL;
contactDose = NULL;
next = NULL;
}
OutputFormat::OutputFormat(const OutputFormat& o) :
resolution(o.resolution), outTypes(o.outTypes), actMult(o.actMult),
normType(o.normType)
{
actUnits = new char[strlen(o.actUnits)+1];
strcpy(actUnits,o.actUnits);
normUnits = new char[strlen(o.normUnits)+1];
strcpy(normUnits,o.normUnits);
next = NULL;
}
OutputFormat::~OutputFormat()
{
delete actUnits;
delete normUnits;
delete gammaSrc;
delete contactDose;
delete next;
}
/** The correct implementation of this operator must ensure that
previously allocated space is returned to the free store before
allocating new space into which to copy the object. Note that
'next' is NOT copied, the object will continue to be part of the
same list unless explicitly changed. */
OutputFormat& OutputFormat::operator=(const OutputFormat& o)
{
if (this == &o)
return *this;
resolution = o.resolution;
outTypes = o.outTypes;
delete actUnits;
actUnits = new char[strlen(o.actUnits)+1];
strcpy(actUnits,o.actUnits);
actMult = o.actMult;
delete normUnits;
normUnits = new char[strlen(o.normUnits)+1];
strcpy(normUnits,o.normUnits);
normType = o.normType;
return *this;
}
/***************************
********** Input **********
**************************/
OutputFormat* OutputFormat::getOutFmts(istream& input)
{
const char *Out_Res = " izm";
int type;
char token[64];
char *fileNamePtr;
input >> token;
type = strchr(Out_Res,tolower(token[0]))-Out_Res;
next = new OutputFormat(type);
verbose(2,"Added output at resolution %d (%s)",type,token);
/* read a list of output types until keyword "end" */
clearComment(input);
input >> token;
while (strcmp(token,"end"))
{
/* match the first character of the type in the constant string */
type = strchr(Out_Types,tolower(token[0]))-Out_Types;
if (type<0)
error(230,"Output type '%s' is not currently supported.",
token);
verbose(3,"Added output type %d (%s)",1<<type,token);
switch (1<<type)
{
case OUTFMT_UNITS:
next->outTypes |= 1<<type;
delete next->actUnits;
input >> token;
next->actUnits = new char[strlen(token)+1];
strcpy(next->actUnits,token);
next->actMult = (tolower(token[0]) == 'c'?BQ_CI:1);
delete next->normUnits;
input >> token;
next->normUnits = new char[strlen(token)+2];
strcpy((next->normUnits)+1,token);
if (tolower(token[0]) == 'v') {
next->normUnits[0] = ' ';
} else {
next->normUnits[0] = '/';
}
switch (tolower(token[0]))
{
case 'm':
next->normType = OUTNORM_M3;
break;
case 'g':
next->normType = OUTNORM_G;
break;
case 'k':
next->normType = OUTNORM_KG;
break;
case 'v':
next->normType = OUTNORM_VOL_INT;
break;
default:
next->normType = OUTNORM_CM3;
break;
}
break;
case OUTFMT_WDR:
next->outTypes |= 1<<type;
input >> token;
fileNamePtr = new char[strlen(token)+1];
strcpy(fileNamePtr,token);
next->wdrFilenames.insert(fileNamePtr);
verbose(4,"Added WDR/Clearance file %s", token);
break;
case OUTFMT_SRC:
next->outTypes |= 1<<type;
/* set gamma source file name here */
next->gammaSrc= new GammaSrc(input,GAMMASRC_RAW_SRC);
break;
case OUTFMT_CDOSE:
//Need to determine which dose approximation is defined
char approx_token[64];
input >> approx_token;
if (approx_token[0] == 'l' || approx_token[0] == 'L') {
//adjust outTypes
//next->outTypes -= OUTFMT_CDOSE;
next->outTypes += OUTFMT_EXP;
/* setup gamma source for exposure dose with line approximation */
next->exposureDose = new GammaSrc(input, GAMMASRC_EXPOSURE);
}
else if ( approx_token[0] == 'v' || approx_token[0] == 'V' ) {
//adjust outTypes
//next->outTypes -= OUTFMT_CDOSE;
next->outTypes += OUTFMT_EXP_CYL_VOL;
/* setup gamma source for exposure dose with line approximation */
next->exposureCylVolDose = new GammaSrc(input, GAMMASRC_EXPOSURE_CYLINDRICAL_VOLUME);
}
else if (approx_token[0] == 'c' || approx_token[0] == 'C') {
next->outTypes |= 1<<type;
/* setup gamma source for contact dose */
next->contactDose = new GammaSrc(input,GAMMASRC_CONTACT);
}
//Add more types of dose output here
break;
case OUTFMT_ADJ:
/* setup gamma source for adjoint dose */
next->adjointDose = new GammaSrc(input,GAMMASRC_ADJOINT);
break;
default:
/* use logical and to set the correct bit in the outTypes field */
next->outTypes |= 1<<type;
break;
}
clearComment(input);
input >> token;
}
return next;
}
/** It does this by calling the write() function on the list of intervals,
zones or mixtures, as determined by the 'resolution' member. The last
argument is the kza number for the target isotope for which the
current invocation is being called. */
void OutputFormat::write(Volume* volList, Mixture* mixList, Loading* loadList,
CoolingTime *coolList, int targetKza)
{
OutputFormat *ptr = this;
GammaSrc *tmpGammaSrc = NULL;
char buffer[256];
int outTypeNum;
/* for each output description */
while (ptr->next != NULL)
{
ptr = ptr->next;
/* write a header */
switch(ptr->resolution)
{
case OUTRES_INT:
cout << "Interval output requested:"<< endl;
break;
case OUTRES_ZONE:
cout << "Zone output requested:"<< endl;
break;
case OUTRES_MIX:
cout << "Mixture output requested:"<< endl;
break;
}
/* list the reponses and features to come */
/* units */
outTypeNum = 0;
cout << "\t" << Out_Types_Str[outTypeNum] << ": "
<< ptr->actUnits << " " << ptr->normUnits << endl;
/* regular singular responses */
for (++outTypeNum;outTypeNum<lastSingularResponse;outTypeNum++)
if (ptr->outTypes & 1<<outTypeNum)
{
switch(1<<outTypeNum)
{
case (OUTFMT_ACT):
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_SRC) :
sprintf(buffer,Out_Types_Str[outTypeNum],
/* deliver gamma src filename, */
ptr->normUnits, ptr->gammaSrc->getFileName(),ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_CDOSE) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->contactDose->getFileName());
break;
case (OUTFMT_ADJ) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->adjointDose->getFileName());
break;
case (OUTFMT_EXP) :
sprintf(buffer, Out_Types_Str[outTypeNum],
ptr->exposureDose->getFileName());
break;
case (OUTFMT_EXP_CYL_VOL) :
sprintf(buffer, Out_Types_Str[outTypeNum],
ptr->exposureCylVolDose->getFileName());
break;
default:
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->normUnits);
}
cout << "\t" << buffer << endl;
}
/* WDR header */
if (ptr->outTypes & OUTFMT_WDR)
for(filenameList::iterator fileName = ptr->wdrFilenames.begin();
fileName != ptr->wdrFilenames.end(); ++fileName)
cout << "\t" << Out_Types_Str[outTypeNum] << ": "
<< *fileName << endl;
cout << endl << endl;
/* set units for activity */
Result::setNorm(ptr->actMult,ptr->normType);
/* for each indicated response */
for (outTypeNum=firstResponse;outTypeNum<lastSingularResponse;outTypeNum++) {
if (ptr->outTypes & 1<<outTypeNum)
{
/* write a response title */
switch(1<<outTypeNum)
{
case(OUTFMT_ACT):
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_SRC) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->normUnits, ptr->gammaSrc->getFileName(),ptr->actUnits,ptr->normUnits);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->gammaSrc);
break;
case (OUTFMT_CDOSE) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->contactDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->contactDose->setGammaAttenCoef(mixList);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->contactDose);
break;
case (OUTFMT_ADJ) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->adjointDose->getFileName());
/* read/set flux-dose conversion factors */
ptr->adjointDose->setAdjDoseData(volList);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->adjointDose);
break;
case (OUTFMT_EXP) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->exposureDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->exposureDose->setGammaAttenCoef(mixList);
Result::setGammaSrc(ptr->exposureDose);
break;
case (OUTFMT_EXP_CYL_VOL) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->exposureCylVolDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->exposureCylVolDose->setGammaAttenCoef(mixList);
Result::setGammaSrc(ptr->exposureCylVolDose);
break;
default:
sprintf(buffer,Out_Types_Str[outTypeNum],ptr->normUnits);
}
cout << "*** " << buffer << " ***" << endl;
Result::setReminderStr(buffer);
/* call write() on the appropriate object determined by
the resulotition */
switch(ptr->resolution)
{
case OUTRES_INT:
volList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_ZONE:
loadList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_MIX:
mixList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
}
cout << endl << endl << endl;
}
}
if (ptr->outTypes & OUTFMT_WDR)
{
cout << "*** WDR ***" << endl;
for(filenameList::iterator fileName = ptr->wdrFilenames.begin();
fileName != ptr->wdrFilenames.end(); ++fileName)
{
/* write a response title */
cout << "*** " << Out_Types_Str[outTypeNum] << ": "
<< *fileName << " ***" << endl;
sprintf(buffer,"%s: %s",Out_Types_Str[outTypeNum],*fileName);
Result::setReminderStr(buffer);
Node::loadWDR(*fileName);
/* call write() on the appropriate object determined by
the resulotition */
switch(ptr->resolution)
{
case OUTRES_INT:
volList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_ZONE:
loadList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_MIX:
mixList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
}
delete [] *fileName;
cout << endl << endl << endl;
}
}
}
}
<commit_msg>Fix bug in parsing output options for new dose approximations.<commit_after>/* $Id: OutputFormat.C,v 1.35 2009-02-17 21:51:28 wilsonp Exp $ */
#include "OutputFormat.h"
#include "GammaSrc.h"
#include "Input/CoolingTime.h"
#include "Input/Volume.h"
#include "Input/Mixture.h"
#include "Input/Loading.h"
#include "Chains/Node.h"
const char *Out_Types = "ucnstabgpdflvw";
const int nOutTypes = 14;
const int firstResponse = 2;
const int lastSingularResponse = 13;
const char *Out_Types_Str[nOutTypes] = {
"Response Units",
"Break-down by Constituent",
"Number Density [atoms%s]",
"Specific Activity [%s%s]",
"Total Decay Heat [W%s]",
"Alpha Decay Heat [W%s]",
"Beta Decay Heat [W%s]",
"Gamma Decay Heat [W%s]",
"Photon Source Distribution [gammas/s%s] : %s\n\t with Specific Activity [%s%s]",
"Contact Dose [ Sv/hr] : %s",
"Folded (Adjoint/Biological) Dose [Sv/hr] : %s",
"Exposure Rate [mR/hr] - Infinite Line Approximation: %s",
"Exposure Rate [mR/hr] - Cylindrical Volume Source: %s",
"WDR/Clearance index"};
/***************************
********* Service *********
**************************/
/** When called without arguments, the default constructor creates a
blank list head with no problem data. Otherwise, it sets the
'resolution' to the first argument and initializes the 'next'
pointer to NULL. */
OutputFormat::OutputFormat(int type)
{
resolution = type;
outTypes = 0;
actUnits = new char[3];
strcpy(actUnits,"Bq");
actMult = 1;
normUnits = new char[4];
strcpy(normUnits,"/cm3");
normType = 1;
gammaSrc = NULL;
contactDose = NULL;
next = NULL;
}
OutputFormat::OutputFormat(const OutputFormat& o) :
resolution(o.resolution), outTypes(o.outTypes), actMult(o.actMult),
normType(o.normType)
{
actUnits = new char[strlen(o.actUnits)+1];
strcpy(actUnits,o.actUnits);
normUnits = new char[strlen(o.normUnits)+1];
strcpy(normUnits,o.normUnits);
next = NULL;
}
OutputFormat::~OutputFormat()
{
delete actUnits;
delete normUnits;
delete gammaSrc;
delete contactDose;
delete next;
}
/** The correct implementation of this operator must ensure that
previously allocated space is returned to the free store before
allocating new space into which to copy the object. Note that
'next' is NOT copied, the object will continue to be part of the
same list unless explicitly changed. */
OutputFormat& OutputFormat::operator=(const OutputFormat& o)
{
if (this == &o)
return *this;
resolution = o.resolution;
outTypes = o.outTypes;
delete actUnits;
actUnits = new char[strlen(o.actUnits)+1];
strcpy(actUnits,o.actUnits);
actMult = o.actMult;
delete normUnits;
normUnits = new char[strlen(o.normUnits)+1];
strcpy(normUnits,o.normUnits);
normType = o.normType;
return *this;
}
/***************************
********** Input **********
**************************/
OutputFormat* OutputFormat::getOutFmts(istream& input)
{
const char *Out_Res = " izm";
int type;
char token[64];
char *fileNamePtr;
input >> token;
type = strchr(Out_Res,tolower(token[0]))-Out_Res;
next = new OutputFormat(type);
verbose(2,"Added output at resolution %d (%s)",type,token);
/* read a list of output types until keyword "end" */
clearComment(input);
input >> token;
while (strcmp(token,"end"))
{
/* match the first character of the type in the constant string */
type = strchr(Out_Types,tolower(token[0]))-Out_Types;
if (type<0)
error(230,"Output type '%s' is not currently supported.",
token);
verbose(3,"Added output type %d (%s)",1<<type,token);
switch (1<<type)
{
case OUTFMT_UNITS:
next->outTypes |= 1<<type;
delete next->actUnits;
input >> token;
next->actUnits = new char[strlen(token)+1];
strcpy(next->actUnits,token);
next->actMult = (tolower(token[0]) == 'c'?BQ_CI:1);
delete next->normUnits;
input >> token;
next->normUnits = new char[strlen(token)+2];
strcpy((next->normUnits)+1,token);
if (tolower(token[0]) == 'v') {
next->normUnits[0] = ' ';
} else {
next->normUnits[0] = '/';
}
switch (tolower(token[0]))
{
case 'm':
next->normType = OUTNORM_M3;
break;
case 'g':
next->normType = OUTNORM_G;
break;
case 'k':
next->normType = OUTNORM_KG;
break;
case 'v':
next->normType = OUTNORM_VOL_INT;
break;
default:
next->normType = OUTNORM_CM3;
break;
}
break;
case OUTFMT_WDR:
next->outTypes |= 1<<type;
input >> token;
fileNamePtr = new char[strlen(token)+1];
strcpy(fileNamePtr,token);
next->wdrFilenames.insert(fileNamePtr);
verbose(4,"Added WDR/Clearance file %s", token);
break;
case OUTFMT_SRC:
next->outTypes |= 1<<type;
/* set gamma source file name here */
next->gammaSrc= new GammaSrc(input,GAMMASRC_RAW_SRC);
break;
case OUTFMT_CDOSE:
//Need to determine which dose approximation is defined
char approx_token[64];
input >> approx_token;
if (approx_token[0] == 'l' || approx_token[0] == 'L') {
//adjust outTypes
//next->outTypes -= OUTFMT_CDOSE;
next->outTypes += OUTFMT_EXP;
/* setup gamma source for exposure dose with line approximation */
next->exposureDose = new GammaSrc(input, GAMMASRC_EXPOSURE);
}
else if ( approx_token[0] == 'v' || approx_token[0] == 'V' ) {
//adjust outTypes
//next->outTypes -= OUTFMT_CDOSE;
next->outTypes += OUTFMT_EXP_CYL_VOL;
/* setup gamma source for exposure dose with line approximation */
next->exposureCylVolDose = new GammaSrc(input, GAMMASRC_EXPOSURE_CYLINDRICAL_VOLUME);
}
else if (approx_token[0] == 'c' || approx_token[0] == 'C') {
next->outTypes |= 1<<type;
/* setup gamma source for contact dose */
next->contactDose = new GammaSrc(input,GAMMASRC_CONTACT);
}
//Add more types of dose output here
break;
case OUTFMT_ADJ:
/* setup gamma source for adjoint dose */
next->adjointDose = new GammaSrc(input,GAMMASRC_ADJOINT);
break;
default:
/* use logical and to set the correct bit in the outTypes field */
next->outTypes |= 1<<type;
break;
}
clearComment(input);
input >> token;
}
return next;
}
/** It does this by calling the write() function on the list of intervals,
zones or mixtures, as determined by the 'resolution' member. The last
argument is the kza number for the target isotope for which the
current invocation is being called. */
void OutputFormat::write(Volume* volList, Mixture* mixList, Loading* loadList,
CoolingTime *coolList, int targetKza)
{
OutputFormat *ptr = this;
GammaSrc *tmpGammaSrc = NULL;
char buffer[256];
int outTypeNum;
/* for each output description */
while (ptr->next != NULL)
{
ptr = ptr->next;
/* write a header */
switch(ptr->resolution)
{
case OUTRES_INT:
cout << "Interval output requested:"<< endl;
break;
case OUTRES_ZONE:
cout << "Zone output requested:"<< endl;
break;
case OUTRES_MIX:
cout << "Mixture output requested:"<< endl;
break;
}
/* list the reponses and features to come */
/* units */
outTypeNum = 0;
cout << "\t" << Out_Types_Str[outTypeNum] << ": "
<< ptr->actUnits << " " << ptr->normUnits << endl;
/* regular singular responses */
for (++outTypeNum;outTypeNum<lastSingularResponse;outTypeNum++)
if (ptr->outTypes & 1<<outTypeNum)
{
switch(1<<outTypeNum)
{
case (OUTFMT_ACT):
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_SRC) :
sprintf(buffer,Out_Types_Str[outTypeNum],
/* deliver gamma src filename, */
ptr->normUnits, ptr->gammaSrc->getFileName(),ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_CDOSE) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->contactDose->getFileName());
break;
case (OUTFMT_ADJ) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->adjointDose->getFileName());
break;
case (OUTFMT_EXP) :
sprintf(buffer, Out_Types_Str[outTypeNum],
ptr->exposureDose->getFileName());
break;
case (OUTFMT_EXP_CYL_VOL) :
sprintf(buffer, Out_Types_Str[outTypeNum],
ptr->exposureCylVolDose->getFileName());
break;
default:
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->normUnits);
}
cout << "\t" << buffer << endl;
}
/* WDR header */
if (ptr->outTypes & OUTFMT_WDR)
for(filenameList::iterator fileName = ptr->wdrFilenames.begin();
fileName != ptr->wdrFilenames.end(); ++fileName)
cout << "\t" << Out_Types_Str[outTypeNum] << ": "
<< *fileName << endl;
cout << endl << endl;
/* set units for activity */
Result::setNorm(ptr->actMult,ptr->normType);
/* for each indicated response */
for (outTypeNum=firstResponse;outTypeNum<lastSingularResponse;outTypeNum++) {
if (ptr->outTypes & 1<<outTypeNum)
{
/* write a response title */
switch(1<<outTypeNum)
{
case(OUTFMT_ACT):
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->actUnits,ptr->normUnits);
break;
case (OUTFMT_SRC) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->normUnits, ptr->gammaSrc->getFileName(),ptr->actUnits,ptr->normUnits);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->gammaSrc);
break;
case (OUTFMT_CDOSE) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->contactDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->contactDose->setGammaAttenCoef(mixList);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->contactDose);
break;
case (OUTFMT_ADJ) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->adjointDose->getFileName());
/* read/set flux-dose conversion factors */
ptr->adjointDose->setAdjDoseData(volList);
/* set gamma source to use for this */
Result::setGammaSrc(ptr->adjointDose);
break;
case (OUTFMT_EXP) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->exposureDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->exposureDose->setGammaAttenCoef(mixList);
Result::setGammaSrc(ptr->exposureDose);
break;
case (OUTFMT_EXP_CYL_VOL) :
sprintf(buffer,Out_Types_Str[outTypeNum],
ptr->exposureCylVolDose->getFileName());
/* setup gamma attenuation coefficients */
ptr->exposureCylVolDose->setGammaAttenCoef(mixList);
Result::setGammaSrc(ptr->exposureCylVolDose);
break;
default:
sprintf(buffer,Out_Types_Str[outTypeNum],ptr->normUnits);
}
cout << "*** " << buffer << " ***" << endl;
Result::setReminderStr(buffer);
/* call write() on the appropriate object determined by
the resulotition */
switch(ptr->resolution)
{
case OUTRES_INT:
volList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_ZONE:
loadList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_MIX:
mixList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
}
cout << endl << endl << endl;
}
}
if (ptr->outTypes & OUTFMT_WDR)
{
cout << "*** WDR ***" << endl;
for(filenameList::iterator fileName = ptr->wdrFilenames.begin();
fileName != ptr->wdrFilenames.end(); ++fileName)
{
/* write a response title */
cout << "*** " << Out_Types_Str[outTypeNum] << ": "
<< *fileName << " ***" << endl;
sprintf(buffer,"%s: %s",Out_Types_Str[outTypeNum],*fileName);
Result::setReminderStr(buffer);
Node::loadWDR(*fileName);
/* call write() on the appropriate object determined by
the resulotition */
switch(ptr->resolution)
{
case OUTRES_INT:
volList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_ZONE:
loadList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
case OUTRES_MIX:
mixList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,
coolList,targetKza,ptr->normType);
break;
}
delete [] *fileName;
cout << endl << endl << endl;
}
}
}
}
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief int type definition and macros
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
// std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)
#elif defined(__GNUC__)
#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)
#endif
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#ifdef _MSC_VER
#define CYBOZU_SNPRINTF _snprintf_s
#else
#define CYBOZU_SNPRINTF snprintf
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
} // cybozu
<commit_msg>same meanings of len at CYBOZU_SNPRINTF for VC/gcc<commit_after>#pragma once
/**
@file
@brief int type definition and macros
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
// std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)
#elif defined(__GNUC__)
#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)
#endif
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#ifdef _MSC_VER
#define CYBOZU_SNPRINTF(x, len, ...) _snprintf_s(x, len - 1, __VA_ARGS__)
#else
#define CYBOZU_SNPRINTF(x, len, ...) snprintf(x, len, __VA_ARGS__)
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
} // cybozu
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_DENSE_DESC_HPP
#define DLL_DENSE_DESC_HPP
#include "base_conf.hpp"
#include "tmp.hpp"
namespace dll {
/*!
* \brief Describe a dense layer.
*/
template <std::size_t visibles, std::size_t hiddens, typename... Parameters>
struct dense_desc {
static constexpr const std::size_t num_visible = visibles;
static constexpr const std::size_t num_hidden = hiddens;
using parameters = cpp::type_list<Parameters...>;
static constexpr const function activation_function = detail::get_value<activation<function::SIGMOID>, Parameters...>::value;
/*! The type used to store the weights */
using weight = typename detail::get_type<weight_type<float>, Parameters...>::value;
/*! The dense type */
using layer_t = dense_layer<dense_desc<visibles, hiddens, Parameters...>>;
static_assert(num_visible > 0, "There must be at least 1 visible unit");
static_assert(num_hidden > 0, "There must be at least 1 hidden unit");
//Make sure only valid types are passed to the configuration list
static_assert(
detail::is_valid<cpp::type_list<weight_type_id, dbn_only_id, activation_id>, Parameters...>::value,
"Invalid parameters type for rbm_desc");
};
} //end of dll namespace
#endif
<commit_msg>Fix assertion message<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_DENSE_DESC_HPP
#define DLL_DENSE_DESC_HPP
#include "base_conf.hpp"
#include "tmp.hpp"
namespace dll {
/*!
* \brief Describe a dense layer.
*/
template <std::size_t visibles, std::size_t hiddens, typename... Parameters>
struct dense_desc {
static constexpr const std::size_t num_visible = visibles;
static constexpr const std::size_t num_hidden = hiddens;
using parameters = cpp::type_list<Parameters...>;
static constexpr const function activation_function = detail::get_value<activation<function::SIGMOID>, Parameters...>::value;
/*! The type used to store the weights */
using weight = typename detail::get_type<weight_type<float>, Parameters...>::value;
/*! The dense type */
using layer_t = dense_layer<dense_desc<visibles, hiddens, Parameters...>>;
static_assert(num_visible > 0, "There must be at least 1 visible unit");
static_assert(num_hidden > 0, "There must be at least 1 hidden unit");
//Make sure only valid types are passed to the configuration list
static_assert(
detail::is_valid<cpp::type_list<weight_type_id, dbn_only_id, activation_id>, Parameters...>::value,
"Invalid parameters type for dense_desc");
};
} //end of dll namespace
#endif
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file traits.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__TRAITS_HPP
#define FL__UTIL__TRAITS_HPP
#include <Eigen/Dense>
#include "types.hpp"
namespace fl
{
/**
* \ingroup traits
* \def from_traits
* \brief Helper macro to import typedefs from the traits of a class
*
* typedef from_traits(SomeTypeName);
*
* is the short hand for
*
* typedef typename Traits<This>::SomeTypeName SomeTypeName;
*
* \note from_this(.) requires the typedef \c This of the current class
*/
#define from_traits(TypeName) typename Traits<This>::TypeName TypeName
#if defined(__GXX_EXPERIMENTAL_CXX0X__)
#define override
#endif
/**
* \ingroup traits
* \brief Generic trait template
*
* Filters, models and distributions may specify a \c Traits specialization
*/
template <typename> struct Traits { };
/**
* \ingroup traits
*
* \brief \c IsDynamic<int> trait for static dynamic-size checks.
*
* Generic IsDynamic<int> definition which evaluates to false.
*
* Examples
*
* static_assert(IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <int Size> struct IsDynamic
{
static_assert(Size > Eigen::Dynamic, "Invalid static size");
static constexpr bool value = false;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
* \brief \c IsDynamic<-1> or \c IsDynamic<Eigen::Dynamic> trait for static
* dynamic-size checks.
*
* A specialization IsDynamic<Eigen::Dynamic> definition which evaluates to
* true.
*
* Examples
*
* // overloaded operator bool ()
* static_assert(!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <> struct IsDynamic<Eigen::Dynamic>
{
static constexpr bool value = true;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
*
* \brief \c IsFixed<int> trait for static fixed-size checks.
*
* Generic IsFixed<int> definition which evaluates to true. This traits is the
* opposite of IsDynamic.
*
* Examples
*
* static_assert(IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value, "");
*
* // overloaded operator bool ()
* if (IsFixed<MyEigenMatrixType::SizeAtCompileTime>()) ...
*/
template <int Size> struct IsFixed
{
static_assert(Size > Eigen::Dynamic, "Invalid static size");
static constexpr bool value = true;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
* \brief \c IsFixed<-1> or \c IsFixed<Eigen::Dynamic> trait for static
* fixed-size checks.
*
* A specialization IsFixed<Eigen::Dynamic> definition which evaluates to
* false. This traits is the opposite of IsDynamic<Eigen::Dynamic>.
*
* Examples
*
* static_assert(!IsFixed<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (!IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <> struct IsFixed<Eigen::Dynamic>
{
static constexpr bool value = false;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
*
* \brief Mapps Eigen::Dynamic onto 0.
*
* For any type matrix or column vector the dimension is the number of rows,
* i.e. Matrix::RowsAtCompileTime. If the Matrix::SizeAtCompileTime enum is not
* equal Eigen::Dynamic (-1) the dimension is set to Matrix::RowsAtCompileTime.
* Otherwise, 0 is returned.
*
* Examples
*
* static_assert(DimensionOf<MyEigenMatrixType>() > 0, "Dim must be greater 0");
*
* static_assert(DimensionOf<MyEigenMatrixType>::value > 0, "Dim must be .. 0");
*
* Eigen::VectorXd vector(DimensionOf<MyEigenMatrixType>());
*/
template <typename Matrix> struct DimensionOf
{
enum : signed int { Value = IsFixed<Matrix::SizeAtCompileTime>()
? Matrix::RowsAtCompileTime
: 0 };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
* \brief Returns the compile time size of a matrix or vector.
*
* SizeOf<M>() is shorthand for M::SizeAtCompileTime
*/
template <typename Matrix> struct SizeOf
{
enum : signed int { Value = Matrix::SizeAtCompileTime };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
*
*/
template <int Dimension> struct ToDimension
{
enum : signed int { Value = Dimension == Eigen::Dynamic ? 0 : Dimension };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
*
* \brief Returns simple the max integer of A and B
*/
template <int A, int B> struct MaxOf
{
static constexpr int value = (A > B) ? A : B;
constexpr operator int () { return value; }
};
/**
* \ingroup traits
*
* \brief Returns simple the min integer of A and B
*/
template <int A, int B> struct MinOf
{
static constexpr int value = (A < B) ? A : B;
constexpr operator int () { return value; }
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <typename Variate>
struct SecondMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::Matrix<Real, Dimension, Dimension> Type;
};
/**
* \ingroup traits
*/
template <typename Variate>
struct FirstMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::Matrix<Real, Dimension, 1> Type;
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <typename Variate>
struct DiagonalSecondMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::DiagonalMatrix<Real, Dimension> Type;
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <>
struct SecondMomentOf<Real>
{
typedef Real Type;
};
/**
* \ingroup traits
*/
template <>
struct FirstMomentOf<Real>
{
typedef Real Type;
};
/**
* \ingroup traits
*/
template <typename Model> struct IsAdditive
{
enum: bool
{
Value = std::is_base_of<internal::AdditiveNoiseModelType, Model>::value
};
};
/**
* \ingroup traits
*/
template <typename Model> struct IsAdditiveUncorrelated
{
enum: bool
{
Value = std::is_base_of<
internal::AdditiveUncorrelatedNoiseModelType,
Model
>::value
};
};
/**
* \ingroup traits
*/
template <typename Model> struct IsNonAdditive
{
enum: bool
{
Value = std::is_base_of<internal::NonAdditiveNoiseModelType, Model>::value
};
};
/**
* \internal
* \ingroup traits
*/
template <typename Model, typename ...> struct AdditivityOf;
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Model, internal::AdditiveNoiseModelType>
{
typedef Additive<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Model, internal::NonAdditiveNoiseModelType>
{
typedef NonAdditive<Model> Type;
};
template <typename Model>
struct AdditivityOf<Additive<Model>>
{
typedef Additive<Model> Type;
};
template <typename Model>
struct AdditivityOf<NonAdditive<Model>>
{
typedef NonAdditive<Model> Type;
};
/**
* \ingroup traits
* \brief Provides access to the type of the model
*
* The model type will be one of the following
* - \c NonAdditive (Noise)
* - \c Additive (Noise)
* - \c AdditiveUncorrelated (Noise)
*/
template <typename Model> struct AdditivityOf<Model>
{
typedef typename AdditivityOf<Model, typename Model::Type>::Type Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model> struct RemoveAdditivityOf
{
typedef Model Type;
};
template <typename Model>
struct RemoveAdditivityOf<Additive<Model>>
{
typedef Model Type;
};
template <typename Model>
struct RemoveAdditivityOf<NonAdditive<Model>>
{
typedef Model Type;
};
/**
* \internal
*
* \ingroup traits
*/
template <typename Model>
struct ForwardLinearModelOnly
{
static_assert(std::is_base_of<internal::LinearModelType, Model>::value,
"The specified model is not linear!");
typedef Model Type;
};
}
#endif
<commit_msg>Added support of AdditiveUncorrelated in AdditivityOf<> and RemoveAdditivityOf<><commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file traits.hpp
* \date October 2014
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__TRAITS_HPP
#define FL__UTIL__TRAITS_HPP
#include <Eigen/Dense>
#include "types.hpp"
namespace fl
{
/**
* \ingroup traits
* \def from_traits
* \brief Helper macro to import typedefs from the traits of a class
*
* typedef from_traits(SomeTypeName);
*
* is the short hand for
*
* typedef typename Traits<This>::SomeTypeName SomeTypeName;
*
* \note from_this(.) requires the typedef \c This of the current class
*/
#define from_traits(TypeName) typename Traits<This>::TypeName TypeName
#if defined(__GXX_EXPERIMENTAL_CXX0X__)
#define override
#endif
/**
* \ingroup traits
* \brief Generic trait template
*
* Filters, models and distributions may specify a \c Traits specialization
*/
template <typename> struct Traits { };
/**
* \ingroup traits
*
* \brief \c IsDynamic<int> trait for static dynamic-size checks.
*
* Generic IsDynamic<int> definition which evaluates to false.
*
* Examples
*
* static_assert(IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <int Size> struct IsDynamic
{
static_assert(Size > Eigen::Dynamic, "Invalid static size");
static constexpr bool value = false;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
* \brief \c IsDynamic<-1> or \c IsDynamic<Eigen::Dynamic> trait for static
* dynamic-size checks.
*
* A specialization IsDynamic<Eigen::Dynamic> definition which evaluates to
* true.
*
* Examples
*
* // overloaded operator bool ()
* static_assert(!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (!IsDynamic<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <> struct IsDynamic<Eigen::Dynamic>
{
static constexpr bool value = true;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
*
* \brief \c IsFixed<int> trait for static fixed-size checks.
*
* Generic IsFixed<int> definition which evaluates to true. This traits is the
* opposite of IsDynamic.
*
* Examples
*
* static_assert(IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value, "");
*
* // overloaded operator bool ()
* if (IsFixed<MyEigenMatrixType::SizeAtCompileTime>()) ...
*/
template <int Size> struct IsFixed
{
static_assert(Size > Eigen::Dynamic, "Invalid static size");
static constexpr bool value = true;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
* \brief \c IsFixed<-1> or \c IsFixed<Eigen::Dynamic> trait for static
* fixed-size checks.
*
* A specialization IsFixed<Eigen::Dynamic> definition which evaluates to
* false. This traits is the opposite of IsDynamic<Eigen::Dynamic>.
*
* Examples
*
* static_assert(!IsFixed<MyEigenMatrixType::SizeAtCompileTime>(), "");
*
* if (!IsFixed<MyEigenMatrixType::SizeAtCompileTime>::value) ...
*/
template <> struct IsFixed<Eigen::Dynamic>
{
static constexpr bool value = false;
constexpr operator bool () { return value; }
};
/**
* \ingroup traits
*
* \brief Mapps Eigen::Dynamic onto 0.
*
* For any type matrix or column vector the dimension is the number of rows,
* i.e. Matrix::RowsAtCompileTime. If the Matrix::SizeAtCompileTime enum is not
* equal Eigen::Dynamic (-1) the dimension is set to Matrix::RowsAtCompileTime.
* Otherwise, 0 is returned.
*
* Examples
*
* static_assert(DimensionOf<MyEigenMatrixType>() > 0, "Dim must be greater 0");
*
* static_assert(DimensionOf<MyEigenMatrixType>::value > 0, "Dim must be .. 0");
*
* Eigen::VectorXd vector(DimensionOf<MyEigenMatrixType>());
*/
template <typename Matrix> struct DimensionOf
{
enum : signed int { Value = IsFixed<Matrix::SizeAtCompileTime>()
? Matrix::RowsAtCompileTime
: 0 };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
* \brief Returns the compile time size of a matrix or vector.
*
* SizeOf<M>() is shorthand for M::SizeAtCompileTime
*/
template <typename Matrix> struct SizeOf
{
enum : signed int { Value = Matrix::SizeAtCompileTime };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
*
*/
template <int Dimension> struct ToDimension
{
enum : signed int { Value = Dimension == Eigen::Dynamic ? 0 : Dimension };
constexpr operator int () { return Value; }
};
/**
* \ingroup traits
*
* \brief Returns simple the max integer of A and B
*/
template <int A, int B> struct MaxOf
{
static constexpr int value = (A > B) ? A : B;
constexpr operator int () { return value; }
};
/**
* \ingroup traits
*
* \brief Returns simple the min integer of A and B
*/
template <int A, int B> struct MinOf
{
static constexpr int value = (A < B) ? A : B;
constexpr operator int () { return value; }
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <typename Variate>
struct SecondMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::Matrix<Real, Dimension, Dimension> Type;
};
/**
* \ingroup traits
*/
template <typename Variate>
struct FirstMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::Matrix<Real, Dimension, 1> Type;
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <typename Variate>
struct DiagonalSecondMomentOf
{
enum: signed int { Dimension = SizeOf<Variate>::Value };
typedef Eigen::DiagonalMatrix<Real, Dimension> Type;
};
/**
* \ingroup traits
*
* Defines the second moment type of a given variate
*/
template <>
struct SecondMomentOf<Real>
{
typedef Real Type;
};
/**
* \ingroup traits
*/
template <>
struct FirstMomentOf<Real>
{
typedef Real Type;
};
/**
* \ingroup traits
*/
template <typename Model> struct IsAdditive
{
enum: bool
{
Value = std::is_base_of<internal::AdditiveNoiseModelType, Model>::value
};
};
/**
* \ingroup traits
*/
template <typename Model> struct IsAdditiveUncorrelated
{
enum: bool
{
Value = std::is_base_of<
internal::AdditiveUncorrelatedNoiseModelType,
Model
>::value
};
};
/**
* \ingroup traits
*/
template <typename Model> struct IsNonAdditive
{
enum: bool
{
Value = std::is_base_of<internal::NonAdditiveNoiseModelType, Model>::value
};
};
/**
* \internal
* \ingroup traits
*/
template <typename Model, typename ...> struct AdditivityOf;
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Model, internal::AdditiveNoiseModelType>
{
typedef Additive<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Model, internal::AdditiveUncorrelatedNoiseModelType>
{
typedef AdditiveUncorrelated<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Model, internal::NonAdditiveNoiseModelType>
{
typedef NonAdditive<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<Additive<Model>>
{
typedef Additive<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<AdditiveUncorrelated<Model>>
{
typedef AdditiveUncorrelated<Model> Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model>
struct AdditivityOf<NonAdditive<Model>>
{
typedef NonAdditive<Model> Type;
};
/**
* \ingroup traits
* \brief Provides access to the type of the model
*
* The model type will be one of the following
* - \c NonAdditive (Noise)
* - \c Additive (Noise)
* - \c AdditiveUncorrelated (Noise)
*/
template <typename Model> struct AdditivityOf<Model>
{
typedef typename AdditivityOf<Model, typename Model::Type>::Type Type;
};
/**
* \internal
* \ingroup traits
*/
template <typename Model> struct RemoveAdditivityOf
{
typedef Model Type;
};
template <typename Model>
struct RemoveAdditivityOf<Additive<Model>>
{
typedef Model Type;
};
template <typename Model>
struct RemoveAdditivityOf<AdditiveUncorrelated<Model>>
{
typedef Model Type;
};
template <typename Model>
struct RemoveAdditivityOf<NonAdditive<Model>>
{
typedef Model Type;
};
/**
* \internal
*
* \ingroup traits
*/
template <typename Model>
struct ForwardLinearModelOnly
{
static_assert(std::is_base_of<internal::LinearModelType, Model>::value,
"The specified model is not linear!");
typedef Model Type;
};
}
#endif
<|endoftext|> |
<commit_before>// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <[email protected]>
//
// 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 "doublearea.h"
#include "edge_lengths.h"
#include "sort.h"
#include <cassert>
#include <iostream>
template <typename DerivedV, typename DerivedF, typename DeriveddblA>
IGL_INLINE void igl::doublearea(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
if (F.cols() == 4) // quads are handled by a specialized function
return doublearea_quad(V,F,dblA);
const int dim = V.cols();
// Only support triangles
assert(F.cols() == 3);
const int m = F.rows();
// Compute edge lengths
Eigen::PlainObjectBase<DerivedV> l;
// "Lecture Notes on Geometric Robustness" Shewchuck 09, Section 3.1
// http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
// Projected area helper
const auto & proj_doublearea =
[&V,&F](const int x, const int y, const int f)->double
{
auto rx = V(F(f,0),x)-V(F(f,2),x);
auto sx = V(F(f,1),x)-V(F(f,2),x);
auto ry = V(F(f,0),y)-V(F(f,2),y);
auto sy = V(F(f,1),y)-V(F(f,2),y);
return rx*sy - ry*sx;
};
switch(dim)
{
case 3:
{
dblA = Eigen::PlainObjectBase<DeriveddblA>::Zero(m,1);
for(int f = 0;f<F.rows();f++)
{
for(int d = 0;d<3;d++)
{
double dblAd = proj_doublearea(d,(d+1)%3,f);
dblA(f) += dblAd*dblAd;
}
}
dblA = dblA.array().sqrt().eval();
break;
}
case 2:
{
dblA.resize(m,1);
for(int f = 0;f<m;f++)
{
dblA(f) = proj_doublearea(0,1,f);
}
break;
}
default:
{
edge_lengths(V,F,l);
return doublearea(l,dblA);
}
}
}
template <
typename DerivedA,
typename DerivedB,
typename DerivedC,
typename DerivedD>
IGL_INLINE void doublearea(
const Eigen::PlainObjectBase<DerivedA> & A,
const Eigen::PlainObjectBase<DerivedB> & B,
const Eigen::PlainObjectBase<DerivedC> & C,
Eigen::PlainObjectBase<DerivedD> & D)
{
assert(A.cols() == 2 && "corners should be 2d");
assert(B.cols() == 2 && "corners should be 2d");
assert(C.cols() == 2 && "corners should be 2d");
assert(A.rows() == B.rows() && "corners should have same length");
assert(A.rows() == C.rows() && "corners should have same length");
const auto & R = A-C;
const auto & S = B-C;
D = R.col(0).array()*S.col(1).array() - R.col(1).array()*S.col(0).array();
}
template <
typename DerivedA,
typename DerivedB,
typename DerivedC>
IGL_INLINE typename DerivedA::Scalar igl::doublearea_single(
const Eigen::PlainObjectBase<DerivedA> & A,
const Eigen::PlainObjectBase<DerivedB> & B,
const Eigen::PlainObjectBase<DerivedC> & C)
{
auto r = A-C;
auto s = B-C;
return r(0)*s(1) - r(1)*s(0);
}
template <typename Derivedl, typename DeriveddblA>
IGL_INLINE void igl::doublearea(
const Eigen::PlainObjectBase<Derivedl> & ul,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
using namespace Eigen;
using namespace std;
// Only support triangles
assert(ul.cols() == 3);
// Number of triangles
const int m = ul.rows();
Eigen::PlainObjectBase<Derivedl> l;
MatrixXi _;
sort(ul,2,false,l,_);
// semiperimeters
Matrix<typename Derivedl::Scalar,Dynamic,1> s = l.rowwise().sum()*0.5;
assert(s.rows() == m);
// resize output
dblA.resize(l.rows(),1);
// Minimum number of iterms per openmp thread
#ifndef IGL_OMP_MIN_VALUE
# define IGL_OMP_MIN_VALUE 1000
#endif
#pragma omp parallel for if (m>IGL_OMP_MIN_VALUE)
for(int i = 0;i<m;i++)
{
//// Heron's formula for area
//const typename Derivedl::Scalar arg =
// s(i)*(s(i)-l(i,0))*(s(i)-l(i,1))*(s(i)-l(i,2));
//assert(arg>=0);
//dblA(i) = 2.0*sqrt(arg);
// Kahan's Heron's formula
const typename Derivedl::Scalar arg =
(l(i,0)+(l(i,1)+l(i,2)))*
(l(i,2)-(l(i,0)-l(i,1)))*
(l(i,2)+(l(i,0)-l(i,1)))*
(l(i,0)+(l(i,1)-l(i,2)));
dblA(i) = 2.0*0.25*sqrt(arg);
assert( l(i,2) - (l(i,0)-l(i,1)) && "FAILED KAHAN'S ASSERTION");
assert(dblA(i) == dblA(i) && "DOUBLEAREA() PRODUCED NaN");
}
}
template <typename DerivedV, typename DerivedF, typename DeriveddblA>
IGL_INLINE void igl::doublearea_quad(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
assert(V.cols() == 3); // Only supports points in 3D
assert(F.cols() == 4); // Only support quads
const int m = F.rows();
// Split the quads into triangles
Eigen::MatrixXi Ft(F.rows()*2,3);
for(unsigned i=0; i<F.rows();++i)
{
Ft.row(i*2 ) << F(i,0), F(i,1), F(i,2);
Ft.row(i*2 + 1) << F(i,2), F(i,3), F(i,0);
}
// Compute areas
Eigen::VectorXd doublearea_tri;
igl::doublearea(V,Ft,doublearea_tri);
dblA.resize(F.rows(),1);
for(unsigned i=0; i<F.rows();++i)
dblA(i) = doublearea_tri(i*2) + doublearea_tri(i*2 + 1);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
// generated by autoexplicit.sh
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::doublearea<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template Eigen::Matrix<double, 2, 1, 0, 2, 1>::Scalar igl::doublearea_single<Eigen::Matrix<double, 2, 1, 0, 2, 1>, Eigen::Matrix<double, 2, 1, 0, 2, 1>, Eigen::Matrix<double, 2, 1, 0, 2, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&);
#endif
<commit_msg>fix warnings<commit_after>// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <[email protected]>
//
// 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 "doublearea.h"
#include "edge_lengths.h"
#include "sort.h"
#include <cassert>
#include <iostream>
template <typename DerivedV, typename DerivedF, typename DeriveddblA>
IGL_INLINE void igl::doublearea(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
if (F.cols() == 4) // quads are handled by a specialized function
return doublearea_quad(V,F,dblA);
const int dim = V.cols();
// Only support triangles
assert(F.cols() == 3);
const size_t m = F.rows();
// Compute edge lengths
Eigen::PlainObjectBase<DerivedV> l;
// "Lecture Notes on Geometric Robustness" Shewchuck 09, Section 3.1
// http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
// Projected area helper
const auto & proj_doublearea =
[&V,&F](const int x, const int y, const int f)->double
{
auto rx = V(F(f,0),x)-V(F(f,2),x);
auto sx = V(F(f,1),x)-V(F(f,2),x);
auto ry = V(F(f,0),y)-V(F(f,2),y);
auto sy = V(F(f,1),y)-V(F(f,2),y);
return rx*sy - ry*sx;
};
switch(dim)
{
case 3:
{
dblA = Eigen::PlainObjectBase<DeriveddblA>::Zero(m,1);
for(size_t f = 0;f<m;f++)
{
for(int d = 0;d<3;d++)
{
double dblAd = proj_doublearea(d,(d+1)%3,f);
dblA(f) += dblAd*dblAd;
}
}
dblA = dblA.array().sqrt().eval();
break;
}
case 2:
{
dblA.resize(m,1);
for(size_t f = 0;f<m;f++)
{
dblA(f) = proj_doublearea(0,1,f);
}
break;
}
default:
{
edge_lengths(V,F,l);
return doublearea(l,dblA);
}
}
}
template <
typename DerivedA,
typename DerivedB,
typename DerivedC,
typename DerivedD>
IGL_INLINE void doublearea(
const Eigen::PlainObjectBase<DerivedA> & A,
const Eigen::PlainObjectBase<DerivedB> & B,
const Eigen::PlainObjectBase<DerivedC> & C,
Eigen::PlainObjectBase<DerivedD> & D)
{
assert(A.cols() == 2 && "corners should be 2d");
assert(B.cols() == 2 && "corners should be 2d");
assert(C.cols() == 2 && "corners should be 2d");
assert(A.rows() == B.rows() && "corners should have same length");
assert(A.rows() == C.rows() && "corners should have same length");
const auto & R = A-C;
const auto & S = B-C;
D = R.col(0).array()*S.col(1).array() - R.col(1).array()*S.col(0).array();
}
template <
typename DerivedA,
typename DerivedB,
typename DerivedC>
IGL_INLINE typename DerivedA::Scalar igl::doublearea_single(
const Eigen::PlainObjectBase<DerivedA> & A,
const Eigen::PlainObjectBase<DerivedB> & B,
const Eigen::PlainObjectBase<DerivedC> & C)
{
auto r = A-C;
auto s = B-C;
return r(0)*s(1) - r(1)*s(0);
}
template <typename Derivedl, typename DeriveddblA>
IGL_INLINE void igl::doublearea(
const Eigen::PlainObjectBase<Derivedl> & ul,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
using namespace Eigen;
using namespace std;
// Only support triangles
assert(ul.cols() == 3);
// Number of triangles
const size_t m = ul.rows();
Eigen::PlainObjectBase<Derivedl> l;
MatrixXi _;
sort(ul,2,false,l,_);
// semiperimeters
Matrix<typename Derivedl::Scalar,Dynamic,1> s = l.rowwise().sum()*0.5;
assert(s.rows() == m);
// resize output
dblA.resize(l.rows(),1);
// Minimum number of iterms per openmp thread
#ifndef IGL_OMP_MIN_VALUE
# define IGL_OMP_MIN_VALUE 1000
#endif
#pragma omp parallel for if (m>IGL_OMP_MIN_VALUE)
for(size_t i = 0;i<m;i++)
{
//// Heron's formula for area
//const typename Derivedl::Scalar arg =
// s(i)*(s(i)-l(i,0))*(s(i)-l(i,1))*(s(i)-l(i,2));
//assert(arg>=0);
//dblA(i) = 2.0*sqrt(arg);
// Kahan's Heron's formula
const typename Derivedl::Scalar arg =
(l(i,0)+(l(i,1)+l(i,2)))*
(l(i,2)-(l(i,0)-l(i,1)))*
(l(i,2)+(l(i,0)-l(i,1)))*
(l(i,0)+(l(i,1)-l(i,2)));
dblA(i) = 2.0*0.25*sqrt(arg);
assert( l(i,2) - (l(i,0)-l(i,1)) && "FAILED KAHAN'S ASSERTION");
assert(dblA(i) == dblA(i) && "DOUBLEAREA() PRODUCED NaN");
}
}
template <typename DerivedV, typename DerivedF, typename DeriveddblA>
IGL_INLINE void igl::doublearea_quad(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
Eigen::PlainObjectBase<DeriveddblA> & dblA)
{
assert(V.cols() == 3); // Only supports points in 3D
assert(F.cols() == 4); // Only support quads
const size_t m = F.rows();
// Split the quads into triangles
Eigen::MatrixXi Ft(F.rows()*2,3);
for(size_t i=0; i<m;++i)
{
Ft.row(i*2 ) << F(i,0), F(i,1), F(i,2);
Ft.row(i*2 + 1) << F(i,2), F(i,3), F(i,0);
}
// Compute areas
Eigen::VectorXd doublearea_tri;
igl::doublearea(V,Ft,doublearea_tri);
dblA.resize(F.rows(),1);
for(unsigned i=0; i<F.rows();++i)
dblA(i) = doublearea_tri(i*2) + doublearea_tri(i*2 + 1);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
// generated by autoexplicit.sh
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
// generated by autoexplicit.sh
template void igl::doublearea<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::doublearea<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template Eigen::Matrix<double, 2, 1, 0, 2, 1>::Scalar igl::doublearea_single<Eigen::Matrix<double, 2, 1, 0, 2, 1>, Eigen::Matrix<double, 2, 1, 0, 2, 1>, Eigen::Matrix<double, 2, 1, 0, 2, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 1, 0, 2, 1> > const&);
#endif
<|endoftext|> |
<commit_before>#include <UtH\Platform\Graphics.hpp>
#include <UtH\Platform\Configuration.hpp>
#include <UtH\Platform\OpenGL.hpp>
#include <UtH\Platform\OGLCheck.hpp>
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "freeglut_staticd.lib")
#pragma comment(lib, "glew32sd.lib")
#else // Release
// FIXME: Static 'Release' version of the GLEW lib breaks the build
// consider using dynamic linking for release
#pragma comment(lib, "freeglut_static.lib")
#pragma comment(lib, "glew32sd.lib")
#endif
namespace uth
{
static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,
GL_FRAGMENT_SHADER};
static int dataTypes[DATATYPE_LAST] = {GL_BYTE,
GL_UNSIGNED_BYTE,
GL_SHORT,
GL_UNSIGNED_SHORT,
GL_INT,
GL_UNSIGNED_INT,
GL_FLOAT,
GL_DOUBLE};
static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,
GL_READ_BUFFER,
GL_COPY_WRITE_BUFFER,
GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER,
GL_PIXEL_UNPACK_BUFFER,
GL_TEXTURE_BUFFER,
GL_TRANSFORM_FEEDBACK_BUFFER,
GL_UNIFORM_BUFFER};
static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,
GL_STREAM_READ,
GL_STREAM_COPY,
GL_STATIC_DRAW,
GL_STATIC_READ,
GL_STATIC_COPY,
GL_DYNAMIC_DRAW,
GL_DYNAMIC_READ,
GL_DYNAMIC_COPY};
static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,
GL_PACK_LSB_FIRST,
GL_PACK_ROW_LENGTH,
GL_PACK_IMAGE_HEIGHT,
GL_PACK_SKIP_PIXELS,
GL_PACK_SKIP_ROWS,
GL_PACK_SKIP_IMAGES,
GL_PACK_ALIGNMENT,
GL_UNPACK_SWAP_BYTES,
GL_UNPACK_LSB_FIRST,
GL_UNPACK_ROW_LENGTH,
GL_UNPACK_IMAGE_HEIGHT,
GL_UNPACK_SKIP_PIXELS,
GL_UNPACK_SKIP_ROWS,
GL_UNPACK_SKIP_IMAGES,
GL_UNPACK_ALIGNMENT};
static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D,
TEXTURE_2D,
TEXTURE_3D,
TEXTURE_1D_ARRAY,
TEXTURE_2D_ARRAY,
TEXTURE_RECTANGLE,
TEXTURE_CUBE_MAP,
TEXTURE_2D_MULTISAMPLE,
TEXTURE_2D_MULTISAMPLE_ARRAY};
static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,
GL_RGBA};
static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL,
GL_TEXTURE_COMPARE_FUNC,
GL_TEXTURE_COMPARE_MODE,
GL_TEXTURE_LOD_BIAS,
GL_TEXTURE_MIN_FILTER,
GL_TEXTURE_MAG_FILTER,
GL_TEXTURE_MIN_LOD,
GL_TEXTURE_MAX_LOD,
GL_TEXTURE_MAX_LEVEL,
GL_TEXTURE_SWIZZLE_R,
GL_TEXTURE_SWIZZLE_G,
GL_TEXTURE_SWIZZLE_B,
GL_TEXTURE_SWIZZLE_A,
GL_TEXTURE_WRAP_S,
GL_TEXTURE_WRAP_T,
GL_TEXTURE_WRAP_R};
static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_LINES,
GL_LINE_STRIP_ADJACENCY,
GL_LINES_ADJACENCY,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_TRIANGLES,
GL_TRIANGLE_STRIP_ADJACENCY,
GL_TRIANGLES_ADJACENCY};
static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS};
static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_CONSTANT_COLOR,
GL_ONE_MINUS_CONSTANT_COLOR,
GL_CONSTANT_ALPHA,
GL_ONE_MINUS_CONSTANT_ALPHA};
static int faceCullings[FACECULLING_LAST] = {GL_FRONT,
GL_BACK,
GL_FRONT_AND_BACK};
// Window functions
bool Graphics::createWindow(const WindowSettings& settings)
{
if (m_windowHandle) destroyWindow();
m_windowSettings = settings;
// Context settings
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
// Extra settings
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
// Position & size
glutInitWindowPosition(settings.position.x, settings.position.y);
glutInitWindowSize(settings.size.x, settings.size.y);
// Display settings
glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |
settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |
settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |
settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);
int majorVer = settings.contextVersionMajor,
minorVer = settings.contextVersionMinor;
glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);
m_windowHandle = glutCreateWindow("Generic Window Title");
std::cout << "glew init might produces GL_INVALID_ENUM error. Just ignore it" << std::endl;
glewExperimental = GL_TRUE;
oglCheck(glewInit());
return true;
}
void Graphics::destroyWindow()
{
oglCheck(glutDestroyWindow(m_windowHandle));
}
void Graphics::clear(const float r, const float g, const float b, const float a)
{
oglCheck(glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
oglCheck(glClearColor(r, g, b, a));
if (!m_windowSettings.useDepthBuffer) return;
#ifdef UTH_SYSTEM_OPENGLES
oglCheck(glClearDepthf(1));
#else
oglCheck(glClearDepth(1));
#endif
if (!m_windowSettings.useStencilBuffer) return;
oglCheck(glClearStencil(1));
}
void Graphics::swapBuffers()
{
oglCheck(glutSwapBuffers());
}
void Graphics::setViewport(const int x, const int y, const size_t width, const size_t height)
{
oglCheck(glViewport(x, y, width, height));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Shaders
int Graphics::createShaderProgram()
{
return glCreateProgram();
}
bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)
{
if (!shaderCode) return false;
unsigned int shader = glCreateShader(shaderTypes[type]);
oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));
oglCheck(glCompileShader(shader));
int infoLenght;
oglCheck(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLenght));
if(infoLenght > 1)
{
char* buf = new char[infoLenght];
oglCheck(glGetShaderInfoLog(shader, infoLenght, NULL, buf));
std::cout << buf << std::endl;
delete buf;
}
int success;
oglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));
if (!success)
{
glDeleteShader(shader);
return false;
}
oglCheck(glAttachShader(shaderProgram, shader));
oglCheck(glDeleteShader(shader));
return true;
}
bool Graphics::linkShaderProgram(const int shaderProgram)
{
oglCheck(glLinkProgram(shaderProgram));
int success;
oglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));
if (!success)
{
destroyShaderProgram(shaderProgram);
return false;
}
return true;
}
void Graphics::bindProgram(const int shaderProgram)
{
if (shaderProgram)
oglCheck(glUseProgram(shaderProgram));
}
void unbindProgram()
{
oglCheck(glUseProgram(0));
}
void Graphics::destroyShaderProgram(const int shaderProgram)
{
oglCheck(glDeleteProgram(shaderProgram));
}
int Graphics::getUniformLocation(const int shaderProgram, const char* name)
{
return glGetUniformLocation(shaderProgram, name);
}
int Graphics::getAttributeLocation(const int shaderProgram, const char* name)
{
return glGetAttribLocation(shaderProgram, name);
}
void Graphics::setUniform(const int location, const float x)
{
oglCheck(glUniform1f(location, x));
}
void Graphics::setUniform(const int location, const float x, const float y)
{
oglCheck(glUniform2f(location, x, y));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z)
{
oglCheck(glUniform3f(location, x, y, z));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)
{
oglCheck(glUniform4f(location, x, y, z, w));
}
void Graphics::setUniform(const int location, const umath::vector2& vector)
{
oglCheck(glUniform2fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector3& vector)
{
oglCheck(glUniform3fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector4& vector)
{
oglCheck(glUniform4fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::matrix3& matrix)
{
oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::setUniform(const int location, const umath::matrix4& matrix)
{
oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::enableVertexAttribArray(const int location)
{
oglCheck(glEnableVertexAttribArray(location));
}
void Graphics::disableVertexAttribArray(const int location)
{
oglCheck(glDisableVertexAttribArray(location));
}
void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)
{
oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Buffers
void Graphics::generateBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glGenBuffers(amount, buffers));
}
void Graphics::deleteBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glDeleteBuffers(amount, buffers));
}
void Graphics::bindBuffer(BufferType type, const unsigned int buffer)
{
oglCheck(glBindBuffer(bufferTypes[type], buffer));
}
void Graphics::setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)
{
oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));
}
void Graphics::setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)
{
oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Texture functions
void Graphics::setPixelStore(PixelStoreParam param, const int value)
{
oglCheck(glPixelStorei(pixelStoreParams[param], value));
}
void Graphics::generateTextures(const unsigned int amount, unsigned int* data)
{
oglCheck(glGenTextures(amount, data));
}
void Graphics::setActiveTexUnit(TexUnit unit)
{
oglCheck(glActiveTexture(unit));
}
void Graphics::bindTexture(TextureType type, const int texture)
{
oglCheck(glBindTexture(textureTypes[type], texture));
}
void Graphics::setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void Graphics::setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void Graphics::setTextureParameter(TextureType type, TextureParam param, const int value)
{
oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Drawing functions
void Graphics::drawArrays(PrimitiveType type, const int first, const size_t count)
{
oglCheck(glDrawArrays(primitiveTypes[type], first, count));
}
void Graphics::drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)
{
oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));
}
void Graphics::setPointSize(const float size)
{
oglCheck(glPointSize(size));
}
void Graphics::setLineWidth(const float width)
{
oglCheck(glLineWidth(width));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Other
void Graphics::flush()
{
oglCheck(glFlush());
}
void Graphics::setDepthFunction(const bool enable, DepthFunction func)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_DEPTH_TEST));
else
oglCheck(glDisable(GL_DEPTH_TEST));
enabled = !enabled;
}
oglCheck(glDepthFunc(depthFunctions[func]));
}
void Graphics::setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_BLEND));
else
oglCheck(glDisable(GL_BLEND));
enabled = !enabled;
}
oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));
}
void Graphics::setFaceCulling(const bool enable, FaceCulling mode)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_CULL_FACE));
else
oglCheck(glDisable(GL_CULL_FACE));
enabled = !enabled;
}
oglCheck(glCullFace(faceCullings[mode]));
}
// Private
Graphics::Graphics()
: m_windowHandle(0),
m_windowSettings()
{
char* myargv[1];
int myargc = 1;
myargv[0] = strdup("UtH Engine");
glutInit(&myargc, myargv);
}
Graphics::~Graphics()
{
destroyWindow();
}
}<commit_msg>Last one!<commit_after>#include <UtH\Platform\Graphics.hpp>
#include <UtH\Platform\Configuration.hpp>
#include <UtH\Platform\OpenGL.hpp>
#include <UtH\Platform\OGLCheck.hpp>
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "freeglut_staticd.lib")
#pragma comment(lib, "glew32sd.lib")
#else // Release
// FIXME: Static 'Release' version of the GLEW lib breaks the build
// consider using dynamic linking for release
#pragma comment(lib, "freeglut_static.lib")
#pragma comment(lib, "glew32sd.lib")
#endif
namespace uth
{
static int shaderTypes[SHADERTYPE_LAST] = {GL_VERTEX_SHADER,
GL_FRAGMENT_SHADER};
static int dataTypes[DATATYPE_LAST] = {GL_BYTE,
GL_UNSIGNED_BYTE,
GL_SHORT,
GL_UNSIGNED_SHORT,
GL_INT,
GL_UNSIGNED_INT,
GL_FLOAT,
GL_DOUBLE};
static int bufferTypes[BUFFERTYPE_LAST] = {GL_ARRAY_BUFFER,
GL_READ_BUFFER,
GL_COPY_WRITE_BUFFER,
GL_ELEMENT_ARRAY_BUFFER,
GL_PIXEL_PACK_BUFFER,
GL_PIXEL_UNPACK_BUFFER,
GL_TEXTURE_BUFFER,
GL_TRANSFORM_FEEDBACK_BUFFER,
GL_UNIFORM_BUFFER};
static int usageTypes[USAGETYPE_LAST] = {GL_STREAM_DRAW,
GL_STREAM_READ,
GL_STREAM_COPY,
GL_STATIC_DRAW,
GL_STATIC_READ,
GL_STATIC_COPY,
GL_DYNAMIC_DRAW,
GL_DYNAMIC_READ,
GL_DYNAMIC_COPY};
static int pixelStoreParams[PIXELSTOREPARAM_LAST] = {GL_PACK_SWAP_BYTES,
GL_PACK_LSB_FIRST,
GL_PACK_ROW_LENGTH,
GL_PACK_IMAGE_HEIGHT,
GL_PACK_SKIP_PIXELS,
GL_PACK_SKIP_ROWS,
GL_PACK_SKIP_IMAGES,
GL_PACK_ALIGNMENT,
GL_UNPACK_SWAP_BYTES,
GL_UNPACK_LSB_FIRST,
GL_UNPACK_ROW_LENGTH,
GL_UNPACK_IMAGE_HEIGHT,
GL_UNPACK_SKIP_PIXELS,
GL_UNPACK_SKIP_ROWS,
GL_UNPACK_SKIP_IMAGES,
GL_UNPACK_ALIGNMENT};
static int textureTypes[TEXTURETYPE_LAST] = {TEXTURE_1D,
TEXTURE_2D,
TEXTURE_3D,
TEXTURE_1D_ARRAY,
TEXTURE_2D_ARRAY,
TEXTURE_RECTANGLE,
TEXTURE_CUBE_MAP,
TEXTURE_2D_MULTISAMPLE,
TEXTURE_2D_MULTISAMPLE_ARRAY};
static int imageFormats[IMAGEFORMAT_LAST] = {GL_RGB,
GL_RGBA};
static int textureParams[TEXTUREPARAM_LAST] = {GL_TEXTURE_BASE_LEVEL,
GL_TEXTURE_COMPARE_FUNC,
GL_TEXTURE_COMPARE_MODE,
GL_TEXTURE_LOD_BIAS,
GL_TEXTURE_MIN_FILTER,
GL_TEXTURE_MAG_FILTER,
GL_TEXTURE_MIN_LOD,
GL_TEXTURE_MAX_LOD,
GL_TEXTURE_MAX_LEVEL,
GL_TEXTURE_SWIZZLE_R,
GL_TEXTURE_SWIZZLE_G,
GL_TEXTURE_SWIZZLE_B,
GL_TEXTURE_SWIZZLE_A,
GL_TEXTURE_WRAP_S,
GL_TEXTURE_WRAP_T,
GL_TEXTURE_WRAP_R};
static int primitiveTypes[PRIMITIVETYPE_LAST] = {GL_POINTS,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_LINES,
GL_LINE_STRIP_ADJACENCY,
GL_LINES_ADJACENCY,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_TRIANGLES,
GL_TRIANGLE_STRIP_ADJACENCY,
GL_TRIANGLES_ADJACENCY};
static int depthFunctions[DEPTHFUNCTION_LAST] = {GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS};
static int blendFunctions[BLENDFUNCTION_LAST] = {GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_CONSTANT_COLOR,
GL_ONE_MINUS_CONSTANT_COLOR,
GL_CONSTANT_ALPHA,
GL_ONE_MINUS_CONSTANT_ALPHA};
static int faceCullings[FACECULLING_LAST] = {GL_FRONT,
GL_BACK,
GL_FRONT_AND_BACK};
// Window functions
bool Graphics::createWindow(const WindowSettings& settings)
{
if (m_windowHandle) destroyWindow();
m_windowSettings = settings;
// Context settings
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
// Extra settings
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
// Position & size
glutInitWindowPosition(settings.position.x, settings.position.y);
glutInitWindowSize(settings.size.x, settings.size.y);
// Display settings
glutInitDisplayMode(settings.useBlending ? GLUT_RGBA : GLUT_RGB |
settings.useDepthBuffer ? GLUT_DEPTH : 0x0 |
settings.useStencilBuffer ? GLUT_STENCIL : 0x0 |
settings.useDoubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE);
int majorVer = settings.contextVersionMajor,
minorVer = settings.contextVersionMinor;
glutInitContextVersion(settings.contextVersionMajor, settings.contextVersionMinor);
m_windowHandle = glutCreateWindow("Generic Window Title");
std::cout << "glew init might produces GL_INVALID_ENUM error. Just ignore it" << std::endl;
glewExperimental = GL_TRUE;
oglCheck(glewInit());
return true;
}
void Graphics::destroyWindow()
{
oglCheck(glutDestroyWindow(m_windowHandle));
}
void Graphics::clear(const float r, const float g, const float b, const float a)
{
oglCheck(glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT |
GL_STENCIL_BUFFER_BIT));
oglCheck(glClearColor(r, g, b, a));
if (!m_windowSettings.useDepthBuffer) return;
#ifdef UTH_SYSTEM_OPENGLES
oglCheck(glClearDepthf(1));
#else
oglCheck(glClearDepth(1));
#endif
if (!m_windowSettings.useStencilBuffer) return;
oglCheck(glClearStencil(1));
}
void Graphics::swapBuffers()
{
oglCheck(glutSwapBuffers());
}
void Graphics::setViewport(const int x, const int y, const size_t width, const size_t height)
{
oglCheck(glViewport(x, y, width, height));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Shaders
int Graphics::createShaderProgram()
{
return glCreateProgram();
}
bool Graphics::createShader(const ShaderType type, const int shaderProgram, const char* shaderCode)
{
if (!shaderCode) return false;
unsigned int shader = glCreateShader(shaderTypes[type]);
oglCheck(glShaderSource(shader, 1, &shaderCode, NULL));
oglCheck(glCompileShader(shader));
int infoLenght;
oglCheck(glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLenght));
if(infoLenght > 1)
{
char* buf = new char[infoLenght];
oglCheck(glGetShaderInfoLog(shader, infoLenght, NULL, buf));
std::cout << buf << std::endl;
delete buf;
}
int success;
oglCheck(glGetShaderiv(shader, GL_COMPILE_STATUS, &success));
if (!success)
{
glDeleteShader(shader);
return false;
}
oglCheck(glAttachShader(shaderProgram, shader));
oglCheck(glDeleteShader(shader));
return true;
}
bool Graphics::linkShaderProgram(const int shaderProgram)
{
oglCheck(glLinkProgram(shaderProgram));
int success;
oglCheck(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success));
if (!success)
{
destroyShaderProgram(shaderProgram);
return false;
}
return true;
}
void Graphics::bindProgram(const int shaderProgram)
{
if (shaderProgram)
oglCheck(glUseProgram(shaderProgram));
}
void Graphics::unbindProgram()
{
oglCheck(glUseProgram(0));
}
void Graphics::destroyShaderProgram(const int shaderProgram)
{
oglCheck(glDeleteProgram(shaderProgram));
}
int Graphics::getUniformLocation(const int shaderProgram, const char* name)
{
return glGetUniformLocation(shaderProgram, name);
}
int Graphics::getAttributeLocation(const int shaderProgram, const char* name)
{
return glGetAttribLocation(shaderProgram, name);
}
void Graphics::setUniform(const int location, const float x)
{
oglCheck(glUniform1f(location, x));
}
void Graphics::setUniform(const int location, const float x, const float y)
{
oglCheck(glUniform2f(location, x, y));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z)
{
oglCheck(glUniform3f(location, x, y, z));
}
void Graphics::setUniform(const int location, const float x, const float y, const float z, const float w)
{
oglCheck(glUniform4f(location, x, y, z, w));
}
void Graphics::setUniform(const int location, const umath::vector2& vector)
{
oglCheck(glUniform2fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector3& vector)
{
oglCheck(glUniform3fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::vector4& vector)
{
oglCheck(glUniform4fv(location, 1, &vector.x));
}
void Graphics::setUniform(const int location, const umath::matrix3& matrix)
{
oglCheck(glUniformMatrix3fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::setUniform(const int location, const umath::matrix4& matrix)
{
oglCheck(glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]));
}
void Graphics::enableVertexAttribArray(const int location)
{
oglCheck(glEnableVertexAttribArray(location));
}
void Graphics::disableVertexAttribArray(const int location)
{
oglCheck(glDisableVertexAttribArray(location));
}
void Graphics::setVertexAttribPointer(const int location, const int size, DataType type, const int stride, const void* pointer)
{
oglCheck(glVertexAttribPointer(location, size, dataTypes[type], GL_FALSE, stride, pointer));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Buffers
void Graphics::generateBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glGenBuffers(amount, buffers));
}
void Graphics::deleteBuffers(const unsigned int amount, unsigned int* buffers)
{
oglCheck(glDeleteBuffers(amount, buffers));
}
void Graphics::bindBuffer(BufferType type, const unsigned int buffer)
{
oglCheck(glBindBuffer(bufferTypes[type], buffer));
}
void Graphics::setBufferData(BufferType type, const unsigned int size, const void* data, UsageType usageType)
{
oglCheck(glBufferData(bufferTypes[type], size, data, usageTypes[usageType]));
}
void Graphics::setBufferSubData(BufferType type, const unsigned int offset, const unsigned int size, const void* data)
{
oglCheck(glBufferSubData(bufferTypes[type], offset, size, data));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Texture functions
void Graphics::setPixelStore(PixelStoreParam param, const int value)
{
oglCheck(glPixelStorei(pixelStoreParams[param], value));
}
void Graphics::generateTextures(const unsigned int amount, unsigned int* data)
{
oglCheck(glGenTextures(amount, data));
}
void Graphics::setActiveTexUnit(TexUnit unit)
{
oglCheck(glActiveTexture(unit));
}
void Graphics::bindTexture(TextureType type, const int texture)
{
oglCheck(glBindTexture(textureTypes[type], texture));
}
void Graphics::setTextureImage1D(const int level, ImageFormat imageFormat, const size_t width, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage1D(textureTypes[TEXTURE_1D], level, imageFormats[imageFormat], width, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void Graphics::setTextureImage2D(TextureType type, const int level, ImageFormat imageFormat, const size_t width, const size_t height, ImageFormat pixelFormat, DataType dataType, const void* pixels)
{
oglCheck(glTexImage2D(textureTypes[TEXTURE_2D], level, imageFormats[imageFormat], width, height, 0, imageFormats[pixelFormat], dataTypes[dataType], pixels));
}
void Graphics::setTextureParameter(TextureType type, TextureParam param, const int value)
{
oglCheck(glTexParameteri(textureTypes[type], textureParams[param], value));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Drawing functions
void Graphics::drawArrays(PrimitiveType type, const int first, const size_t count)
{
oglCheck(glDrawArrays(primitiveTypes[type], first, count));
}
void Graphics::drawElements(PrimitiveType type, const size_t count, DataType dataType, const void* indices)
{
oglCheck(glDrawElements(primitiveTypes[type], count, dataTypes[dataType], indices));
}
void Graphics::setPointSize(const float size)
{
oglCheck(glPointSize(size));
}
void Graphics::setLineWidth(const float width)
{
oglCheck(glLineWidth(width));
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Other
void Graphics::flush()
{
oglCheck(glFlush());
}
void Graphics::setDepthFunction(const bool enable, DepthFunction func)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_DEPTH_TEST));
else
oglCheck(glDisable(GL_DEPTH_TEST));
enabled = !enabled;
}
oglCheck(glDepthFunc(depthFunctions[func]));
}
void Graphics::setBlendFunction(const bool enable, BlendFunction sfunc, BlendFunction dfunc)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_BLEND));
else
oglCheck(glDisable(GL_BLEND));
enabled = !enabled;
}
oglCheck(glBlendFunc(blendFunctions[sfunc], blendFunctions[dfunc]));
}
void Graphics::setFaceCulling(const bool enable, FaceCulling mode)
{
static bool enabled = false;
if (enable != enabled)
{
if (enable)
oglCheck(glEnable(GL_CULL_FACE));
else
oglCheck(glDisable(GL_CULL_FACE));
enabled = !enabled;
}
oglCheck(glCullFace(faceCullings[mode]));
}
// Private
Graphics::Graphics()
: m_windowHandle(0),
m_windowSettings()
{
char* myargv[1];
int myargc = 1;
myargv[0] = strdup("UtH Engine");
glutInit(&myargc, myargv);
}
Graphics::~Graphics()
{
destroyWindow();
}
}<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Render/ViewScene.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Core/Datatypes/Geometry.h>
#include <QtGui>
#include "QtGLContext.h"
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;
// Simple function to handle object transformations so that the GPU does not
// need to do the same calculation for each vertex.
static void lambdaUniformObjTrafs(Spire::ObjectLambdaInterface& iface,
std::list<Spire::Interface::UnsatisfiedUniform>& unsatisfiedUniforms)
{
// Cache object to world transform.
Spire::M44 objToWorld = iface.getObjectMetadata<Spire::M44>(
std::get<0>(Spire::SRCommonAttributes::getObjectToWorldTrafo()));
std::string objectTrafoName = std::get<0>(Spire::SRCommonUniforms::getObject());
std::string objectToViewName = std::get<0>(Spire::SRCommonUniforms::getObjectToView());
std::string objectToCamProjName = std::get<0>(Spire::SRCommonUniforms::getObjectToCameraToProjection());
// Loop through the unsatisfied uniforms and see if we can provide any.
for (auto it = unsatisfiedUniforms.begin(); it != unsatisfiedUniforms.end(); /*nothing*/ )
{
if (it->uniformName == objectTrafoName)
{
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else if (it->uniformName == objectToViewName)
{
// Grab the inverse view transform.
Spire::M44 inverseView = glm::affineInverse(
iface.getGlobalUniform<Spire::M44>(std::get<0>(Spire::SRCommonUniforms::getCameraToWorld())));
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, inverseView * objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else if (it->uniformName == objectToCamProjName)
{
Spire::M44 inverseViewProjection = iface.getGlobalUniform<Spire::M44>(
std::get<0>(Spire::SRCommonUniforms::getToCameraToProjection()));
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, inverseViewProjection * objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else
{
++it;
}
}
}
//------------------------------------------------------------------------------
ViewSceneDialog::ViewSceneDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
addToolBar();
// Setup Qt OpenGL widget.
QGLFormat fmt;
fmt.setAlpha(true);
fmt.setRgba(true);
mGLWidget = new GLWidget(new QtGLContext(fmt));
if (mGLWidget->isValid())
{
// Hook up the GLWidget
glLayout->addWidget(mGLWidget);
glLayout->update();
// Set spire transient value (should no longer be used).
mSpire = std::weak_ptr<Spire::SCIRun::SRInterface>(mGLWidget->getSpire());
}
else
{
/// \todo Display dialog.
delete mGLWidget;
}
}
//------------------------------------------------------------------------------
ViewSceneDialog::~ViewSceneDialog()
{
}
//------------------------------------------------------------------------------
void ViewSceneDialog::closeEvent(QCloseEvent *evt)
{
}
//------------------------------------------------------------------------------
void ViewSceneDialog::moduleExecuted()
{
// Grab the geomData transient value.
boost::any geomDataTransient = state_->getTransientValue("geomData");
if (!geomDataTransient.empty())
{
boost::shared_ptr<std::list<boost::shared_ptr<Core::Datatypes::GeometryObject>>> geomData; // Whoa...
try
{
geomData = boost::any_cast<boost::shared_ptr<std::list<boost::shared_ptr<Core::Datatypes::GeometryObject>>>>(geomDataTransient);
}
catch (const boost::bad_any_cast&)
{
//error("Unable to cast boost::any transient value to spire pointer.");
return;
}
std::shared_ptr<Spire::SCIRun::SRInterface> spire = mSpire.lock();
if (spire == nullptr)
return;
// Remove ALL prior objects.
spire->removeAllObjects();
for (auto it = geomData->begin(); it != geomData->end(); ++it)
{
boost::shared_ptr<Core::Datatypes::GeometryObject> obj = *it;
// Since we simply remove all objects from the scene everyframe (that
// needs to change) we don't need to remove the objects one-by-one.
//// Try/catch is for single-threaded cases. Exceptions are handled on the
//// spire thread when spire is threaded.
//try
//{
// // Will remove all traces of old VBO's / IBO's not in use.
// // (remember, we remove the VBOs/IBOs we added at the end of this loop,
// // this is to ensure there is only 1 shared_ptr reference to the IBOs
// // and VBOs in Spire).
// spire->removeObject(obj->objectName);
//}
//catch (std::out_of_range&)
//{
// // Ignore
//}
spire->addObject(obj->objectName);
// Add vertex buffer objects.
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const GeometryObject::SpireVBO& vbo = *it;
spire->addVBO(vbo.name, vbo.data, vbo.attributeNames);
}
// Add index buffer objects.
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const GeometryObject::SpireIBO& ibo = *it;
Spire::Interface::IBO_TYPE type;
switch (ibo.indexSize)
{
case 1: // 8-bit
type = Spire::Interface::IBO_8BIT;
break;
case 2: // 16-bit
type = Spire::Interface::IBO_16BIT;
break;
case 4: // 32-bit
type = Spire::Interface::IBO_32BIT;
break;
default:
type = Spire::Interface::IBO_32BIT;
throw std::invalid_argument("Unable to determine index buffer depth.");
break;
}
spire->addIBO(ibo.name, ibo.data, type);
}
// Add passes
for (auto it = obj->mPasses.cbegin(); it != obj->mPasses.cend(); ++it)
{
const GeometryObject::SpireSubPass& pass = *it;
spire->addPassToObject(obj->objectName, pass.programName,
pass.vboName, pass.iboName, pass.type,
pass.passName, SPIRE_DEFAULT_PASS);
// Add uniforms associated with the pass
for (auto it = pass.uniforms.begin(); it != pass.uniforms.end(); ++it)
{
std::string uniformName = std::get<0>(*it);
std::shared_ptr<Spire::AbstractUniformStateItem> uniform(std::get<1>(*it));
// Be sure to always include the pass name as we are updating a
// subpass of SPIRE_DEFAULT_PASS.
spire->addObjectPassUniformConcrete(obj->objectName, uniformName,
uniform, pass.passName);
}
// Add gpu state if it has been set.
if (pass.hasGPUState == true)
// Be sure to always include the pass name as we are updating a
// subpass of SPIRE_DEFAULT_PASS.
spire->addObjectPassGPUState(obj->objectName, pass.gpuState, pass.passName);
// Add lambda object uniforms to the pass.
spire->addLambdaObjectUniforms(obj->objectName, lambdaUniformObjTrafs, pass.passName);
}
// This must come *after* adding the passes.
// Now that we have created all of the appropriate passes, get rid of the
// VBOs and IBOs.
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const GeometryObject::SpireVBO& vbo = *it;
spire->removeVBO(vbo.name);
}
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const GeometryObject::SpireIBO& ibo = *it;
spire->removeIBO(ibo.name);
}
}
}
}
void ViewSceneDialog::addToolBar()
{
auto tools = new QToolBar(this);
auto menu = new QComboBox(this);
menu->addItem("Legacy Mouse Control");
menu->addItem("New Mouse Control");
tools->addWidget(menu);
//TODO: hook up to slots. for now, disable.
menu->setEnabled(false);
glLayout->addWidget(tools);
}
<commit_msg>Fixed default transform for objects.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Render/ViewScene.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Core/Datatypes/Geometry.h>
#include <QtGui>
#include "QtGLContext.h"
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Datatypes;
// Simple function to handle object transformations so that the GPU does not
// need to do the same calculation for each vertex.
static void lambdaUniformObjTrafs(Spire::ObjectLambdaInterface& iface,
std::list<Spire::Interface::UnsatisfiedUniform>& unsatisfiedUniforms)
{
// Cache object to world transform.
Spire::M44 objToWorld = iface.getObjectMetadata<Spire::M44>(
std::get<0>(Spire::SRCommonAttributes::getObjectToWorldTrafo()));
std::string objectTrafoName = std::get<0>(Spire::SRCommonUniforms::getObject());
std::string objectToViewName = std::get<0>(Spire::SRCommonUniforms::getObjectToView());
std::string objectToCamProjName = std::get<0>(Spire::SRCommonUniforms::getObjectToCameraToProjection());
// Loop through the unsatisfied uniforms and see if we can provide any.
for (auto it = unsatisfiedUniforms.begin(); it != unsatisfiedUniforms.end(); /*nothing*/ )
{
if (it->uniformName == objectTrafoName)
{
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else if (it->uniformName == objectToViewName)
{
// Grab the inverse view transform.
Spire::M44 inverseView = glm::affineInverse(
iface.getGlobalUniform<Spire::M44>(std::get<0>(Spire::SRCommonUniforms::getCameraToWorld())));
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, inverseView * objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else if (it->uniformName == objectToCamProjName)
{
Spire::M44 inverseViewProjection = iface.getGlobalUniform<Spire::M44>(
std::get<0>(Spire::SRCommonUniforms::getToCameraToProjection()));
Spire::LambdaInterface::setUniform<Spire::M44>(it->uniformType, it->uniformName,
it->shaderLocation, inverseViewProjection * objToWorld);
it = unsatisfiedUniforms.erase(it);
}
else
{
++it;
}
}
}
//------------------------------------------------------------------------------
ViewSceneDialog::ViewSceneDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
addToolBar();
// Setup Qt OpenGL widget.
QGLFormat fmt;
fmt.setAlpha(true);
fmt.setRgba(true);
mGLWidget = new GLWidget(new QtGLContext(fmt));
if (mGLWidget->isValid())
{
// Hook up the GLWidget
glLayout->addWidget(mGLWidget);
glLayout->update();
// Set spire transient value (should no longer be used).
mSpire = std::weak_ptr<Spire::SCIRun::SRInterface>(mGLWidget->getSpire());
}
else
{
/// \todo Display dialog.
delete mGLWidget;
}
}
//------------------------------------------------------------------------------
ViewSceneDialog::~ViewSceneDialog()
{
}
//------------------------------------------------------------------------------
void ViewSceneDialog::closeEvent(QCloseEvent *evt)
{
}
//------------------------------------------------------------------------------
void ViewSceneDialog::moduleExecuted()
{
// Grab the geomData transient value.
boost::any geomDataTransient = state_->getTransientValue("geomData");
if (!geomDataTransient.empty())
{
boost::shared_ptr<std::list<boost::shared_ptr<Core::Datatypes::GeometryObject>>> geomData; // Whoa...
try
{
geomData = boost::any_cast<boost::shared_ptr<std::list<boost::shared_ptr<Core::Datatypes::GeometryObject>>>>(geomDataTransient);
}
catch (const boost::bad_any_cast&)
{
//error("Unable to cast boost::any transient value to spire pointer.");
return;
}
std::shared_ptr<Spire::SCIRun::SRInterface> spire = mSpire.lock();
if (spire == nullptr)
return;
// Remove ALL prior objects.
spire->removeAllObjects();
for (auto it = geomData->begin(); it != geomData->end(); ++it)
{
boost::shared_ptr<Core::Datatypes::GeometryObject> obj = *it;
// Since we simply remove all objects from the scene everyframe (that
// needs to change) we don't need to remove the objects one-by-one.
//// Try/catch is for single-threaded cases. Exceptions are handled on the
//// spire thread when spire is threaded.
//try
//{
// // Will remove all traces of old VBO's / IBO's not in use.
// // (remember, we remove the VBOs/IBOs we added at the end of this loop,
// // this is to ensure there is only 1 shared_ptr reference to the IBOs
// // and VBOs in Spire).
// spire->removeObject(obj->objectName);
//}
//catch (std::out_of_range&)
//{
// // Ignore
//}
spire->addObject(obj->objectName);
// Add vertex buffer objects.
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const GeometryObject::SpireVBO& vbo = *it;
spire->addVBO(vbo.name, vbo.data, vbo.attributeNames);
}
// Add index buffer objects.
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const GeometryObject::SpireIBO& ibo = *it;
Spire::Interface::IBO_TYPE type;
switch (ibo.indexSize)
{
case 1: // 8-bit
type = Spire::Interface::IBO_8BIT;
break;
case 2: // 16-bit
type = Spire::Interface::IBO_16BIT;
break;
case 4: // 32-bit
type = Spire::Interface::IBO_32BIT;
break;
default:
type = Spire::Interface::IBO_32BIT;
throw std::invalid_argument("Unable to determine index buffer depth.");
break;
}
spire->addIBO(ibo.name, ibo.data, type);
}
// Add passes
for (auto it = obj->mPasses.cbegin(); it != obj->mPasses.cend(); ++it)
{
const GeometryObject::SpireSubPass& pass = *it;
spire->addPassToObject(obj->objectName, pass.programName,
pass.vboName, pass.iboName, pass.type,
pass.passName, SPIRE_DEFAULT_PASS);
// Add uniforms associated with the pass
for (auto it = pass.uniforms.begin(); it != pass.uniforms.end(); ++it)
{
std::string uniformName = std::get<0>(*it);
std::shared_ptr<Spire::AbstractUniformStateItem> uniform(std::get<1>(*it));
// Be sure to always include the pass name as we are updating a
// subpass of SPIRE_DEFAULT_PASS.
spire->addObjectPassUniformConcrete(obj->objectName, uniformName,
uniform, pass.passName);
}
// Add gpu state if it has been set.
if (pass.hasGPUState == true)
// Be sure to always include the pass name as we are updating a
// subpass of SPIRE_DEFAULT_PASS.
spire->addObjectPassGPUState(obj->objectName, pass.gpuState, pass.passName);
// Add lambda object uniforms to the pass.
spire->addLambdaObjectUniforms(obj->objectName, lambdaUniformObjTrafs, pass.passName);
}
// Add default identity transform to the object globally (instead of
// per-pass).
Spire::M44 xform;
xform[3] = Spire::V4(0.0f, 0.0f, 0.0f, 1.0f);
spire->addObjectGlobalMetadata(
obj->objectName, std::get<0>(Spire::SRCommonAttributes::getObjectToWorldTrafo()), xform);
// This must come *after* adding the passes.
// Now that we have created all of the appropriate passes, get rid of the
// VBOs and IBOs.
for (auto it = obj->mVBOs.cbegin(); it != obj->mVBOs.cend(); ++it)
{
const GeometryObject::SpireVBO& vbo = *it;
spire->removeVBO(vbo.name);
}
for (auto it = obj->mIBOs.cbegin(); it != obj->mIBOs.cend(); ++it)
{
const GeometryObject::SpireIBO& ibo = *it;
spire->removeIBO(ibo.name);
}
}
}
}
void ViewSceneDialog::addToolBar()
{
auto tools = new QToolBar(this);
auto menu = new QComboBox(this);
menu->addItem("Legacy Mouse Control");
menu->addItem("New Mouse Control");
tools->addWidget(menu);
//TODO: hook up to slots. for now, disable.
menu->setEnabled(false);
glLayout->addWidget(tools);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.