text
stringlengths
54
60.6k
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include "FreeTypeFont.h" #include FT_GLYPH_H #include <osgDB/WriteFile> FreeTypeFont::FreeTypeFont(const std::string& filename, FT_Face face): _filename(filename), _face(face) { } void FreeTypeFont::setSize(unsigned int width, unsigned int height) { FT_Error error = FT_Set_Pixel_Sizes( _face, /* handle to face object */ width, /* pixel_width */ height ); /* pixel_height */ if (error) { std::cout<<"FT_Set_Pixel_Sizes() - error "<<error<<std::endl; } else { _width = width; _height = height; } } osgText::Font::Glyph* FreeTypeFont::getGlyph(unsigned int charcode) { // search for glyph amoungst existing glyphs. GlyphMap::iterator itr = _glyphMap.find(charcode); if (itr!=_glyphMap.end()) return itr->second.get(); FT_Error error = FT_Load_Char( _face, charcode, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP ); if (error) { std::cout << "FT_Load_Char(...) error "<<error<<std::endl; return 0; } FT_GlyphSlot glyphslot = _face->glyph; int rows = glyphslot->bitmap.rows; int width = glyphslot->bitmap.width; int pitch = glyphslot->bitmap.pitch; unsigned char* buffer = glyphslot->bitmap.buffer; osg::ref_ptr<Glyph> glyph = new Glyph; unsigned char* data = new unsigned char[width*rows*2]; glyph->setImage(width,rows,1, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); // copy image across to osgText::Glyph image. for(int r=rows-1;r>=0;--r) { unsigned char* ptr = buffer+r*pitch; for(int c=0;c<width;++c,++ptr) { (*data++)=255; (*data++)=*ptr; } } FT_Glyph_Metrics* metrics = &(glyphslot->metrics); glyph->setFont(this); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX/64.0f,(float)(metrics->horiBearingY-metrics->height)/64.0f)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance/64.0f); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX/64.0f,(float)(metrics->vertBearingY-metrics->height)/64.0f)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance/64.0f); addGlyph(charcode,glyph.get()); return glyph.get(); } osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightcharcode) { if (!FT_HAS_KERNING(_face)) return osg::Vec2(0.0f,0.0f); // convert character code to glyph index FT_UInt left = FT_Get_Char_Index( _face, leftcharcode ); FT_UInt right = FT_Get_Char_Index( _face, rightcharcode ); // get the kerning distances. FT_Vector kerning; FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index ft_kerning_default, // kerning mode &kerning ); // target vector if (error) { return osg::Vec2(0.0f,0.0f); } return osg::Vec2((float)kerning.x/64.0f,(float)kerning.y/64.0f); } bool FreeTypeFont::hasVertical() const { return FT_HAS_VERTICAL(_face); } <commit_msg>Fix for warning under Windows.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include "FreeTypeFont.h" #include FT_GLYPH_H #include <osgDB/WriteFile> FreeTypeFont::FreeTypeFont(const std::string& filename, FT_Face face): _filename(filename), _face(face) { } void FreeTypeFont::setSize(unsigned int width, unsigned int height) { FT_Error error = FT_Set_Pixel_Sizes( _face, /* handle to face object */ width, /* pixel_width */ height ); /* pixel_height */ if (error) { std::cout<<"FT_Set_Pixel_Sizes() - error "<<error<<std::endl; } else { _width = width; _height = height; } } osgText::Font::Glyph* FreeTypeFont::getGlyph(unsigned int charcode) { // search for glyph amoungst existing glyphs. GlyphMap::iterator itr = _glyphMap.find(charcode); if (itr!=_glyphMap.end()) return itr->second.get(); FT_Error error = FT_Load_Char( _face, charcode, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP ); if (error) { std::cout << "FT_Load_Char(...) error "<<error<<std::endl; return 0; } FT_GlyphSlot glyphslot = _face->glyph; int rows = glyphslot->bitmap.rows; int width = glyphslot->bitmap.width; int pitch = glyphslot->bitmap.pitch; unsigned char* buffer = glyphslot->bitmap.buffer; osg::ref_ptr<Glyph> glyph = new Glyph; unsigned char* data = new unsigned char[width*rows*2]; glyph->setImage(width,rows,1, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); // copy image across to osgText::Glyph image. for(int r=rows-1;r>=0;--r) { unsigned char* ptr = buffer+r*pitch; for(int c=0;c<width;++c,++ptr) { (*data++)=255; (*data++)=*ptr; } } FT_Glyph_Metrics* metrics = &(glyphslot->metrics); glyph->setFont(this); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX/64.0f,(float)(metrics->horiBearingY-metrics->height)/64.0f)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance/64.0f); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX/64.0f,(float)(metrics->vertBearingY-metrics->height)/64.0f)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance/64.0f); addGlyph(charcode,glyph.get()); return glyph.get(); } osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightcharcode) { if (!FT_HAS_KERNING(_face)) return osg::Vec2(0.0f,0.0f); // convert character code to glyph index FT_UInt left = FT_Get_Char_Index( _face, leftcharcode ); FT_UInt right = FT_Get_Char_Index( _face, rightcharcode ); // get the kerning distances. FT_Vector kerning; FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index ft_kerning_default, // kerning mode &kerning ); // target vector if (error) { return osg::Vec2(0.0f,0.0f); } return osg::Vec2((float)kerning.x/64.0f,(float)kerning.y/64.0f); } bool FreeTypeFont::hasVertical() const { return FT_HAS_VERTICAL(_face)!=0; } <|endoftext|>
<commit_before>#include "BooPHF.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <sys/types.h> #include <random> #include <algorithm> #include <fstream> using namespace std; //example with user provided custom hasher for uint64_t type : class Custom_string_Hasher { public: // the class should have operator () with this signature : uint64_t operator () (std::string key, uint64_t seed=0) const { uint64_t hash = hash_fn(key); hash ^= seed; return hash; } std::hash<std::string> hash_fn; }; //then tell BBhash to use this custom hash : (also appears below, line 104) typedef boomphf::mphf< std::string, Custom_string_Hasher > boophf_t; //from http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int main (int argc, char* argv[]){ //PARAMETERS u_int64_t nelem = 1000000; uint nthreads = 1; if(argc !=3 ){ printf("Usage :\n"); printf("%s <nelem> <nthreads> \n",argv[0]); return EXIT_FAILURE; } if(argc ==3 ){ nelem = strtoul(argv[1], NULL,0); nthreads = atoi(argv[2]); } uint64_t ii, jj; std::vector<std::string> data; int string_size = 18; ///// generation of random strings char * tempchar = (char *) malloc(sizeof(string_size)*sizeof(char)); string lolstr; ifstream inputfile("StringFile.txt",ios::in); for (u_int64_t i = 0; i < nelem; i++){ //RANDOM STRINGS //~ gen_random(tempchar,string_size); //~ data.push_back((string)tempchar); //STRING READ FROM FILE getline(inputfile,lolstr); data.push_back(lolstr); } ////////////////// // at this point, array data contains a set of nelem random unique keys boophf_t * bphf = NULL; double t_begin,t_end; struct timeval timet; printf("Construct a BooPHF with %lli elements \n",nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); // mphf takes as input a c++ range. A std::vector is already a c++ range double gammaFactor = 2.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query // gamma = 2 is a good tradeoff (leads to approx 3.7 bits/key ) //build the mphf bphf = new boomphf::mphf<std::string,Custom_string_Hasher>(nelem,data,nthreads,gammaFactor); gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed = t_end - t_begin; printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed); printf("boophf bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); //query mphf like this for (u_int64_t i = 0; i < 1000000; i++){ uint64_t idx = bphf->lookup(data[i]); } gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed2 = t_end - t_begin; printf("Query of 1M key in %.2fs\n", nelem,elapsed2); delete bphf; return EXIT_SUCCESS; } <commit_msg>string example<commit_after>#include "BooPHF.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <sys/types.h> #include <random> #include <algorithm> #include <fstream> using namespace std; //example with user provided custom hasher for uint64_t type : class Custom_string_Hasher { public: // the class should have operator () with this signature : uint64_t operator () (std::string key, uint64_t seed=0) const { uint64_t hash = hash_fn(key); hash ^= seed; return hash; } std::hash<std::string> hash_fn; }; //then tell BBhash to use this custom hash : (also appears below, line 104) typedef boomphf::mphf< std::string, Custom_string_Hasher > boophf_t; //from http://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c void gen_random(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int main (int argc, char* argv[]){ //PARAMETERS u_int64_t nelem = 1000000; uint nthreads = 1; if(argc !=3 ){ printf("Usage :\n"); printf("%s <nelem> <nthreads> \n",argv[0]); return EXIT_FAILURE; } if(argc ==3 ){ nelem = strtoul(argv[1], NULL,0); nthreads = atoi(argv[2]); } uint64_t ii, jj; std::vector<std::string> data; int string_size = 100; ///// generation of random strings char * tempchar = (char *) malloc(string_size*sizeof(char)); //string lolstr; //ifstream inputfile("StringFile.txt",ios::in); for (u_int64_t i = 0; i < nelem; i++){ //RANDOM STRINGS gen_random(tempchar,string_size); data.push_back((string)tempchar); //STRING READ FROM FILE //getline(inputfile,lolstr); //data.push_back(lolstr); } ////////////////// // at this point, array data contains a set of nelem random unique keys boophf_t * bphf = NULL; double t_begin,t_end; struct timeval timet; printf("Construct a BooPHF with %lli elements \n",nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); // mphf takes as input a c++ range. A std::vector is already a c++ range double gammaFactor = 2.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query // gamma = 2 is a good tradeoff (leads to approx 3.7 bits/key ) //build the mphf bphf = new boomphf::mphf<std::string,Custom_string_Hasher>(nelem,data,nthreads,gammaFactor); gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed = t_end - t_begin; printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", nelem,elapsed); printf("boophf bits/elem : %f\n",(float) (bphf->totalBitSize())/nelem); gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0); //query mphf like this for (u_int64_t i = 0; i < 1000000; i++){ uint64_t idx = bphf->lookup(data[i]); } gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0); double elapsed2 = t_end - t_begin; printf("Query of %llu key in %.2fs\n", nelem,elapsed2); delete bphf; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include <QMessageBox> #include <algorithm> #include "propertieswindow.h" #include "ui_propertieswindow.h" #include "stuff.h" #include "level.h" #include "graphics.h" #include "hexspinbox.h" #include "tileset.h" #include "tilesetview.h" PropertiesWindow::PropertiesWindow(QWidget *parent, const QPixmap *tileset) : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint ), ui(new Ui::PropertiesWindow), tileBox(new HexSpinBox(this, 2)), tilePalBox(new HexSpinBox(this, 2)), spriteBox(new HexSpinBox(this, 2)), spritePalBox(new HexSpinBox(this, 2)), tileView(new TilesetView(this, tileset, 0)) { ui->setupUi(this); // prevent window resizing this->layout()->setSizeConstraint(QLayout::SetFixedSize); // add spinboxes QGridLayout *layout = ui->gridLayout; layout->addWidget(tileBox, 2, 2, 1, 1); layout->addWidget(tilePalBox, 2, 5, 1, 1); layout->addWidget(spriteBox, 3, 2, 1, 1); layout->addWidget(spritePalBox, 3, 5, 1, 1); layout = ui->mainLayout; layout->addWidget(tileView, 0, 1, 1, 1); // add music names to other dropdown for (StringMap::const_iterator i = musicNames.begin(); i != musicNames.end(); i++) { ui->comboBox_Music->addItem(i->second, i->first); } // set up signals to automatically apply changes QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)), tileView, SLOT(update())); QObject::connect(this->tileBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->tileBox, SIGNAL(valueChanged(int)), tileView, SLOT(update())); QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)), tileView, SLOT(update())); QObject::connect(this->spriteBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->spritePalBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->slider_AnimSpeed, SIGNAL(valueChanged(int)), this, SLOT(applySpeed(int))); QObject::connect(ui->slider_AnimSpeed, SIGNAL(valueChanged(int)), tileView, SLOT(setAnimSpeed(int))); QObject::connect(ui->spinBox_Height, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); // set up signals to handle width/length constraints QObject::connect(ui->spinBox_Height, SIGNAL(valueChanged(int)), this, SLOT(setMaxLevelWidth(int))); QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)), this, SLOT(setMaxLevelHeight(int))); } PropertiesWindow::~PropertiesWindow() { delete ui; delete tileBox; delete tilePalBox; delete spriteBox; delete spritePalBox; delete tileView; } void PropertiesWindow::setMaxLevelWidth(int height) { ui->spinBox_Width->setMaximum(16 / height); } void PropertiesWindow::setMaxLevelHeight(int width) { ui->spinBox_Height->setMaximum(16 / width); } void PropertiesWindow::startEdit(leveldata_t *level) { this->level = NULL; // add graphics indices to dropdown ui->comboBox_TileGFX->clear(); for (int i = 0; i < 256; i++) ui->comboBox_TileGFX->addItem(QString::number(i, 16).rightJustified(2, QLatin1Char('0')).toUpper() + ": banks " + QString::number(bankTable[0][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + ", " + QString::number(bankTable[1][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + ", " + QString::number(bankTable[2][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + "-" + QString::number((bankTable[2][i] + 3) & 0xFF, 16).rightJustified(2, QLatin1Char('0')).toUpper()); // set graphics values ui->comboBox_TileGFX->setCurrentIndex(level->header.tileIndex); this->tileBox ->setValue(level->tileset); this->tileBox ->setMaximum(NUM_TILESETS - 1); this->tilePalBox ->setValue(level->header.tilePal); this->tilePalBox ->setMaximum(255); this->spriteBox ->setValue(level->header.sprIndex); this->spriteBox ->setMaximum(255); this->spritePalBox ->setValue(level->header.sprPal); this->spritePalBox ->setMaximum(255); ui->slider_AnimSpeed->setValue(level->header.animSpeed); // set height and width values ui->spinBox_Height->setValue(level->header.screensV); ui->spinBox_Width ->setValue(level->header.screensH); // set music value ui->comboBox_Music->setCurrentIndex(std::distance(musicNames.begin(), musicNames.find(level->header.music))); // set no return value ui->checkBox_NoReturn->setCheckState(level->noReturn ? Qt::Checked : Qt::Unchecked); // save pointer this->level = level; // and original data, in case user cancels this->header = level->header; this->tileset = level->tileset; this->exec(); } void PropertiesWindow::applySpeed(int speed) { if (speed) { speed = ui->slider_AnimSpeed->maximum() - speed + 1; ui->label_FrameLength->setText(QString("%1 frame%2").arg(speed) .arg(speed > 1 ? "s" : "")); } else ui->label_FrameLength->setText("none"); if (level) { level->header.animSpeed = speed; emit speedChanged(speed); } } void PropertiesWindow::applyChange() { if (!level) return; level->header.tileIndex = ui->comboBox_TileGFX->currentIndex(); level->header.tilePal = this->tilePalBox->value(); level->tileset = this->tileBox->value(); level->header.sprIndex = this->spriteBox->value(); level->header.sprPal = this->spritePalBox->value(); // apply level size level->header.screensV = ui->spinBox_Height->value(); level->header.screensH = ui->spinBox_Width ->value(); // apply music setting level->header.music = ui->comboBox_Music->itemData(ui->comboBox_Music->currentIndex()).toUInt(); // apply return flag level->noReturn = ui->checkBox_NoReturn->checkState() == Qt::Checked; emit changed(); } void PropertiesWindow::accept() { level->modified = true; level->modifiedRecently = true; QDialog::accept(); } // discard settings void PropertiesWindow::reject() { // return to original settings level->header = this->header; level->tileset = this->tileset; emit changed(); QDialog::reject(); } <commit_msg>fix tileview animation speed<commit_after>/* This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include <QMessageBox> #include <algorithm> #include "propertieswindow.h" #include "ui_propertieswindow.h" #include "stuff.h" #include "level.h" #include "graphics.h" #include "hexspinbox.h" #include "tileset.h" #include "tilesetview.h" PropertiesWindow::PropertiesWindow(QWidget *parent, const QPixmap *tileset) : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint ), ui(new Ui::PropertiesWindow), tileBox(new HexSpinBox(this, 2)), tilePalBox(new HexSpinBox(this, 2)), spriteBox(new HexSpinBox(this, 2)), spritePalBox(new HexSpinBox(this, 2)), tileView(new TilesetView(this, tileset, 0)) { ui->setupUi(this); // prevent window resizing this->layout()->setSizeConstraint(QLayout::SetFixedSize); // add spinboxes QGridLayout *layout = ui->gridLayout; layout->addWidget(tileBox, 2, 2, 1, 1); layout->addWidget(tilePalBox, 2, 5, 1, 1); layout->addWidget(spriteBox, 3, 2, 1, 1); layout->addWidget(spritePalBox, 3, 5, 1, 1); layout = ui->mainLayout; layout->addWidget(tileView, 0, 1, 1, 1); // add music names to other dropdown for (StringMap::const_iterator i = musicNames.begin(); i != musicNames.end(); i++) { ui->comboBox_Music->addItem(i->second, i->first); } // set up signals to automatically apply changes QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)), tileView, SLOT(update())); QObject::connect(this->tileBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->tileBox, SIGNAL(valueChanged(int)), tileView, SLOT(update())); QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)), tileView, SLOT(update())); QObject::connect(this->spriteBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(this->spritePalBox, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->slider_AnimSpeed, SIGNAL(valueChanged(int)), this, SLOT(applySpeed(int))); QObject::connect(ui->spinBox_Height, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)), this, SLOT(applyChange())); // set up signals to handle width/length constraints QObject::connect(ui->spinBox_Height, SIGNAL(valueChanged(int)), this, SLOT(setMaxLevelWidth(int))); QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)), this, SLOT(setMaxLevelHeight(int))); } PropertiesWindow::~PropertiesWindow() { delete ui; delete tileBox; delete tilePalBox; delete spriteBox; delete spritePalBox; delete tileView; } void PropertiesWindow::setMaxLevelWidth(int height) { ui->spinBox_Width->setMaximum(16 / height); } void PropertiesWindow::setMaxLevelHeight(int width) { ui->spinBox_Height->setMaximum(16 / width); } void PropertiesWindow::startEdit(leveldata_t *level) { this->level = NULL; // add graphics indices to dropdown ui->comboBox_TileGFX->clear(); for (int i = 0; i < 256; i++) ui->comboBox_TileGFX->addItem(QString::number(i, 16).rightJustified(2, QLatin1Char('0')).toUpper() + ": banks " + QString::number(bankTable[0][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + ", " + QString::number(bankTable[1][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + ", " + QString::number(bankTable[2][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + "-" + QString::number((bankTable[2][i] + 3) & 0xFF, 16).rightJustified(2, QLatin1Char('0')).toUpper()); // set graphics values ui->comboBox_TileGFX->setCurrentIndex(level->header.tileIndex); this->tileBox ->setValue(level->tileset); this->tileBox ->setMaximum(NUM_TILESETS - 1); this->tilePalBox ->setValue(level->header.tilePal); this->tilePalBox ->setMaximum(255); this->spriteBox ->setValue(level->header.sprIndex); this->spriteBox ->setMaximum(255); this->spritePalBox ->setValue(level->header.sprPal); this->spritePalBox ->setMaximum(255); ui->slider_AnimSpeed->setValue(level->header.animSpeed); // set height and width values ui->spinBox_Height->setValue(level->header.screensV); ui->spinBox_Width ->setValue(level->header.screensH); // set music value ui->comboBox_Music->setCurrentIndex(std::distance(musicNames.begin(), musicNames.find(level->header.music))); // set no return value ui->checkBox_NoReturn->setCheckState(level->noReturn ? Qt::Checked : Qt::Unchecked); // save pointer this->level = level; // and original data, in case user cancels this->header = level->header; this->tileset = level->tileset; this->exec(); } void PropertiesWindow::applySpeed(int speed) { if (speed) { speed = ui->slider_AnimSpeed->maximum() - speed + 1; ui->label_FrameLength->setText(QString("%1 frame%2").arg(speed) .arg(speed > 1 ? "s" : "")); } else ui->label_FrameLength->setText("none"); if (level) { level->header.animSpeed = speed; emit speedChanged(speed); } tileView->setAnimSpeed(speed); } void PropertiesWindow::applyChange() { if (!level) return; level->header.tileIndex = ui->comboBox_TileGFX->currentIndex(); level->header.tilePal = this->tilePalBox->value(); level->tileset = this->tileBox->value(); level->header.sprIndex = this->spriteBox->value(); level->header.sprPal = this->spritePalBox->value(); // apply level size level->header.screensV = ui->spinBox_Height->value(); level->header.screensH = ui->spinBox_Width ->value(); // apply music setting level->header.music = ui->comboBox_Music->itemData(ui->comboBox_Music->currentIndex()).toUInt(); // apply return flag level->noReturn = ui->checkBox_NoReturn->checkState() == Qt::Checked; emit changed(); } void PropertiesWindow::accept() { level->modified = true; level->modifiedRecently = true; QDialog::accept(); } // discard settings void PropertiesWindow::reject() { // return to original settings level->header = this->header; level->tileset = this->tileset; emit changed(); QDialog::reject(); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/size.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/scal/fun/inv_logit.hpp> #include <stan/math/prim/scal/fun/log1p_exp.hpp> #include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_greater.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <vector> namespace stan { namespace math { template <typename T> struct ordLog_helper { /** * Returns the (natural) log probability of the specified integer * outcome given the continuous location and specified cutpoints * in an ordered logistic model. * * Error-checking handled by main distribution functions, with this * function only called once inputs have been validated. * * @tparam T Type of location & cutpoint variables. * @param y Outcome. * @param K Number of categories. * @param lambda Location. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. */ T logp(const int& y, const int& K, const T& lambda, const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) { if (y == 1) return -log1p_exp(lambda - c[0]); else if (y == K) return -log1p_exp(c[K - 2] - lambda); else return log_inv_logit_diff(lambda - c[y - 2], lambda - c[y - 1]); } /** * Returns a vector with the gradients of the the continuous location * and ordered cutpoints in an ordered logistic model. The first element * of the vector contains the gradient for the location variable (lambda), * followed by the gradients for the ordered cutpoints (c). * * Error-checking handled by main distribution functions, with this * function only called once inputs have been validated. * * @tparam T Type of location & cutpoint variables. * @param y Outcome. * @param K Number of categories. * @param lambda Location. * @param c Positive increasing vector of cutpoints. * @return Vector of gradients. */ Eigen::Matrix<T, Eigen::Dynamic, 1> deriv( const int& y, const int& K, const T& lambda, const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) { using std::exp; Eigen::Matrix<T, Eigen::Dynamic, 1> d( Eigen::Matrix<T, Eigen::Dynamic, 1>::Zero(K)); if (y == 1) { d[0] -= inv_logit(lambda - c[0]); d[1] -= d[0]; return d; } else if (y == K) { d[0] += inv_logit(c[K - 2] - lambda); d[K - 1] -= d[0]; return d; } else { d[y - 1] += inv(1 - exp(c[y - 1] - c[y - 2])) - inv_logit(c[y - 2] - lambda); d[y] += inv(1 - exp(c[y - 2] - c[y - 1])) - inv_logit(c[y - 1] - lambda); d[0] -= d[y] + d[y - 1]; return d; } } }; /** * Returns the (natural) log probability of the specified integer * outcome given the continuous location and specified cutpoints * in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome. * * @tparam propto True if calculating up to a proportion. * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Outcome. * @param lambda Location. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. */ template <bool propto, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( int y, const T_loc& lambda, const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type< T_loc, Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; int K = c.size() + 1; check_bounded(function, "Random variable", y, 1, K); check_finite(function, "Location parameter", lambda); check_greater(function, "Size of cut points parameter", c.size(), 0); check_ordered(function, "Cut-points", c); check_finite(function, "Final cut-point", c(c.size() - 1)); check_finite(function, "First cut-point", c(0)); scalar_seq_view<T_loc> lam_vec(lambda); T_partials_return lam_dbl = value_of(lam_vec[0]); vector_seq_view<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>> c_vec(c); T_partials_vec c_dbl((K - 1)); c_dbl = value_of(c_vec[0]).template cast<T_partials_return>(); ordLog_helper<T_partials_return> ordhelp; T_partials_vec d = ordhelp.deriv(y, K, lam_dbl, c_dbl); operands_and_partials<T_loc, Eigen::Matrix<T_cut, Eigen::Dynamic, 1>> ops_partials(lambda, c); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[0] = d[0]; if (!is_constant_struct<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>::value) ops_partials.edge2_.partials_ = d.tail(K - 1); return ops_partials.build(ordhelp.logp(y, K, lam_dbl, c_dbl)); } template <typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( int y, const T_loc& lambda, const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } /** * Returns the (natural) log probability of the specified array * of integers given the vector of continuous locations and * specified cutpoints in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome. * * @tparam propto True if calculating up to a proportion. * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Array of integers * @param lambda Vector of continuous location variables. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. * @throw std::invalid_argument If y and lambda are different * lengths. */ template <bool propto, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const std::vector<int>& y, const Eigen::Matrix<T_loc, Eigen::Dynamic, 1>& lambda, const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type< Eigen::Matrix<T_loc, Eigen::Dynamic, 1>, Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; int N = lambda.size(); int K = c.size() + 1; check_consistent_sizes(function, "Integers", y, "Locations", lambda); check_bounded(function, "Random variable", y, 1, K); check_finite(function, "Location parameter", lambda); check_ordered(function, "Cut-points", c); check_greater(function, "Size of cut points parameter", c.size(), 0); check_finite(function, "Final cut-point", c(c.size() - 1)); check_finite(function, "First cut-point", c(0)); vector_seq_view<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>> lam_vec(lambda); T_partials_vec lam_dbl = value_of(lam_vec[0]).template cast<T_partials_return>(); vector_seq_view<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>> c_vec(c); T_partials_vec c_dbl((K - 1)); c_dbl = value_of(c_vec[0]).template cast<T_partials_return>(); ordLog_helper<T_partials_return> ordhelp; T_partials_return logp(0.0); T_partials_vec lam_deriv(N); T_partials_vec c_deriv(T_partials_vec::Zero(K - 1)); for (int n = 0; n < N; ++n) { T_partials_vec d = ordhelp.deriv(y[n], K, lam_dbl[n], c_dbl); logp += ordhelp.logp(y[n], K, lam_dbl[n], c_dbl); lam_deriv[n] = d[0]; c_deriv += d.tail(K - 1); } operands_and_partials<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>, Eigen::Matrix<T_cut, Eigen::Dynamic, 1>> ops_partials(lambda, c); if (!is_constant_struct<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>>::value) ops_partials.edge1_.partials_ = lam_deriv; if (!is_constant_struct<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>::value) ops_partials.edge2_.partials_ = c_deriv; return ops_partials.build(logp); } template <typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const std::vector<int>& y, const Eigen::Matrix<T_loc, Eigen::Dynamic, 1>& lambda, const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } /** * Returns the (natural) log probability of the specified array * of integers given the vector of continuous locations and * array of specified cutpoints in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome. * * @tparam propto True if calculating up to a proportion. * @tparam T_y Type of y variable (should be std::vector<int>). * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Array of integers * @param lambda Vector of continuous location variables. * @param c array of Positive increasing vectors of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. * @throw std::invalid_argument If y and lambda are different * lengths, or if y and the array of cutpoints are of different * lengths. */ template <bool propto, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const std::vector<int>& y, const Eigen::Matrix<T_loc, Eigen::Dynamic, 1>& lambda, const std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type< Eigen::Matrix<T_loc, Eigen::Dynamic, 1>, std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; int N = lambda.size(); int K = c[0].size() + 1; for (int n = 0; n < N; ++n) { check_bounded(function, "Random variable", y[n], 1, K); check_greater(function, "Size of cut points parameter", c[n].size(), 0); check_ordered(function, "Cut-points", c[n]); } check_consistent_sizes(function, "Integers", y, "Locations", lambda); check_consistent_sizes(function, "Integers", y, "Cut-points", c); check_finite(function, "Location parameter", lambda); check_finite(function, "Cut-points", c); vector_seq_view<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>> lam_vec(lambda); T_partials_vec lam_dbl = value_of(lam_vec[0]).template cast<T_partials_return>(); vector_seq_view<std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>> c_vec( c); std::vector<T_partials_vec> c_dbl(N); for (int n = 0; n < N; ++n) c_dbl[n] = value_of(c_vec[n]).template cast<T_partials_return>(); ordLog_helper<T_partials_return> ordhelp; T_partials_return logp(0.0); T_partials_vec lam_deriv(N); std::vector<T_partials_vec> c_deriv(N); for (int n = 0; n < N; ++n) { T_partials_vec d = ordhelp.deriv(y[n], K, lam_dbl[n], c_dbl[n]); logp += ordhelp.logp(y[n], K, lam_dbl[n], c_dbl[n]); lam_deriv[n] = d[0]; c_deriv[n] = d.tail(K - 1); } operands_and_partials<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>, std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>> ops_partials(lambda, c); if (!is_constant_struct<Eigen::Matrix<T_loc, Eigen::Dynamic, 1>>::value) ops_partials.edge1_.partials_ = lam_deriv; if (!is_constant_struct< std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>>::value) { for (int n = 0; n < N; ++n) ops_partials.edge2_.partials_vec_[n] = c_deriv[n]; } return ops_partials.build(logp); } template <typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const std::vector<int>& y, const Eigen::Matrix<T_loc, Eigen::Dynamic, 1>& lambda, const std::vector<Eigen::Matrix<T_cut, Eigen::Dynamic, 1>>& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } } // namespace math } // namespace stan #endif <commit_msg>Collapse to single function with vector views<commit_after>#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/size.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/mat/err/check_ordered.hpp> #include <stan/math/prim/scal/fun/inv_logit.hpp> #include <stan/math/prim/scal/fun/log1p_exp.hpp> #include <stan/math/prim/scal/fun/log_inv_logit_diff.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/err/check_greater.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <vector> namespace stan { namespace math { template <typename T> struct ordLog_helper { /** * Returns the (natural) log probability of the specified integer * outcome given the continuous location and specified cutpoints * in an ordered logistic model. * * Error-checking handled by main distribution functions, with this * function only called once inputs have been validated. * * @tparam T Type of location & cutpoint variables. * @param y Outcome. * @param K Number of categories. * @param lambda Location. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. */ T logp(const int& y, const int& K, const T& lambda, const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) { if (y == 1) return -log1p_exp(lambda - c[0]); else if (y == K) return -log1p_exp(c[K - 2] - lambda); else return log_inv_logit_diff(lambda - c[y - 2], lambda - c[y - 1]); } /** * Returns a vector with the gradients of the the continuous location * and ordered cutpoints in an ordered logistic model. The first element * of the vector contains the gradient for the location variable (lambda), * followed by the gradients for the ordered cutpoints (c). * * Error-checking handled by main distribution functions, with this * function only called once inputs have been validated. * * @tparam T Type of location & cutpoint variables. * @param y Outcome. * @param K Number of categories. * @param lambda Location. * @param c Positive increasing vector of cutpoints. * @return Vector of gradients. */ Eigen::Matrix<T, Eigen::Dynamic, 1> deriv( const int& y, const int& K, const T& lambda, const Eigen::Matrix<T, Eigen::Dynamic, 1>& c) { using std::exp; Eigen::Matrix<T, Eigen::Dynamic, 1> d( Eigen::Matrix<T, Eigen::Dynamic, 1>::Zero(K)); if (y == 1) { d[0] -= inv_logit(lambda - c[0]); d[1] -= d[0]; return d; } else if (y == K) { d[0] += inv_logit(c[K - 2] - lambda); d[K - 1] -= d[0]; return d; } else { d[y - 1] += inv(1 - exp(c[y - 1] - c[y - 2])) - inv_logit(c[y - 2] - lambda); d[y] += inv(1 - exp(c[y - 2] - c[y - 1])) - inv_logit(c[y - 1] - lambda); d[0] -= d[y] + d[y - 1]; return d; } } }; /** * Returns the (natural) log probability of the specified array * of integers given the vector of continuous locations and * specified cutpoints in an ordered logistic model. * * <p>Typically the continous location * will be the dot product of a vector of regression coefficients * and a vector of predictors for the outcome. * * @tparam propto True if calculating up to a proportion. * @tparam T_loc Location type. * @tparam T_cut Cut-point type. * @param y Array of integers * @param lambda Vector of continuous location variables. * @param c Positive increasing vector of cutpoints. * @return Log probability of outcome given location and * cutpoints. * @throw std::domain_error If the outcome is not between 1 and * the number of cutpoints plus 2; if the cutpoint vector is * empty; if the cutpoint vector contains a non-positive, * non-finite value; or if the cutpoint vector is not sorted in * ascending order. * @throw std::invalid_argument If y and lambda are different * lengths. */ template <bool propto, typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { static const char* function = "ordered_logistic"; typedef typename stan::partials_return_type<T_loc, T_cut>::type T_partials_return; typedef typename Eigen::Matrix<T_partials_return, -1, 1> T_partials_vec; scalar_seq_view<T_loc> lam_vec(lambda); scalar_seq_view<T_y> y_vec(y); vector_seq_view<T_cut> c_vec(c); int K = c_vec[0].size() + 1; int N = length(lambda); check_consistent_sizes(function, "Integers", y, "Locations", lambda); for (size_t n = 0; n < N; n++) { check_bounded(function, "Random variable", y_vec[n], 1, K); check_finite(function, "Location parameter", lam_vec[n]); } for (size_t i = 0, size_ = length(c_vec); i < size_; i++) { check_ordered(function, "Cut-points", c_vec[i]); check_greater(function, "Size of cut points parameter", c_vec[i].size(), 0); check_finite(function, "Final cut-point", c_vec[i](c_vec[i].size() - 1)); check_finite(function, "First cut-point", c_vec[i](0)); } ordLog_helper<T_partials_return> ordhelp; operands_and_partials<T_loc, T_cut> ops_partials(lambda, c); T_partials_return logp(0.0); for (int n = 0; n < N; ++n) { for (size_t i = 0, size_ = length(c_vec); i < size_; i++) { T_partials_return lam_dbl = value_of(lam_vec[n]); T_partials_vec c_dbl = value_of(c_vec[i]).template cast<T_partials_return>(); T_partials_vec d = ordhelp.deriv(y_vec[n], K, lam_dbl, c_dbl); logp += ordhelp.logp(y_vec[n], K, lam_dbl, c_dbl); if (!is_constant_struct<T_loc>::value) ops_partials.edge1_.partials_[n] = d[0]; if (!is_constant_struct<T_cut>::value) ops_partials.edge2_.partials_vec_[n] += d.tail(K - 1); } } return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_cut> typename return_type<T_loc, T_cut>::type ordered_logistic_lpmf( const T_y& y, const T_loc& lambda, const T_cut& c) { return ordered_logistic_lpmf<false>(y, lambda, c); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>//=- AArch64RedundantCopyElimination.cpp - Remove useless copy for AArch64 -=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // This pass removes unnecessary zero copies in BBs that are targets of // cbz/cbnz instructions. For instance, the copy instruction in the code below // can be removed because the CBZW jumps to BB#2 when W0 is zero. // BB#1: // CBZW %W0, <BB#2> // BB#2: // %W0 = COPY %WZR // This pass should be run after register allocation. // // FIXME: This should be extended to handle any constant other than zero. E.g., // cmp w0, #1 // b.eq .BB1 // BB1: // mov w0, #1 // // FIXME: This could also be extended to check the whole dominance subtree below // the comparison if the compile time regression is acceptable. // //===----------------------------------------------------------------------===// #include "AArch64.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/iterator_range.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" using namespace llvm; #define DEBUG_TYPE "aarch64-copyelim" STATISTIC(NumCopiesRemoved, "Number of copies removed."); namespace { class AArch64RedundantCopyElimination : public MachineFunctionPass { const MachineRegisterInfo *MRI; const TargetRegisterInfo *TRI; public: static char ID; AArch64RedundantCopyElimination() : MachineFunctionPass(ID) { initializeAArch64RedundantCopyEliminationPass( *PassRegistry::getPassRegistry()); } bool optimizeCopy(MachineBasicBlock *MBB); bool runOnMachineFunction(MachineFunction &MF) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } StringRef getPassName() const override { return "AArch64 Redundant Copy Elimination"; } }; char AArch64RedundantCopyElimination::ID = 0; } INITIALIZE_PASS(AArch64RedundantCopyElimination, "aarch64-copyelim", "AArch64 redundant copy elimination pass", false, false) static bool guaranteesZeroRegInBlock(MachineInstr &MI, MachineBasicBlock *MBB) { unsigned Opc = MI.getOpcode(); // Check if the current basic block is the target block to which the // CBZ/CBNZ instruction jumps when its Wt/Xt is zero. if ((Opc == AArch64::CBZW || Opc == AArch64::CBZX) && MBB == MI.getOperand(1).getMBB()) return true; else if ((Opc == AArch64::CBNZW || Opc == AArch64::CBNZX) && MBB != MI.getOperand(1).getMBB()) return true; return false; } bool AArch64RedundantCopyElimination::optimizeCopy(MachineBasicBlock *MBB) { // Check if the current basic block has a single predecessor. if (MBB->pred_size() != 1) return false; MachineBasicBlock *PredMBB = *MBB->pred_begin(); MachineBasicBlock::iterator CompBr = PredMBB->getLastNonDebugInstr(); if (CompBr == PredMBB->end() || PredMBB->succ_size() != 2) return false; ++CompBr; do { --CompBr; if (guaranteesZeroRegInBlock(*CompBr, MBB)) break; } while (CompBr != PredMBB->begin() && CompBr->isTerminator()); // We've not found a CBZ/CBNZ, time to bail out. if (!guaranteesZeroRegInBlock(*CompBr, MBB)) return false; unsigned TargetReg = CompBr->getOperand(0).getReg(); if (!TargetReg) return false; assert(TargetRegisterInfo::isPhysicalRegister(TargetReg) && "Expect physical register"); // Remember all registers aliasing with TargetReg. SmallSetVector<unsigned, 8> TargetRegs; for (MCRegAliasIterator AI(TargetReg, TRI, true); AI.isValid(); ++AI) TargetRegs.insert(*AI); bool Changed = false; MachineBasicBlock::iterator LastChange = MBB->begin(); unsigned SmallestDef = TargetReg; // Remove redundant Copy instructions unless TargetReg is modified. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) { MachineInstr *MI = &*I; ++I; if (MI->isCopy() && MI->getOperand(0).isReg() && MI->getOperand(1).isReg()) { unsigned DefReg = MI->getOperand(0).getReg(); unsigned SrcReg = MI->getOperand(1).getReg(); if ((SrcReg == AArch64::XZR || SrcReg == AArch64::WZR) && !MRI->isReserved(DefReg) && (TargetReg == DefReg || TRI->isSuperRegister(DefReg, TargetReg))) { DEBUG(dbgs() << "Remove redundant Copy : "); DEBUG((MI)->print(dbgs())); MI->eraseFromParent(); Changed = true; LastChange = I; NumCopiesRemoved++; SmallestDef = TRI->isSubRegister(SmallestDef, DefReg) ? DefReg : SmallestDef; continue; } } if (MI->modifiesRegister(TargetReg, TRI)) break; } if (!Changed) return false; // Otherwise, we have to fixup the use-def chain, starting with the // CBZ/CBNZ. Conservatively mark as much as we can live. CompBr->clearRegisterKills(SmallestDef, TRI); if (none_of(TargetRegs, [&](unsigned Reg) { return MBB->isLiveIn(Reg); })) MBB->addLiveIn(TargetReg); // Clear any kills of TargetReg between CompBr and the last removed COPY. for (MachineInstr &MMI : make_range(MBB->begin(), LastChange)) MMI.clearRegisterKills(SmallestDef, TRI); return true; } bool AArch64RedundantCopyElimination::runOnMachineFunction( MachineFunction &MF) { if (skipFunction(*MF.getFunction())) return false; TRI = MF.getSubtarget().getRegisterInfo(); MRI = &MF.getRegInfo(); bool Changed = false; for (MachineBasicBlock &MBB : MF) Changed |= optimizeCopy(&MBB); return Changed; } FunctionPass *llvm::createAArch64RedundantCopyEliminationPass() { return new AArch64RedundantCopyElimination(); } <commit_msg>[AArch64] Minor code refactoring. NFC.<commit_after>//=- AArch64RedundantCopyElimination.cpp - Remove useless copy for AArch64 -=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // This pass removes unnecessary zero copies in BBs that are targets of // cbz/cbnz instructions. For instance, the copy instruction in the code below // can be removed because the CBZW jumps to BB#2 when W0 is zero. // BB#1: // CBZW %W0, <BB#2> // BB#2: // %W0 = COPY %WZR // This pass should be run after register allocation. // // FIXME: This should be extended to handle any constant other than zero. E.g., // cmp w0, #1 // b.eq .BB1 // BB1: // mov w0, #1 // // FIXME: This could also be extended to check the whole dominance subtree below // the comparison if the compile time regression is acceptable. // //===----------------------------------------------------------------------===// #include "AArch64.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/iterator_range.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/Debug.h" using namespace llvm; #define DEBUG_TYPE "aarch64-copyelim" STATISTIC(NumCopiesRemoved, "Number of copies removed."); namespace { class AArch64RedundantCopyElimination : public MachineFunctionPass { const MachineRegisterInfo *MRI; const TargetRegisterInfo *TRI; public: static char ID; AArch64RedundantCopyElimination() : MachineFunctionPass(ID) { initializeAArch64RedundantCopyEliminationPass( *PassRegistry::getPassRegistry()); } bool optimizeCopy(MachineBasicBlock *MBB); bool runOnMachineFunction(MachineFunction &MF) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } StringRef getPassName() const override { return "AArch64 Redundant Copy Elimination"; } }; char AArch64RedundantCopyElimination::ID = 0; } INITIALIZE_PASS(AArch64RedundantCopyElimination, "aarch64-copyelim", "AArch64 redundant copy elimination pass", false, false) static bool guaranteesZeroRegInBlock(MachineInstr &MI, MachineBasicBlock *MBB) { unsigned Opc = MI.getOpcode(); // Check if the current basic block is the target block to which the // CBZ/CBNZ instruction jumps when its Wt/Xt is zero. return ((Opc == AArch64::CBZW || Opc == AArch64::CBZX) && MBB == MI.getOperand(1).getMBB()) || ((Opc == AArch64::CBNZW || Opc == AArch64::CBNZX) && MBB != MI.getOperand(1).getMBB()); } bool AArch64RedundantCopyElimination::optimizeCopy(MachineBasicBlock *MBB) { // Check if the current basic block has a single predecessor. if (MBB->pred_size() != 1) return false; // Check if the predecessor has two successors, implying the block ends in a // conditional branch. MachineBasicBlock *PredMBB = *MBB->pred_begin(); if (PredMBB->succ_size() != 2) return false; MachineBasicBlock::iterator CompBr = PredMBB->getLastNonDebugInstr(); if (CompBr == PredMBB->end()) return false; ++CompBr; do { --CompBr; if (guaranteesZeroRegInBlock(*CompBr, MBB)) break; } while (CompBr != PredMBB->begin() && CompBr->isTerminator()); // We've not found a CBZ/CBNZ, time to bail out. if (!guaranteesZeroRegInBlock(*CompBr, MBB)) return false; unsigned TargetReg = CompBr->getOperand(0).getReg(); if (!TargetReg) return false; assert(TargetRegisterInfo::isPhysicalRegister(TargetReg) && "Expect physical register"); // Remember all registers aliasing with TargetReg. SmallSetVector<unsigned, 8> TargetRegs; for (MCRegAliasIterator AI(TargetReg, TRI, true); AI.isValid(); ++AI) TargetRegs.insert(*AI); bool Changed = false; MachineBasicBlock::iterator LastChange = MBB->begin(); unsigned SmallestDef = TargetReg; // Remove redundant Copy instructions unless TargetReg is modified. for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) { MachineInstr *MI = &*I; ++I; if (MI->isCopy() && MI->getOperand(0).isReg() && MI->getOperand(1).isReg()) { unsigned DefReg = MI->getOperand(0).getReg(); unsigned SrcReg = MI->getOperand(1).getReg(); if ((SrcReg == AArch64::XZR || SrcReg == AArch64::WZR) && !MRI->isReserved(DefReg) && (TargetReg == DefReg || TRI->isSuperRegister(DefReg, TargetReg))) { DEBUG(dbgs() << "Remove redundant Copy : "); DEBUG((MI)->print(dbgs())); MI->eraseFromParent(); Changed = true; LastChange = I; NumCopiesRemoved++; SmallestDef = TRI->isSubRegister(SmallestDef, DefReg) ? DefReg : SmallestDef; continue; } } if (MI->modifiesRegister(TargetReg, TRI)) break; } if (!Changed) return false; // Otherwise, we have to fixup the use-def chain, starting with the // CBZ/CBNZ. Conservatively mark as much as we can live. CompBr->clearRegisterKills(SmallestDef, TRI); if (none_of(TargetRegs, [&](unsigned Reg) { return MBB->isLiveIn(Reg); })) MBB->addLiveIn(TargetReg); // Clear any kills of TargetReg between CompBr and the last removed COPY. for (MachineInstr &MMI : make_range(MBB->begin(), LastChange)) MMI.clearRegisterKills(SmallestDef, TRI); return true; } bool AArch64RedundantCopyElimination::runOnMachineFunction( MachineFunction &MF) { if (skipFunction(*MF.getFunction())) return false; TRI = MF.getSubtarget().getRegisterInfo(); MRI = &MF.getRegInfo(); bool Changed = false; for (MachineBasicBlock &MBB : MF) Changed |= optimizeCopy(&MBB); return Changed; } FunctionPass *llvm::createAArch64RedundantCopyEliminationPass() { return new AArch64RedundantCopyElimination(); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_STYLE_PROCESSOR_HPP #define MAPNIK_FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/datasource.hpp> // for featureset_ptr // stl #include <set> #include <string> #include <vector> namespace mapnik { class Map; class layer; class projection; class proj_transform; class feature_type_style; enum eAttributeCollectionPolicy { DEFAULT = 0, COLLECT_ALL = 1 }; template <typename Processor> class feature_style_processor { struct symbol_dispatch; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0); /*! * \brief apply renderer to all map layers. */ void apply(); /*! * \brief apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names); private: /*! * \brief render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names); /*! * \brief renders a featureset with the given styles. */ void render_style(layer const& lay, Processor & p, feature_type_style* style, std::string const& style_name, featureset_ptr features, proj_transform const& prj_trans, double scale_denom); Map const& m_; double scale_factor_; }; } #endif // MAPNIK_FEATURE_STYLE_PROCESSOR_HPP <commit_msg>make apply_to_layer public<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_STYLE_PROCESSOR_HPP #define MAPNIK_FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/datasource.hpp> // for featureset_ptr // stl #include <set> #include <string> #include <vector> namespace mapnik { class Map; class layer; class projection; class proj_transform; class feature_type_style; enum eAttributeCollectionPolicy { DEFAULT = 0, COLLECT_ALL = 1 }; template <typename Processor> class feature_style_processor { struct symbol_dispatch; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0); /*! * \brief apply renderer to all map layers. */ void apply(); /*! * \brief apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names); /*! * \brief render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names); private: /*! * \brief renders a featureset with the given styles. */ void render_style(layer const& lay, Processor & p, feature_type_style* style, std::string const& style_name, featureset_ptr features, proj_transform const& prj_trans, double scale_denom); Map const& m_; double scale_factor_; }; } #endif // MAPNIK_FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/lorenzsystem.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator2d.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator3d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/lic2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/hedgehog2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dmagnitude.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/4d/tmip.h> // Autogenerated #include <modules/vectorfieldvisualizationgl/shader_resources.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator4d.h> namespace inviwo { VectorFieldVisualizationGLModule::VectorFieldVisualizationGLModule(InviwoApplication* app) : InviwoModule(app, "VectorFieldVisualizationGL") { // Add a directory to the search path of the Shadermanager vectorfieldvisualizationgl::addShaderResources(ShaderManager::getPtr(), {getPath(ModulePath::GLSL)}); registerProcessor<LorenzSystem>(); registerProcessor<VectorFieldGenerator2D>(); registerProcessor<VectorFieldGenerator3D>(); registerProcessor<LIC2D>(); registerProcessor<HedgeHog2D>(); registerProcessor<Vector2DMagnitude>(); registerProcessor<Vector2DCurl>(); registerProcessor<Vector2DDivergence>(); registerProcessor<Vector3DCurl>(); registerProcessor<Vector3DDivergence>(); registerProcessor<TMIP>(); registerProcessor<VectorFieldGenerator4D>(); } int VectorFieldVisualizationGLModule::getVersion() const { return 1; } std::unique_ptr<VersionConverter> VectorFieldVisualizationGLModule::getConverter(int version) const { return util::make_unique<Converter>(version); } VectorFieldVisualizationGLModule::Converter::Converter(int version) : version_(version) {} bool VectorFieldVisualizationGLModule::Converter::convert(TxElement* root) { std::vector<xml::IdentifierReplacement> repl = {}; const std::vector<std::pair<std::string, std::string>> volumeGLrepl = { {"Vector3DCurl", "vector3dcurl.frag"}, {"Vector3DDivergence", "vector3ddivergence.frag"}}; for (const auto& i : volumeGLrepl) { xml::IdentifierReplacement inport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::inport("org.inviwo.VolumeInport")}, i.second + "inport", "inputVolume" }; xml::IdentifierReplacement outport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::outport("org.inviwo.VolumeOutport")}, i.second + "outport", "outputVolume" }; repl.push_back(inport); repl.push_back(outport); } bool res = false; switch (version_) { case 0: { res |= xml::changeIdentifiers(root, repl); } return res; default: return false; // No changes } return true; } } // namespace <commit_msg>VectorVis: Moved include<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmodule.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/lorenzsystem.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator2d.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator3d.h> #include <modules/vectorfieldvisualizationgl/processors/datageneration/vectorfieldgenerator4d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/lic2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/hedgehog2d.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dmagnitude.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/2d/vector2ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3dcurl.h> #include <modules/vectorfieldvisualizationgl/processors/3d/vector3ddivergence.h> #include <modules/vectorfieldvisualizationgl/processors/4d/tmip.h> // Autogenerated #include <modules/vectorfieldvisualizationgl/shader_resources.h> namespace inviwo { VectorFieldVisualizationGLModule::VectorFieldVisualizationGLModule(InviwoApplication* app) : InviwoModule(app, "VectorFieldVisualizationGL") { // Add a directory to the search path of the Shadermanager vectorfieldvisualizationgl::addShaderResources(ShaderManager::getPtr(), {getPath(ModulePath::GLSL)}); registerProcessor<LorenzSystem>(); registerProcessor<VectorFieldGenerator2D>(); registerProcessor<VectorFieldGenerator3D>(); registerProcessor<LIC2D>(); registerProcessor<HedgeHog2D>(); registerProcessor<Vector2DMagnitude>(); registerProcessor<Vector2DCurl>(); registerProcessor<Vector2DDivergence>(); registerProcessor<Vector3DCurl>(); registerProcessor<Vector3DDivergence>(); registerProcessor<TMIP>(); registerProcessor<VectorFieldGenerator4D>(); } int VectorFieldVisualizationGLModule::getVersion() const { return 1; } std::unique_ptr<VersionConverter> VectorFieldVisualizationGLModule::getConverter(int version) const { return util::make_unique<Converter>(version); } VectorFieldVisualizationGLModule::Converter::Converter(int version) : version_(version) {} bool VectorFieldVisualizationGLModule::Converter::convert(TxElement* root) { std::vector<xml::IdentifierReplacement> repl = {}; const std::vector<std::pair<std::string, std::string>> volumeGLrepl = { {"Vector3DCurl", "vector3dcurl.frag"}, {"Vector3DDivergence", "vector3ddivergence.frag"}}; for (const auto& i : volumeGLrepl) { xml::IdentifierReplacement inport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::inport("org.inviwo.VolumeInport")}, i.second + "inport", "inputVolume" }; xml::IdentifierReplacement outport = { {xml::Kind::processor("org.inviwo." + i.first), xml::Kind::outport("org.inviwo.VolumeOutport")}, i.second + "outport", "outputVolume" }; repl.push_back(inport); repl.push_back(outport); } bool res = false; switch (version_) { case 0: { res |= xml::changeIdentifiers(root, repl); } return res; default: return false; // No changes } return true; } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "content/renderer/media/mock_peer_connection_impl.h" #include <vector> #include "base/logging.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" using testing::_; using webrtc::AudioTrackInterface; using webrtc::CreateSessionDescriptionObserver; using webrtc::DtmfSenderInterface; using webrtc::DtmfSenderObserverInterface; using webrtc::IceCandidateInterface; using webrtc::MediaConstraintsInterface; using webrtc::MediaStreamInterface; using webrtc::PeerConnectionInterface; using webrtc::SessionDescriptionInterface; using webrtc::SetSessionDescriptionObserver; namespace content { class MockStreamCollection : public webrtc::StreamCollectionInterface { public: virtual size_t count() OVERRIDE { return streams_.size(); } virtual MediaStreamInterface* at(size_t index) OVERRIDE { return streams_[index]; } virtual MediaStreamInterface* find(const std::string& label) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { if (streams_[i]->label() == label) return streams_[i]; } return NULL; } virtual webrtc::MediaStreamTrackInterface* FindAudioTrack( const std::string& id) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { webrtc::MediaStreamTrackInterface* track = streams_.at(i)->FindAudioTrack(id); if (track) return track; } return NULL; } virtual webrtc::MediaStreamTrackInterface* FindVideoTrack( const std::string& id) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { webrtc::MediaStreamTrackInterface* track = streams_.at(i)->FindVideoTrack(id); if (track) return track; } return NULL; } void AddStream(MediaStreamInterface* stream) { streams_.push_back(stream); } void RemoveStream(MediaStreamInterface* stream) { StreamVector::iterator it = streams_.begin(); for (; it != streams_.end(); ++it) { if (it->get() == stream) { streams_.erase(it); break; } } } protected: virtual ~MockStreamCollection() {} private: typedef std::vector<talk_base::scoped_refptr<MediaStreamInterface> > StreamVector; StreamVector streams_; }; class MockDataChannel : public webrtc::DataChannelInterface { public: MockDataChannel(const std::string& label, const webrtc::DataChannelInit* config) : label_(label), reliable_(config->reliable), state_(webrtc::DataChannelInterface::kConnecting), config_(*config) { } virtual void RegisterObserver( webrtc::DataChannelObserver* observer) OVERRIDE { } virtual void UnregisterObserver() OVERRIDE { } virtual std::string label() const OVERRIDE { return label_; } virtual bool reliable() const OVERRIDE { return reliable_; } virtual bool ordered() const OVERRIDE { return config_.ordered; } virtual unsigned short maxRetransmitTime() const OVERRIDE { return config_.maxRetransmitTime; } virtual unsigned short maxRetransmits() const OVERRIDE { return config_.maxRetransmits; } virtual std::string protocol() const OVERRIDE { return config_.protocol; } virtual bool negotiated() const OVERRIDE { return config_.negotiated; } virtual int id() const OVERRIDE { NOTIMPLEMENTED(); return 0; } virtual DataState state() const OVERRIDE { return state_; } virtual uint64 buffered_amount() const OVERRIDE { NOTIMPLEMENTED(); return 0; } virtual void Close() OVERRIDE { state_ = webrtc::DataChannelInterface::kClosing; } virtual bool Send(const webrtc::DataBuffer& buffer) OVERRIDE { return state_ == webrtc::DataChannelInterface::kOpen; } protected: virtual ~MockDataChannel() {} private: std::string label_; bool reliable_; webrtc::DataChannelInterface::DataState state_; webrtc::DataChannelInit config_; }; class MockDtmfSender : public DtmfSenderInterface { public: explicit MockDtmfSender(AudioTrackInterface* track) : track_(track), observer_(NULL), duration_(0), inter_tone_gap_(0) {} virtual void RegisterObserver( DtmfSenderObserverInterface* observer) OVERRIDE { observer_ = observer; } virtual void UnregisterObserver() OVERRIDE { observer_ = NULL; } virtual bool CanInsertDtmf() OVERRIDE { return true; } virtual bool InsertDtmf(const std::string& tones, int duration, int inter_tone_gap) OVERRIDE { tones_ = tones; duration_ = duration; inter_tone_gap_ = inter_tone_gap; return true; } virtual const AudioTrackInterface* track() const OVERRIDE { return track_.get(); } virtual std::string tones() const OVERRIDE { return tones_; } virtual int duration() const OVERRIDE { return duration_; } virtual int inter_tone_gap() const OVERRIDE { return inter_tone_gap_; } protected: virtual ~MockDtmfSender() {} private: talk_base::scoped_refptr<AudioTrackInterface> track_; DtmfSenderObserverInterface* observer_; std::string tones_; int duration_; int inter_tone_gap_; }; const char MockPeerConnectionImpl::kDummyOffer[] = "dummy offer"; const char MockPeerConnectionImpl::kDummyAnswer[] = "dummy answer"; MockPeerConnectionImpl::MockPeerConnectionImpl( MockPeerConnectionDependencyFactory* factory) : dependency_factory_(factory), local_streams_(new talk_base::RefCountedObject<MockStreamCollection>), remote_streams_(new talk_base::RefCountedObject<MockStreamCollection>), hint_audio_(false), hint_video_(false), getstats_result_(true), sdp_mline_index_(-1) { ON_CALL(*this, SetLocalDescription(_, _)).WillByDefault(testing::Invoke( this, &MockPeerConnectionImpl::SetLocalDescriptionWorker)); ON_CALL(*this, SetRemoteDescription(_, _)).WillByDefault(testing::Invoke( this, &MockPeerConnectionImpl::SetRemoteDescriptionWorker)); } MockPeerConnectionImpl::~MockPeerConnectionImpl() {} talk_base::scoped_refptr<webrtc::StreamCollectionInterface> MockPeerConnectionImpl::local_streams() { return local_streams_; } talk_base::scoped_refptr<webrtc::StreamCollectionInterface> MockPeerConnectionImpl::remote_streams() { return remote_streams_; } bool MockPeerConnectionImpl::AddStream( MediaStreamInterface* local_stream, const MediaConstraintsInterface* constraints) { DCHECK(stream_label_.empty()); stream_label_ = local_stream->label(); local_streams_->AddStream(local_stream); return true; } void MockPeerConnectionImpl::RemoveStream( MediaStreamInterface* local_stream) { DCHECK_EQ(stream_label_, local_stream->label()); stream_label_.clear(); local_streams_->RemoveStream(local_stream); } talk_base::scoped_refptr<DtmfSenderInterface> MockPeerConnectionImpl::CreateDtmfSender(AudioTrackInterface* track) { if (!track) { return NULL; } return new talk_base::RefCountedObject<MockDtmfSender>(track); } talk_base::scoped_refptr<webrtc::DataChannelInterface> MockPeerConnectionImpl::CreateDataChannel(const std::string& label, const webrtc::DataChannelInit* config) { return new talk_base::RefCountedObject<MockDataChannel>(label, config); } bool MockPeerConnectionImpl::GetStats( webrtc::StatsObserver* observer, webrtc::MediaStreamTrackInterface* track, StatsOutputLevel level) { if (!getstats_result_) return false; DCHECK_EQ(kStatsOutputLevelStandard, level); std::vector<webrtc::StatsReport> reports(track ? 1 : 2); webrtc::StatsReport& report = reports[0]; report.id = "1234"; report.type = "ssrc"; report.timestamp = 42; webrtc::StatsReport::Value value; value.name = "trackname"; value.value = "trackvalue"; report.values.push_back(value); // If selector is given, we pass back one report. // If selector is not given, we pass back two. if (!track) { webrtc::StatsReport& report2 = reports[1]; report2.id = "nontrack"; report2.type = "generic"; report2.timestamp = 44; report2.values.push_back(value); value.name = "somename"; value.value = "somevalue"; report2.values.push_back(value); } // Note that the callback is synchronous, not asynchronous; it will // happen before the request call completes. observer->OnComplete(reports); return true; } const webrtc::SessionDescriptionInterface* MockPeerConnectionImpl::local_description() const { return local_desc_.get(); } const webrtc::SessionDescriptionInterface* MockPeerConnectionImpl::remote_description() const { return remote_desc_.get(); } void MockPeerConnectionImpl::AddRemoteStream(MediaStreamInterface* stream) { remote_streams_->AddStream(stream); } void MockPeerConnectionImpl::CreateOffer( CreateSessionDescriptionObserver* observer, const MediaConstraintsInterface* constraints) { DCHECK(observer); created_sessiondescription_.reset( dependency_factory_->CreateSessionDescription("unknown", kDummyOffer, NULL)); } void MockPeerConnectionImpl::CreateAnswer( CreateSessionDescriptionObserver* observer, const MediaConstraintsInterface* constraints) { DCHECK(observer); created_sessiondescription_.reset( dependency_factory_->CreateSessionDescription("unknown", kDummyAnswer, NULL)); } void MockPeerConnectionImpl::SetLocalDescriptionWorker( SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) { desc->ToString(&description_sdp_); local_desc_.reset(desc); } void MockPeerConnectionImpl::SetRemoteDescriptionWorker( SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) { desc->ToString(&description_sdp_); remote_desc_.reset(desc); } bool MockPeerConnectionImpl::UpdateIce( const IceServers& configuration, const MediaConstraintsInterface* constraints) { return true; } bool MockPeerConnectionImpl::AddIceCandidate( const IceCandidateInterface* candidate) { sdp_mid_ = candidate->sdp_mid(); sdp_mline_index_ = candidate->sdp_mline_index(); return candidate->ToString(&ice_sdp_); } void MockPeerConnectionImpl::RegisterUMAObserver( webrtc::UMAObserver* observer) { NOTIMPLEMENTED(); } } // namespace content <commit_msg>Fix an issue with an upcoming webrtc roll where the 'name' property of StatsReport::Value is const.<commit_after>// Copyright (c) 2012 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 "content/renderer/media/mock_peer_connection_impl.h" #include <vector> #include "base/logging.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" using testing::_; using webrtc::AudioTrackInterface; using webrtc::CreateSessionDescriptionObserver; using webrtc::DtmfSenderInterface; using webrtc::DtmfSenderObserverInterface; using webrtc::IceCandidateInterface; using webrtc::MediaConstraintsInterface; using webrtc::MediaStreamInterface; using webrtc::PeerConnectionInterface; using webrtc::SessionDescriptionInterface; using webrtc::SetSessionDescriptionObserver; namespace content { class MockStreamCollection : public webrtc::StreamCollectionInterface { public: virtual size_t count() OVERRIDE { return streams_.size(); } virtual MediaStreamInterface* at(size_t index) OVERRIDE { return streams_[index]; } virtual MediaStreamInterface* find(const std::string& label) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { if (streams_[i]->label() == label) return streams_[i]; } return NULL; } virtual webrtc::MediaStreamTrackInterface* FindAudioTrack( const std::string& id) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { webrtc::MediaStreamTrackInterface* track = streams_.at(i)->FindAudioTrack(id); if (track) return track; } return NULL; } virtual webrtc::MediaStreamTrackInterface* FindVideoTrack( const std::string& id) OVERRIDE { for (size_t i = 0; i < streams_.size(); ++i) { webrtc::MediaStreamTrackInterface* track = streams_.at(i)->FindVideoTrack(id); if (track) return track; } return NULL; } void AddStream(MediaStreamInterface* stream) { streams_.push_back(stream); } void RemoveStream(MediaStreamInterface* stream) { StreamVector::iterator it = streams_.begin(); for (; it != streams_.end(); ++it) { if (it->get() == stream) { streams_.erase(it); break; } } } protected: virtual ~MockStreamCollection() {} private: typedef std::vector<talk_base::scoped_refptr<MediaStreamInterface> > StreamVector; StreamVector streams_; }; class MockDataChannel : public webrtc::DataChannelInterface { public: MockDataChannel(const std::string& label, const webrtc::DataChannelInit* config) : label_(label), reliable_(config->reliable), state_(webrtc::DataChannelInterface::kConnecting), config_(*config) { } virtual void RegisterObserver( webrtc::DataChannelObserver* observer) OVERRIDE { } virtual void UnregisterObserver() OVERRIDE { } virtual std::string label() const OVERRIDE { return label_; } virtual bool reliable() const OVERRIDE { return reliable_; } virtual bool ordered() const OVERRIDE { return config_.ordered; } virtual unsigned short maxRetransmitTime() const OVERRIDE { return config_.maxRetransmitTime; } virtual unsigned short maxRetransmits() const OVERRIDE { return config_.maxRetransmits; } virtual std::string protocol() const OVERRIDE { return config_.protocol; } virtual bool negotiated() const OVERRIDE { return config_.negotiated; } virtual int id() const OVERRIDE { NOTIMPLEMENTED(); return 0; } virtual DataState state() const OVERRIDE { return state_; } virtual uint64 buffered_amount() const OVERRIDE { NOTIMPLEMENTED(); return 0; } virtual void Close() OVERRIDE { state_ = webrtc::DataChannelInterface::kClosing; } virtual bool Send(const webrtc::DataBuffer& buffer) OVERRIDE { return state_ == webrtc::DataChannelInterface::kOpen; } protected: virtual ~MockDataChannel() {} private: std::string label_; bool reliable_; webrtc::DataChannelInterface::DataState state_; webrtc::DataChannelInit config_; }; class MockDtmfSender : public DtmfSenderInterface { public: explicit MockDtmfSender(AudioTrackInterface* track) : track_(track), observer_(NULL), duration_(0), inter_tone_gap_(0) {} virtual void RegisterObserver( DtmfSenderObserverInterface* observer) OVERRIDE { observer_ = observer; } virtual void UnregisterObserver() OVERRIDE { observer_ = NULL; } virtual bool CanInsertDtmf() OVERRIDE { return true; } virtual bool InsertDtmf(const std::string& tones, int duration, int inter_tone_gap) OVERRIDE { tones_ = tones; duration_ = duration; inter_tone_gap_ = inter_tone_gap; return true; } virtual const AudioTrackInterface* track() const OVERRIDE { return track_.get(); } virtual std::string tones() const OVERRIDE { return tones_; } virtual int duration() const OVERRIDE { return duration_; } virtual int inter_tone_gap() const OVERRIDE { return inter_tone_gap_; } protected: virtual ~MockDtmfSender() {} private: talk_base::scoped_refptr<AudioTrackInterface> track_; DtmfSenderObserverInterface* observer_; std::string tones_; int duration_; int inter_tone_gap_; }; const char MockPeerConnectionImpl::kDummyOffer[] = "dummy offer"; const char MockPeerConnectionImpl::kDummyAnswer[] = "dummy answer"; MockPeerConnectionImpl::MockPeerConnectionImpl( MockPeerConnectionDependencyFactory* factory) : dependency_factory_(factory), local_streams_(new talk_base::RefCountedObject<MockStreamCollection>), remote_streams_(new talk_base::RefCountedObject<MockStreamCollection>), hint_audio_(false), hint_video_(false), getstats_result_(true), sdp_mline_index_(-1) { ON_CALL(*this, SetLocalDescription(_, _)).WillByDefault(testing::Invoke( this, &MockPeerConnectionImpl::SetLocalDescriptionWorker)); ON_CALL(*this, SetRemoteDescription(_, _)).WillByDefault(testing::Invoke( this, &MockPeerConnectionImpl::SetRemoteDescriptionWorker)); } MockPeerConnectionImpl::~MockPeerConnectionImpl() {} talk_base::scoped_refptr<webrtc::StreamCollectionInterface> MockPeerConnectionImpl::local_streams() { return local_streams_; } talk_base::scoped_refptr<webrtc::StreamCollectionInterface> MockPeerConnectionImpl::remote_streams() { return remote_streams_; } bool MockPeerConnectionImpl::AddStream( MediaStreamInterface* local_stream, const MediaConstraintsInterface* constraints) { DCHECK(stream_label_.empty()); stream_label_ = local_stream->label(); local_streams_->AddStream(local_stream); return true; } void MockPeerConnectionImpl::RemoveStream( MediaStreamInterface* local_stream) { DCHECK_EQ(stream_label_, local_stream->label()); stream_label_.clear(); local_streams_->RemoveStream(local_stream); } talk_base::scoped_refptr<DtmfSenderInterface> MockPeerConnectionImpl::CreateDtmfSender(AudioTrackInterface* track) { if (!track) { return NULL; } return new talk_base::RefCountedObject<MockDtmfSender>(track); } talk_base::scoped_refptr<webrtc::DataChannelInterface> MockPeerConnectionImpl::CreateDataChannel(const std::string& label, const webrtc::DataChannelInit* config) { return new talk_base::RefCountedObject<MockDataChannel>(label, config); } bool MockPeerConnectionImpl::GetStats( webrtc::StatsObserver* observer, webrtc::MediaStreamTrackInterface* track, StatsOutputLevel level) { if (!getstats_result_) return false; DCHECK_EQ(kStatsOutputLevelStandard, level); std::vector<webrtc::StatsReport> reports(track ? 1 : 2); webrtc::StatsReport& report = reports[0]; report.id = "1234"; report.type = "ssrc"; report.timestamp = 42; webrtc::StatsReport::Value value = { webrtc::StatsReport::kStatsValueNameFingerprint, "trackvalue" }; report.values.push_back(value); // If selector is given, we pass back one report. // If selector is not given, we pass back two. if (!track) { webrtc::StatsReport& report2 = reports[1]; report2.id = "nontrack"; report2.type = "generic"; report2.timestamp = 44; report2.values.push_back(value); webrtc::StatsReport::Value value2 = { webrtc::StatsReport::kStatsValueNameFingerprintAlgorithm, "somevalue" }; report2.values.push_back(value2); } // Note that the callback is synchronous, not asynchronous; it will // happen before the request call completes. observer->OnComplete(reports); return true; } const webrtc::SessionDescriptionInterface* MockPeerConnectionImpl::local_description() const { return local_desc_.get(); } const webrtc::SessionDescriptionInterface* MockPeerConnectionImpl::remote_description() const { return remote_desc_.get(); } void MockPeerConnectionImpl::AddRemoteStream(MediaStreamInterface* stream) { remote_streams_->AddStream(stream); } void MockPeerConnectionImpl::CreateOffer( CreateSessionDescriptionObserver* observer, const MediaConstraintsInterface* constraints) { DCHECK(observer); created_sessiondescription_.reset( dependency_factory_->CreateSessionDescription("unknown", kDummyOffer, NULL)); } void MockPeerConnectionImpl::CreateAnswer( CreateSessionDescriptionObserver* observer, const MediaConstraintsInterface* constraints) { DCHECK(observer); created_sessiondescription_.reset( dependency_factory_->CreateSessionDescription("unknown", kDummyAnswer, NULL)); } void MockPeerConnectionImpl::SetLocalDescriptionWorker( SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) { desc->ToString(&description_sdp_); local_desc_.reset(desc); } void MockPeerConnectionImpl::SetRemoteDescriptionWorker( SetSessionDescriptionObserver* observer, SessionDescriptionInterface* desc) { desc->ToString(&description_sdp_); remote_desc_.reset(desc); } bool MockPeerConnectionImpl::UpdateIce( const IceServers& configuration, const MediaConstraintsInterface* constraints) { return true; } bool MockPeerConnectionImpl::AddIceCandidate( const IceCandidateInterface* candidate) { sdp_mid_ = candidate->sdp_mid(); sdp_mline_index_ = candidate->sdp_mline_index(); return candidate->ToString(&ice_sdp_); } void MockPeerConnectionImpl::RegisterUMAObserver( webrtc::UMAObserver* observer) { NOTIMPLEMENTED(); } } // namespace content <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Gabriel Motta <[email protected]> * @since 0.1.9 * @date September, 2021 * * @section LICENSE * * Copyright (C) 2021, Gabriel Motta. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Average data from a raw data file * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <utils/files.h> #include <chrono> #include <string> #include <iostream> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QCoreApplication> #include <QCommandLineParser> #include <QDir> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace UTILSLIB; //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param[in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param[in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("File Utils Example"); parser.addHelpOption(); QCommandLineOption stepOption("step", "Steps through each command waiting for input before proceeding.", "pickAll", "true"); parser.addOption(stepOption); parser.process(a); bool bStep = (parser.value("step") == "true"); std::string sDirPath = QCoreApplication::applicationDirPath().toStdString(); std::string sFilePath = sDirPath + "/test.txt"; std::cout << "===== Creating File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } Files::create(sFilePath); std::cout << "===== Checking File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string answer; if (Files::exists(sFilePath)){ answer = "Yes."; } else { answer = "No."; } std::cout << "Does file exist? " << answer << "\n"; std::cout << "===== Copying File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string sFilePath2 = sDirPath + "/test_copy.txt"; std::string sFilePath3 = sDirPath + "/another_test_copy.txt"; Files::copy(sFilePath, sFilePath2); Files::copy(sFilePath2, sFilePath); std::cout << "===== Renaming File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string sFilePath4 = sDirPath + "/another_test_copy.txt"; Files::rename(sFilePath3, sFilePath4); return a.exec(); } <commit_msg>debug file utils example<commit_after>//============================================================================================================= /** * @file main.cpp * @author Gabriel Motta <[email protected]> * @since 0.1.9 * @date September, 2021 * * @section LICENSE * * Copyright (C) 2021, Gabriel Motta. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Average data from a raw data file * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <utils/files.h> #include <chrono> #include <string> #include <iostream> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QCoreApplication> #include <QCommandLineParser> #include <QDir> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace UTILSLIB; //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param[in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param[in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("File Utils Example"); parser.addHelpOption(); QCommandLineOption stepOption("step", "Steps through each command waiting for input before proceeding.", "pickAll", "true"); parser.addOption(stepOption); parser.process(a); bool bStep = (parser.value("step") == "true"); std::string sDirPath = QCoreApplication::applicationDirPath().toStdString(); std::string sFilePath = sDirPath + "/test.txt"; std::cout << "===== Creating File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } Files::create(sFilePath); std::cout << "===== Checking File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string answer; if (Files::exists(sFilePath)){ answer = "Yes."; } else { answer = "No."; } std::cout << "Does file exist? " << answer << "\n"; std::cout << "===== Copying File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string sFilePath2 = sDirPath + "/test_copy.txt"; std::string sFilePath3 = sDirPath + "/another_test_copy.txt"; Files::copy(sFilePath, sFilePath2); Files::copy(sFilePath2, sFilePath3); std::cout << "===== Renaming File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } std::string sFilePath4 = sDirPath + "/yet_another_test_copy.txt"; Files::rename(sFilePath3, sFilePath4); std::cout << "===== Removing File =====\n"; if(bStep){ std::cout << "Press RETURN to execute.\n"; std::cin.get(); } Files::remove(sFilePath); Files::remove(sFilePath2); Files::remove(sFilePath4); return a.exec(); } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <fstream> #include <cstring> #include <vector> #include <queue> using namespace std; class const_string { const char* _M_str; public: explicit const_string(const char* _str): _M_str(_str){} ~const_string(){} const char* str() const {return this->_M_str;} bool operator==(const const_string& _cstr) {return this==&_cstr;} bool operator!=(const const_string& _cstr) {return this!=&_cstr;} template<class ostream_type> friend ostream_type& operator<<(ostream_type& os, const const_string& _cstr) {return os << _cstr._M_str;} operator const char*() const {return this->_M_str;} }; namespace span { const const_string preprocessor("<span style=\"color: #00a000\">"), comment("<span style=\"color: #a0a0a0\">"), string("<span style=\"color: #ff0000\">"), character("<span style=\"color: #e0a000\">"), special_character("<span style=\"color: #d923e9\">"), number("<span style=\"color: #d923e9\">"), keyword("<span style=\"color: #0000ff;font-weight: bold\">"), type("<span style=\"color: #c90049;font-weight: bold;\">"), function("<span style=\"\">"), operators("<span style=\"color: #61612d\">"), true_false("<span style=\"color: #d923e9\">"), end("</span>"); } // main.cpp extern const bool is_name[], is_true_name[]; inline string safe_character(char _c) { if(_c=='<') return "&lt"; if(_c=='>') return "&gt"; if(_c=='&') return "&amp"; return string(&_c, 1); } inline string safe_string(const string& str) { string ret; for(string::const_iterator i=str.begin(); i!=str.end(); ++i) ret+=safe_character(*i); return ret; } // coloring.cpp namespace coloring { void init(); string synax_highlight(const string& code); void color_code(const string& code, ostream& output); } // aho.cpp class aho { class class_trie { public: struct node { int E[256], fail, long_sh_pat, pattern_id; // fail pointer, max shorter pattern, pattern id bool is_pattern; // is pattern end in this vertex unsigned char character; // this node character node(unsigned char letter=0): is_pattern(false), character(letter) { for(int i=0; i<256; ++i) E[i]=0; } ~node(){} }; vector<node> graph; class_trie(): graph(1) // add root { this->graph.front().fail=this->graph.front().long_sh_pat=0; // max shorter pattern isn't exist } void swap(class_trie& _t) { this->graph.swap(_t.graph); } int add_word(const string& word, int id); void add_fails(); // and the longest shorter patterns, based on BFS algorithm } trie; vector<vector<unsigned>* > fin; // finding patterns public: vector<vector<unsigned>* >::size_type size() {return this->fin.size();} vector<unsigned>& operator[](vector<vector<unsigned>* >::size_type n) {return *this->fin[n];} const vector<unsigned>& operator[](vector<vector<unsigned>* >::size_type n) const {return *this->fin[n];} void swap(aho& _a) { this->trie.swap(_a.trie); this->fin.swap(_a.fin); } void find(const vector<string>& patterns, const string& text); }; class special_aho { class class_trie { public: struct node { int E[256], fail, long_sh_pat, pattern_id; // fail pointer, max shorter pattern, pattern id bool is_pattern; // is pattern end in this vertex // unsigned char color; // highlight color unsigned char character; // this node character node(unsigned char letter=0): is_pattern(false), character(letter) { for(int i=0; i<256; ++i) E[i]=0; } ~node(){} }; vector<node> graph; class_trie(): graph(1) // add root { this->graph.front().fail=this->graph.front().long_sh_pat=0; // max shorter pattern isn't exist } void swap(class_trie& _t) { this->graph.swap(_t.graph); } int add_word(const string& word, int id); void add_fails(); // and the longest shorter patterns, based on BFS algorithm } trie; vector<pair<string, const_string> > patterns; vector<int> fin; // finding patterns public: vector<int>::size_type size() {return this->fin.size();} int& operator[](vector<int>::size_type n) {return this->fin[n];} const int& operator[](vector<int>::size_type n) const {return this->fin[n];} void swap(special_aho& _a) { this->trie.swap(_a.trie); this->fin.swap(_a.fin); } const pair<string, const_string>& pattern(vector<pair<string, const_string> >::size_type n) const {return this->patterns[n];} void set_patterns(const vector<pair<string, const_string> >& new_patterns); void find(const string& text); };<commit_msg>Removed potential bug<commit_after>#pragma once #include <iostream> #include <fstream> #include <cstring> #include <vector> #include <queue> using namespace std; class const_string { char* _M_str; public: explicit const_string(const char* _str): _M_str(new char[strlen(_str)+1]) { memcpy(this->_M_str, _str, strlen(_str)+1); } ~const_string(){} const char* str() const {return this->_M_str;} bool operator==(const const_string& _cstr) {return this==&_cstr;} bool operator!=(const const_string& _cstr) {return this!=&_cstr;} template<class ostream_type> friend ostream_type& operator<<(ostream_type& os, const const_string& _cstr) {return os << _cstr._M_str;} operator const char*() const {return this->_M_str;} }; namespace span { const const_string preprocessor("<span style=\"color: #00a000\">"), comment("<span style=\"color: #a0a0a0\">"), string("<span style=\"color: #ff0000\">"), character("<span style=\"color: #e0a000\">"), special_character("<span style=\"color: #d923e9\">"), number("<span style=\"color: #d923e9\">"), keyword("<span style=\"color: #0000ff;font-weight: bold\">"), type("<span style=\"color: #c90049;font-weight: bold;\">"), function("<span style=\"\">"), operators("<span style=\"color: #61612d\">"), true_false("<span style=\"color: #d923e9\">"), end("</span>"); } // main.cpp extern const bool is_name[], is_true_name[]; inline string safe_character(char _c) { if(_c=='<') return "&lt"; if(_c=='>') return "&gt"; if(_c=='&') return "&amp"; return string(&_c, 1); } inline string safe_string(const string& str) { string ret; for(string::const_iterator i=str.begin(); i!=str.end(); ++i) ret+=safe_character(*i); return ret; } // coloring.cpp namespace coloring { void init(); string synax_highlight(const string& code); void color_code(const string& code, ostream& output); } // aho.cpp class aho { class class_trie { public: struct node { int E[256], fail, long_sh_pat, pattern_id; // fail pointer, max shorter pattern, pattern id bool is_pattern; // is pattern end in this vertex unsigned char character; // this node character node(unsigned char letter=0): is_pattern(false), character(letter) { for(int i=0; i<256; ++i) E[i]=0; } ~node(){} }; vector<node> graph; class_trie(): graph(1) // add root { this->graph.front().fail=this->graph.front().long_sh_pat=0; // max shorter pattern isn't exist } void swap(class_trie& _t) { this->graph.swap(_t.graph); } int add_word(const string& word, int id); void add_fails(); // and the longest shorter patterns, based on BFS algorithm } trie; vector<vector<unsigned>* > fin; // finding patterns public: vector<vector<unsigned>* >::size_type size() {return this->fin.size();} vector<unsigned>& operator[](vector<vector<unsigned>* >::size_type n) {return *this->fin[n];} const vector<unsigned>& operator[](vector<vector<unsigned>* >::size_type n) const {return *this->fin[n];} void swap(aho& _a) { this->trie.swap(_a.trie); this->fin.swap(_a.fin); } void find(const vector<string>& patterns, const string& text); }; class special_aho { class class_trie { public: struct node { int E[256], fail, long_sh_pat, pattern_id; // fail pointer, max shorter pattern, pattern id bool is_pattern; // is pattern end in this vertex // unsigned char color; // highlight color unsigned char character; // this node character node(unsigned char letter=0): is_pattern(false), character(letter) { for(int i=0; i<256; ++i) E[i]=0; } ~node(){} }; vector<node> graph; class_trie(): graph(1) // add root { this->graph.front().fail=this->graph.front().long_sh_pat=0; // max shorter pattern isn't exist } void swap(class_trie& _t) { this->graph.swap(_t.graph); } int add_word(const string& word, int id); void add_fails(); // and the longest shorter patterns, based on BFS algorithm } trie; vector<pair<string, const_string> > patterns; vector<int> fin; // finding patterns public: vector<int>::size_type size() {return this->fin.size();} int& operator[](vector<int>::size_type n) {return this->fin[n];} const int& operator[](vector<int>::size_type n) const {return this->fin[n];} void swap(special_aho& _a) { this->trie.swap(_a.trie); this->fin.swap(_a.fin); } const pair<string, const_string>& pattern(vector<pair<string, const_string> >::size_type n) const {return this->patterns[n];} void set_patterns(const vector<pair<string, const_string> >& new_patterns); void find(const string& text); };<|endoftext|>
<commit_before>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_DUSELTRONIK_HPP #define TAOCPP_PEGTL_INCLUDE_INTERNAL_DUSELTRONIK_HPP #include "../apply_mode.hpp" #include "../config.hpp" #include "../rewind_mode.hpp" #include "dusel_mode.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { namespace internal { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, dusel_mode = dusel_mode::NOTHING > struct duseltronik; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::NOTHING > { template< typename Input, typename... States > static auto match( Input& in, States&&... st ) -> decltype( Rule::template match< A, M, Action, Control >( in, st... ), true ) { return Rule::template match< A, M, Action, Control >( in, st... ); } // NOTE: The additional "int = 0" is a work-around for missing expression SFINAE in VS2015. template< typename Input, typename... States, int = 0 > static auto match( Input& in, States&&... ) -> decltype( Rule::match( in ), true ) { return Rule::match( in ); } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { Control< Rule >::start( const_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, M, Action, Control, dusel_mode::NOTHING >::match( in, st... ) ) { Control< Rule >::success( const_cast< const Input& >( in ), st... ); return true; } Control< Rule >::failure( const_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY_VOID > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { Control< Rule >::template apply< Action >( m.iterator(), const_cast< const Input& >( in ), st... ); return m( true ); } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY0_VOID > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { if( duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { Control< Rule >::template apply0< Action >( const_cast< const Input& >( in ), st... ); return true; } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY_BOOL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { return m( Control< Rule >::template apply< Action >( m.iterator(), const_cast< const Input& >( in ), st... ) ); } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY0_BOOL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { return m( Control< Rule >::template apply0< Action >( const_cast< const Input& >( in ), st... ) ); } return false; } }; } // namespace internal } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #endif <commit_msg>Fix order.<commit_after>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_DUSELTRONIK_HPP #define TAOCPP_PEGTL_INCLUDE_INTERNAL_DUSELTRONIK_HPP #include "../apply_mode.hpp" #include "../config.hpp" #include "../rewind_mode.hpp" #include "dusel_mode.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { namespace internal { template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control, dusel_mode = dusel_mode::NOTHING > struct duseltronik; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::NOTHING > { template< typename Input, typename... States > static auto match( Input& in, States&&... st ) -> decltype( Rule::template match< A, M, Action, Control >( in, st... ), true ) { return Rule::template match< A, M, Action, Control >( in, st... ); } // NOTE: The additional "int = 0" is a work-around for missing expression SFINAE in VS2015. template< typename Input, typename... States, int = 0 > static auto match( Input& in, States&&... ) -> decltype( Rule::match( in ), true ) { return Rule::match( in ); } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { Control< Rule >::start( const_cast< const Input& >( in ), st... ); if( duseltronik< Rule, A, M, Action, Control, dusel_mode::NOTHING >::match( in, st... ) ) { Control< Rule >::success( const_cast< const Input& >( in ), st... ); return true; } Control< Rule >::failure( const_cast< const Input& >( in ), st... ); return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY_VOID > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { Control< Rule >::template apply< Action >( m.iterator(), const_cast< const Input& >( in ), st... ); return m( true ); } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY_BOOL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { return m( Control< Rule >::template apply< Action >( m.iterator(), const_cast< const Input& >( in ), st... ) ); } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY0_VOID > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { if( duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { Control< Rule >::template apply0< Action >( const_cast< const Input& >( in ), st... ); return true; } return false; } }; template< typename Rule, apply_mode A, rewind_mode M, template< typename... > class Action, template< typename... > class Control > struct duseltronik< Rule, A, M, Action, Control, dusel_mode::CONTROL_AND_APPLY0_BOOL > { template< typename Input, typename... States > static bool match( Input& in, States&&... st ) { auto m = in.template mark< rewind_mode::REQUIRED >(); if( duseltronik< Rule, A, rewind_mode::ACTIVE, Action, Control, dusel_mode::CONTROL >::match( in, st... ) ) { return m( Control< Rule >::template apply0< Action >( const_cast< const Input& >( in ), st... ) ); } return false; } }; } // namespace internal } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #endif <|endoftext|>
<commit_before>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "ConfigEnv.h" ConfigMgr Config; //#define _CONFIG_DEBUG ConfigFile::ConfigFile() { } ConfigFile::~ConfigFile() { } void remove_spaces(std::string & str) { while (str.size() && (*str.begin() == ' ' || *str.begin() == '\t')) str.erase(str.begin()); } void remove_all_spaces(std::string & str) { std::string::size_type off = str.find(" "); while (off != std::string::npos) { str.erase(off, 1); off = str.find(" "); } off = str.find("\t"); while (off != std::string::npos) { str.erase(off, 1); off = str.find("\t"); } } bool is_comment(std::string & str, bool* in_multiline_quote) { std::string stemp = str; remove_spaces(stemp); if (stemp.length() == 0) return false; if (stemp[0] == '/') { if (stemp.length() < 2) return false; if (stemp[1] == '*') { *in_multiline_quote = true; return true; } else if (stemp[2] == '/') { return true; } } if (stemp[0] == '#') return true; return false; } void apply_setting(std::string & str, ConfigSetting & setting) { setting.AsString = str; setting.AsInt = atoi(str.c_str()); setting.AsBool = (setting.AsInt > 0); setting.AsFloat = (float)atof(str.c_str()); // check for verbal yes/no answers if (str.length() > 1) { // this might be a yes/no? if (str.size() >= 3 && !strnicmp("yes", str.c_str(), 3)) { setting.AsBool = true; setting.AsInt = 1; } else if (str.size() >= 2 && !strnicmp("no", str.c_str(), 2)) { setting.AsBool = false; setting.AsInt = 0; } } } uint32 ahash(const char* str) { register size_t len = strlen(str); register uint32 ret = 0; register size_t i = 0; for (; i < len; ++i) ret += 5 * ret + (tolower(str[i])); //printf("%s : %u\n", str, ret); return ret; } uint32 ahash(std::string & str) { return ahash(str.c_str()); } bool ConfigFile::SetSource(const char* file, bool ignorecase) { // wipe any existing settings m_settings.clear(); // open the file if (file != 0) { //the right mode in Windows is "rb" since '\n' is saved as 0x0D,0x0A but fopen(file,"r") reads these 2 chars //as only 1 char, so ftell(f) returns a higher value than the required by fread() to the file to buf. #ifdef WIN32 FILE* f = fopen(file, "rb"); #else FILE* f = fopen(file, "r"); #endif char* buf; int length; if (!f) { sLog.outError("Could not open %s.", file); return false; } // get the length of the file fseek(f, 0, SEEK_END); length = ftell(f); if (length < 0) return false; buf = new char[length + 1]; fseek(f, 0, SEEK_SET); // read the file if (fread(buf, length, 1, f) != 1) { sLog.outError("Could not read %s.", file); // delete buf and close the file before returning delete[] buf; fclose(f); return false; } buf[length] = '\0'; std::string buffer = std::string(buf); delete[] buf; // close the file, it is no longer needed fclose(f); // let's parse it std::string line; std::string::size_type end; std::string::size_type offset; bool in_multiline_comment = false; bool in_multiline_quote = false; bool in_block = false; std::string current_setting = ""; std::string current_variable = ""; std::string current_block = ""; ConfigBlock current_block_map; ConfigSetting current_setting_struct; // oh god this is awful try { for (;;) { // grab a line end = buffer.find(EOL); if (end == std::string::npos) { if (buffer.size() == 0) break; line = buffer; buffer.clear(); goto parse; } line = buffer.substr(0, end); buffer.erase(0, end + EOL_SIZE); goto parse; parse: if (!line.size()) continue; // are we a comment? if (!in_multiline_comment && is_comment(line, &in_multiline_comment)) { // our line is a comment if (!in_multiline_comment) { // the entire line is a comment, skip it continue; } } // handle our cases if (in_multiline_comment) { // we need to find a "*/". offset = line.find("*/", 0); // skip this entire line, eh? if (offset == std::string::npos) continue; // remove up to the end of the comment block line.erase(0, offset + 2); in_multiline_comment = false; } if (in_block) { // handle settings across multiple lines if (in_multiline_quote) { // attempt to find the end of the quote block offset = line.find("\""); if (offset == std::string::npos) { // append the whole line to the quote current_setting += line; current_setting += "\n"; continue; } // only append part of the line to the setting current_setting.append(line.c_str(), offset + 1); line.erase(0, offset + 1); // append the setting to the config block if (current_block == "" || current_variable == "") { sLog.outError("Quote without variable."); return false; } // apply the setting apply_setting(current_setting, current_setting_struct); // the setting is done, append it to the current block current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif // no longer doing this setting, or in a quote current_setting = ""; current_variable = ""; in_multiline_quote = false; } // remove any leading spaces remove_spaces(line); if (!line.size()) continue; // our target is a *setting*. look for an '=' sign, this is our seperator offset = line.find("="); if (offset != std::string::npos) { ASSERT(current_variable == ""); current_variable = line.substr(0, offset); // remove any spaces from the end of the setting remove_all_spaces(current_variable); // remove the directive *and* the = from the line line.erase(0, offset + 1); } // look for the opening quote. this signifies the start of a setting offset = line.find("\""); if (offset != std::string::npos) { ASSERT(current_setting == ""); ASSERT(current_variable != ""); // try and find the ending quote end = line.find("\"", offset + 1); if (end != std::string::npos) { // the closing quote is on the same line, oh goody current_setting = line.substr(offset + 1, end - offset - 1); // erase up to the end line.erase(0, end + 1); // apply the setting apply_setting(current_setting, current_setting_struct); // the setting is done, append it to the current block current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif // no longer doing this setting, or in a quote current_setting = ""; current_variable = ""; in_multiline_quote = false; // attempt to grab more settings from the same line goto parse; } else { // the closing quote is not on the same line. means we'll try and find it on the next current_setting.append(line.c_str(), offset); // skip to the next line. (after setting our condition first, of course :P in_multiline_quote = true; continue; } } // are we at the end of the block yet? offset = line.find(">"); if (offset != std::string::npos) { line.erase(0, offset + 1); // freeeee! in_block = false; // assign this block to the main "big" map m_settings[ahash(current_block)] = current_block_map; // erase all data for this so it doesn't seep through current_block_map.clear(); current_setting = ""; current_variable = ""; current_block = ""; } } else { // we're not in a block. look for the start of one offset = line.find("<"); if (offset != std::string::npos) { in_block = true; // whee, a block! let's cut the string and re-parse line.erase(0, offset + 1); // find the name of the block first, though offset = line.find(" "); if (offset != std::string::npos) { current_block = line.substr(0, offset); line.erase(0, offset + 1); } else { sLog.outError("Block without name."); return false; } // skip back goto parse; } } } } catch (...) { sLog.outError("Exception in config parsing."); return false; } // handle any errors if (in_block) { sLog.outError("Unterminated block."); return false; } if (in_multiline_comment) { sLog.outError("Unterminated comment."); return false; } if (in_multiline_quote) { sLog.outError("Unterminated quote."); return false; } return true; } return false; } ConfigSetting* ConfigFile::GetSetting(const char* Block, const char* Setting) { uint32 block_hash = ahash(Block); uint32 setting_hash = ahash(Setting); // find it in the big map std::map<uint32, ConfigBlock>::iterator itr = m_settings.find(block_hash); if (itr != m_settings.end()) { ConfigBlock::iterator it2 = itr->second.find(setting_hash); if (it2 != itr->second.end()) return &(it2->second); return 0; } return 0; } bool ConfigFile::GetString(const char* block, const char* name, std::string* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsString; return true; } std::string ConfigFile::GetStringDefault(const char* block, const char* name, const char* def) { std::string ret; return GetString(block, name, &ret) ? ret : def; } bool ConfigFile::GetBool(const char* block, const char* name, bool* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsBool; return true; } bool ConfigFile::GetBoolDefault(const char* block, const char* name, const bool def /* = false */) { bool val; return GetBool(block, name, &val) ? val : def; } bool ConfigFile::GetInt(const char* block, const char* name, int* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsInt; return true; } bool ConfigFile::GetFloat(const char* block, const char* name, float* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsFloat; return true; } int ConfigFile::GetIntDefault(const char* block, const char* name, const int def) { int val; return GetInt(block, name, &val) ? val : def; } float ConfigFile::GetFloatDefault(const char* block, const char* name, const float def) { float val; return (GetFloat(block, name, &val) ? val : def); } int ConfigFile::GetIntVA(const char* block, int def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); int val; return GetInt(str, block, &val) ? val : def; } float ConfigFile::GetFloatVA(const char* block, float def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); float val; return GetFloat(str, block, &val) ? val : def; } std::string ConfigFile::GetStringVA(const char* block, const char* def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); return GetStringDefault(str, block, def); } bool ConfigFile::GetString(const char* block, char* buffer, const char* name, const char* def, uint32 len) { std::string val = GetStringDefault(block, name, def); size_t blen = val.length(); if (blen > len) blen = len; memcpy(buffer, val.c_str(), blen); buffer[blen] = 0; return true; } <commit_msg>Attemp to resolve CID53179<commit_after>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "ConfigEnv.h" ConfigMgr Config; //#define _CONFIG_DEBUG ConfigFile::ConfigFile() { } ConfigFile::~ConfigFile() { } void remove_spaces(std::string & str) { while (str.size() && (*str.begin() == ' ' || *str.begin() == '\t')) str.erase(str.begin()); } void remove_all_spaces(std::string & str) { std::string::size_type off = str.find(" "); while (off != std::string::npos) { str.erase(off, 1); off = str.find(" "); } off = str.find("\t"); while (off != std::string::npos) { str.erase(off, 1); off = str.find("\t"); } } bool is_comment(std::string & str, bool* in_multiline_quote) { std::string stemp = str; remove_spaces(stemp); if (stemp.length() == 0) return false; if (stemp[0] == '/') { if (stemp.length() < 2) return false; if (stemp[1] == '*') { *in_multiline_quote = true; return true; } else if (stemp[2] == '/') { return true; } } if (stemp[0] == '#') return true; return false; } void apply_setting(std::string & str, ConfigSetting & setting) { setting.AsString = str; setting.AsInt = atoi(str.c_str()); setting.AsBool = (setting.AsInt > 0); setting.AsFloat = (float)atof(str.c_str()); // check for verbal yes/no answers if (str.length() > 1) { // this might be a yes/no? if (str.size() >= 3 && !strnicmp("yes", str.c_str(), 3)) { setting.AsBool = true; setting.AsInt = 1; } else if (str.size() >= 2 && !strnicmp("no", str.c_str(), 2)) { setting.AsBool = false; setting.AsInt = 0; } } } uint32 ahash(const char* str) { register size_t len = strlen(str); register uint32 ret = 0; register size_t i = 0; for (; i < len; ++i) ret += 5 * ret + (tolower(str[i])); //printf("%s : %u\n", str, ret); return ret; } uint32 ahash(std::string & str) { return ahash(str.c_str()); } bool ConfigFile::SetSource(const char* file, bool ignorecase) { // wipe any existing settings m_settings.clear(); // open the file if (file != 0) { //the right mode in Windows is "rb" since '\n' is saved as 0x0D,0x0A but fopen(file,"r") reads these 2 chars //as only 1 char, so ftell(f) returns a higher value than the required by fread() to the file to buf. #ifdef WIN32 FILE* f = fopen(file, "rb"); #else FILE* f = fopen(file, "r"); #endif char* buf; uint32 length; if (!f) { sLog.outError("Could not open %s.", file); return false; } // get the length of the file fseek(f, 0, SEEK_END); if (ftell(f) <= 0) return false; else length = ftell(f); buf = new char[length + 1]; fseek(f, 0, SEEK_SET); // read the file if (fread(buf, length, 1, f) != 1) { sLog.outError("Could not read %s.", file); // delete buf and close the file before returning delete[] buf; fclose(f); return false; } buf[length] = '\0'; std::string buffer = std::string(buf); delete[] buf; // close the file, it is no longer needed fclose(f); // let's parse it std::string line; std::string::size_type end; std::string::size_type offset; bool in_multiline_comment = false; bool in_multiline_quote = false; bool in_block = false; std::string current_setting = ""; std::string current_variable = ""; std::string current_block = ""; ConfigBlock current_block_map; ConfigSetting current_setting_struct; // oh god this is awful try { for (;;) { // grab a line end = buffer.find(EOL); if (end == std::string::npos) { if (buffer.size() == 0) break; line = buffer; buffer.clear(); goto parse; } line = buffer.substr(0, end); buffer.erase(0, end + EOL_SIZE); goto parse; parse: if (!line.size()) continue; // are we a comment? if (!in_multiline_comment && is_comment(line, &in_multiline_comment)) { // our line is a comment if (!in_multiline_comment) { // the entire line is a comment, skip it continue; } } // handle our cases if (in_multiline_comment) { // we need to find a "*/". offset = line.find("*/", 0); // skip this entire line, eh? if (offset == std::string::npos) continue; // remove up to the end of the comment block line.erase(0, offset + 2); in_multiline_comment = false; } if (in_block) { // handle settings across multiple lines if (in_multiline_quote) { // attempt to find the end of the quote block offset = line.find("\""); if (offset == std::string::npos) { // append the whole line to the quote current_setting += line; current_setting += "\n"; continue; } // only append part of the line to the setting current_setting.append(line.c_str(), offset + 1); line.erase(0, offset + 1); // append the setting to the config block if (current_block == "" || current_variable == "") { sLog.outError("Quote without variable."); return false; } // apply the setting apply_setting(current_setting, current_setting_struct); // the setting is done, append it to the current block current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif // no longer doing this setting, or in a quote current_setting = ""; current_variable = ""; in_multiline_quote = false; } // remove any leading spaces remove_spaces(line); if (!line.size()) continue; // our target is a *setting*. look for an '=' sign, this is our seperator offset = line.find("="); if (offset != std::string::npos) { ASSERT(current_variable == ""); current_variable = line.substr(0, offset); // remove any spaces from the end of the setting remove_all_spaces(current_variable); // remove the directive *and* the = from the line line.erase(0, offset + 1); } // look for the opening quote. this signifies the start of a setting offset = line.find("\""); if (offset != std::string::npos) { ASSERT(current_setting == ""); ASSERT(current_variable != ""); // try and find the ending quote end = line.find("\"", offset + 1); if (end != std::string::npos) { // the closing quote is on the same line, oh goody current_setting = line.substr(offset + 1, end - offset - 1); // erase up to the end line.erase(0, end + 1); // apply the setting apply_setting(current_setting, current_setting_struct); // the setting is done, append it to the current block current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif // no longer doing this setting, or in a quote current_setting = ""; current_variable = ""; in_multiline_quote = false; // attempt to grab more settings from the same line goto parse; } else { // the closing quote is not on the same line. means we'll try and find it on the next current_setting.append(line.c_str(), offset); // skip to the next line. (after setting our condition first, of course :P in_multiline_quote = true; continue; } } // are we at the end of the block yet? offset = line.find(">"); if (offset != std::string::npos) { line.erase(0, offset + 1); // freeeee! in_block = false; // assign this block to the main "big" map m_settings[ahash(current_block)] = current_block_map; // erase all data for this so it doesn't seep through current_block_map.clear(); current_setting = ""; current_variable = ""; current_block = ""; } } else { // we're not in a block. look for the start of one offset = line.find("<"); if (offset != std::string::npos) { in_block = true; // whee, a block! let's cut the string and re-parse line.erase(0, offset + 1); // find the name of the block first, though offset = line.find(" "); if (offset != std::string::npos) { current_block = line.substr(0, offset); line.erase(0, offset + 1); } else { sLog.outError("Block without name."); return false; } // skip back goto parse; } } } } catch (...) { sLog.outError("Exception in config parsing."); return false; } // handle any errors if (in_block) { sLog.outError("Unterminated block."); return false; } if (in_multiline_comment) { sLog.outError("Unterminated comment."); return false; } if (in_multiline_quote) { sLog.outError("Unterminated quote."); return false; } return true; } return false; } ConfigSetting* ConfigFile::GetSetting(const char* Block, const char* Setting) { uint32 block_hash = ahash(Block); uint32 setting_hash = ahash(Setting); // find it in the big map std::map<uint32, ConfigBlock>::iterator itr = m_settings.find(block_hash); if (itr != m_settings.end()) { ConfigBlock::iterator it2 = itr->second.find(setting_hash); if (it2 != itr->second.end()) return &(it2->second); return 0; } return 0; } bool ConfigFile::GetString(const char* block, const char* name, std::string* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsString; return true; } std::string ConfigFile::GetStringDefault(const char* block, const char* name, const char* def) { std::string ret; return GetString(block, name, &ret) ? ret : def; } bool ConfigFile::GetBool(const char* block, const char* name, bool* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsBool; return true; } bool ConfigFile::GetBoolDefault(const char* block, const char* name, const bool def /* = false */) { bool val; return GetBool(block, name, &val) ? val : def; } bool ConfigFile::GetInt(const char* block, const char* name, int* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsInt; return true; } bool ConfigFile::GetFloat(const char* block, const char* name, float* value) { ConfigSetting* Setting = GetSetting(block, name); if (Setting == 0) return false; *value = Setting->AsFloat; return true; } int ConfigFile::GetIntDefault(const char* block, const char* name, const int def) { int val; return GetInt(block, name, &val) ? val : def; } float ConfigFile::GetFloatDefault(const char* block, const char* name, const float def) { float val; return (GetFloat(block, name, &val) ? val : def); } int ConfigFile::GetIntVA(const char* block, int def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); int val; return GetInt(str, block, &val) ? val : def; } float ConfigFile::GetFloatVA(const char* block, float def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); float val; return GetFloat(str, block, &val) ? val : def; } std::string ConfigFile::GetStringVA(const char* block, const char* def, const char* name, ...) { va_list ap; va_start(ap, name); char str[150]; vsnprintf(str, 150, name, ap); va_end(ap); return GetStringDefault(str, block, def); } bool ConfigFile::GetString(const char* block, char* buffer, const char* name, const char* def, uint32 len) { std::string val = GetStringDefault(block, name, def); size_t blen = val.length(); if (blen > len) blen = len; memcpy(buffer, val.c_str(), blen); buffer[blen] = 0; return true; } <|endoftext|>
<commit_before>#include "json-to-value.hh" #include <cstring> namespace nix { static void skipWhitespace(const char * & s) { while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') s++; } static string parseJSONString(const char * & s) { string res; if (*s++ != '"') throw JSONParseError("expected JSON string"); while (*s != '"') { if (!*s) throw JSONParseError("got end-of-string in JSON string"); if (*s == '\\') { s++; if (*s == '"') res += '"'; else if (*s == '\\') res += '\\'; else if (*s == '/') res += '/'; else if (*s == '/') res += '/'; else if (*s == 'b') res += '\b'; else if (*s == 'f') res += '\f'; else if (*s == 'n') res += '\n'; else if (*s == 'r') res += '\r'; else if (*s == 't') res += '\t'; else if (*s == 'u') throw JSONParseError("\\u characters in JSON strings are currently not supported"); else throw JSONParseError("invalid escaped character in JSON string"); s++; } else res += *s++; } s++; return res; } static void parseJSON(EvalState & state, const char * & s, Value & v) { skipWhitespace(s); if (!*s) throw JSONParseError("expected JSON value"); if (*s == '[') { s++; ValueVector values; values.reserve(128); skipWhitespace(s); while (1) { if (values.empty() && *s == ']') break; Value * v2 = state.allocValue(); parseJSON(state, s, *v2); values.push_back(v2); skipWhitespace(s); if (*s == ']') break; if (*s != ',') throw JSONParseError("expected ',' or ']' after JSON array element"); s++; } s++; state.mkList(v, values.size()); for (size_t n = 0; n < values.size(); ++n) v.listElems()[n] = values[n]; } else if (*s == '{') { s++; ValueMap attrs; while (1) { skipWhitespace(s); if (attrs.empty() && *s == '}') break; string name = parseJSONString(s); skipWhitespace(s); if (*s != ':') throw JSONParseError("expected ':' in JSON object"); s++; Value * v2 = state.allocValue(); parseJSON(state, s, *v2); attrs[state.symbols.create(name)] = v2; skipWhitespace(s); if (*s == '}') break; if (*s != ',') throw JSONParseError("expected ',' or '}' after JSON member"); s++; } state.mkAttrs(v, attrs.size()); for (auto & i : attrs) v.attrs->push_back(Attr(i.first, i.second)); v.attrs->sort(); s++; } else if (*s == '"') { mkString(v, parseJSONString(s)); } else if (isdigit(*s) || *s == '-' || *s == '.' ) { // Buffer into a string first, then use built-in C++ conversions std::string tmp_number; ValueType number_type = tInt; while (isdigit(*s) || *s == '-' || *s == '.' || *s == 'e' || *s == 'E') { if (*s == '.' || *s == 'e' || *s == 'E') number_type = tFloat; tmp_number += *s++; } try { if (number_type == tFloat) mkFloat(v, stod(tmp_number)); else mkInt(v, stoi(tmp_number)); } catch (std::invalid_argument e) { throw JSONParseError("invalid JSON number"); } catch (std::out_of_range e) { throw JSONParseError("out-of-range JSON number"); } } else if (strncmp(s, "true", 4) == 0) { s += 4; mkBool(v, true); } else if (strncmp(s, "false", 5) == 0) { s += 5; mkBool(v, false); } else if (strncmp(s, "null", 4) == 0) { s += 4; mkNull(v); } else throw JSONParseError("unrecognised JSON value"); } void parseJSON(EvalState & state, const string & s_, Value & v) { const char * s = s_.c_str(); parseJSON(state, s, v); skipWhitespace(s); if (*s) throw JSONParseError(format("expected end-of-string while parsing JSON value: %1%") % s); } } <commit_msg>json-to-value: Use strtol instead of strtoi<commit_after>#include "json-to-value.hh" #include <cstring> namespace nix { static void skipWhitespace(const char * & s) { while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') s++; } static string parseJSONString(const char * & s) { string res; if (*s++ != '"') throw JSONParseError("expected JSON string"); while (*s != '"') { if (!*s) throw JSONParseError("got end-of-string in JSON string"); if (*s == '\\') { s++; if (*s == '"') res += '"'; else if (*s == '\\') res += '\\'; else if (*s == '/') res += '/'; else if (*s == '/') res += '/'; else if (*s == 'b') res += '\b'; else if (*s == 'f') res += '\f'; else if (*s == 'n') res += '\n'; else if (*s == 'r') res += '\r'; else if (*s == 't') res += '\t'; else if (*s == 'u') throw JSONParseError("\\u characters in JSON strings are currently not supported"); else throw JSONParseError("invalid escaped character in JSON string"); s++; } else res += *s++; } s++; return res; } static void parseJSON(EvalState & state, const char * & s, Value & v) { skipWhitespace(s); if (!*s) throw JSONParseError("expected JSON value"); if (*s == '[') { s++; ValueVector values; values.reserve(128); skipWhitespace(s); while (1) { if (values.empty() && *s == ']') break; Value * v2 = state.allocValue(); parseJSON(state, s, *v2); values.push_back(v2); skipWhitespace(s); if (*s == ']') break; if (*s != ',') throw JSONParseError("expected ',' or ']' after JSON array element"); s++; } s++; state.mkList(v, values.size()); for (size_t n = 0; n < values.size(); ++n) v.listElems()[n] = values[n]; } else if (*s == '{') { s++; ValueMap attrs; while (1) { skipWhitespace(s); if (attrs.empty() && *s == '}') break; string name = parseJSONString(s); skipWhitespace(s); if (*s != ':') throw JSONParseError("expected ':' in JSON object"); s++; Value * v2 = state.allocValue(); parseJSON(state, s, *v2); attrs[state.symbols.create(name)] = v2; skipWhitespace(s); if (*s == '}') break; if (*s != ',') throw JSONParseError("expected ',' or '}' after JSON member"); s++; } state.mkAttrs(v, attrs.size()); for (auto & i : attrs) v.attrs->push_back(Attr(i.first, i.second)); v.attrs->sort(); s++; } else if (*s == '"') { mkString(v, parseJSONString(s)); } else if (isdigit(*s) || *s == '-' || *s == '.' ) { // Buffer into a string first, then use built-in C++ conversions std::string tmp_number; ValueType number_type = tInt; while (isdigit(*s) || *s == '-' || *s == '.' || *s == 'e' || *s == 'E') { if (*s == '.' || *s == 'e' || *s == 'E') number_type = tFloat; tmp_number += *s++; } try { if (number_type == tFloat) mkFloat(v, stod(tmp_number)); else mkInt(v, stol(tmp_number)); } catch (std::invalid_argument e) { throw JSONParseError("invalid JSON number"); } catch (std::out_of_range e) { throw JSONParseError("out-of-range JSON number"); } } else if (strncmp(s, "true", 4) == 0) { s += 4; mkBool(v, true); } else if (strncmp(s, "false", 5) == 0) { s += 5; mkBool(v, false); } else if (strncmp(s, "null", 4) == 0) { s += 4; mkNull(v); } else throw JSONParseError("unrecognised JSON value"); } void parseJSON(EvalState & state, const string & s_, Value & v) { const char * s = s_.c_str(); parseJSON(state, s, v); skipWhitespace(s); if (*s) throw JSONParseError(format("expected end-of-string while parsing JSON value: %1%") % s); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "content/renderer/render_widget_fullscreen_pepper.h" #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "content/common/gpu/client/gpu_channel_host.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" #include "content/renderer/gpu/render_widget_compositor.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/public/platform/WebCanvas.h" #include "third_party/WebKit/public/platform/WebCursorInfo.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/WebKit/public/platform/WebLayer.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebWidget.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gl/gpu_preference.h" using blink::WebCanvas; using blink::WebCompositionUnderline; using blink::WebCursorInfo; using blink::WebGestureEvent; using blink::WebInputEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; using blink::WebPoint; using blink::WebRect; using blink::WebSize; using blink::WebString; using blink::WebTextDirection; using blink::WebTextInputType; using blink::WebVector; using blink::WebWidget; using blink::WGC3Dintptr; namespace content { namespace { class FullscreenMouseLockDispatcher : public MouseLockDispatcher { public: explicit FullscreenMouseLockDispatcher(RenderWidgetFullscreenPepper* widget); ~FullscreenMouseLockDispatcher() override; private: // MouseLockDispatcher implementation. void SendLockMouseRequest(bool unlocked_by_target) override; void SendUnlockMouseRequest() override; RenderWidgetFullscreenPepper* widget_; DISALLOW_COPY_AND_ASSIGN(FullscreenMouseLockDispatcher); }; WebMouseEvent WebMouseEventFromGestureEvent(const WebGestureEvent& gesture) { WebMouseEvent mouse; switch (gesture.type) { case WebInputEvent::GestureScrollBegin: mouse.type = WebInputEvent::MouseDown; break; case WebInputEvent::GestureScrollUpdate: mouse.type = WebInputEvent::MouseMove; break; case WebInputEvent::GestureFlingStart: if (gesture.sourceDevice == blink::WebGestureDeviceTouchscreen) { // A scroll gesture on the touchscreen may end with a GestureScrollEnd // when there is no velocity, or a GestureFlingStart when it has a // velocity. In both cases, it should end the drag that was initiated by // the GestureScrollBegin (and subsequent GestureScrollUpdate) events. mouse.type = WebInputEvent::MouseUp; break; } else { return mouse; } case WebInputEvent::GestureScrollEnd: mouse.type = WebInputEvent::MouseUp; break; default: break; } if (mouse.type == WebInputEvent::Undefined) return mouse; mouse.timeStampSeconds = gesture.timeStampSeconds; mouse.modifiers = gesture.modifiers | WebInputEvent::LeftButtonDown; mouse.button = WebMouseEvent::ButtonLeft; mouse.clickCount = (mouse.type == WebInputEvent::MouseDown || mouse.type == WebInputEvent::MouseUp); mouse.x = gesture.x; mouse.y = gesture.y; mouse.windowX = gesture.globalX; mouse.windowY = gesture.globalY; mouse.globalX = gesture.globalX; mouse.globalY = gesture.globalY; return mouse; } FullscreenMouseLockDispatcher::FullscreenMouseLockDispatcher( RenderWidgetFullscreenPepper* widget) : widget_(widget) { } FullscreenMouseLockDispatcher::~FullscreenMouseLockDispatcher() { } void FullscreenMouseLockDispatcher::SendLockMouseRequest( bool unlocked_by_target) { widget_->Send(new ViewHostMsg_LockMouse(widget_->routing_id(), false, unlocked_by_target, true)); } void FullscreenMouseLockDispatcher::SendUnlockMouseRequest() { widget_->Send(new ViewHostMsg_UnlockMouse(widget_->routing_id())); } // WebWidget that simply wraps the pepper plugin. // TODO(piman): figure out IME and implement setComposition and friends if // necessary. class PepperWidget : public WebWidget { public: explicit PepperWidget(RenderWidgetFullscreenPepper* widget) : widget_(widget) { } virtual ~PepperWidget() {} // WebWidget API virtual void close() { delete this; } virtual WebSize size() { return size_; } virtual void resize(const WebSize& size) { if (!widget_->plugin()) return; size_ = size; WebRect plugin_rect(0, 0, size_.width, size_.height); widget_->plugin()->ViewChanged(plugin_rect, plugin_rect, plugin_rect, std::vector<gfx::Rect>()); widget_->Invalidate(); } virtual void themeChanged() { NOTIMPLEMENTED(); } virtual bool handleInputEvent(const WebInputEvent& event) { if (!widget_->plugin()) return false; // This cursor info is ignored, we always set the cursor directly from // RenderWidgetFullscreenPepper::DidChangeCursor. WebCursorInfo cursor; // Pepper plugins do not accept gesture events. So do not send the gesture // events directly to the plugin. Instead, try to convert them to equivalent // mouse events, and then send to the plugin. if (WebInputEvent::isGestureEventType(event.type)) { bool result = false; const WebGestureEvent* gesture_event = static_cast<const WebGestureEvent*>(&event); switch (event.type) { case WebInputEvent::GestureTap: { WebMouseEvent mouse; mouse.timeStampSeconds = gesture_event->timeStampSeconds; mouse.type = WebInputEvent::MouseMove; mouse.modifiers = gesture_event->modifiers; mouse.x = gesture_event->x; mouse.y = gesture_event->y; mouse.windowX = gesture_event->globalX; mouse.windowY = gesture_event->globalY; mouse.globalX = gesture_event->globalX; mouse.globalY = gesture_event->globalY; mouse.movementX = 0; mouse.movementY = 0; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); mouse.type = WebInputEvent::MouseDown; mouse.button = WebMouseEvent::ButtonLeft; mouse.clickCount = gesture_event->data.tap.tapCount; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); mouse.type = WebInputEvent::MouseUp; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); break; } default: { WebMouseEvent mouse = WebMouseEventFromGestureEvent(*gesture_event); if (mouse.type != WebInputEvent::Undefined) result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); break; } } return result; } bool result = widget_->plugin()->HandleInputEvent(event, &cursor); // For normal web pages, WebViewImpl does input event translations and // generates context menu events. Since we don't have a WebView, we need to // do the necessary translation ourselves. if (WebInputEvent::isMouseEventType(event.type)) { const WebMouseEvent& mouse_event = reinterpret_cast<const WebMouseEvent&>(event); bool send_context_menu_event = false; // On Mac/Linux, we handle it on mouse down. // On Windows, we handle it on mouse up. #if defined(OS_WIN) send_context_menu_event = mouse_event.type == WebInputEvent::MouseUp && mouse_event.button == WebMouseEvent::ButtonRight; #elif defined(OS_MACOSX) send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && (mouse_event.button == WebMouseEvent::ButtonRight || (mouse_event.button == WebMouseEvent::ButtonLeft && mouse_event.modifiers & WebMouseEvent::ControlKey)); #else send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && mouse_event.button == WebMouseEvent::ButtonRight; #endif if (send_context_menu_event) { WebMouseEvent context_menu_event(mouse_event); context_menu_event.type = WebInputEvent::ContextMenu; widget_->plugin()->HandleInputEvent(context_menu_event, &cursor); } } return result; } private: RenderWidgetFullscreenPepper* widget_; WebSize size_; DISALLOW_COPY_AND_ASSIGN(PepperWidget); }; } // anonymous namespace // static RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create( int32 opener_id, CompositorDependencies* compositor_deps, PepperPluginInstanceImpl* plugin, const GURL& active_url, const blink::WebScreenInfo& screen_info) { DCHECK_NE(MSG_ROUTING_NONE, opener_id); scoped_refptr<RenderWidgetFullscreenPepper> widget( new RenderWidgetFullscreenPepper(plugin, active_url, screen_info)); widget->Init(opener_id, compositor_deps); widget->AddRef(); return widget.get(); } RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper( PepperPluginInstanceImpl* plugin, const GURL& active_url, const blink::WebScreenInfo& screen_info) : RenderWidgetFullscreen(screen_info), active_url_(active_url), plugin_(plugin), layer_(NULL), mouse_lock_dispatcher_(new FullscreenMouseLockDispatcher( this)) { } RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() { } void RenderWidgetFullscreenPepper::Invalidate() { InvalidateRect(gfx::Rect(size_.width(), size_.height())); } void RenderWidgetFullscreenPepper::InvalidateRect(const blink::WebRect& rect) { didInvalidateRect(rect); } void RenderWidgetFullscreenPepper::ScrollRect( int dx, int dy, const blink::WebRect& rect) { } void RenderWidgetFullscreenPepper::Destroy() { // This function is called by the plugin instance as it's going away, so reset // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close(). plugin_ = NULL; // After calling Destroy(), the plugin instance assumes that the layer is not // used by us anymore, so it may destroy the layer before this object goes // away. SetLayer(NULL); Send(new ViewHostMsg_Close(routing_id_)); Release(); } void RenderWidgetFullscreenPepper::DidChangeCursor( const blink::WebCursorInfo& cursor) { didChangeCursor(cursor); } void RenderWidgetFullscreenPepper::SetLayer(blink::WebLayer* layer) { layer_ = layer; if (!layer_) { if (compositor_) compositor_->clearRootLayer(); return; } if (!layerTreeView()) initializeLayerTreeView(); layer_->setBounds(blink::WebSize(size())); layer_->setDrawsContent(true); compositor_->setDeviceScaleFactor(device_scale_factor_); compositor_->setRootLayer(*layer_); } bool RenderWidgetFullscreenPepper::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderWidgetFullscreenPepper, msg) IPC_MESSAGE_FORWARD(ViewMsg_LockMouse_ACK, mouse_lock_dispatcher_.get(), MouseLockDispatcher::OnLockMouseACK) IPC_MESSAGE_FORWARD(ViewMsg_MouseLockLost, mouse_lock_dispatcher_.get(), MouseLockDispatcher::OnMouseLockLost) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; return RenderWidgetFullscreen::OnMessageReceived(msg); } void RenderWidgetFullscreenPepper::DidInitiatePaint() { if (plugin_) plugin_->ViewInitiatedPaint(); } void RenderWidgetFullscreenPepper::DidFlushPaint() { } void RenderWidgetFullscreenPepper::Close() { // If the fullscreen window is closed (e.g. user pressed escape), reset to // normal mode. if (plugin_) plugin_->FlashSetFullscreen(false, false); // Call Close on the base class to destroy the WebWidget instance. RenderWidget::Close(); } void RenderWidgetFullscreenPepper::OnResize( const ViewMsg_Resize_Params& params) { if (layer_) layer_->setBounds(blink::WebSize(params.new_size)); RenderWidget::OnResize(params); } WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() { return new PepperWidget(this); } GURL RenderWidgetFullscreenPepper::GetURLForGraphicsContext3D() { return active_url_; } void RenderWidgetFullscreenPepper::SetDeviceScaleFactor( float device_scale_factor) { RenderWidget::SetDeviceScaleFactor(device_scale_factor); if (compositor_) compositor_->setDeviceScaleFactor(device_scale_factor); } } // namespace content <commit_msg>Make WebMouseEvent.windowX equal to WebMouseEvent.x. Same for y.<commit_after>// Copyright (c) 2012 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 "content/renderer/render_widget_fullscreen_pepper.h" #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "content/common/gpu/client/gpu_channel_host.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" #include "content/renderer/gpu/render_widget_compositor.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/public/platform/WebCanvas.h" #include "third_party/WebKit/public/platform/WebCursorInfo.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/WebKit/public/platform/WebLayer.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebWidget.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gl/gpu_preference.h" using blink::WebCanvas; using blink::WebCompositionUnderline; using blink::WebCursorInfo; using blink::WebGestureEvent; using blink::WebInputEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; using blink::WebPoint; using blink::WebRect; using blink::WebSize; using blink::WebString; using blink::WebTextDirection; using blink::WebTextInputType; using blink::WebVector; using blink::WebWidget; using blink::WGC3Dintptr; namespace content { namespace { class FullscreenMouseLockDispatcher : public MouseLockDispatcher { public: explicit FullscreenMouseLockDispatcher(RenderWidgetFullscreenPepper* widget); ~FullscreenMouseLockDispatcher() override; private: // MouseLockDispatcher implementation. void SendLockMouseRequest(bool unlocked_by_target) override; void SendUnlockMouseRequest() override; RenderWidgetFullscreenPepper* widget_; DISALLOW_COPY_AND_ASSIGN(FullscreenMouseLockDispatcher); }; WebMouseEvent WebMouseEventFromGestureEvent(const WebGestureEvent& gesture) { WebMouseEvent mouse; switch (gesture.type) { case WebInputEvent::GestureScrollBegin: mouse.type = WebInputEvent::MouseDown; break; case WebInputEvent::GestureScrollUpdate: mouse.type = WebInputEvent::MouseMove; break; case WebInputEvent::GestureFlingStart: if (gesture.sourceDevice == blink::WebGestureDeviceTouchscreen) { // A scroll gesture on the touchscreen may end with a GestureScrollEnd // when there is no velocity, or a GestureFlingStart when it has a // velocity. In both cases, it should end the drag that was initiated by // the GestureScrollBegin (and subsequent GestureScrollUpdate) events. mouse.type = WebInputEvent::MouseUp; break; } else { return mouse; } case WebInputEvent::GestureScrollEnd: mouse.type = WebInputEvent::MouseUp; break; default: break; } if (mouse.type == WebInputEvent::Undefined) return mouse; mouse.timeStampSeconds = gesture.timeStampSeconds; mouse.modifiers = gesture.modifiers | WebInputEvent::LeftButtonDown; mouse.button = WebMouseEvent::ButtonLeft; mouse.clickCount = (mouse.type == WebInputEvent::MouseDown || mouse.type == WebInputEvent::MouseUp); mouse.x = gesture.x; mouse.y = gesture.y; mouse.windowX = gesture.x; mouse.windowY = gesture.y; mouse.globalX = gesture.globalX; mouse.globalY = gesture.globalY; return mouse; } FullscreenMouseLockDispatcher::FullscreenMouseLockDispatcher( RenderWidgetFullscreenPepper* widget) : widget_(widget) { } FullscreenMouseLockDispatcher::~FullscreenMouseLockDispatcher() { } void FullscreenMouseLockDispatcher::SendLockMouseRequest( bool unlocked_by_target) { widget_->Send(new ViewHostMsg_LockMouse(widget_->routing_id(), false, unlocked_by_target, true)); } void FullscreenMouseLockDispatcher::SendUnlockMouseRequest() { widget_->Send(new ViewHostMsg_UnlockMouse(widget_->routing_id())); } // WebWidget that simply wraps the pepper plugin. // TODO(piman): figure out IME and implement setComposition and friends if // necessary. class PepperWidget : public WebWidget { public: explicit PepperWidget(RenderWidgetFullscreenPepper* widget) : widget_(widget) { } virtual ~PepperWidget() {} // WebWidget API virtual void close() { delete this; } virtual WebSize size() { return size_; } virtual void resize(const WebSize& size) { if (!widget_->plugin()) return; size_ = size; WebRect plugin_rect(0, 0, size_.width, size_.height); widget_->plugin()->ViewChanged(plugin_rect, plugin_rect, plugin_rect, std::vector<gfx::Rect>()); widget_->Invalidate(); } virtual void themeChanged() { NOTIMPLEMENTED(); } virtual bool handleInputEvent(const WebInputEvent& event) { if (!widget_->plugin()) return false; // This cursor info is ignored, we always set the cursor directly from // RenderWidgetFullscreenPepper::DidChangeCursor. WebCursorInfo cursor; // Pepper plugins do not accept gesture events. So do not send the gesture // events directly to the plugin. Instead, try to convert them to equivalent // mouse events, and then send to the plugin. if (WebInputEvent::isGestureEventType(event.type)) { bool result = false; const WebGestureEvent* gesture_event = static_cast<const WebGestureEvent*>(&event); switch (event.type) { case WebInputEvent::GestureTap: { WebMouseEvent mouse; mouse.timeStampSeconds = gesture_event->timeStampSeconds; mouse.type = WebInputEvent::MouseMove; mouse.modifiers = gesture_event->modifiers; mouse.x = gesture_event->x; mouse.y = gesture_event->y; mouse.windowX = gesture_event->x; mouse.windowY = gesture_event->y; mouse.globalX = gesture_event->globalX; mouse.globalY = gesture_event->globalY; mouse.movementX = 0; mouse.movementY = 0; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); mouse.type = WebInputEvent::MouseDown; mouse.button = WebMouseEvent::ButtonLeft; mouse.clickCount = gesture_event->data.tap.tapCount; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); mouse.type = WebInputEvent::MouseUp; result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); break; } default: { WebMouseEvent mouse = WebMouseEventFromGestureEvent(*gesture_event); if (mouse.type != WebInputEvent::Undefined) result |= widget_->plugin()->HandleInputEvent(mouse, &cursor); break; } } return result; } bool result = widget_->plugin()->HandleInputEvent(event, &cursor); // For normal web pages, WebViewImpl does input event translations and // generates context menu events. Since we don't have a WebView, we need to // do the necessary translation ourselves. if (WebInputEvent::isMouseEventType(event.type)) { const WebMouseEvent& mouse_event = reinterpret_cast<const WebMouseEvent&>(event); bool send_context_menu_event = false; // On Mac/Linux, we handle it on mouse down. // On Windows, we handle it on mouse up. #if defined(OS_WIN) send_context_menu_event = mouse_event.type == WebInputEvent::MouseUp && mouse_event.button == WebMouseEvent::ButtonRight; #elif defined(OS_MACOSX) send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && (mouse_event.button == WebMouseEvent::ButtonRight || (mouse_event.button == WebMouseEvent::ButtonLeft && mouse_event.modifiers & WebMouseEvent::ControlKey)); #else send_context_menu_event = mouse_event.type == WebInputEvent::MouseDown && mouse_event.button == WebMouseEvent::ButtonRight; #endif if (send_context_menu_event) { WebMouseEvent context_menu_event(mouse_event); context_menu_event.type = WebInputEvent::ContextMenu; widget_->plugin()->HandleInputEvent(context_menu_event, &cursor); } } return result; } private: RenderWidgetFullscreenPepper* widget_; WebSize size_; DISALLOW_COPY_AND_ASSIGN(PepperWidget); }; } // anonymous namespace // static RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create( int32 opener_id, CompositorDependencies* compositor_deps, PepperPluginInstanceImpl* plugin, const GURL& active_url, const blink::WebScreenInfo& screen_info) { DCHECK_NE(MSG_ROUTING_NONE, opener_id); scoped_refptr<RenderWidgetFullscreenPepper> widget( new RenderWidgetFullscreenPepper(plugin, active_url, screen_info)); widget->Init(opener_id, compositor_deps); widget->AddRef(); return widget.get(); } RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper( PepperPluginInstanceImpl* plugin, const GURL& active_url, const blink::WebScreenInfo& screen_info) : RenderWidgetFullscreen(screen_info), active_url_(active_url), plugin_(plugin), layer_(NULL), mouse_lock_dispatcher_(new FullscreenMouseLockDispatcher( this)) { } RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() { } void RenderWidgetFullscreenPepper::Invalidate() { InvalidateRect(gfx::Rect(size_.width(), size_.height())); } void RenderWidgetFullscreenPepper::InvalidateRect(const blink::WebRect& rect) { didInvalidateRect(rect); } void RenderWidgetFullscreenPepper::ScrollRect( int dx, int dy, const blink::WebRect& rect) { } void RenderWidgetFullscreenPepper::Destroy() { // This function is called by the plugin instance as it's going away, so reset // plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close(). plugin_ = NULL; // After calling Destroy(), the plugin instance assumes that the layer is not // used by us anymore, so it may destroy the layer before this object goes // away. SetLayer(NULL); Send(new ViewHostMsg_Close(routing_id_)); Release(); } void RenderWidgetFullscreenPepper::DidChangeCursor( const blink::WebCursorInfo& cursor) { didChangeCursor(cursor); } void RenderWidgetFullscreenPepper::SetLayer(blink::WebLayer* layer) { layer_ = layer; if (!layer_) { if (compositor_) compositor_->clearRootLayer(); return; } if (!layerTreeView()) initializeLayerTreeView(); layer_->setBounds(blink::WebSize(size())); layer_->setDrawsContent(true); compositor_->setDeviceScaleFactor(device_scale_factor_); compositor_->setRootLayer(*layer_); } bool RenderWidgetFullscreenPepper::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderWidgetFullscreenPepper, msg) IPC_MESSAGE_FORWARD(ViewMsg_LockMouse_ACK, mouse_lock_dispatcher_.get(), MouseLockDispatcher::OnLockMouseACK) IPC_MESSAGE_FORWARD(ViewMsg_MouseLockLost, mouse_lock_dispatcher_.get(), MouseLockDispatcher::OnMouseLockLost) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; return RenderWidgetFullscreen::OnMessageReceived(msg); } void RenderWidgetFullscreenPepper::DidInitiatePaint() { if (plugin_) plugin_->ViewInitiatedPaint(); } void RenderWidgetFullscreenPepper::DidFlushPaint() { } void RenderWidgetFullscreenPepper::Close() { // If the fullscreen window is closed (e.g. user pressed escape), reset to // normal mode. if (plugin_) plugin_->FlashSetFullscreen(false, false); // Call Close on the base class to destroy the WebWidget instance. RenderWidget::Close(); } void RenderWidgetFullscreenPepper::OnResize( const ViewMsg_Resize_Params& params) { if (layer_) layer_->setBounds(blink::WebSize(params.new_size)); RenderWidget::OnResize(params); } WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() { return new PepperWidget(this); } GURL RenderWidgetFullscreenPepper::GetURLForGraphicsContext3D() { return active_url_; } void RenderWidgetFullscreenPepper::SetDeviceScaleFactor( float device_scale_factor) { RenderWidget::SetDeviceScaleFactor(device_scale_factor); if (compositor_) compositor_->setDeviceScaleFactor(device_scale_factor); } } // namespace content <|endoftext|>
<commit_before>#include <iodata/validator> #include <iodata/storage> #include <string> #include <sstream> #include <set> #include <map> using namespace std ; #include "olson.h" #include "misc.h" #include "tzdata.h" #if DEADCODE struct tz_single_t ; struct tz_distinct_t ; struct tz_distinct_t { olson * guess_timezone(int mcc, tz_suggestions_t &list) ; tz_distinct_t(const iodata::record *) ; map<int, vector<olson*> > mcc_to_tzlist ; } ; struct tz_single_t { olson * guess_timezone(int mcc) ; tz_single_t(const iodata::record *) ; map<int, string> mcc_to_tz ; } ; string mcc_to_xy(int mcc) ; // maps mcc to country code (2 chars) map<string, vector<string> > xy_to_tz ; // time zones by country code iodata::validator *validator() ; iodata::record *open_database(const char *path, const char *type) ; void read_timezones_by_country() ; #endif // we need some some data structures... // 1. Mapping mcc to alpha-2 code: 310=>US map<string,string> mcc_to_xy ; // 2. Mapping alpha-2 to zone to importance (0,1,2,3): US=>(New_York=>0, Chicago=>1, Phoenix=>2, Zaporozhye=>3) map<string,map<string,int> > xy_to_zone_to_level ; // 3. Mapping alpha-2 to main zone: US=>New_York map<string,string> xy_to_zone0 ; // 4. Default country (alpha-2) and zone based on default time zome customization string home_country ; olson *home_zone=NULL ; // 5. Set of alpha-2 of single zone counties (only 0,1,2 count; 3 doesn't) set<string> small_countries ; string tzdata::iso_3166_1_alpha2_by_mcc(const string &mcc) { map<string,string>::const_iterator it = mcc_to_xy.find(mcc) ; return it==mcc_to_xy.end() ? "" : it->second ; } int tzdata::by_country(const string &alpha2, enum tzdata::zone_type type, set<olson*> &out) { map<string,map<string,int> >::const_iterator it = xy_to_zone_to_level.find(alpha2) ; if (it==xy_to_zone_to_level.end()) return 0 ; int counter = 0 ; int threshold = type==tzdata::Main_Zones ? 1 : type==tzdata::Real_Zones ? 2 : 3 ; // all by default const map<string,int> &zone_to_level = it->second ; for (map<string,int>::const_iterator jt=zone_to_level.begin(); jt!=zone_to_level.end(); ++jt) if (jt->second <= threshold) out.insert(olson::by_name(jt->first)), ++counter ; return counter ; } olson *tzdata::country_default(const string &alpha2) { map<string,string>::const_iterator it = xy_to_zone0.find(alpha2) ; return it==xy_to_zone0.end() ? NULL : olson::by_name(it->second) ; } olson *tzdata::device_default() { return home_zone ; } int tzdata::filter(const set<olson*> &in, time_t moment, int offset, int dst, set<olson*> &out) { int counter = 0 ; for (set<olson*>::const_iterator it=in.begin(); it!=in.end(); ++it) if ((*it)->match(moment, offset, dst)) ++counter, out.insert(*it) ; return counter ; } bool tzdata::is_single_zone_country(const string &alpha2) { return small_countries.find(alpha2) != small_countries.end() ; } string tzdata::set_str(const set<olson*> &x) { ostringstream os ; bool first ; for (set<olson*>::const_iterator it=x.begin(); it!=x.end(); ++it) os << (first ? first=false, "{" : ", " ) << (*it)->name() ; os << (first ? " }" : "}") ; return os.str() ; } // --- initialization --- static iodata::validator *tzdata_validator = iodata::validator::from_file("/usr/share/timed/typeinfo/tzdata.type") ; #if 0 static struct tz_distinct_t { // olson * guess_timezone(int mcc, tz_suggestions_t &list) ; tz_distinct_t(const iodata::record *) ; map<int, vector<olson*> > mcc_to_tzlist ; } *tz_distinct=NULL ; static struct tz_single_t { // olson * guess_timezone(int mcc) ; tz_single_t(const iodata::record *) ; map<int, string> mcc_to_tz ; } tz_single_t *tz_single=NULL ; #endif static iodata::record *open_database(const char *path, const char *type) { log_notice("opening file '%s', reading record of type '%s'", path, type) ; iodata::storage file ; file.set_validator(tzdata_validator, type) ; file.set_primary_path(path) ; if (iodata::record *res = file.load()) return res ; log_abort("file '%s' corrupted or not present", path) ; // return NULL ; TODO: just print an error in init() and continue } static void process_zone(const string &xy, const string &tz, int i_value) { if (i_value==0) xy_to_zone0[xy] = tz ; // capital if (tz==home_zone->name()) home_country = xy ; xy_to_zone_to_level[xy][tz] = i_value ; } void tzdata::init(const string &default_tz) { home_zone = olson::by_name(default_tz) ; iodata::record *A = open_database("/usr/share/tzdata-timed/country-by-mcc.data", "mcc_to_xy_t") ; iodata::record *B = open_database("/usr/share/tzdata-timed/single.data", "tz_single_t") ; iodata::record *C = open_database("/usr/share/tzdata-timed/zones-by-country.data", "zones_by_country_t") ; const iodata::array *a = A->get("mcc_to_xy")->arr() ; for(unsigned i=0; i<a->size(); ++i) { int mcc_d = a->get(i)->get("mcc")->value() ; string mcc = str_printf("%d", mcc_d) ; string xy = a->get(i)->get("country")->str() ; mcc_to_xy[mcc] = xy ; } const iodata::array *b = B->get("list")->arr() ; // TODO: rename list->tz_single (here and in tzdata script) for(unsigned i=0; i<b->size(); ++i) { int mcc_d = b->get(i)->get("mcc")->value() ; string mcc = str_printf("%d", mcc_d) ; string xy = tzdata::iso_3166_1_alpha2_by_mcc(mcc) ; if (xy.empty()) { log_critical("Iso-3166 alpha-2 ID not found for MCC=%d", mcc_d) ; continue ; } small_countries.insert(xy) ; string tz = b->get(i)->get("tz")->str() ; process_zone(xy, tz, 0) ; // 0 is 'capital' } const iodata::array *c = C->get("xy_to_tz")->arr() ; for(unsigned i=0; i<c->size(); ++i) { // log_debug("i=%d", i) ; string xy = c->get(i)->get("xy")->str() ; for (int important=1; important<=2; ++important) { // log_debug("i=%d important=%d", i, important) ; const char *key = important==1 ? "major" : "minor" ; const iodata::array *list = c->get(i)->get(key)->arr() ; for (unsigned j=0; j<list->size(); ++j) { // log_debug("i=%d important=%d j=%d", i, important, j) ; int i_value = (important==1 and j==0) ? 0 : important ; // the very first is the capital process_zone(xy, list->get(j)->str(), i_value) ; } } } delete A ; delete B ; delete C ; } <commit_msg>a header<commit_after>#include <iodata/validator> #include <iodata/storage> #include <string> #include <sstream> #include <set> #include <map> using namespace std ; #include <qmlog> #include "olson.h" #include "misc.h" #include "tzdata.h" #if DEADCODE struct tz_single_t ; struct tz_distinct_t ; struct tz_distinct_t { olson * guess_timezone(int mcc, tz_suggestions_t &list) ; tz_distinct_t(const iodata::record *) ; map<int, vector<olson*> > mcc_to_tzlist ; } ; struct tz_single_t { olson * guess_timezone(int mcc) ; tz_single_t(const iodata::record *) ; map<int, string> mcc_to_tz ; } ; string mcc_to_xy(int mcc) ; // maps mcc to country code (2 chars) map<string, vector<string> > xy_to_tz ; // time zones by country code iodata::validator *validator() ; iodata::record *open_database(const char *path, const char *type) ; void read_timezones_by_country() ; #endif // we need some some data structures... // 1. Mapping mcc to alpha-2 code: 310=>US map<string,string> mcc_to_xy ; // 2. Mapping alpha-2 to zone to importance (0,1,2,3): US=>(New_York=>0, Chicago=>1, Phoenix=>2, Zaporozhye=>3) map<string,map<string,int> > xy_to_zone_to_level ; // 3. Mapping alpha-2 to main zone: US=>New_York map<string,string> xy_to_zone0 ; // 4. Default country (alpha-2) and zone based on default time zome customization string home_country ; olson *home_zone=NULL ; // 5. Set of alpha-2 of single zone counties (only 0,1,2 count; 3 doesn't) set<string> small_countries ; string tzdata::iso_3166_1_alpha2_by_mcc(const string &mcc) { map<string,string>::const_iterator it = mcc_to_xy.find(mcc) ; return it==mcc_to_xy.end() ? "" : it->second ; } int tzdata::by_country(const string &alpha2, enum tzdata::zone_type type, set<olson*> &out) { map<string,map<string,int> >::const_iterator it = xy_to_zone_to_level.find(alpha2) ; if (it==xy_to_zone_to_level.end()) return 0 ; int counter = 0 ; int threshold = type==tzdata::Main_Zones ? 1 : type==tzdata::Real_Zones ? 2 : 3 ; // all by default const map<string,int> &zone_to_level = it->second ; for (map<string,int>::const_iterator jt=zone_to_level.begin(); jt!=zone_to_level.end(); ++jt) if (jt->second <= threshold) out.insert(olson::by_name(jt->first)), ++counter ; return counter ; } olson *tzdata::country_default(const string &alpha2) { map<string,string>::const_iterator it = xy_to_zone0.find(alpha2) ; return it==xy_to_zone0.end() ? NULL : olson::by_name(it->second) ; } olson *tzdata::device_default() { return home_zone ; } int tzdata::filter(const set<olson*> &in, time_t moment, int offset, int dst, set<olson*> &out) { int counter = 0 ; for (set<olson*>::const_iterator it=in.begin(); it!=in.end(); ++it) if ((*it)->match(moment, offset, dst)) ++counter, out.insert(*it) ; return counter ; } bool tzdata::is_single_zone_country(const string &alpha2) { return small_countries.find(alpha2) != small_countries.end() ; } string tzdata::set_str(const set<olson*> &x) { ostringstream os ; bool first ; for (set<olson*>::const_iterator it=x.begin(); it!=x.end(); ++it) os << (first ? first=false, "{" : ", " ) << (*it)->name() ; os << (first ? " }" : "}") ; return os.str() ; } // --- initialization --- static iodata::validator *tzdata_validator = iodata::validator::from_file("/usr/share/timed/typeinfo/tzdata.type") ; #if 0 static struct tz_distinct_t { // olson * guess_timezone(int mcc, tz_suggestions_t &list) ; tz_distinct_t(const iodata::record *) ; map<int, vector<olson*> > mcc_to_tzlist ; } *tz_distinct=NULL ; static struct tz_single_t { // olson * guess_timezone(int mcc) ; tz_single_t(const iodata::record *) ; map<int, string> mcc_to_tz ; } tz_single_t *tz_single=NULL ; #endif static iodata::record *open_database(const char *path, const char *type) { log_notice("opening file '%s', reading record of type '%s'", path, type) ; iodata::storage file ; file.set_validator(tzdata_validator, type) ; file.set_primary_path(path) ; if (iodata::record *res = file.load()) return res ; log_abort("file '%s' corrupted or not present", path) ; // return NULL ; TODO: just print an error in init() and continue } static void process_zone(const string &xy, const string &tz, int i_value) { if (i_value==0) xy_to_zone0[xy] = tz ; // capital if (tz==home_zone->name()) home_country = xy ; xy_to_zone_to_level[xy][tz] = i_value ; } void tzdata::init(const string &default_tz) { home_zone = olson::by_name(default_tz) ; iodata::record *A = open_database("/usr/share/tzdata-timed/country-by-mcc.data", "mcc_to_xy_t") ; iodata::record *B = open_database("/usr/share/tzdata-timed/single.data", "tz_single_t") ; iodata::record *C = open_database("/usr/share/tzdata-timed/zones-by-country.data", "zones_by_country_t") ; const iodata::array *a = A->get("mcc_to_xy")->arr() ; for(unsigned i=0; i<a->size(); ++i) { int mcc_d = a->get(i)->get("mcc")->value() ; string mcc = str_printf("%d", mcc_d) ; string xy = a->get(i)->get("country")->str() ; mcc_to_xy[mcc] = xy ; } const iodata::array *b = B->get("list")->arr() ; // TODO: rename list->tz_single (here and in tzdata script) for(unsigned i=0; i<b->size(); ++i) { int mcc_d = b->get(i)->get("mcc")->value() ; string mcc = str_printf("%d", mcc_d) ; string xy = tzdata::iso_3166_1_alpha2_by_mcc(mcc) ; if (xy.empty()) { log_critical("Iso-3166 alpha-2 ID not found for MCC=%d", mcc_d) ; continue ; } small_countries.insert(xy) ; string tz = b->get(i)->get("tz")->str() ; process_zone(xy, tz, 0) ; // 0 is 'capital' } const iodata::array *c = C->get("xy_to_tz")->arr() ; for(unsigned i=0; i<c->size(); ++i) { // log_debug("i=%d", i) ; string xy = c->get(i)->get("xy")->str() ; for (int important=1; important<=2; ++important) { // log_debug("i=%d important=%d", i, important) ; const char *key = important==1 ? "major" : "minor" ; const iodata::array *list = c->get(i)->get(key)->arr() ; for (unsigned j=0; j<list->size(); ++j) { // log_debug("i=%d important=%d j=%d", i, important, j) ; int i_value = (important==1 and j==0) ? 0 : important ; // the very first is the capital process_zone(xy, list->get(j)->str(), i_value) ; } } } delete A ; delete B ; delete C ; } <|endoftext|>
<commit_before>#include <iostream> #include <string> void run_part_one() { } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day21 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } <commit_msg>added runtime code for day 21 part one<commit_after>#include <iostream> #include <string> #include "BossFight.hpp" void run_part_one() { std::cout << find_lowest_gold_to_win(100,8,2) << std::endl; } void run_part_two() { } int main(int argc, char* argv[]) { if (argc > 1) { if (std::string(argv[1]) == "--part_two") { run_part_two(); } else { std::cout << "Usage: day21 [--part_two]" << std::endl; return -1; } } else { run_part_one(); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; m_MetaProcessor->increaseRedirectionRAIILevel(); if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() { pop(); m_MetaProcessor->decreaseRedirectionRAIILevel(); } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { //If we have only one redirection RAII //only then do the unredirection. if (m_MetaProcessor->getRedirectionRAIILevel() != 1) return; if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() { close(m_backupFDStdout); close(m_backupFDStderr); } int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (!m_InputValidator->inBlockComment() && m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input; m_InputValidator->reset(&input); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, size_t posOpenCurly) { { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); // Binary files < 300 bytes are rare, and below newlines etc make the // heuristic unreliable. if (readMagic >= 300) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a binary file!\n"; return Interpreter::kFailure; } unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. llvm::errs() << "Error in cling::MetaProcessor: " "cannot read input from a (likely) binary file!\n" << printable; return Interpreter::kFailure; } } } std::ifstream in(filename.str().c_str()); in.seekg(0, std::ios::end); size_t size = in.tellg(); std::string content(size, ' '); in.seekg(0); in.read(&content[0], size); if (posOpenCurly != (size_t)-1 && !content.empty()) { assert(content[posOpenCurly] == '{' && "No curly at claimed position of opening curly!"); // hide the curly brace: content[posOpenCurly] = ' '; // and the matching closing '}' static const char whitespace[] = " \t\r\n"; size_t posCloseCurly = content.find_last_not_of(whitespace); if (posCloseCurly != std::string::npos) { if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') { content[posCloseCurly--] = ' '; // replace ';' and enter next if } if (content[posCloseCurly] == '}') { content[posCloseCurly] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posBlockClose); if (posComment != std::string::npos && content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posCloseCurly) { content[posComment++] = ' '; // replace '}' and comment } } else { content[posCloseCurly] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find "//" } // remove comments after the trailing '}' } // find '}' } // ignore outermost block std::string strFilename(filename.str()); m_CurrentlyExecutingFile = strFilename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << " is not valid.\n"; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << " resulted in an error." " Will not be able to unredirect.\n"; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <commit_msg>Add error handling to MetaProcessor::readInputFromFile.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/MetaProcessor/MetaProcessor.h" #include "Display.h" #include "InputValidator.h" #include "MetaParser.h" #include "MetaSema.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/Path.h" #include <fstream> #include <cstdlib> #include <cctype> #include <stdio.h> #ifndef WIN32 #include <unistd.h> #else #include <io.h> #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif using namespace clang; namespace cling { MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII( MetaProcessor* p) :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) { StringRef redirectionFile; m_MetaProcessor->increaseRedirectionRAIILevel(); if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); redirect(stdout, redirectionFile.str(), kSTDOUT); } if (!m_MetaProcessor->m_PrevStderrFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back(); // Deal with the case 2>&1 and 2&>1 if (strcmp(redirectionFile.data(), "_IO_2_1_stdout_") == 0) { // If out is redirected to a file. if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) { redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back(); } else { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } redirect(stderr, redirectionFile.str(), kSTDERR); } } MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() { pop(); m_MetaProcessor->decreaseRedirectionRAIILevel(); } void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file, const std::string& fileName, MetaProcessor::RedirectionScope scope) { if (!fileName.empty()) { FILE* redirectionFile = freopen(fileName.c_str(), "a", file); if (!redirectionFile) { llvm::errs()<<"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:" " Not succefully reopened the redirection file " << fileName.c_str() << "\n."; } else { m_isCurrentlyRedirecting |= scope; } } } void MetaProcessor::MaybeRedirectOutputRAII::pop() { //If we have only one redirection RAII //only then do the unredirection. if (m_MetaProcessor->getRedirectionRAIILevel() != 1) return; if (m_isCurrentlyRedirecting & kSTDOUT) { unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout); } if (m_isCurrentlyRedirecting & kSTDERR) { unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr); } } void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD, int expectedFD, FILE* file) { // Switch back to previous file after line is processed. // Flush the current content if there is any. if (!feof(file)) { fflush(file); } // Copy the original fd for the std. if (dup2(backupFD, expectedFD) != expectedFD) { llvm::errs() << "cling::MetaProcessor::unredirect " << "The unredirection file descriptor not valid " << backupFD << ".\n"; } } MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs) : m_Interp(interp), m_Outs(&outs) { m_InputValidator.reset(new InputValidator()); m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this))); m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO); m_backupFDStderr = copyFileDescriptor(STDERR_FILENO); } MetaProcessor::~MetaProcessor() { close(m_backupFDStdout); close(m_backupFDStderr); } int MetaProcessor::process(const char* input_text, Interpreter::CompilationResult& compRes, Value* result) { if (result) *result = Value(); compRes = Interpreter::kSuccess; int expectedIndent = m_InputValidator->getExpectedIndent(); if (expectedIndent) compRes = Interpreter::kMoreInputExpected; if (!input_text || !input_text[0]) { // nullptr / empty string, nothing to do. return expectedIndent; } std::string input_line(input_text); if (input_line == "\n") { // just a blank line, nothing to do. return expectedIndent; } // Check for and handle meta commands. m_MetaParser->enterNewInputLine(input_line); MetaSema::ActionResult actionResult = MetaSema::AR_Success; if (!m_InputValidator->inBlockComment() && m_MetaParser->isMetaCommand(actionResult, result)) { if (m_MetaParser->isQuitRequested()) return -1; if (actionResult != MetaSema::AR_Success) compRes = Interpreter::kFailure; // ExpectedIndent might have changed after meta command. return m_InputValidator->getExpectedIndent(); } // Check if the current statement is now complete. If not, return to // prompt for more. if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) { compRes = Interpreter::kMoreInputExpected; return m_InputValidator->getExpectedIndent(); } // We have a complete statement, compile and execute it. std::string input; m_InputValidator->reset(&input); // if (m_Options.RawInput) // compResLocal = m_Interp.declare(input); // else compRes = m_Interp.process(input, result); return 0; } void MetaProcessor::cancelContinuation() const { m_InputValidator->reset(); } int MetaProcessor::getExpectedIndent() const { return m_InputValidator->getExpectedIndent(); } static Interpreter::CompilationResult reportIOErr(llvm::StringRef File, const char* What) { llvm::errs() << "Error in cling::MetaProcessor: " "cannot " << What << " input: '" << File << "'\n"; return Interpreter::kFailure; } Interpreter::CompilationResult MetaProcessor::readInputFromFile(llvm::StringRef filename, Value* result, size_t posOpenCurly) { // FIXME: This will fail for Unicode BOMs (and seems really weird) { // check that it's not binary: std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary); if (in.fail()) return reportIOErr(filename, "open"); char magic[1024] = {0}; in.read(magic, sizeof(magic)); size_t readMagic = in.gcount(); // Binary files < 300 bytes are rare, and below newlines etc make the // heuristic unreliable. if (!in.fail() && readMagic >= 300) { llvm::StringRef magicStr(magic,in.gcount()); llvm::sys::fs::file_magic fileType = llvm::sys::fs::identify_magic(magicStr); if (fileType != llvm::sys::fs::file_magic::unknown) return reportIOErr(filename, "read from binary"); unsigned printable = 0; for (size_t i = 0; i < readMagic; ++i) if (isprint(magic[i])) ++printable; if (10 * printable < 5 * readMagic) { // 50% printable for ASCII files should be a safe guess. return reportIOErr(filename, "won't read from likely binary"); } } } std::ifstream in(filename.str().c_str()); if (in.fail()) return reportIOErr(filename, "open"); in.seekg(0, std::ios::end); if (in.fail()) return reportIOErr(filename, "seek"); size_t size = in.tellg(); if (in.fail()) return reportIOErr(filename, "tell"); in.seekg(0); if (in.fail()) return reportIOErr(filename, "rewind"); std::string content(size, ' '); in.read(&content[0], size); if (in.fail()) return reportIOErr(filename, "read"); if (posOpenCurly != (size_t)-1 && !content.empty()) { assert(content[posOpenCurly] == '{' && "No curly at claimed position of opening curly!"); // hide the curly brace: content[posOpenCurly] = ' '; // and the matching closing '}' static const char whitespace[] = " \t\r\n"; size_t posCloseCurly = content.find_last_not_of(whitespace); if (posCloseCurly != std::string::npos) { if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') { content[posCloseCurly--] = ' '; // replace ';' and enter next if } if (content[posCloseCurly] == '}') { content[posCloseCurly] = ' '; // replace '}' } else { std::string::size_type posBlockClose = content.find_last_of('}'); if (posBlockClose != std::string::npos) { content[posBlockClose] = ' '; // replace '}' } std::string::size_type posComment = content.find_first_not_of(whitespace, posBlockClose); if (posComment != std::string::npos && content[posComment] == '/' && content[posComment+1] == '/') { // More text (comments) are okay after the last '}', but // we can not easily find it to remove it (so we need to upgrade // this code to better handle the case with comments or // preprocessor code before and after the leading { and // trailing }) while (posComment <= posCloseCurly) { content[posComment++] = ' '; // replace '}' and comment } } else { content[posCloseCurly] = '{'; // By putting the '{' back, we keep the code as consistent as // the user wrote it ... but we should still warn that we not // goint to treat this file an unamed macro. llvm::errs() << "Warning in cling::MetaProcessor: can not find the closing '}', " << llvm::sys::path::filename(filename) << " is not handled as an unamed script!\n"; } // did not find "//" } // remove comments after the trailing '}' } // find '}' } // ignore outermost block m_CurrentlyExecutingFile = filename; bool topmost = !m_TopExecutingFile.data(); if (topmost) m_TopExecutingFile = m_CurrentlyExecutingFile; Interpreter::CompilationResult ret; // We don't want to value print the results of a unnamed macro. content = "#line 2 \"" + filename.str() + "\" \n" + content; if (process((content + ";").c_str(), ret, result)) { // Input file has to be complete. llvm::errs() << "Error in cling::MetaProcessor: file " << llvm::sys::path::filename(filename) << " is incomplete (missing parenthesis or similar)!\n"; ret = Interpreter::kFailure; } m_CurrentlyExecutingFile = llvm::StringRef(); if (topmost) m_TopExecutingFile = llvm::StringRef(); return ret; } void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd, llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) { // If we have a fileName to redirect to store it. if (!file.empty()) { prevFileStack.push_back(file); // pop and push a null terminating 0. // SmallVectorImpl<T> does not have a c_str(), thus instead of casting to // a SmallString<T> we null terminate the data that we have and pop the // 0 char back. prevFileStack.back().push_back(0); prevFileStack.back().pop_back(); if (!append) { FILE * f; if (!(f = fopen(file.data(), "w"))) { llvm::errs() << "cling::MetaProcessor::setFileStream:" " The file path " << file.data() << " is not valid.\n"; } else { fclose(f); } } // Else unredirection, so switch to the previous file. } else { // If there is no previous file on the stack we pop the file if (!prevFileStack.empty()) { prevFileStack.pop_back(); } } } void MetaProcessor::setStdStream(llvm::StringRef file, RedirectionScope stream, bool append) { if (stream & kSTDOUT) { setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName); } if (stream & kSTDERR) { setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName); } } int MetaProcessor::copyFileDescriptor(int fd) { int backupFD = dup(fd); if (backupFD < 0) { llvm::errs() << "MetaProcessor::copyFileDescriptor: Duplicating the file" " descriptor " << fd << " resulted in an error." " Will not be able to unredirect.\n"; } return backupFD; } void MetaProcessor::registerUnloadPoint(const Transaction* T, llvm::StringRef filename) { m_MetaParser->getActions().registerUnloadPoint(T, filename); } } // end namespace cling <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP #define INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP /* * A collection of functions and classes related to application mainloops * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "allocore/protocol/al_Graphics.hpp" #include "allocore/spatial/al_Camera.hpp" namespace al { namespace gfx{ /// A framed area on a display screen struct Viewport { int l, b, w, h; ///< left, bottom, width, height Viewport(int w=0, int h=1) : b(0), l(0), w(w), h(h) {} Viewport(int l, int b, int w, int h) : l(l), b(b), w(w), h(h) {} double aspect() { return w/(double)h; } }; /// Higher-level utility class to manage various stereo rendering techniques class Stereographic { public: enum StereoMode{ Anaglyph=0, /**< Red (left eye) / cyan (right eye) stereo */ Active, /**< Active quad-buffered stereo */ Dual, /**< Dual side-by-side stereo */ LeftEye, /**< Left eye only */ RightEye /**< Right eye only */ }; enum AnaglyphMode { RedBlue = 0, RedGreen, RedCyan, BlueRed, GreenRed, CyanRed }; Stereographic() : mMode(Anaglyph), mAnaglyphMode(RedBlue), mStereo(false) {} ~Stereographic() {} ///< draw the scene according to the stored stereographic mode void draw(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); /// So many different ways to draw :-) void drawMono(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawActive(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawAnaglyph(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawDual(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawLeft(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawRight(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); /// Blue line sync for active stereo (for those projectors that need it) /// add this call at the end of rendering (just before the swap buffers call) void drawBlueLine(double window_width, double window_height); Stereographic& mode(StereoMode v){ mMode=v; return *this; } ///< Set stereographic mode Stereographic& stereo(bool v){ mStereo=v; return *this; } ///< Set stereographic active Stereographic& anaglyphMode(AnaglyphMode v) { mAnaglyphMode=v; return *this; } ///< set glasses type StereoMode mode() const { return mMode; } ///< Get stereographic mode bool stereo() const { return mStereo; } ///< Get stereographic active AnaglyphMode anaglyphMode() const { return mAnaglyphMode; } ///< get anaglyph glasses type protected: StereoMode mMode; AnaglyphMode mAnaglyphMode; bool mStereo; }; } // gfx:: } // al:: #endif /* include guard */ <commit_msg>updates to Viewport<commit_after>#ifndef INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP #define INCLUDE_AL_GRAPHICS_STEREOGRAPHIC_HPP /* * A collection of functions and classes related to application mainloops * AlloSphere Research Group / Media Arts & Technology, UCSB, 2009 */ /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "allocore/protocol/al_Graphics.hpp" #include "allocore/spatial/al_Camera.hpp" namespace al { namespace gfx{ /// A framed area on a display screen struct Viewport { int l, b, w, h; ///< left, bottom, width, height Viewport(int w=0, int h=1) : b(0), l(0), w(w), h(h) {} Viewport(int l, int b, int w, int h) : l(l), b(b), w(w), h(h) {} /// Get aspect ratio double aspect() const { return w/(double)h; } /// Set dimensions void set(int l_, int b_, int w_, int h_){ l=l_; b=b_; w=w_; h=h_; } }; /// Higher-level utility class to manage various stereo rendering techniques class Stereographic { public: enum StereoMode{ Anaglyph=0, /**< Red (left eye) / cyan (right eye) stereo */ Active, /**< Active quad-buffered stereo */ Dual, /**< Dual side-by-side stereo */ LeftEye, /**< Left eye only */ RightEye /**< Right eye only */ }; enum AnaglyphMode { RedBlue = 0, RedGreen, RedCyan, BlueRed, GreenRed, CyanRed }; Stereographic() : mMode(Anaglyph), mAnaglyphMode(RedBlue), mStereo(false) {} ~Stereographic() {} ///< draw the scene according to the stored stereographic mode void draw(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); /// So many different ways to draw :-) void drawMono(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawActive(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawAnaglyph(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawDual(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawLeft(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); void drawRight(Graphics& gl, Camera& cam, Pose& pose, Viewport& viewport, Drawable& draw); /// Blue line sync for active stereo (for those projectors that need it) /// add this call at the end of rendering (just before the swap buffers call) void drawBlueLine(double window_width, double window_height); Stereographic& mode(StereoMode v){ mMode=v; return *this; } ///< Set stereographic mode Stereographic& stereo(bool v){ mStereo=v; return *this; } ///< Set stereographic active Stereographic& anaglyphMode(AnaglyphMode v) { mAnaglyphMode=v; return *this; } ///< set glasses type StereoMode mode() const { return mMode; } ///< Get stereographic mode bool stereo() const { return mStereo; } ///< Get stereographic active AnaglyphMode anaglyphMode() const { return mAnaglyphMode; } ///< get anaglyph glasses type protected: StereoMode mMode; AnaglyphMode mAnaglyphMode; bool mStereo; }; } // gfx:: } // al:: #endif /* include guard */ <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_NAVIER_SOLVER_HPP #define MFEM_NAVIER_SOLVER_HPP #define NAVIER_VERSION 0.1 #include "mfem.hpp" #include "ortho_solver.hpp" namespace mfem { namespace navier { using VecFuncT = void(const Vector &x, double t, Vector &u); using ScalarFuncT = double(const Vector &x, double t); /// Container for a Dirichlet boundary condition of the velocity field. class VelDirichletBC_T { public: VelDirichletBC_T(Array<int> attr, VectorCoefficient *coeff) : attr(attr), coeff(coeff) {} VelDirichletBC_T(VelDirichletBC_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~VelDirichletBC_T() { delete coeff; } Array<int> attr; VectorCoefficient *coeff; }; /// Container for a Dirichlet boundary condition of the pressure field. class PresDirichletBC_T { public: PresDirichletBC_T(Array<int> attr, Coefficient *coeff) : attr(attr), coeff(coeff) {} PresDirichletBC_T(PresDirichletBC_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~PresDirichletBC_T() { delete coeff; } Array<int> attr; Coefficient *coeff; }; /// Container for an acceleration term. class AccelTerm_T { public: AccelTerm_T(Array<int> attr, VectorCoefficient *coeff) : attr(attr), coeff(coeff) {} AccelTerm_T(AccelTerm_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~AccelTerm_T() { delete coeff; } Array<int> attr; VectorCoefficient *coeff; }; /// Transient incompressible Navier Stokes solver in a split scheme formulation. /** * This implementation of a transient incompressible Navier Stokes solver uses * the non-dimensionalized formulation. The coupled momentum and * incompressibilty equations are decoupled using the split scheme described in * [1]. This leads to three solving steps. * * 1. An extrapolation step for all nonlinear terms which are treated * explicitly. This step avoids a fully coupled nonlinear solve and only * requires a solve of the mass matrix in velocity space \f$M_v^{-1}\f$. On * the other hand this introduces a CFL stability condition on the maximum * timestep. * * 2. A Poisson solve \f$S_p^{-1}\f$. * * 3. A Helmholtz like solve \f$(M_v - \partial t K_v)^{-1}\f$. * * The numerical solver setup for each step are as follows. * * \f$M_v^{-1}\f$ is solved using CG with Jacobi as preconditioner. * * \f$S_p^{-1}\f$ is solved using CG with AMG applied to the low order refined * (LOR) assembled pressure poisson matrix. To avoid assembling a matrix for * preconditioning, one can use p-MG as an alternative (NYI). * * \f$(M_v - \partial t K_v)^{-1}\f$ due to the CFL condition we expect the time * step to be small. Therefore this is solved using CG with Jacobi as * preconditioner. For large time steps a preconditioner like AMG or p-MG should * be used (NYI). * * Statements marked with NYI mean this feature is planned but Not Yet * Implemented. * * A detailed description is available in [1] section 4.2. The algorithm is * originated from [2]. * * [1] Michael Franco, Jean-Sylvain Camier, Julian Andrej, Will Pazner (2020) * High-order matrix-free incompressible flow solvers with GPU acceleration and * low-order refined preconditioners (https://arxiv.org/abs/1910.03032) * * [2] A. G. Tomboulides, J. C. Y. Lee & S. A. Orszag (1997) Numerical * Simulation of Low Mach Number Reactive Flows */ class NavierSolver { public: /// Initialize data structures, set FE space order and kinematic viscosity. /** * The ParMesh @a mesh can be a linear or curved parallel mesh. The @a order * of the finite element spaces is this algorithm is of equal order * \f$(P_N)^d P_N\f$ for velocity and pressure respectively. This means the * pressure is in discretized in the same space (just scalar instead of a * vector space) as the velocity. * * Kinematic viscosity (dimensionless) is set using @a kin_vis and * automatically converted to the Reynolds number. If you want to set the * Reynolds number directly, you can provide the inverse. */ NavierSolver(ParMesh *mesh, int order, double kin_vis); /// Initialize forms, solvers and preconditioners. void Setup(double dt); /// Compute solution at the next time step t+dt. void Step(double &time, double dt, int cur_step); /// Return a pointer to the current velocity ParGridFunction. ParGridFunction *GetCurrentVelocity() { return &un_gf; } /// Return a pointer to the current pressure ParGridFunction. ParGridFunction *GetCurrentPressure() { return &pn_gf; } /// Add a Dirichlet boundary condition to the velocity field. void AddVelDirichletBC(VectorCoefficient *coeff, Array<int> &attr); void AddVelDirichletBC(VecFuncT *f, Array<int> &attr); /// Add a Dirichlet boundary condition to the pressure field. void AddPresDirichletBC(Coefficient *coeff, Array<int> &attr); void AddPresDirichletBC(ScalarFuncT *f, Array<int> &attr); /// Add an accelaration term to the RHS of the equation. /** * The VecFuncT @a f is evaluated at the current time t and extrapolated * together with the nonlinear parts of the Navier Stokes equation. */ void AddAccelTerm(VectorCoefficient *coeff, Array<int> &attr); void AddAccelTerm(VecFuncT *f, Array<int> &attr); /// Enable partial assembly for every operator. void EnablePA(bool pa) { partial_assembly = pa; } /// Enable numerical integration rules. This means collocated quadrature at /// the nodal points. void EnableNI(bool ni) { numerical_integ = ni; } /// Print timing summary of the solving routine. /** * The summary shows the timing in seconds in the first row of * * 1. SETUP: Time spent for the setup of all forms, solvers and * preconditioners. * 2. STEP: Time spent computing a full time step. It includes allthree * solves. * 3. EXTRAP: Time spent for extrapolation of all forcing and nonlinear * terms. * 4. CURLCURL: Time spent for computing the curl curl term in the pressure * Poisson equation (see references for detailed explanation). * 5. PSOLVE: Time spent in the pressure Poisson solve. * 6. HSOLVE: Time spent in the Helmholtz solve. * * The second row shows a proportion of a column relative to the whole * time step. */ void PrintTimingData(); ~NavierSolver(); /// Compute \f$\nabla \times \nabla \times u\f$ for \f$u \in (H^1)^2\f$. void ComputeCurl2D(ParGridFunction &u, ParGridFunction &cu, bool assume_scalar = false); /// Compute \f$\nabla \times \nabla \times u\f$ for \f$u \in (H^1)^3\f$. void ComputeCurl3D(ParGridFunction &u, ParGridFunction &cu); /// Remove mean from a Vector. /** * Modify the Vector @a v by subtracting its mean using * \f$v = v - \frac{\sum_i^N v_i}{N} \f$ */ void Orthogonalize(Vector &v); /// Remove the mean from a ParGridFunction. /** * Modify the ParGridFunction @a v by subtracting its mean using * \f$ v = v - \int_\Omega \frac{v}{vol(\Omega)} dx \f$. */ void MeanZero(ParGridFunction &v); /// Compute CFL double ComputeCFL(ParGridFunction &u, double dt); /// Set the number of modes to cut off in the interpolation filter void SetCutoffModes(int c) { filter_cutoff_modes = c; } /// Set the interpolation filter parameter @a alpha /** * If the @a a is > 0, the filtering algorithm for the velocity field after * every time step from [1] is used. * * [1] Paul Fischer, Julia Mullen: Filter-based stabilization of spectral * element methods */ void SetFilterAlpha(double a) { filter_alpha = a; } protected: /// Print informations about the Navier version. void PrintInfo(); /// Update the EXTk/BDF time integration coefficient. /** * Depending on which time step the computation is in, the EXTk/BDF time * integration coefficients have to be set accordingly. This allows * bootstrapping with a BDF scheme of order 1 and increasing the order each * following time step, up to order 3. */ void SetTimeIntegrationCoefficients(int step); /// Eliminate essential BCs in an Operator and apply to RHS. void EliminateRHS(Operator &A, ConstrainedOperator &constrainedA, const Array<int> &ess_tdof_list, Vector &x, Vector &b, Vector &X, Vector &B, int copy_interior = 0); /// Enable/disable debug output. bool debug = false; /// Enable/disable verbose output. bool verbose = true; /// Enable/disable partial assembly of forms. bool partial_assembly = false; /// Enable/disable numerical integration rules of forms. bool numerical_integ = false; /// The parallel mesh. ParMesh *pmesh = nullptr; /// The order of the velocity and pressure space. int order; /// Kinematic viscosity (dimensionless). double kin_vis; /// Velocity \f$H^1\f$ finite element collection. FiniteElementCollection *vfec = nullptr; /// Pressure \f$H^1\f$ finite element collection. FiniteElementCollection *pfec = nullptr; /// Velocity \f$(H^1)^d\f$ finite element space. ParFiniteElementSpace *vfes = nullptr; /// Pressure \f$H^1\f$ finite element space. ParFiniteElementSpace *pfes = nullptr; ParNonlinearForm *N = nullptr; ParBilinearForm *Mv_form = nullptr; ParBilinearForm *Sp_form = nullptr; ParMixedBilinearForm *D_form = nullptr; ParMixedBilinearForm *G_form = nullptr; ParBilinearForm *H_form = nullptr; VectorGridFunctionCoefficient *FText_gfcoeff = nullptr; ParLinearForm *FText_bdr_form = nullptr; ParLinearForm *f_form = nullptr; ParLinearForm *g_bdr_form = nullptr; /// Linear form to compute the mass matrix in various subroutines. ParLinearForm *mass_lf = nullptr; ConstantCoefficient onecoeff; double volume = 0.0; ConstantCoefficient nlcoeff; ConstantCoefficient Sp_coeff; ConstantCoefficient H_lincoeff; ConstantCoefficient H_bdfcoeff; OperatorHandle Mv; OperatorHandle Sp; OperatorHandle D; OperatorHandle G; OperatorHandle H; Solver *MvInvPC = nullptr; CGSolver *MvInv = nullptr; HypreBoomerAMG *SpInvPC = nullptr; OrthoSolver *SpInvOrthoPC = nullptr; CGSolver *SpInv = nullptr; Solver *HInvPC = nullptr; CGSolver *HInv = nullptr; Vector fn, un, unm1, unm2, Nun, Nunm1, Nunm2, Fext, FText, Lext, resu; Vector tmp1; Vector pn, resp, FText_bdr, g_bdr; ParGridFunction un_gf, curlu_gf, curlcurlu_gf, Lext_gf, FText_gf, resu_gf; ParGridFunction pn_gf, resp_gf; // All essential attributes. Array<int> vel_ess_attr; Array<int> pres_ess_attr; // All essential true dofs. Array<int> vel_ess_tdof; Array<int> pres_ess_tdof; // Bookkeeping for velocity dirichlet bcs. std::vector<VelDirichletBC_T> vel_dbcs; // Bookkeeping for pressure dirichlet bcs. std::vector<PresDirichletBC_T> pres_dbcs; // Bookkeeping for acceleration (forcing) terms. std::vector<AccelTerm_T> accel_terms; int cur_step = 0; // BDFk/EXTk coefficients. double bd0 = 0.0; double bd1 = 0.0; double bd2 = 0.0; double bd3 = 0.0; double ab1 = 0.0; double ab2 = 0.0; double ab3 = 0.0; // Timers. StopWatch sw_setup, sw_step, sw_extrap, sw_curlcurl, sw_spsolve, sw_hsolve; // Print levels. int pl_mvsolve = 0; int pl_spsolve = 0; int pl_hsolve = 0; int pl_amg = 0; // Relative tolerances. double rtol_spsolve = 1e-6; double rtol_hsolve = 1e-8; // Iteration counts. int iter_mvsolve = 0, iter_spsolve = 0, iter_hsolve = 0; // Residuals. double res_mvsolve = 0.0, res_spsolve = 0.0, res_hsolve = 0.0; // LOR related. ParMesh *pmesh_lor = nullptr; FiniteElementCollection *pfec_lor = nullptr; ParFiniteElementSpace *pfes_lor = nullptr; InterpolationGridTransfer *vgt = nullptr, *pgt = nullptr; ParBilinearForm *Mv_form_lor = nullptr; ParBilinearForm *Sp_form_lor = nullptr; ParBilinearForm *H_form_lor = nullptr; OperatorHandle Mv_lor; OperatorHandle Sp_lor; OperatorHandle H_lor; // Filter-based stabilization int filter_cutoff_modes = 1; double filter_alpha = 0.0; FiniteElementCollection *vfec_filter = nullptr; ParFiniteElementSpace *vfes_filter = nullptr; ParGridFunction un_NM1_gf; ParGridFunction un_filtered_gf; }; } // namespace navier } // namespace mfem #endif <commit_msg>spelling<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_NAVIER_SOLVER_HPP #define MFEM_NAVIER_SOLVER_HPP #define NAVIER_VERSION 0.1 #include "mfem.hpp" #include "ortho_solver.hpp" namespace mfem { namespace navier { using VecFuncT = void(const Vector &x, double t, Vector &u); using ScalarFuncT = double(const Vector &x, double t); /// Container for a Dirichlet boundary condition of the velocity field. class VelDirichletBC_T { public: VelDirichletBC_T(Array<int> attr, VectorCoefficient *coeff) : attr(attr), coeff(coeff) {} VelDirichletBC_T(VelDirichletBC_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~VelDirichletBC_T() { delete coeff; } Array<int> attr; VectorCoefficient *coeff; }; /// Container for a Dirichlet boundary condition of the pressure field. class PresDirichletBC_T { public: PresDirichletBC_T(Array<int> attr, Coefficient *coeff) : attr(attr), coeff(coeff) {} PresDirichletBC_T(PresDirichletBC_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~PresDirichletBC_T() { delete coeff; } Array<int> attr; Coefficient *coeff; }; /// Container for an acceleration term. class AccelTerm_T { public: AccelTerm_T(Array<int> attr, VectorCoefficient *coeff) : attr(attr), coeff(coeff) {} AccelTerm_T(AccelTerm_T &&obj) { // Deep copy the attribute array this->attr = obj.attr; // Move the coefficient pointer this->coeff = obj.coeff; obj.coeff = nullptr; } ~AccelTerm_T() { delete coeff; } Array<int> attr; VectorCoefficient *coeff; }; /// Transient incompressible Navier Stokes solver in a split scheme formulation. /** * This implementation of a transient incompressible Navier Stokes solver uses * the non-dimensionalized formulation. The coupled momentum and * incompressibilty equations are decoupled using the split scheme described in * [1]. This leads to three solving steps. * * 1. An extrapolation step for all nonlinear terms which are treated * explicitly. This step avoids a fully coupled nonlinear solve and only * requires a solve of the mass matrix in velocity space \f$M_v^{-1}\f$. On * the other hand this introduces a CFL stability condition on the maximum * timestep. * * 2. A Poisson solve \f$S_p^{-1}\f$. * * 3. A Helmholtz like solve \f$(M_v - \partial t K_v)^{-1}\f$. * * The numerical solver setup for each step are as follows. * * \f$M_v^{-1}\f$ is solved using CG with Jacobi as preconditioner. * * \f$S_p^{-1}\f$ is solved using CG with AMG applied to the low order refined * (LOR) assembled pressure poisson matrix. To avoid assembling a matrix for * preconditioning, one can use p-MG as an alternative (NYI). * * \f$(M_v - \partial t K_v)^{-1}\f$ due to the CFL condition we expect the time * step to be small. Therefore this is solved using CG with Jacobi as * preconditioner. For large time steps a preconditioner like AMG or p-MG should * be used (NYI). * * Statements marked with NYI mean this feature is planned but Not Yet * Implemented. * * A detailed description is available in [1] section 4.2. The algorithm is * originated from [2]. * * [1] Michael Franco, Jean-Sylvain Camier, Julian Andrej, Will Pazner (2020) * High-order matrix-free incompressible flow solvers with GPU acceleration and * low-order refined preconditioners (https://arxiv.org/abs/1910.03032) * * [2] A. G. Tomboulides, J. C. Y. Lee & S. A. Orszag (1997) Numerical * Simulation of Low Mach Number Reactive Flows */ class NavierSolver { public: /// Initialize data structures, set FE space order and kinematic viscosity. /** * The ParMesh @a mesh can be a linear or curved parallel mesh. The @a order * of the finite element spaces is this algorithm is of equal order * \f$(P_N)^d P_N\f$ for velocity and pressure respectively. This means the * pressure is in discretized in the same space (just scalar instead of a * vector space) as the velocity. * * Kinematic viscosity (dimensionless) is set using @a kin_vis and * automatically converted to the Reynolds number. If you want to set the * Reynolds number directly, you can provide the inverse. */ NavierSolver(ParMesh *mesh, int order, double kin_vis); /// Initialize forms, solvers and preconditioners. void Setup(double dt); /// Compute solution at the next time step t+dt. void Step(double &time, double dt, int cur_step); /// Return a pointer to the current velocity ParGridFunction. ParGridFunction *GetCurrentVelocity() { return &un_gf; } /// Return a pointer to the current pressure ParGridFunction. ParGridFunction *GetCurrentPressure() { return &pn_gf; } /// Add a Dirichlet boundary condition to the velocity field. void AddVelDirichletBC(VectorCoefficient *coeff, Array<int> &attr); void AddVelDirichletBC(VecFuncT *f, Array<int> &attr); /// Add a Dirichlet boundary condition to the pressure field. void AddPresDirichletBC(Coefficient *coeff, Array<int> &attr); void AddPresDirichletBC(ScalarFuncT *f, Array<int> &attr); /// Add an accelaration term to the RHS of the equation. /** * The VecFuncT @a f is evaluated at the current time t and extrapolated * together with the nonlinear parts of the Navier Stokes equation. */ void AddAccelTerm(VectorCoefficient *coeff, Array<int> &attr); void AddAccelTerm(VecFuncT *f, Array<int> &attr); /// Enable partial assembly for every operator. void EnablePA(bool pa) { partial_assembly = pa; } /// Enable numerical integration rules. This means collocated quadrature at /// the nodal points. void EnableNI(bool ni) { numerical_integ = ni; } /// Print timing summary of the solving routine. /** * The summary shows the timing in seconds in the first row of * * 1. SETUP: Time spent for the setup of all forms, solvers and * preconditioners. * 2. STEP: Time spent computing a full time step. It includes allthree * solves. * 3. EXTRAP: Time spent for extrapolation of all forcing and nonlinear * terms. * 4. CURLCURL: Time spent for computing the curl curl term in the pressure * Poisson equation (see references for detailed explanation). * 5. PSOLVE: Time spent in the pressure Poisson solve. * 6. HSOLVE: Time spent in the Helmholtz solve. * * The second row shows a proportion of a column relative to the whole * time step. */ void PrintTimingData(); ~NavierSolver(); /// Compute \f$\nabla \times \nabla \times u\f$ for \f$u \in (H^1)^2\f$. void ComputeCurl2D(ParGridFunction &u, ParGridFunction &cu, bool assume_scalar = false); /// Compute \f$\nabla \times \nabla \times u\f$ for \f$u \in (H^1)^3\f$. void ComputeCurl3D(ParGridFunction &u, ParGridFunction &cu); /// Remove mean from a Vector. /** * Modify the Vector @a v by subtracting its mean using * \f$v = v - \frac{\sum_i^N v_i}{N} \f$ */ void Orthogonalize(Vector &v); /// Remove the mean from a ParGridFunction. /** * Modify the ParGridFunction @a v by subtracting its mean using * \f$ v = v - \int_\Omega \frac{v}{vol(\Omega)} dx \f$. */ void MeanZero(ParGridFunction &v); /// Compute CFL double ComputeCFL(ParGridFunction &u, double dt); /// Set the number of modes to cut off in the interpolation filter void SetCutoffModes(int c) { filter_cutoff_modes = c; } /// Set the interpolation filter parameter @a alpha /** * If @a a is > 0, the filtering algorithm for the velocity field after every * time step from [1] is used. * * [1] Paul Fischer, Julia Mullen: Filter-based stabilization of spectral * element methods */ void SetFilterAlpha(double a) { filter_alpha = a; } protected: /// Print informations about the Navier version. void PrintInfo(); /// Update the EXTk/BDF time integration coefficient. /** * Depending on which time step the computation is in, the EXTk/BDF time * integration coefficients have to be set accordingly. This allows * bootstrapping with a BDF scheme of order 1 and increasing the order each * following time step, up to order 3. */ void SetTimeIntegrationCoefficients(int step); /// Eliminate essential BCs in an Operator and apply to RHS. void EliminateRHS(Operator &A, ConstrainedOperator &constrainedA, const Array<int> &ess_tdof_list, Vector &x, Vector &b, Vector &X, Vector &B, int copy_interior = 0); /// Enable/disable debug output. bool debug = false; /// Enable/disable verbose output. bool verbose = true; /// Enable/disable partial assembly of forms. bool partial_assembly = false; /// Enable/disable numerical integration rules of forms. bool numerical_integ = false; /// The parallel mesh. ParMesh *pmesh = nullptr; /// The order of the velocity and pressure space. int order; /// Kinematic viscosity (dimensionless). double kin_vis; /// Velocity \f$H^1\f$ finite element collection. FiniteElementCollection *vfec = nullptr; /// Pressure \f$H^1\f$ finite element collection. FiniteElementCollection *pfec = nullptr; /// Velocity \f$(H^1)^d\f$ finite element space. ParFiniteElementSpace *vfes = nullptr; /// Pressure \f$H^1\f$ finite element space. ParFiniteElementSpace *pfes = nullptr; ParNonlinearForm *N = nullptr; ParBilinearForm *Mv_form = nullptr; ParBilinearForm *Sp_form = nullptr; ParMixedBilinearForm *D_form = nullptr; ParMixedBilinearForm *G_form = nullptr; ParBilinearForm *H_form = nullptr; VectorGridFunctionCoefficient *FText_gfcoeff = nullptr; ParLinearForm *FText_bdr_form = nullptr; ParLinearForm *f_form = nullptr; ParLinearForm *g_bdr_form = nullptr; /// Linear form to compute the mass matrix in various subroutines. ParLinearForm *mass_lf = nullptr; ConstantCoefficient onecoeff; double volume = 0.0; ConstantCoefficient nlcoeff; ConstantCoefficient Sp_coeff; ConstantCoefficient H_lincoeff; ConstantCoefficient H_bdfcoeff; OperatorHandle Mv; OperatorHandle Sp; OperatorHandle D; OperatorHandle G; OperatorHandle H; Solver *MvInvPC = nullptr; CGSolver *MvInv = nullptr; HypreBoomerAMG *SpInvPC = nullptr; OrthoSolver *SpInvOrthoPC = nullptr; CGSolver *SpInv = nullptr; Solver *HInvPC = nullptr; CGSolver *HInv = nullptr; Vector fn, un, unm1, unm2, Nun, Nunm1, Nunm2, Fext, FText, Lext, resu; Vector tmp1; Vector pn, resp, FText_bdr, g_bdr; ParGridFunction un_gf, curlu_gf, curlcurlu_gf, Lext_gf, FText_gf, resu_gf; ParGridFunction pn_gf, resp_gf; // All essential attributes. Array<int> vel_ess_attr; Array<int> pres_ess_attr; // All essential true dofs. Array<int> vel_ess_tdof; Array<int> pres_ess_tdof; // Bookkeeping for velocity dirichlet bcs. std::vector<VelDirichletBC_T> vel_dbcs; // Bookkeeping for pressure dirichlet bcs. std::vector<PresDirichletBC_T> pres_dbcs; // Bookkeeping for acceleration (forcing) terms. std::vector<AccelTerm_T> accel_terms; int cur_step = 0; // BDFk/EXTk coefficients. double bd0 = 0.0; double bd1 = 0.0; double bd2 = 0.0; double bd3 = 0.0; double ab1 = 0.0; double ab2 = 0.0; double ab3 = 0.0; // Timers. StopWatch sw_setup, sw_step, sw_extrap, sw_curlcurl, sw_spsolve, sw_hsolve; // Print levels. int pl_mvsolve = 0; int pl_spsolve = 0; int pl_hsolve = 0; int pl_amg = 0; // Relative tolerances. double rtol_spsolve = 1e-6; double rtol_hsolve = 1e-8; // Iteration counts. int iter_mvsolve = 0, iter_spsolve = 0, iter_hsolve = 0; // Residuals. double res_mvsolve = 0.0, res_spsolve = 0.0, res_hsolve = 0.0; // LOR related. ParMesh *pmesh_lor = nullptr; FiniteElementCollection *pfec_lor = nullptr; ParFiniteElementSpace *pfes_lor = nullptr; InterpolationGridTransfer *vgt = nullptr, *pgt = nullptr; ParBilinearForm *Mv_form_lor = nullptr; ParBilinearForm *Sp_form_lor = nullptr; ParBilinearForm *H_form_lor = nullptr; OperatorHandle Mv_lor; OperatorHandle Sp_lor; OperatorHandle H_lor; // Filter-based stabilization int filter_cutoff_modes = 1; double filter_alpha = 0.0; FiniteElementCollection *vfec_filter = nullptr; ParFiniteElementSpace *vfes_filter = nullptr; ParGridFunction un_NM1_gf; ParGridFunction un_filtered_gf; }; } // namespace navier } // namespace mfem #endif <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2015 - 2017) // Rene Milk (2016 - 2017) #include <dune/xt/common/test/main.hxx> // <- this one has to come first #include "l2.hh" #include <dune/gdt/test/spaces/cg/pdelab.hh> #include <dune/gdt/test/spaces/dg/fem.hh> #include <dune/gdt/test/spaces/fv/default.hh> using namespace Dune::GDT::Test; #if HAVE_DUNE_FEM typedef testing::Types<SPACE_DG_FEM_YASPGRID(1, 1, 2), SPACE_DG_FEM_YASPGRID(2, 1, 2), SPACE_DG_FEM_YASPGRID(3, 1, 2)> QuadraticSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, QuadraticSpaces); #elif HAVE_DUNE_PDELAB // HAVE_DUNE_FEM typedef testing::Types<SPACE_CG_PDELAB_YASPGRID(1, 1, 1), SPACE_CG_PDELAB_YASPGRID(2, 1, 1), SPACE_CG_PDELAB_YASPGRID(3, 1, 1)> LinearSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, LinearSpaces); #else // HAVE_DUNE_FEM || HAVE_DUNE_PDELAB typedef testing::Types<SPACE_FV_YASPGRID(1, 1), SPACE_FV_YASPGRID(2, 1), SPACE_FV_YASPGRID(3, 1)> ConstantSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, ConstantSpaces); #endif // HAVE_DUNE_FEM || HAVE_DUNE_PDELAB TYPED_TEST(L2MatrixOperatorTest, constructible_by_ctor) { this->constructible_by_ctor(); } TYPED_TEST(L2MatrixOperatorTest, constructible_by_factory) { this->constructible_by_factory(); } TYPED_TEST(L2MatrixOperatorTest, is_matrix_operator) { this->is_matrix_operator(); } TYPED_TEST(L2MatrixOperatorTest, correct_for_constant_arguments) { this->correct_for_constant_arguments(2.5e-15); } #if HAVE_DUNE_FEM || HAVE_DUNE_PDELAB TYPED_TEST(L2MatrixOperatorTest, correct_for_linear_arguments) { this->correct_for_linear_arguments(); } #else TEST(DISABLED_L2MatrixOperatorTest, correct_for_linear_arguments) { std::cerr << Dune::XT::Common::colorStringRed("Missing dependencies!") << std::endl; } #endif #if HAVE_DUNE_FEM TYPED_TEST(L2MatrixOperatorTest, correct_for_quadratic_arguments) { this->correct_for_quadratic_arguments(); } #else TEST(DISABLED_L2MatrixOperatorTest, correct_for_quadratic_arguments) { std::cerr << Dune::XT::Common::colorStringRed("Missing dependencies!") << std::endl; } #endif <commit_msg>[test] lower expectations for l2 matrix operator<commit_after>// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2015 - 2017) // Rene Milk (2016 - 2017) #include <dune/xt/common/test/main.hxx> // <- this one has to come first #include "l2.hh" #include <dune/gdt/test/spaces/cg/pdelab.hh> #include <dune/gdt/test/spaces/dg/fem.hh> #include <dune/gdt/test/spaces/fv/default.hh> using namespace Dune::GDT::Test; #if HAVE_DUNE_FEM typedef testing::Types<SPACE_DG_FEM_YASPGRID(1, 1, 2), SPACE_DG_FEM_YASPGRID(2, 1, 2), SPACE_DG_FEM_YASPGRID(3, 1, 2)> QuadraticSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, QuadraticSpaces); #elif HAVE_DUNE_PDELAB // HAVE_DUNE_FEM typedef testing::Types<SPACE_CG_PDELAB_YASPGRID(1, 1, 1), SPACE_CG_PDELAB_YASPGRID(2, 1, 1), SPACE_CG_PDELAB_YASPGRID(3, 1, 1)> LinearSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, LinearSpaces); #else // HAVE_DUNE_FEM || HAVE_DUNE_PDELAB typedef testing::Types<SPACE_FV_YASPGRID(1, 1), SPACE_FV_YASPGRID(2, 1), SPACE_FV_YASPGRID(3, 1)> ConstantSpaces; TYPED_TEST_CASE(L2MatrixOperatorTest, ConstantSpaces); #endif // HAVE_DUNE_FEM || HAVE_DUNE_PDELAB TYPED_TEST(L2MatrixOperatorTest, constructible_by_ctor) { this->constructible_by_ctor(); } TYPED_TEST(L2MatrixOperatorTest, constructible_by_factory) { this->constructible_by_factory(); } TYPED_TEST(L2MatrixOperatorTest, is_matrix_operator) { this->is_matrix_operator(); } TYPED_TEST(L2MatrixOperatorTest, correct_for_constant_arguments) { this->correct_for_constant_arguments(1.5e-14); } #if HAVE_DUNE_FEM || HAVE_DUNE_PDELAB TYPED_TEST(L2MatrixOperatorTest, correct_for_linear_arguments) { this->correct_for_linear_arguments(); } #else TEST(DISABLED_L2MatrixOperatorTest, correct_for_linear_arguments) { std::cerr << Dune::XT::Common::colorStringRed("Missing dependencies!") << std::endl; } #endif #if HAVE_DUNE_FEM TYPED_TEST(L2MatrixOperatorTest, correct_for_quadratic_arguments) { this->correct_for_quadratic_arguments(); } #else TEST(DISABLED_L2MatrixOperatorTest, correct_for_quadratic_arguments) { std::cerr << Dune::XT::Common::colorStringRed("Missing dependencies!") << std::endl; } #endif <|endoftext|>
<commit_before>/** * @file density.cpp * * Computes desity for dry air from pressure and temperature using the ideal gas law. * * @date Mar 11, 2014 * @author Tack */ #include "density.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("density"); density::density() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName)); } void density::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to ??? * - name PARM_NAME * - univ_id UNIV_ID * - grib2 descriptor X'Y'Z * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * */ vector<param> theParams; param theRequestedParam("RHO-KGM3", 9999); // GRIB 2 theRequestedParam.GribDiscipline(0); theRequestedParam.GribCategory(3); theRequestedParam.GribParameter(10); // GRIB 1 /* * GRIB 1 parameters go here * */ theParams.push_back(theRequestedParam); SetParams(theParams); Start(); } /* * Calculate() * * This function does the actual calculation. */ void density::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters /* * eg. param PParam("P-Pa"); for pressure in pascals * */ param PParam("P-PA"); param TParam("T-K"); // ---- unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); shared_ptr<info> PInfo; shared_ptr<info> TInfo; try { // Source info for PParam and TParam PInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), PParam); TInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), TParam); // ---- } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (itsConfiguration->StatisticsEnabled()) { processTimer->Start(); } int missingCount = 0; int count = 0; /* * Converting original grid-data to newbase grid * */ shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> PGrid(PInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); bool equalGrids = (*myTargetInfo->Grid() == *PInfo->Grid() && *myTargetInfo->Grid() == *TInfo->Grid()); string deviceType; { deviceType = "CPU"; assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; /* * interpolation happens here * */ double P = kFloatMissing; double T = kFloatMissing; InterpolateToPoint(targetGrid, PGrid, equalGrids, P); InterpolateToPoint(targetGrid, TGrid, equalGrids, T); if (P == kFloatMissing || T == kFloatMissing ) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } // actual calculation of the density using the ideal gas law double rho; rho = P / (constants::kRd * T); if (!myTargetInfo->Value(rho)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } } /* * Newbase normalizes scanning mode to bottom left -- if that's not what * the target scanning mode is, we have to swap the data back. */ SwapTo(myTargetInfo, kBottomLeft); if (itsConfiguration->StatisticsEnabled()) { processTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif itsConfiguration->Statistics()->AddToMissingCount(missingCount); itsConfiguration->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places * */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (itsConfiguration->FileWriteOption() != kSingleFile) { WriteToFile(myTargetInfo); } } } <commit_msg>Changed PParam to also except pressure in hPa and made changes to allow calculation on pressure levels.<commit_after>/** * @file density.cpp * * Computes desity for dry air from pressure and temperature using the ideal gas law. * * @date Mar 11, 2014 * @author Tack */ #include "density.h" #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const string itsName("density"); density::density() { itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName)); } void density::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to ??? * - name PARM_NAME * - univ_id UNIV_ID * - grib2 descriptor X'Y'Z * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * */ vector<param> theParams; param theRequestedParam("RHO-KGM3", 9999); // GRIB 2 theRequestedParam.GribDiscipline(0); theRequestedParam.GribCategory(3); theRequestedParam.GribParameter(10); // GRIB 1 /* * GRIB 1 parameters go here * */ theParams.push_back(theRequestedParam); SetParams(theParams); Start(); } /* * Calculate() * * This function does the actual calculation. */ void density::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { shared_ptr<fetcher> theFetcher = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters /* * eg. param PParam("P-Pa"); for pressure in pascals * */ params PParam = { param("P-PA"), param("P-HPA") }; param TParam("T-K"); // ---- unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(itsName + "Thread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); double PScale = 1; shared_ptr<info> PInfo; shared_ptr<info> TInfo; shared_ptr<NFmiGrid> PGrid; bool isPressureLevel = (myTargetInfo->Level().Type() == kPressure); try { if(!isPressureLevel) { // Source info for PParam and TParam PInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), PParam); if (PInfo->Param().Unit() == kHPa || PInfo->Param().Name() == "P-HPA") { PScale = 100; } PGrid = shared_ptr<NFmiGrid> (PInfo->Grid()->ToNewbaseGrid()); } TInfo = theFetcher->Fetch(itsConfiguration, myTargetInfo->Time(), myTargetInfo->Level(), TParam); // ---- } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Warning("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Fill(kFloatMissing); if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size()); itsConfiguration->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size()); } continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); if (itsConfiguration->StatisticsEnabled()) { processTimer->Start(); } int missingCount = 0; int count = 0; /* * Converting original grid-data to newbase grid * */ shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid()); shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid()); bool equalGrids = ((isPressureLevel || *myTargetInfo->Grid() == *PInfo->Grid()) && *myTargetInfo->Grid() == *TInfo->Grid()); string deviceType; { deviceType = "CPU"; assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; /* * interpolation happens here * */ double P = kFloatMissing; double T = kFloatMissing; if (isPressureLevel) { P = 100 * myTargetInfo->Level().Value(); } else { InterpolateToPoint(targetGrid, PGrid, equalGrids, P); } InterpolateToPoint(targetGrid, TGrid, equalGrids, T); if (P == kFloatMissing || T == kFloatMissing ) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } // actual calculation of the density using the ideal gas law double rho; rho = P * PScale / (constants::kRd * T); if (!myTargetInfo->Value(rho)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } } /* * Newbase normalizes scanning mode to bottom left -- if that's not what * the target scanning mode is, we have to swap the data back. */ SwapTo(myTargetInfo, kBottomLeft); if (itsConfiguration->StatisticsEnabled()) { processTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(processTimer->GetTime()); #ifdef DEBUG itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType); #endif itsConfiguration->Statistics()->AddToMissingCount(missingCount); itsConfiguration->Statistics()->AddToValueCount(count); } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places * */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (itsConfiguration->FileWriteOption() != kSingleFile) { WriteToFile(myTargetInfo); } } } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Unit test for speech Hotword model using TFLite Ops. #include <string.h> #include <memory> #include <string> #include "base/logging.h" #include "testing/base/public/googletest.h" #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "tensorflow/contrib/lite/context.h" #include "tensorflow/contrib/lite/interpreter.h" #include "tensorflow/contrib/lite/kernels/register.h" #include "tensorflow/contrib/lite/model.h" #include "tensorflow/contrib/lite/models/test_utils.h" namespace tflite { namespace models { void RunTest(int model_input_tensor, int svdf_layer_state_tensor, int model_output_tensor, const string& model_name, const string& golden_in_name, const string& golden_out_name) { // Read the model. string tflite_file_path = StrCat(TestDataPath(), "/", model_name); auto model = FlatBufferModel::BuildFromFile(tflite_file_path.c_str()); CHECK(model) << "Failed to read model from file " << tflite_file_path; // Initialize the interpreter. ops::builtin::BuiltinOpResolver builtins; std::unique_ptr<Interpreter> interpreter; InterpreterBuilder(*model, builtins)(&interpreter); CHECK(interpreter != nullptr); interpreter->AllocateTensors(); // Reset the SVDF layer state. memset(interpreter->tensor(svdf_layer_state_tensor)->data.raw, 0, interpreter->tensor(svdf_layer_state_tensor)->bytes); // Load the input frames. Frames input_frames; const string input_file_path = StrCat(TestDataPath(), "/", golden_in_name); ReadFrames(input_file_path, &input_frames); // Load the golden output results. Frames output_frames; const string output_file_path = StrCat(TestDataPath(), "/", golden_out_name); ReadFrames(output_file_path, &output_frames); const int speech_batch_size = interpreter->tensor(model_input_tensor)->dims->data[0]; const int speech_input_size = interpreter->tensor(model_input_tensor)->dims->data[1]; const int speech_output_size = interpreter->tensor(model_output_tensor)->dims->data[1]; const int input_sequence_size = input_frames[0].size() / (speech_input_size * speech_batch_size); float* input_ptr = interpreter->tensor(model_input_tensor)->data.f; float* output_ptr = interpreter->tensor(model_output_tensor)->data.f; // The first layer (SVDF) input size is 40 (speech_input_size). Each speech // input frames for this model is 1280 floats, which can be fed to input in a // sequence of size 32 (input_sequence_size). for (int i = 0; i < TestInputSize(input_frames); i++) { int frame_ptr = 0; for (int s = 0; s < input_sequence_size; s++) { for (int k = 0; k < speech_input_size * speech_batch_size; k++) { input_ptr[k] = input_frames[i][frame_ptr++]; } interpreter->Invoke(); } // After the whole frame (1280 floats) is fed, we can check the output frame // matches with the golden output frame. for (int k = 0; k < speech_output_size; k++) { ASSERT_NEAR(output_ptr[k], output_frames[i][k], 1e-5); } } } TEST(SpeechHotword, OkGoogleTestRank1) { constexpr int kModelInputTensor = 0; constexpr int kSvdfLayerStateTensor = 4; constexpr int kModelOutputTensor = 18; RunTest(kModelInputTensor, kSvdfLayerStateTensor, kModelOutputTensor, "speech_hotword_model_rank1.tflite", "speech_hotword_model_in.csv", "speech_hotword_model_out_rank1.csv"); } TEST(SpeechHotword, OkGoogleTestRank2) { constexpr int kModelInputTensor = 17; constexpr int kSvdfLayerStateTensor = 1; constexpr int kModelOutputTensor = 18; RunTest(kModelInputTensor, kSvdfLayerStateTensor, kModelOutputTensor, "speech_hotword_model_rank2.tflite", "speech_hotword_model_in.csv", "speech_hotword_model_out_rank2.csv"); } } // namespace models } // namespace tflite <commit_msg>Update the comment in speech_hotword_model_test.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Unit test for speech Hotword model using TFLite Ops. #include <string.h> #include <memory> #include <string> #include "base/logging.h" #include "testing/base/public/googletest.h" #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "tensorflow/contrib/lite/context.h" #include "tensorflow/contrib/lite/interpreter.h" #include "tensorflow/contrib/lite/kernels/register.h" #include "tensorflow/contrib/lite/model.h" #include "tensorflow/contrib/lite/models/test_utils.h" namespace tflite { namespace models { void RunTest(int model_input_tensor, int svdf_layer_state_tensor, int model_output_tensor, const string& model_name, const string& golden_in_name, const string& golden_out_name) { // Read the model. string tflite_file_path = StrCat(TestDataPath(), "/", model_name); auto model = FlatBufferModel::BuildFromFile(tflite_file_path.c_str()); CHECK(model) << "Failed to read model from file " << tflite_file_path; // Initialize the interpreter. ops::builtin::BuiltinOpResolver builtins; std::unique_ptr<Interpreter> interpreter; InterpreterBuilder(*model, builtins)(&interpreter); CHECK(interpreter != nullptr); interpreter->AllocateTensors(); // Reset the SVDF layer state. memset(interpreter->tensor(svdf_layer_state_tensor)->data.raw, 0, interpreter->tensor(svdf_layer_state_tensor)->bytes); // Load the input frames. Frames input_frames; const string input_file_path = StrCat(TestDataPath(), "/", golden_in_name); ReadFrames(input_file_path, &input_frames); // Load the golden output results. Frames output_frames; const string output_file_path = StrCat(TestDataPath(), "/", golden_out_name); ReadFrames(output_file_path, &output_frames); const int speech_batch_size = interpreter->tensor(model_input_tensor)->dims->data[0]; const int speech_input_size = interpreter->tensor(model_input_tensor)->dims->data[1]; const int speech_output_size = interpreter->tensor(model_output_tensor)->dims->data[1]; const int input_sequence_size = input_frames[0].size() / (speech_input_size * speech_batch_size); float* input_ptr = interpreter->tensor(model_input_tensor)->data.f; float* output_ptr = interpreter->tensor(model_output_tensor)->data.f; // The first layer (SVDF) input size is 40 (speech_input_size). Each speech // input frames for this model is 1600 floats, which can be fed to input in a // sequence of size 40 (input_sequence_size). for (int i = 0; i < TestInputSize(input_frames); i++) { int frame_ptr = 0; for (int s = 0; s < input_sequence_size; s++) { for (int k = 0; k < speech_input_size * speech_batch_size; k++) { input_ptr[k] = input_frames[i][frame_ptr++]; } interpreter->Invoke(); } // After the whole frame (1280 floats) is fed, we can check the output frame // matches with the golden output frame. for (int k = 0; k < speech_output_size; k++) { ASSERT_NEAR(output_ptr[k], output_frames[i][k], 1e-5); } } } TEST(SpeechHotword, OkGoogleTestRank1) { constexpr int kModelInputTensor = 0; constexpr int kSvdfLayerStateTensor = 4; constexpr int kModelOutputTensor = 18; RunTest(kModelInputTensor, kSvdfLayerStateTensor, kModelOutputTensor, "speech_hotword_model_rank1.tflite", "speech_hotword_model_in.csv", "speech_hotword_model_out_rank1.csv"); } TEST(SpeechHotword, OkGoogleTestRank2) { constexpr int kModelInputTensor = 17; constexpr int kSvdfLayerStateTensor = 1; constexpr int kModelOutputTensor = 18; RunTest(kModelInputTensor, kSvdfLayerStateTensor, kModelOutputTensor, "speech_hotword_model_rank2.tflite", "speech_hotword_model_in.csv", "speech_hotword_model_out_rank2.csv"); } } // namespace models } // namespace tflite <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012-2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "ai.h" #include "IECore/VectorTypedData.h" #include "IECore/SimpleTypedData.h" #include "IECore/Primitive.h" #include "IECore/MessageHandler.h" #include "IECoreArnold/ParameterAlgo.h" #include "IECoreArnold/ShapeAlgo.h" using namespace std; using namespace IECore; using namespace IECoreArnold; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { AtArray *identityIndices( size_t size ) { AtArray *result = AiArrayAllocate( size, 1, AI_TYPE_UINT ); for( size_t i=0; i < size; ++i ) { AiArraySetInt( result, i, i ); } return result; } ConstFloatVectorDataPtr radius( const Primitive *primitive ) { if( ConstFloatVectorDataPtr radius = primitive->variableData<FloatVectorData>( "radius" ) ) { return radius; } FloatVectorDataPtr calculatedRadius = new FloatVectorData(); if( const FloatData *constantRadius = primitive->variableData<FloatData>( "radius", PrimitiveVariable::Constant ) ) { calculatedRadius->writable().push_back( constantRadius->readable() ); } else if( const FloatVectorData *width = primitive->variableData<FloatVectorData>( "width" ) ) { calculatedRadius->writable().resize( width->readable().size() ); const std::vector<float>::iterator end = calculatedRadius->writable().end(); std::vector<float>::const_iterator wIt = width->readable().begin(); for( std::vector<float>::iterator it = calculatedRadius->writable().begin(); it != end; it++, wIt++ ) { *it = *wIt / 2.0f; } } else { const FloatData *constantWidth = primitive->variableData<FloatData>( "width", PrimitiveVariable::Constant ); if( !constantWidth ) { constantWidth = primitive->variableData<FloatData>( "constantwidth", PrimitiveVariable::Constant ); } float r = constantWidth ? constantWidth->readable() / 2.0f : 0.5f; calculatedRadius->writable().push_back( r ); } return calculatedRadius; } } // namespace ////////////////////////////////////////////////////////////////////////// // Implementation of public API. ////////////////////////////////////////////////////////////////////////// namespace IECoreArnold { namespace ShapeAlgo { void convertP( const IECore::Primitive *primitive, AtNode *shape, const char *name ) { const V3fVectorData *p = primitive->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "Primitive does not have \"P\" primitive variable of interpolation type Vertex." ); } AiNodeSetArray( shape, name, AiArrayConvert( p->readable().size(), 1, AI_TYPE_POINT, (void *)&( p->readable()[0] ) ) ); } void convertP( const std::vector<const IECore::Primitive *> &samples, AtNode *shape, const char *name ) { vector<const Data *> dataSamples; dataSamples.reserve( samples.size() ); for( vector<const Primitive *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it ) { const V3fVectorData *p = (*it)->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "Primitive does not have \"P\" primitive variable of interpolation type Vertex." ); } dataSamples.push_back( p ); } AtArray *array = ParameterAlgo::dataToArray( dataSamples, AI_TYPE_POINT ); AiNodeSetArray( shape, name, array ); } void convertRadius( const IECore::Primitive *primitive, AtNode *shape ) { ConstFloatVectorDataPtr r = radius( primitive ); AiNodeSetArray( shape, "radius", AiArrayConvert( r->readable().size(), 1, AI_TYPE_FLOAT, (void *)&( r->readable()[0] ) ) ); } void convertRadius( const std::vector<const IECore::Primitive *> &samples, AtNode *shape ) { vector<ConstFloatVectorDataPtr> radiusSamples; // for ownership vector<const Data *> dataSamples; // for passing to dataToArray() radiusSamples.reserve( samples.size() ); dataSamples.reserve( samples.size() ); for( vector<const Primitive *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it ) { ConstFloatVectorDataPtr r = radius( *it ); radiusSamples.push_back( r ); dataSamples.push_back( r.get() ); } AtArray *array = ParameterAlgo::dataToArray( dataSamples, AI_TYPE_FLOAT ); AiNodeSetArray( shape, "radius", array ); } void convertPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primitiveVariable, AtNode *shape, const char *name ) { if( primitiveVariable.interpolation == PrimitiveVariable::Constant ) { ParameterAlgo::setParameter( shape, name, primitiveVariable.data.get() ); } else { bool isArray = false; int type = ParameterAlgo::parameterType( primitiveVariable.data->typeId(), isArray ); if( type == AI_TYPE_NONE || !isArray ) { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Unable to create user parameter \"%s\" for primitive variable of type \"%s\"" ) % name % primitiveVariable.data->typeName() ); return; } std::string typeString; if( primitiveVariable.interpolation == PrimitiveVariable::Uniform ) { typeString = "uniform "; } else if( primitiveVariable.interpolation == PrimitiveVariable::Vertex ) { typeString = "varying "; } else if( primitive->variableSize( primitiveVariable.interpolation ) == primitive->variableSize( PrimitiveVariable::Vertex ) ) { typeString = "varying "; } else if( primitiveVariable.interpolation == PrimitiveVariable::FaceVarying ) { typeString = "indexed "; } if( typeString == "" ) { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Unable to create user parameter \"%s\" because primitive variable has unsupported interpolation" ) % name ); return; } typeString += AiParamGetTypeName( type ); AiNodeDeclare( shape, name, typeString.c_str() ); AtArray *array = ParameterAlgo::dataToArray( primitiveVariable.data.get() ); if( array ) { AiNodeSetArray( shape, name, array ); if( primitiveVariable.interpolation == PrimitiveVariable::FaceVarying ) { AiNodeSetArray( shape, (name + string("idxs")).c_str(), identityIndices( array->nelements ) ); } } else { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Failed to create array for parameter \"%s\" from data of type \"%s\"" ) % name % primitiveVariable.data->typeName() ); } } } void convertPrimitiveVariables( const IECore::Primitive *primitive, AtNode *shape, const char **namesToIgnore ) { for( PrimitiveVariableMap::const_iterator it = primitive->variables.begin(), eIt = primitive->variables.end(); it!=eIt; it++ ) { if( namesToIgnore ) { bool skip = false; for( const char **n = namesToIgnore; *n; n++ ) { if( it->first == *n ) { skip = true; break; } } if( skip ) { continue; } } // we prefix all the names, as otherwise the chance of a conflict between // an arbitrary primitive variable name and an existing arnold parameter name // seems too great. string prefixedName = "user:" + it->first; convertPrimitiveVariable( primitive, it->second, shape, prefixedName.c_str() ); } } } // namespace ShapeAlgo } // namespace IECoreArnold <commit_msg>IECoreArnold::ShapeAlgo : Refactor for clarity.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012-2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "ai.h" #include "IECore/VectorTypedData.h" #include "IECore/SimpleTypedData.h" #include "IECore/Primitive.h" #include "IECore/MessageHandler.h" #include "IECoreArnold/ParameterAlgo.h" #include "IECoreArnold/ShapeAlgo.h" using namespace std; using namespace IECore; using namespace IECoreArnold; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { AtArray *identityIndices( size_t size ) { AtArray *result = AiArrayAllocate( size, 1, AI_TYPE_UINT ); for( size_t i=0; i < size; ++i ) { AiArraySetInt( result, i, i ); } return result; } ConstFloatVectorDataPtr radius( const Primitive *primitive ) { if( ConstFloatVectorDataPtr radius = primitive->variableData<FloatVectorData>( "radius" ) ) { return radius; } FloatVectorDataPtr calculatedRadius = new FloatVectorData(); if( const FloatData *constantRadius = primitive->variableData<FloatData>( "radius", PrimitiveVariable::Constant ) ) { calculatedRadius->writable().push_back( constantRadius->readable() ); } else if( const FloatVectorData *width = primitive->variableData<FloatVectorData>( "width" ) ) { calculatedRadius->writable().resize( width->readable().size() ); const std::vector<float>::iterator end = calculatedRadius->writable().end(); std::vector<float>::const_iterator wIt = width->readable().begin(); for( std::vector<float>::iterator it = calculatedRadius->writable().begin(); it != end; it++, wIt++ ) { *it = *wIt / 2.0f; } } else { const FloatData *constantWidth = primitive->variableData<FloatData>( "width", PrimitiveVariable::Constant ); if( !constantWidth ) { constantWidth = primitive->variableData<FloatData>( "constantwidth", PrimitiveVariable::Constant ); } float r = constantWidth ? constantWidth->readable() / 2.0f : 0.5f; calculatedRadius->writable().push_back( r ); } return calculatedRadius; } } // namespace ////////////////////////////////////////////////////////////////////////// // Implementation of public API. ////////////////////////////////////////////////////////////////////////// namespace IECoreArnold { namespace ShapeAlgo { void convertP( const IECore::Primitive *primitive, AtNode *shape, const char *name ) { const V3fVectorData *p = primitive->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "Primitive does not have \"P\" primitive variable of interpolation type Vertex." ); } AiNodeSetArray( shape, name, AiArrayConvert( p->readable().size(), 1, AI_TYPE_POINT, (void *)&( p->readable()[0] ) ) ); } void convertP( const std::vector<const IECore::Primitive *> &samples, AtNode *shape, const char *name ) { vector<const Data *> dataSamples; dataSamples.reserve( samples.size() ); for( vector<const Primitive *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it ) { const V3fVectorData *p = (*it)->variableData<V3fVectorData>( "P", PrimitiveVariable::Vertex ); if( !p ) { throw Exception( "Primitive does not have \"P\" primitive variable of interpolation type Vertex." ); } dataSamples.push_back( p ); } AtArray *array = ParameterAlgo::dataToArray( dataSamples, AI_TYPE_POINT ); AiNodeSetArray( shape, name, array ); } void convertRadius( const IECore::Primitive *primitive, AtNode *shape ) { ConstFloatVectorDataPtr r = radius( primitive ); AiNodeSetArray( shape, "radius", AiArrayConvert( r->readable().size(), 1, AI_TYPE_FLOAT, (void *)&( r->readable()[0] ) ) ); } void convertRadius( const std::vector<const IECore::Primitive *> &samples, AtNode *shape ) { vector<ConstFloatVectorDataPtr> radiusSamples; // for ownership vector<const Data *> dataSamples; // for passing to dataToArray() radiusSamples.reserve( samples.size() ); dataSamples.reserve( samples.size() ); for( vector<const Primitive *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it ) { ConstFloatVectorDataPtr r = radius( *it ); radiusSamples.push_back( r ); dataSamples.push_back( r.get() ); } AtArray *array = ParameterAlgo::dataToArray( dataSamples, AI_TYPE_FLOAT ); AiNodeSetArray( shape, "radius", array ); } void convertPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primitiveVariable, AtNode *shape, const char *name ) { // Deal with the simple case of constant data. if( primitiveVariable.interpolation == PrimitiveVariable::Constant ) { ParameterAlgo::setParameter( shape, name, primitiveVariable.data.get() ); return; } // Now deal with more complex cases with array data. bool isArray = false; int type = ParameterAlgo::parameterType( primitiveVariable.data->typeId(), isArray ); if( type == AI_TYPE_NONE || !isArray ) { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Unable to create user parameter \"%s\" for primitive variable of type \"%s\"" ) % name % primitiveVariable.data->typeName() ); return; } std::string typeString; if( primitiveVariable.interpolation == PrimitiveVariable::Uniform ) { typeString = "uniform "; } else if( primitiveVariable.interpolation == PrimitiveVariable::Vertex ) { typeString = "varying "; } else if( primitive->variableSize( primitiveVariable.interpolation ) == primitive->variableSize( PrimitiveVariable::Vertex ) ) { typeString = "varying "; } else if( primitiveVariable.interpolation == PrimitiveVariable::FaceVarying ) { typeString = "indexed "; } if( typeString == "" ) { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Unable to create user parameter \"%s\" because primitive variable has unsupported interpolation" ) % name ); return; } typeString += AiParamGetTypeName( type ); AiNodeDeclare( shape, name, typeString.c_str() ); AtArray *array = ParameterAlgo::dataToArray( primitiveVariable.data.get() ); if( array ) { AiNodeSetArray( shape, name, array ); if( primitiveVariable.interpolation == PrimitiveVariable::FaceVarying ) { AiNodeSetArray( shape, (name + string("idxs")).c_str(), identityIndices( array->nelements ) ); } } else { msg( Msg::Warning, "ToArnoldShapeConverter::convertPrimitiveVariable", boost::format( "Failed to create array for parameter \"%s\" from data of type \"%s\"" ) % name % primitiveVariable.data->typeName() ); } } void convertPrimitiveVariables( const IECore::Primitive *primitive, AtNode *shape, const char **namesToIgnore ) { for( PrimitiveVariableMap::const_iterator it = primitive->variables.begin(), eIt = primitive->variables.end(); it!=eIt; it++ ) { if( namesToIgnore ) { bool skip = false; for( const char **n = namesToIgnore; *n; n++ ) { if( it->first == *n ) { skip = true; break; } } if( skip ) { continue; } } // we prefix all the names, as otherwise the chance of a conflict between // an arbitrary primitive variable name and an existing arnold parameter name // seems too great. string prefixedName = "user:" + it->first; convertPrimitiveVariable( primitive, it->second, shape, prefixedName.c_str() ); } } } // namespace ShapeAlgo } // namespace IECoreArnold <|endoftext|>
<commit_before>#ifndef GUARD_signature_hpp #define GUARD_signature_hpp #include <boost/noncopyable.hpp> namespace jewel { /** * The instantiation of this template for a class T is a * non-copyable class the constructor of which is only * accessible by * class T. This provides a mechanism whereby a * function that wants to ensure at compile time * that it can only be called by class T, can achieve * this simply by having a * parameter of type Signature<T>& (or Signature<T> const&). * This provides a fine-grained, function-level means of * access control, that is not directly provided by * the \e friend mechanism. */ template <class T> class Signature: private boost::noncopyable { public: friend T; private: Signature(); }; template <class T> inline Signature<T>::Signature() { } } // namespace jewel #endif // GUARD_signature_hpp <commit_msg>Added note re. jewel::Signature being strictly non-conformant pre-C++11.<commit_after>#ifndef GUARD_signature_hpp #define GUARD_signature_hpp #include <boost/noncopyable.hpp> namespace jewel { /** * The instantiation of this template for a class T is a * non-copyable class the constructor of which is only * accessible by * class T. This provides a mechanism whereby a * function that wants to ensure at compile time * that it can only be called by class T, can achieve * this simply by having a * parameter of type Signature<T>& (or Signature<T> const&). * This provides a fine-grained, function-level means of * access control, that is not directly provided by * the \e friend mechanism. */ template <class T> class Signature: private boost::noncopyable { public: // WARNING this is non-conformant prior to C++11; although // some C++98 compilers neverthless allow it. friend T; private: Signature(); }; template <class T> inline Signature<T>::Signature() { } } // namespace jewel #endif // GUARD_signature_hpp <|endoftext|>
<commit_before>// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 <sstream> #include "app/canvas.hh" #include "formats/format.hh" #include "formats/gif/file-gif.hh" #include "text/formatting.hh" #include "util/image.hh" #include "util/image-util.hh" #include "util/index-iter.hh" #include "util/frame-iter.hh" #include "util/make-vector.hh" namespace faint{ static size_t find_mismatch_index(const std::vector<IntSize>& sizes){ assert(!sizes.empty()); size_t i = 1; for (; i != sizes.size(); i++){ if (sizes[i] != sizes[0]){ break; } } return i; } static bool uniform_size(const std::vector<IntSize>& sizes){ return find_mismatch_index(sizes) == sizes.size(); } static SaveResult fail_size_mismatch(const std::vector<IntSize>& sizes){ size_t index = find_mismatch_index(sizes); assert(index != sizes.size()); std::stringstream ss; ss << "This image can not be saved as a gif." << std::endl << std::endl << "It contains frames of different sizes." << std::endl << "Frame 1: " << str(sizes[0]) << std::endl << "Frame " << index + 1 << ": " << str(sizes[index]); return SaveResult::SaveFailed(utf8_string(ss.str())); } static std::vector<IntSize> get_frame_sizes(Canvas& canvas){ const auto get_size = [](const auto& frame){return frame.GetSize();}; return make_vector(canvas, get_size); } class FormatGIF : public Format { public: FormatGIF() : Format(FileExtension("gif"), label_t(utf8_string("Graphics Interchange Format (GIF)")), can_save(true), can_load(true)) {} void Load(const FilePath& filePath, ImageProps& imageProps) override{ read_gif(filePath, imageProps); } SaveResult Save(const FilePath& filePath, Canvas& canvas) override{ // Verify that all frames have the same size std::vector<IntSize> sizes = get_frame_sizes(canvas); if (!uniform_size(sizes)){ return fail_size_mismatch(sizes); } // Flatten and quantize std::vector<MappedColors_and_delay> images; for (const auto& f : canvas){ // Fixme: Consider using the same palette for multiple frames images.emplace_back(quantized(flatten(f), Dithering::ON), f.GetDelay()); } return write_gif(filePath, images); } }; Format* format_gif(){ return new FormatGIF(); } } // namespace <commit_msg>Using <algorithms> some more.<commit_after>// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 <algorithm> #include <sstream> #include "app/canvas.hh" #include "formats/format.hh" #include "formats/gif/file-gif.hh" #include "text/formatting.hh" #include "util/image.hh" #include "util/image-util.hh" #include "util/index-iter.hh" #include "util/frame-iter.hh" #include "util/make-vector.hh" namespace faint{ static auto find_mismatch(const std::vector<IntSize>& sizes){ const auto not_equal = [first = sizes.front()](const auto& sz){ return sz != first;}; return std::find_if(sizes.begin(), sizes.end(), not_equal); } static bool uniform_size(const std::vector<IntSize>& sizes){ return find_mismatch(sizes) == sizes.end(); } static SaveResult fail_size_mismatch(const std::vector<IntSize>& sizes){ size_t index = std::distance(begin(sizes), find_mismatch(sizes)); assert(index != sizes.size()); std::stringstream ss; ss << "This image can not be saved as a gif." << std::endl << std::endl << "It contains frames of different sizes." << std::endl << "Frame 1: " << str(sizes[0]) << std::endl << "Frame " << index + 1 << ": " << str(sizes[index]); return SaveResult::SaveFailed(utf8_string(ss.str())); } static std::vector<IntSize> get_frame_sizes(Canvas& canvas){ const auto get_size = [](const auto& frame){return frame.GetSize();}; return make_vector(canvas, get_size); } class FormatGIF : public Format { public: FormatGIF() : Format(FileExtension("gif"), label_t(utf8_string("Graphics Interchange Format (GIF)")), can_save(true), can_load(true)) {} void Load(const FilePath& filePath, ImageProps& imageProps) override{ read_gif(filePath, imageProps); } SaveResult Save(const FilePath& filePath, Canvas& canvas) override{ // Verify that all frames have the same size auto sizes = get_frame_sizes(canvas); if (!uniform_size(sizes)){ return fail_size_mismatch(sizes); } // Flatten and quantize std::vector<MappedColors_and_delay> images; for (const auto& f : canvas){ // Fixme: Consider using the same palette for multiple frames images.emplace_back(quantized(flatten(f), Dithering::ON), f.GetDelay()); } return write_gif(filePath, images); } }; Format* format_gif(){ return new FormatGIF(); } } // namespace <|endoftext|>
<commit_before>// // video_manager.cpp // emptyExample // // Created by Mark van de Korput on 16-05-03. // // #include "video_manager.hpp" #include "xml_settings.hpp" using namespace of2030; SINGLETON_INLINE_IMPLEMENTATION_CODE(VideoManager) VideoManager::VideoManager(){ #ifdef __APPLE__ folder_path = "vids/_osx/"; #else folder_path = "vids/_raspi/"; #endif // __APPLE__ } void VideoManager::destroy(){ // don't iterate like normal, because the iterator gets corrupted and causes // BAD ACCESS errors when the map gets modified during its iterations // we'll just take the first item every time and remove it, until there's nothing left while(!players.empty()){ unload(players.begin()->first); } players.clear(); } //void VideoManager::setup(){ // //} void VideoManager::update(){ for(auto& pair: players){ pair.second->update(); } } ofVideoPlayer* VideoManager::get(const string &video_name, bool load){ // assume alias IS the video's path return get(video_name, video_name, load); } ofVideoPlayer* VideoManager::get(const string &video_name, const string &alias, bool load){ std::map<string,ofVideoPlayer*>::iterator it = players.find(alias); // found it if(it != players.end()){ return it->second; } // not found, no loading if(!load) return NULL; // (try to) create a player ofVideoPlayer* player = createPlayer(video_name); // store it if(player){ ofLog() << alias << " loaded."; players[alias] = player; } // return it return player; } bool VideoManager::unload(const string &alias){ ofLog() << "VideoManager::unload with " << alias; // No specific player specified? destroy all if(alias == ""){ destroy(); return true; } // find specified player std::map<string,ofVideoPlayer*>::iterator it = players.find(alias); // not found, abort if(it == players.end()){ ofLogWarning() << "VideoManager::unload player not found"; return false; } ofNotifyEvent(unloadEvent, *it->second, this); // remove from our list players.erase(it); if(it->second){ // close player/video file it->second->close(); // delete instance from memory delete it->second; } // log and report ofLog() << "Video players still loaded: " << players.size(); return true; } void VideoManager::unload(ofVideoPlayer *player){ if(player == NULL){ return; } // find player for (auto& pair: players) { // this one? if(pair.second == player){ unload(pair.first); } } } ofVideoPlayer* VideoManager::createPlayer(const string &video_name){ string path = video_name_to_path(video_name); ofLog() << "VideoManager::createPlayer loading: " << path; //player->getMoviePath(); if(!ofFile::doesFileExist(path)){ ofLogWarning() << "could not find video file."; return NULL; } ofVideoPlayer *player = new ofVideoPlayer; if(XmlSettings::instance()->rgbaVidPixels){ player->setPixelFormat(OF_PIXELS_RGBA); } player->loadAsync(path); player->setVolume(0.0f); return player; } <commit_msg>video manager minor tweak<commit_after>// // video_manager.cpp // emptyExample // // Created by Mark van de Korput on 16-05-03. // // #include "video_manager.hpp" #include "xml_settings.hpp" using namespace of2030; SINGLETON_INLINE_IMPLEMENTATION_CODE(VideoManager) VideoManager::VideoManager(){ #ifdef __APPLE__ folder_path = "vids/_osx/"; #else folder_path = "vids/_raspi/"; #endif // __APPLE__ } void VideoManager::destroy(){ // don't iterate like normal, because the iterator gets corrupted and causes // BAD ACCESS errors when the map gets modified during its iterations // we'll just take the first item every time and remove it, until there's nothing left while(!players.empty()){ unload(players.begin()->first); } players.clear(); } //void VideoManager::setup(){ // //} void VideoManager::update(){ for(auto& pair: players){ pair.second->update(); } } ofVideoPlayer* VideoManager::get(const string &video_name, bool load){ // assume alias IS the video's path return get(video_name, video_name, load); } ofVideoPlayer* VideoManager::get(const string &video_name, const string &alias, bool load){ std::map<string,ofVideoPlayer*>::iterator it = players.find(alias); // found it if(it != players.end()){ return it->second; } // not found, no loading if(!load) return NULL; // (try to) create a player ofVideoPlayer* player = createPlayer(video_name); // store it if(player){ ofLog() << alias << " loaded."; players[alias] = player; } // return it return player; } bool VideoManager::unload(const string &alias){ ofLog() << "VideoManager::unload with " << alias; // No specific player specified? destroy all if(alias == ""){ destroy(); return true; } // find specified player std::map<string,ofVideoPlayer*>::iterator it = players.find(alias); // not found, abort if(it == players.end()){ ofLogWarning() << "VideoManager::unload player not found"; return false; } ofNotifyEvent(unloadEvent, *it->second, this); if(it->second){ // close player/video file it->second->close(); // delete instance from memory delete it->second; } // remove from our list players.erase(it); // log and report ofLog() << "Video players still loaded: " << players.size(); return true; } void VideoManager::unload(ofVideoPlayer *player){ if(player == NULL){ return; } // find player for (auto& pair: players) { // this one? if(pair.second == player){ unload(pair.first); } } } ofVideoPlayer* VideoManager::createPlayer(const string &video_name){ string path = video_name_to_path(video_name); ofLog() << "VideoManager::createPlayer loading: " << path; //player->getMoviePath(); if(!ofFile::doesFileExist(path)){ ofLogWarning() << "could not find video file."; return NULL; } ofVideoPlayer *player = new ofVideoPlayer; if(XmlSettings::instance()->rgbaVidPixels){ player->setPixelFormat(OF_PIXELS_RGBA); } player->loadAsync(path); player->setVolume(0.0f); return player; } <|endoftext|>
<commit_before>/** * Copyright (c) Jason White * * MIT License * * Description: * Removes comments and unnecessary whitespace from a Lua file. This is useful * for embedding Lua scripts into an executable. */ #include <stdio.h> #include <string.h> #include <ctype.h> const char* read_file(FILE* f, size_t* len) { // Find the length of the file fseek(f, 0, SEEK_END); *len = (size_t)ftell(f); if (fseek(f, 0, SEEK_SET) != 0) { return NULL; } char* buf = new char[*len]; if (!buf || fread(buf, 1, *len, f) != *len) { return NULL; } return (const char*)buf; } size_t skip_block_comment(const char* buf, size_t len) { size_t i = 0; if (len >= 4 && strncmp(buf, "--[[", 4) == 0) { i += 4; while (i < (len - 2)) { if (strncmp(buf+i, "]]", 2) == 0) { i += 2; return i; } ++i; } } return i; } enum StringType { STRING_NONE, STRING_BLOCK, STRING_SINGLE, STRING_DOUBLE, }; size_t skip_string(const char* buf, size_t len) { size_t i = 0; StringType t = STRING_NONE; if (i < len) { switch (buf[i]) { case '"': t = STRING_DOUBLE; i += 1; break; case '\'': t = STRING_SINGLE; i += 1; break; case '[': if ((len-i) >= 2 && buf[i+1] == '[') { t = STRING_BLOCK; i += 2; break; } return 0; default: return 0; } } while (i < len) { switch (buf[i]) { case '"': if (t == STRING_DOUBLE && buf[i-1] != '\\') return i+1; break; case '\'': if (t == STRING_SINGLE && buf[i-1] != '\\') return i+1; break; case ']': if (t == STRING_BLOCK && buf[i-1] != '\\' && (len-i) > 0 && buf[i+1] == ']') return i+2; break; } ++i; } if (i > 0) fwrite(buf, 1, i, stdout); return i; } size_t skip_line_comment(const char* buf, size_t len) { size_t i = 0; if (len >= 2 && strncmp(buf, "--", 2) == 0) { i += 2; while (i < len && buf[i] != '\n') ++i; if (buf[i-1] == '\n') --i; } return i; } size_t skip_trailing_spaces(const char* buf, size_t len) { size_t i = 0; // Replace \s*\n with \n while (i < len && isblank(buf[i])) ++i; if (i < len && buf[i] == '\n') return i; return 0; } size_t skip_whitespace(const char* buf, size_t len) { size_t i = 0; // Replace \n\s* with \n if (len > 0 && buf[i] == '\n') { ++i; while (i < len && isspace(buf[i])) ++i; putchar('\n'); } return i; } void minify(const char* buf, size_t len) { size_t delta = 0; for (size_t i = 0; i < len; ) { while (true) { delta = 0; delta += skip_block_comment(buf+i+delta, len-i-delta); delta += skip_line_comment(buf+i+delta, len-i-delta); delta += skip_trailing_spaces(buf+i+delta, len-i-delta); delta += skip_whitespace(buf+i+delta, len-i-delta); delta += skip_string(buf+i+delta, len-i-delta); // As long as we can keep doing work, keep going. if (delta > 0) { i += delta; continue; } break; } putchar(buf[i]); ++i; } } int main(int argc, char** argv) { if (argc <= 1) { puts("Usage: luamin FILE"); return 1; } FILE* f = fopen(argv[1], "rb"); if (!f) { perror("failed to open file"); return 1; } size_t len; const char* buf = read_file(f, &len); fclose(f); if (!buf) { perror("failed to read file"); return 1; } minify(buf, len); return 0; } <commit_msg>Remove unused luaminify tool<commit_after><|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../../../core/Setup.h" #if defined(__ANDROID__) && OUZEL_COMPILE_OPENGL #include "OGLRenderDeviceAndroid.hpp" #include "../EGLErrorCategory.hpp" #include "../../../core/Engine.hpp" #include "../../../core/Window.hpp" #include "../../../core/android/NativeWindowAndroid.hpp" #include "../../../utils/Log.hpp" namespace ouzel::graphics::opengl::android { namespace { const egl::ErrorCategory eglErrorCategory{}; } RenderDevice::RenderDevice(const Settings& settings, core::Window& initWindow, const std::function<void(const Event&)>& initCallback): opengl::RenderDevice(settings, initWindow, initCallback) { embedded = true; display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (display == EGL_NO_DISPLAY) throw std::runtime_error("Failed to get display"); if (!eglInitialize(display, nullptr, nullptr)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to initialize EGL"); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, settings.depth ? 24 : 0, EGL_STENCIL_SIZE, settings.stencil ? 8 : 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (settings.sampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(settings.sampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); EGLint format; if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get config attribute"); auto windowAndroid = static_cast<core::android::NativeWindow*>(window.getNativeWindow()); ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format); surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { const EGLint contextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, version, EGL_CONTEXT_OPENGL_DEBUG, settings.debugRenderer ? EGL_TRUE : EGL_FALSE, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes); if (context != EGL_NO_CONTEXT) { apiVersion = ApiVersion(version, 0); logger.log(Log::Level::info) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::runtime_error("Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, settings.verticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); EGLint surfaceWidth; EGLint surfaceHeight; if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) || !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get query window size"); init(surfaceWidth, surfaceHeight); if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); running = true; renderThread = Thread(&RenderDevice::renderMain, this); } RenderDevice::~RenderDevice() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); if (context != EGL_NO_CONTEXT) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(display, context); } if (surface != EGL_NO_SURFACE) eglDestroySurface(display, surface); if (display != EGL_NO_DISPLAY) eglTerminate(display); } void RenderDevice::reload() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, depth ? 24 : 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(sampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); EGLint format; if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get config attribute"); auto windowAndroid = static_cast<core::android::NativeWindow*>(window.getNativeWindow()); ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format); surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { const EGLint contextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, version, EGL_CONTEXT_OPENGL_DEBUG, settings.debugRenderer ? EGL_TRUE : EGL_FALSE, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes); if (context != EGL_NO_CONTEXT) { apiVersion = ApiVersion(version, 0); logger.log(Log::Level::info) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::runtime_error("Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, verticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); EGLint surfaceWidth; EGLint surfaceHeight; if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) || !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get query window size"); frameBufferWidth = surfaceWidth; frameBufferHeight = surfaceHeight; stateCache = StateCache(); glDisableProc(GL_DITHER); glDepthFuncProc(GL_LEQUAL); GLenum error; if ((error = glGetErrorProc()) != GL_NO_ERROR) throw std::system_error(makeErrorCode(error), "Failed to set depth function"); if (glGenVertexArraysProc) glGenVertexArraysProc(1, &vertexArrayId); for (const auto& resource : resources) if (resource) resource->invalidate(); for (const auto& resource : resources) if (resource) resource->restore(); if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); running = true; renderThread = Thread(&RenderDevice::renderMain, this); } void RenderDevice::destroy() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); if (context) { if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) logger.log(Log::Level::error) << "Failed to unset EGL context"; if (!eglDestroyContext(display, context)) logger.log(Log::Level::error) << "Failed to destroy EGL context"; context = nullptr; } if (surface) { if (!eglDestroySurface(display, surface)) logger.log(Log::Level::error) << "Failed to destroy EGL surface"; surface = nullptr; } } void RenderDevice::present() { if (eglSwapBuffers(display, surface) != EGL_TRUE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to swap buffers"); } void RenderDevice::renderMain() { Thread::setCurrentThreadName("Render"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); while (running) { try { process(); } catch (const std::exception& e) { logger.log(Log::Level::error) << e.what(); } } if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); } } #endif <commit_msg>Fix the Android build<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../../../core/Setup.h" #if defined(__ANDROID__) && OUZEL_COMPILE_OPENGL #include "OGLRenderDeviceAndroid.hpp" #include "../EGLErrorCategory.hpp" #include "../../../core/Engine.hpp" #include "../../../core/Window.hpp" #include "../../../core/android/NativeWindowAndroid.hpp" #include "../../../utils/Log.hpp" namespace ouzel::graphics::opengl::android { namespace { const egl::ErrorCategory eglErrorCategory{}; } RenderDevice::RenderDevice(const Settings& settings, core::Window& initWindow, const std::function<void(const Event&)>& initCallback): opengl::RenderDevice(settings, initWindow, initCallback) { embedded = true; display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (display == EGL_NO_DISPLAY) throw std::runtime_error("Failed to get display"); if (!eglInitialize(display, nullptr, nullptr)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to initialize EGL"); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, settings.depth ? 24 : 0, EGL_STENCIL_SIZE, settings.stencil ? 8 : 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (settings.sampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(settings.sampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); EGLint format; if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get config attribute"); auto windowAndroid = static_cast<core::android::NativeWindow*>(window.getNativeWindow()); ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format); surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { const EGLint contextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, version, EGL_CONTEXT_OPENGL_DEBUG, settings.debugRenderer ? EGL_TRUE : EGL_FALSE, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes); if (context != EGL_NO_CONTEXT) { apiVersion = ApiVersion(version, 0); logger.log(Log::Level::info) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::runtime_error("Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, settings.verticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); EGLint surfaceWidth; EGLint surfaceHeight; if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) || !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get query window size"); init(surfaceWidth, surfaceHeight); if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); running = true; renderThread = Thread(&RenderDevice::renderMain, this); } RenderDevice::~RenderDevice() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); if (context != EGL_NO_CONTEXT) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(display, context); } if (surface != EGL_NO_SURFACE) eglDestroySurface(display, surface); if (display != EGL_NO_DISPLAY) eglTerminate(display); } void RenderDevice::reload() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, depth ? 24 : 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(sampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); EGLint format; if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get config attribute"); auto windowAndroid = static_cast<core::android::NativeWindow*>(window.getNativeWindow()); ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format); surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { const EGLint contextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, version, EGL_CONTEXT_OPENGL_DEBUG, debugRenderer ? EGL_TRUE : EGL_FALSE, EGL_NONE }; context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes); if (context != EGL_NO_CONTEXT) { apiVersion = ApiVersion(version, 0); logger.log(Log::Level::info) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::runtime_error("Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, verticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); EGLint surfaceWidth; EGLint surfaceHeight; if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) || !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get query window size"); frameBufferWidth = surfaceWidth; frameBufferHeight = surfaceHeight; stateCache = StateCache(); glDisableProc(GL_DITHER); glDepthFuncProc(GL_LEQUAL); GLenum error; if ((error = glGetErrorProc()) != GL_NO_ERROR) throw std::system_error(makeErrorCode(error), "Failed to set depth function"); if (glGenVertexArraysProc) glGenVertexArraysProc(1, &vertexArrayId); for (const auto& resource : resources) if (resource) resource->invalidate(); for (const auto& resource : resources) if (resource) resource->restore(); if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); running = true; renderThread = Thread(&RenderDevice::renderMain, this); } void RenderDevice::destroy() { running = false; CommandBuffer commandBuffer; commandBuffer.pushCommand(std::make_unique<PresentCommand>()); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.isJoinable()) renderThread.join(); if (context) { if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) logger.log(Log::Level::error) << "Failed to unset EGL context"; if (!eglDestroyContext(display, context)) logger.log(Log::Level::error) << "Failed to destroy EGL context"; context = nullptr; } if (surface) { if (!eglDestroySurface(display, surface)) logger.log(Log::Level::error) << "Failed to destroy EGL surface"; surface = nullptr; } } void RenderDevice::present() { if (eglSwapBuffers(display, surface) != EGL_TRUE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to swap buffers"); } void RenderDevice::renderMain() { Thread::setCurrentThreadName("Render"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); while (running) { try { process(); } catch (const std::exception& e) { logger.log(Log::Level::error) << e.what(); } } if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GEOMETRY_SVG_GENERATOR_HPP #define MAPNIK_GEOMETRY_SVG_GENERATOR_HPP #define BOOST_SPIRIT_USE_PHOENIX_V3 1 // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> // for container stuff #include <mapnik/ctrans.hpp> // for container stuff #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/type_traits/remove_pointer.hpp> /*! * adapted to conform to the concepts * required by Karma to be recognized as a container of * attributes for output generation. */ namespace boost { namespace spirit { namespace traits { // TODO - this needs to be made generic to any path type typedef mapnik::coord_transform<mapnik::CoordTransform, mapnik::geometry_type> path_type; template <> struct is_container<path_type const> : mpl::true_ {} ; template <> struct container_iterator<path_type const> { typedef mapnik::util::path_iterator<path_type> type; }; template <> struct begin_container<path_type const> { static mapnik::util::path_iterator<path_type> call (path_type const& g) { return mapnik::util::path_iterator<path_type>(g); } }; template <> struct end_container<path_type const> { static mapnik::util::path_iterator<path_type> call (path_type const& g) { return mapnik::util::path_iterator<path_type>(); } }; }}} namespace mapnik { namespace util { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace svg_detail { template <typename Geometry> struct get_type { template <typename T> struct result { typedef int type; }; int operator() (Geometry const& geom) const { return static_cast<int>(geom.type()); } }; template <typename T> struct get_first { typedef T geometry_type; template <typename U> struct result { typedef typename geometry_type::value_type const type; }; typename geometry_type::value_type const operator() (geometry_type const& geom) const { typename geometry_type::value_type coord; geom.rewind(0); boost::get<0>(coord) = geom.vertex(&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; template <typename T> struct coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { return 6u ;} }; } template <typename OutputIterator, typename Geometry> struct svg_generator : karma::grammar<OutputIterator, Geometry const& ()> { typedef Geometry geometry_type; typedef typename boost::remove_pointer<typename geometry_type::value_type>::type coord_type; svg_generator() : svg_generator::base_type(svg) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; svg = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << svg_point [_1 = _first(_val)] ; svg_point = &uint_ << lit("cx=\"") << coordinate << lit("\" cy=\"") << coordinate << lit('\"') ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << svg_path << lit('\"') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << svg_path << lit('\"') ; svg_path %= ((&uint_(mapnik::SEG_MOVETO) << lit("d=\"") << lit('M') | &uint_(mapnik::SEG_LINETO) [_a +=1] << karma::string [if_(_a == 1) [_1 = "L" ] ]) << lit(' ') << coordinate << lit(' ') << coordinate) % lit(' ') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> svg; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, coord_type ()> svg_point; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> svg_path; // phoenix functions phoenix::function<svg_detail::get_type<geometry_type> > _type; phoenix::function<svg_detail::get_first<geometry_type> > _first; // karma::real_generator<double, svg_detail::coordinate_policy<double> > coordinate; }; }} #endif // MAPNIK_GEOMETRY_SVG_GENERATOR_HPP <commit_msg>+ fix grammar to work with phoenix v3 and c++11<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GEOMETRY_SVG_GENERATOR_HPP #define MAPNIK_GEOMETRY_SVG_GENERATOR_HPP #define BOOST_SPIRIT_USE_PHOENIX_V3 1 // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> // for container stuff #include <mapnik/ctrans.hpp> // for container stuff #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/type_traits/remove_pointer.hpp> /*! * adapted to conform to the concepts * required by Karma to be recognized as a container of * attributes for output generation. */ namespace boost { namespace spirit { namespace traits { // TODO - this needs to be made generic to any path type typedef mapnik::coord_transform<mapnik::CoordTransform, mapnik::geometry_type> path_type; template <> struct is_container<path_type const> : mpl::true_ {} ; template <> struct container_iterator<path_type const> { typedef mapnik::util::path_iterator<path_type> type; }; template <> struct begin_container<path_type const> { static mapnik::util::path_iterator<path_type> call (path_type const& g) { return mapnik::util::path_iterator<path_type>(g); } }; template <> struct end_container<path_type const> { static mapnik::util::path_iterator<path_type> call (path_type const& g) { return mapnik::util::path_iterator<path_type>(); } }; }}} namespace mapnik { namespace util { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace svg_detail { template <typename Geometry> struct get_type { template <typename T> struct result { typedef int type; }; int operator() (Geometry const& geom) const { return static_cast<int>(geom.type()); } }; template <typename T> struct get_first { typedef T geometry_type; template <typename U> struct result { typedef typename geometry_type::value_type const type; }; typename geometry_type::value_type const operator() (geometry_type const& geom) const { typename geometry_type::value_type coord; geom.rewind(0); boost::get<0>(coord) = geom.vertex(&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; template <typename T> struct coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { return 6u ;} }; } template <typename OutputIterator, typename Geometry> struct svg_generator : karma::grammar<OutputIterator, Geometry const& ()> { typedef Geometry geometry_type; typedef typename boost::remove_pointer<typename geometry_type::value_type>::type coord_type; svg_generator() : svg_generator::base_type(svg) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; svg = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << svg_point [_1 = _first(_val)] ; svg_point = &uint_ << lit("cx=\"") << coordinate << lit("\" cy=\"") << coordinate << lit('\"') ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << svg_path << lit('\"') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << svg_path << lit('\"') ; svg_path %= ((&uint_(mapnik::SEG_MOVETO) << lit("d=\"") << lit('M') | &uint_(mapnik::SEG_LINETO) [_a +=1] << karma::string [if_(_a == 1) [_1 = "L" ].else_[_1 =""]]) << lit(' ') << coordinate << lit(' ') << coordinate) % lit(' ') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> svg; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, coord_type ()> svg_point; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> svg_path; // phoenix functions phoenix::function<svg_detail::get_type<geometry_type> > _type; phoenix::function<svg_detail::get_first<geometry_type> > _first; // karma::real_generator<double, svg_detail::coordinate_policy<double> > coordinate; }; }} #endif // MAPNIK_GEOMETRY_SVG_GENERATOR_HPP <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <[email protected]> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element #include <glm/glm.hpp> #include <glm/vec3.hpp> Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; Optional_hit temp; std::vector<float> hits; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { if (it == scene_.shapes.begin() || !o.hit) { o.hit = (*it)->intersect(ray, o.distance, o.intersection, o.normal); o.shape = &**it; } else { temp.hit = (*it)->intersect(ray, temp.distance, temp.intersection, temp.normal); temp.shape = &**it; if(o.distance > temp.distance && temp.distance > 0) { o = temp; } } } //std::cout << o.shape->get_name() << std::endl; return o; } Color Renderer::raytrace(Ray const& ray, int depth){ Optional_hit o = intersect(ray); if(o.hit) return shade(ray, o, depth); else return scene_.ambient; } /* Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ //braucht man noch color und recursion depth statt distance? wenn ja woher? Material temp_mat = scene_.material[o.shape->get_material()]; float r = 0, g = 0, b = 0; float red = 0, green = 0, blue = 0; for(std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { //Ray von Schnittpunkt zu Lichtquelle Ray lightray(o.intersection, glm::normalize((*l).get_position())); //Lichtintensität (Skalarprodukt, wird dann mit Reflexionskoeffizient und Helligkeit der Lichtquelle multipliziert) //oder Winkel zwischen Normale und Lichtquelle float tmp = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float angle_n_l = std::max(tmp, 0.0f); float temp_r = 0, temp_g = 0, temp_b = 0; Optional_hit shadow = intersect(lightray); if(!shadow.hit){ /* Reflection ?? //Winkel Kamera/Lichquelle float cam_light_angle = glm::dot(glm::normalize(o.intersection - scene_.cam.get_position()), glm::normalize((*l).get_position() - o.intersection)); //Reflektionswinkel float reflection = cam_light_angle - (2* tmp); //Reflektionsvecktor glm::vec3 reflect_vec((2 * tmp * o.normal.x - (*l).get_position().x), (2 * tmp * o.normal.y - (*l).get_position().y), (2 * tmp * o.normal.z - (*l).get_position().z)); //Ray reflection_ray(o.intersection, reflect_vec); //oder Ray reflection_ray = reflect_ray(o.intersection, o.normale, l.get_position()); ? Ray reflection_ray = reflect_ray(o.intersection, o.normal, (*l).get_position()); temp_r = temp_mat.get_ks().r; //* pow(reflection, m); temp_g = temp_mat.get_ks().g; //* pow(reflection, m); temp_b = temp_mat.get_ks().b; //* pow(reflection, m); //...... r += (*l).get_diffuse().r * (angle_n_l * temp_mat.get_kd().r + temp_mat.get_ks().r); g += (*l).get_diffuse().g * (angle_n_l * temp_mat.get_kd().g + temp_mat.get_ks().g); b += (*l).get_diffuse().b * (angle_n_l * temp_mat.get_kd().b + temp_mat.get_ks().b); } else{ //Wenn im Schatten werden die Werde berechnet, sonst 0 ( Operator shadow.hit ? 1 : 0) r += temp_mat.get_kd().r * (*l).get_diffuse().r * angle_n_l; g += temp_mat.get_kd().g * (*l).get_diffuse().g * angle_n_l; b += temp_mat.get_kd().b * (*l).get_diffuse().b * angle_n_l; } } //mit Ambiente red = temp_mat.get_ka().r * scene_.ambient.r + r; green = temp_mat.get_ka().g * scene_.ambient.g + g; blue = temp_mat.get_ka().b * scene_.ambient.b + b; return Color(red, green, blue); }*/ Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ Color color; // Farbe des Strahls Ray rRay, tRay, sRay; // Reflexions-, Brechungs- und Schattenstrahlen Color rColor, tColor; // Farbe des reflektierten und gebrochenen Strahls Material temp_mat = scene_.material[o.shape->get_material()]; // Material des geschnittenen Shapes for (std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { sRay = Ray(o.intersection, glm::normalize((*l).get_position())); //Teste ob Skalarprodukt von Normalen und sRay.direction positiv ist if(glm::dot(o.normal, sRay.direction) > 0){ // Wieviel Licht wird von opaken und transparenten Flächen blockiert? Optional_hit shadow= intersect(sRay); float shading = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float shading_pos = std::max(shading, 0.0f); if (!shadow.hit) { color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos) + temp_mat.get_ks()); } else{ //Wenn im Schatten color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos)); } } } if (depth <= 3)//3 = Max depth, { if (temp_mat.get_m() != 0)//Objekt reflektiert(spiegelt) { //Reflektionsray mit Reflektionsrichtung (ist der Einfallsvektor = Schnittpunkt?) rRay = reflect_ray(o.intersection, o.normal, o.intersection); rColor = raytrace(rRay, depth + 1); rColor *= temp_mat.get_m(); //rColor *= temp_mat.get_ks(); color += rColor; } /* if (temp_mat.get_opacity() != 0)//Objekt transparent(mit Refraktion) { //Ray in Brechungsrichtung tRay = Ray (o.intersection, (o.intersection + o.intersection * temp_mat.get_refract())); if(temp_mat.get_m() != 1) tColor = raytrace(tRay, depth + 1); tColor *= temp_mat.get_opacity(); color += tColor; }*/ } //ambiente Beleuchtung color += temp_mat.get_ka() * scene_.ambient; return color; } void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobjekt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); //Pixel für die Rays generieren std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i,1); (*j).color = temp; //std::cout << temp; write(*j); ++j; } ppm_.save(filename_); } Ray Renderer::reflect_ray(glm::vec3 const& intersection, glm::vec3 const& normale, glm::vec3 const& rayDirection) const{ glm::vec3 spiegel{0.0f, 0.0f, 0.0f}; //neuer Ray direction kommt hier rein, origin ist intersection spiegel.x = (2*normale.x*normale.x*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.x*normale.z*rayDirection.z - rayDirection.x); spiegel.y = (2*normale.x*normale.y*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.y*normale.z*rayDirection.z - rayDirection.y); spiegel.z = (2*normale.y*normale.z*rayDirection.x + 2*normale.y*normale.z*rayDirection.y + 2*normale.z*normale.z*rayDirection.z - rayDirection.z); Ray newRay{intersection, spiegel}; //spiegel muss vielleicht *-1 genommen werden, bin mir nicht sicher ob der in die richtige Richtung zeigt return newRay; } <commit_msg>Update shade, transparenz<commit_after>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <[email protected]> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element #include <glm/glm.hpp> #include <glm/vec3.hpp> Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; Optional_hit temp; std::vector<float> hits; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { if (it == scene_.shapes.begin() || !o.hit) { o.hit = (*it)->intersect(ray, o.distance, o.intersection, o.normal); o.shape = &**it; } else { temp.hit = (*it)->intersect(ray, temp.distance, temp.intersection, temp.normal); temp.shape = &**it; if(o.distance > temp.distance && temp.distance > 0) { o = temp; } } } //std::cout << o.shape->get_name() << std::endl; return o; } Color Renderer::raytrace(Ray const& ray, int depth){ Optional_hit o = intersect(ray); if(o.hit) return shade(ray, o, depth); else return scene_.ambient; } /* Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ //braucht man noch color und recursion depth statt distance? wenn ja woher? Material temp_mat = scene_.material[o.shape->get_material()]; float r = 0, g = 0, b = 0; float red = 0, green = 0, blue = 0; for(std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { //Ray von Schnittpunkt zu Lichtquelle Ray lightray(o.intersection, glm::normalize((*l).get_position())); //Lichtintensität (Skalarprodukt, wird dann mit Reflexionskoeffizient und Helligkeit der Lichtquelle multipliziert) //oder Winkel zwischen Normale und Lichtquelle float tmp = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float angle_n_l = std::max(tmp, 0.0f); float temp_r = 0, temp_g = 0, temp_b = 0; Optional_hit shadow = intersect(lightray); if(!shadow.hit){ /* Reflection ?? //Winkel Kamera/Lichquelle float cam_light_angle = glm::dot(glm::normalize(o.intersection - scene_.cam.get_position()), glm::normalize((*l).get_position() - o.intersection)); //Reflektionswinkel float reflection = cam_light_angle - (2* tmp); //Reflektionsvecktor glm::vec3 reflect_vec((2 * tmp * o.normal.x - (*l).get_position().x), (2 * tmp * o.normal.y - (*l).get_position().y), (2 * tmp * o.normal.z - (*l).get_position().z)); //Ray reflection_ray(o.intersection, reflect_vec); //oder Ray reflection_ray = reflect_ray(o.intersection, o.normale, l.get_position()); ? Ray reflection_ray = reflect_ray(o.intersection, o.normal, (*l).get_position()); temp_r = temp_mat.get_ks().r; //* pow(reflection, m); temp_g = temp_mat.get_ks().g; //* pow(reflection, m); temp_b = temp_mat.get_ks().b; //* pow(reflection, m); //...... r += (*l).get_diffuse().r * (angle_n_l * temp_mat.get_kd().r + temp_mat.get_ks().r); g += (*l).get_diffuse().g * (angle_n_l * temp_mat.get_kd().g + temp_mat.get_ks().g); b += (*l).get_diffuse().b * (angle_n_l * temp_mat.get_kd().b + temp_mat.get_ks().b); } else{ //Wenn im Schatten werden die Werde berechnet, sonst 0 ( Operator shadow.hit ? 1 : 0) r += temp_mat.get_kd().r * (*l).get_diffuse().r * angle_n_l; g += temp_mat.get_kd().g * (*l).get_diffuse().g * angle_n_l; b += temp_mat.get_kd().b * (*l).get_diffuse().b * angle_n_l; } } //mit Ambiente red = temp_mat.get_ka().r * scene_.ambient.r + r; green = temp_mat.get_ka().g * scene_.ambient.g + g; blue = temp_mat.get_ka().b * scene_.ambient.b + b; return Color(red, green, blue); }*/ Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ Color color; // Farbe des Strahls Ray rRay, tRay, sRay; // Reflexions-, Brechungs- und Schattenstrahlen Color rColor, tColor; // Farbe des reflektierten und gebrochenen Strahls Material temp_mat = scene_.material[o.shape->get_material()]; // Material des geschnittenen Shapes for (std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { sRay = Ray(o.intersection, glm::normalize((*l).get_position())); //Teste ob Skalarprodukt von Normalen und sRay.direction positiv ist if(glm::dot(o.normal, sRay.direction) > 0){ // Wieviel Licht wird von opaken und transparenten Flächen blockiert? Optional_hit shadow= intersect(sRay); float shading = glm::dot(o.normal, glm::normalize((*l).get_position()) ); float shading_pos = std::max(shading, 0.0f); if (!shadow.hit) { color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos) + temp_mat.get_ks()); } else{ //Wenn im Schatten color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos)); } } } if (depth <= 3)//3 = Max depth, { if (temp_mat.get_m() != 0)//Objekt reflektiert(spiegelt) { //Reflektionsray mit Reflektionsrichtung (ist der Einfallsvektor = Schnittpunkt?) rRay = reflect_ray(o.intersection, o.normal, o.intersection); rColor = raytrace(rRay, depth + 1); rColor *= temp_mat.get_m(); //rColor *= temp_mat.get_ks(); color += rColor; } if (temp_mat.get_opacity() != 0)//Objekt transparent(mit Refraktion) { //Ray in Brechungsrichtung tRay = Ray (o.intersection, (o.intersection + o.intersection * temp_mat.get_refract())); if(temp_mat.get_m() != 1) tColor = raytrace(tRay, depth + 1); tColor *= temp_mat.get_opacity(); color += tColor; } } //ambiente Beleuchtung color += temp_mat.get_ka() * scene_.ambient; return color; } void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobjekt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); //Pixel für die Rays generieren std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i,1); (*j).color = temp; //std::cout << temp; write(*j); ++j; } ppm_.save(filename_); } Ray Renderer::reflect_ray(glm::vec3 const& intersection, glm::vec3 const& normale, glm::vec3 const& rayDirection) const{ glm::vec3 spiegel{0.0f, 0.0f, 0.0f}; //neuer Ray direction kommt hier rein, origin ist intersection spiegel.x = (2*normale.x*normale.x*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.x*normale.z*rayDirection.z - rayDirection.x); spiegel.y = (2*normale.x*normale.y*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.y*normale.z*rayDirection.z - rayDirection.y); spiegel.z = (2*normale.y*normale.z*rayDirection.x + 2*normale.y*normale.z*rayDirection.y + 2*normale.z*normale.z*rayDirection.z - rayDirection.z); Ray newRay{intersection, spiegel}; //spiegel muss vielleicht *-1 genommen werden, bin mir nicht sicher ob der in die richtige Richtung zeigt return newRay; } <|endoftext|>
<commit_before>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; bool DontInternalize; public: InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){ if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else if (!APIList.empty()) // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); else if (!InternalizeEverything) // Finally, if we're allowed to, internalize all but main. DontInternalize = true; } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool runOnModule(Module &M) { if (DontInternalize) return false; // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors"|| I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace ModulePass *llvm::createInternalizePass(bool InternalizeEverything) { return new InternalizePass(InternalizeEverything); } <commit_msg>Wrap a long line, never internalize llvm.used.<commit_after>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; bool DontInternalize; public: InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){ if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else if (!APIList.empty()) // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); else if (!InternalizeEverything) // Finally, if we're allowed to, internalize all but main. DontInternalize = true; } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool runOnModule(Module &M) { if (DontInternalize) return false; // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName()) && // *never* internalize the llvm.used symbol, used to implement // attribute((used)). I->getName() != "llvm.used") { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors"|| I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace ModulePass *llvm::createInternalizePass(bool InternalizeEverything) { return new InternalizePass(InternalizeEverything); } <|endoftext|>
<commit_before>#include <string> #include <cstring> #include <vector> #include "math3d/math3d.h" #include "pbge/pbge.h" #include "Ellipsoids.h" Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx, int total_ellipsoids) { std::vector<pbge::Model*> _models; _models.push_back(pbge::Geometrics::createSphere(1.0f, 10, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 7, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 5, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 4, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 3, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 2, _gfx)); std::vector<float> distances; distances.push_back(10.0f); distances.push_back(20.0f); distances.push_back(35.0f); distances.push_back(60.0f); distances.push_back(100.0f); this->models = new LODModels(_models, distances); this->gfx = _gfx; this->tex = gfx->getFactory()->createTextureBuffer(total_ellipsoids * sizeof(math3d::matrix44)); this->added_ellipsoids = 0; this->render_pass_program = NULL; this->depth_pass_program = NULL; this->peeling_program = NULL; this->transformation_shader = NULL; } PeelingAwareCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms, BoundingBox box) { void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY); memcpy((unsigned char *)texData + this->added_ellipsoids * sizeof(math3d::matrix44), transforms, number_of_ellipsoids * sizeof(math3d::matrix44)); tex->getBuffer()->unmap(); texData = NULL; tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA); PeelingAwareCollection * ellipsoids = new PeelingAwareCollection(models, get_peeling_program()); ellipsoids->setNumberOfInstances(number_of_ellipsoids); pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms"); uniform->setValue(tex); ellipsoids->setTransforms(transforms); pbge::UniformFloat * base_instance = ellipsoids->getUniformSet()->getFloat("base_instance"); base_instance->setValue((float)this->added_ellipsoids); this->added_ellipsoids += number_of_ellipsoids; ellipsoids->setRenderPassProgram(get_render_pass_program()); ellipsoids->setDepthPassProgram(get_depth_pass_program()); ellipsoids->setBoundingBox(box); return ellipsoids; } pbge::Shader * Ellipsoids::get_transformation_shader() { if(this->transformation_shader == NULL) { this->transformation_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform samplerBuffer transforms;\n" "uniform float base_instance;\n" "uniform float scale;\n" "uniform mat4 pbge_ModelViewMatrix;\n" "uniform float alpha_index;\n" "in vec4 pbge_Vertex;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_transform) {\n" " int index = (int(base_instance) + gl_InstanceID) * 4;\n" " vec4 vertex = vec4(pbge_Vertex.xyz * scale, 1.0);\n" " vec4 col1 = texelFetch(transforms, index);\n" " vec4 col2 = texelFetch(transforms, index + 1);\n" " vec4 col3 = texelFetch(transforms, index + 2);\n" " vec4 col4 = texelFetch(transforms, index + 3);\n" " color = vec4(col1.w,col2.w,col3.w,col4.w);\n" " color = vec4(1,1,1,color[int(alpha_index)]);\n" " col1 = vec4(col1.xyz, 0);\n" " col2 = vec4(col2.xyz, 0);\n" " col3 = vec4(col3.xyz, 0);\n" " col4 = vec4(col4.xyz, 1);\n" " mat4 transformation = mat4(col1, col2, col3, col4);\n" " view_transform = pbge_ModelViewMatrix * transformation;\n" " vec4 _normal = inverse(transpose(view_transform)) * pbge_Vertex;\n" " view_normal = normalize(_normal.xyz);\n" " view_position = view_transform * vertex;\n" "}", pbge::Shader::VERTEX_SHADER); } return this->transformation_shader; } pbge::GPUProgram * Ellipsoids::get_render_pass_program() { if(this->render_pass_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " const vec4 light_position = vec4(16,16,16,1);\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " lightPosition = view_transform * light_position;\n" " gl_Position = pbge_ProjectionMatrix * position;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "uniform float min_alpha;\n" "uniform float max_alpha;\n" "uniform vec4 min_color;\n" "uniform vec4 max_color;\n" "in vec4 position;\n" "in vec3 normal;\n" "in vec4 lightPosition;\n" "void main() {\n" " float alpha = gl_Color.a;\n" " if(alpha <= min_alpha - 0.005) discard;\n" " if(alpha >= max_alpha + 0.005) discard;\n" " float rampIndex = (alpha - min_alpha) / max(max_alpha - min_alpha - 0.6,0.1);" " vec4 diffuseColor = mix(min_color, max_color, rampIndex);\n" " vec4 lightDiffuseColor = vec4(2,2,2,2);\n" " vec3 lightDir = normalize((lightPosition - position).xyz);\n" " float intensity = max(0.0, dot(lightDir, normal));\n" " gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, alpha);\n" "}", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->render_pass_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->render_pass_program; } pbge::GPUProgram * Ellipsoids::get_depth_pass_program() { if(this->depth_pass_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " gl_Position = pbge_ProjectionMatrix * position;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->depth_pass_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->depth_pass_program; } pbge::GPUProgram * Ellipsoids::get_peeling_program() { if(this->peeling_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec4 nposition;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " const vec4 light_position = vec4(16,16,16,1);\n" " lightPosition = view_transform * light_position;\n" " nposition = pbge_ProjectionMatrix * position;\n" " gl_Position = nposition;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "in vec4 position;\n" "in vec3 normal;\n" "in vec4 lightPosition;\n" "in vec4 nposition;\n" "uniform sampler2D depth;\n" "uniform float min_alpha;\n" "uniform float max_alpha;\n" "uniform vec4 min_color;\n" "uniform vec4 max_color;\n" "void main() {\n" // nposition is in ndc so we need to do the perspective division to transform the position // to the range -1 to 1. " vec2 p = 0.5 * (nposition.xy / nposition.w) + 0.5;\n" " float alpha = gl_Color.a;\n" // depth + offset to avoid z-fighting " if(gl_FragCoord.z <= (texture2D(depth,p.xy)).r + 0.0001) discard;\n" " if(normal.z >= 0) discard;\n" " if(alpha <= min_alpha - 0.005) discard;\n" " if(alpha >= max_alpha + 0.005) discard;\n" " float rampIndex = (alpha - min_alpha) / max(max_alpha - min_alpha - 0.6,0.1);" " vec4 diffuseColor = mix(min_color, max_color, rampIndex);\n" " vec4 lightDiffuseColor = vec4(2,2,2,2);\n" " vec3 lightDir = normalize((lightPosition - position).xyz);\n" " float intensity = max(0.0, dot(lightDir, normal));\n" " gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, alpha);\n" "}", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->peeling_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->peeling_program; }<commit_msg>Enhancing lights on tensor field<commit_after>#include <string> #include <cstring> #include <vector> #include "math3d/math3d.h" #include "pbge/pbge.h" #include "Ellipsoids.h" Ellipsoids::Ellipsoids(pbge::GraphicAPI * _gfx, int total_ellipsoids) { std::vector<pbge::Model*> _models; _models.push_back(pbge::Geometrics::createSphere(1.0f, 10, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 7, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 5, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 4, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 3, _gfx)); _models.push_back(pbge::Geometrics::createSphere(1.0f, 2, _gfx)); std::vector<float> distances; distances.push_back(10.0f); distances.push_back(20.0f); distances.push_back(35.0f); distances.push_back(60.0f); distances.push_back(100.0f); this->models = new LODModels(_models, distances); this->gfx = _gfx; this->tex = gfx->getFactory()->createTextureBuffer(total_ellipsoids * sizeof(math3d::matrix44)); this->added_ellipsoids = 0; this->render_pass_program = NULL; this->depth_pass_program = NULL; this->peeling_program = NULL; this->transformation_shader = NULL; } PeelingAwareCollection * Ellipsoids::createEllipsoids(unsigned number_of_ellipsoids, math3d::matrix44 * transforms, BoundingBox box) { void * texData = tex->getBuffer()->map(pbge::Buffer::WRITE_ONLY); memcpy((unsigned char *)texData + this->added_ellipsoids * sizeof(math3d::matrix44), transforms, number_of_ellipsoids * sizeof(math3d::matrix44)); tex->getBuffer()->unmap(); texData = NULL; tex->setInternalFormat(pbge::Texture::FLOAT, pbge::Texture::RGBA); PeelingAwareCollection * ellipsoids = new PeelingAwareCollection(models, get_peeling_program()); ellipsoids->setNumberOfInstances(number_of_ellipsoids); pbge::UniformBufferSampler * uniform = ellipsoids->getUniformSet()->getBufferSampler("transforms"); uniform->setValue(tex); ellipsoids->setTransforms(transforms); pbge::UniformFloat * base_instance = ellipsoids->getUniformSet()->getFloat("base_instance"); base_instance->setValue((float)this->added_ellipsoids); this->added_ellipsoids += number_of_ellipsoids; ellipsoids->setRenderPassProgram(get_render_pass_program()); ellipsoids->setDepthPassProgram(get_depth_pass_program()); ellipsoids->setBoundingBox(box); return ellipsoids; } pbge::Shader * Ellipsoids::get_transformation_shader() { if(this->transformation_shader == NULL) { this->transformation_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform samplerBuffer transforms;\n" "uniform float base_instance;\n" "uniform float scale;\n" "uniform mat4 pbge_ModelViewMatrix;\n" "uniform float alpha_index;\n" "in vec4 pbge_Vertex;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_transform) {\n" " int index = (int(base_instance) + gl_InstanceID) * 4;\n" " vec4 vertex = vec4(pbge_Vertex.xyz * scale, 1.0);\n" " vec4 col1 = texelFetch(transforms, index);\n" " vec4 col2 = texelFetch(transforms, index + 1);\n" " vec4 col3 = texelFetch(transforms, index + 2);\n" " vec4 col4 = texelFetch(transforms, index + 3);\n" " color = vec4(col1.w,col2.w,col3.w,col4.w);\n" " color = vec4(1,1,1,color[int(alpha_index)]);\n" " col1 = vec4(col1.xyz, 0);\n" " col2 = vec4(col2.xyz, 0);\n" " col3 = vec4(col3.xyz, 0);\n" " col4 = vec4(col4.xyz, 1);\n" " mat4 transformation = mat4(col1, col2, col3, col4);\n" " view_transform = pbge_ModelViewMatrix * transformation;\n" " vec4 _normal = inverse(transpose(view_transform)) * pbge_Vertex;\n" " view_normal = normalize(_normal.xyz);\n" " view_position = view_transform * vertex;\n" "}", pbge::Shader::VERTEX_SHADER); } return this->transformation_shader; } pbge::GPUProgram * Ellipsoids::get_render_pass_program() { if(this->render_pass_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " const vec4 light_position = vec4(0,16,16,1);\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " lightPosition = pbge_ProjectionMatrix * view_transform * light_position;\n" " gl_Position = pbge_ProjectionMatrix * position;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "uniform float min_alpha;\n" "uniform float max_alpha;\n" "uniform vec4 min_color;\n" "uniform vec4 max_color;\n" "in vec4 position;\n" "in vec3 normal;\n" "in vec4 lightPosition;\n" "void main() {\n" " float alpha = gl_Color.a;\n" " if(alpha <= min_alpha - 0.005) discard;\n" " if(alpha >= max_alpha + 0.005) discard;\n" " float rampIndex = (alpha - min_alpha) / max(max_alpha - min_alpha - 0.6,0.1);" " vec4 diffuseColor = mix(min_color, max_color, rampIndex);\n" " vec4 lightDiffuseColor = vec4(2,2,2,2);\n" " vec3 lightDir = normalize((lightPosition - position).xyz);\n" " float intensity = max(0.0, dot(lightDir, normal));\n" " gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, alpha);\n" "}", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->render_pass_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->render_pass_program; } pbge::GPUProgram * Ellipsoids::get_depth_pass_program() { if(this->depth_pass_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " gl_Position = pbge_ProjectionMatrix * position;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->depth_pass_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->depth_pass_program; } pbge::GPUProgram * Ellipsoids::get_peeling_program() { if(this->peeling_program == NULL) { pbge::Shader * vertex_shader = gfx->getFactory()->createShaderFromString( "#version 150\n" "uniform mat4 pbge_ProjectionMatrix;\n" "out vec4 position;\n" "out vec4 nposition;\n" "out vec3 normal;\n" "out vec4 lightPosition;\n" "void calc_transformations(out vec4 view_position, out vec3 view_normal, out vec4 color, out mat4 view_tranform);\n" "void main() {\n" " mat4 view_transform;\n" " calc_transformations(position, normal, gl_FrontColor, view_transform);\n" " const vec4 light_position = vec4(0,16,16,1);\n" " lightPosition = pbge_ProjectionMatrix * view_transform * light_position;\n" " nposition = pbge_ProjectionMatrix * position;\n" " gl_Position = nposition;\n" "}", pbge::Shader::VERTEX_SHADER); pbge::Shader * frag_shader = gfx->getFactory()->createShaderFromString( "in vec4 position;\n" "in vec3 normal;\n" "in vec4 lightPosition;\n" "in vec4 nposition;\n" "uniform sampler2D depth;\n" "uniform float min_alpha;\n" "uniform float max_alpha;\n" "uniform vec4 min_color;\n" "uniform vec4 max_color;\n" "void main() {\n" // nposition is in ndc so we need to do the perspective division to transform the position // to the range -1 to 1. " vec2 p = 0.5 * (nposition.xy / nposition.w) + 0.5;\n" " float alpha = gl_Color.a;\n" // depth + offset to avoid z-fighting " if(gl_FragCoord.z <= (texture2D(depth,p.xy)).r + 0.0001) discard;\n" " if(normal.z >= 0) discard;\n" " if(alpha <= min_alpha - 0.005) discard;\n" " if(alpha >= max_alpha + 0.005) discard;\n" " float rampIndex = (alpha - min_alpha) / max(max_alpha - min_alpha - 0.6,0.1);" " vec4 diffuseColor = mix(min_color, max_color, rampIndex);\n" " vec4 lightDiffuseColor = vec4(2,2,2,2);\n" " vec3 lightDir = normalize((lightPosition - position).xyz);\n" " float intensity = max(0.0, dot(lightDir, normal));\n" " gl_FragData[0] = vec4(diffuseColor.rgb * lightDiffuseColor.rgb * intensity, alpha);\n" "}", pbge::Shader::FRAGMENT_SHADER); std::vector<pbge::Shader *> vertex_shaders; std::vector<pbge::Shader *> fragment_shaders; vertex_shaders.push_back(vertex_shader); vertex_shaders.push_back(get_transformation_shader()); fragment_shaders.push_back(frag_shader); this->peeling_program = gfx->getFactory()->createProgram( vertex_shaders, fragment_shaders ); } return this->peeling_program; }<|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <[email protected]> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; std::vector<float> dis; float distance; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { std::shared_ptr <Shape> s_ptr = *it; //Shape s = *s_ptr; s_ptr->intersect_optional(ray, distance, o.intersection, o.normal); dis.push_back(distance); } //suche geringste distance und passendes Shape dazu int min_pos = std::distance(dis.begin(), std::min_element(dis.begin(), dis.end())); //std::cout << "test intersect" << std::endl; o.shape = &*scene_.shapes[min_pos]; o.distance = *std::min_element(dis.begin(), dis.end()); //normal, ... berechnen return o; } Color Renderer::raytrace(Ray const& ray){ Optional_hit o = intersect(ray); //std::cout << "test raytrace" << std::endl; if(o.distance == 0){ //ehemalige depth return scene_.ambient; } if(o.hit) { Light_source l{"licht", {0,0,0}, {1.0,1.0,1.0}, {0.4,0.4,0.4}}; float tmp = glm::dot(glm::normalize(ray.direction), glm::normalize(l.get_position() - o.intersection)); //intersection ausrechnen lassen bei intersect! Material temp_mat = scene_.material[(*o.shape).get_material()]; float red = temp_mat.get_kd().r * l.get_diffuse().r * tmp; float green = temp_mat.get_kd().g * l.get_diffuse().g * tmp; float blue = temp_mat.get_kd().b * l.get_diffuse().b * tmp; return Color(red, green, blue); } else { return scene_.ambient; } } //ungefähres Prozedere? was ist mit den Methoden vom Bernstein? void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobejkt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); std::cout << rays.size() << std::endl; std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i); (*j).color = temp; ++j; write(*j); } ppm_.save(filename_); } <commit_msg>Kleines Update bei raytrace, Frage zu lights<commit_after>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <[email protected]> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; std::vector<float> dis; float distance; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { std::shared_ptr <Shape> s_ptr = *it; //Shape s = *s_ptr; o.hit = s_ptr->intersect_optional(ray, distance, o.intersection, o.normal); dis.push_back(distance); } //suche geringste distance und passendes Shape dazu int min_pos = std::distance(dis.begin(), std::min_element(dis.begin(), dis.end())); o.shape = &*scene_.shapes[min_pos]; o.distance = *std::min_element(dis.begin(), dis.end()); //normal, ... berechnen return o; } Color Renderer::raytrace(Ray const& ray){ Optional_hit o = intersect(ray); if(o.distance == 0){ //ehemalige depth return scene_.ambient; } if(o.hit) { //Light_source l{"licht", {0,0,0}, {1.0,1.0,1.0}, {0.4,0.4,0.4}}; //Schleife für alle lights? Light_source l = scene_.lights[0]; float tmp = glm::dot(glm::normalize(ray.direction), glm::normalize(l.get_position() - o.intersection)); //intersection ausrechnen lassen bei intersect! Material temp_mat = scene_.material[(*o.shape).get_material()]; float red = temp_mat.get_kd().r * l.get_diffuse().r * tmp; float green = temp_mat.get_kd().g * l.get_diffuse().g * tmp; float blue = temp_mat.get_kd().b * l.get_diffuse().b * tmp; std::cout << tmp << std::endl; return Color(red, green, blue); } else { return scene_.ambient; } } //ungefähres Prozedere? was ist mit den Methoden vom Bernstein? void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobejkt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); std::cout << rays.size() << std::endl; std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i); (*j).color = temp; ++j; write(*j); } ppm_.save(filename_); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: testMetaObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <stdio.h> #include <fstream> #include <ctype.h> #include <metaObject.h> #include <metaUtils.h> #include "itkNumericTraits.h" int testMetaObject(int , char *[]) { MetaObject tObj; tObj.InitializeEssential(3); tObj.FileName("testObject.txt"); tObj.Comment("TestObject"); tObj.ObjectTypeName("Object"); tObj.ObjectSubTypeName("MinorObject"); tObj.Position(0, 1); tObj.Position(1, 2); tObj.Position(2, 3); float orient[9]; int i; for(i=0; i<9; i++) { orient[i] = 0; } orient[0] = 1; orient[5] = 1; orient[7] = 1; tObj.Orientation(orient); tObj.ElementSpacing(0, 1); tObj.ElementSpacing(1, 2); tObj.ElementSpacing(2, 1); // Add user's defined fields int myarray[3]; myarray[0]=1; myarray[1]=2; myarray[2]=3; tObj.AddUserField("MyName", MET_STRING, strlen("Julien"), "Julien"); tObj.AddUserField("MyArray", MET_INT_ARRAY,3,myarray); float myMatrix[4]; for(i=0; i<4; i++) { myMatrix[i] = i; } tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2,myMatrix); tObj.PrintInfo(); tObj.Write(); tObj.Clear(); tObj.ClearUserFields(); tObj.AddUserField("MyName", MET_STRING); tObj.AddUserField("MyArray", MET_INT_ARRAY,3); tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2); std::cout << "Test Reading: "; tObj.Read(); std::cout << "[PASSED]" << std::endl; tObj.PrintInfo(); char* name = static_cast<char*>(tObj.GetUserField("MyName")); if(strcmp(name,"Julien")) { std::cout << "MyName: FAIL" << std::endl; return 1; } delete [] name; int* array = static_cast<int*>(tObj.GetUserField("MyArray")); for(i=0;i<3;i++) { if(array[i] != i+1) { std::cout << "MyArray: FAIL" << std::endl; return 1; } } delete [] array; float* matrix = static_cast<float*>(tObj.GetUserField("MyMatrix")); for(i=0; i<4; i++) { if(matrix[i] != i) { std::cout << "MyMatrix: FAIL" << std::endl; return 1; } } delete [] matrix; std::cout << "PASSED!" << std::endl; tObj.Clear(); tObj.ClearUserFields(); tObj.FileName("testObject2.txt"); tObj.InitializeEssential(2); tObj.Position(0, 4); tObj.ElementSpacing(0,2); tObj.PrintInfo(); tObj.Write(); tObj.Clear(); tObj.Read(); tObj.PrintInfo(); if(tObj.NDims() != 2) { std::cout << "NDims: FAIL" << std::endl; return 1; } else { std::cout << "NDims: PASS" << std::endl; } int zero = 0; if(tObj.Position(zero) != 4) { std::cout << "Position: FAIL :" << tObj.Position(zero) << std::endl; return 1; } else { std::cout << "Position: PASS" << std::endl; } if(tObj.ElementSpacing(zero) != 2) { std::cout << "ElementSpacing: FAIL: " << tObj.ElementSpacing(zero) << std::endl; return 1; } else { std::cout << "ElementSpacing: PASS" << std::endl; } // testing metaUtils char* inDataChar = new char[1]; inDataChar[0]=1; char* outDataChar = new char[1]; if(!MET_ValueToValue(MET_CHAR_ARRAY,inDataChar,0,MET_CHAR_ARRAY,outDataChar)) { std::cout << "MET_ValueToValue: FAIL" << std::endl; return 1; } else { std::cout << "outDataChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataChar[0]) << std::endl; } delete [] inDataChar; delete [] outDataChar; unsigned char* inDataUChar = new unsigned char[1]; inDataUChar[0]=1; unsigned char* outDataUChar = new unsigned char[1]; if(!MET_ValueToValue(MET_UCHAR_ARRAY,inDataUChar,0,MET_UCHAR_ARRAY,outDataUChar)) { std::cout << "MET_ValueToValue: FAIL" << std::endl; return 1; } else { std::cout << "outDataUChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataUChar[0]) << std::endl; } delete [] inDataUChar; delete [] outDataUChar; std::cout << "[DONE]" << std::endl; return 0; } <commit_msg>ENH: Orientation is now of type double<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: testMetaObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <stdio.h> #include <fstream> #include <ctype.h> #include <metaObject.h> #include <metaUtils.h> #include "itkNumericTraits.h" int testMetaObject(int , char *[]) { MetaObject tObj; tObj.InitializeEssential(3); tObj.FileName("testObject.txt"); tObj.Comment("TestObject"); tObj.ObjectTypeName("Object"); tObj.ObjectSubTypeName("MinorObject"); tObj.Position(0, 1); tObj.Position(1, 2); tObj.Position(2, 3); double orient[9]; int i; for(i=0; i<9; i++) { orient[i] = 0; } orient[0] = 1; orient[5] = 1; orient[7] = 1; tObj.Orientation(orient); tObj.ElementSpacing(0, 1); tObj.ElementSpacing(1, 2); tObj.ElementSpacing(2, 1); // Add user's defined fields int myarray[3]; myarray[0]=1; myarray[1]=2; myarray[2]=3; tObj.AddUserField("MyName", MET_STRING, strlen("Julien"), "Julien"); tObj.AddUserField("MyArray", MET_INT_ARRAY,3,myarray); float myMatrix[4]; for(i=0; i<4; i++) { myMatrix[i] = i; } tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2,myMatrix); tObj.PrintInfo(); tObj.Write(); tObj.Clear(); tObj.ClearUserFields(); tObj.AddUserField("MyName", MET_STRING); tObj.AddUserField("MyArray", MET_INT_ARRAY,3); tObj.AddUserField("MyMatrix", MET_FLOAT_MATRIX,2); std::cout << "Test Reading: "; tObj.Read(); std::cout << "[PASSED]" << std::endl; tObj.PrintInfo(); char* name = static_cast<char*>(tObj.GetUserField("MyName")); if(strcmp(name,"Julien")) { std::cout << "MyName: FAIL" << std::endl; return 1; } delete [] name; int* array = static_cast<int*>(tObj.GetUserField("MyArray")); for(i=0;i<3;i++) { if(array[i] != i+1) { std::cout << "MyArray: FAIL" << std::endl; return 1; } } delete [] array; float* matrix = static_cast<float*>(tObj.GetUserField("MyMatrix")); for(i=0; i<4; i++) { if(matrix[i] != i) { std::cout << "MyMatrix: FAIL" << std::endl; return 1; } } delete [] matrix; std::cout << "PASSED!" << std::endl; tObj.Clear(); tObj.ClearUserFields(); tObj.FileName("testObject2.txt"); tObj.InitializeEssential(2); tObj.Position(0, 4); tObj.ElementSpacing(0,2); tObj.PrintInfo(); tObj.Write(); tObj.Clear(); tObj.Read(); tObj.PrintInfo(); if(tObj.NDims() != 2) { std::cout << "NDims: FAIL" << std::endl; return 1; } else { std::cout << "NDims: PASS" << std::endl; } int zero = 0; if(tObj.Position(zero) != 4) { std::cout << "Position: FAIL :" << tObj.Position(zero) << std::endl; return 1; } else { std::cout << "Position: PASS" << std::endl; } if(tObj.ElementSpacing(zero) != 2) { std::cout << "ElementSpacing: FAIL: " << tObj.ElementSpacing(zero) << std::endl; return 1; } else { std::cout << "ElementSpacing: PASS" << std::endl; } // testing metaUtils char* inDataChar = new char[1]; inDataChar[0]=1; char* outDataChar = new char[1]; if(!MET_ValueToValue(MET_CHAR_ARRAY,inDataChar,0,MET_CHAR_ARRAY,outDataChar)) { std::cout << "MET_ValueToValue: FAIL" << std::endl; return 1; } else { std::cout << "outDataChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataChar[0]) << std::endl; } delete [] inDataChar; delete [] outDataChar; unsigned char* inDataUChar = new unsigned char[1]; inDataUChar[0]=1; unsigned char* outDataUChar = new unsigned char[1]; if(!MET_ValueToValue(MET_UCHAR_ARRAY,inDataUChar,0,MET_UCHAR_ARRAY,outDataUChar)) { std::cout << "MET_ValueToValue: FAIL" << std::endl; return 1; } else { std::cout << "outDataUChar = " << static_cast<itk::NumericTraits<char>::PrintType>(outDataUChar[0]) << std::endl; } delete [] inDataUChar; delete [] outDataUChar; std::cout << "[DONE]" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <iostream> #include "gtest/gtest.h" #include "connection_handler/heartbeat_monitor.h" #include "connection_handler/connection.h" #include "connection_handler/connection_handler.h" #include "connection_handler/mock_connection_handler.h" #include "utils/test_async_waiter.h" namespace { const int32_t MILLISECONDS_IN_SECOND = 1000; const int32_t MICROSECONDS_IN_MILLISECONDS = 1000; const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000; const uint32_t kTime_offset = 20u; } namespace test { namespace components { namespace connection_handler_test { using ::testing::DoAll; using ::testing::_; using ::testing::Return; class HeartBeatMonitorTest : public testing::Test { public: HeartBeatMonitorTest() : connection_(NULL) , timeout_(100u) , time_allowance_multiplier_(1.5) , expiration_timeout_(timeout_ * 2u) {} protected: testing::NiceMock<MockConnectionHandler> connection_handler_mock_; connection_handler::Connection* connection_; const uint32_t timeout_; const float_t time_allowance_multiplier_; const uint32_t expiration_timeout_; static const connection_handler::ConnectionHandle connection_handle_ = 0xABCDEF; static const transport_manager::ConnectionUID kDefaultConnectionHandle = 1; static const uint32_t kDefaultSessionId = 1; void SetUp() OVERRIDE { connection_ = new connection_handler::Connection( connection_handle_, 0, &connection_handler_mock_, timeout_); } void TearDown() OVERRIDE { delete connection_; } }; ACTION_P2(RemoveSession, conn, session_id) { conn->RemoveSession(session_id); } TEST_F(HeartBeatMonitorTest, TimerNotStarted) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); // called by destructor of Connection // Whithout StartHeartBeat nothing to be call EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); connection_->AddNewSession(kDefaultConnectionHandle); } TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); connection_->StartHeartBeat(session); } TEST_F(HeartBeatMonitorTest, TimerElapsed) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); // invoked by RemoveSession action const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, session, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, session))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, session)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; connection_->StartHeartBeat(session); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, KeptAlive) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); connection_->StartHeartBeat(session); usleep(timeout_); connection_->KeepAlive(session); usleep(timeout_); connection_->KeepAlive(session); } TEST_F(HeartBeatMonitorTest, NotKeptAlive) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, session)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; EXPECT_CALL(connection_handler_mock_, CloseSession(_, session, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, session))); times++; connection_->StartHeartBeat(session); usleep(timeout_); connection_->KeepAlive(session); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { const uint32_t kMockSessionId1 = 1; const uint32_t kMockSessionId2 = 2; EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kMockSessionId1)) .WillOnce(Return(kMockSessionId2)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kMockSessionId1)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kMockSessionId2)) .WillOnce(Return(true)); const uint32_t kSession1 = connection_->AddNewSession(kDefaultConnectionHandle); const transport_manager::ConnectionUID kAnotherConnectionHandle = 2; const uint32_t kSession2 = connection_->AddNewSession(kAnotherConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession1, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession1))); times++; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession2, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession2))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession1)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession2)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; connection_->StartHeartBeat(kSession1); connection_->StartHeartBeat(kSession2); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t kSession = connection_->AddNewSession(kDefaultConnectionHandle); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); const uint32_t kNewTimeout = timeout_ + MICROSECONDS_IN_MILLISECONDS; connection_->StartHeartBeat(kSession); connection_->SetHeartBeatTimeout(kNewTimeout, kSession); } TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t kSession = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; const uint32_t new_timeout = timeout_ - kTime_offset; connection_->StartHeartBeat(kSession); connection_->SetHeartBeatTimeout(new_timeout, kSession); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } } // namespace connection_handler_test } // namespace components } // namespace test <commit_msg>Fix style<commit_after>/* * Copyright (c) 2013-2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <iostream> #include "gtest/gtest.h" #include "connection_handler/heartbeat_monitor.h" #include "connection_handler/connection.h" #include "connection_handler/connection_handler.h" #include "connection_handler/mock_connection_handler.h" #include "utils/test_async_waiter.h" namespace { const int32_t MILLISECONDS_IN_SECOND = 1000; const int32_t MICROSECONDS_IN_MILLISECONDS = 1000; const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000; const uint32_t kTime_offset = 20u; } namespace test { namespace components { namespace connection_handler_test { using ::testing::DoAll; using ::testing::_; using ::testing::Return; class HeartBeatMonitorTest : public testing::Test { public: HeartBeatMonitorTest() : connection_(NULL) , timeout_(100u) , time_allowance_multiplier_(1.5) , expiration_timeout_(timeout_ * 2u) {} protected: testing::NiceMock<MockConnectionHandler> connection_handler_mock_; connection_handler::Connection* connection_; const uint32_t timeout_; const float_t time_allowance_multiplier_; const uint32_t expiration_timeout_; static const connection_handler::ConnectionHandle connection_handle_ = 0xABCDEF; static const transport_manager::ConnectionUID kDefaultConnectionHandle = 1; static const uint32_t kDefaultSessionId = 1; void SetUp() OVERRIDE { connection_ = new connection_handler::Connection( connection_handle_, 0, &connection_handler_mock_, timeout_); } void TearDown() OVERRIDE { delete connection_; } }; ACTION_P2(RemoveSession, conn, session_id) { conn->RemoveSession(session_id); } TEST_F(HeartBeatMonitorTest, TimerNotStarted) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); // called by destructor of Connection // Whithout StartHeartBeat nothing to be call EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); connection_->AddNewSession(kDefaultConnectionHandle); } TEST_F(HeartBeatMonitorTest, TimerNotElapsed) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); connection_->StartHeartBeat(session); } TEST_F(HeartBeatMonitorTest, TimerElapsed) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); // invoked by RemoveSession action const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, session, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, session))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, session)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; connection_->StartHeartBeat(session); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, KeptAlive) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); connection_->StartHeartBeat(session); usleep(timeout_); connection_->KeepAlive(session); usleep(timeout_); connection_->KeepAlive(session); } TEST_F(HeartBeatMonitorTest, NotKeptAlive) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t session = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, session)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; EXPECT_CALL(connection_handler_mock_, CloseSession(_, session, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, session))); times++; connection_->StartHeartBeat(session); usleep(timeout_); connection_->KeepAlive(session); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) { const uint32_t kMockSessionId1 = 1; const uint32_t kMockSessionId2 = 2; EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kMockSessionId1)) .WillOnce(Return(kMockSessionId2)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kMockSessionId1)) .WillOnce(Return(true)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kMockSessionId2)) .WillOnce(Return(true)); const uint32_t kSession1 = connection_->AddNewSession(kDefaultConnectionHandle); const transport_manager::ConnectionUID kAnotherConnectionHandle = 2; const uint32_t kSession2 = connection_->AddNewSession(kAnotherConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession1, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession1))); times++; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession2, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession2))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession1)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession2)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; connection_->StartHeartBeat(kSession1); connection_->StartHeartBeat(kSession2); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t kSession = connection_->AddNewSession(kDefaultConnectionHandle); EXPECT_CALL(connection_handler_mock_, CloseSession(_, _)).Times(0); EXPECT_CALL(connection_handler_mock_, CloseConnection(_)).Times(0); EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, _)).Times(0); const uint32_t kNewTimeout = timeout_ + MICROSECONDS_IN_MILLISECONDS; connection_->StartHeartBeat(kSession); connection_->SetHeartBeatTimeout(kNewTimeout, kSession); } TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) { EXPECT_CALL(connection_handler_mock_, AddSession(_)) .WillOnce(Return(kDefaultSessionId)); EXPECT_CALL(connection_handler_mock_, RemoveSession(kDefaultSessionId)) .WillOnce(Return(true)); const uint32_t kSession = connection_->AddNewSession(kDefaultConnectionHandle); TestAsyncWaiter waiter; uint32_t times = 0; EXPECT_CALL(connection_handler_mock_, CloseSession(_, kSession, _)) .WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), RemoveSession(connection_, kSession))); times++; EXPECT_CALL(connection_handler_mock_, SendHeartBeat(_, kSession)) .WillOnce(NotifyTestAsyncWaiter(&waiter)); times++; const uint32_t new_timeout = timeout_ - kTime_offset; connection_->StartHeartBeat(kSession); connection_->SetHeartBeatTimeout(new_timeout, kSession); EXPECT_TRUE(waiter.WaitFor( times, 2 * timeout_ * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND)); } } // namespace connection_handler_test } // namespace components } // namespace test <|endoftext|>
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NonSmoothDynamicalSystem.hpp * \brief container for DynamicalSystem and Interaction */ #ifndef NSDS_H #define NSDS_H #include "SiconosPointers.hpp" #include "Topology.hpp" #include "DynamicalSystem.hpp" /** the NonSmoothDynamicalSystem consists in Dynamical Systems and Interactions structured into a graph defined in a Topology. In the DynamicalSystem graph, DynamicalSystem objects are nodes and Interaction objects are edges. To add a DynamicalSystem, use insertDynamicalSystem method. To add a new Interaction, use link method. A dual graph is also contructed, where Interactions are vertices and DynamicalSystems are edges. */ class NonSmoothDynamicalSystem { public: typedef enum { addDynamicalSystem, rmDynamicalSystem, addInteraction, rmInteraction, clearTopology } ChangeType; class Change { private: ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem::Change); Change(){}; public: ChangeType typeOfChange; SP::DynamicalSystem ds; SP::Interaction i; Change(ChangeType t, SP::DynamicalSystem dsnew ):typeOfChange(t),ds(dsnew){}; Change(ChangeType t, SP::Interaction inew):typeOfChange(t),i(inew){}; Change(ChangeType t):typeOfChange(t){}; void display() const; }; typedef std::list<Change> ChangeLog; class ChangeLogIter { ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem::Change); public: ChangeLogIter(){}; ChangeLogIter(const ChangeLog& log, const ChangeLog::const_iterator& i) : _log(&log), it(i) {}; const ChangeLog *_log; ChangeLog::const_iterator it; }; private: /** serialization hooks */ ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem); /** current time of the simulation Warning FP : it corresponds to the time at the end of the integration step. It means that _t corresponds to tkp1 of the simulation or nextTime(). */ double _t; /** initial time of the simulation */ double _t0; /** final time of the simulation */ double _T; /** information concerning the Model */ std::string _title, _author, _description, _date; /** TRUE if the NonSmoothDynamicalSystem is a boundary value problem*/ bool _BVP; /** log list of the modifications of the nsds */ std::list<Change> _changeLog; /** the topology of the system */ SP::Topology _topology; NonSmoothDynamicalSystem(const NonSmoothDynamicalSystem& nsds); /** False is one of the interaction is non-linear. */ bool _mIsLinear; public: /** default constructor */ NonSmoothDynamicalSystem(); /** constructor with t0 and T * \param t0 initial time * \param T final time */ NonSmoothDynamicalSystem(double t0, double T); /** destructor */ ~NonSmoothDynamicalSystem(); // --- GETTERS/SETTERS --- /** get the current time * \return a double */ inline double currentTime() const { return _t; } /** set the current time * \param newValue the new time */ inline void setCurrentTime(double newValue) { _t = newValue; } /** get initial time * \return a double */ inline double t0() const { return _t0; } /** set initial time of the time discretisation * \param newT0 */ inline void sett0(double newT0) { _t0 = newT0; }; /** get final time * \return a double */ inline double finalT() const { return _T; } /** set final time * \param newValue the new final time for the Simulatiom */ void setT(double newValue) { _T = newValue; }; /** get the title of the simulation * \return std::string : the title */ inline const std::string title() const { return _title; } /** set the title of the simulation * \param s : the title */ inline void setTitle(const std::string & s) { _title = s; } /** get the author of the simulation * \return std::string : the author */ inline const std::string author() const { return _author; } /** set the author of the simulation * \param s std::string : the author */ inline void setAuthor(const std::string & s) { _author = s; } /** allows to get the description of the simulation * \return std::string : the description */ inline const std::string description() const { return _description; } /** set the author of the simulation * \param s std::string : the author */ inline void setDescription(const std::string & s) { _description = s; } /** allows to get the date of the simulation * \return std::string : the date */ inline const std::string date() const { return _date; } /** set the date of the simulation * \param s std::string : the date */ inline void setDate(const std::string & s) { _date = s; } /** get problem type (true if BVP) * \return a bool */ inline bool isBVP() const { return _BVP; } /** get problem type (true if IVP) * \return a bool */ inline bool isIVP() const { return !_BVP; } /** set the NonSmoothDynamicalSystem to BVP, else it is IVP * \param newBvp true if BVP, false otherwise */ inline void setBVP(const bool& newBvp) { _BVP = newBvp; } /** get a reference to the changelog for an NSDS. * \return a reference to the changelog. */ inline const ChangeLog& changeLog() { return _changeLog; }; /** get an iterator to the last item in the changelog. * \return an iterator pointing at the last item in the changelog. */ inline ChangeLogIter changeLogPosition() { ChangeLogIter it(_changeLog, _changeLog.end()); // return iterator to last item, i.e. one less than end --it.it; return it; }; /** get an iterator to the beginning of the changelog. * \return an iterator pointing at the beginning of the changelog. */ inline ChangeLogIter changeLogBegin() { ChangeLogIter it(_changeLog, _changeLog.begin()); return it; }; /** clear the changelog up to a given position. * \param it This iterator must point to somewhere in the changelog * for this NSDS. */ void clearChangeLogTo(const ChangeLogIter& it); // === DynamicalSystems management === /** get the number of Dynamical Systems present in the NSDS \return an unsigned int */ inline unsigned int getNumberOfDS() const { return _topology->dSG(0)->size(); } /** get all the dynamical systems declared in the NonSmoothDynamicalSystem. * \return a SP::DynamicalSystemsGraph */ inline const SP::DynamicalSystemsGraph dynamicalSystems() const { return _topology->dSG(0); } /** add a dynamical system into the DS graph (as a vertex) * \param ds a pointer to the system to add */ void insertDynamicalSystem(SP::DynamicalSystem ds); /** get Dynamical system number I * \param nb the identifier of the DynamicalSystem to get * \return a pointer on DynamicalSystem */ inline SP::DynamicalSystem dynamicalSystems(int nb) const { return _topology->getDynamicalSystems(nb); } inline void displayDynamicalSystem() const { _topology->displayDynamicalSystem(); } /** remove a dynamical system * \param ds a pointer to the dynamical system to remove */ void removeDynamicalSystem(SP::DynamicalSystem ds); // === Interactions management === /** get the number of Interactions present in the NSDS. * \return an unsigned int */ inline unsigned int getNumberOfInteractions() const { return _topology->indexSet0()->size(); }; /** return the graph of Interactions present in the NSDS. * \return SP::InteractionGraph */ inline const SP::InteractionsGraph interactions() const { return _topology->indexSet0(); }; /** remove an interaction to the system * \param inter a pointer to the interaction to remove */ void removeInteraction(SP::Interaction inter); /** get Interaction number I * \param nb the identifier of the Interaction to get * \return a pointer to an Interaction */ inline SP::Interaction interaction(int nb) const { return _topology->getInteraction(nb); } /** get Interaction named name * \param name of the Interaction to get * \return a pointer to an Interaction */ inline SP::Interaction interaction(std::string name) const { return _topology->getInteraction(name); } /** link an interaction to two dynamical systems * \param inter the interaction * \param ds1 a DynamicalSystem * \param ds2 a DynamicalSystem (optional) */ void link(SP::Interaction inter, SP::DynamicalSystem ds1, SP::DynamicalSystem ds2 = SP::DynamicalSystem()); /** set the name for this Dynamical System * \param ds a pointer to the system * \param name the name of the DynamicalSystem */ inline void setName(SP::DynamicalSystem ds, const std::string& name) { _topology->setName(ds, name); }; /** get the name for this Dynamical System * \param ds a pointer to the system * \return name the name of the DynamicalSystem, or empty string if not found. */ std::string name(SP::DynamicalSystem ds) { return _topology->name(ds); } /** set the name for this Interaction * \param interaction a pointer to the Interaction * \param name the name of the Interaction */ inline void setName(SP::Interaction interaction, const std::string& name) { _topology->setName(interaction, name); }; /** get the name for this Interaction * \param inter a pointer to the Interaction * \return name the name of the Interaction, or empty string if not found. */ std::string name(SP::Interaction inter) { return _topology->name(inter); } /** specify id the given Interaction is for controlling the DS * \param inter the Interaction * \param isControlInteraction true if the Interaction is used for * control purposes **/ void setControlProperty(SP::Interaction inter, const bool isControlInteraction) { _topology->setControlProperty(inter, isControlInteraction); } /** get the topology of the system * \return a pointer on Topology */ inline SP::Topology topology() const { return _topology; } /** display the data of the Non Smooth Dynamical System */ void display() const; /** return false is one of the interations is not linear. else * return true. * \return a bool */ inline bool isLinear() const { return _mIsLinear; }; void clear(); /** set symmetry in the blocks computation * \param val a bool */ void setSymmetric(bool val); /** Set all DS non-smooth part to zero. */ void reset(); /** Set all DS non-smooth part to zero for a given level. * \param level the level to will be zeroed */ void reset(unsigned int level); /** save DynamicalSystems and Interactions states in Memories */ void swapInMemory(); /** save interaction states in memories. Applied to all interactions of the connected topology */ void pushInteractionsInMemory(); /** compute r thanks to lambda[level] for all Interactions * \param time * \param level lambda level */ void updateInput(double time, unsigned int level); /** compute output for all the interactions for a given level * \param time * \param level y order to be computed */ void updateOutput(double time, unsigned int level = 0); /** compute output for all the interactions and for a level range * \param time * \param level_min y min order to be computed * \param level_max y max order to be computed */ void updateOutput(double time, unsigned int level_min, unsigned int level_max); /** compute Jacobians for all the interactions (in indexSet0) * \param time */ void computeInteractionJacobians(double time); /** compute Jacobians for all the interactions of a given index set. \param time \param indexSet InteractionsGraph of interest */ void computeInteractionJacobians(double time, InteractionsGraph& indexSet); /** visit all dynamical systems in this system. * \param visitor an SP::SiconosVisitor that can visit classes derived from DS */ void visitDynamicalSystems(SP::SiconosVisitor visitor); }; #endif <commit_msg>[kernel] fix typos<commit_after>/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file NonSmoothDynamicalSystem.hpp * \brief container for DynamicalSystem and Interaction */ #ifndef NSDS_H #define NSDS_H #include "SiconosPointers.hpp" #include "Topology.hpp" #include "DynamicalSystem.hpp" /** the NonSmoothDynamicalSystem consists in Dynamical Systems and Interactions structured into a graph defined in a Topology. In the DynamicalSystem graph, DynamicalSystem objects are nodes and Interaction objects are edges. To add a DynamicalSystem, use insertDynamicalSystem method. To add a new Interaction, use link method. A dual graph is also contructed, where Interactions are vertices and DynamicalSystems are edges. */ class NonSmoothDynamicalSystem { public: typedef enum { addDynamicalSystem, rmDynamicalSystem, addInteraction, rmInteraction, clearTopology } ChangeType; class Change { private: ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem::Change); Change(){}; public: ChangeType typeOfChange; SP::DynamicalSystem ds; SP::Interaction i; Change(ChangeType t, SP::DynamicalSystem dsnew ):typeOfChange(t),ds(dsnew){}; Change(ChangeType t, SP::Interaction inew):typeOfChange(t),i(inew){}; Change(ChangeType t):typeOfChange(t){}; void display() const; }; typedef std::list<Change> ChangeLog; class ChangeLogIter { ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem::Change); public: ChangeLogIter(){}; ChangeLogIter(const ChangeLog& log, const ChangeLog::const_iterator& i) : _log(&log), it(i) {}; const ChangeLog *_log; ChangeLog::const_iterator it; }; private: /** serialization hooks */ ACCEPT_SERIALIZATION(NonSmoothDynamicalSystem); /** current time of the simulation Warning FP : it corresponds to the time at the end of the integration step. It means that _t corresponds to tkp1 of the simulation or nextTime(). */ double _t; /** initial time of the simulation */ double _t0; /** final time of the simulation */ double _T; /** information concerning the Model */ std::string _title, _author, _description, _date; /** TRUE if the NonSmoothDynamicalSystem is a boundary value problem*/ bool _BVP; /** log list of the modifications of the nsds */ std::list<Change> _changeLog; /** the topology of the system */ SP::Topology _topology; NonSmoothDynamicalSystem(const NonSmoothDynamicalSystem& nsds); /** False is one of the interaction is non-linear. */ bool _mIsLinear; public: /** default constructor */ NonSmoothDynamicalSystem(); /** constructor with t0 and T * \param t0 initial time * \param T final time */ NonSmoothDynamicalSystem(double t0, double T); /** destructor */ ~NonSmoothDynamicalSystem(); // --- GETTERS/SETTERS --- /** get the current time * \return a double */ inline double currentTime() const { return _t; } /** set the current time * \param newValue the new time */ inline void setCurrentTime(double newValue) { _t = newValue; } /** get initial time * \return a double */ inline double t0() const { return _t0; } /** set initial time of the time discretisation * \param newT0 */ inline void sett0(double newT0) { _t0 = newT0; }; /** get final time * \return a double */ inline double finalT() const { return _T; } /** set final time * \param newValue the new final time for the Simulatiom */ void setT(double newValue) { _T = newValue; }; /** get the title of the simulation * \return std::string : the title */ inline const std::string title() const { return _title; } /** set the title of the simulation * \param s : the title */ inline void setTitle(const std::string & s) { _title = s; } /** get the author of the simulation * \return std::string : the author */ inline const std::string author() const { return _author; } /** set the author of the simulation * \param s std::string : the author */ inline void setAuthor(const std::string & s) { _author = s; } /** allows to get the description of the simulation * \return std::string : the description */ inline const std::string description() const { return _description; } /** set the author of the simulation * \param s std::string : the author */ inline void setDescription(const std::string & s) { _description = s; } /** allows to get the date of the simulation * \return std::string : the date */ inline const std::string date() const { return _date; } /** set the date of the simulation * \param s std::string : the date */ inline void setDate(const std::string & s) { _date = s; } /** get problem type (true if BVP) * \return a bool */ inline bool isBVP() const { return _BVP; } /** get problem type (true if IVP) * \return a bool */ inline bool isIVP() const { return !_BVP; } /** set the NonSmoothDynamicalSystem to BVP, else it is IVP * \param newBvp true if BVP, false otherwise */ inline void setBVP(const bool& newBvp) { _BVP = newBvp; } /** get a reference to the changelog for an NSDS. * \return a reference to the changelog. */ inline const ChangeLog& changeLog() { return _changeLog; }; /** get an iterator to the last item in the changelog. * \return an iterator pointing at the last item in the changelog. */ inline ChangeLogIter changeLogPosition() { ChangeLogIter it(_changeLog, _changeLog.end()); // return iterator to last item, i.e. one less than end --it.it; return it; }; /** get an iterator to the beginning of the changelog. * \return an iterator pointing at the beginning of the changelog. */ inline ChangeLogIter changeLogBegin() { ChangeLogIter it(_changeLog, _changeLog.begin()); return it; }; /** clear the changelog up to a given position. * \param it This iterator must point to somewhere in the changelog * for this NSDS. */ void clearChangeLogTo(const ChangeLogIter& it); // === DynamicalSystems management === /** get the number of Dynamical Systems present in the NSDS \return an unsigned int */ inline unsigned int getNumberOfDS() const { return _topology->dSG(0)->size(); } /** get all the dynamical systems declared in the NonSmoothDynamicalSystem. * \return a SP::DynamicalSystemsGraph */ inline const SP::DynamicalSystemsGraph dynamicalSystems() const { return _topology->dSG(0); } /** add a dynamical system into the DS graph (as a vertex) * \param ds a pointer to the system to add */ void insertDynamicalSystem(SP::DynamicalSystem ds); /** get Dynamical system number I * \param nb the identifier of the DynamicalSystem to get * \return a pointer on DynamicalSystem */ inline SP::DynamicalSystem dynamicalSystem(int nb) const { return _topology->getDynamicalSystem(nb); } inline void displayDynamicalSystems() const { _topology->displayDynamicalSystems(); } /** remove a dynamical system * \param ds a pointer to the dynamical system to remove */ void removeDynamicalSystem(SP::DynamicalSystem ds); // === Interactions management === /** get the number of Interactions present in the NSDS. * \return an unsigned int */ inline unsigned int getNumberOfInteractions() const { return _topology->indexSet0()->size(); }; /** return the graph of Interactions present in the NSDS. * \return SP::InteractionGraph */ inline const SP::InteractionsGraph interactions() const { return _topology->indexSet0(); }; /** remove an interaction to the system * \param inter a pointer to the interaction to remove */ void removeInteraction(SP::Interaction inter); /** get Interaction number I * \param nb the identifier of the Interaction to get * \return a pointer to an Interaction */ inline SP::Interaction interaction(int nb) const { return _topology->getInteraction(nb); } /** get Interaction named name * \param name of the Interaction to get * \return a pointer to an Interaction */ inline SP::Interaction interaction(std::string name) const { return _topology->getInteraction(name); } /** link an interaction to two dynamical systems * \param inter the interaction * \param ds1 a DynamicalSystem * \param ds2 a DynamicalSystem (optional) */ void link(SP::Interaction inter, SP::DynamicalSystem ds1, SP::DynamicalSystem ds2 = SP::DynamicalSystem()); /** set the name for this Dynamical System * \param ds a pointer to the system * \param name the name of the DynamicalSystem */ inline void setName(SP::DynamicalSystem ds, const std::string& name) { _topology->setName(ds, name); }; /** get the name for this Dynamical System * \param ds a pointer to the system * \return name the name of the DynamicalSystem, or empty string if not found. */ std::string name(SP::DynamicalSystem ds) { return _topology->name(ds); } /** set the name for this Interaction * \param interaction a pointer to the Interaction * \param name the name of the Interaction */ inline void setName(SP::Interaction interaction, const std::string& name) { _topology->setName(interaction, name); }; /** get the name for this Interaction * \param inter a pointer to the Interaction * \return name the name of the Interaction, or empty string if not found. */ std::string name(SP::Interaction inter) { return _topology->name(inter); } /** specify id the given Interaction is for controlling the DS * \param inter the Interaction * \param isControlInteraction true if the Interaction is used for * control purposes **/ void setControlProperty(SP::Interaction inter, const bool isControlInteraction) { _topology->setControlProperty(inter, isControlInteraction); } /** get the topology of the system * \return a pointer on Topology */ inline SP::Topology topology() const { return _topology; } /** display the data of the Non Smooth Dynamical System */ void display() const; /** return false is one of the interations is not linear. else * return true. * \return a bool */ inline bool isLinear() const { return _mIsLinear; }; void clear(); /** set symmetry in the blocks computation * \param val a bool */ void setSymmetric(bool val); /** Set all DS non-smooth part to zero. */ void reset(); /** Set all DS non-smooth part to zero for a given level. * \param level the level to will be zeroed */ void reset(unsigned int level); /** save DynamicalSystems and Interactions states in Memories */ void swapInMemory(); /** save interaction states in memories. Applied to all interactions of the connected topology */ void pushInteractionsInMemory(); /** compute r thanks to lambda[level] for all Interactions * \param time * \param level lambda level */ void updateInput(double time, unsigned int level); /** compute output for all the interactions for a given level * \param time * \param level y order to be computed */ void updateOutput(double time, unsigned int level = 0); /** compute output for all the interactions and for a level range * \param time * \param level_min y min order to be computed * \param level_max y max order to be computed */ void updateOutput(double time, unsigned int level_min, unsigned int level_max); /** compute Jacobians for all the interactions (in indexSet0) * \param time */ void computeInteractionJacobians(double time); /** compute Jacobians for all the interactions of a given index set. \param time \param indexSet InteractionsGraph of interest */ void computeInteractionJacobians(double time, InteractionsGraph& indexSet); /** visit all dynamical systems in this system. * \param visitor an SP::SiconosVisitor that can visit classes derived from DS */ void visitDynamicalSystems(SP::SiconosVisitor visitor); }; #endif <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/flet.h" #include "util/scoped_map.h" #include "util/interrupt.h" #include "kernel/environment.h" #include "kernel/normalizer.h" #include "kernel/builtin.h" #include "kernel/kernel_exception.h" #include "kernel/type_checker_justification.h" #include "kernel/instantiate.h" #include "kernel/free_vars.h" #include "kernel/metavar.h" #include "library/kernel_bindings.h" #include "library/type_inferer.h" namespace lean { static name g_x_name("x"); class type_inferer::imp { typedef scoped_map<expr, expr, expr_hash_alloc, expr_eqp> cache; typedef buffer<unification_constraint> unification_constraints; ro_environment m_env; context m_ctx; cached_metavar_env m_menv; unification_constraints * m_uc; normalizer m_normalizer; cache m_cache; expr normalize(expr const & e, context const & ctx) { return m_normalizer(e, ctx, m_menv.to_some_menv()); } expr lift_free_vars(expr const & e, unsigned s, unsigned d) { return ::lean::lift_free_vars(e, s, d, m_menv.to_some_menv()); } expr lift_free_vars(expr const & e, unsigned d) { return ::lean::lift_free_vars(e, d, m_menv.to_some_menv()); } expr instantiate(expr const & e, unsigned n, expr const * s) { return ::lean::instantiate(e, n, s, m_menv.to_some_menv()); } expr check_type(expr const & e, expr const & s, context const & ctx) { if (is_type(e)) return e; if (is_bool(e)) return Type(); expr u = normalize(e, ctx); if (is_type(u)) return u; if (is_bool(u)) return Type(); if (has_metavar(u) && m_menv && m_uc) { justification jst = mk_type_expected_justification(ctx, s); m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst)); return u; } throw type_expected_exception(m_env, ctx, s); } expr get_range(expr t, expr const & e, context const & ctx) { unsigned num = num_args(e) - 1; while (num > 0) { --num; if (is_pi(t)) { t = abst_body(t); } else { t = m_normalizer(t, ctx); if (is_pi(t)) { t = abst_body(t); } else if (has_metavar(t) && m_menv && m_uc) { // Create two fresh variables A and B, // and assign r == (Pi(x : A), B) expr A = m_menv->mk_metavar(ctx); expr B = m_menv->mk_metavar(extend(ctx, g_x_name, A)); expr p = mk_pi(g_x_name, A, B); justification jst = mk_function_expected_justification(ctx, e); m_uc->push_back(mk_eq_constraint(ctx, t, p, jst)); t = abst_body(p); } else { throw function_expected_exception(m_env, ctx, e); } } } if (closed(t)) return t; else return instantiate(t, num_args(e)-1, &arg(e, 1)); } expr infer_type(expr const & e, context const & ctx) { // cheap cases, we do not cache results switch (e.kind()) { case expr_kind::MetaVar: if (m_menv) { if (m_menv->is_assigned(e)) return infer_type(*(m_menv->get_subst(e)), ctx); else return m_menv->get_type(e); } else { throw unexpected_metavar_occurrence(m_env, e); } case expr_kind::Constant: { if (const_type(e)) { return *const_type(e); } else { object const & obj = m_env->get_object(const_name(e)); if (obj.has_type()) return obj.get_type(); else throw has_no_type_exception(m_env, e); } break; } case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; if (ce.get_domain()) { context const & ce_ctx = p.second; return lift_free_vars(*(ce.get_domain()), ctx.size() - ce_ctx.size()); } // Remark: the case where ce.get_domain() is not // available is not considered cheap. break; } case expr_kind::Eq: return mk_bool_type(); case expr_kind::Value: return to_value(e).get_type(); case expr_kind::Type: return mk_type(ty_level(e) + 1); case expr_kind::App: case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Let: break; // expensive cases } check_system("type inference"); bool shared = false; if (is_shared(e)) { shared = true; auto it = m_cache.find(e); if (it != m_cache.end()) return it->second; } expr r; switch (e.kind()) { case expr_kind::Constant: case expr_kind::Eq: case expr_kind::Value: case expr_kind::Type: case expr_kind::MetaVar: lean_unreachable(); // LCOV_EXCL_LINE case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; context const & ce_ctx = p.second; lean_assert(!ce.get_domain()); r = lift_free_vars(infer_type(*(ce.get_body()), ce_ctx), ctx.size() - ce_ctx.size()); break; } case expr_kind::App: { expr const & f = arg(e, 0); expr f_t = infer_type(f, ctx); r = get_range(f_t, e, ctx); break; } case expr_kind::Lambda: { cache::mk_scope sc(m_cache); r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e)))); break; } case expr_kind::Pi: { expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx); expr t2; context new_ctx = extend(ctx, abst_name(e), abst_domain(e)); { cache::mk_scope sc(m_cache); t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx); } if (is_type(t1) && is_type(t2)) { r = mk_type(max(ty_level(t1), ty_level(t2))); } else { lean_assert(m_uc); justification jst = mk_max_type_justification(ctx, e); r = m_menv->mk_metavar(ctx); m_uc->push_back(mk_max_constraint(new_ctx, lift_free_vars(t1, 0, 1), t2, r, jst)); } break; } case expr_kind::Let: { cache::mk_scope sc(m_cache); r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e))); break; }} if (shared) { m_cache.insert(e, r); } return r; } void set_ctx(context const & ctx) { if (!is_eqp(m_ctx, ctx)) { clear(); m_ctx = ctx; } } public: imp(ro_environment const & env): m_env(env), m_normalizer(env) { m_uc = nullptr; } expr operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) { set_ctx(ctx); if (m_menv.update(menv)) clear_cache(); flet<unification_constraints*> set(m_uc, uc); return infer_type(e, ctx); } void clear_cache() { m_cache.clear(); m_normalizer.clear(); } void clear() { clear_cache(); m_menv.clear(); m_ctx = context(); } bool is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) { // Catch easy cases switch (e.kind()) { case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Type: return false; case expr_kind::Eq: return true; default: break; } expr t = operator()(e, ctx, menv, nullptr); if (is_bool(t)) return true; else return is_bool(normalize(t, ctx)); } }; type_inferer::type_inferer(ro_environment const & env):m_ptr(new imp(env)) {} type_inferer::~type_inferer() {} expr type_inferer::operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) { return m_ptr->operator()(e, ctx, menv, uc); } expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env const & menv, buffer<unification_constraint> & uc) { return m_ptr->operator()(e, ctx, some_menv(menv), &uc); } expr type_inferer::operator()(expr const & e, context const & ctx) { return operator()(e, ctx, none_menv(), nullptr); } bool type_inferer::is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) { return m_ptr->is_proposition(e, ctx, menv); } bool type_inferer::is_proposition(expr const & e, context const & ctx) { return is_proposition(e, ctx, none_menv()); } bool type_inferer::is_proposition(expr const & e, context const & ctx, metavar_env const & menv) { return is_proposition(e, ctx, some_menv(menv)); } void type_inferer::clear() { m_ptr->clear(); } constexpr char const * type_inferer_mt = "type_inferer"; type_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); } DECL_PRED(type_inferer) DECL_GC(type_inferer) static int type_inferer_call(lua_State * L) { int nargs = lua_gettop(L); type_inferer & inferer = to_type_inferer(L, 1); if (nargs == 2) return push_expr(L, inferer(to_expr(L, 2))); else return push_expr(L, inferer(to_expr(L, 2), to_context(L, 3))); } static int type_inferer_clear(lua_State * L) { to_type_inferer(L, 1).clear(); return 0; } static int mk_type_inferer(lua_State * L) { void * mem = lua_newuserdata(L, sizeof(type_inferer)); new (mem) type_inferer(to_environment(L, 1)); luaL_getmetatable(L, type_inferer_mt); lua_setmetatable(L, -2); return 1; } static const struct luaL_Reg type_inferer_m[] = { {"__gc", type_inferer_gc}, // never throws {"__call", safe_function<type_inferer_call>}, {"clear", safe_function<type_inferer_clear>}, {0, 0} }; void open_type_inferer(lua_State * L) { luaL_newmetatable(L, type_inferer_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, type_inferer_m, 0); SET_GLOBAL_FUN(mk_type_inferer, "type_inferer"); SET_GLOBAL_FUN(type_inferer_pred, "is_type_inferer"); } } <commit_msg>fix(library/type_inferer): another incorrect use of scoped_map<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <unordered_map> #include "util/flet.h" #include "util/freset.h" #include "util/interrupt.h" #include "kernel/environment.h" #include "kernel/normalizer.h" #include "kernel/builtin.h" #include "kernel/kernel_exception.h" #include "kernel/type_checker_justification.h" #include "kernel/instantiate.h" #include "kernel/free_vars.h" #include "kernel/metavar.h" #include "library/kernel_bindings.h" #include "library/type_inferer.h" namespace lean { static name g_x_name("x"); class type_inferer::imp { typedef std::unordered_map<expr, expr, expr_hash_alloc, expr_eqp> cache; typedef buffer<unification_constraint> unification_constraints; ro_environment m_env; context m_ctx; cached_metavar_env m_menv; unification_constraints * m_uc; normalizer m_normalizer; cache m_cache; expr normalize(expr const & e, context const & ctx) { return m_normalizer(e, ctx, m_menv.to_some_menv()); } expr lift_free_vars(expr const & e, unsigned s, unsigned d) { return ::lean::lift_free_vars(e, s, d, m_menv.to_some_menv()); } expr lift_free_vars(expr const & e, unsigned d) { return ::lean::lift_free_vars(e, d, m_menv.to_some_menv()); } expr instantiate(expr const & e, unsigned n, expr const * s) { return ::lean::instantiate(e, n, s, m_menv.to_some_menv()); } expr check_type(expr const & e, expr const & s, context const & ctx) { if (is_type(e)) return e; if (is_bool(e)) return Type(); expr u = normalize(e, ctx); if (is_type(u)) return u; if (is_bool(u)) return Type(); if (has_metavar(u) && m_menv && m_uc) { justification jst = mk_type_expected_justification(ctx, s); m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst)); return u; } throw type_expected_exception(m_env, ctx, s); } expr get_range(expr t, expr const & e, context const & ctx) { unsigned num = num_args(e) - 1; while (num > 0) { --num; if (is_pi(t)) { t = abst_body(t); } else { t = m_normalizer(t, ctx); if (is_pi(t)) { t = abst_body(t); } else if (has_metavar(t) && m_menv && m_uc) { // Create two fresh variables A and B, // and assign r == (Pi(x : A), B) expr A = m_menv->mk_metavar(ctx); expr B = m_menv->mk_metavar(extend(ctx, g_x_name, A)); expr p = mk_pi(g_x_name, A, B); justification jst = mk_function_expected_justification(ctx, e); m_uc->push_back(mk_eq_constraint(ctx, t, p, jst)); t = abst_body(p); } else { throw function_expected_exception(m_env, ctx, e); } } } if (closed(t)) return t; else return instantiate(t, num_args(e)-1, &arg(e, 1)); } expr infer_type(expr const & e, context const & ctx) { // cheap cases, we do not cache results switch (e.kind()) { case expr_kind::MetaVar: if (m_menv) { if (m_menv->is_assigned(e)) return infer_type(*(m_menv->get_subst(e)), ctx); else return m_menv->get_type(e); } else { throw unexpected_metavar_occurrence(m_env, e); } case expr_kind::Constant: { if (const_type(e)) { return *const_type(e); } else { object const & obj = m_env->get_object(const_name(e)); if (obj.has_type()) return obj.get_type(); else throw has_no_type_exception(m_env, e); } break; } case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; if (ce.get_domain()) { context const & ce_ctx = p.second; return lift_free_vars(*(ce.get_domain()), ctx.size() - ce_ctx.size()); } // Remark: the case where ce.get_domain() is not // available is not considered cheap. break; } case expr_kind::Eq: return mk_bool_type(); case expr_kind::Value: return to_value(e).get_type(); case expr_kind::Type: return mk_type(ty_level(e) + 1); case expr_kind::App: case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Let: break; // expensive cases } check_system("type inference"); bool shared = false; if (is_shared(e)) { shared = true; auto it = m_cache.find(e); if (it != m_cache.end()) return it->second; } expr r; switch (e.kind()) { case expr_kind::Constant: case expr_kind::Eq: case expr_kind::Value: case expr_kind::Type: case expr_kind::MetaVar: lean_unreachable(); // LCOV_EXCL_LINE case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; context const & ce_ctx = p.second; lean_assert(!ce.get_domain()); r = lift_free_vars(infer_type(*(ce.get_body()), ce_ctx), ctx.size() - ce_ctx.size()); break; } case expr_kind::App: { expr const & f = arg(e, 0); expr f_t = infer_type(f, ctx); r = get_range(f_t, e, ctx); break; } case expr_kind::Lambda: { freset<cache> reset(m_cache); r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e)))); break; } case expr_kind::Pi: { expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx); expr t2; context new_ctx = extend(ctx, abst_name(e), abst_domain(e)); { freset<cache> reset(m_cache); t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx); } if (is_type(t1) && is_type(t2)) { r = mk_type(max(ty_level(t1), ty_level(t2))); } else { lean_assert(m_uc); justification jst = mk_max_type_justification(ctx, e); r = m_menv->mk_metavar(ctx); m_uc->push_back(mk_max_constraint(new_ctx, lift_free_vars(t1, 0, 1), t2, r, jst)); } break; } case expr_kind::Let: { freset<cache> reset(m_cache); r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e))); break; }} if (shared) { m_cache[e] = r; } return r; } void set_ctx(context const & ctx) { if (!is_eqp(m_ctx, ctx)) { clear(); m_ctx = ctx; } } public: imp(ro_environment const & env): m_env(env), m_normalizer(env) { m_uc = nullptr; } expr operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) { set_ctx(ctx); if (m_menv.update(menv)) clear_cache(); flet<unification_constraints*> set(m_uc, uc); return infer_type(e, ctx); } void clear_cache() { m_cache.clear(); m_normalizer.clear(); } void clear() { clear_cache(); m_menv.clear(); m_ctx = context(); } bool is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) { // Catch easy cases switch (e.kind()) { case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Type: return false; case expr_kind::Eq: return true; default: break; } expr t = operator()(e, ctx, menv, nullptr); if (is_bool(t)) return true; else return is_bool(normalize(t, ctx)); } }; type_inferer::type_inferer(ro_environment const & env):m_ptr(new imp(env)) {} type_inferer::~type_inferer() {} expr type_inferer::operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) { return m_ptr->operator()(e, ctx, menv, uc); } expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env const & menv, buffer<unification_constraint> & uc) { return m_ptr->operator()(e, ctx, some_menv(menv), &uc); } expr type_inferer::operator()(expr const & e, context const & ctx) { return operator()(e, ctx, none_menv(), nullptr); } bool type_inferer::is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) { return m_ptr->is_proposition(e, ctx, menv); } bool type_inferer::is_proposition(expr const & e, context const & ctx) { return is_proposition(e, ctx, none_menv()); } bool type_inferer::is_proposition(expr const & e, context const & ctx, metavar_env const & menv) { return is_proposition(e, ctx, some_menv(menv)); } void type_inferer::clear() { m_ptr->clear(); } constexpr char const * type_inferer_mt = "type_inferer"; type_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); } DECL_PRED(type_inferer) DECL_GC(type_inferer) static int type_inferer_call(lua_State * L) { int nargs = lua_gettop(L); type_inferer & inferer = to_type_inferer(L, 1); if (nargs == 2) return push_expr(L, inferer(to_expr(L, 2))); else return push_expr(L, inferer(to_expr(L, 2), to_context(L, 3))); } static int type_inferer_clear(lua_State * L) { to_type_inferer(L, 1).clear(); return 0; } static int mk_type_inferer(lua_State * L) { void * mem = lua_newuserdata(L, sizeof(type_inferer)); new (mem) type_inferer(to_environment(L, 1)); luaL_getmetatable(L, type_inferer_mt); lua_setmetatable(L, -2); return 1; } static const struct luaL_Reg type_inferer_m[] = { {"__gc", type_inferer_gc}, // never throws {"__call", safe_function<type_inferer_call>}, {"clear", safe_function<type_inferer_clear>}, {0, 0} }; void open_type_inferer(lua_State * L) { luaL_newmetatable(L, type_inferer_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, type_inferer_m, 0); SET_GLOBAL_FUN(mk_type_inferer, "type_inferer"); SET_GLOBAL_FUN(type_inferer_pred, "is_type_inferer"); } } <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // Copyright 2008 Carlos Licea <[email protected]> // #include "TextureColorizer.h" #include <cmath> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QString> #include <QtCore/QTime> #include <QtGui/QColor> #include <QtGui/QImage> #include <QtGui/QPainter> #include "global.h" #include "GeoSceneDocument.h" #include "GeoSceneSettings.h" #include "ViewParams.h" #include "ViewportParams.h" #include "AbstractProjection.h" #include "MathHelper.h" using namespace Marble; uint TextureColorizer::texturepalette[16][512]; TextureColorizer::TextureColorizer( const QString& seafile, const QString& landfile ) { QTime t; t.start(); generatePalette(seafile, landfile); qDebug("TextureColorizer: Time elapsed: %d ms", t.elapsed()); } QString TextureColorizer::seafile() const { return m_seafile; } QString TextureColorizer::landfile() const { return m_landfile; } // This function takes two images, both in viewParams: // - The coast image, which has a number of colors where each color // represents a sort of terrain (ex: land/sea) // - The canvas image, which has a gray scale image, often // representing a height field. // // It then uses the values of the pixels in the coast image to select // a color map. The value of the pixel in the canvas image is used as // an index into the selected color map and the resulting color is // written back to the canvas image. This way we can have different // color schemes for land and water. // // In addition to this, a simple form of bump mapping is performed to // increase the illusion of height differences (see the variable // showRelief). // void TextureColorizer::colorize(ViewParams *viewParams) { QImage *origimg = viewParams->canvasImage(); const QImage *coastimg = viewParams->coastImage(); const qint64 radius = viewParams->radius(); const int imgheight = origimg->height(); const int imgwidth = origimg->width(); const int imgrx = imgwidth / 2; const int imgry = imgheight / 2; // This variable is not used anywhere.. const int imgradius = imgrx * imgrx + imgry * imgry; const uint landoffscreen = qRgb(255,0,0); // const uint seaoffscreen = qRgb(0,0,0); const uint lakeoffscreen = qRgb(0,0,0); // const uint glaciercolor = qRgb(200,200,200); int bump = 8; GpFifo emboss; emboss.buffer = 0; bool showRelief; viewParams->mapTheme()->settings()->propertyValue( "relief", showRelief ); if ( radius * radius > imgradius || viewParams->projection() == Equirectangular || viewParams->projection() == Mercator ) { int yTop = 0; int yBottom = imgheight; if( viewParams->projection() == Equirectangular || viewParams->projection() == Mercator ) { // Calculate translation of center point qreal centerLon; qreal centerLat; viewParams->centerCoordinates( centerLon, centerLat ); const float rad2Pixel = (qreal)( 2 * radius ) / M_PI; if ( viewParams->projection() == Equirectangular ) { int yCenterOffset = (int)( centerLat * rad2Pixel ); yTop = ( imgry - radius + yCenterOffset < 0)? 0 : imgry - radius + yCenterOffset; yBottom = ( imgry + yCenterOffset + radius > imgheight )? imgheight : imgry + yCenterOffset + radius; } else if ( viewParams->projection() == Mercator ) { int yCenterOffset = (int)( asinh( tan( centerLat ) ) * rad2Pixel ); yTop = ( imgry - 2 * radius + yCenterOffset < 0 ) ? 0 : imgry - 2 * radius + yCenterOffset; yBottom = ( imgry + 2 * radius + yCenterOffset > imgheight )? imgheight : imgry + 2 * radius + yCenterOffset; } } const int itEnd = yBottom; for (int y = yTop; y < itEnd; ++y) { QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ); const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ); uchar *readDataStart = origimg->scanLine( y ); const uchar *readDataEnd = readDataStart + imgwidth*4; emboss.buffer = 0; for ( uchar* readData = readDataStart; readData < readDataEnd; readData += 4, ++writeData, ++coastData ) { // Cheap Emboss / Bumpmapping uchar& grey = *readData; // qBlue(*data); if ( showRelief ) { emboss.gpuint.x4 = grey; emboss.buffer = emboss.buffer >> 8; bump = ( emboss.gpuint.x1 + 8 - grey ); if ( bump < 0 ) bump = 0; if ( bump > 15 ) bump = 15; } int alpha = qRed( *coastData ); if ( alpha == 255 || alpha == 0 ) { if ( *coastData == landoffscreen ) *writeData = texturepalette[bump][grey + 0x100]; else { if (*coastData == lakeoffscreen) *writeData = texturepalette[bump][0x055]; else { *writeData = texturepalette[bump][grey]; } } } else { qreal c = 1.0 / 255.0; if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb watercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( landcolor ) + ( 255 - alpha ) * qRed( watercolor ) ) ), (int) ( c * ( alpha * qGreen( landcolor ) + ( 255 - alpha ) * qGreen( watercolor ) ) ), (int) ( c * ( alpha * qBlue( landcolor ) + ( 255 - alpha ) * qBlue( watercolor ) ) ) ); } else { if ( qGreen( *coastData ) != 0 ) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( glaciercolor ) + ( 255 - alpha ) * qRed( landcolor ) ) ), (int) ( c * ( alpha * qGreen( glaciercolor ) + ( 255 - alpha ) * qGreen( landcolor ) ) ), (int) ( c * ( alpha * qBlue( glaciercolor ) + ( 255 - alpha ) * qBlue( landcolor ) ) ) ); } } } } } } else { int yTop = ( imgry-radius < 0 ) ? 0 : imgry-radius; const int yBottom = ( yTop == 0 ) ? imgheight : imgry + radius; for ( int y = yTop; y < yBottom; ++y ) { const int dy = imgry - y; int rx = (int)sqrt( (qreal)( radius * radius - dy * dy ) ); int xLeft = 0; int xRight = imgwidth; if ( imgrx-rx > 0 ) { xLeft = imgrx - rx; xRight = imgrx + rx; } QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ) + xLeft; const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ) + xLeft; uchar *readDataStart = origimg->scanLine( y ) + xLeft * 4; const uchar *readDataEnd = origimg->scanLine( y ) + xRight * 4; for ( uchar* readData = readDataStart; readData < readDataEnd; readData += 4, ++writeData, ++coastData ) { // Cheap Embosss / Bumpmapping uchar& grey = *readData; // qBlue(*data); if ( showRelief == true ) { emboss.buffer = emboss.buffer >> 8; emboss.gpuint.x4 = grey; bump = ( emboss.gpuint.x1 + 16 - grey ) >> 1; if ( bump > 15 ) bump = 15; if ( bump < 0 ) bump = 0; } int alpha = qRed( *coastData ); if ( alpha == 255 || alpha == 0 ) { if ( *coastData == landoffscreen ) *writeData = texturepalette[bump][grey + 0x100]; else { if (*coastData == lakeoffscreen) *writeData = texturepalette[bump][0x055]; else { *writeData = texturepalette[bump][grey]; } } } else { qreal c = 1.0 / 255.0; if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb watercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( landcolor ) + ( 255 - alpha ) * qRed( watercolor ) ) ), (int) ( c * ( alpha * qGreen( landcolor ) + ( 255 - alpha ) * qGreen( watercolor ) ) ), (int) ( c * ( alpha * qBlue( landcolor ) + ( 255 - alpha ) * qBlue( watercolor ) ) ) ); } else { if ( qGreen( *coastData ) != 0 ) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( glaciercolor ) + ( 255 - alpha ) * qRed( landcolor ) ) ), (int) ( c * ( alpha * qGreen( glaciercolor ) + ( 255 - alpha ) * qGreen( landcolor ) ) ), (int) ( c * ( alpha * qBlue( glaciercolor ) + ( 255 - alpha ) * qBlue( landcolor ) ) ) ); } } } } } } } void TextureColorizer::generatePalette(const QString& seafile, const QString& landfile) { QImage gradientImage ( 256, 3, QImage::Format_RGB32 ); QPainter gradientPainter; gradientPainter.begin( &gradientImage ); gradientPainter.setPen( Qt::NoPen ); int shadingStart = 120; QImage shadingImage ( 16, 3, QImage::Format_RGB32 ); QPainter shadingPainter; shadingPainter.begin( &shadingImage ); shadingPainter.setPen( Qt::NoPen ); int offset = 0; QStringList filelist; filelist << seafile << landfile; foreach ( const QString &filename, filelist ) { QLinearGradient gradient( 0, 0, 256, 0 ); QFile file( filename ); file.open( QIODevice::ReadOnly ); QTextStream stream( &file ); // read the data from the file QString evalstrg; while ( !stream.atEnd() ) { stream >> evalstrg; if ( !evalstrg.isEmpty() && evalstrg.contains( '=' ) ) { QString colorValue = evalstrg.left( evalstrg.indexOf( '=' ) ); QString colorPosition = evalstrg.mid( evalstrg.indexOf( '=' ) + 1 ); gradient.setColorAt( colorPosition.toDouble(), QColor( colorValue ) ); } } gradientPainter.setBrush( gradient ); gradientPainter.drawRect( 0, 0, 256, 3 ); QLinearGradient shadeGradient( - shadingStart, 0, 256 - shadingStart, 0 ); shadeGradient.setColorAt(0.00, QColor(Qt::white)); shadeGradient.setColorAt(0.15, QColor(Qt::white)); shadeGradient.setColorAt(0.75, QColor(Qt::black)); shadeGradient.setColorAt(1.00, QColor(Qt::black)); const QRgb * gradientScanLine = (QRgb*)( gradientImage.scanLine( 1 ) ); const QRgb * shadingScanLine = (QRgb*)( shadingImage.scanLine( 1 ) ); for ( int i = 0; i < 256; ++i ) { QRgb shadeColor = *(gradientScanLine + i ); shadeGradient.setColorAt(0.496, shadeColor); shadeGradient.setColorAt(0.504, shadeColor); shadingPainter.setBrush( shadeGradient ); shadingPainter.drawRect( 0, 0, 16, 3 ); // populate texturepalette[][] for ( int j = 0; j < 16; ++j ) { texturepalette[j][offset + i] = *(shadingScanLine + j ); } } offset += 256; } shadingPainter.end(); // Need to explicitly tell painter lifetime to avoid crash gradientPainter.end(); // on some systems. m_seafile = seafile; m_landfile = landfile; } <commit_msg>Simplify bool expressions, do not compare bool values with "true", just use the value.<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]>" // Copyright 2007 Inge Wallin <[email protected]>" // Copyright 2008 Carlos Licea <[email protected]> // #include "TextureColorizer.h" #include <cmath> #include <QtCore/QDebug> #include <QtCore/QFile> #include <QtCore/QString> #include <QtCore/QTime> #include <QtGui/QColor> #include <QtGui/QImage> #include <QtGui/QPainter> #include "global.h" #include "GeoSceneDocument.h" #include "GeoSceneSettings.h" #include "ViewParams.h" #include "ViewportParams.h" #include "AbstractProjection.h" #include "MathHelper.h" using namespace Marble; uint TextureColorizer::texturepalette[16][512]; TextureColorizer::TextureColorizer( const QString& seafile, const QString& landfile ) { QTime t; t.start(); generatePalette(seafile, landfile); qDebug("TextureColorizer: Time elapsed: %d ms", t.elapsed()); } QString TextureColorizer::seafile() const { return m_seafile; } QString TextureColorizer::landfile() const { return m_landfile; } // This function takes two images, both in viewParams: // - The coast image, which has a number of colors where each color // represents a sort of terrain (ex: land/sea) // - The canvas image, which has a gray scale image, often // representing a height field. // // It then uses the values of the pixels in the coast image to select // a color map. The value of the pixel in the canvas image is used as // an index into the selected color map and the resulting color is // written back to the canvas image. This way we can have different // color schemes for land and water. // // In addition to this, a simple form of bump mapping is performed to // increase the illusion of height differences (see the variable // showRelief). // void TextureColorizer::colorize(ViewParams *viewParams) { QImage *origimg = viewParams->canvasImage(); const QImage *coastimg = viewParams->coastImage(); const qint64 radius = viewParams->radius(); const int imgheight = origimg->height(); const int imgwidth = origimg->width(); const int imgrx = imgwidth / 2; const int imgry = imgheight / 2; // This variable is not used anywhere.. const int imgradius = imgrx * imgrx + imgry * imgry; const uint landoffscreen = qRgb(255,0,0); // const uint seaoffscreen = qRgb(0,0,0); const uint lakeoffscreen = qRgb(0,0,0); // const uint glaciercolor = qRgb(200,200,200); int bump = 8; GpFifo emboss; emboss.buffer = 0; bool showRelief; viewParams->mapTheme()->settings()->propertyValue( "relief", showRelief ); if ( radius * radius > imgradius || viewParams->projection() == Equirectangular || viewParams->projection() == Mercator ) { int yTop = 0; int yBottom = imgheight; if( viewParams->projection() == Equirectangular || viewParams->projection() == Mercator ) { // Calculate translation of center point qreal centerLon; qreal centerLat; viewParams->centerCoordinates( centerLon, centerLat ); const float rad2Pixel = (qreal)( 2 * radius ) / M_PI; if ( viewParams->projection() == Equirectangular ) { int yCenterOffset = (int)( centerLat * rad2Pixel ); yTop = ( imgry - radius + yCenterOffset < 0)? 0 : imgry - radius + yCenterOffset; yBottom = ( imgry + yCenterOffset + radius > imgheight )? imgheight : imgry + yCenterOffset + radius; } else if ( viewParams->projection() == Mercator ) { int yCenterOffset = (int)( asinh( tan( centerLat ) ) * rad2Pixel ); yTop = ( imgry - 2 * radius + yCenterOffset < 0 ) ? 0 : imgry - 2 * radius + yCenterOffset; yBottom = ( imgry + 2 * radius + yCenterOffset > imgheight )? imgheight : imgry + 2 * radius + yCenterOffset; } } const int itEnd = yBottom; for (int y = yTop; y < itEnd; ++y) { QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ); const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ); uchar *readDataStart = origimg->scanLine( y ); const uchar *readDataEnd = readDataStart + imgwidth*4; emboss.buffer = 0; for ( uchar* readData = readDataStart; readData < readDataEnd; readData += 4, ++writeData, ++coastData ) { // Cheap Emboss / Bumpmapping uchar& grey = *readData; // qBlue(*data); if ( showRelief ) { emboss.gpuint.x4 = grey; emboss.buffer = emboss.buffer >> 8; bump = ( emboss.gpuint.x1 + 8 - grey ); if ( bump < 0 ) bump = 0; if ( bump > 15 ) bump = 15; } int alpha = qRed( *coastData ); if ( alpha == 255 || alpha == 0 ) { if ( *coastData == landoffscreen ) *writeData = texturepalette[bump][grey + 0x100]; else { if (*coastData == lakeoffscreen) *writeData = texturepalette[bump][0x055]; else { *writeData = texturepalette[bump][grey]; } } } else { qreal c = 1.0 / 255.0; if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb watercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( landcolor ) + ( 255 - alpha ) * qRed( watercolor ) ) ), (int) ( c * ( alpha * qGreen( landcolor ) + ( 255 - alpha ) * qGreen( watercolor ) ) ), (int) ( c * ( alpha * qBlue( landcolor ) + ( 255 - alpha ) * qBlue( watercolor ) ) ) ); } else { if ( qGreen( *coastData ) != 0 ) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( glaciercolor ) + ( 255 - alpha ) * qRed( landcolor ) ) ), (int) ( c * ( alpha * qGreen( glaciercolor ) + ( 255 - alpha ) * qGreen( landcolor ) ) ), (int) ( c * ( alpha * qBlue( glaciercolor ) + ( 255 - alpha ) * qBlue( landcolor ) ) ) ); } } } } } } else { int yTop = ( imgry-radius < 0 ) ? 0 : imgry-radius; const int yBottom = ( yTop == 0 ) ? imgheight : imgry + radius; for ( int y = yTop; y < yBottom; ++y ) { const int dy = imgry - y; int rx = (int)sqrt( (qreal)( radius * radius - dy * dy ) ); int xLeft = 0; int xRight = imgwidth; if ( imgrx-rx > 0 ) { xLeft = imgrx - rx; xRight = imgrx + rx; } QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ) + xLeft; const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ) + xLeft; uchar *readDataStart = origimg->scanLine( y ) + xLeft * 4; const uchar *readDataEnd = origimg->scanLine( y ) + xRight * 4; for ( uchar* readData = readDataStart; readData < readDataEnd; readData += 4, ++writeData, ++coastData ) { // Cheap Embosss / Bumpmapping uchar& grey = *readData; // qBlue(*data); if ( showRelief ) { emboss.buffer = emboss.buffer >> 8; emboss.gpuint.x4 = grey; bump = ( emboss.gpuint.x1 + 16 - grey ) >> 1; if ( bump > 15 ) bump = 15; if ( bump < 0 ) bump = 0; } int alpha = qRed( *coastData ); if ( alpha == 255 || alpha == 0 ) { if ( *coastData == landoffscreen ) *writeData = texturepalette[bump][grey + 0x100]; else { if (*coastData == lakeoffscreen) *writeData = texturepalette[bump][0x055]; else { *writeData = texturepalette[bump][grey]; } } } else { qreal c = 1.0 / 255.0; if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb watercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( landcolor ) + ( 255 - alpha ) * qRed( watercolor ) ) ), (int) ( c * ( alpha * qGreen( landcolor ) + ( 255 - alpha ) * qGreen( watercolor ) ) ), (int) ( c * ( alpha * qBlue( landcolor ) + ( 255 - alpha ) * qBlue( watercolor ) ) ) ); } else { if ( qGreen( *coastData ) != 0 ) { QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]); QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]); *writeData = qRgb( (int) ( c * ( alpha * qRed( glaciercolor ) + ( 255 - alpha ) * qRed( landcolor ) ) ), (int) ( c * ( alpha * qGreen( glaciercolor ) + ( 255 - alpha ) * qGreen( landcolor ) ) ), (int) ( c * ( alpha * qBlue( glaciercolor ) + ( 255 - alpha ) * qBlue( landcolor ) ) ) ); } } } } } } } void TextureColorizer::generatePalette(const QString& seafile, const QString& landfile) { QImage gradientImage ( 256, 3, QImage::Format_RGB32 ); QPainter gradientPainter; gradientPainter.begin( &gradientImage ); gradientPainter.setPen( Qt::NoPen ); int shadingStart = 120; QImage shadingImage ( 16, 3, QImage::Format_RGB32 ); QPainter shadingPainter; shadingPainter.begin( &shadingImage ); shadingPainter.setPen( Qt::NoPen ); int offset = 0; QStringList filelist; filelist << seafile << landfile; foreach ( const QString &filename, filelist ) { QLinearGradient gradient( 0, 0, 256, 0 ); QFile file( filename ); file.open( QIODevice::ReadOnly ); QTextStream stream( &file ); // read the data from the file QString evalstrg; while ( !stream.atEnd() ) { stream >> evalstrg; if ( !evalstrg.isEmpty() && evalstrg.contains( '=' ) ) { QString colorValue = evalstrg.left( evalstrg.indexOf( '=' ) ); QString colorPosition = evalstrg.mid( evalstrg.indexOf( '=' ) + 1 ); gradient.setColorAt( colorPosition.toDouble(), QColor( colorValue ) ); } } gradientPainter.setBrush( gradient ); gradientPainter.drawRect( 0, 0, 256, 3 ); QLinearGradient shadeGradient( - shadingStart, 0, 256 - shadingStart, 0 ); shadeGradient.setColorAt(0.00, QColor(Qt::white)); shadeGradient.setColorAt(0.15, QColor(Qt::white)); shadeGradient.setColorAt(0.75, QColor(Qt::black)); shadeGradient.setColorAt(1.00, QColor(Qt::black)); const QRgb * gradientScanLine = (QRgb*)( gradientImage.scanLine( 1 ) ); const QRgb * shadingScanLine = (QRgb*)( shadingImage.scanLine( 1 ) ); for ( int i = 0; i < 256; ++i ) { QRgb shadeColor = *(gradientScanLine + i ); shadeGradient.setColorAt(0.496, shadeColor); shadeGradient.setColorAt(0.504, shadeColor); shadingPainter.setBrush( shadeGradient ); shadingPainter.drawRect( 0, 0, 16, 3 ); // populate texturepalette[][] for ( int j = 0; j < 16; ++j ) { texturepalette[j][offset + i] = *(shadingScanLine + j ); } } offset += 256; } shadingPainter.end(); // Need to explicitly tell painter lifetime to avoid crash gradientPainter.end(); // on some systems. m_seafile = seafile; m_landfile = landfile; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <std_msgs/Int32.h> #include <signal.h> #include <termios.h> #include <stdio.h> #define KEYCODE_RA 0x43 #define KEYCODE_LA 0x44 #define KEYCODE_UA 0x41 #define KEYCODE_DA 0x42 #define KEYCODE_Q 0x71 #define KEYCODE_W 0x77 #define KEYCODE_S 0x73 #define KEYCODE_A 0x61 #define KEYCODE_D 0x64 #define KEYCODE_T 0x74 #define KEYCODE_L 0x6C #define KEYCODE_P 0x70 #define KEYCODE_O 0x6F #define KEYCODE_I 0x69 #define KEYCODE_C 0x63 #define POSITION_MODE 0 #define ORIENTATION_MODE 1 #define PID_TUNING_MODE 2 #define WAITING 0 #define TAKE_OFF 1 #define POS_CTRL 2 #define LAND 3 #define EMERGENCY 4 #define Z_TUNE 5 #define Y_TUNE 6 #define X_TUNE 7 #define CALIBRATE 8 #define KP_Z_INIT 250000.0 #define KI_Z_INIT 0.0 #define KD_Z_INIT 200000.0 #define KP_Z_OFFSET 1000.0 #define KI_Z_OFFSET 100.0 #define KD_Z_OFFSET 1000.0 #define KP_XY_INIT 0.0 #define KI_XY_INIT 0.0 #define KD_XY_INIT 0.0 #define KP_XY_OFFSET 1.0 #define KI_XY_OFFSET 1.0 #define KD_XY_OFFSET 1.0 using namespace geometry_msgs; using namespace std; class TeleopCrazyflie { public: TeleopCrazyflie(); void keyLoop(); private: ros::NodeHandle nh_; double roll, pitch, yawrate, thrust, goal_x, goal_y, goal_z, kp, ki, kd; int mode, state, tune_param, prev_tune_param; ros::Publisher vel_pub_, cmd_pub_, state_pub_; }; TeleopCrazyflie::TeleopCrazyflie(): roll(0.0), pitch(0.0), yawrate(0.0), thrust(32767.0), mode(ORIENTATION_MODE), state(WAITING), goal_x(0.0), goal_y(0.0), goal_z(0.15), kp(KP_Z_INIT), kd(KD_Z_INIT), ki(KI_Z_INIT), tune_param(Z_TUNE), prev_tune_param(Z_TUNE) { vel_pub_ = nh_.advertise<geometry_msgs::Twist>("crazyflie/deep_learning/cmd_vel", 1); state_pub_ = nh_.advertise<std_msgs::Int32>("crazyflie/deep_learning/cmd_state", 1); cmd_pub_ = nh_.advertise<geometry_msgs::Twist>("crazyflie/deep_learning/cmd_pos", 1); } int kfd = 0; struct termios cooked, raw; void quit(int sig) { tcsetattr(kfd, TCSANOW, &cooked); ros::shutdown(); exit(0); } int main(int argc, char** argv) { ros::init(argc, argv, "crazyflie_teleop_node"); TeleopCrazyflie teleop_crazyflie; signal(SIGINT,quit); teleop_crazyflie.keyLoop(); return(0); } void TeleopCrazyflie::keyLoop() { char c; bool dirty=false; // get the console in raw mode tcgetattr(kfd, &cooked); memcpy(&raw, &cooked, sizeof(struct termios)); raw.c_lflag &=~ (ICANON | ECHO); // Setting a new line, then end of file raw.c_cc[VEOL] = 1; raw.c_cc[VEOF] = 2; tcsetattr(kfd, TCSANOW, &raw); double thrust_offset,roll_offset,pitch_offset,yawrate_offset; double goal_x_offset,goal_y_offset,goal_z_offset; double kp_offset, kd_offset, ki_offset; puts("Reading from keyboard"); puts("---------------------------"); puts("Use arrow keys to move the crazyflie."); puts("P - Position Mode"); puts("O - Orientation Mode"); puts("I - PID Tuning Mode"); puts("C - Calibrate"); for(;;) { // get the next event from the keyboard if(read(kfd, &c, 1) < 0) { perror("read():"); exit(-1); } ROS_INFO("value: 0x%02X\n", c); thrust_offset = 1000 ; roll_offset = 1.0; yawrate_offset = 1.0; pitch_offset = 1.0; goal_z_offset = 0.05; goal_y_offset = 0.05; goal_x_offset = 0.05; kp_offset = KP_Z_OFFSET; kd_offset = KD_Z_OFFSET; ki_offset = KI_Z_OFFSET; if( tune_param == X_TUNE || tune_param == Y_TUNE) { kp_offset = KP_XY_OFFSET; kd_offset = KD_XY_OFFSET; ki_offset = KI_XY_OFFSET; } //ros::Duration(0.05).sleep(); switch(c) { case KEYCODE_T: ROS_INFO("TAKING OFF"); if(mode == POSITION_MODE) state = TAKE_OFF; else ROS_INFO("To Take Off, Enable Position Mode"); dirty = true; break; case KEYCODE_C: ROS_INFO("CALIBRATE"); state = CALIBRATE; dirty = true; break; case KEYCODE_L: ROS_INFO("LAND"); if(mode == POSITION_MODE) state = LAND; else ROS_INFO("To Land, Enable Position Mode"); dirty = true; break; case KEYCODE_P: ROS_INFO("POSITION MODE"); mode = POSITION_MODE; state = WAITING; dirty = true; break; case KEYCODE_O: ROS_INFO("ORIENTATION MODE"); state = WAITING; mode = ORIENTATION_MODE; dirty = true; break; case KEYCODE_I: ROS_INFO("PID TUNING MODE"); mode = PID_TUNING_MODE; state = tune_param; goal_x = 0.0; goal_y = 0.0; goal_z = 0.2; dirty = true; break; case KEYCODE_Q: ROS_INFO("STOP"); state = EMERGENCY; thrust = 0; roll = 0; pitch = 0; yawrate = 0; dirty = true; break; case KEYCODE_LA: ROS_DEBUG("LEFT"); if(mode == ORIENTATION_MODE) roll -= roll_offset; else if(mode == POSITION_MODE) goal_y -= goal_y_offset; else kd -= kd_offset; dirty = true; break; case KEYCODE_RA: ROS_DEBUG("RIGHT"); if(mode == ORIENTATION_MODE) roll += roll_offset; else if(mode == POSITION_MODE) goal_y += goal_y_offset; else kd += kd_offset; dirty = true; break; case KEYCODE_UA: ROS_DEBUG("UP"); if(mode == ORIENTATION_MODE) pitch += pitch_offset; else if(mode == POSITION_MODE) goal_x += goal_x_offset; else kp += kp_offset; dirty = true; break; case KEYCODE_DA: ROS_DEBUG("DOWN"); if(mode == ORIENTATION_MODE) pitch -= pitch_offset; else if(mode == POSITION_MODE) goal_x -= goal_x_offset; else kp -= kp_offset; dirty = true; break; case KEYCODE_A: ROS_DEBUG("LEFT_A"); yawrate -= yawrate_offset; if(mode == PID_TUNING_MODE) { if(tune_param == Z_TUNE) tune_param = Z_TUNE; else tune_param= tune_param-1; state = tune_param; if(tune_param != prev_tune_param ) { if(tune_param == Z_TUNE) { kp = KP_Z_INIT; kd = KD_Z_INIT; ki = KI_Z_INIT; } if(tune_param == X_TUNE || tune_param == Y_TUNE) { kp = KP_XY_INIT; kd = KD_XY_INIT; ki = KI_XY_INIT; } } prev_tune_param = tune_param; } break; dirty = true; case KEYCODE_D: ROS_DEBUG("RIGHT_D"); yawrate += yawrate_offset; if(mode == PID_TUNING_MODE) { if(tune_param == X_TUNE) tune_param = X_TUNE; else tune_param = tune_param + 1; state = tune_param; if(tune_param != prev_tune_param ) { if(tune_param == Z_TUNE) { kp = KP_Z_INIT; kd = KD_Z_INIT; ki = KI_Z_INIT; } if(tune_param == X_TUNE || tune_param == Y_TUNE) { kp = KP_XY_INIT; kd = KD_XY_INIT; ki = KI_XY_INIT; } } prev_tune_param = tune_param; } dirty = true; break; case KEYCODE_W: ROS_DEBUG("UP_W"); if(mode == ORIENTATION_MODE) thrust += thrust_offset; else if(mode == POSITION_MODE) goal_z += goal_z_offset; else ki += ki_offset; dirty = true; break; case KEYCODE_S: ROS_DEBUG("DOWN_S"); if(mode == ORIENTATION_MODE) thrust -= thrust_offset; else if(mode == POSITION_MODE) goal_z -= goal_z_offset; else ki -= ki_offset; dirty = true; break; } geometry_msgs::Twist twist; std_msgs::Int32 state_msg; twist.angular.y = yawrate; if(mode == ORIENTATION_MODE) { twist.linear.z = thrust; twist.linear.x = pitch; twist.linear.y = roll; } else { twist.linear.z = goal_z; twist.linear.x = goal_x; twist.linear.y = goal_y; if(mode == PID_TUNING_MODE) { twist.angular.x = kp; twist.angular.y = ki; twist.angular.z = kd; } } if(dirty ==true) { thrust_offset = 0.0; roll_offset = 0.0; yawrate_offset = 0.0; pitch_offset = 0.0; goal_x_offset = 0.0; goal_y_offset = 0.0; goal_z_offset = 0.0; kp_offset = 0.0; kd_offset = 0.0; ki_offset = 0.0; dirty=false; } if(mode == ORIENTATION_MODE) { vel_pub_.publish(twist); } else { cmd_pub_.publish(twist); } state_msg.data = state; state_pub_.publish(state_msg); if(mode == POSITION_MODE) ROS_INFO("X - %f, Y - %f ,Z - %f,yawrate - %f", goal_x ,goal_y, goal_z,yawrate); else if(mode == ORIENTATION_MODE) ROS_INFO("Thrust - %f, roll - %f ,pitch - %f,yawrate - %f",thrust,roll,pitch,yawrate); else ROS_INFO("Tune Param = %d, Kp - %f, Ki - %f , Kd - %f",tune_param,kp,ki,kd); } return; } <commit_msg>Make sure teleop node doesn't publish cmd during Calibration<commit_after>#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <std_msgs/Int32.h> #include <signal.h> #include <termios.h> #include <stdio.h> #define KEYCODE_RA 0x43 #define KEYCODE_LA 0x44 #define KEYCODE_UA 0x41 #define KEYCODE_DA 0x42 #define KEYCODE_Q 0x71 #define KEYCODE_W 0x77 #define KEYCODE_S 0x73 #define KEYCODE_A 0x61 #define KEYCODE_D 0x64 #define KEYCODE_T 0x74 #define KEYCODE_L 0x6C #define KEYCODE_P 0x70 #define KEYCODE_O 0x6F #define KEYCODE_I 0x69 #define KEYCODE_C 0x63 #define POSITION_MODE 0 #define ORIENTATION_MODE 1 #define PID_TUNING_MODE 2 #define WAITING 0 #define TAKE_OFF 1 #define POS_CTRL 2 #define LAND 3 #define EMERGENCY 4 #define Z_TUNE 5 #define Y_TUNE 6 #define X_TUNE 7 #define CALIBRATE 8 #define KP_Z_INIT 250000.0 #define KI_Z_INIT 0.0 #define KD_Z_INIT 200000.0 #define KP_Z_OFFSET 1000.0 #define KI_Z_OFFSET 100.0 #define KD_Z_OFFSET 1000.0 #define KP_XY_INIT 0.0 #define KI_XY_INIT 0.0 #define KD_XY_INIT 0.0 #define KP_XY_OFFSET 0.05 #define KI_XY_OFFSET 0.05 #define KD_XY_OFFSET 0.05 using namespace geometry_msgs; using namespace std; class TeleopCrazyflie { public: TeleopCrazyflie(); void keyLoop(); private: ros::NodeHandle nh_; double roll, pitch, yawrate, thrust, goal_x, goal_y, goal_z, kp, ki, kd; int mode, state, tune_param, prev_tune_param; ros::Publisher vel_pub_, cmd_pub_, state_pub_; }; TeleopCrazyflie::TeleopCrazyflie(): roll(0.0), pitch(0.0), yawrate(0.0), thrust(32767.0), mode(ORIENTATION_MODE), state(WAITING), goal_x(0.0), goal_y(0.0), goal_z(0.15), kp(KP_Z_INIT), kd(KD_Z_INIT), ki(KI_Z_INIT), tune_param(Z_TUNE), prev_tune_param(Z_TUNE) { vel_pub_ = nh_.advertise<geometry_msgs::Twist>("crazyflie/deep_learning/cmd_vel", 1); state_pub_ = nh_.advertise<std_msgs::Int32>("crazyflie/deep_learning/cmd_state", 1); cmd_pub_ = nh_.advertise<geometry_msgs::Twist>("crazyflie/deep_learning/cmd_pos", 1); } int kfd = 0; struct termios cooked, raw; void quit(int sig) { tcsetattr(kfd, TCSANOW, &cooked); ros::shutdown(); exit(0); } int main(int argc, char** argv) { ros::init(argc, argv, "crazyflie_teleop_node"); TeleopCrazyflie teleop_crazyflie; signal(SIGINT,quit); teleop_crazyflie.keyLoop(); return(0); } void TeleopCrazyflie::keyLoop() { char c; bool dirty=false; // get the console in raw mode tcgetattr(kfd, &cooked); memcpy(&raw, &cooked, sizeof(struct termios)); raw.c_lflag &=~ (ICANON | ECHO); // Setting a new line, then end of file raw.c_cc[VEOL] = 1; raw.c_cc[VEOF] = 2; tcsetattr(kfd, TCSANOW, &raw); double thrust_offset,roll_offset,pitch_offset,yawrate_offset; double goal_x_offset,goal_y_offset,goal_z_offset; double kp_offset, kd_offset, ki_offset; puts("Reading from keyboard"); puts("---------------------------"); puts("Use arrow keys to move the crazyflie."); puts("P - Position Mode"); puts("O - Orientation Mode"); puts("I - PID Tuning Mode"); puts("C - Calibrate"); for(;;) { // get the next event from the keyboard if(read(kfd, &c, 1) < 0) { perror("read():"); exit(-1); } ROS_INFO("value: 0x%02X\n", c); thrust_offset = 1000 ; roll_offset = 1.0; yawrate_offset = 1.0; pitch_offset = 1.0; goal_z_offset = 0.05; goal_y_offset = 0.05; goal_x_offset = 0.05; kp_offset = KP_Z_OFFSET; kd_offset = KD_Z_OFFSET; ki_offset = KI_Z_OFFSET; if( tune_param == X_TUNE || tune_param == Y_TUNE) { kp_offset = KP_XY_OFFSET; kd_offset = KD_XY_OFFSET; ki_offset = KI_XY_OFFSET; } //ros::Duration(0.05).sleep(); switch(c) { case KEYCODE_T: ROS_INFO("TAKING OFF"); if(mode == POSITION_MODE) state = TAKE_OFF; else ROS_INFO("To Take Off, Enable Position Mode"); dirty = true; break; case KEYCODE_C: ROS_INFO("CALIBRATE"); state = CALIBRATE; dirty = true; break; case KEYCODE_L: ROS_INFO("LAND"); if(mode == POSITION_MODE) state = LAND; else ROS_INFO("To Land, Enable Position Mode"); dirty = true; break; case KEYCODE_P: ROS_INFO("POSITION MODE"); mode = POSITION_MODE; state = WAITING; dirty = true; break; case KEYCODE_O: ROS_INFO("ORIENTATION MODE"); state = WAITING; mode = ORIENTATION_MODE; dirty = true; break; case KEYCODE_I: ROS_INFO("PID TUNING MODE"); mode = PID_TUNING_MODE; state = tune_param; goal_x = 0.0; goal_y = 0.0; goal_z = 0.2; dirty = true; break; case KEYCODE_Q: ROS_INFO("STOP"); state = EMERGENCY; thrust = 0; roll = 0; pitch = 0; yawrate = 0; dirty = true; break; case KEYCODE_LA: ROS_DEBUG("LEFT"); if(mode == ORIENTATION_MODE) roll -= roll_offset; else if(mode == POSITION_MODE) goal_y -= goal_y_offset; else kd -= kd_offset; dirty = true; break; case KEYCODE_RA: ROS_DEBUG("RIGHT"); if(mode == ORIENTATION_MODE) roll += roll_offset; else if(mode == POSITION_MODE) goal_y += goal_y_offset; else kd += kd_offset; dirty = true; break; case KEYCODE_UA: ROS_DEBUG("UP"); if(mode == ORIENTATION_MODE) pitch += pitch_offset; else if(mode == POSITION_MODE) goal_x += goal_x_offset; else kp += kp_offset; dirty = true; break; case KEYCODE_DA: ROS_DEBUG("DOWN"); if(mode == ORIENTATION_MODE) pitch -= pitch_offset; else if(mode == POSITION_MODE) goal_x -= goal_x_offset; else kp -= kp_offset; dirty = true; break; case KEYCODE_A: ROS_DEBUG("LEFT_A"); yawrate -= yawrate_offset; if(mode == PID_TUNING_MODE) { if(tune_param == Z_TUNE) tune_param = Z_TUNE; else tune_param= tune_param-1; state = tune_param; if(tune_param != prev_tune_param ) { if(tune_param == Z_TUNE) { kp = KP_Z_INIT; kd = KD_Z_INIT; ki = KI_Z_INIT; } if(tune_param == X_TUNE || tune_param == Y_TUNE) { kp = KP_XY_INIT; kd = KD_XY_INIT; ki = KI_XY_INIT; } } prev_tune_param = tune_param; } break; dirty = true; case KEYCODE_D: ROS_DEBUG("RIGHT_D"); yawrate += yawrate_offset; if(mode == PID_TUNING_MODE) { if(tune_param == X_TUNE) tune_param = X_TUNE; else tune_param = tune_param + 1; state = tune_param; if(tune_param != prev_tune_param ) { if(tune_param == Z_TUNE) { kp = KP_Z_INIT; kd = KD_Z_INIT; ki = KI_Z_INIT; } if(tune_param == X_TUNE || tune_param == Y_TUNE) { kp = KP_XY_INIT; kd = KD_XY_INIT; ki = KI_XY_INIT; } } prev_tune_param = tune_param; } dirty = true; break; case KEYCODE_W: ROS_DEBUG("UP_W"); if(mode == ORIENTATION_MODE) thrust += thrust_offset; else if(mode == POSITION_MODE) goal_z += goal_z_offset; else ki += ki_offset; dirty = true; break; case KEYCODE_S: ROS_DEBUG("DOWN_S"); if(mode == ORIENTATION_MODE) thrust -= thrust_offset; else if(mode == POSITION_MODE) goal_z -= goal_z_offset; else ki -= ki_offset; dirty = true; break; } geometry_msgs::Twist twist; std_msgs::Int32 state_msg; twist.angular.y = yawrate; if(mode == ORIENTATION_MODE) { twist.linear.z = thrust; twist.linear.x = pitch; twist.linear.y = roll; } else { twist.linear.z = goal_z; twist.linear.x = goal_x; twist.linear.y = goal_y; if(mode == PID_TUNING_MODE) { twist.angular.x = kp; twist.angular.y = ki; twist.angular.z = kd; } } if(dirty ==true) { thrust_offset = 0.0; roll_offset = 0.0; yawrate_offset = 0.0; pitch_offset = 0.0; goal_x_offset = 0.0; goal_y_offset = 0.0; goal_z_offset = 0.0; kp_offset = 0.0; kd_offset = 0.0; ki_offset = 0.0; dirty=false; } state_msg.data = state; state_pub_.publish(state_msg); if(state!= CALIBRATE) { if(mode == ORIENTATION_MODE) { vel_pub_.publish(twist); } else { cmd_pub_.publish(twist); } if(mode == POSITION_MODE) ROS_INFO("X - %f, Y - %f ,Z - %f,yawrate - %f", goal_x ,goal_y, goal_z,yawrate); else if(mode == ORIENTATION_MODE) ROS_INFO("Thrust - %f, roll - %f ,pitch - %f,yawrate - %f",thrust,roll,pitch,yawrate); else ROS_INFO("Tune Param = %d, Kp - %f, Ki - %f , Kd - %f",tune_param,kp,ki,kd); } } return; } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #include "search_snippet.h" #include "miscutil.h" #include "encode.h" #include <iostream> using sp::miscutil; using sp::encode; namespace seeks_plugins { search_snippet::search_snippet() :_rank(0),_seeks_ir(0.0),_seeks_rank(0),_doc_type(WEBPAGE) { } search_snippet::search_snippet(const short &rank) :_rank(rank),_seeks_ir(0.0),_seeks_rank(0),_doc_type(WEBPAGE) { } search_snippet::~search_snippet() { } void search_snippet::highlight_query(std::vector<std::string> &words, std::string &str) { if (words.empty()) return; // sort words by size. std::sort(words.begin(),words.end(),std::greater<std::string>()); // surround every of those words appearing within the // argument string with <b> </b> for html // bold format. TODO: green ? for (size_t i=0;i<words.size();i++) { if (words.at(i).length() > 2) { std::string bold_str = "<b>" + words.at(i) + "</b>"; miscutil::ci_replace_in_string(str,words.at(i),bold_str); } } } std::ostream& search_snippet::print(std::ostream &output) { output << "-----------------------------------\n"; output << "- seeks rank: " << _seeks_rank << std::endl; output << "- rank: " << _rank << std::endl; output << "- title: " << _title << std::endl; output << "- url: " << _url << std::endl; output << "- cite: " << _cite << std::endl; output << "- cached: " << _cached << std::endl; output << "- summary: " << _summary << std::endl; output << "- file format: " << _file_format << std::endl; output << "- date: " << _date << std::endl; output << "- lang: " << _lang << std::endl; if (_doc_type == FORUM) output << "- forum thread info: " << _forum_thread_info << std::endl; output << "-----------------------------------\n"; return output; } std::string search_snippet::to_html() const { std::vector<std::string> words; return to_html_with_highlight(words); } std::string search_snippet::to_html_with_highlight(std::vector<std::string> &words) const { static std::string se_icon = "<img src=\"icon.png\" alt=\"icon\" width=\"12\" height=\"12\" hspace=\"2\" vspace=\"0\" align=\"\" border=\"0\" />"; std::string html_content = "<li><h3><a href=\""; html_content += _url; html_content += "\" class=\"l\"><em>"; const char *title_enc = encode::html_encode(_title.c_str()); html_content += title_enc; free_const(title_enc); html_content += "</em></a>"; if (_engine.to_ulong()&SE_GOOGLE) { std::string ggle_se_icon = se_icon; miscutil::replace_in_string(ggle_se_icon,"icon","seeks_wb_google"); miscutil::replace_in_string(ggle_se_icon,"hspace=\"2\"","hspace=\"5\""); html_content += ggle_se_icon; } if (_engine.to_ulong()&SE_CUIL) { std::string cuil_se_icon = se_icon; miscutil::replace_in_string(cuil_se_icon,"icon","seeks_wb_cuil"); html_content += cuil_se_icon; } if (_engine.to_ulong()&SE_BING) { std::string bing_se_icon = se_icon; miscutil::replace_in_string(bing_se_icon,"icon","seeks_wb_bing"); html_content += bing_se_icon; } html_content += "</h3>"; if (_summary != "") { html_content += "<div>"; std::string summary = _summary; search_snippet::highlight_query(words,summary); html_content += summary; } else html_content += "<div>"; if (_cite != "") { const char *cite_enc = encode::html_encode(_cite.c_str()); html_content += "<br><cite>"; html_content += cite_enc; free_const(cite_enc); html_content += "</cite>"; } if (!_cached.empty()) { html_content += "<span class=\"gl\"><a href=\""; html_content += _cached; html_content += " \">Cached</a></span>"; } else if (!_archive.empty()) { html_content += _archive; html_content += " \">Archive</a></span>"; } html_content += "</div></li>\n"; /* std::cout << "html_content:\n"; std::cout << html_content << std::endl; */ return html_content; } void search_snippet::set_url(const std::string &url) { // decode url. char* str = encode::url_decode(url.c_str()); _url = std::string(str); free(str); } void search_snippet::set_url(const char *url) { // decode url. char *str = encode::url_decode(url); _url = std::string(str); free(str); } void search_snippet::set_summary(const char *summary) { // encode html so tags are not interpreted. char* str = encode::html_encode(summary); _summary = std::string(str); free(str); } void search_snippet::set_summary(const std::string &summary) { // encode html so tags are not interpreted. char* str = encode::html_encode(summary.c_str()); _summary = std::string(str); free(str); } void search_snippet::set_archive_link() { if (_cached.empty()) _archive = "http://web.archive.org/web/*/" + _url; } // static. void search_snippet::delete_snippets(std::vector<search_snippet*> &snippets) { size_t snippets_size = snippets.size(); for (size_t i=0;i<snippets_size; i++) delete snippets.at(i); snippets.clear(); } void search_snippet::merge_snippets(search_snippet *s1, const search_snippet *s2) { // seeks_rank is updated after merging. // search engine rank. s1->_rank = std::min(s1->_rank,s2->_rank); // search engine. s1->_engine |= s2->_engine; // cached link. if (s1->_cached.empty()) s1->_cached = s2->_cached; // summary. if (s1->_summary.length() < s2->_summary.length()) s1->_summary = s2->_summary; // file format. if (s1->_file_format.length() < s2->_file_format.length()) // we could do better here, ok enough for now. s1->_file_format = s2->_file_format; } } /* end of namespace. */ <commit_msg>fixed archive link rendering<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2009 Emmanuel Benazera, [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **/ #include "search_snippet.h" #include "miscutil.h" #include "encode.h" #include <iostream> using sp::miscutil; using sp::encode; namespace seeks_plugins { search_snippet::search_snippet() :_rank(0),_seeks_ir(0.0),_seeks_rank(0),_doc_type(WEBPAGE) { } search_snippet::search_snippet(const short &rank) :_rank(rank),_seeks_ir(0.0),_seeks_rank(0),_doc_type(WEBPAGE) { } search_snippet::~search_snippet() { } void search_snippet::highlight_query(std::vector<std::string> &words, std::string &str) { if (words.empty()) return; // sort words by size. std::sort(words.begin(),words.end(),std::greater<std::string>()); // surround every of those words appearing within the // argument string with <b> </b> for html // bold format. TODO: green ? for (size_t i=0;i<words.size();i++) { if (words.at(i).length() > 2) { std::string bold_str = "<b>" + words.at(i) + "</b>"; miscutil::ci_replace_in_string(str,words.at(i),bold_str); } } } std::ostream& search_snippet::print(std::ostream &output) { output << "-----------------------------------\n"; output << "- seeks rank: " << _seeks_rank << std::endl; output << "- rank: " << _rank << std::endl; output << "- title: " << _title << std::endl; output << "- url: " << _url << std::endl; output << "- cite: " << _cite << std::endl; output << "- cached: " << _cached << std::endl; output << "- summary: " << _summary << std::endl; output << "- file format: " << _file_format << std::endl; output << "- date: " << _date << std::endl; output << "- lang: " << _lang << std::endl; if (_doc_type == FORUM) output << "- forum thread info: " << _forum_thread_info << std::endl; output << "-----------------------------------\n"; return output; } std::string search_snippet::to_html() const { std::vector<std::string> words; return to_html_with_highlight(words); } std::string search_snippet::to_html_with_highlight(std::vector<std::string> &words) const { static std::string se_icon = "<img src=\"icon.png\" alt=\"icon\" width=\"12\" height=\"12\" hspace=\"2\" vspace=\"0\" align=\"\" border=\"0\" />"; std::string html_content = "<li><h3><a href=\""; html_content += _url; html_content += "\" class=\"l\"><em>"; const char *title_enc = encode::html_encode(_title.c_str()); html_content += title_enc; free_const(title_enc); html_content += "</em></a>"; if (_engine.to_ulong()&SE_GOOGLE) { std::string ggle_se_icon = se_icon; miscutil::replace_in_string(ggle_se_icon,"icon","seeks_wb_google"); miscutil::replace_in_string(ggle_se_icon,"hspace=\"2\"","hspace=\"5\""); html_content += ggle_se_icon; } if (_engine.to_ulong()&SE_CUIL) { std::string cuil_se_icon = se_icon; miscutil::replace_in_string(cuil_se_icon,"icon","seeks_wb_cuil"); html_content += cuil_se_icon; } if (_engine.to_ulong()&SE_BING) { std::string bing_se_icon = se_icon; miscutil::replace_in_string(bing_se_icon,"icon","seeks_wb_bing"); html_content += bing_se_icon; } html_content += "</h3>"; if (_summary != "") { html_content += "<div>"; std::string summary = _summary; search_snippet::highlight_query(words,summary); html_content += summary; } else html_content += "<div>"; if (_cite != "") { const char *cite_enc = encode::html_encode(_cite.c_str()); html_content += "<br><cite>"; html_content += cite_enc; free_const(cite_enc); html_content += "</cite>"; } if (!_cached.empty()) { html_content += "<span class=\"gl\"><a href=\""; html_content += _cached; html_content += " \">Cached</a></span>"; } else if (!_archive.empty()) { html_content += "<span class=\"gl\"><a href=\""; html_content += _archive; html_content += " \">Archive</a></span>"; } html_content += "</div></li>\n"; /* std::cout << "html_content:\n"; std::cout << html_content << std::endl; */ return html_content; } void search_snippet::set_url(const std::string &url) { // decode url. char* str = encode::url_decode(url.c_str()); _url = std::string(str); free(str); } void search_snippet::set_url(const char *url) { // decode url. char *str = encode::url_decode(url); _url = std::string(str); free(str); } void search_snippet::set_summary(const char *summary) { // encode html so tags are not interpreted. char* str = encode::html_encode(summary); _summary = std::string(str); free(str); } void search_snippet::set_summary(const std::string &summary) { // encode html so tags are not interpreted. char* str = encode::html_encode(summary.c_str()); _summary = std::string(str); free(str); } void search_snippet::set_archive_link() { if (_cached.empty()) _archive = "http://web.archive.org/web/*/" + _url; } // static. void search_snippet::delete_snippets(std::vector<search_snippet*> &snippets) { size_t snippets_size = snippets.size(); for (size_t i=0;i<snippets_size; i++) delete snippets.at(i); snippets.clear(); } void search_snippet::merge_snippets(search_snippet *s1, const search_snippet *s2) { // seeks_rank is updated after merging. // search engine rank. s1->_rank = std::min(s1->_rank,s2->_rank); // search engine. s1->_engine |= s2->_engine; // cached link. if (s1->_cached.empty()) s1->_cached = s2->_cached; // summary. if (s1->_summary.length() < s2->_summary.length()) s1->_summary = s2->_summary; // file format. if (s1->_file_format.length() < s2->_file_format.length()) // we could do better here, ok enough for now. s1->_file_format = s2->_file_format; } } /* end of namespace. */ <|endoftext|>
<commit_before>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for writing to a Windows console // i.e. cmd.exe. // // Axel Naumann <[email protected]>, 2011-05-12 //===----------------------------------------------------------------------===// #ifdef _WIN32 #include "textinput/TerminalDisplayWin.h" #include "textinput/Color.h" #include <assert.h> #ifdef UNICODE #define filename L"CONOUT$" #else #define filename "CONOUT$" #endif namespace textinput { TerminalDisplayWin::TerminalDisplayWin(): TerminalDisplay(false), fStartLine(0), fIsAttached(false), fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) { DWORD mode; SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0); fOut = ::GetStdHandle(STD_OUTPUT_HANDLE); bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0; if (!isConsole) { // Prevent redirection from stealing our console handle, // simply open our own. fOut = ::CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); ::GetConsoleMode(fOut, &fOldMode); } else { // disable unicode (UTF-8) for the time being, since it causes // problems on Windows 10 //::SetConsoleOutputCP(65001); // Force UTF-8 output } CONSOLE_SCREEN_BUFFER_INFO csbi; ::GetConsoleScreenBufferInfo(fOut, &csbi); fDefaultAttributes = csbi.wAttributes; assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken"); fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT; HandleResizeEvent(); } #undef filename TerminalDisplayWin::~TerminalDisplayWin() { if (fDefaultAttributes) { ::SetConsoleTextAttribute(fOut, fDefaultAttributes); // We allocated CONOUT$: CloseHandle(fOut); } ::SetConsoleOutputCP(fOldCodePage); } void TerminalDisplayWin::HandleResizeEvent() { if (IsTTY()) { CONSOLE_SCREEN_BUFFER_INFO Info; if (!::GetConsoleScreenBufferInfo(fOut, &Info)) { ShowError("resize / getting console info"); return; } SetWidth(Info.dwSize.X); } } void TerminalDisplayWin::SetColor(char CIdx, const Color& C) { WORD Attribs = 0; // There is no underline since DOS has died. if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY; if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY; if (C.fR > 64) Attribs |= FOREGROUND_RED; if (C.fG > 64) Attribs |= FOREGROUND_GREEN; if (C.fB > 64) Attribs |= FOREGROUND_BLUE; // if CIdx is 0 (default) then use the original console text color // (instead of the greyish one) if (CIdx == 0) ::SetConsoleTextAttribute(fOut, fDefaultAttributes); else ::SetConsoleTextAttribute(fOut, Attribs); } void TerminalDisplayWin::CheckCursorPos() { if (!IsTTY()) return; // Did something print something on the screen? // I.e. did the cursor move? CONSOLE_SCREEN_BUFFER_INFO CSI; if (::GetConsoleScreenBufferInfo(fOut, &CSI)) { if (CSI.dwCursorPosition.X != fWritePos.fCol || CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) { fStartLine = CSI.dwCursorPosition.Y; if (CSI.dwCursorPosition.X) { // fStartLine may be a couple of lines higher (or more precisely // the number of written lines higher) fStartLine -= fWritePos.fLine; } fWritePos.fCol = 0; fWritePos.fLine = 0; } } } void TerminalDisplayWin::Move(Pos P) { CheckCursorPos(); MoveInternal(P); fWritePos = P; } void TerminalDisplayWin::MoveInternal(Pos P) { if (IsTTY()) { COORD C = {P.fCol, P.fLine + fStartLine}; ::SetConsoleCursorPosition(fOut, C); } } void TerminalDisplayWin::MoveFront() { Pos P(fWritePos); P.fCol = 0; MoveInternal(P); } void TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) { Pos P(fWritePos); --P.fLine; MoveInternal(P); } void TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) { Pos P(fWritePos); ++P.fLine; MoveInternal(P); } void TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) { Pos P(fWritePos); ++P.fCol; MoveInternal(P); } void TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) { Pos P(fWritePos); --P.fCol; MoveInternal(P); } void TerminalDisplayWin::EraseToRight() { DWORD NumWritten; COORD C = {fWritePos.fCol, fWritePos.fLine + fStartLine}; ::FillConsoleOutputCharacter(fOut, ' ', GetWidth() - C.X, C, &NumWritten); // It wraps, so move up and reset WritePos: //MoveUp(); //++WritePos.Line; } void TerminalDisplayWin::WriteRawString(const char *text, size_t len) { DWORD NumWritten = 0; if (IsTTY()) { WriteConsole(fOut, text, (DWORD) len, &NumWritten, NULL); } else { WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL); } if (NumWritten != len) { ShowError("writing to output"); } } void TerminalDisplayWin::Attach() { // set to noecho if (fIsAttached || !IsTTY()) return; if (!::SetConsoleMode(fOut, fMyMode)) { ShowError("attaching to console output"); } CONSOLE_SCREEN_BUFFER_INFO Info; if (!::GetConsoleScreenBufferInfo(fOut, &Info)) { ShowError("attaching / getting console info"); } else { fStartLine = Info.dwCursorPosition.Y; if (Info.dwCursorPosition.X) { // Whooa - where are we?! Newline and cross fingers: WriteRawString("\n", 1); ++fStartLine; } } fIsAttached = true; } void TerminalDisplayWin::Detach() { if (!fIsAttached || !IsTTY()) return; if (!SetConsoleMode(fOut, fOldMode)) { ShowError("detaching to console output"); } TerminalDisplay::Detach(); fIsAttached = false; } void TerminalDisplayWin::ShowError(const char* Where) const { DWORD Err = GetLastError(); LPVOID MsgBuf = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &MsgBuf, 0, NULL); printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, MsgBuf); LocalFree(MsgBuf); } } #endif // ifdef _WIN32 <commit_msg>text input: fix windows warnings<commit_after>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for writing to a Windows console // i.e. cmd.exe. // // Axel Naumann <[email protected]>, 2011-05-12 //===----------------------------------------------------------------------===// #ifdef _WIN32 #include "textinput/TerminalDisplayWin.h" #include "textinput/Color.h" #include <assert.h> #ifdef UNICODE #define filename L"CONOUT$" #else #define filename "CONOUT$" #endif namespace textinput { TerminalDisplayWin::TerminalDisplayWin(): TerminalDisplay(false), fStartLine(0), fIsAttached(false), fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) { DWORD mode; SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0); fOut = ::GetStdHandle(STD_OUTPUT_HANDLE); bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0; if (!isConsole) { // Prevent redirection from stealing our console handle, // simply open our own. fOut = ::CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); ::GetConsoleMode(fOut, &fOldMode); } else { // disable unicode (UTF-8) for the time being, since it causes // problems on Windows 10 //::SetConsoleOutputCP(65001); // Force UTF-8 output } CONSOLE_SCREEN_BUFFER_INFO csbi; ::GetConsoleScreenBufferInfo(fOut, &csbi); fDefaultAttributes = csbi.wAttributes; assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken"); fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT; HandleResizeEvent(); } #undef filename TerminalDisplayWin::~TerminalDisplayWin() { if (fDefaultAttributes) { ::SetConsoleTextAttribute(fOut, fDefaultAttributes); // We allocated CONOUT$: CloseHandle(fOut); } ::SetConsoleOutputCP(fOldCodePage); } void TerminalDisplayWin::HandleResizeEvent() { if (IsTTY()) { CONSOLE_SCREEN_BUFFER_INFO Info; if (!::GetConsoleScreenBufferInfo(fOut, &Info)) { ShowError("resize / getting console info"); return; } SetWidth(Info.dwSize.X); } } void TerminalDisplayWin::SetColor(char CIdx, const Color& C) { WORD Attribs = 0; // There is no underline since DOS has died. if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY; if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY; if (C.fR > 64) Attribs |= FOREGROUND_RED; if (C.fG > 64) Attribs |= FOREGROUND_GREEN; if (C.fB > 64) Attribs |= FOREGROUND_BLUE; // if CIdx is 0 (default) then use the original console text color // (instead of the greyish one) if (CIdx == 0) ::SetConsoleTextAttribute(fOut, fDefaultAttributes); else ::SetConsoleTextAttribute(fOut, Attribs); } void TerminalDisplayWin::CheckCursorPos() { if (!IsTTY()) return; // Did something print something on the screen? // I.e. did the cursor move? CONSOLE_SCREEN_BUFFER_INFO CSI; if (::GetConsoleScreenBufferInfo(fOut, &CSI)) { if (CSI.dwCursorPosition.X != fWritePos.fCol || CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) { fStartLine = CSI.dwCursorPosition.Y; if (CSI.dwCursorPosition.X) { // fStartLine may be a couple of lines higher (or more precisely // the number of written lines higher) fStartLine -= fWritePos.fLine; } fWritePos.fCol = 0; fWritePos.fLine = 0; } } } void TerminalDisplayWin::Move(Pos P) { CheckCursorPos(); MoveInternal(P); fWritePos = P; } void TerminalDisplayWin::MoveInternal(Pos P) { if (IsTTY()) { COORD C = { (SHORT) P.fCol, (SHORT) (P.fLine + fStartLine) }; ::SetConsoleCursorPosition(fOut, C); } } void TerminalDisplayWin::MoveFront() { Pos P(fWritePos); P.fCol = 0; MoveInternal(P); } void TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) { Pos P(fWritePos); --P.fLine; MoveInternal(P); } void TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) { Pos P(fWritePos); ++P.fLine; MoveInternal(P); } void TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) { Pos P(fWritePos); ++P.fCol; MoveInternal(P); } void TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) { Pos P(fWritePos); --P.fCol; MoveInternal(P); } void TerminalDisplayWin::EraseToRight() { DWORD NumWritten; COORD C = { (SHORT) fWritePos.fCol, (SHORT) (fWritePos.fLine + fStartLine) }; ::FillConsoleOutputCharacter(fOut, ' ', GetWidth() - C.X, C, &NumWritten); // It wraps, so move up and reset WritePos: //MoveUp(); //++WritePos.Line; } void TerminalDisplayWin::WriteRawString(const char *text, size_t len) { DWORD NumWritten = 0; if (IsTTY()) { WriteConsole(fOut, text, (DWORD) len, &NumWritten, NULL); } else { WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL); } if (NumWritten != len) { ShowError("writing to output"); } } void TerminalDisplayWin::Attach() { // set to noecho if (fIsAttached || !IsTTY()) return; if (!::SetConsoleMode(fOut, fMyMode)) { ShowError("attaching to console output"); } CONSOLE_SCREEN_BUFFER_INFO Info; if (!::GetConsoleScreenBufferInfo(fOut, &Info)) { ShowError("attaching / getting console info"); } else { fStartLine = Info.dwCursorPosition.Y; if (Info.dwCursorPosition.X) { // Whooa - where are we?! Newline and cross fingers: WriteRawString("\n", 1); ++fStartLine; } } fIsAttached = true; } void TerminalDisplayWin::Detach() { if (!fIsAttached || !IsTTY()) return; if (!SetConsoleMode(fOut, fOldMode)) { ShowError("detaching to console output"); } TerminalDisplay::Detach(); fIsAttached = false; } void TerminalDisplayWin::ShowError(const char* Where) const { DWORD Err = GetLastError(); LPVOID MsgBuf = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &MsgBuf, 0, NULL); printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, (const char *) MsgBuf); LocalFree(MsgBuf); } } #endif // ifdef _WIN32 <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - loading an Abaqus tetahedrom mesh // - apply a load to the mesh using an external tool, // say CFD or SPH (here simulated as a function in this .cpp file) // that is perform a cosimulation. #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); //mrigidmesh->GetMesh().Transform(VNULL, Q_from_AngAxis(CH_C_PI, VECT_Y) ); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL, ChMatrix33<>(1), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::DeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2,1.5,5,20,60); // or use a height map: //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01,// Janosi shear coefficient (m) 5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi ); mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut mterrain.SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut 0.8, // displaced material vs downward pressed material. 2, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: mterrain.SetAutomaticRefinement(true); mterrain.SetAutomaticRefinementResolution(0.04); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8); mterrain.GetMesh()->SetWireframe(false); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change solver to embedded MINRES // NOTE! it is strongly advised that you compile the optional MKL module // if you need higher precision, and switch to its MKL solver - see demos for FEA & MKL. my_system.SetSolverType(ChSystem::SOLVER_MINRES); my_system.SetSolverWarmStarting(true); // this helps a lot to speedup convergence in this class of problems my_system.SetMaxItersSolverSpeed(40); my_system.SetTolForce(1e-10); */ application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180); application.EndScene(); } return 0; } <commit_msg>Just formatting and comments.<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code (advanced), about // // - using the SCM semi-empirical model for deformable soil #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystem.h" #include "chrono/physics/ChSystemDEM.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/DeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; int main(int argc, char* argv[]) { // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02+tire_rad, 0); double tire_w0 = tire_vel_z0/tire_rad; // Create a Chrono::Engine physical system ChSystemDEM my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss (new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // // CREATE A RIGID BODY WITH A MESH // // Create also a rigid body with a rigid mesh that will be used for the cosimulation, // this time the ChLoadContactSurfaceMesh cannot be used as in the FEA case, so we // will use the ChLoadBodyMesh class: std::shared_ptr<ChBody> mrigidbody (new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(200); mrigidbody->SetInertiaXX(ChVector<>(20,20,20)); mrigidbody->SetPos(tire_center + ChVector<>(0,0.3,0)); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->GetMesh().LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(mrigidmesh->GetMesh(), false, false, VNULL, ChMatrix33<>(1), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_SPEED); if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(myengine->Get_spe_funct()) ) mfun->Set_yconst(CH_C_PI / 4.0); myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2,VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::DeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2,1.5,5,20,60); // or use a height map: //mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(1.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01,// Janosi shear coefficient (m) 5e7 // Elastic stiffness (Pa/m), before plastic yeld, must be > Kphi ); mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut mterrain.SetBulldozingParameters(55, // angle of friction for erosion of displaced material at the border of the rut 0.8, // displaced material vs downward pressed material. 5, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: mterrain.SetAutomaticRefinement(true); mterrain.SetAutomaticRefinementResolution(0.04); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. //mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE, 0, 30000.2); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_ISLAND_ID, 0, 8); //mterrain.SetPlotType(vehicle::DeformableTerrain::PLOT_IS_TOUCHED, 0, 8); mterrain.GetMesh()->SetWireframe(true); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // application.SetTimestep(0.005); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0,30000, "Pressure yeld [Pa]", application.GetDevice(), 1180); application.EndScene(); } return 0; } <|endoftext|>
<commit_before>#include "TrackingWorker.hpp" #include <boost/chrono/duration.hpp> #include <ros/console.h> #include <opencv2/core/core.hpp> #include <map> #include "../../matlab/profiling.hpp" TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(200, "Difference") { assert(receiver != 0); this->receiver = receiver; stop = false; std::map<int, cv::Scalar> colors; colors[0] = cv::Scalar(0, 255, 0); colors[1] = cv::Scalar(0, 255, 255); colors[2] = cv::Scalar(255, 0, 255); errorGraph.setColors(colors); thread = new boost::thread(boost::bind(&TrackingWorker::run, this)); } TrackingWorker::~TrackingWorker() { stop = true; thread->join(); } void TrackingWorker::run() { ROS_INFO("Started tracking thread"); bool receivedFirstPosition = false; int emptyCount = 0; while (!stop) { std::vector<CameraData> data = dequeue(); if (data.size() > 0) { emptyCount = 0; if (!receivedFirstPosition) { receivedFirstPosition = true; ROS_INFO("Found quadcopter %d", data[0].quadcopterId); } // ROS_DEBUG("Got info from camera %d: [%.2f, %.2f, %.2f]", data[0].camNo, data[0].cameraVector.getV1(), data[0].cameraVector.getV2(), data[0].cameraVector.getV3()); Vector position = tracker.updatePosition(data); for (size_t i = 0; i < data.size(); i++) { errorGraph.nextPoint(tracker.getDistance(), data[i].camNo); } std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(position); ids.push_back(data[0].quadcopterId); updates.push_back(1); if (position.isValid()) { receiver->updatePositions(positions, ids, updates); } } else if (receivedFirstPosition) { emptyCount++; if (emptyCount == 5) { ROS_WARN("Position update buffer is empty!"); emptyCount = 0; } // Produce a context switch, since there are no good results anyways and to prevent busy waiting usleep(0); } } ROS_INFO("Stopped tracking thread"); } void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId, long int time) { CameraData data; data.cameraVector = cameraVector; data.camNo = camNo; data.quadcopterId = quadcopterId; data.valid = true; data.time = time; updatePosition(data); } void TrackingWorker::updatePosition(CameraData data) { enqueue(data); } void TrackingWorker::enqueue(CameraData data) { boost::mutex::scoped_lock lock(queueMutex); queue.enqueue(data); queueEmpty.notify_one(); } std::vector<CameraData> TrackingWorker::dequeue() { boost::mutex::scoped_lock lock(queueMutex); if (!dataAvailable()) { queueEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100)); } if (dataAvailable()) { return queue.dequeue(); } else { return std::vector<CameraData>(); } } bool TrackingWorker::dataAvailable() { return queue.dataAvailable(); } bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo) { return tracker.calibrate(chessboard, camNo); } Vector TrackingWorker::getCameraPosition(int camNo) { return tracker.getPosition(camNo); } cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo) { return tracker.getIntrinsicsMatrix(camNo); } cv::Mat TrackingWorker::getDistortionCoefficients(int camNo) { return tracker.getDistortionCoefficients(camNo); } void TrackingWorker::updateTrackingArea() { receiver->setTrackingArea(tracker.getTrackingArea()); }<commit_msg>Prevent burst dequeueing when queue can not give data<commit_after>#include "TrackingWorker.hpp" #include <boost/chrono/duration.hpp> #include <ros/console.h> #include <opencv2/core/core.hpp> #include <map> #include "../../matlab/profiling.hpp" TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(200, "Difference") { assert(receiver != 0); this->receiver = receiver; stop = false; std::map<int, cv::Scalar> colors; colors[0] = cv::Scalar(0, 255, 0); colors[1] = cv::Scalar(0, 255, 255); colors[2] = cv::Scalar(255, 0, 255); errorGraph.setColors(colors); thread = new boost::thread(boost::bind(&TrackingWorker::run, this)); } TrackingWorker::~TrackingWorker() { stop = true; thread->join(); } void TrackingWorker::run() { ROS_INFO("Started tracking thread"); bool receivedFirstPosition = false; int emptyCount = 0; while (!stop) { std::vector<CameraData> data = dequeue(); if (data.size() > 0) { emptyCount = 0; if (!receivedFirstPosition) { receivedFirstPosition = true; ROS_INFO("Found quadcopter %d", data[0].quadcopterId); } // ROS_DEBUG("Got info from camera %d: [%.2f, %.2f, %.2f]", data[0].camNo, data[0].cameraVector.getV1(), data[0].cameraVector.getV2(), data[0].cameraVector.getV3()); Vector position = tracker.updatePosition(data); for (size_t i = 0; i < data.size(); i++) { errorGraph.nextPoint(tracker.getDistance(), data[i].camNo); } std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(position); ids.push_back(data[0].quadcopterId); updates.push_back(1); if (position.isValid()) { receiver->updatePositions(positions, ids, updates); } } else if (receivedFirstPosition) { emptyCount++; if (emptyCount == 5) { ROS_WARN("Position update buffer is empty!"); emptyCount = 0; } boost::mutex::scoped_lock lock(queueMutex); queueEmpty.wait(lock); } } ROS_INFO("Stopped tracking thread"); } void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId, long int time) { CameraData data; data.cameraVector = cameraVector; data.camNo = camNo; data.quadcopterId = quadcopterId; data.valid = true; data.time = time; updatePosition(data); } void TrackingWorker::updatePosition(CameraData data) { enqueue(data); } void TrackingWorker::enqueue(CameraData data) { boost::mutex::scoped_lock lock(queueMutex); queue.enqueue(data); queueEmpty.notify_all(); } std::vector<CameraData> TrackingWorker::dequeue() { boost::mutex::scoped_lock lock(queueMutex); if (!dataAvailable()) { queueEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100)); } if (dataAvailable()) { return queue.dequeue(); } else { return std::vector<CameraData>(); } } bool TrackingWorker::dataAvailable() { return queue.dataAvailable(); } bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo) { return tracker.calibrate(chessboard, camNo); } Vector TrackingWorker::getCameraPosition(int camNo) { return tracker.getPosition(camNo); } cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo) { return tracker.getIntrinsicsMatrix(camNo); } cv::Mat TrackingWorker::getDistortionCoefficients(int camNo) { return tracker.getDistortionCoefficients(camNo); } void TrackingWorker::updateTrackingArea() { receiver->setTrackingArea(tracker.getTrackingArea()); }<|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ #define JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ #include <sys/types.h> #include <unistd.h> #include <map> #include <string> #include "jubatus/util/lang/bind.h" #include "jubatus/util/lang/shared_ptr.h" #include "jubatus/util/system/sysstat.h" #include "jubatus/util/system/time_util.h" #include "jubatus/core/common/jsonconfig.hpp" #include "mixer/mixer.hpp" #include "server_util.hpp" #include "../../config.hpp" #include "../common/lock_service.hpp" #include "../common/mprpc/rpc_server.hpp" #include "../common/signals.hpp" #include "../common/config.hpp" #include "../common/logger/logger.hpp" using jubatus::util::system::time::clock_time; using jubatus::util::system::time::get_clock_time; namespace jubatus { namespace server { namespace framework { class server_helper_impl { public: explicit server_helper_impl(const server_argv& a); ~server_helper_impl(); void prepare_for_start(const server_argv& a, bool use_cht); void prepare_for_run(const server_argv& a, bool use_cht); void get_config_lock(const server_argv& a, int retry); void prepare_for_stop(const server_argv& a); jubatus::util::lang::shared_ptr<common::lock_service> zk() const { return zk_; } private: jubatus::util::lang::shared_ptr<common::lock_service> zk_; jubatus::util::lang::shared_ptr<common::try_lockable> zk_config_lock_; }; template<typename Server> class server_helper { public: typedef typename Server::status_t status_t; explicit server_helper(const server_argv& a, bool use_cht = false) : impl_(a), start_time_(get_clock_time()), use_cht_(use_cht) { impl_.prepare_for_start(a, use_cht); server_.reset(new Server(a, impl_.zk())); impl_.get_config_lock(a, 3); try { if (a.is_standalone() && !a.modelpath.empty()) { // Load from a specified model file. // `load_file` implies `set_config`; no further actions needed. if (!a.configpath.empty()) { LOG(INFO) << "both model file and configuration are specified; " << "using configuration from model file"; } server_->load_file(a.modelpath); } else { server_->set_config(get_conf(a)); } } catch (const core::common::jsonconfig::cast_check_error& e) { core::common::config_exception config_error; const core::common::jsonconfig::config_error_list& errors = e.errors(); for (core::common::jsonconfig::config_error_list::const_iterator it = errors.begin(), end = errors.end(); it != end; ++it) { config_error << core::common::exception::error_message((*it)->what()); } // send error message to caller throw JUBATUS_EXCEPTION(config_error); } catch (const jubatus::util::lang::parse_error& e) { // exit immediately on JSON parse error with exit-code 1 std::string msg = std::string("syntax error in configuration: ") + (a.is_standalone() ? a.configpath : std::string("<zookeeper>")) + ":" + jubatus::util::lang::lexical_cast<std::string>(e.lineno()) + ":" + jubatus::util::lang::lexical_cast<std::string>(e.pos()) + " " + e.msg(); LOG(ERROR) << msg; exit(1); } catch (const std::runtime_error& e) { throw; } } std::map<std::string, std::string> get_loads() const { std::map<std::string, std::string> result; { jubatus::util::system::sysstat::sysstat_ret sys; get_sysstat(sys); result["loadavg"] = jubatus::util::lang::lexical_cast<std::string>(sys.loadavg); result["total_memory"] = jubatus::util::lang::lexical_cast<std::string>( sys.total_memory); result["free_memory"] = jubatus::util::lang::lexical_cast<std::string>( sys.free_memory); } return result; } std::map<std::string, status_t> get_status() const { std::map<std::string, status_t> status; const server_argv& a = server_->argv(); status_t& data = status[get_server_identifier(a)]; const clock_time ct = get_clock_time(); data["clock_time"] = jubatus::util::lang::lexical_cast<std::string>(ct.sec); data["start_time"] = jubatus::util::lang::lexical_cast<std::string>(start_time_.sec); data["uptime"] = jubatus::util::lang::lexical_cast<std::string>((ct - start_time_).sec); common::machine_status_t mt; common::get_machine_status(mt); data["VIRT"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_size); data["RSS"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_resident); data["SHR"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_share); data["timeout"] = jubatus::util::lang::lexical_cast<std::string>(a.timeout); data["threadnum"] = jubatus::util::lang::lexical_cast<std::string>(a.threadnum); data["datadir"] = a.datadir; data["is_standalone"] = jubatus::util::lang::lexical_cast<std::string>( a.is_standalone()); data["VERSION"] = JUBATUS_VERSION; data["PROGNAME"] = a.program_name; data["type"] = a.type; data["logdir"] = a.logdir; data["log_config"] = a.log_config; std::string configpath; if (a.is_standalone()) { configpath = a.configpath; } else { #ifdef HAVE_ZOOKEEPER_H // return zookeeper node name jubatus::server::common::build_config_path(configpath, a.type, a.name); #endif } data["configpath"] = configpath; data["pid"] = jubatus::util::lang::lexical_cast<std::string>(getpid()); data["user"] = jubatus::server::common::get_user_name(); data["update_count"] = jubatus::util::lang::lexical_cast<std::string>( server_->update_count()); data["last_saved"] = jubatus::util::lang::lexical_cast<std::string> (server_->last_saved_sec()); data["last_saved_path"] = server_->last_saved_path(); data["last_loaded"] = jubatus::util::lang::lexical_cast<std::string> (server_->last_loaded_sec()); data["last_loaded_path"] = server_->last_loaded_path(); server_->get_status(data); // distributed mode only if (!a.is_standalone()) { data["zk"] = a.z; data["name"] = a.name; data["interval_sec"] = jubatus::util::lang::lexical_cast<std::string>(a.interval_sec); data["interval_count"] = jubatus::util::lang::lexical_cast<std::string>( a.interval_count); data["zookeeper_timeout"] = jubatus::util::lang::lexical_cast<std::string>(a.zookeeper_timeout); data["interconnect_timeout"] = jubatus::util::lang::lexical_cast<std::string> (a.interconnect_timeout); data["connected_zookeeper"] = impl_.zk()->get_connected_host_and_port(); data["use_cht"] = jubatus::util::lang::lexical_cast<std::string>( use_cht_); data["mixer"] = a.mixer; server_->get_mixer()->get_status(data); } return status; } int start(common::mprpc::rpc_server& serv) { const server_argv& a = server_->argv(); try { serv.listen(a.port, a.bind_address); LOG(INFO) << "start listening at port " << a.port; start_time_ = get_clock_time(); serv.start(a.threadnum, true); // RPC server started, then register group membership impl_.prepare_for_run(a, use_cht_); LOG(INFO) << common::get_program_name() << " RPC server startup"; // Stop RPC server when terminate signal is sent common::set_action_on_term( jubatus::util::lang::bind( &server_helper::stop, this, jubatus::util::lang::ref(serv))); if (!a.is_standalone()) { // Start mixer and register active membership server_->get_mixer()->start(); } // wait for termination serv.join(); return 0; } catch (const mp::system_error& e) { if (e.code == EADDRINUSE) { LOG(FATAL) << "server failed to start: any process using port " << a.port << "?"; } else { LOG(FATAL) << "server failed to start: " << e.what(); } } catch (jubatus::core::common::exception::jubatus_exception&) { throw; } catch (const std::exception& e) { LOG(FATAL) << "server failed to start: " << e.what(); } return -1; } void stop(common::mprpc::rpc_server& serv) { // stop mixer before RPC server stopped for avoiding mixer RPC call to the // server itself if (!server_->argv().is_standalone()) { LOG(INFO) << "stopping mixer thread"; server_->get_mixer()->stop(); impl_.prepare_for_stop(server_->argv()); } LOG(INFO) << "stopping RPC server"; serv.end(); } jubatus::util::lang::shared_ptr<Server> server() const { return server_; } jubatus::util::concurrent::rw_mutex& rw_mutex() { return server_->rw_mutex(); } private: jubatus::util::lang::shared_ptr<Server> server_; server_helper_impl impl_; clock_time start_time_; const bool use_cht_; }; } // namespace framework } // namespace server } // namespace jubatus #define JRLOCK_(p) \ ::jubatus::util::concurrent::scoped_rlock lk((p)->rw_mutex()) #define JWLOCK_(p) \ ::jubatus::util::concurrent::scoped_wlock lk((p)->rw_mutex()); \ (p)->server()->event_model_updated() #define NOLOCK_(p) #endif // JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ <commit_msg>fix code style<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ #define JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ #include <sys/types.h> #include <unistd.h> #include <map> #include <string> #include "jubatus/util/lang/bind.h" #include "jubatus/util/lang/shared_ptr.h" #include "jubatus/util/system/sysstat.h" #include "jubatus/util/system/time_util.h" #include "jubatus/core/common/jsonconfig.hpp" #include "mixer/mixer.hpp" #include "server_util.hpp" #include "../../config.hpp" #include "../common/lock_service.hpp" #include "../common/mprpc/rpc_server.hpp" #include "../common/signals.hpp" #include "../common/config.hpp" #include "../common/logger/logger.hpp" using jubatus::util::system::time::clock_time; using jubatus::util::system::time::get_clock_time; namespace jubatus { namespace server { namespace framework { class server_helper_impl { public: explicit server_helper_impl(const server_argv& a); ~server_helper_impl(); void prepare_for_start(const server_argv& a, bool use_cht); void prepare_for_run(const server_argv& a, bool use_cht); void get_config_lock(const server_argv& a, int retry); void prepare_for_stop(const server_argv& a); jubatus::util::lang::shared_ptr<common::lock_service> zk() const { return zk_; } private: jubatus::util::lang::shared_ptr<common::lock_service> zk_; jubatus::util::lang::shared_ptr<common::try_lockable> zk_config_lock_; }; template<typename Server> class server_helper { public: typedef typename Server::status_t status_t; explicit server_helper(const server_argv& a, bool use_cht = false) : impl_(a), start_time_(get_clock_time()), use_cht_(use_cht) { impl_.prepare_for_start(a, use_cht); server_.reset(new Server(a, impl_.zk())); impl_.get_config_lock(a, 3); try { if (a.is_standalone() && !a.modelpath.empty()) { // Load from a specified model file. // `load_file` implies `set_config`; no further actions needed. if (!a.configpath.empty()) { LOG(INFO) << "both model file and configuration are specified; " << "using configuration from model file"; } server_->load_file(a.modelpath); } else { server_->set_config(get_conf(a)); } } catch (const core::common::jsonconfig::cast_check_error& e) { core::common::config_exception config_error; const core::common::jsonconfig::config_error_list& errors = e.errors(); for (core::common::jsonconfig::config_error_list::const_iterator it = errors.begin(), end = errors.end(); it != end; ++it) { config_error << core::common::exception::error_message((*it)->what()); } // send error message to caller throw JUBATUS_EXCEPTION(config_error); } catch (const jubatus::util::lang::parse_error& e) { // exit immediately on JSON parse error with exit-code 1 std::string msg = std::string("syntax error in configuration: ") + (a.is_standalone() ? a.configpath : std::string("<zookeeper>")) + ":" + jubatus::util::lang::lexical_cast<std::string>(e.lineno()) + ":" + jubatus::util::lang::lexical_cast<std::string>(e.pos()) + " " + e.msg(); LOG(ERROR) << msg; exit(1); } catch (const std::runtime_error& e) { throw; } } std::map<std::string, std::string> get_loads() const { std::map<std::string, std::string> result; { jubatus::util::system::sysstat::sysstat_ret sys; get_sysstat(sys); result["loadavg"] = jubatus::util::lang::lexical_cast<std::string>(sys.loadavg); result["total_memory"] = jubatus::util::lang::lexical_cast<std::string>( sys.total_memory); result["free_memory"] = jubatus::util::lang::lexical_cast<std::string>( sys.free_memory); } return result; } std::map<std::string, status_t> get_status() const { std::map<std::string, status_t> status; const server_argv& a = server_->argv(); status_t& data = status[get_server_identifier(a)]; const clock_time ct = get_clock_time(); data["clock_time"] = jubatus::util::lang::lexical_cast<std::string>(ct.sec); data["start_time"] = jubatus::util::lang::lexical_cast<std::string>(start_time_.sec); data["uptime"] = jubatus::util::lang::lexical_cast<std::string>((ct - start_time_).sec); common::machine_status_t mt; common::get_machine_status(mt); data["VIRT"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_size); data["RSS"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_resident); data["SHR"] = jubatus::util::lang::lexical_cast<std::string>(mt.vm_share); data["timeout"] = jubatus::util::lang::lexical_cast<std::string>(a.timeout); data["threadnum"] = jubatus::util::lang::lexical_cast<std::string>(a.threadnum); data["datadir"] = a.datadir; data["is_standalone"] = jubatus::util::lang::lexical_cast<std::string>( a.is_standalone()); data["VERSION"] = JUBATUS_VERSION; data["PROGNAME"] = a.program_name; data["type"] = a.type; data["logdir"] = a.logdir; data["log_config"] = a.log_config; std::string configpath; if (a.is_standalone()) { configpath = a.configpath; } else { #ifdef HAVE_ZOOKEEPER_H // return zookeeper node name jubatus::server::common::build_config_path(configpath, a.type, a.name); #endif } data["configpath"] = configpath; data["pid"] = jubatus::util::lang::lexical_cast<std::string>(getpid()); data["user"] = jubatus::server::common::get_user_name(); data["update_count"] = jubatus::util::lang::lexical_cast<std::string>( server_->update_count()); data["last_saved"] = jubatus::util::lang::lexical_cast<std::string> (server_->last_saved_sec()); data["last_saved_path"] = server_->last_saved_path(); data["last_loaded"] = jubatus::util::lang::lexical_cast<std::string> (server_->last_loaded_sec()); data["last_loaded_path"] = server_->last_loaded_path(); server_->get_status(data); // distributed mode only if (!a.is_standalone()) { data["zk"] = a.z; data["name"] = a.name; data["interval_sec"] = jubatus::util::lang::lexical_cast<std::string>(a.interval_sec); data["interval_count"] = jubatus::util::lang::lexical_cast<std::string>( a.interval_count); data["zookeeper_timeout"] = jubatus::util::lang::lexical_cast<std::string>(a.zookeeper_timeout); data["interconnect_timeout"] = jubatus::util::lang::lexical_cast<std::string> (a.interconnect_timeout); data["connected_zookeeper"] = impl_.zk()->get_connected_host_and_port(); data["use_cht"] = jubatus::util::lang::lexical_cast<std::string>( use_cht_); data["mixer"] = a.mixer; server_->get_mixer()->get_status(data); } return status; } int start(common::mprpc::rpc_server& serv) { const server_argv& a = server_->argv(); try { serv.listen(a.port, a.bind_address); LOG(INFO) << "start listening at port " << a.port; start_time_ = get_clock_time(); serv.start(a.threadnum, true); // RPC server started, then register group membership impl_.prepare_for_run(a, use_cht_); LOG(INFO) << common::get_program_name() << " RPC server startup"; // Stop RPC server when terminate signal is sent common::set_action_on_term( jubatus::util::lang::bind( &server_helper::stop, this, jubatus::util::lang::ref(serv))); if (!a.is_standalone()) { // Start mixer and register active membership server_->get_mixer()->start(); } // wait for termination serv.join(); return 0; } catch (const mp::system_error& e) { if (e.code == EADDRINUSE) { LOG(FATAL) << "server failed to start: any process using port " << a.port << "?"; } else { LOG(FATAL) << "server failed to start: " << e.what(); } } catch (jubatus::core::common::exception::jubatus_exception&) { throw; } catch (const std::exception& e) { LOG(FATAL) << "server failed to start: " << e.what(); } return -1; } void stop(common::mprpc::rpc_server& serv) { // stop mixer before RPC server stopped for avoiding mixer RPC call to the // server itself if (!server_->argv().is_standalone()) { LOG(INFO) << "stopping mixer thread"; server_->get_mixer()->stop(); impl_.prepare_for_stop(server_->argv()); } LOG(INFO) << "stopping RPC server"; serv.end(); } jubatus::util::lang::shared_ptr<Server> server() const { return server_; } jubatus::util::concurrent::rw_mutex& rw_mutex() { return server_->rw_mutex(); } private: jubatus::util::lang::shared_ptr<Server> server_; server_helper_impl impl_; clock_time start_time_; const bool use_cht_; }; } // namespace framework } // namespace server } // namespace jubatus #define JRLOCK_(p) \ ::jubatus::util::concurrent::scoped_rlock lk((p)->rw_mutex()) #define JWLOCK_(p) \ ::jubatus::util::concurrent::scoped_wlock lk((p)->rw_mutex()); \ (p)->server()->event_model_updated() #define NOLOCK_(p) #endif // JUBATUS_SERVER_FRAMEWORK_SERVER_HELPER_HPP_ <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/network/settings.hpp> #include <bitcoin/bitcoin.hpp> namespace libbitcoin { namespace network { using namespace bc::asio; using namespace bc::message; // Common default values (no settings context). settings::settings() : threads(50), protocol(version::level::maximum), inbound_connections(32), outbound_connections(4), manual_attempt_limit(0), connect_batch_size(5), connect_timeout_seconds(5), channel_handshake_seconds(30), channel_heartbeat_minutes(5), channel_inactivity_minutes(10), channel_expiration_minutes(1440), channel_germination_seconds(30), host_pool_capacity(1000), relay_transactions(true), hosts_file("hosts.cache"), debug_file("debug.log"), error_file("error.log"), self(unspecified_network_address) { } // Use push_back due to initializer_list bug: // stackoverflow.com/a/20168627/1172329 settings::settings(bc::settings context) : settings() { // Handle deviations from common defaults. switch (context) { case bc::settings::mainnet: { identifier = 0x4d53564d; inbound_port = 5251; // Seeds based on bitcoinstats.com/network/dns-servers seeds.reserve(6); seeds.push_back({ "main-asia.metaverse.live", 5251 }); seeds.push_back({ "main-americas.metaverse.live", 5251 }); seeds.push_back({ "main-europe.metaverse.live", 5251 }); seeds.push_back({ "main-asia.mvs.live", 5251 }); seeds.push_back({ "main-americas.mvs.live", 5251 }); seeds.push_back({ "main-europe.mvs.live", 5251 }); break; } case bc::settings::testnet: { identifier = 0x73766d74; inbound_port = 15251; seeds.reserve(6); seeds.push_back({ "test-asia.metaverse.live", 15251 }); seeds.push_back({ "test-americas.metaverse.live", 15251 }); seeds.push_back({ "test-europe.metaverse.live", 15251 }); seeds.push_back({ "test-asia.mvs.live", 15251 }); seeds.push_back({ "test-americas.mvs.live", 15251 }); seeds.push_back({ "test-europe.mvs.live", 15251 }); break; } default: case bc::settings::none: { } } } duration settings::connect_timeout() const { return seconds(connect_timeout_seconds); } duration settings::channel_handshake() const { return seconds(channel_handshake_seconds); } duration settings::channel_heartbeat() const { return minutes(channel_heartbeat_minutes); } duration settings::channel_inactivity() const { return minutes(channel_inactivity_minutes); } duration settings::channel_expiration() const { return minutes(channel_expiration_minutes); } duration settings::channel_germination() const { return seconds(channel_germination_seconds); } } // namespace network } // namespace libbitcoin <commit_msg>change outbound connections as 8 for sync bug<commit_after>/** * Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/network/settings.hpp> #include <bitcoin/bitcoin.hpp> namespace libbitcoin { namespace network { using namespace bc::asio; using namespace bc::message; // Common default values (no settings context). settings::settings() : threads(50), protocol(version::level::maximum), inbound_connections(32), outbound_connections(8), manual_attempt_limit(0), connect_batch_size(5), connect_timeout_seconds(5), channel_handshake_seconds(30), channel_heartbeat_minutes(5), channel_inactivity_minutes(10), channel_expiration_minutes(1440), channel_germination_seconds(30), host_pool_capacity(1000), relay_transactions(true), hosts_file("hosts.cache"), debug_file("debug.log"), error_file("error.log"), self(unspecified_network_address) { } // Use push_back due to initializer_list bug: // stackoverflow.com/a/20168627/1172329 settings::settings(bc::settings context) : settings() { // Handle deviations from common defaults. switch (context) { case bc::settings::mainnet: { identifier = 0x4d53564d; inbound_port = 5251; // Seeds based on bitcoinstats.com/network/dns-servers seeds.reserve(6); seeds.push_back({ "main-asia.metaverse.live", 5251 }); seeds.push_back({ "main-americas.metaverse.live", 5251 }); seeds.push_back({ "main-europe.metaverse.live", 5251 }); seeds.push_back({ "main-asia.mvs.live", 5251 }); seeds.push_back({ "main-americas.mvs.live", 5251 }); seeds.push_back({ "main-europe.mvs.live", 5251 }); break; } case bc::settings::testnet: { identifier = 0x73766d74; inbound_port = 15251; seeds.reserve(6); seeds.push_back({ "test-asia.metaverse.live", 15251 }); seeds.push_back({ "test-americas.metaverse.live", 15251 }); seeds.push_back({ "test-europe.metaverse.live", 15251 }); seeds.push_back({ "test-asia.mvs.live", 15251 }); seeds.push_back({ "test-americas.mvs.live", 15251 }); seeds.push_back({ "test-europe.mvs.live", 15251 }); break; } default: case bc::settings::none: { } } } duration settings::connect_timeout() const { return seconds(connect_timeout_seconds); } duration settings::channel_handshake() const { return seconds(channel_handshake_seconds); } duration settings::channel_heartbeat() const { return minutes(channel_heartbeat_minutes); } duration settings::channel_inactivity() const { return minutes(channel_inactivity_minutes); } duration settings::channel_expiration() const { return minutes(channel_expiration_minutes); } duration settings::channel_germination() const { return seconds(channel_germination_seconds); } } // namespace network } // namespace libbitcoin <|endoftext|>
<commit_before>/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <[email protected]> * * Peli 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. * * 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, see <http://www.gnu.org/licenses/>. * */ #include <sstream> #include <iostream> #include <cmath> #include <limits> #include "peli/json/value.h" #include "exception_check.h" using namespace std; using namespace peli; using namespace peli::test; int check_zero() { const string str1 = " [\n\t0 ]\r\n "; const wstring str2 = L"[ \r\t0 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number(0) }; json::warray ch2 { json::number(0) }; if (arr1 != ch1) return -1; if (arr2 != ch2) return -2; return 0; } int check_integer() { const string str1 = " [\n\t-123456, 123456 ]\r\n "; const wstring str2 = L"[ \r\t-123456, 123456 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number { -123456 }, json::number { 123456 } }; json::warray ch2 { json::number { -123456 }, json::number { 123456 } }; if (arr1 != ch1) return -3; if (arr2 != ch2) return -4; return 0; } int check_decimal_fraction() { const string str1 = " [\n\t3.4375, -3.4375, 0.04, -0.04 ]\r\n "; const wstring str2 = L"[ \r\t3.4375, -3.4375, 0.04, -0.04 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number(3.4375), json::number(-3.4375), json::value(json::number(0.04)), json::value(json::number(-0.04)) }; json::warray ch2 { json::number(3.4375), json::number(-3.4375), json::wvalue(json::number(0.04)), json::wvalue(json::number(-0.04)) }; json::number precision = pow(10, -1 * (numeric_limits<json::number>::digits10 - 2)); if (abs(get<json::number>(arr1[2]) - get<json::number>(ch1[2])) < precision) ch1[2] = arr1[2]; if (abs(get<json::number>(arr1[3]) - get<json::number>(ch1[3])) < precision) ch1[3] = arr1[3]; if (arr1 != ch1) return -5; if (arr2 != ch2) return -6; return 0; } int check_engineer_fraction() { const string str1 = " [\n\t0.34375e1, -0.34375e+1, 0.34375E1, -0.34375E+1, 4e-2, -4e-2 ]\r\n "; const wstring str2 = L"[ \r\t0.34375e1, -0.34375e+1, 0.34375E1, -0.34375E+1, 4e-2, -4e-2 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number { 3.4375 }, json::number { -3.4375 }, json::number { 3.4375 }, json::number { -3.4375 }, json::value(json::number(4e-2)), json::value(json::number(-4e-2)) }; json::warray ch2 { json::number { 3.4375 }, json::number { -3.4375 }, json::number { 3.4375 }, json::number { -3.4375 }, json::wvalue(json::number(4e-2)), json::wvalue(json::number(-4e-2)) }; json::number precision = pow(10, -1 * (numeric_limits<json::number>::digits10 - 2)); if (fabs(get<json::number>(arr1[4]) - get<json::number>(ch1[4])) < precision) ch1[4] = arr1[4]; if (fabs(get<json::number>(arr1[5]) - get<json::number>(ch1[5])) < precision) ch1[5] = arr1[5]; if (arr1 != ch1) return -7; if (arr2 != ch2) return -8; return 0; } int check_overflow() { if (!has_thrown_on<invalid_argument>("[45e+1459823]")) return -9; return 0; } int main(int, char**) { const int zr = check_zero(); if (zr) return zr; const int ir = check_integer(); if (ir) return ir; const int dr = check_decimal_fraction(); if (dr) return dr; const int er = check_engineer_fraction(); return er; } <commit_msg>Positive return codes and better handling for numbers as well<commit_after>/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <[email protected]> * * Peli 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. * * 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, see <http://www.gnu.org/licenses/>. * */ #include <sstream> #include <iostream> #include <cmath> #include <limits> #include "peli/json/value.h" #include "exception_check.h" using namespace std; using namespace peli; using namespace peli::test; int check_zero() { const string str1 = " [\n\t0 ]\r\n "; const wstring str2 = L"[ \r\t0 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number(0) }; json::warray ch2 { json::number(0) }; if (arr1 != ch1) return 1; if (arr2 != ch2) return 2; return 0; } int check_integer() { const string str1 = " [\n\t-123456, 123456 ]\r\n "; const wstring str2 = L"[ \r\t-123456, 123456 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number { -123456 }, json::number { 123456 } }; json::warray ch2 { json::number { -123456 }, json::number { 123456 } }; if (arr1 != ch1) return 3; if (arr2 != ch2) return 4; return 0; } int check_decimal_fraction() { const string str1 = " [\n\t3.4375, -3.4375, 0.04, -0.04 ]\r\n "; const wstring str2 = L"[ \r\t3.4375, -3.4375, 0.04, -0.04 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number(3.4375), json::number(-3.4375), json::value(json::number(0.04)), json::value(json::number(-0.04)) }; json::warray ch2 { json::number(3.4375), json::number(-3.4375), json::wvalue(json::number(0.04)), json::wvalue(json::number(-0.04)) }; json::number precision = pow(10, -1 * (numeric_limits<json::number>::digits10 - 2)); if (abs(get<json::number>(arr1[2]) - get<json::number>(ch1[2])) < precision) ch1[2] = arr1[2]; if (abs(get<json::number>(arr1[3]) - get<json::number>(ch1[3])) < precision) ch1[3] = arr1[3]; if (arr1 != ch1) return 5; if (arr2 != ch2) return 6; return 0; } int check_engineer_fraction() { const string str1 = " [\n\t0.34375e1, -0.34375e+1, 0.34375E1, -0.34375E+1, 4e-2, -4e-2 ]\r\n "; const wstring str2 = L"[ \r\t0.34375e1, -0.34375e+1, 0.34375E1, -0.34375E+1, 4e-2, -4e-2 ]\n\t \n \n\r "; istringstream is1(str1); json::value v1; is1 >> v1; wistringstream is2(str2); json::wvalue v2; is2 >> v2; const json::array& arr1(get<json::array>(v1)); const json::warray& arr2(get<json::warray>(v2)); json::array ch1 { json::number { 3.4375 }, json::number { -3.4375 }, json::number { 3.4375 }, json::number { -3.4375 }, json::value(json::number(4e-2)), json::value(json::number(-4e-2)) }; json::warray ch2 { json::number { 3.4375 }, json::number { -3.4375 }, json::number { 3.4375 }, json::number { -3.4375 }, json::wvalue(json::number(4e-2)), json::wvalue(json::number(-4e-2)) }; json::number precision = pow(10, -1 * (numeric_limits<json::number>::digits10 - 2)); if (fabs(get<json::number>(arr1[4]) - get<json::number>(ch1[4])) < precision) ch1[4] = arr1[4]; if (fabs(get<json::number>(arr1[5]) - get<json::number>(ch1[5])) < precision) ch1[5] = arr1[5]; if (arr1 != ch1) return 7; if (arr2 != ch2) return 8; return 0; } int check_overflow() { if (!has_thrown_on<invalid_argument>("[45e+1459823]")) return 9; return 0; } int main(int, char**) { if (const auto r = check_zero()) return r; if (const auto r = check_integer()) return r; if (const auto r = check_decimal_fraction()) return r; if (const auto r = check_engineer_fraction()) return r; if (const auto r = check_overflow()) return r; return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * * Copyright 2008 Szymon Tomasz Stefanek <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * *******************************************************************************/ #include "messagelistview/core/aggregation.h" #include <QDataStream> #include <klocale.h> namespace KMail { namespace MessageListView { namespace Core { static const int gAggregationCurrentVersion = 0x1009; // increase if you add new fields of change the meaning of some Aggregation::Aggregation( const QString &name, const QString &description, Grouping grouping, GroupExpandPolicy groupExpandPolicy, Threading threading, ThreadLeader threadLeader, ThreadExpandPolicy threadExpandPolicy, FillViewStrategy fillViewStrategy ) : OptionSet( name, description ), mGrouping( grouping ), mGroupExpandPolicy( groupExpandPolicy ), mThreading( threading ), mThreadLeader( threadLeader ), mThreadExpandPolicy( threadExpandPolicy ), mFillViewStrategy( fillViewStrategy ) { } Aggregation::Aggregation( const Aggregation &opt ) : OptionSet( opt ), mGrouping( opt.mGrouping ), mGroupExpandPolicy( opt.mGroupExpandPolicy ), mThreading( opt.mThreading ), mThreadLeader( opt.mThreadLeader ), mThreadExpandPolicy( opt.mThreadExpandPolicy ), mFillViewStrategy( opt.mFillViewStrategy ) { } Aggregation::Aggregation() : OptionSet(), mGrouping( NoGrouping ), mGroupExpandPolicy( NeverExpandGroups ), mThreading( NoThreading ), mThreadLeader( TopmostMessage ), mThreadExpandPolicy( NeverExpandThreads ), mFillViewStrategy( FavorInteractivity ) { } bool Aggregation::load( QDataStream &stream ) { int val; stream >> val; if ( val != gAggregationCurrentVersion ) return false; // b0rken (invalid version) stream >> val; mGrouping = (Grouping)val; switch( mGrouping ) { case NoGrouping: case GroupByDate: case GroupByDateRange: case GroupBySenderOrReceiver: case GroupBySender: case GroupByReceiver: // ok break; default: // b0rken return false; break; }; stream >> val; // Formerly contained group sorting stream >> val; // Formerly contained group sorting direction stream >> val; mGroupExpandPolicy = (GroupExpandPolicy)val; switch( mGroupExpandPolicy ) { case NeverExpandGroups: case ExpandRecentGroups: case AlwaysExpandGroups: // ok break; default: // b0rken return false; break; }; stream >> val; mThreading = (Threading)val; switch( mThreading ) { case NoThreading: case PerfectOnly: case PerfectAndReferences: case PerfectReferencesAndSubject: // ok break; default: // b0rken return false; break; } stream >> val; mThreadLeader = (ThreadLeader)val; switch( mThreadLeader ) { case MostRecentMessage: case TopmostMessage: // ok // FIXME: Should check that thread leaders setting matches grouping and threading settings. break; default: // b0rken return false; break; } stream >> val; mThreadExpandPolicy = (ThreadExpandPolicy)val; switch( mThreadExpandPolicy ) { case NeverExpandThreads: case ExpandThreadsWithNewMessages: case ExpandThreadsWithUnreadMessages: case ExpandThreadsWithUnreadOrImportantMessages: case AlwaysExpandThreads: // ok break; default: // b0rken return false; break; } stream >> val; // Formely contained message sorting stream >> val; // Formely contained message sort direction stream >> val; mFillViewStrategy = (FillViewStrategy)val; switch( mFillViewStrategy ) { case FavorSpeed: case FavorInteractivity: case BatchNoInteractivity: // ok break; default: // b0rken return false; break; } return true; } void Aggregation::save( QDataStream &stream ) const { stream << (int)gAggregationCurrentVersion; stream << (int)mGrouping; stream << 0; // Formerly group sorting stream << 0; // Formerly group sort direction stream << (int)mGroupExpandPolicy; stream << (int)mThreading; stream << (int)mThreadLeader; stream << (int)mThreadExpandPolicy; stream << 0; // Formerly message sorting stream << 0; // Formerly message sort direction stream << (int)mFillViewStrategy; } QList< QPair< QString, int > > Aggregation::enumerateGroupingOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18nc( "No grouping of messages", "None" ), NoGrouping ) ); ret.append( QPair< QString, int >( i18n( "By Exact Date (of Thread Leaders)" ), GroupByDate ) ); ret.append( QPair< QString, int >( i18n( "By Smart Date Ranges (of Thread Leaders)" ), GroupByDateRange ) ); ret.append( QPair< QString, int >( i18n( "By Smart Sender/Receiver" ), GroupBySenderOrReceiver ) ); ret.append( QPair< QString, int >( i18n( "By Sender" ), GroupBySender ) ); ret.append( QPair< QString, int >( i18n( "By Receiver" ), GroupBySender ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateGroupExpandPolicyOptions( Grouping g ) { QList< QPair< QString, int > > ret; if ( g == NoGrouping ) return ret; ret.append( QPair< QString, int >( i18n( "Never Expand Groups" ), NeverExpandGroups ) ); if ( ( g == GroupByDate ) || ( g == GroupByDateRange ) ) ret.append( QPair< QString, int >( i18n( "Expand Recent Groups" ), ExpandRecentGroups ) ); ret.append( QPair< QString, int >( i18n( "Always Expand Groups" ), AlwaysExpandGroups ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadingOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18nc( "No threading of messages", "None" ), NoThreading ) ); ret.append( QPair< QString, int >( i18n( "Perfect Only" ), PerfectOnly ) ); ret.append( QPair< QString, int >( i18n( "Perfect and by References" ), PerfectAndReferences ) ); ret.append( QPair< QString, int >( i18n( "Perfect, by References and by Subject" ), PerfectReferencesAndSubject ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadLeaderOptions( Grouping g, Threading t ) { QList< QPair< QString, int > > ret; if ( t == NoThreading ) return ret; ret.append( QPair< QString, int >( i18n( "Topmost Message" ), TopmostMessage ) ); if ( ( g != GroupByDate ) && ( g != GroupByDateRange ) ) return ret; ret.append( QPair< QString, int >( i18n( "Most Recent Message" ), MostRecentMessage ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadExpandPolicyOptions( Threading t ) { QList< QPair< QString, int > > ret; if ( t == NoThreading ) return ret; ret.append( QPair< QString, int >( i18n( "Never Expand Threads" ), NeverExpandThreads ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With New Messages" ), ExpandThreadsWithNewMessages ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With Unread Messages" ), ExpandThreadsWithUnreadMessages ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With Unread or Important Messages" ), ExpandThreadsWithUnreadOrImportantMessages ) ); ret.append( QPair< QString, int >( i18n( "Always Expand Threads" ), AlwaysExpandThreads ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateFillViewStrategyOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18n( "Favor Interactivity" ), FavorInteractivity ) ); ret.append( QPair< QString, int >( i18n( "Favor Speed" ), FavorSpeed ) ); ret.append( QPair< QString, int >( i18n( "Batch Job (No Interactivity)" ), BatchNoInteractivity ) ); return ret; } } // namespace Core } // namespace MessageListView } // namespace KMail <commit_msg>BUG: 204193<commit_after>/****************************************************************************** * * Copyright 2008 Szymon Tomasz Stefanek <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * *******************************************************************************/ #include "messagelistview/core/aggregation.h" #include <QDataStream> #include <klocale.h> namespace KMail { namespace MessageListView { namespace Core { static const int gAggregationCurrentVersion = 0x1009; // increase if you add new fields of change the meaning of some Aggregation::Aggregation( const QString &name, const QString &description, Grouping grouping, GroupExpandPolicy groupExpandPolicy, Threading threading, ThreadLeader threadLeader, ThreadExpandPolicy threadExpandPolicy, FillViewStrategy fillViewStrategy ) : OptionSet( name, description ), mGrouping( grouping ), mGroupExpandPolicy( groupExpandPolicy ), mThreading( threading ), mThreadLeader( threadLeader ), mThreadExpandPolicy( threadExpandPolicy ), mFillViewStrategy( fillViewStrategy ) { } Aggregation::Aggregation( const Aggregation &opt ) : OptionSet( opt ), mGrouping( opt.mGrouping ), mGroupExpandPolicy( opt.mGroupExpandPolicy ), mThreading( opt.mThreading ), mThreadLeader( opt.mThreadLeader ), mThreadExpandPolicy( opt.mThreadExpandPolicy ), mFillViewStrategy( opt.mFillViewStrategy ) { } Aggregation::Aggregation() : OptionSet(), mGrouping( NoGrouping ), mGroupExpandPolicy( NeverExpandGroups ), mThreading( NoThreading ), mThreadLeader( TopmostMessage ), mThreadExpandPolicy( NeverExpandThreads ), mFillViewStrategy( FavorInteractivity ) { } bool Aggregation::load( QDataStream &stream ) { int val; stream >> val; if ( val != gAggregationCurrentVersion ) return false; // b0rken (invalid version) stream >> val; mGrouping = (Grouping)val; switch( mGrouping ) { case NoGrouping: case GroupByDate: case GroupByDateRange: case GroupBySenderOrReceiver: case GroupBySender: case GroupByReceiver: // ok break; default: // b0rken return false; break; }; stream >> val; // Formerly contained group sorting stream >> val; // Formerly contained group sorting direction stream >> val; mGroupExpandPolicy = (GroupExpandPolicy)val; switch( mGroupExpandPolicy ) { case NeverExpandGroups: case ExpandRecentGroups: case AlwaysExpandGroups: // ok break; default: // b0rken return false; break; }; stream >> val; mThreading = (Threading)val; switch( mThreading ) { case NoThreading: case PerfectOnly: case PerfectAndReferences: case PerfectReferencesAndSubject: // ok break; default: // b0rken return false; break; } stream >> val; mThreadLeader = (ThreadLeader)val; switch( mThreadLeader ) { case MostRecentMessage: case TopmostMessage: // ok // FIXME: Should check that thread leaders setting matches grouping and threading settings. break; default: // b0rken return false; break; } stream >> val; mThreadExpandPolicy = (ThreadExpandPolicy)val; switch( mThreadExpandPolicy ) { case NeverExpandThreads: case ExpandThreadsWithNewMessages: case ExpandThreadsWithUnreadMessages: case ExpandThreadsWithUnreadOrImportantMessages: case AlwaysExpandThreads: // ok break; default: // b0rken return false; break; } stream >> val; // Formely contained message sorting stream >> val; // Formely contained message sort direction stream >> val; mFillViewStrategy = (FillViewStrategy)val; switch( mFillViewStrategy ) { case FavorSpeed: case FavorInteractivity: case BatchNoInteractivity: // ok break; default: // b0rken return false; break; } return true; } void Aggregation::save( QDataStream &stream ) const { stream << (int)gAggregationCurrentVersion; stream << (int)mGrouping; stream << 0; // Formerly group sorting stream << 0; // Formerly group sort direction stream << (int)mGroupExpandPolicy; stream << (int)mThreading; stream << (int)mThreadLeader; stream << (int)mThreadExpandPolicy; stream << 0; // Formerly message sorting stream << 0; // Formerly message sort direction stream << (int)mFillViewStrategy; } QList< QPair< QString, int > > Aggregation::enumerateGroupingOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18nc( "No grouping of messages", "None" ), NoGrouping ) ); ret.append( QPair< QString, int >( i18n( "By Exact Date (of Thread Leaders)" ), GroupByDate ) ); ret.append( QPair< QString, int >( i18n( "By Smart Date Ranges (of Thread Leaders)" ), GroupByDateRange ) ); ret.append( QPair< QString, int >( i18n( "By Smart Sender/Receiver" ), GroupBySenderOrReceiver ) ); ret.append( QPair< QString, int >( i18n( "By Sender" ), GroupBySender ) ); ret.append( QPair< QString, int >( i18n( "By Receiver" ), GroupByReceiver ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateGroupExpandPolicyOptions( Grouping g ) { QList< QPair< QString, int > > ret; if ( g == NoGrouping ) return ret; ret.append( QPair< QString, int >( i18n( "Never Expand Groups" ), NeverExpandGroups ) ); if ( ( g == GroupByDate ) || ( g == GroupByDateRange ) ) ret.append( QPair< QString, int >( i18n( "Expand Recent Groups" ), ExpandRecentGroups ) ); ret.append( QPair< QString, int >( i18n( "Always Expand Groups" ), AlwaysExpandGroups ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadingOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18nc( "No threading of messages", "None" ), NoThreading ) ); ret.append( QPair< QString, int >( i18n( "Perfect Only" ), PerfectOnly ) ); ret.append( QPair< QString, int >( i18n( "Perfect and by References" ), PerfectAndReferences ) ); ret.append( QPair< QString, int >( i18n( "Perfect, by References and by Subject" ), PerfectReferencesAndSubject ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadLeaderOptions( Grouping g, Threading t ) { QList< QPair< QString, int > > ret; if ( t == NoThreading ) return ret; ret.append( QPair< QString, int >( i18n( "Topmost Message" ), TopmostMessage ) ); if ( ( g != GroupByDate ) && ( g != GroupByDateRange ) ) return ret; ret.append( QPair< QString, int >( i18n( "Most Recent Message" ), MostRecentMessage ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateThreadExpandPolicyOptions( Threading t ) { QList< QPair< QString, int > > ret; if ( t == NoThreading ) return ret; ret.append( QPair< QString, int >( i18n( "Never Expand Threads" ), NeverExpandThreads ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With New Messages" ), ExpandThreadsWithNewMessages ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With Unread Messages" ), ExpandThreadsWithUnreadMessages ) ); ret.append( QPair< QString, int >( i18n( "Expand Threads With Unread or Important Messages" ), ExpandThreadsWithUnreadOrImportantMessages ) ); ret.append( QPair< QString, int >( i18n( "Always Expand Threads" ), AlwaysExpandThreads ) ); return ret; } QList< QPair< QString, int > > Aggregation::enumerateFillViewStrategyOptions() { QList< QPair< QString, int > > ret; ret.append( QPair< QString, int >( i18n( "Favor Interactivity" ), FavorInteractivity ) ); ret.append( QPair< QString, int >( i18n( "Favor Speed" ), FavorSpeed ) ); ret.append( QPair< QString, int >( i18n( "Batch Job (No Interactivity)" ), BatchNoInteractivity ) ); return ret; } } // namespace Core } // namespace MessageListView } // namespace KMail <|endoftext|>
<commit_before>/*************************************************************************** konsolekalendarexports.cpp - description ------------------- begin : Sun May 25 2003 copyright : (C) 2003 by Tuukka Pasanen copyright : (C) 2003 by Allen Winter email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdlib.h> #include <iostream> #include <qdatetime.h> #include <kdebug.h> #include <klocale.h> #include <libkcal/calendarlocal.h> #include <libkcal/calendar.h> #include <libkcal/event.h> #include <libkcal/htmlexport.h> #include "konsolekalendarexports.h" using namespace KCal; using namespace std; KonsoleKalendarExports::KonsoleKalendarExports( KonsoleKalendarVariables *variables ) { m_variables = variables; m_firstEntry = true; } KonsoleKalendarExports::~KonsoleKalendarExports() { } bool KonsoleKalendarExports::exportAsTxt( QTextStream *ts, Event *event ){ if( m_firstEntry == true || m_lastDate.day() != event->dtStart().date().day() || m_lastDate.month() != event->dtStart().date().month() || m_lastDate.year() != event->dtStart().date().year() ){ m_firstEntry=false; int len = event->dtStartStr().length(); QString date = event->dtStartStr(); date.truncate( len - 5 ); *ts << I18N_NOOP("Date:") << "\t" << date.local8Bit() << endl; m_lastDate = event->dtStart().date(); } if ( !event->doesFloat() ) { *ts << "\t"; *ts << event->dtStartStr().remove(0, (event->dtStartStr().find(' ', 0, false) + 1) ).local8Bit(); *ts << " - "; *ts << event->dtEndStr().remove(0, (event->dtEndStr().find(' ', 0, false) + 1) ).local8Bit(); } *ts << endl << I18N_NOOP("Summary:") << endl; *ts << "\t" << event->summary().local8Bit() << endl; *ts << I18N_NOOP("Description:") << endl; if( !event->description().isEmpty() ) { *ts << "\t" << event->description().local8Bit() << endl; } else { *ts << "\t" << I18N_NOOP("(no description available)") << endl; } *ts << I18N_NOOP("UID:") << endl; *ts << "\t" << event->uid().local8Bit() << endl; *ts << "----------------------------------" << endl; return true; } bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, Event *event ){ // startdate,starttime,enddate,endtime,summary,description,UID QString delim = ","; //one day maybe the delim character can be an option?? if ( !event->doesFloat() ) { *ts << event->dtStart().date().toString("yyyy:M:d"); *ts << delim << event->dtStart().time().toString("hh:mm"); *ts << delim << event->dtEnd().date().toString("yyyy:M:d"); *ts << delim << event->dtEnd().time().toString("hh:mm"); } else { *ts << ",,,"; } *ts << delim << event->summary().local8Bit(); *ts << delim << event->description().local8Bit(); *ts << delim << event->uid().local8Bit(); *ts << endl; return true; } // Old function for printing out as keyword:<tab>value //bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, Event *event ){ // // if ( !event->doesFloat() ) { // *ts << event->dtStartStr().remove(0, (event->dtStartStr().find(' ', 0, false) + 1) ).local8Bit(); // *ts << "\t"; // *ts << event->dtEndStr().remove(0, (event->dtEndStr().find(' ', 0, false) + 1) ).local8Bit(); // } // // *ts << "\t" << I18N_NOOP("Summary:"); // *ts << "\t\"" << event->summary().local8Bit() << "\""; // *ts << "\t" << I18N_NOOP("Description:"); // *ts << "\t\"" << event->description().local8Bit() << "\""; // *ts << "\t" << I18N_NOOP("UID:"); // *ts << "\t" << event->uid().local8Bit() << endl; // // return true; //} <commit_msg>BUG Fix: why can't I concentrate today? Another tweak for CSVexport<commit_after>/*************************************************************************** konsolekalendarexports.cpp - description ------------------- begin : Sun May 25 2003 copyright : (C) 2003 by Tuukka Pasanen copyright : (C) 2003 by Allen Winter email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdlib.h> #include <iostream> #include <qdatetime.h> #include <kdebug.h> #include <klocale.h> #include <libkcal/calendarlocal.h> #include <libkcal/calendar.h> #include <libkcal/event.h> #include <libkcal/htmlexport.h> #include "konsolekalendarexports.h" using namespace KCal; using namespace std; KonsoleKalendarExports::KonsoleKalendarExports( KonsoleKalendarVariables *variables ) { m_variables = variables; m_firstEntry = true; } KonsoleKalendarExports::~KonsoleKalendarExports() { } bool KonsoleKalendarExports::exportAsTxt( QTextStream *ts, Event *event ){ if( m_firstEntry == true || m_lastDate.day() != event->dtStart().date().day() || m_lastDate.month() != event->dtStart().date().month() || m_lastDate.year() != event->dtStart().date().year() ){ m_firstEntry=false; int len = event->dtStartStr().length(); QString date = event->dtStartStr(); date.truncate( len - 5 ); *ts << I18N_NOOP("Date:") << "\t" << date.local8Bit() << endl; m_lastDate = event->dtStart().date(); } if ( !event->doesFloat() ) { *ts << "\t"; *ts << event->dtStartStr().remove(0, (event->dtStartStr().find(' ', 0, false) + 1) ).local8Bit(); *ts << " - "; *ts << event->dtEndStr().remove(0, (event->dtEndStr().find(' ', 0, false) + 1) ).local8Bit(); } *ts << endl << I18N_NOOP("Summary:") << endl; *ts << "\t" << event->summary().local8Bit() << endl; *ts << I18N_NOOP("Description:") << endl; if( !event->description().isEmpty() ) { *ts << "\t" << event->description().local8Bit() << endl; } else { *ts << "\t" << I18N_NOOP("(no description available)") << endl; } *ts << I18N_NOOP("UID:") << endl; *ts << "\t" << event->uid().local8Bit() << endl; *ts << "----------------------------------" << endl; return true; } bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, Event *event ){ // startdate,starttime,enddate,endtime,summary,description,UID QString delim = ","; //one day maybe the delim character can be an option?? if ( !event->doesFloat() ) { *ts << event->dtStart().date().toString("yyyy-M-d"); *ts << delim << event->dtStart().time().toString("hh:mm"); *ts << delim << event->dtEnd().date().toString("yyyy-M-d"); *ts << delim << event->dtEnd().time().toString("hh:mm"); } else { *ts << ",,,"; } *ts << delim << event->summary().local8Bit(); *ts << delim << event->description().local8Bit(); *ts << delim << event->uid().local8Bit(); *ts << endl; return true; } // Old function for printing out as keyword:<tab>value //bool KonsoleKalendarExports::exportAsCSV( QTextStream *ts, Event *event ){ // // if ( !event->doesFloat() ) { // *ts << event->dtStartStr().remove(0, (event->dtStartStr().find(' ', 0, false) + 1) ).local8Bit(); // *ts << "\t"; // *ts << event->dtEndStr().remove(0, (event->dtEndStr().find(' ', 0, false) + 1) ).local8Bit(); // } // // *ts << "\t" << I18N_NOOP("Summary:"); // *ts << "\t\"" << event->summary().local8Bit() << "\""; // *ts << "\t" << I18N_NOOP("Description:"); // *ts << "\t\"" << event->description().local8Bit() << "\""; // *ts << "\t" << I18N_NOOP("UID:"); // *ts << "\t" << event->uid().local8Bit() << endl; // // return true; //} <|endoftext|>
<commit_before>/* testhhrecord.cc KPilot ** ** Copyright (C) 2007 by Bertjan Broeksema <[email protected]> ** Copyright (C) 2007 by Jason "vanRijn" Kasper <[email protected]> */ /* ** This program 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 program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "testhhrecord.h" #include "testrecord.h" #include "options.h" TestHHRecord::TestHHRecord( const QStringList& fields, const QString &id ) : HHRecord( 0L, CSL1( "Unfiled" ) ), fId( id ), fFields( fields ), fModified( false ) , fDeleted( false ), fArchived( false ) { } TestHHRecord::TestHHRecord( const TestHHRecord *other ) : HHRecord( 0L, CSL1( "Unfiled" ) ) { fId = other->id(); fFields = other->fields(); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); setValue( field, other->value( field ) ); } fModified = other->isModified(); fDeleted = other->isDeleted(); fArchived = other->isArchived();; } TestHHRecord::TestHHRecord( const TestRecord *other ) : HHRecord( 0L, CSL1( "Unfiled" ) ) { fId = other->id(); fFields = other->fields(); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); setValue( field, other->value( field ) ); } fModified = other->isModified(); fDeleted = other->isDeleted(); fArchived = false; } void TestHHRecord::setArchived() { setDeleted(); fArchived = true; } void TestHHRecord::setDeleted() { fDeleted = true; } void TestHHRecord::setModified() { fModified = true; } const QString TestHHRecord::id() const { return fId; } void TestHHRecord::setId( const QString &id ) { fId = id; } QVariant TestHHRecord::value( const QString &field ) const { return fValues.value( field ); } bool TestHHRecord::setValue( const QString &field, const QVariant &value ) { fValues.insert( field, value ); fModified = true; return true; } bool TestHHRecord::isModified() const { return fModified || isDeleted(); } bool TestHHRecord::isDeleted() const { return fDeleted; } void TestHHRecord::synced() { fDeleted = false; fModified = false; } QString TestHHRecord::toString() const { QString representation = fId + CSL1( " [" ); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); representation += CSL1( " " ); representation += field; representation += CSL1( "=\"" ); representation += fValues.value( field ).toString(); representation += CSL1( "\"" ); } representation += CSL1( " ]" ); return representation; } const QStringList TestHHRecord::fields() const { return fFields; } TestHHRecord* TestHHRecord::duplicate() const { return new TestHHRecord( this ); } bool TestHHRecord::equal( const Record *rec ) const { if( const TestRecord *other = dynamic_cast<const TestRecord*>( rec ) ) { QStringList fields = other->fields(); QStringListIterator it(fields); bool allEqual = true; while( it.hasNext() ) { QString field = it.next(); allEqual = allEqual && ( fValues.value( field ) == other->value( field ) ); } return allEqual && (fields == fFields); } else if( const TestHHRecord *other = dynamic_cast<const TestHHRecord*>( rec ) ) { QStringList fields = other->fields(); QStringListIterator it(fields); bool allEqual = true; while( it.hasNext() ) { QString field = it.next(); allEqual = allEqual && ( fValues.value( field ) == other->value( field ) ); } return allEqual && (fields == fFields); } return false; } <commit_msg>Create a pilotRecord in the the TestHHRecord to avoid seg faults when the conduit tries to set the category.<commit_after>/* testhhrecord.cc KPilot ** ** Copyright (C) 2007 by Bertjan Broeksema <[email protected]> ** Copyright (C) 2007 by Jason "vanRijn" Kasper <[email protected]> */ /* ** This program 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 program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "testhhrecord.h" #include "testrecord.h" #include "options.h" #include "pilotRecord.h" TestHHRecord::TestHHRecord( const QStringList& fields, const QString &id ) : HHRecord( 0L, CSL1( "Unfiled" ) ), fId( id ), fFields( fields ), fModified( false ) , fDeleted( false ), fArchived( false ) { pi_buffer_t *buf = pi_buffer_new( QString( "" ).size() ); Pilot::toPilot( QString(""), buf->data, 0 ); fRecord = new PilotRecord( buf, 0, 0, 0); fRecord->setCategory( 0 ); } TestHHRecord::TestHHRecord( const TestHHRecord *other ) : HHRecord( 0L, CSL1( "Unfiled" ) ) { fId = other->id(); fFields = other->fields(); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); setValue( field, other->value( field ) ); } fModified = other->isModified(); fDeleted = other->isDeleted(); fArchived = other->isArchived();; } TestHHRecord::TestHHRecord( const TestRecord *other ) : HHRecord( 0L, CSL1( "Unfiled" ) ) { fId = other->id(); fFields = other->fields(); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); setValue( field, other->value( field ) ); } fModified = other->isModified(); fDeleted = other->isDeleted(); fArchived = false; } void TestHHRecord::setArchived() { setDeleted(); fArchived = true; } void TestHHRecord::setDeleted() { fDeleted = true; } void TestHHRecord::setModified() { fModified = true; } const QString TestHHRecord::id() const { return fId; } void TestHHRecord::setId( const QString &id ) { fId = id; } QVariant TestHHRecord::value( const QString &field ) const { return fValues.value( field ); } bool TestHHRecord::setValue( const QString &field, const QVariant &value ) { fValues.insert( field, value ); fModified = true; return true; } bool TestHHRecord::isModified() const { return fModified || isDeleted(); } bool TestHHRecord::isDeleted() const { return fDeleted; } void TestHHRecord::synced() { fDeleted = false; fModified = false; } QString TestHHRecord::toString() const { QString representation = fId + CSL1( " [" ); QStringListIterator it(fFields); while( it.hasNext() ) { QString field = it.next(); representation += CSL1( " " ); representation += field; representation += CSL1( "=\"" ); representation += fValues.value( field ).toString(); representation += CSL1( "\"" ); } representation += CSL1( " ]" ); return representation; } const QStringList TestHHRecord::fields() const { return fFields; } TestHHRecord* TestHHRecord::duplicate() const { return new TestHHRecord( this ); } bool TestHHRecord::equal( const Record *rec ) const { if( const TestRecord *other = dynamic_cast<const TestRecord*>( rec ) ) { QStringList fields = other->fields(); QStringListIterator it(fields); bool allEqual = true; while( it.hasNext() ) { QString field = it.next(); allEqual = allEqual && ( fValues.value( field ) == other->value( field ) ); } return allEqual && (fields == fFields); } else if( const TestHHRecord *other = dynamic_cast<const TestHHRecord*>( rec ) ) { QStringList fields = other->fields(); QStringListIterator it(fields); bool allEqual = true; while( it.hasNext() ) { QString field = it.next(); allEqual = allEqual && ( fValues.value( field ) == other->value( field ) ); } return allEqual && (fields == fFields); } return false; } <|endoftext|>
<commit_before>// Author: Jingyue #include <cstdio> #include <set> using namespace std; #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #include "common/PointerAnalysis.h" using namespace rcs; #include "dyn-aa/LogRecord.h" #include "dyn-aa/IntervalTree.h" using namespace dyn_aa; namespace dyn_aa { struct DynamicPointerAnalysis: public ModulePass, public PointerAnalysis { static char ID; DynamicPointerAnalysis(): ModulePass(ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual void getAllPointers(ValueList &Pointers); virtual bool getPointees(const Value *Pointer, ValueList &Pointees); private: void processAddrTakenDecl(const AddrTakenDeclLogRecord &Record); void processTopLevelPointTo(const TopLevelPointToLogRecord &Record); void processAddrTakenPointTo(const AddrTakenPointToLogRecord &Record); // Returns the value ID of <Addr>'s allocator. // Possible allocators include malloc function calls, AllocaInsts, and // global variables. Value *lookupAddress(void *Addr) const; // Stores all addr-taken declarations. IntervalTree AddrTakenDecls; // Use DenseSet instead of vector, because they are usually lots of // duplicated edges. DenseMap<const Value *, ValueSet> PointTos; }; } static RegisterPass<DynamicPointerAnalysis> X("dyn-pa", "Build the point-to graph from " "the point-to log", false, true); static RegisterAnalysisGroup<PointerAnalysis> Y(X); static cl::opt<string> LogFileName("log-file", cl::desc("Point-to log file generated by " "running the instrumented program"), cl::init("")); char DynamicPointerAnalysis::ID = 0; bool DynamicPointerAnalysis::runOnModule(Module &M) { LogRecordType RecordType; int numRecords = 0; int numAddrTakenDecls = 0; int numAddrTakenPointTos = 0; int numTopLevelPointTos = 0; FILE *LogFile = fopen(LogFileName.c_str(), "rb"); while (fread(&RecordType, sizeof RecordType, 1, LogFile) == 1) { if (numRecords % 1000000 == 0) errs() << "Processed " << numRecords << " records\n"; ++numRecords; switch (RecordType) { case AddrTakenDecl: { ++numAddrTakenDecls; AddrTakenDeclLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processAddrTakenDecl(Record); } break; case TopLevelPointTo: { ++numTopLevelPointTos; TopLevelPointToLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processTopLevelPointTo(Record); } break; case AddrTakenPointTo: { ++numAddrTakenPointTos; AddrTakenPointToLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processAddrTakenPointTo(Record); } break; default: fprintf(stderr, "RecordType = %d\n", RecordType); assert(false && "Unknown record type"); } } errs() << "Processed " << numRecords << " records\n"; errs() << "# of addr-taken decls = " << numAddrTakenDecls << "\n"; errs() << "# of addr-taken point-tos = " << numAddrTakenPointTos << "\n"; errs() << "# of top-level point-tos = " << numTopLevelPointTos << "\n"; return false; } void DynamicPointerAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<IDAssigner>(); } void DynamicPointerAnalysis::processAddrTakenDecl( const AddrTakenDeclLogRecord &Record) { IDAssigner &IDA = getAnalysis<IDAssigner>(); Value *Allocator = IDA.getValue(Record.AllocatedBy); assert(Allocator); unsigned long Start = (unsigned long)Record.Address; Interval I(Start, Start + Record.Bound); pair<IntervalTree::iterator, IntervalTree::iterator> ER = AddrTakenDecls.equal_range(I); AddrTakenDecls.erase(ER.first, ER.second); AddrTakenDecls.insert(make_pair(I, Allocator)); } void DynamicPointerAnalysis::processTopLevelPointTo( const TopLevelPointToLogRecord &Record) { IDAssigner &IDA = getAnalysis<IDAssigner>(); Value *Pointer = IDA.getValue(Record.PointerValueID); Value *Pointee = lookupAddress(Record.PointeeAddress); assert(Pointer); if (Pointee) PointTos[Pointer].insert(Pointee); } void DynamicPointerAnalysis::processAddrTakenPointTo( const AddrTakenPointToLogRecord &Record) { Value *Pointer = lookupAddress(Record.PointerAddress); Value *Pointee = lookupAddress(Record.PointeeAddress); assert(Pointer); if (Pointee) PointTos[Pointer].insert(Pointee); } Value *DynamicPointerAnalysis::lookupAddress(void *Addr) const { Interval I((unsigned long)Addr, (unsigned long)Addr + 1); IntervalTree::const_iterator Pos = AddrTakenDecls.find(I); if (Pos == AddrTakenDecls.end()) return NULL; return Pos->second; } bool DynamicPointerAnalysis::getPointees(const Value *Pointer, ValueList &Pointees) { Pointees.clear(); DenseMap<const Value *, ValueSet>::iterator I = PointTos.find(Pointer); if (I == PointTos.end()) return false; Pointees.insert(Pointees.end(), I->second.begin(), I->second.end()); return true; } void DynamicPointerAnalysis::getAllPointers(ValueList &Pointers) { for (DenseMap<const Value *, ValueSet>::iterator I = PointTos.begin(); I != PointTos.end(); ++I) { Pointers.push_back(const_cast<Value *>(I->first)); } } <commit_msg>allow AddrTakenDecls have NULL values<commit_after>// Author: Jingyue #include <cstdio> #include <set> using namespace std; #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #include "common/PointerAnalysis.h" using namespace rcs; #include "dyn-aa/LogRecord.h" #include "dyn-aa/IntervalTree.h" using namespace dyn_aa; namespace dyn_aa { struct DynamicPointerAnalysis: public ModulePass, public PointerAnalysis { static char ID; DynamicPointerAnalysis(): ModulePass(ID) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual void getAllPointers(ValueList &Pointers); virtual bool getPointees(const Value *Pointer, ValueList &Pointees); private: void processAddrTakenDecl(const AddrTakenDeclLogRecord &Record); void processTopLevelPointTo(const TopLevelPointToLogRecord &Record); void processAddrTakenPointTo(const AddrTakenPointToLogRecord &Record); // Returns the value ID of <Addr>'s allocator. // Possible allocators include malloc function calls, AllocaInsts, and // global variables. Value *lookupAddress(void *Addr) const; // Stores all addr-taken declarations. IntervalTree AddrTakenDecls; // Use DenseSet instead of vector, because they are usually lots of // duplicated edges. DenseMap<const Value *, ValueSet> PointTos; }; } static RegisterPass<DynamicPointerAnalysis> X("dyn-pa", "Build the point-to graph from " "the point-to log", false, true); static RegisterAnalysisGroup<PointerAnalysis> Y(X); static cl::opt<string> LogFileName("log-file", cl::desc("Point-to log file generated by " "running the instrumented program"), cl::init("")); char DynamicPointerAnalysis::ID = 0; bool DynamicPointerAnalysis::runOnModule(Module &M) { LogRecordType RecordType; int numRecords = 0; int numAddrTakenDecls = 0; int numAddrTakenPointTos = 0; int numTopLevelPointTos = 0; FILE *LogFile = fopen(LogFileName.c_str(), "rb"); while (fread(&RecordType, sizeof RecordType, 1, LogFile) == 1) { if (numRecords % 1000000 == 0) errs() << "Processed " << numRecords << " records\n"; ++numRecords; switch (RecordType) { case AddrTakenDecl: { ++numAddrTakenDecls; AddrTakenDeclLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processAddrTakenDecl(Record); } break; case TopLevelPointTo: { ++numTopLevelPointTos; TopLevelPointToLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processTopLevelPointTo(Record); } break; case AddrTakenPointTo: { ++numAddrTakenPointTos; AddrTakenPointToLogRecord Record; assert(fread(&Record, sizeof Record, 1, LogFile) == 1); processAddrTakenPointTo(Record); } break; default: fprintf(stderr, "RecordType = %d\n", RecordType); assert(false && "Unknown record type"); } } errs() << "Processed " << numRecords << " records\n"; errs() << "# of addr-taken decls = " << numAddrTakenDecls << "\n"; errs() << "# of addr-taken point-tos = " << numAddrTakenPointTos << "\n"; errs() << "# of top-level point-tos = " << numTopLevelPointTos << "\n"; return false; } void DynamicPointerAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequired<IDAssigner>(); } void DynamicPointerAnalysis::processAddrTakenDecl( const AddrTakenDeclLogRecord &Record) { IDAssigner &IDA = getAnalysis<IDAssigner>(); Value *Allocator = NULL; if (Record.AllocatedBy != IDAssigner::INVALID_ID) Allocator = IDA.getValue(Record.AllocatedBy); // Allocator may be NULL. // In that case, the memory block is allocated by an external instruction. // e.g. main arguments. unsigned long Start = (unsigned long)Record.Address; Interval I(Start, Start + Record.Bound); pair<IntervalTree::iterator, IntervalTree::iterator> ER = AddrTakenDecls.equal_range(I); AddrTakenDecls.erase(ER.first, ER.second); AddrTakenDecls.insert(make_pair(I, Allocator)); } void DynamicPointerAnalysis::processTopLevelPointTo( const TopLevelPointToLogRecord &Record) { IDAssigner &IDA = getAnalysis<IDAssigner>(); Value *Pointer = IDA.getValue(Record.PointerValueID); Value *Pointee = lookupAddress(Record.PointeeAddress); assert(Pointer); if (Pointee) PointTos[Pointer].insert(Pointee); } void DynamicPointerAnalysis::processAddrTakenPointTo( const AddrTakenPointToLogRecord &Record) { Value *Pointer = lookupAddress(Record.PointerAddress); Value *Pointee = lookupAddress(Record.PointeeAddress); assert(Pointer); if (Pointee) PointTos[Pointer].insert(Pointee); } Value *DynamicPointerAnalysis::lookupAddress(void *Addr) const { Interval I((unsigned long)Addr, (unsigned long)Addr + 1); IntervalTree::const_iterator Pos = AddrTakenDecls.find(I); if (Pos == AddrTakenDecls.end()) return NULL; return Pos->second; } bool DynamicPointerAnalysis::getPointees(const Value *Pointer, ValueList &Pointees) { Pointees.clear(); DenseMap<const Value *, ValueSet>::iterator I = PointTos.find(Pointer); if (I == PointTos.end()) return false; Pointees.insert(Pointees.end(), I->second.begin(), I->second.end()); return true; } void DynamicPointerAnalysis::getAllPointers(ValueList &Pointers) { for (DenseMap<const Value *, ValueSet>::iterator I = PointTos.begin(); I != PointTos.end(); ++I) { Pointers.push_back(const_cast<Value *>(I->first)); } } <|endoftext|>
<commit_before>// // Copyright 2013-2014, Bradley A. Grantham // // 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 <cstdio> #include <cstdlib> #include <string> #include <map> #include <limits> #include <algorithm> #include <vector> #include <unistd.h> #define GLFW_INCLUDE_GLCOREARB #include <GLFW/glfw3.h> #include "vectormath.h" #include "geometry.h" #include "manipulator.h" #include "drawable.h" #include "builtin_loader.h" #include "trisrc_loader.h" //------------------------------------------------------------------------ static manipulator *gSceneManip; static manipulator *gObjectManip; static manipulator *gCurrentManip = NULL; static bool gDrawWireframe = false; static bool gStreamFrames = false; static int gWindowWidth; static int gWindowHeight; static double gMotionReported = false; static double gOldMouseX, gOldMouseY; static int gButtonPressed = -1; // XXX Allow these to be set by options bool gVerbose = true; std::vector<Drawable::sptr> gObjects; float gFOV = 45; struct Light { vec4f position; vec4f color; Light(const vec4f& position_, const vec4f color_) : position(position_), color(color_) {} }; struct Environment { mat4f projection; mat4f modelview; std::vector<Light> lights; // only one supported at present Environment(const mat4f& projection_, const mat4f& modelview_, const std::vector<Light>& lights_) : projection(projection_), modelview(modelview_), lights(lights_) {} }; struct DisplayInfo { mat4f modelview; GLuint program; DisplayInfo(const mat4f& modelview_, GLuint program_) : modelview(modelview_), program(program_) {} struct Comparator { bool operator() (const DisplayInfo& d1, const DisplayInfo& d2) const { for(int i = 0; i < 16; i++) { if(d1.modelview.m_v[i] < d2.modelview.m_v[i]) return true; if(d1.modelview.m_v[i] < d2.modelview.m_v[i]) return false; } if(d1.program < d2.program) return true; if(d1.program < d2.program) return false; return false; } }; }; typedef std::map<DisplayInfo, std::vector<Drawable::sptr>, DisplayInfo::Comparator> DisplayList; struct Node { typedef boost::shared_ptr<Node> sptr; box bounds; // Later can cull virtual void Visit(const Environment& env, DisplayList& displaylist) = 0; Node(const box& bounds_) : bounds(bounds_) {} }; struct Shape : public Node { typedef boost::shared_ptr<Shape> sptr; Drawable::sptr drawable; virtual void Visit(const Environment& env, DisplayList& displaylist); Shape(const Drawable::sptr& drawable_) : Node(drawable->bounds), drawable(drawable_) {} }; void Shape::Visit(const Environment& env, DisplayList& displaylist) { displaylist[DisplayInfo(env.modelview, drawable->GetProgram())].push_back(drawable); } box TransformedBounds(const mat4f& transform, std::vector<Node::sptr> children) { box b; for(auto it = children.begin(); it != children.end(); it++) b.extend((*it)->bounds * transform); return b; } struct Group : public Node { typedef boost::shared_ptr<Group> sptr; mat4f transform; std::vector<Node::sptr> children; virtual void Visit(const Environment& env, DisplayList& displaylist); Group(const mat4f& transform_, std::vector<Node::sptr> children_) : Node(TransformedBounds(transform_, children_)), transform(transform_), children(children_) {} }; void Group::Visit(const Environment& env, DisplayList& displaylist) { mat4f newtransform = transform * env.modelview; Environment env2(env.projection, newtransform, env.lights); for(auto it = children.begin(); it != children.end(); it++) (*it)->Visit(env2, displaylist); } void DrawScene() { float nearClip, farClip; /* XXX - need to create new box from all subordinate boxes */ nearClip = - gSceneManip->m_translation[2] - gSceneManip->m_reference_size; farClip = - gSceneManip->m_translation[2] + gSceneManip->m_reference_size; if(nearClip < 0.1 * gSceneManip->m_reference_size) nearClip = 0.1 * gSceneManip->m_reference_size; if(farClip < 0.2 * gSceneManip->m_reference_size) nearClip = 0.2 * gSceneManip->m_reference_size; float frustumLeft, frustumRight, frustumBottom, frustumTop; frustumTop = tanf(gFOV / 180.0 * 3.14159 / 2) * nearClip; frustumBottom = -frustumTop; frustumRight = frustumTop * gWindowWidth / gWindowHeight; frustumLeft = -frustumRight; mat4f projection = mat4f::frustum(frustumLeft, frustumRight, frustumBottom, frustumTop, nearClip, farClip); Light light(vec4f(.577, .577, .577, 0), vec4f(1, 1, 1, 1)); GLuint prevprogram; for(auto it = gObjects.begin(); it != gObjects.end(); it++) { Drawable::sptr ob(*it); GLuint program = ob->GetProgram(); if(program != prevprogram) { glUseProgram(program); EnvironmentUniforms envu = ob->GetEnvironmentUniforms(); glUniformMatrix4fv(envu.projection, 1, GL_FALSE, projection.m_v); CheckOpenGL(__FILE__, __LINE__); glUniform4fv(envu.lightPosition, 1, light.position.m_v); glUniform4fv(envu.lightColor, 1, light.color.m_v); CheckOpenGL(__FILE__, __LINE__); /* draw floor, draw shadow, etc */ // XXX same object matrix for all objects mat4f modelview = gObjectManip->m_matrix * gSceneManip->m_matrix; mat4f modelview_normal = modelview; // XXX should not invert every time; parallel normal matrix math path? modelview_normal.transpose(); modelview_normal.invert(); glUniformMatrix4fv(envu.modelview, 1, GL_FALSE, modelview.m_v); glUniformMatrix4fv(envu.modelviewNormal, 1, GL_FALSE, modelview_normal.m_v); prevprogram = program; } ob->Draw(0, gDrawWireframe); } } void InitializeGL() { CheckOpenGL(__FILE__, __LINE__); glClearColor(.25, .25, .25, 0); glEnable(GL_DEPTH_TEST); // glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); CheckOpenGL(__FILE__, __LINE__); } void TeardownGL() { } static void InitializeScene(std::vector<Drawable::sptr>& objects) { box bounds; for(auto it = objects.begin(); it != objects.end(); it++) { Drawable::sptr ob(*it); bounds.extend(ob->bounds); } gSceneManip = new manipulator(bounds, gFOV / 180.0 * 3.14159); gObjectManip = new manipulator(); gObjectManip->calculate_matrix(); gCurrentManip = gSceneManip; } static void ErrorCallback(int error, const char* description) { fprintf(stderr, "GLFW: %s\n", description); } static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { if(action == GLFW_PRESS) { switch(key) { case 'W': gDrawWireframe = !gDrawWireframe; break; case 'R': gCurrentManip->m_mode = manipulator::ROTATE; break; case 'O': gCurrentManip->m_mode = manipulator::ROLL; break; case 'X': gCurrentManip->m_mode = manipulator::SCROLL; break; case 'Z': gCurrentManip->m_mode = manipulator::DOLLY; break; case '1': gCurrentManip = gSceneManip; break; case '2': gCurrentManip = gObjectManip; break; case 'Q': case '\033': glfwSetWindowShouldClose(window, GL_TRUE); break; } } } static void ResizeCallback(GLFWwindow *window, int x, int y) { glfwGetFramebufferSize(window, &gWindowWidth, &gWindowHeight); glViewport(0, 0, gWindowWidth, gWindowHeight); } static void ButtonCallback(GLFWwindow *window, int b, int action, int mods) { double x, y; glfwGetCursorPos(window, &x, &y); if(b == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) { gButtonPressed = 1; gOldMouseX = x; gOldMouseY = y; } else { gButtonPressed = -1; } } static void MotionCallback(GLFWwindow *window, double x, double y) { // glfw/glfw#103 // If no motion has been reported yet, we catch the first motion // reported and store the current location if(!gMotionReported) { gMotionReported = true; gOldMouseX = x; gOldMouseY = y; } double dx, dy; dx = x - gOldMouseX; dy = y - gOldMouseY; gOldMouseX = x; gOldMouseY = y; if(gButtonPressed == 1) { gCurrentManip->move(dx / gWindowWidth, dy / gWindowHeight); if(gCurrentManip == gSceneManip) gObjectManip->set_frame(gSceneManip->m_matrix); } } static void ScrollCallback(GLFWwindow *window, double dx, double dy) { gCurrentManip->move(dx / gWindowWidth, dy / gWindowHeight); if(gCurrentManip == gSceneManip) gObjectManip->set_frame(gSceneManip->m_matrix); } static void DrawFrame(GLFWwindow *window) { CheckOpenGL(__FILE__, __LINE__); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CheckOpenGL(__FILE__, __LINE__); DrawScene(); CheckOpenGL(__FILE__, __LINE__); } bool LoadScene(const std::string& filename, std::vector<Drawable::sptr>& objects) { int index = filename.find_last_of("."); std::string extension = filename.substr(index + 1); if(extension == "builtin") { return BuiltinLoader::Load(filename, objects); } else if(extension == "trisrc") { return TriSrcLoader::Load(filename, objects); } else { return false; } } int main(int argc, char **argv) { const char *progname = argv[0]; if(argc < 2) { fprintf(stderr, "usage: %s filename # e.g. \"%s 64gon.builtin\"\n", progname, progname); exit(EXIT_FAILURE); } const char *scene_filename = argv[1]; GLFWwindow* window; glfwSetErrorCallback(ErrorCallback); if(!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); window = glfwCreateWindow(gWindowWidth = 512, gWindowHeight = 512, "Spin", NULL, NULL); if (!window) { glfwTerminate(); fprintf(stdout, "Couldn't open main window\n"); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); InitializeGL(); if(!LoadScene(scene_filename, gObjects)) { fprintf(stderr, "couldn't load scene from %s\n", scene_filename); exit(EXIT_FAILURE); } InitializeScene(gObjects); if(gVerbose) { printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER)); printf("GL_VERSION: %s\n", glGetString(GL_VERSION)); } glfwSetKeyCallback(window, KeyCallback); glfwSetMouseButtonCallback(window, ButtonCallback); glfwSetCursorPosCallback(window, MotionCallback); glfwSetScrollCallback(window, ScrollCallback); glfwSetFramebufferSizeCallback(window, ResizeCallback); glfwSetWindowRefreshCallback(window, DrawFrame); while (!glfwWindowShouldClose(window)) { DrawFrame(window); glfwSwapBuffers(window); if(gStreamFrames) glfwPollEvents(); else glfwWaitEvents(); } glfwTerminate(); } <commit_msg>remove gObjectManip<commit_after>// // Copyright 2013-2014, Bradley A. Grantham // // 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 <cstdio> #include <cstdlib> #include <string> #include <map> #include <limits> #include <algorithm> #include <vector> #include <unistd.h> #define GLFW_INCLUDE_GLCOREARB #include <GLFW/glfw3.h> #include "vectormath.h" #include "geometry.h" #include "manipulator.h" #include "drawable.h" #include "builtin_loader.h" #include "trisrc_loader.h" //------------------------------------------------------------------------ static manipulator *gSceneManip; static manipulator *gCurrentManip = NULL; static bool gDrawWireframe = false; static bool gStreamFrames = false; static int gWindowWidth; static int gWindowHeight; static double gMotionReported = false; static double gOldMouseX, gOldMouseY; static int gButtonPressed = -1; // XXX Allow these to be set by options bool gVerbose = true; std::vector<Drawable::sptr> gObjects; float gFOV = 45; struct Light { vec4f position; vec4f color; Light(const vec4f& position_, const vec4f color_) : position(position_), color(color_) {} }; struct Environment { mat4f projection; mat4f modelview; std::vector<Light> lights; // only one supported at present Environment(const mat4f& projection_, const mat4f& modelview_, const std::vector<Light>& lights_) : projection(projection_), modelview(modelview_), lights(lights_) {} }; struct DisplayInfo { mat4f modelview; GLuint program; DisplayInfo(const mat4f& modelview_, GLuint program_) : modelview(modelview_), program(program_) {} struct Comparator { bool operator() (const DisplayInfo& d1, const DisplayInfo& d2) const { for(int i = 0; i < 16; i++) { if(d1.modelview.m_v[i] < d2.modelview.m_v[i]) return true; if(d1.modelview.m_v[i] < d2.modelview.m_v[i]) return false; } if(d1.program < d2.program) return true; if(d1.program < d2.program) return false; return false; } }; }; typedef std::map<DisplayInfo, std::vector<Drawable::sptr>, DisplayInfo::Comparator> DisplayList; struct Node { typedef boost::shared_ptr<Node> sptr; box bounds; // Later can cull virtual void Visit(const Environment& env, DisplayList& displaylist) = 0; Node(const box& bounds_) : bounds(bounds_) {} }; struct Shape : public Node { typedef boost::shared_ptr<Shape> sptr; Drawable::sptr drawable; virtual void Visit(const Environment& env, DisplayList& displaylist); Shape(const Drawable::sptr& drawable_) : Node(drawable->bounds), drawable(drawable_) {} }; void Shape::Visit(const Environment& env, DisplayList& displaylist) { displaylist[DisplayInfo(env.modelview, drawable->GetProgram())].push_back(drawable); } box TransformedBounds(const mat4f& transform, std::vector<Node::sptr> children) { box b; for(auto it = children.begin(); it != children.end(); it++) b.extend((*it)->bounds * transform); return b; } struct Group : public Node { typedef boost::shared_ptr<Group> sptr; mat4f transform; std::vector<Node::sptr> children; virtual void Visit(const Environment& env, DisplayList& displaylist); Group(const mat4f& transform_, std::vector<Node::sptr> children_) : Node(TransformedBounds(transform_, children_)), transform(transform_), children(children_) {} }; void Group::Visit(const Environment& env, DisplayList& displaylist) { mat4f newtransform = transform * env.modelview; Environment env2(env.projection, newtransform, env.lights); for(auto it = children.begin(); it != children.end(); it++) (*it)->Visit(env2, displaylist); } void DrawScene() { float nearClip, farClip; /* XXX - need to create new box from all subordinate boxes */ nearClip = - gSceneManip->m_translation[2] - gSceneManip->m_reference_size; farClip = - gSceneManip->m_translation[2] + gSceneManip->m_reference_size; if(nearClip < 0.1 * gSceneManip->m_reference_size) nearClip = 0.1 * gSceneManip->m_reference_size; if(farClip < 0.2 * gSceneManip->m_reference_size) nearClip = 0.2 * gSceneManip->m_reference_size; float frustumLeft, frustumRight, frustumBottom, frustumTop; frustumTop = tanf(gFOV / 180.0 * 3.14159 / 2) * nearClip; frustumBottom = -frustumTop; frustumRight = frustumTop * gWindowWidth / gWindowHeight; frustumLeft = -frustumRight; mat4f projection = mat4f::frustum(frustumLeft, frustumRight, frustumBottom, frustumTop, nearClip, farClip); Light light(vec4f(.577, .577, .577, 0), vec4f(1, 1, 1, 1)); GLuint prevprogram; for(auto it = gObjects.begin(); it != gObjects.end(); it++) { Drawable::sptr ob(*it); GLuint program = ob->GetProgram(); if(program != prevprogram) { glUseProgram(program); EnvironmentUniforms envu = ob->GetEnvironmentUniforms(); glUniformMatrix4fv(envu.projection, 1, GL_FALSE, projection.m_v); CheckOpenGL(__FILE__, __LINE__); glUniform4fv(envu.lightPosition, 1, light.position.m_v); glUniform4fv(envu.lightColor, 1, light.color.m_v); CheckOpenGL(__FILE__, __LINE__); /* draw floor, draw shadow, etc */ // XXX same object matrix for all objects mat4f modelview = gSceneManip->m_matrix; mat4f modelview_normal = modelview; // XXX should not invert every time // XXX parallel normal matrix math path? modelview_normal.transpose(); modelview_normal.invert(); glUniformMatrix4fv(envu.modelview, 1, GL_FALSE, modelview.m_v); glUniformMatrix4fv(envu.modelviewNormal, 1, GL_FALSE, modelview_normal.m_v); prevprogram = program; } ob->Draw(0, gDrawWireframe); } } void InitializeGL() { CheckOpenGL(__FILE__, __LINE__); glClearColor(.25, .25, .25, 0); glEnable(GL_DEPTH_TEST); // glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); CheckOpenGL(__FILE__, __LINE__); } void TeardownGL() { } static void InitializeScene(std::vector<Drawable::sptr>& objects) { box bounds; for(auto it = objects.begin(); it != objects.end(); it++) { Drawable::sptr ob(*it); bounds.extend(ob->bounds); } gSceneManip = new manipulator(bounds, gFOV / 180.0 * 3.14159); gCurrentManip = gSceneManip; } static void ErrorCallback(int error, const char* description) { fprintf(stderr, "GLFW: %s\n", description); } static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { if(action == GLFW_PRESS) { switch(key) { case 'W': gDrawWireframe = !gDrawWireframe; break; case 'R': gCurrentManip->m_mode = manipulator::ROTATE; break; case 'O': gCurrentManip->m_mode = manipulator::ROLL; break; case 'X': gCurrentManip->m_mode = manipulator::SCROLL; break; case 'Z': gCurrentManip->m_mode = manipulator::DOLLY; break; case 'Q': case '\033': glfwSetWindowShouldClose(window, GL_TRUE); break; } } } static void ResizeCallback(GLFWwindow *window, int x, int y) { glfwGetFramebufferSize(window, &gWindowWidth, &gWindowHeight); glViewport(0, 0, gWindowWidth, gWindowHeight); } static void ButtonCallback(GLFWwindow *window, int b, int action, int mods) { double x, y; glfwGetCursorPos(window, &x, &y); if(b == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) { gButtonPressed = 1; gOldMouseX = x; gOldMouseY = y; } else { gButtonPressed = -1; } } static void MotionCallback(GLFWwindow *window, double x, double y) { // glfw/glfw#103 // If no motion has been reported yet, we catch the first motion // reported and store the current location if(!gMotionReported) { gMotionReported = true; gOldMouseX = x; gOldMouseY = y; } double dx, dy; dx = x - gOldMouseX; dy = y - gOldMouseY; gOldMouseX = x; gOldMouseY = y; if(gButtonPressed == 1) { gCurrentManip->move(dx / gWindowWidth, dy / gWindowHeight); } } static void ScrollCallback(GLFWwindow *window, double dx, double dy) { gCurrentManip->move(dx / gWindowWidth, dy / gWindowHeight); } static void DrawFrame(GLFWwindow *window) { CheckOpenGL(__FILE__, __LINE__); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CheckOpenGL(__FILE__, __LINE__); DrawScene(); CheckOpenGL(__FILE__, __LINE__); } bool LoadScene(const std::string& filename, std::vector<Drawable::sptr>& objects) { int index = filename.find_last_of("."); std::string extension = filename.substr(index + 1); if(extension == "builtin") { return BuiltinLoader::Load(filename, objects); } else if(extension == "trisrc") { return TriSrcLoader::Load(filename, objects); } else { return false; } } int main(int argc, char **argv) { const char *progname = argv[0]; if(argc < 2) { fprintf(stderr, "usage: %s filename # e.g. \"%s 64gon.builtin\"\n", progname, progname); exit(EXIT_FAILURE); } const char *scene_filename = argv[1]; GLFWwindow* window; glfwSetErrorCallback(ErrorCallback); if(!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); window = glfwCreateWindow(gWindowWidth = 512, gWindowHeight = 512, "Spin", NULL, NULL); if (!window) { glfwTerminate(); fprintf(stdout, "Couldn't open main window\n"); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); InitializeGL(); if(!LoadScene(scene_filename, gObjects)) { fprintf(stderr, "couldn't load scene from %s\n", scene_filename); exit(EXIT_FAILURE); } InitializeScene(gObjects); if(gVerbose) { printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER)); printf("GL_VERSION: %s\n", glGetString(GL_VERSION)); } glfwSetKeyCallback(window, KeyCallback); glfwSetMouseButtonCallback(window, ButtonCallback); glfwSetCursorPosCallback(window, MotionCallback); glfwSetScrollCallback(window, ScrollCallback); glfwSetFramebufferSizeCallback(window, ResizeCallback); glfwSetWindowRefreshCallback(window, DrawFrame); while (!glfwWindowShouldClose(window)) { DrawFrame(window); glfwSwapBuffers(window); if(gStreamFrames) glfwPollEvents(); else glfwWaitEvents(); } glfwTerminate(); } <|endoftext|>
<commit_before>/** * \file * \brief priorityTestPhases object declaration * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef TEST_PRIORITYTESTPHASES_HPP_ #define TEST_PRIORITYTESTPHASES_HPP_ #include <array> namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | global constants +---------------------------------------------------------------------------------------------------------------------*/ /// number of test threads constexpr size_t totalThreads {10}; /// number of test phases constexpr size_t totalPhases {8}; /// max priority used in test phases constexpr uint8_t maxPhasePriority {UINT8_MAX}; /*---------------------------------------------------------------------------------------------------------------------+ | global types +---------------------------------------------------------------------------------------------------------------------*/ /// parameters of test thread - priority, sequence point using ThreadParameters = std::pair<uint8_t, uint8_t>; /// description of test phase - reference to array with ThreadParameters, sequence of indexes for this array using TestPhase = std::pair<const std::array<ThreadParameters, totalThreads>&, std::array<uint8_t, totalThreads>>; /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ /// array with test phases extern const std::array<TestPhase, totalPhases> priorityTestPhases; } // namespace test } // namespace distortos #endif // TEST_PRIORITYTESTPHASES_HPP_ <commit_msg>Reduce maxPhasePriority value in priorityTestPhases<commit_after>/** * \file * \brief priorityTestPhases object declaration * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef TEST_PRIORITYTESTPHASES_HPP_ #define TEST_PRIORITYTESTPHASES_HPP_ #include <array> namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | global constants +---------------------------------------------------------------------------------------------------------------------*/ /// number of test threads constexpr size_t totalThreads {10}; /// number of test phases constexpr size_t totalPhases {8}; /// max priority used in test phases constexpr uint8_t maxPhasePriority {UINT8_MAX - 1}; /*---------------------------------------------------------------------------------------------------------------------+ | global types +---------------------------------------------------------------------------------------------------------------------*/ /// parameters of test thread - priority, sequence point using ThreadParameters = std::pair<uint8_t, uint8_t>; /// description of test phase - reference to array with ThreadParameters, sequence of indexes for this array using TestPhase = std::pair<const std::array<ThreadParameters, totalThreads>&, std::array<uint8_t, totalThreads>>; /*---------------------------------------------------------------------------------------------------------------------+ | global objects +---------------------------------------------------------------------------------------------------------------------*/ /// array with test phases extern const std::array<TestPhase, totalPhases> priorityTestPhases; } // namespace test } // namespace distortos #endif // TEST_PRIORITYTESTPHASES_HPP_ <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/error.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/initialize.hpp> // TODO: Add support for for passing args, work dir, etc to CreateAndInject. // e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN? namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main(int argc, char* /*argv*/[]) { try { hadesmem::detail::InitializeAll(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("free", "unload module") ("add-path", "add module dir to serach order") ("run", boost::program_options::wvalue<std::wstring>(), "process path") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help") || argc == 1) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("module")) { std::cerr << "\nError! Module path must be specified.\n"; return 1; } bool const has_pid = (var_map.count("pid") != 0); bool const create_proc = (var_map.count("run") != 0); if ((has_pid && create_proc) || (!has_pid && !create_proc)) { std::cerr << "\nError! A process ID or an executable path must be " "specified.\n"; return 1; } bool const inject = (var_map.count("free") == 0); if (!inject && create_proc) { std::cerr << "\nError! Modules can only be unloaded from running " "targets.\n"; return 1; } std::wstring const module_path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } if (has_pid) { try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } DWORD const pid = var_map["pid"].as<DWORD>(); hadesmem::Process const process(pid); HMODULE module = nullptr; if (inject) { module = hadesmem::InjectDll(process, module_path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(module_path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); auto const export_ret = hadesmem::CallExport(process, module, export_name); std::wcout << "\nSuccessfully called module export.\n"; std::wcout << "Return: " << export_ret.GetReturnValue() << ".\n"; std::wcout << "LastError: " << export_ret.GetLastError() << ".\n"; } if (!inject) { hadesmem::FreeDll(process, module); std::wcout << "\nSuccessfully freed module at base address " << PtrToString(module) << ".\n"; } } else { std::wstring const exe_path = var_map["run"].as<std::wstring>(); std::string const export_name = var_map.count("export") ? var_map["export"].as<std::string>() : ""; hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( exe_path, L"", std::vector<std::wstring>::iterator(), std::vector<std::wstring>::iterator(), module_path, export_name, flags); std::wcout << "\nSuccessfully created target.\n"; std::wcout << "Process ID: " << inject_data.GetProcess() << ".\n"; std::wcout << "Module Base: " << PtrToString(inject_data.GetModule()) << ".\n"; std::wcout << "Export Return: " << inject_data.GetExportRet() << ".\n"; std::wcout << "Export LastError: " << inject_data.GetExportLastError() << ".\n"; } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <commit_msg>* Fix bug in Inject.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/error.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/initialize.hpp> // TODO: Add support for for passing args, work dir, etc to CreateAndInject. // e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN? namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main(int argc, char* /*argv*/[]) { try { hadesmem::detail::InitializeAll(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("free", "unload module") ("add-path", "add module dir to serach order") ("run", boost::program_options::wvalue<std::wstring>(), "process path") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help") || argc == 1) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("module")) { std::cerr << "\nError! Module path must be specified.\n"; return 1; } bool const has_pid = (var_map.count("pid") != 0); bool const create_proc = (var_map.count("run") != 0); if ((has_pid && create_proc) || (!has_pid && !create_proc)) { std::cerr << "\nError! A process ID or an executable path must be " "specified.\n"; return 1; } bool const inject = (var_map.count("free") == 0); if (!inject && create_proc) { std::cerr << "\nError! Modules can only be unloaded from running " "targets.\n"; return 1; } std::wstring const module_path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } if (has_pid) { try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } DWORD const pid = var_map["pid"].as<DWORD>(); hadesmem::Process const process(pid); HMODULE module = nullptr; if (inject) { module = hadesmem::InjectDll(process, module_path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(module_path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); auto const export_ret = hadesmem::CallExport(process, module, export_name); std::wcout << "\nSuccessfully called module export.\n"; std::wcout << "Return: " << export_ret.GetReturnValue() << ".\n"; std::wcout << "LastError: " << export_ret.GetLastError() << ".\n"; } if (!inject) { hadesmem::FreeDll(process, module); std::wcout << "\nSuccessfully freed module at base address " << PtrToString(module) << ".\n"; } } else { std::vector<std::wstring> args; std::wstring const exe_path = var_map["run"].as<std::wstring>(); std::string const export_name = var_map.count("export") ? var_map["export"].as<std::string>() : ""; hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( exe_path, L"", std::begin(args), std::end(args), module_path, export_name, flags); std::wcout << "\nSuccessfully created target.\n"; std::wcout << "Process ID: " << inject_data.GetProcess() << ".\n"; std::wcout << "Module Base: " << PtrToString(inject_data.GetModule()) << ".\n"; std::wcout << "Export Return: " << inject_data.GetExportRet() << ".\n"; std::wcout << "Export LastError: " << inject_data.GetExportLastError() << ".\n"; } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0. // Author: Jin Qing (http://blog.csdn.net/jq0123) // Dynamic singleton helper for manager class. // See struct manager::dyn_singleton_helper in // "(A dynamic) Singleton using weak_ptr and shared_ptr" // http://boost.2283326.n4.nabble.com/A-dynamic-Singleton-using-weak-ptr-and-shared-ptr-td2581447.html #include <rpcz/manager.hpp> namespace rpcz { manager::dyn_singleton_helper::manager_weak_ptr manager::dyn_singleton_helper::mgr_wptr; boost::recursive_mutex manager::dyn_singleton_helper::mgr_wptr_mtx; bool manager::dyn_singleton_helper::mgr_exists = false; boost::recursive_mutex manager::dyn_singleton_helper::mgr_exists_mtx; boost::condition_variable_any manager::dyn_singleton_helper::cond; struct manager::dyn_singleton_deleter { void operator()(manager* p) { BOOST_ASSERT(p); delete p; manager::dyn_singleton_helper::finish_destruction(); } }; void manager::dyn_singleton_helper::start_construction() { boost::recursive_mutex::scoped_lock lock(mgr_exists_mtx); while (mgr_exists) { cond.wait(lock); } mgr_exists = true; } void manager::dyn_singleton_helper::finish_destruction() { boost::recursive_mutex::scoped_lock lock(mgr_exists_mtx); mgr_exists = false; cond.notify_one(); } manager_ptr manager::dyn_singleton_helper::make_manager_ptr() { // Syncronise Initialization: boost::recursive_mutex::scoped_lock lock( dyn_singleton_helper::mgr_wptr_mtx); // Acquire singleton pointer: manager_ptr p = dyn_singleton_helper::mgr_wptr.lock(); if (p) return p; start_construction(); // blocking until previous object finished destruction. p.reset(new manager(), manager::dyn_singleton_deleter()); // shared_ptr mgr_wptr = p; return p; } } // namespace rpcz <commit_msg>cleanup in singleton helper<commit_after>// Licensed under the Apache License, Version 2.0. // Author: Jin Qing (http://blog.csdn.net/jq0123) // Dynamic singleton helper for manager class. // See struct manager::dyn_singleton_helper in // "(A dynamic) Singleton using weak_ptr and shared_ptr" // http://boost.2283326.n4.nabble.com/A-dynamic-Singleton-using-weak-ptr-and-shared-ptr-td2581447.html #include <rpcz/manager.hpp> namespace rpcz { manager::dyn_singleton_helper::manager_weak_ptr manager::dyn_singleton_helper::mgr_wptr; boost::recursive_mutex manager::dyn_singleton_helper::mgr_wptr_mtx; bool manager::dyn_singleton_helper::mgr_exists = false; boost::recursive_mutex manager::dyn_singleton_helper::mgr_exists_mtx; boost::condition_variable_any manager::dyn_singleton_helper::cond; struct manager::dyn_singleton_deleter { void operator()(manager* p) { BOOST_ASSERT(p); delete p; dyn_singleton_helper::finish_destruction(); } }; void manager::dyn_singleton_helper::start_construction() { boost::recursive_mutex::scoped_lock lock(mgr_exists_mtx); while (mgr_exists) { cond.wait(lock); } mgr_exists = true; } void manager::dyn_singleton_helper::finish_destruction() { boost::recursive_mutex::scoped_lock lock(mgr_exists_mtx); mgr_exists = false; cond.notify_one(); } manager_ptr manager::dyn_singleton_helper::make_manager_ptr() { // Syncronise Initialization: boost::recursive_mutex::scoped_lock lock(mgr_wptr_mtx); // Acquire singleton pointer: manager_ptr p = mgr_wptr.lock(); if (p) return p; start_construction(); // blocking until previous object finished destruction. p.reset(new manager(), manager::dyn_singleton_deleter()); // shared_ptr mgr_wptr = p; return p; } } // namespace rpcz <|endoftext|>
<commit_before>/* * Copyright (C) 2013 * Alessio Sclocco <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxThreadsMultiplier = 512; const unsigned int maxItemsPerThread = 256; const unsigned int maxItemsMultiplier = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 256; int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl; for ( unsigned int nrDMs = 2; nrDMs <= 4096; nrDMs *= 2 ) { observation.setNrDMs(nrDMs); for ( unsigned int nrPeriods = 2; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); counterData->blankHostData(); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 2; DMs <= maxThreadsPerBlock; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for (unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) { if ( (*DMs * periodsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrPeriods() % periodsPerBlock) != 0 ) { continue; } for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) { if ( (*DMs * periodsPerBlock * binsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrBins() % binsPerBlock) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) { if ( (observation.getNrDMs() % (*DMs * DMsPerThread)) != 0 ) { continue; } for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) { if ( (DMsPerThread * periodsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrPeriods() % (periodsPerBlock * periodsPerThread)) != 0 ) { continue; } for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) { if ( (DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrBins() % (binsPerBlock * binsPerThread))) != 0 ) { continue; } double Acur = 0.0; double Aold = 0.0; double Vcur = 0.0; double Vold = 0.0; try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrDMsPerBlock(*DMs); clFold.setNrPeriodsPerBlock(periodsPerBlock); clFold.setNrBinsPerBlock(binsPerBlock); clFold.setNrDMsPerThread(DMsPerThread); clFold.setNrPeriodsPerThread(periodsPerThread); clFold.setNrBinsPerThread(binsPerThread); clFold.generateCode(); clFold(dedispersedData, foldedData, counterData); (clFold.getTimer()).reset(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); } else { Aold = Acur; Vold = Vcur; Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1)); Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur)); } } Vcur = sqrt(Vcur / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *DMs << " " << periodsPerBlock << " " << binsPerBlock << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } } } } } cout << endl << endl; } } cout << endl; return 0; } <commit_msg>Typo, Fixed.<commit_after>/* * Copyright (C) 2013 * Alessio Sclocco <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxThreadsMultiplier = 512; const unsigned int maxItemsPerThread = 256; const unsigned int maxItemsMultiplier = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 256; int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl; for ( unsigned int nrDMs = 2; nrDMs <= 4096; nrDMs *= 2 ) { observation.setNrDMs(nrDMs); for ( unsigned int nrPeriods = 2; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); counterData->blankHostData(); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 2; DMs <= maxThreadsPerBlock; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for (unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) { if ( (*DMs * periodsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrPeriods() % periodsPerBlock) != 0 ) { continue; } for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) { if ( (*DMs * periodsPerBlock * binsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrBins() % binsPerBlock) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) { if ( (observation.getNrDMs() % (*DMs * DMsPerThread)) != 0 ) { continue; } for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) { if ( (DMsPerThread * periodsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrPeriods() % (periodsPerBlock * periodsPerThread)) != 0 ) { continue; } for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) { if ( (DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrBins() % (binsPerBlock * binsPerThread)) != 0 ) { continue; } double Acur = 0.0; double Aold = 0.0; double Vcur = 0.0; double Vold = 0.0; try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrDMsPerBlock(*DMs); clFold.setNrPeriodsPerBlock(periodsPerBlock); clFold.setNrBinsPerBlock(binsPerBlock); clFold.setNrDMsPerThread(DMsPerThread); clFold.setNrPeriodsPerThread(periodsPerThread); clFold.setNrBinsPerThread(binsPerThread); clFold.generateCode(); clFold(dedispersedData, foldedData, counterData); (clFold.getTimer()).reset(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); } else { Aold = Acur; Vold = Vcur; Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1)); Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur)); } } Vcur = sqrt(Vcur / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *DMs << " " << periodsPerBlock << " " << binsPerBlock << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } } } } } cout << endl << endl; } } cout << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_engine/test/auto_test/primitives/choice_helpers.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <algorithm> namespace webrtc { ChoiceBuilder::ChoiceBuilder(const std::string& title, const Choices& choices) : choices_(choices), input_helper_(TypedInput(title)) { input_helper_.WithInputValidator( new IntegerWithinRangeValidator(1, choices.size())); input_helper_.WithAdditionalInfo(MakeHumanReadableOptions()); } int ChoiceBuilder::Choose() { std::string input = input_helper_.AskForInput(); return atoi(input.c_str()); } ChoiceBuilder& ChoiceBuilder::WithDefault(const std::string& default_choice) { Choices::const_iterator iterator = std::find( choices_.begin(), choices_.end(), default_choice); assert(iterator != choices_.end() && "No such choice."); // Store the value as the choice number, e.g. its index + 1. int choice_index = (iterator - choices_.begin()) + 1; char number[16]; sprintf(number, "%d", choice_index); input_helper_.WithDefault(number); return *this; } ChoiceBuilder& ChoiceBuilder::WithInputSource(FILE* input_source) { input_helper_.WithInputSource(input_source); return *this; } std::string ChoiceBuilder::MakeHumanReadableOptions() { std::string result = ""; Choices::const_iterator iterator = choices_.begin(); for (int number = 1; iterator != choices_.end(); ++iterator, ++number) { char buffer[128]; sprintf(buffer, "\n %d. %s", number, (*iterator).c_str()); result += buffer; } return result; } Choices SplitChoices(const std::string& raw_choices) { return Split(raw_choices, "\n"); } ChoiceBuilder FromChoices( const std::string& title, const std::string& raw_choices) { return ChoiceBuilder(title, SplitChoices(raw_choices)); } } // namespace webrtc <commit_msg>Fix for buffer overflow, WebRTC issue 1196 Review URL: https://webrtc-codereview.appspot.com/998004<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_engine/test/auto_test/primitives/choice_helpers.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <algorithm> #include <sstream> namespace webrtc { ChoiceBuilder::ChoiceBuilder(const std::string& title, const Choices& choices) : choices_(choices), input_helper_(TypedInput(title)) { input_helper_.WithInputValidator( new IntegerWithinRangeValidator(1, choices.size())); input_helper_.WithAdditionalInfo(MakeHumanReadableOptions()); } int ChoiceBuilder::Choose() { std::string input = input_helper_.AskForInput(); return atoi(input.c_str()); } ChoiceBuilder& ChoiceBuilder::WithDefault(const std::string& default_choice) { Choices::const_iterator iterator = std::find( choices_.begin(), choices_.end(), default_choice); assert(iterator != choices_.end() && "No such choice."); // Store the value as the choice number, e.g. its index + 1. int choice_index = (iterator - choices_.begin()) + 1; char number[16]; sprintf(number, "%d", choice_index); input_helper_.WithDefault(number); return *this; } ChoiceBuilder& ChoiceBuilder::WithInputSource(FILE* input_source) { input_helper_.WithInputSource(input_source); return *this; } std::string ChoiceBuilder::MakeHumanReadableOptions() { std::string result = ""; Choices::const_iterator iterator = choices_.begin(); for (int number = 1; iterator != choices_.end(); ++iterator, ++number) { std::ostringstream os; os << "\n " << number << ". " << (*iterator).c_str(); result += os.str(); } return result; } Choices SplitChoices(const std::string& raw_choices) { return Split(raw_choices, "\n"); } ChoiceBuilder FromChoices( const std::string& title, const std::string& raw_choices) { return ChoiceBuilder(title, SplitChoices(raw_choices)); } } // namespace webrtc <|endoftext|>
<commit_before>// ==Montelight== // Tegan Brennan, Stephen Merity, Taiyo Wilson #include <cmath> #include <string> #include <fstream> #define EPSILON 0.01f using namespace std; struct Vector { double x, y, z; // Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {} Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {} inline Vector operator+(const Vector &o) const { return Vector(x + o.x, y + o.y, z + o.z); } inline Vector operator-(const Vector &o) const { return Vector(x - o.x, y - o.y, z - o.z); } inline Vector operator*(double o) const { return Vector(x * o, y * o, z * o); } inline double dot(const Vector &o) const { return x * o.x + y * o.y + z * o.z; } inline Vector &norm(){ return *this = *this * (1 / sqrt(x * x + y * y + z * z)); } inline Vector cross(Vector &o){ return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x); } }; struct Ray { Vector origin, direction; Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {} }; struct Image { unsigned int width, height; Vector *pixels; // Image(unsigned int w, unsigned int h) : width(w), height(h) { pixels = new Vector[width * height]; } void setPixel(unsigned int x, unsigned int y, const Vector &v) { pixels[(height - y) * width + x] = v; } void save(std::string filePrefix) { std::string filename = filePrefix + ".ppm"; std::ofstream f; f.open(filename.c_str(), std::ofstream::out); // PPM header: P3 => RGB, width, height, and max RGB value f << "P3 " << width << " " << height << " " << 255 << std::endl; // For each pixel, write the space separated RGB values for (int i=0; i < width * height; i++) { unsigned int r = pixels[i].x * 255, g = pixels[i].y * 255, b = pixels[i].z * 255; f << r << " " << g << " " << b << std::endl; } } ~Image() { delete[] pixels; } }; struct Shape { Vector color; // Shape(const Vector color_) : color(color_) {} virtual double intersects(const Ray &r) const { return 0; } }; struct Sphere : Shape { Vector center, color; double radius; // Sphere(const Vector center_, double radius_, const Vector color_) : Shape(color_), center(center_), radius(radius_) {} double intersects(const Ray &r) const { // Find if, and at what distance, the ray intersects with this object // Equation follows from solving quadratic equation of (r - c) ^ 2 // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection Vector offset = r.origin - center; double a = r.direction.dot(r.direction); double b = 2 * offset.dot(r.direction); double c = offset.dot(offset) - radius * radius; // Find discriminant for use in quadratic equation (b^2 - 4ac) double disc = b * b - 4 * a * c; // If the discriminant is negative, there are no real roots // (ray misses sphere) if (disc < 0) { return 0; } // The smallest positive root is the closest intersection point disc = sqrt(disc); double t = - b - disc; if (t > EPSILON) { return t; } t = - b + disc; if (t > EPSILON) { return t; } return 0; } }; int main(int argc, const char *argv[]) { // Initialize the image int w = 256, h = 256; Image img(w, h); // Set up the scene // Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html Shape *scene[] = {//Scene: radius, position, emission, color, material new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25)),//Left new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75)),//Rght new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75)),//Back new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector()),//Frnt new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75)),//Botm new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75)),//Top new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9),//Mirr new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9),//Glas new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1)) //Light }; // Set up the camera Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm()); // Upright camera with field of view angle set by 0.5135 Vector cx = Vector((w * 0.5135) / h, 0, 0); // Cross product gets the vector perpendicular to cx and the "gaze" direction Vector cy = (cx.cross(camera.direction)).norm() * 0.5135; // Take a set number of samples per pixel for (int samples = 0; samples < 1; ++samples) { // For each pixel, sample a ray in that direction for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { // Calculate the direction of the camera ray Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction; Ray ray = Ray(camera.origin + d * 140, d.norm()); // Check for intersection with objects in scene Vector color; double closest = 1e20f; for (auto obj : scene) { double hit = obj->intersects(ray); if (hit > 0 && hit < closest) { color = obj->color; closest = hit; } } // Add result of sample to image img.setPixel(x, y, color); } } } // Save the resulting raytraced image img.save("render"); return 0; } <commit_msg>Tracer now handles scene + intersections and we have shadow ray testing<commit_after>// ==Montelight== // Tegan Brennan, Stephen Merity, Taiyo Wilson #include <cmath> #include <string> #include <iostream> #include <fstream> #include <vector> #define EPSILON 0.1f using namespace std; struct Vector { double x, y, z; // Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {} Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {} inline Vector operator+(const Vector &o) const { return Vector(x + o.x, y + o.y, z + o.z); } inline Vector operator-(const Vector &o) const { return Vector(x - o.x, y - o.y, z - o.z); } inline Vector operator*(const Vector &o) const { return Vector(x * o.x, y * o.y, z * o.z); } inline Vector operator*(double o) const { return Vector(x * o, y * o, z * o); } inline double dot(const Vector &o) const { return x * o.x + y * o.y + z * o.z; } inline Vector &norm(){ return *this = *this * (1 / sqrt(x * x + y * y + z * z)); } inline Vector cross(Vector &o){ return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x); } inline double max() { return fmax(x, fmax(y, z)); } }; struct Ray { Vector origin, direction; Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {} }; struct Image { unsigned int width, height; Vector *pixels; // Image(unsigned int w, unsigned int h) : width(w), height(h) { pixels = new Vector[width * height]; } void setPixel(unsigned int x, unsigned int y, const Vector &v) { pixels[(height - y) * width + x] = v; } void save(std::string filePrefix) { std::string filename = filePrefix + ".ppm"; std::ofstream f; f.open(filename.c_str(), std::ofstream::out); // PPM header: P3 => RGB, width, height, and max RGB value f << "P3 " << width << " " << height << " " << 255 << std::endl; // For each pixel, write the space separated RGB values for (int i=0; i < width * height; i++) { unsigned int r = pixels[i].x * 255, g = pixels[i].y * 255, b = pixels[i].z * 255; f << r << " " << g << " " << b << std::endl; } } ~Image() { delete[] pixels; } }; struct Shape { Vector color, emit; // Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {} virtual double intersects(const Ray &r) const { return 0; } virtual Vector randomPoint() const { return Vector(); } }; struct Sphere : Shape { Vector center; double radius; // Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) : Shape(color_, emit_), center(center_), radius(radius_) {} double intersects(const Ray &r) const { // Find if, and at what distance, the ray intersects with this object // Equation follows from solving quadratic equation of (r - c) ^ 2 // http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection Vector offset = r.origin - center; double a = r.direction.dot(r.direction); double b = 2 * offset.dot(r.direction); double c = offset.dot(offset) - radius * radius; // Find discriminant for use in quadratic equation (b^2 - 4ac) double disc = b * b - 4 * a * c; // If the discriminant is negative, there are no real roots // (ray misses sphere) if (disc < 0) { return 0; } // The smallest positive root is the closest intersection point disc = sqrt(disc); double t = - b - disc; if (t > EPSILON) { return t / 2; } t = - b + disc; if (t > EPSILON) { return t / 2; } return 0; } Vector randomPoint() const { return center; } }; struct Tracer { std::vector<Shape *> scene; // Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {} std::pair<Shape *, double> getIntersection(const Ray &r) const { Shape *hitObj = NULL; double closest = 1e20f; for (Shape *obj : scene) { double distToHit = obj->intersects(r); if (distToHit > 0 && distToHit < closest) { hitObj = obj; closest = distToHit; } } return std::make_pair(hitObj, closest); } Vector getRadiance(const Ray &r, int depth) { // Work out what (if anything) was hit auto result = getIntersection(r); if (!result.first) { return Vector(); } Vector hit = r.origin + r.direction * result.second; // Work out the color Vector color; for (Shape *light : scene) { // Skip any objects that don't emit light if (light->emit.max() == 0) { continue; } Vector lightDirection = (light->randomPoint() - hit).norm(); Ray rayToLight = Ray(hit, lightDirection); auto lightHit = getIntersection(rayToLight); if (light == lightHit.first) { color = light->emit * result.first->color; } } return result.first->emit + color; } }; int main(int argc, const char *argv[]) { // Initialize the image int w = 256, h = 256; Image img(w, h); // Set up the scene // Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html std::vector<Shape *> scene = {//Scene: radius, position, emission, color, material new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Mirr new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9, Vector(0.4, 0.4, 0.4)),//Glas //new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1)) //Light new Sphere(Vector(50,65.1,81.6), 1.5, Vector(1,1,1), Vector(1,1,1)) //Light }; Tracer tracer = Tracer(scene); // Set up the camera Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm()); // Upright camera with field of view angle set by 0.5135 Vector cx = Vector((w * 0.5135) / h, 0, 0); // Cross product gets the vector perpendicular to cx and the "gaze" direction Vector cy = (cx.cross(camera.direction)).norm() * 0.5135; // Take a set number of samples per pixel for (int samples = 0; samples < 1; ++samples) { // For each pixel, sample a ray in that direction for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { // Calculate the direction of the camera ray Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction; Ray ray = Ray(camera.origin + d * 140, d.norm()); Vector color = tracer.getRadiance(ray, 0); // Add result of sample to image img.setPixel(x, y, color); } } } // Save the resulting raytraced image img.save("render"); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/error.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/initialize.hpp> // TODO: Add support for for passing args, work dir, etc to CreateAndInject. // e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN? namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main(int argc, char* /*argv*/[]) { try { hadesmem::detail::InitializeAll(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("free", "unload module") ("add-path", "add module dir to serach order") ("run", boost::program_options::wvalue<std::wstring>(), "process path") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help") || argc == 1) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("module")) { std::cerr << "\nError! Module path must be specified.\n"; return 1; } bool const has_pid = (var_map.count("pid") != 0); bool const create_proc = (var_map.count("run") != 0); if ((has_pid && create_proc) || (!has_pid && !create_proc)) { std::cerr << "\nError! A process ID or an executable path must be " "specified.\n"; return 1; } bool const inject = (var_map.count("free") == 0); if (!inject && create_proc) { std::cerr << "\nError! Modules can only be unloaded from running " "targets.\n"; return 1; } std::wstring const module_path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } if (has_pid) { try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } DWORD const pid = var_map["pid"].as<DWORD>(); hadesmem::Process const process(pid); HMODULE module = nullptr; if (inject) { module = hadesmem::InjectDll(process, module_path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(module_path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); auto const export_ret = hadesmem::CallExport(process, module, export_name); std::wcout << "\nSuccessfully called module export.\n"; std::wcout << "Return: " << export_ret.GetReturnValue() << ".\n"; std::wcout << "LastError: " << export_ret.GetLastError() << ".\n"; } if (!inject) { hadesmem::FreeDll(process, module); std::wcout << "\nSuccessfully freed module at base address " << PtrToString(module) << ".\n"; } } else { std::vector<std::wstring> create_args; std::wstring const exe_path = var_map["run"].as<std::wstring>(); std::string const export_name = var_map.count("export") ? var_map["export"].as<std::string>() : ""; hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( exe_path, L"", std::begin(create_args), std::end(create_args), module_path, export_name, flags); std::wcout << "\nSuccessfully created target.\n"; std::wcout << "Process ID: " << inject_data.GetProcess() << ".\n"; std::wcout << "Module Base: " << PtrToString(inject_data.GetModule()) << ".\n"; std::wcout << "Export Return: " << inject_data.GetExportRet() << ".\n"; std::wcout << "Export LastError: " << inject_data.GetExportLastError() << ".\n"; } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <commit_msg>* Make calling either InjectDll or FreeDll optional. (Support calling export by itself.)<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <memory> #include <string> #include <vector> #include <sstream> #include <iostream> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <windows.h> #include <hadesmem/call.hpp> #include <hadesmem/error.hpp> #include <hadesmem/config.hpp> #include <hadesmem/module.hpp> #include <hadesmem/process.hpp> #include <hadesmem/injector.hpp> #include <hadesmem/detail/self_path.hpp> #include <hadesmem/detail/initialize.hpp> // TODO: Add support for for passing args, work dir, etc to CreateAndInject. // e.g. exe-arg0, exe-arg1, exe-arg2, ..., exe-argN? namespace { std::wstring PtrToString(void const* const ptr) { std::wostringstream str; str.imbue(std::locale::classic()); str << std::hex << reinterpret_cast<DWORD_PTR>(ptr); return str.str(); } } int main(int argc, char* /*argv*/[]) { try { hadesmem::detail::InitializeAll(); std::cout << "HadesMem Injector\n"; boost::program_options::options_description opts_desc( "General options"); opts_desc.add_options() ("help", "produce help message") ("pid", boost::program_options::value<DWORD>(), "process id") ("module", boost::program_options::wvalue<std::wstring>(), "module path") ("path-resolution", "perform path resolution") ("export", boost::program_options::value<std::string>(), "export name") ("inject", "inject module") ("free", "unload module") ("add-path", "add module dir to search order") ("run", boost::program_options::wvalue<std::wstring>(), "process path") ; std::vector<std::wstring> const args = boost::program_options:: split_winmain(GetCommandLine()); boost::program_options::variables_map var_map; boost::program_options::store(boost::program_options::wcommand_line_parser( args).options(opts_desc).run(), var_map); boost::program_options::notify(var_map); if (var_map.count("help") || argc == 1) { std::cout << '\n' << opts_desc << '\n'; return 1; } if (!var_map.count("module")) { std::cerr << "\nError! Module path must be specified.\n"; return 1; } bool const has_pid = (var_map.count("pid") != 0); bool const create_proc = (var_map.count("run") != 0); if ((has_pid && create_proc) || (!has_pid && !create_proc)) { std::cerr << "\nError! A process ID or an executable path must be " "specified.\n"; return 1; } bool const inject = (var_map.count("inject") != 0); bool const free = (var_map.count("free") != 0); if (inject && free) { std::cerr << "\nError! Please specify inject or free, not both.\n"; } if ((!inject || free) && create_proc) { std::cerr << "\nError! Modules can only be unloaded from running " "targets.\n"; return 1; } std::wstring const module_path = var_map["module"].as<std::wstring>(); bool const path_resolution = var_map.count("path-resolution") != 0; bool const add_path = var_map.count("add-path") != 0; int flags = hadesmem::InjectFlags::kNone; if (path_resolution) { flags |= hadesmem::InjectFlags::kPathResolution; } if (add_path) { flags |= hadesmem::InjectFlags::kAddToSearchOrder; } if (has_pid) { try { hadesmem::GetSeDebugPrivilege(); std::wcout << "\nAcquired SeDebugPrivilege.\n"; } catch (std::exception const& /*e*/) { std::wcout << "\nFailed to acquire SeDebugPrivilege.\n"; } DWORD const pid = var_map["pid"].as<DWORD>(); hadesmem::Process const process(pid); HMODULE module = nullptr; if (inject) { module = hadesmem::InjectDll(process, module_path, flags); std::wcout << "\nSuccessfully injected module at base address " << PtrToString(module) << ".\n"; } else { boost::filesystem::path path_real(module_path); if (path_resolution && path_real.is_relative()) { path_real = boost::filesystem::absolute(path_real, hadesmem::detail::GetSelfDirPath()); } path_real.make_preferred(); hadesmem::Module const remote_module(process, path_real.native()); module = remote_module.GetHandle(); } if (var_map.count("export")) { std::string const export_name = var_map["export"].as<std::string>(); auto const export_ret = hadesmem::CallExport(process, module, export_name); std::wcout << "\nSuccessfully called module export.\n"; std::wcout << "Return: " << export_ret.GetReturnValue() << ".\n"; std::wcout << "LastError: " << export_ret.GetLastError() << ".\n"; } if (free) { hadesmem::FreeDll(process, module); std::wcout << "\nSuccessfully freed module at base address " << PtrToString(module) << ".\n"; } } else { std::vector<std::wstring> create_args; std::wstring const exe_path = var_map["run"].as<std::wstring>(); std::string const export_name = var_map.count("export") ? var_map["export"].as<std::string>() : ""; hadesmem::CreateAndInjectData const inject_data = hadesmem::CreateAndInject( exe_path, L"", std::begin(create_args), std::end(create_args), module_path, export_name, flags); std::wcout << "\nSuccessfully created target.\n"; std::wcout << "Process ID: " << inject_data.GetProcess() << ".\n"; std::wcout << "Module Base: " << PtrToString(inject_data.GetModule()) << ".\n"; std::wcout << "Export Return: " << inject_data.GetExportRet() << ".\n"; std::wcout << "Export LastError: " << inject_data.GetExportLastError() << ".\n"; } return 0; } catch (std::exception const& e) { std::cerr << "\nError!\n"; std::cerr << boost::diagnostic_information(e) << '\n'; return 1; } } <|endoftext|>
<commit_before>/* * server_memory_test.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <[email protected]> * Contact: José Antonio Santos Cadenas <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "server_test_base.hpp" #include <boost/test/unit_test.hpp> #include "memory.hpp" #include "mediaServer_constants.h" #include <gst/gst.h> using namespace kurento; using namespace kurento; #define GST_CAT_DEFAULT _server_memory_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "server_memory_test" #define ITERATIONS 10000 #define MEMORY_TOLERANCE 1024 BOOST_FIXTURE_TEST_SUITE ( server_memory_test_suite, F ) BOOST_AUTO_TEST_CASE ( create_media_pipeline_memory_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( create_rtp_end_point_memory_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( create_zbar_filter_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createFilter (mo, mediaPipeline, FilterType::type::ZBAR_FILTER); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_releasing_sink_element_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); for (i = 0; i < ITERATIONS; i++) { client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (recorder); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_releasing_source_element_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); for (i = 0; i < ITERATIONS; i++) { client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (player); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add memory test for creating player<commit_after>/* * server_memory_test.cpp - Kurento Media Server * * Copyright (C) 2013 Kurento * Contact: Miguel París Díaz <[email protected]> * Contact: José Antonio Santos Cadenas <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "server_test_base.hpp" #include <boost/test/unit_test.hpp> #include "memory.hpp" #include "mediaServer_constants.h" #include <gst/gst.h> using namespace kurento; using namespace kurento; #define GST_CAT_DEFAULT _server_memory_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "server_memory_test" #define ITERATIONS 10000 #define MEMORY_TOLERANCE 1024 BOOST_FIXTURE_TEST_SUITE ( server_memory_test_suite, F ) BOOST_AUTO_TEST_CASE ( create_media_pipeline_memory_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( create_player_memory_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (mo, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( create_rtp_end_point_memory_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( create_zbar_filter_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId mo = MediaObjectId(); int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createFilter (mo, mediaPipeline, FilterType::type::ZBAR_FILTER); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); for (i = 0; i < ITERATIONS; i++) { client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (mediaPipeline); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_releasing_sink_element_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); for (i = 0; i < ITERATIONS; i++) { client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (recorder); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_CASE ( connect_releasing_source_element_test ) { MediaObjectId mediaPipeline = MediaObjectId(); MediaObjectId player = MediaObjectId(); MediaObjectId recorder = MediaObjectId(); std::vector<MediaObjectId> srcs, sinks; int i, maxMemorySize, currentMemorySize; BOOST_REQUIRE_MESSAGE (initialized, "Cannot connect to the server"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); client->addHandlerAddress (0, "localhost", 2323); client->createMediaPipeline (mediaPipeline, 0); client->createUriEndPoint (recorder, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, "file:///tmp/b"); client->getMediaSinksByMediaType (sinks, recorder, MediaType::type::VIDEO); for (i = 0; i < ITERATIONS; i++) { client->createUriEndPoint (player, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, "file:///tmp/a"); client->getMediaSrcsByMediaType (srcs, player, MediaType::type::VIDEO); client->connect (srcs.front (), sinks.front () ); client->release (player); if (i == 0) { maxMemorySize = get_data_memory (pid) + MEMORY_TOLERANCE; GST_INFO ("MAX memory size: %d", maxMemorySize); } if (i % 100 == 0) { currentMemorySize = get_data_memory (pid); GST_INFO ("Memory size: %d", currentMemorySize); BOOST_REQUIRE (currentMemorySize <= maxMemorySize); } } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "../config.h" #include <iostream> #include <fstream> #include <getopt.h> #include <netinet/in.h> #include <ev.h> #include <sysexits.h> #include "../Socket/Socket.hxx" #include "../Log/TimestampLog.hxx" static const size_t READ_SIZE = 4096; static const int MAX_CONN_BACKLOG = 32; std::string logfilename; std::ofstream logfile; std::auto_ptr<std::ostream> log; std::auto_ptr<SockAddr::SockAddr> bind_addr_outgoing; void received_sigint(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGINT, exiting\n" << std::flush; ev_break(EV_A_ EVUNLOOP_ALL); } void received_sigterm(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGTERM, exiting\n" << std::flush; ev_break(EV_A_ EVUNLOOP_ALL); } void received_sighup(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGHUP, closing this logfile\n" << std::flush; logfile.close(); logfile.open(logfilename.c_str(), std::ios_base::app | std::ios_base::out ); *log << "Received SIGHUP, (re)opening this logfile\n" << std::flush; } static void listening_socket_ready_for_read(EV_P_ ev_io *w, int revents) { Socket* s_listen = reinterpret_cast<Socket*>( w->data ); std::auto_ptr<SockAddr::SockAddr> client_addr; Socket client_socket = s_listen->accept(&client_addr); std::auto_ptr<SockAddr::SockAddr> server_addr; server_addr = client_socket.getsockname(); *log << "Connection intercepted " << client_addr->string() << "-->" << server_addr->string() << "\n" << std::flush; Socket server_socket = Socket::socket(AF_INET, SOCK_STREAM, 0); if( bind_addr_outgoing.get() != NULL ) { server_socket.bind( *bind_addr_outgoing ); *log << "Connecting " << bind_addr_outgoing->string() << "-->"; } else { #if HAVE_DECL_IP_TRANSPARENT int value = 1; server_socket.setsockopt(SOL_IP, IP_TRANSPARENT, &value, sizeof(value)); #endif server_socket.bind( *client_addr ); *log << "Connecting " << client_addr->string() << "-->"; } *log << server_addr->string() << "\n" << std::flush; server_socket.connect( *server_addr ); // TODO: keep client_socket around // TODO: keep server_socket around // TODO: connect these sockets // TODO: make connect async } int main(int argc, char* argv[]) { // Default options struct { bool fork; std::string pid_file; std::string bind_addr_listen; std::string bind_addr_outgoing; } options = { /* fork = */ true, /* pid_file = */ "", /* bind_addr_listen = */ "[0.0.0.0]:[5000]", /* bind_addr_outgoing = */ "[0.0.0.0]:[0]" }; log.reset( new TimestampLog( std::cerr ) ); { // Parse options char optstring[] = "hVfp:b:B:l:"; struct option longopts[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {"forgeground", no_argument, NULL, 'f'}, {"pid-file", required_argument, NULL, 'p'}, {"bind-listen", required_argument, NULL, 'b'}, {"bind-outgoing", required_argument, NULL, 'B'}, {"log", required_argument, NULL, 'l'}, {NULL, 0, 0, 0} }; int longindex; int opt; while( (opt = getopt_long(argc, argv, optstring, longopts, &longindex)) != -1 ) { switch(opt) { case '?': case 'h': std::cerr << // >---------------------- Standard terminal width ---------------------------------< "Options:\n" " -h -? --help Displays this help message and exits\n" " -V --version Displays the version and exits\n" " --foreground -f Don't fork into the background after init\n" " --pid-file -p file The file to write the PID to, especially\n" " usefull when running as a daemon\n" " --bind-listen -b host:port Bind to the specified address for incomming\n" " connections.\n" " host and port resolving can be bypassed by\n" " placing [] around them\n" " --bind-outgoing -b host:port Bind to the specified address for outgoing\n" " connections.\n" " host and port resolving can be bypassed by\n" " placing [] around them\n" " the special string \"client\" can be used to\n" " reuse the client's source address. Note that\n" " you should take care that the return packets\n" " pass through this process again!\n" " --log -l file Log to file\n" ; if( opt == '?' ) exit(EX_USAGE); exit(EX_OK); case 'V': std::cout << PACKAGE_NAME << " version " << PACKAGE_VERSION << " (" << PACKAGE_GITREVISION << ")\n"; exit(EX_OK); case 'f': options.fork = false; break; case 'p': options.pid_file = optarg; break; case 'b': options.bind_addr_listen = optarg; break; case 'B': options.bind_addr_outgoing = optarg; break; case 'l': logfilename = optarg; logfile.open(logfilename.c_str(), std::ios_base::app | std::ios_base::out ); log.reset( new TimestampLog( logfile ) ); break; } } } *log << "Parsed options, opening listening socket on " << options.bind_addr_listen << "\n" << std::flush; Socket s_listen; { // Open listening socket std::string host, port; /* Address format is * - hostname:portname * - [numeric ip]:portname * - hostname:[portnumber] * - [numeric ip]:[portnumber] */ size_t c = options.bind_addr_listen.rfind(":"); if( c == std::string::npos ) { std::cerr << "Invalid bind string \"" << options.bind_addr_listen << "\": could not find ':'\n"; exit(EX_DATAERR); } host = options.bind_addr_listen.substr(0, c); port = options.bind_addr_listen.substr(c+1); std::auto_ptr< boost::ptr_vector< SockAddr::SockAddr> > bind_sa = SockAddr::resolve( host, port, 0, SOCK_STREAM, 0); if( bind_sa->size() == 0 ) { std::cerr << "Can not bind to \"" << options.bind_addr_listen << "\": Could not resolve\n"; exit(EX_DATAERR); } else if( bind_sa->size() > 1 ) { // TODO: allow this std::cerr << "Can not bind to \"" << options.bind_addr_listen << "\": Resolves to multiple entries:\n"; for( typeof(bind_sa->begin()) i = bind_sa->begin(); i != bind_sa->end(); i++ ) { std::cerr << " " << i->string() << "\n"; } exit(EX_DATAERR); } s_listen = Socket::socket( (*bind_sa)[0].proto_family() , SOCK_STREAM, 0); s_listen.set_reuseaddr(); s_listen.bind((*bind_sa)[0]); s_listen.listen(MAX_CONN_BACKLOG); #if HAVE_DECL_IP_TRANSPARENT int value = 1; s_listen.setsockopt(SOL_IP, IP_TRANSPARENT, &value, sizeof(value)); #endif *log << "Listening on " << (*bind_sa)[0].string() << "\n" << std::flush; } if( options.bind_addr_outgoing == "client" ) { bind_addr_outgoing.reset(NULL); } else { // Resolve client address std::string host, port; /* Address format is * - hostname:portname * - [numeric ip]:portname * - hostname:[portnumber] * - [numeric ip]:[portnumber] */ size_t c = options.bind_addr_outgoing.rfind(":"); if( c == std::string::npos ) { std::cerr << "Invalid bind string \"" << options.bind_addr_outgoing << "\": could not find ':'\n"; exit(EX_DATAERR); } host = options.bind_addr_outgoing.substr(0, c); port = options.bind_addr_outgoing.substr(c+1); std::auto_ptr< boost::ptr_vector< SockAddr::SockAddr> > bind_sa = SockAddr::resolve( host, port, 0, SOCK_STREAM, 0); if( bind_sa->size() == 0 ) { std::cerr << "Can not bind to \"" << options.bind_addr_outgoing << "\": Could not resolve\n"; exit(EX_DATAERR); } else if( bind_sa->size() > 1 ) { std::cerr << "Can not bind to \"" << options.bind_addr_outgoing << "\": Resolves to multiple entries:\n"; for( typeof(bind_sa->begin()) i = bind_sa->begin(); i != bind_sa->end(); i++ ) { std::cerr << " " << i->string() << "\n"; } exit(EX_DATAERR); } bind_addr_outgoing.reset( bind_sa->release(bind_sa->begin()).release() ); // Transfer ownership; TODO: this should be simpeler that double release() *log << "Outgoing connections will connect from " << bind_addr_outgoing->string() << "\n" << std::flush; } { ev_signal ev_sigint_watcher; ev_signal_init( &ev_sigint_watcher, received_sigint, SIGINT); ev_signal_start( EV_DEFAULT_ &ev_sigint_watcher); ev_signal ev_sigterm_watcher; ev_signal_init( &ev_sigterm_watcher, received_sigterm, SIGTERM); ev_signal_start( EV_DEFAULT_ &ev_sigterm_watcher); ev_signal ev_sighup_watcher; ev_signal_init( &ev_sighup_watcher, received_sighup, SIGHUP); ev_signal_start( EV_DEFAULT_ &ev_sighup_watcher); ev_io e_listen; e_listen.data = &s_listen; ev_io_init( &e_listen, listening_socket_ready_for_read, s_listen, EV_READ ); ev_io_start( EV_DEFAULT_ &e_listen ); *log << "Setup done, starting event loop\n" << std::flush; ev_run(EV_DEFAULT_ 0); } *log << "Exiting...\n" << std::flush; return 0; } <commit_msg>Var change 2<commit_after>#include "../config.h" #include <iostream> #include <fstream> #include <getopt.h> #include <netinet/in.h> #include <ev.h> #include <sysexits.h> #include "../Socket/Socket.hxx" #include "../Log/TimestampLog.hxx" static const size_t READ_SIZE = 4096; static const int MAX_CONN_BACKLOG = 32; std::string logfilename; std::ofstream logfile; std::auto_ptr<std::ostream> log; std::auto_ptr<SockAddr::SockAddr> bind_addr_outgoing; void received_sigint(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGINT, exiting\n" << std::flush; ev_break(EV_A_ EVUNLOOP_ALL); } void received_sigterm(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGTERM, exiting\n" << std::flush; ev_break(EV_A_ EVUNLOOP_ALL); } void received_sighup(EV_P_ ev_signal *w, int revents) throw() { *log << "Received SIGHUP, closing this logfile\n" << std::flush; logfile.close(); logfile.open(logfilename.c_str(), std::ios_base::app | std::ios_base::out ); *log << "Received SIGHUP, (re)opening this logfile\n" << std::flush; } static void listening_socket_ready_for_read(EV_P_ ev_io *w, int revents) { Socket* s_listen = reinterpret_cast<Socket*>( w->data ); std::auto_ptr<SockAddr::SockAddr> client_addr; Socket s_client = s_listen->accept(&client_addr); std::auto_ptr<SockAddr::SockAddr> server_addr; server_addr = s_client.getsockname(); *log << "Connection intercepted " << client_addr->string() << "-->" << server_addr->string() << "\n" << std::flush; Socket s_server = Socket::socket(AF_INET, SOCK_STREAM, 0); if( bind_addr_outgoing.get() != NULL ) { s_server.bind( *bind_addr_outgoing ); *log << "Connecting " << bind_addr_outgoing->string() << "-->"; } else { #if HAVE_DECL_IP_TRANSPARENT int value = 1; s_server.setsockopt(SOL_IP, IP_TRANSPARENT, &value, sizeof(value)); #endif s_server.bind( *client_addr ); *log << "Connecting " << client_addr->string() << "-->"; } *log << server_addr->string() << "\n" << std::flush; s_server.connect( *server_addr ); // TODO: keep client_socket around // TODO: keep server_socket around // TODO: connect these sockets // TODO: make connect async } int main(int argc, char* argv[]) { // Default options struct { bool fork; std::string pid_file; std::string bind_addr_listen; std::string bind_addr_outgoing; } options = { /* fork = */ true, /* pid_file = */ "", /* bind_addr_listen = */ "[0.0.0.0]:[5000]", /* bind_addr_outgoing = */ "[0.0.0.0]:[0]" }; log.reset( new TimestampLog( std::cerr ) ); { // Parse options char optstring[] = "hVfp:b:B:l:"; struct option longopts[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, {"forgeground", no_argument, NULL, 'f'}, {"pid-file", required_argument, NULL, 'p'}, {"bind-listen", required_argument, NULL, 'b'}, {"bind-outgoing", required_argument, NULL, 'B'}, {"log", required_argument, NULL, 'l'}, {NULL, 0, 0, 0} }; int longindex; int opt; while( (opt = getopt_long(argc, argv, optstring, longopts, &longindex)) != -1 ) { switch(opt) { case '?': case 'h': std::cerr << // >---------------------- Standard terminal width ---------------------------------< "Options:\n" " -h -? --help Displays this help message and exits\n" " -V --version Displays the version and exits\n" " --foreground -f Don't fork into the background after init\n" " --pid-file -p file The file to write the PID to, especially\n" " usefull when running as a daemon\n" " --bind-listen -b host:port Bind to the specified address for incomming\n" " connections.\n" " host and port resolving can be bypassed by\n" " placing [] around them\n" " --bind-outgoing -b host:port Bind to the specified address for outgoing\n" " connections.\n" " host and port resolving can be bypassed by\n" " placing [] around them\n" " the special string \"client\" can be used to\n" " reuse the client's source address. Note that\n" " you should take care that the return packets\n" " pass through this process again!\n" " --log -l file Log to file\n" ; if( opt == '?' ) exit(EX_USAGE); exit(EX_OK); case 'V': std::cout << PACKAGE_NAME << " version " << PACKAGE_VERSION << " (" << PACKAGE_GITREVISION << ")\n"; exit(EX_OK); case 'f': options.fork = false; break; case 'p': options.pid_file = optarg; break; case 'b': options.bind_addr_listen = optarg; break; case 'B': options.bind_addr_outgoing = optarg; break; case 'l': logfilename = optarg; logfile.open(logfilename.c_str(), std::ios_base::app | std::ios_base::out ); log.reset( new TimestampLog( logfile ) ); break; } } } *log << "Parsed options, opening listening socket on " << options.bind_addr_listen << "\n" << std::flush; Socket s_listen; { // Open listening socket std::string host, port; /* Address format is * - hostname:portname * - [numeric ip]:portname * - hostname:[portnumber] * - [numeric ip]:[portnumber] */ size_t c = options.bind_addr_listen.rfind(":"); if( c == std::string::npos ) { std::cerr << "Invalid bind string \"" << options.bind_addr_listen << "\": could not find ':'\n"; exit(EX_DATAERR); } host = options.bind_addr_listen.substr(0, c); port = options.bind_addr_listen.substr(c+1); std::auto_ptr< boost::ptr_vector< SockAddr::SockAddr> > bind_sa = SockAddr::resolve( host, port, 0, SOCK_STREAM, 0); if( bind_sa->size() == 0 ) { std::cerr << "Can not bind to \"" << options.bind_addr_listen << "\": Could not resolve\n"; exit(EX_DATAERR); } else if( bind_sa->size() > 1 ) { // TODO: allow this std::cerr << "Can not bind to \"" << options.bind_addr_listen << "\": Resolves to multiple entries:\n"; for( typeof(bind_sa->begin()) i = bind_sa->begin(); i != bind_sa->end(); i++ ) { std::cerr << " " << i->string() << "\n"; } exit(EX_DATAERR); } s_listen = Socket::socket( (*bind_sa)[0].proto_family() , SOCK_STREAM, 0); s_listen.set_reuseaddr(); s_listen.bind((*bind_sa)[0]); s_listen.listen(MAX_CONN_BACKLOG); #if HAVE_DECL_IP_TRANSPARENT int value = 1; s_listen.setsockopt(SOL_IP, IP_TRANSPARENT, &value, sizeof(value)); #endif *log << "Listening on " << (*bind_sa)[0].string() << "\n" << std::flush; } if( options.bind_addr_outgoing == "client" ) { bind_addr_outgoing.reset(NULL); } else { // Resolve client address std::string host, port; /* Address format is * - hostname:portname * - [numeric ip]:portname * - hostname:[portnumber] * - [numeric ip]:[portnumber] */ size_t c = options.bind_addr_outgoing.rfind(":"); if( c == std::string::npos ) { std::cerr << "Invalid bind string \"" << options.bind_addr_outgoing << "\": could not find ':'\n"; exit(EX_DATAERR); } host = options.bind_addr_outgoing.substr(0, c); port = options.bind_addr_outgoing.substr(c+1); std::auto_ptr< boost::ptr_vector< SockAddr::SockAddr> > bind_sa = SockAddr::resolve( host, port, 0, SOCK_STREAM, 0); if( bind_sa->size() == 0 ) { std::cerr << "Can not bind to \"" << options.bind_addr_outgoing << "\": Could not resolve\n"; exit(EX_DATAERR); } else if( bind_sa->size() > 1 ) { std::cerr << "Can not bind to \"" << options.bind_addr_outgoing << "\": Resolves to multiple entries:\n"; for( typeof(bind_sa->begin()) i = bind_sa->begin(); i != bind_sa->end(); i++ ) { std::cerr << " " << i->string() << "\n"; } exit(EX_DATAERR); } bind_addr_outgoing.reset( bind_sa->release(bind_sa->begin()).release() ); // Transfer ownership; TODO: this should be simpeler that double release() *log << "Outgoing connections will connect from " << bind_addr_outgoing->string() << "\n" << std::flush; } { ev_signal ev_sigint_watcher; ev_signal_init( &ev_sigint_watcher, received_sigint, SIGINT); ev_signal_start( EV_DEFAULT_ &ev_sigint_watcher); ev_signal ev_sigterm_watcher; ev_signal_init( &ev_sigterm_watcher, received_sigterm, SIGTERM); ev_signal_start( EV_DEFAULT_ &ev_sigterm_watcher); ev_signal ev_sighup_watcher; ev_signal_init( &ev_sighup_watcher, received_sighup, SIGHUP); ev_signal_start( EV_DEFAULT_ &ev_sighup_watcher); ev_io e_listen; e_listen.data = &s_listen; ev_io_init( &e_listen, listening_socket_ready_for_read, s_listen, EV_READ ); ev_io_start( EV_DEFAULT_ &e_listen ); *log << "Setup done, starting event loop\n" << std::flush; ev_run(EV_DEFAULT_ 0); } *log << "Exiting...\n" << std::flush; return 0; } <|endoftext|>
<commit_before><commit_msg>planning: address code review comments<commit_after><|endoftext|>
<commit_before><commit_msg>Update cruise_mlp_evaluator.cc<commit_after><|endoftext|>
<commit_before>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../model/entity_factory.h" #include "../parser_yaml/graphics_parser.h" #include "../parser_yaml/ruleset_parser.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 || TTF_Init() == -1) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, GraphicsParser& graphicsParser, RulesetParser& rulesetParser) : AClient(owner, player), board(player.board), ancho_pantalla(graphicsParser.getPantalla().ancho), alto_pantalla(graphicsParser.getPantalla().alto), margen_pantalla(graphicsParser.getPantalla().margen_scroll), scroll_speed(graphicsParser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542 - " + owner.getBoard()->name + " - " + player.name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); auto tp = graphicsParser.getPantalla(); font = TTF_OpenFont(FUENTE_DEFAULT, graphicsParser.getPantalla().size_text); if (!font) { Logger::getInstance()->writeError("Error al abrir TTF"); } inputText = ""; minimap = std::make_shared<MiniMap>(*this, graphicsParser); isoview = std::make_shared<IsoView>(*this, rulesetParser); menu = std::make_shared<Menu>(*this, graphicsParser); playersList = std::make_shared<PlayersList>(*this, graphicsParser); chat = std::make_shared<Chat>(*this, graphicsParser); resourcesList = std::make_shared<ResourcesList>(*this, graphicsParser); commandMenu = std::make_shared<CommandMenu>(*this, graphicsParser); selectionMenu = std::make_shared<SelectionMenu>(*this, graphicsParser); sController = std::make_shared<SelectionController>(*this); if (player.entities().size() > 0) sController->setSelection(player.entities().at(0)); focus(); sweeping = false; } GameWindow::~GameWindow() { Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } TTF_CloseFont(font); } SDL_Renderer* GameWindow::getRenderer() { return renderer; } void GameWindow::render() { isoview->draw(); if (isSweeping()) { r2 boardClick = isoview->screenToBoardPosition(mouseDown); Uint8 q = 255; SDL_SetRenderDrawColor(getRenderer(), q, q, q, q); isoview->drawRhombus(boardClick, boardMouse); } if (commandMenu->isVisibleWorker && commandMenu->showOptions && commandMenu->positioning) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); r2 sizeBuilding = board.entityFactories[w->products[commandMenu->selectedOption].name]->size; if (player.getVisibility2(boardMouse) > INVISIBLE) { Uint8 q = 255; SDL_SetRenderDrawColor(getRenderer(), q, q, q, q); isoview->drawRhombus(boardMouse - sizeBuilding / 2, boardMouse + sizeBuilding / 2); } } commandMenu->draw(); selectionMenu->draw(); minimap->draw(); chat->draw(inputText); playersList->draw(); resourcesList->draw(); SDL_RenderPresent(renderer); return; } void GameWindow::update(){ sController->update(); isoview->update(); processInput(); render(); return; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); boardMouse = isoview->screenToBoardPosition(mouse); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_TEXTINPUT: if(inputText.size() < MAX_LENGTH_MESSAGE && chat->typing) //Max largo del mensaje a ingresar. inputText += e.text.text; break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_c: if(!chat->typing && commandMenu->isVisibleWorker) commandMenu->showOptions = true; break; case SDLK_p: if(!chat->typing && commandMenu->isVisibleProducer) commandMenu->showOptions = true; break; case SDLK_ESCAPE: sController->clear(); commandMenu->showOptions = false; commandMenu->positioning = false; break; case SDLK_q: if (commandMenu->showOptions) { if (commandMenu->positioning) { commandMenu->positioning = false; } else { commandMenu->showOptions = false; } } break; case SDLK_1: case SDLK_2: case SDLK_3: case SDLK_4: case SDLK_5: { size_t i = e.key.keysym.sym - SDLK_1; if (!chat->typing && commandMenu->showOptions) { if (commandMenu->isVisibleProducer) { auto p = dynamic_cast<Building*>(sController->getSelection().front().get()); if (p) { if (i < p->products.size()) { board.pushCommand(std::make_shared<CreateCommand>(p->getId(),p->products[i].name)); commandMenu->positioning = false; commandMenu->showOptions = false; } } } if (commandMenu->isVisibleWorker) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); if (w) { if (i < w->products.size()) { commandMenu->positioning = true; commandMenu->selectedOption = i; } } } } } break; case SDLK_r: if(!chat->typing) owner.restart(); break; case SDLK_s: for (auto e : sController->getSelection()) { if (!chat->typing && e->owner.name == player.name) { board.pushCommand(make_shared<StopCommand>(e->getId())); } } break; case SDLK_F2: chat->typing = !chat->typing; inputText = ""; break; case SDLK_SPACE: if(!chat->typing) focus(); break; case SDLK_BACKSPACE: if (chat->typing && inputText.length() > 0){ inputText.pop_back(); } break; case SDLK_RETURN: if (chat->typing) { chat->messages.push_back(inputText); inputText = ""; } break; } break; case SDL_MOUSEBUTTONDOWN: if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { if (commandMenu->isVisibleWorker && commandMenu->showOptions && commandMenu->positioning) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); r2 sizeBuilding = board.entityFactories[w->products[commandMenu->selectedOption].name]->size; if (player.getVisibility(boardMouse) > INVISIBLE) { board.pushCommand(std::make_shared<BuildCommand>(w->getId(), boardMouse - sizeBuilding / 2, w->products[commandMenu->selectedOption].name)); commandMenu->positioning = false; } } SDL_GetMouseState(&mouseDown.x, &mouseDown.y); sweeping = true; } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa oss << "; mapa: " << boardMouse.x << "," << boardMouse.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { setSelection(); sweeping = false; } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); std::shared_ptr<Entity> obj = board.findEntity(rectangle(boardMouse,r2(0,0))); for (auto e : sController->getSelection()) { if ((player.getVisibility(boardMouse) == INVISIBLE || !obj) && e->owner.name == player.name) { if (!(SDL_GetModState()&KMOD_SHIFT)) { board.pushCommand(make_shared<StopCommand>(e->getId())); } board.pushCommand(make_shared<MoveCommand>(e->getId(), boardMouse)); } else { if (e->owner.name == player.name && obj) { std::shared_ptr<Command> command = e->defaultCommand(*obj); if(command) board.pushCommand(command); } } } } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { if (sController->getSelection().size() > 0) { focus(sController->getSelection().at(0)->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } void GameWindow::setSelection() { r2 sweepStart = isoview->screenToBoardPosition(mouseDown); r2 sweepEnd = isoview->screenToBoardPosition(mouse); sController->setSelection(rectangle(sweepStart, sweepEnd - sweepStart)); } std::string GameWindow::completeLine(std::string line, double width) { int txtAncho, txtAlto, espAncho, espAlto, esp; std::string result = line; TTF_SizeText(font, " ", &espAncho, &espAlto); TTF_SizeText(font, result.c_str(), &txtAncho, &txtAlto); esp = (int)floor((width - txtAncho) / espAncho); if (txtAncho < width) { if (esp * espAncho + txtAncho < width) esp++; if (esp > 0)result.insert(result.size(), esp, ' '); } return result; } SDL_Color GameWindow::getColor(int id) { Uint8 r = (id & 2) * 255; Uint8 g = (id & 1) * 255; Uint8 b = (id & 4) * 255; return{ r, g, b }; } bool GameWindow::isSweeping() { return (sweeping && (mouse.x != mouseDown.x || mouse.y != mouseDown.y)); } <commit_msg>Mantengo seleccion del worker que construye, (Ver= player.getVisibility)<commit_after>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../model/entity_factory.h" #include "../parser_yaml/graphics_parser.h" #include "../parser_yaml/ruleset_parser.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 || TTF_Init() == -1) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, GraphicsParser& graphicsParser, RulesetParser& rulesetParser) : AClient(owner, player), board(player.board), ancho_pantalla(graphicsParser.getPantalla().ancho), alto_pantalla(graphicsParser.getPantalla().alto), margen_pantalla(graphicsParser.getPantalla().margen_scroll), scroll_speed(graphicsParser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542 - " + owner.getBoard()->name + " - " + player.name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); auto tp = graphicsParser.getPantalla(); font = TTF_OpenFont(FUENTE_DEFAULT, graphicsParser.getPantalla().size_text); if (!font) { Logger::getInstance()->writeError("Error al abrir TTF"); } inputText = ""; minimap = std::make_shared<MiniMap>(*this, graphicsParser); isoview = std::make_shared<IsoView>(*this, rulesetParser); menu = std::make_shared<Menu>(*this, graphicsParser); playersList = std::make_shared<PlayersList>(*this, graphicsParser); chat = std::make_shared<Chat>(*this, graphicsParser); resourcesList = std::make_shared<ResourcesList>(*this, graphicsParser); commandMenu = std::make_shared<CommandMenu>(*this, graphicsParser); selectionMenu = std::make_shared<SelectionMenu>(*this, graphicsParser); sController = std::make_shared<SelectionController>(*this); if (player.entities().size() > 0) sController->setSelection(player.entities().at(0)); focus(); sweeping = false; } GameWindow::~GameWindow() { Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } TTF_CloseFont(font); } SDL_Renderer* GameWindow::getRenderer() { return renderer; } void GameWindow::render() { isoview->draw(); if (isSweeping()) { r2 boardClick = isoview->screenToBoardPosition(mouseDown); Uint8 q = 255; SDL_SetRenderDrawColor(getRenderer(), q, q, q, q); isoview->drawRhombus(boardClick, boardMouse); } if (commandMenu->isVisibleWorker && commandMenu->showOptions && commandMenu->positioning) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); r2 sizeBuilding = board.entityFactories[w->products[commandMenu->selectedOption].name]->size; if (player.getVisibility2(boardMouse) > INVISIBLE) { //TODO: Ver Uint8 q = 255; SDL_SetRenderDrawColor(getRenderer(), q, q, q, q); isoview->drawRhombus(boardMouse - sizeBuilding / 2, boardMouse + sizeBuilding / 2); } } commandMenu->draw(); selectionMenu->draw(); minimap->draw(); chat->draw(inputText); playersList->draw(); resourcesList->draw(); SDL_RenderPresent(renderer); return; } void GameWindow::update(){ sController->update(); isoview->update(); processInput(); render(); return; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); boardMouse = isoview->screenToBoardPosition(mouse); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_TEXTINPUT: if(inputText.size() < MAX_LENGTH_MESSAGE && chat->typing) //Max largo del mensaje a ingresar. inputText += e.text.text; break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_c: if(!chat->typing && commandMenu->isVisibleWorker) commandMenu->showOptions = true; break; case SDLK_p: if(!chat->typing && commandMenu->isVisibleProducer) commandMenu->showOptions = true; break; case SDLK_ESCAPE: sController->clear(); commandMenu->showOptions = false; commandMenu->positioning = false; break; case SDLK_q: if (commandMenu->showOptions) { if (commandMenu->positioning) { commandMenu->positioning = false; } else { commandMenu->showOptions = false; } } break; case SDLK_1: case SDLK_2: case SDLK_3: case SDLK_4: case SDLK_5: { size_t i = e.key.keysym.sym - SDLK_1; if (!chat->typing && commandMenu->showOptions) { if (commandMenu->isVisibleProducer) { auto p = dynamic_cast<Building*>(sController->getSelection().front().get()); if (p) { if (i < p->products.size()) { board.pushCommand(std::make_shared<CreateCommand>(p->getId(),p->products[i].name)); commandMenu->positioning = false; commandMenu->showOptions = false; } } } if (commandMenu->isVisibleWorker) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); if (w) { if (i < w->products.size()) { commandMenu->positioning = true; commandMenu->selectedOption = i; } } } } } break; case SDLK_r: if(!chat->typing) owner.restart(); break; case SDLK_s: for (auto e : sController->getSelection()) { if (!chat->typing && e->owner.name == player.name) { board.pushCommand(make_shared<StopCommand>(e->getId())); } } break; case SDLK_F2: chat->typing = !chat->typing; inputText = ""; break; case SDLK_SPACE: if(!chat->typing) focus(); break; case SDLK_BACKSPACE: if (chat->typing && inputText.length() > 0){ inputText.pop_back(); } break; case SDLK_RETURN: if (chat->typing) { chat->messages.push_back(inputText); inputText = ""; } break; } break; case SDL_MOUSEBUTTONDOWN: if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { if (commandMenu->isVisibleWorker && commandMenu->showOptions && commandMenu->positioning) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); r2 sizeBuilding = board.entityFactories[w->products[commandMenu->selectedOption].name]->size; if (player.getVisibility2(boardMouse) > INVISIBLE) {//TODO: Ver board.pushCommand(std::make_shared<BuildCommand>(w->getId(), boardMouse - sizeBuilding / 2, w->products[commandMenu->selectedOption].name)); commandMenu->positioning = false; } } else { SDL_GetMouseState(&mouseDown.x, &mouseDown.y); sweeping = true; } } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa oss << "; mapa: " << boardMouse.x << "," << boardMouse.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { if (!(commandMenu->isVisibleWorker && commandMenu->showOptions && commandMenu->positioning)) { setSelection(); sweeping = false; } } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); std::shared_ptr<Entity> obj = board.findEntity(rectangle(boardMouse,r2(0,0))); for (auto e : sController->getSelection()) { if ((player.getVisibility2(boardMouse) == INVISIBLE || !obj) && e->owner.name == player.name) {//TODO: Ver if (!(SDL_GetModState()&KMOD_SHIFT)) { board.pushCommand(make_shared<StopCommand>(e->getId())); } board.pushCommand(make_shared<MoveCommand>(e->getId(), boardMouse)); } else { if (e->owner.name == player.name && obj) { std::shared_ptr<Command> command = e->defaultCommand(*obj); if(command) board.pushCommand(command); } } } } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { if (sController->getSelection().size() > 0) { focus(sController->getSelection().at(0)->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } void GameWindow::setSelection() { r2 sweepStart = isoview->screenToBoardPosition(mouseDown); r2 sweepEnd = isoview->screenToBoardPosition(mouse); sController->setSelection(rectangle(sweepStart, sweepEnd - sweepStart)); } std::string GameWindow::completeLine(std::string line, double width) { int txtAncho, txtAlto, espAncho, espAlto, esp; std::string result = line; TTF_SizeText(font, " ", &espAncho, &espAlto); TTF_SizeText(font, result.c_str(), &txtAncho, &txtAlto); esp = (int)floor((width - txtAncho) / espAncho); if (txtAncho < width) { if (esp * espAncho + txtAncho < width) esp++; if (esp > 0)result.insert(result.size(), esp, ' '); } return result; } SDL_Color GameWindow::getColor(int id) { Uint8 r = (id & 2) * 255; Uint8 g = (id & 1) * 255; Uint8 b = (id & 4) * 255; return{ r, g, b }; } bool GameWindow::isSweeping() { return (sweeping && (mouse.x != mouseDown.x || mouse.y != mouseDown.y)); } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Fernando José Iglesias García * Copyright (C) 2012 Fernando José Iglesias García */ #include <shogun/features/DotFeatures.h> #include <shogun/mathematics/Math.h> #include <shogun/structure/MulticlassModel.h> #include <shogun/structure/MulticlassSOLabels.h> using namespace shogun; CMulticlassModel::CMulticlassModel() : CStructuredModel() { init(); } CMulticlassModel::CMulticlassModel(CFeatures* features, CStructuredLabels* labels) : CStructuredModel(features, labels) { init(); } CMulticlassModel::~CMulticlassModel() { } int32_t CMulticlassModel::get_dim() const { // TODO make the casts safe! int32_t num_classes = ((CMulticlassSOLabels*) m_labels)->get_num_classes(); int32_t feats_dim = ((CDotFeatures*) m_features)->get_dim_feature_space(); return feats_dim*num_classes; } SGVector< float64_t > CMulticlassModel::get_joint_feature_vector(int32_t feat_idx, CStructuredData* y) { SGVector< float64_t > psi( get_dim() ); psi.zero(); SGVector< float64_t > x = ((CDotFeatures*) m_features)-> get_computed_dot_feature_vector(feat_idx); CRealNumber* r = CRealNumber::obtain_from_generic(y); ASSERT(r != NULL) float64_t label_value = r->value; for ( index_t i = 0, j = label_value*x.vlen ; i < x.vlen ; ++i, ++j ) psi[j] = x[i]; return psi; } CResultSet* CMulticlassModel::argmax( SGVector< float64_t > w, int32_t feat_idx, bool const training) { CDotFeatures* df = (CDotFeatures*) m_features; int32_t feats_dim = df->get_dim_feature_space(); if ( training ) { CMulticlassSOLabels* ml = (CMulticlassSOLabels*) m_labels; m_num_classes = ml->get_num_classes(); } else { REQUIRE(m_num_classes > 0, "The model needs to be trained before " "using it for prediction\n"); } ASSERT(feats_dim*m_num_classes == w.vlen); // Find the class that gives the maximum score float64_t score = 0, ypred = 0; float64_t max_score = -CMath::INFTY; for ( int32_t c = 0 ; c < m_num_classes ; ++c ) { score = df->dense_dot(feat_idx, w.vector+c*feats_dim, feats_dim); if ( training ) score += delta_loss(feat_idx, c); if ( score > max_score ) { max_score = score; ypred = c; } } // Build the CResultSet object to return CResultSet* ret = new CResultSet(); CRealNumber* y = new CRealNumber(ypred); SG_REF(ret); SG_REF(y); ret->psi_pred = get_joint_feature_vector(feat_idx, y); ret->score = max_score; ret->argmax = y; if ( training ) { ret->psi_truth = CStructuredModel::get_joint_feature_vector(feat_idx, feat_idx); ret->delta = CStructuredModel::delta_loss(feat_idx, y); } return ret; } float64_t CMulticlassModel::delta_loss(CStructuredData* y1, CStructuredData* y2) { CRealNumber* rn1 = CRealNumber::obtain_from_generic(y1); CRealNumber* rn2 = CRealNumber::obtain_from_generic(y2); ASSERT(rn1 != NULL); ASSERT(rn2 != NULL); return delta_loss(rn1->value, rn2->value); } float64_t CMulticlassModel::delta_loss(int32_t y1_idx, float64_t y2) { REQUIRE(y1_idx >= 0 || y1_idx < m_labels->get_num_labels(), "The label index must be inside [0, num_labels-1]\n"); CRealNumber* rn1 = CRealNumber::obtain_from_generic(m_labels->get_label(y1_idx)); float64_t ret = delta_loss(rn1->value, y2); SG_UNREF(rn1); return ret; } float64_t CMulticlassModel::delta_loss(float64_t y1, float64_t y2) { return (y1 == y2) ? 0 : 1; } void CMulticlassModel::init_opt( SGMatrix< float64_t > & A, SGVector< float64_t > a, SGMatrix< float64_t > B, SGVector< float64_t > & b, SGVector< float64_t > lb, SGVector< float64_t > ub, SGMatrix< float64_t > & C) { C = SGMatrix< float64_t >::create_identity_matrix(get_dim(), 1); } void CMulticlassModel::init() { SG_ADD(&m_num_classes, "m_num_classes", "The number of classes", MS_NOT_AVAILABLE); m_num_classes = 0; } float64_t CMulticlassModel::risk(float64_t* subgrad, float64_t* W, TMultipleCPinfo* info) { CDotFeatures* X=(CDotFeatures*)m_features; CMulticlassSOLabels* y=(CMulticlassSOLabels*)m_labels; m_num_classes = y->get_num_classes(); uint32_t from, to; if (info) { from=info->_from; to=(info->N == 0) ? X->get_num_vectors() : from+info->N; } else { from=0; to=X->get_num_vectors(); } uint32_t num_classes=y->get_num_classes(); uint32_t feats_dim=X->get_dim_feature_space(); const uint32_t w_dim=get_dim(); float64_t R=0.0; for (uint32_t i=0; i<w_dim; i++) subgrad[i] = 0; float64_t Rtmp=0.0; float64_t Rmax=0.0; float64_t loss=0.0; uint32_t yhat=0; uint32_t GT=0; CRealNumber* GT_rn=NULL; /* loop through examples */ for(uint32_t i=from; i<to; ++i) { Rmax=-CMath::INFTY; GT_rn=CRealNumber::obtain_from_generic(y->get_label(i)); GT=(uint32_t)GT_rn->value; for (uint32_t c = 0; c < num_classes; ++c) { loss=(c == GT) ? 0.0 : 1.0; Rtmp=loss+X->dense_dot(i, W+c*feats_dim, feats_dim) -X->dense_dot(i, W+GT*feats_dim, feats_dim); if (Rtmp > Rmax) { Rmax=Rtmp; yhat=c; } } R += Rmax; X->add_to_dense_vec(1.0, i, subgrad+yhat*feats_dim, feats_dim); X->add_to_dense_vec(-1.0, i, subgrad+GT*feats_dim, feats_dim); SG_UNREF(GT_rn); } return R; } <commit_msg>~ MulticlassModel::argmax returns the true score instead of score+delta<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Fernando José Iglesias García * Copyright (C) 2012 Fernando José Iglesias García */ #include <shogun/features/DotFeatures.h> #include <shogun/mathematics/Math.h> #include <shogun/structure/MulticlassModel.h> #include <shogun/structure/MulticlassSOLabels.h> using namespace shogun; CMulticlassModel::CMulticlassModel() : CStructuredModel() { init(); } CMulticlassModel::CMulticlassModel(CFeatures* features, CStructuredLabels* labels) : CStructuredModel(features, labels) { init(); } CMulticlassModel::~CMulticlassModel() { } int32_t CMulticlassModel::get_dim() const { // TODO make the casts safe! int32_t num_classes = ((CMulticlassSOLabels*) m_labels)->get_num_classes(); int32_t feats_dim = ((CDotFeatures*) m_features)->get_dim_feature_space(); return feats_dim*num_classes; } SGVector< float64_t > CMulticlassModel::get_joint_feature_vector(int32_t feat_idx, CStructuredData* y) { SGVector< float64_t > psi( get_dim() ); psi.zero(); SGVector< float64_t > x = ((CDotFeatures*) m_features)-> get_computed_dot_feature_vector(feat_idx); CRealNumber* r = CRealNumber::obtain_from_generic(y); ASSERT(r != NULL) float64_t label_value = r->value; for ( index_t i = 0, j = label_value*x.vlen ; i < x.vlen ; ++i, ++j ) psi[j] = x[i]; return psi; } CResultSet* CMulticlassModel::argmax( SGVector< float64_t > w, int32_t feat_idx, bool const training) { CDotFeatures* df = (CDotFeatures*) m_features; int32_t feats_dim = df->get_dim_feature_space(); if ( training ) { CMulticlassSOLabels* ml = (CMulticlassSOLabels*) m_labels; m_num_classes = ml->get_num_classes(); } else { REQUIRE(m_num_classes > 0, "The model needs to be trained before " "using it for prediction\n"); } ASSERT(feats_dim*m_num_classes == w.vlen); // Find the class that gives the maximum score float64_t score = 0, ypred = 0; float64_t max_score = -CMath::INFTY; for ( int32_t c = 0 ; c < m_num_classes ; ++c ) { score = df->dense_dot(feat_idx, w.vector+c*feats_dim, feats_dim); if ( training ) score += delta_loss(feat_idx, c); if ( score > max_score ) { max_score = score; ypred = c; } } // Build the CResultSet object to return CResultSet* ret = new CResultSet(); CRealNumber* y = new CRealNumber(ypred); SG_REF(ret); SG_REF(y); ret->psi_pred = get_joint_feature_vector(feat_idx, y); ret->score = max_score; ret->argmax = y; if ( training ) { ret->psi_truth = CStructuredModel::get_joint_feature_vector(feat_idx, feat_idx); ret->delta = CStructuredModel::delta_loss(feat_idx, y); ret->score -= ret->delta; } return ret; } float64_t CMulticlassModel::delta_loss(CStructuredData* y1, CStructuredData* y2) { CRealNumber* rn1 = CRealNumber::obtain_from_generic(y1); CRealNumber* rn2 = CRealNumber::obtain_from_generic(y2); ASSERT(rn1 != NULL); ASSERT(rn2 != NULL); return delta_loss(rn1->value, rn2->value); } float64_t CMulticlassModel::delta_loss(int32_t y1_idx, float64_t y2) { REQUIRE(y1_idx >= 0 || y1_idx < m_labels->get_num_labels(), "The label index must be inside [0, num_labels-1]\n"); CRealNumber* rn1 = CRealNumber::obtain_from_generic(m_labels->get_label(y1_idx)); float64_t ret = delta_loss(rn1->value, y2); SG_UNREF(rn1); return ret; } float64_t CMulticlassModel::delta_loss(float64_t y1, float64_t y2) { return (y1 == y2) ? 0 : 1; } void CMulticlassModel::init_opt( SGMatrix< float64_t > & A, SGVector< float64_t > a, SGMatrix< float64_t > B, SGVector< float64_t > & b, SGVector< float64_t > lb, SGVector< float64_t > ub, SGMatrix< float64_t > & C) { C = SGMatrix< float64_t >::create_identity_matrix(get_dim(), 1); } void CMulticlassModel::init() { SG_ADD(&m_num_classes, "m_num_classes", "The number of classes", MS_NOT_AVAILABLE); m_num_classes = 0; } float64_t CMulticlassModel::risk(float64_t* subgrad, float64_t* W, TMultipleCPinfo* info) { CDotFeatures* X=(CDotFeatures*)m_features; CMulticlassSOLabels* y=(CMulticlassSOLabels*)m_labels; m_num_classes = y->get_num_classes(); uint32_t from, to; if (info) { from=info->_from; to=(info->N == 0) ? X->get_num_vectors() : from+info->N; } else { from=0; to=X->get_num_vectors(); } uint32_t num_classes=y->get_num_classes(); uint32_t feats_dim=X->get_dim_feature_space(); const uint32_t w_dim=get_dim(); float64_t R=0.0; for (uint32_t i=0; i<w_dim; i++) subgrad[i] = 0; float64_t Rtmp=0.0; float64_t Rmax=0.0; float64_t loss=0.0; uint32_t yhat=0; uint32_t GT=0; CRealNumber* GT_rn=NULL; /* loop through examples */ for(uint32_t i=from; i<to; ++i) { Rmax=-CMath::INFTY; GT_rn=CRealNumber::obtain_from_generic(y->get_label(i)); GT=(uint32_t)GT_rn->value; for (uint32_t c = 0; c < num_classes; ++c) { loss=(c == GT) ? 0.0 : 1.0; Rtmp=loss+X->dense_dot(i, W+c*feats_dim, feats_dim) -X->dense_dot(i, W+GT*feats_dim, feats_dim); if (Rtmp > Rmax) { Rmax=Rtmp; yhat=c; } } R += Rmax; X->add_to_dense_vec(1.0, i, subgrad+yhat*feats_dim, feats_dim); X->add_to_dense_vec(-1.0, i, subgrad+GT*feats_dim, feats_dim); SG_UNREF(GT_rn); } return R; } <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "cairo-inlined/cairo.h" #include "cairocontext.hh" namespace Rapicorn { /* --- Painter --- */ CairoContext::CairoContext() : cr (NULL) {} CairoContext::~CairoContext() { set_cairo (NULL); } void CairoContext::set_cairo (cairo_t *n_cr) { if (n_cr) n_cr = cairo_reference (n_cr); if (cr) cairo_destroy (cr); cr = n_cr; } void CairoContext::save () { cairo_save (cr); } void CairoContext::restore () { cairo_restore (cr); } void CairoContext::set_tolerance (double tolerance) { cairo_set_tolerance (cr, tolerance); } static cairo_antialias_t convert_antialias (CairoContext::Antialias antialias) { switch (antialias) { default: case CairoContext::CAIRO_ANTIALIAS_DEFAULT: return CAIRO_ANTIALIAS_DEFAULT; case CairoContext::CAIRO_ANTIALIAS_NONE: return CAIRO_ANTIALIAS_NONE; case CairoContext::CAIRO_ANTIALIAS_GRAY: return CAIRO_ANTIALIAS_GRAY; case CairoContext::CAIRO_ANTIALIAS_SUBPIXEL: return CAIRO_ANTIALIAS_SUBPIXEL; } } void CairoContext::set_antialias (Antialias antialias) { cairo_set_antialias (cr, convert_antialias (antialias)); } static cairo_fill_rule_t convert_fill_rule (CairoContext::FillRule fill_rule) { switch (fill_rule) { default: case CairoContext::CAIRO_FILL_RULE_WINDING: return CAIRO_FILL_RULE_WINDING; case CairoContext::CAIRO_FILL_RULE_EVEN_ODD: return CAIRO_FILL_RULE_EVEN_ODD; } } void CairoContext::set_fill_rule (FillRule fill_rule) { cairo_set_fill_rule (cr, convert_fill_rule (fill_rule)); } void CairoContext::set_line_width (double width) { cairo_set_line_width (cr, width); } static cairo_line_cap_t convert_line_cap (CairoContext::LineCap line_cap) { switch (line_cap) { default: case CairoContext::CAIRO_LINE_CAP_BUTT: return CAIRO_LINE_CAP_BUTT; case CairoContext::CAIRO_LINE_CAP_ROUND: return CAIRO_LINE_CAP_ROUND; case CairoContext::CAIRO_LINE_CAP_SQUARE: return CAIRO_LINE_CAP_SQUARE; } } void CairoContext::set_line_cap (LineCap line_cap) { cairo_set_line_cap (cr, convert_line_cap (line_cap)); } static cairo_line_join_t convert_line_join (CairoContext::LineJoin line_join) { switch (line_join) { default: case CairoContext::CAIRO_LINE_JOIN_MITER: return CAIRO_LINE_JOIN_MITER; case CairoContext::CAIRO_LINE_JOIN_ROUND: return CAIRO_LINE_JOIN_ROUND; case CairoContext::CAIRO_LINE_JOIN_BEVEL: return CAIRO_LINE_JOIN_BEVEL; } } void CairoContext::set_line_join (LineJoin line_join) { cairo_set_line_join (cr, convert_line_join (line_join)); } void CairoContext::set_miter_limit (double limit) { cairo_set_miter_limit (cr, limit); } void CairoContext::set_dash (double *dashes, int num_dashes, double offset) { cairo_set_dash (cr, dashes, num_dashes, offset); } void CairoContext::set_source_color (Color c) { cairo_set_source_rgba (cr, c.red() / 255., c.green() / 255., c.blue() / 255., c.alpha() / 255.); } void CairoContext::translate (double x, double y) { cairo_translate (cr, x, y); } void CairoContext::new_path () { cairo_new_path (cr); } void CairoContext::move_to (double x, double y) { cairo_move_to (cr, x, y); } void CairoContext::line_to (double x, double y) { cairo_line_to (cr, x, y); } void CairoContext::rel_move_to (double x, double y) { cairo_rel_move_to (cr, x, y); } void CairoContext::rel_line_to (double x, double y) { cairo_rel_line_to (cr, x, y); } void CairoContext::rectangle (double x, double y, double width, double height) { cairo_rectangle (cr, x, y, width, height); } void CairoContext::curve_to (double x1, double y1, double x2, double y2, double x3, double y3) { cairo_curve_to (cr, x1, y1, x2, y2, x3, y3); } void CairoContext::arc (double xc, double yc, double radius, double angle1, double angle2) { cairo_arc (cr, xc, yc, radius, angle1, angle2); } void CairoContext::arc_negative (double xc, double yc, double radius, double angle1, double angle2) { cairo_arc_negative (cr, xc, yc, radius, angle1, angle2); } void CairoContext::close_path () { cairo_close_path (cr); } void CairoContext::paint () { cairo_paint (cr); } void CairoContext::stroke () { cairo_stroke (cr); } void CairoContext::stroke_preserve () { cairo_stroke_preserve (cr); } void CairoContext::fill () { cairo_fill (cr); } void CairoContext::fill_preserve () { cairo_fill_preserve (cr); } CairoContext* CairoContext::cairo_context_from_plane (Plane &plane) { uint32 *buffer = plane.peek (0, 0); cairo_surface_t *cs = cairo_image_surface_create_for_data ((uint8*) buffer, CAIRO_FORMAT_ARGB32, plane.width(), plane.height(), plane.pixstride()); cairo_t *cr = cairo_create (cs); cairo_surface_destroy (cs); cairo_translate (cr, -plane.xstart(), -plane.ystart()); CairoContext *cc = new CairoContext; cc->set_cairo (cr); return cc; } CairoPainter::CairoPainter (Plane &plane) : Painter (plane), cc (*CairoContext::cairo_context_from_plane (m_plane)) {} CairoPainter::~CairoPainter() { delete &cc; } void CairoPainter::draw_arrow (double x, double y, double width, double height, Color c, double angle) { double mx = x + width / 2, my = y + height / 2; double angle0 = (angle + 0) * PI / 180., angle1 = (angle + 120) * PI / 180., angle2 = (angle - 120) * PI / 180.; cc.set_source_color (c); /* east point */ cc.move_to (mx + cos (angle0) * width / 2, my + sin (angle0) * height / 2); /* north-west point */ cc.line_to (mx + cos (angle1) * width / 2, my + sin (angle1) * height / 2); /* south-west point */ cc.line_to (mx + cos (angle2) * width / 2, my + sin (angle2) * height / 2); //cc.move_to (x, y); //cc.line_to (x + width, y); //cc.line_to (x + width / 2., y + height); cc.close_path(); cc.fill(); } void CairoPainter::draw_dir_arrow (double x, double y, double width, double height, Color c, DirType dir) { double xhalf = width / 2., yhalf = height / 2.; cc.set_source_color (c); switch (dir) { default: case DIR_RIGHT: cc.move_to (x + width, y + yhalf); cc.line_to (x, y + height); cc.line_to (x, y); break; case DIR_UP: cc.move_to (x, y); cc.line_to (x + width, y); cc.line_to (x + xhalf, y + height); break; case DIR_LEFT: cc.move_to (x, y + yhalf); cc.line_to (x + width, y); cc.line_to (x + width, y + height); break; case DIR_DOWN: cc.move_to (x, y + height); cc.line_to (x + xhalf, y); cc.line_to (x + width, y + height); break; } cc.close_path(); cc.fill(); } void CairoPainter::draw_dot (double x, double y, double width, double height, Color c1, Color c2, FrameType frame) { cc.rectangle (x, y, width, height); cc.set_source_color (c1); cc.fill(); } } // Rapicorn <commit_msg>UI: cairocontext member renames<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "cairo-inlined/cairo.h" #include "cairocontext.hh" namespace Rapicorn { /* --- Painter --- */ CairoContext::CairoContext() : cr (NULL) {} CairoContext::~CairoContext() { set_cairo (NULL); } void CairoContext::set_cairo (cairo_t *n_cr) { if (n_cr) n_cr = cairo_reference (n_cr); if (cr) cairo_destroy (cr); cr = n_cr; } void CairoContext::save () { cairo_save (cr); } void CairoContext::restore () { cairo_restore (cr); } void CairoContext::set_tolerance (double tolerance) { cairo_set_tolerance (cr, tolerance); } static cairo_antialias_t convert_antialias (CairoContext::Antialias antialias) { switch (antialias) { default: case CairoContext::CAIRO_ANTIALIAS_DEFAULT: return CAIRO_ANTIALIAS_DEFAULT; case CairoContext::CAIRO_ANTIALIAS_NONE: return CAIRO_ANTIALIAS_NONE; case CairoContext::CAIRO_ANTIALIAS_GRAY: return CAIRO_ANTIALIAS_GRAY; case CairoContext::CAIRO_ANTIALIAS_SUBPIXEL: return CAIRO_ANTIALIAS_SUBPIXEL; } } void CairoContext::set_antialias (Antialias antialias) { cairo_set_antialias (cr, convert_antialias (antialias)); } static cairo_fill_rule_t convert_fill_rule (CairoContext::FillRule fill_rule) { switch (fill_rule) { default: case CairoContext::CAIRO_FILL_RULE_WINDING: return CAIRO_FILL_RULE_WINDING; case CairoContext::CAIRO_FILL_RULE_EVEN_ODD: return CAIRO_FILL_RULE_EVEN_ODD; } } void CairoContext::set_fill_rule (FillRule fill_rule) { cairo_set_fill_rule (cr, convert_fill_rule (fill_rule)); } void CairoContext::set_line_width (double width) { cairo_set_line_width (cr, width); } static cairo_line_cap_t convert_line_cap (CairoContext::LineCap line_cap) { switch (line_cap) { default: case CairoContext::CAIRO_LINE_CAP_BUTT: return CAIRO_LINE_CAP_BUTT; case CairoContext::CAIRO_LINE_CAP_ROUND: return CAIRO_LINE_CAP_ROUND; case CairoContext::CAIRO_LINE_CAP_SQUARE: return CAIRO_LINE_CAP_SQUARE; } } void CairoContext::set_line_cap (LineCap line_cap) { cairo_set_line_cap (cr, convert_line_cap (line_cap)); } static cairo_line_join_t convert_line_join (CairoContext::LineJoin line_join) { switch (line_join) { default: case CairoContext::CAIRO_LINE_JOIN_MITER: return CAIRO_LINE_JOIN_MITER; case CairoContext::CAIRO_LINE_JOIN_ROUND: return CAIRO_LINE_JOIN_ROUND; case CairoContext::CAIRO_LINE_JOIN_BEVEL: return CAIRO_LINE_JOIN_BEVEL; } } void CairoContext::set_line_join (LineJoin line_join) { cairo_set_line_join (cr, convert_line_join (line_join)); } void CairoContext::set_miter_limit (double limit) { cairo_set_miter_limit (cr, limit); } void CairoContext::set_dash (double *dashes, int num_dashes, double offset) { cairo_set_dash (cr, dashes, num_dashes, offset); } void CairoContext::set_source_color (Color c) { cairo_set_source_rgba (cr, c.red() / 255., c.green() / 255., c.blue() / 255., c.alpha() / 255.); } void CairoContext::translate (double x, double y) { cairo_translate (cr, x, y); } void CairoContext::new_path () { cairo_new_path (cr); } void CairoContext::move_to (double x, double y) { cairo_move_to (cr, x, y); } void CairoContext::line_to (double x, double y) { cairo_line_to (cr, x, y); } void CairoContext::rel_move_to (double x, double y) { cairo_rel_move_to (cr, x, y); } void CairoContext::rel_line_to (double x, double y) { cairo_rel_line_to (cr, x, y); } void CairoContext::rectangle (double x, double y, double width, double height) { cairo_rectangle (cr, x, y, width, height); } void CairoContext::curve_to (double x1, double y1, double x2, double y2, double x3, double y3) { cairo_curve_to (cr, x1, y1, x2, y2, x3, y3); } void CairoContext::arc (double xc, double yc, double radius, double angle1, double angle2) { cairo_arc (cr, xc, yc, radius, angle1, angle2); } void CairoContext::arc_negative (double xc, double yc, double radius, double angle1, double angle2) { cairo_arc_negative (cr, xc, yc, radius, angle1, angle2); } void CairoContext::close_path () { cairo_close_path (cr); } void CairoContext::paint () { cairo_paint (cr); } void CairoContext::stroke () { cairo_stroke (cr); } void CairoContext::stroke_preserve () { cairo_stroke_preserve (cr); } void CairoContext::fill () { cairo_fill (cr); } void CairoContext::fill_preserve () { cairo_fill_preserve (cr); } CairoContext* CairoContext::cairo_context_from_plane (Plane &plane) { uint32 *buffer = plane.peek (0, 0); cairo_surface_t *cs = cairo_image_surface_create_for_data ((uint8*) buffer, CAIRO_FORMAT_ARGB32, plane.width(), plane.height(), plane.pixstride()); cairo_t *cr = cairo_create (cs); cairo_surface_destroy (cs); cairo_translate (cr, -plane.xstart(), -plane.ystart()); CairoContext *cc = new CairoContext; cc->set_cairo (cr); return cc; } CairoPainter::CairoPainter (Plane &plane) : Painter (plane), cc (*CairoContext::cairo_context_from_plane (plane_)) {} CairoPainter::~CairoPainter() { delete &cc; } void CairoPainter::draw_arrow (double x, double y, double width, double height, Color c, double angle) { double mx = x + width / 2, my = y + height / 2; double angle0 = (angle + 0) * PI / 180., angle1 = (angle + 120) * PI / 180., angle2 = (angle - 120) * PI / 180.; cc.set_source_color (c); /* east point */ cc.move_to (mx + cos (angle0) * width / 2, my + sin (angle0) * height / 2); /* north-west point */ cc.line_to (mx + cos (angle1) * width / 2, my + sin (angle1) * height / 2); /* south-west point */ cc.line_to (mx + cos (angle2) * width / 2, my + sin (angle2) * height / 2); //cc.move_to (x, y); //cc.line_to (x + width, y); //cc.line_to (x + width / 2., y + height); cc.close_path(); cc.fill(); } void CairoPainter::draw_dir_arrow (double x, double y, double width, double height, Color c, DirType dir) { double xhalf = width / 2., yhalf = height / 2.; cc.set_source_color (c); switch (dir) { default: case DIR_RIGHT: cc.move_to (x + width, y + yhalf); cc.line_to (x, y + height); cc.line_to (x, y); break; case DIR_UP: cc.move_to (x, y); cc.line_to (x + width, y); cc.line_to (x + xhalf, y + height); break; case DIR_LEFT: cc.move_to (x, y + yhalf); cc.line_to (x + width, y); cc.line_to (x + width, y + height); break; case DIR_DOWN: cc.move_to (x, y + height); cc.line_to (x + xhalf, y); cc.line_to (x + width, y + height); break; } cc.close_path(); cc.fill(); } void CairoPainter::draw_dot (double x, double y, double width, double height, Color c1, Color c2, FrameType frame) { cc.rectangle (x, y, width, height); cc.set_source_color (c1); cc.fill(); } } // Rapicorn <|endoftext|>
<commit_before>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../parser_yaml/graphics_parser.h" #include "../parser_yaml/ruleset_parser.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 || TTF_Init() == -1) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, GraphicsParser& graphicsParser, RulesetParser& rulesetParser) : AClient(owner, player), board(player.board), ancho_pantalla(graphicsParser.getPantalla().ancho), alto_pantalla(graphicsParser.getPantalla().alto), margen_pantalla(graphicsParser.getPantalla().margen_scroll), scroll_speed(graphicsParser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542 - " + owner.getBoard()->name + " - " + player.name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); auto tp = graphicsParser.getPantalla(); font = TTF_OpenFont(FUENTE_DEFAULT, graphicsParser.getPantalla().size_text); if (!font) { Logger::getInstance()->writeError("Error al abrir TTF"); } inputText = ""; minimap = std::make_shared<MiniMap>(*this, graphicsParser); isoview = std::make_shared<IsoView>(*this, rulesetParser); menu = std::make_shared<Menu>(*this, graphicsParser); playersList = std::make_shared<PlayersList>(*this, graphicsParser); chat = std::make_shared<Chat>(*this, graphicsParser); resourcesList = std::make_shared<ResourcesList>(*this, graphicsParser); commandMenu = std::make_shared<CommandMenu>(*this, graphicsParser); selectionMenu = std::make_shared<SelectionMenu>(*this, graphicsParser); sController = std::make_shared<SelectionController>(*this); if (player.entities().size() > 0) sController->setSelection(player.entities().at(0)); focus(); sweeping = false; } GameWindow::~GameWindow() { Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } TTF_CloseFont(font); } SDL_Renderer* GameWindow::getRenderer() { return renderer; } void GameWindow::render() { isoview->draw(); //menu->draw();TODO: MENU DEBERIA CONTENER A COMMANDMENU SELECTIONMENU MINIMAP commandMenu->draw(); selectionMenu->draw(); minimap->draw(); chat->draw(inputText); playersList->draw(); resourcesList->draw(); if (isSweeping()) { r2 boardClick = isoview->screenToBoardPosition(mouseDown); r2 boardMouse = isoview->screenToBoardPosition(mouse); isoview->drawRhombus(boardClick, boardMouse); } SDL_RenderPresent(renderer); return; } void GameWindow::update(){ sController->update(); isoview->update(); processInput(); render(); return; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); boardMouse = isoview->screenToBoardPosition(mouse); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_TEXTINPUT: if(inputText.size() < MAX_LENGTH_MESSAGE && chat->typing) //Max largo del mensaje a ingresar. inputText += e.text.text; break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_c: if(!chat->typing && commandMenu->isVisibleWorker) commandMenu->showOptions = true; break; case SDLK_p: if(!chat->typing && commandMenu->isVisibleProducer) commandMenu->showOptions = true; break; case SDLK_ESCAPE: commandMenu->showOptions = false; break; case SDLK_1: case SDLK_2: case SDLK_3: case SDLK_4: case SDLK_5: { size_t i = e.key.keysym.sym - SDLK_1; if (!chat->typing && commandMenu->showOptions) { //if (commandMenu->isVisibleProducer) { // auto p = dynamic_cast<Building*>(sController->getSelection().front().get()); // if (p) { // if (i < p->products.size()) { // int j = 0; // for (auto& prod : p->products) { // if (i == j) { // board.pushCommand(make_shared<CreateCommand>(p->getId(), prod.first)); // j++; // } // } // // } // } //} if (commandMenu->isVisibleWorker) { //CONSTRUIR PRODUCTO DEL WORKER SELECCIONADO 1. } } } break; case SDLK_r: if(!chat->typing) owner.restart(); break; case SDLK_s: for (auto e : sController->getSelection()) { if (!chat->typing && e->owner.name == player.name) { board.pushCommand(make_shared<StopCommand>(e->getId())); } } break; case SDLK_F2: chat->typing = !chat->typing; inputText = ""; break; case SDLK_SPACE: if(!chat->typing) focus(); break; case SDLK_BACKSPACE: if (chat->typing && inputText.length() > 0){ inputText.pop_back(); } break; case SDLK_RETURN: if (chat->typing) { chat->messages.push_back(inputText); inputText = ""; } break; } break; case SDL_MOUSEBUTTONDOWN: if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { SDL_GetMouseState(&mouseDown.x, &mouseDown.y); sweeping = true; } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa oss << "; mapa: " << boardMouse.x << "," << boardMouse.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { setSelection(); sweeping = false; } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); std::shared_ptr<Entity> obj = board.findEntity(rectangle(boardMouse,r2(0,0))); for (auto e : sController->getSelection()) { if (e->owner.name == player.name) { if (!(SDL_GetModState()&KMOD_SHIFT)) { board.pushCommand(make_shared<StopCommand>(e->getId())); } board.pushCommand(make_shared<MoveCommand>(e->getId(), boardMouse)); } } } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { if (sController->getSelection().size() > 0) { focus(sController->getSelection().at(0)->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } void GameWindow::setSelection() { r2 sweepStart = isoview->screenToBoardPosition(mouseDown); r2 sweepEnd = isoview->screenToBoardPosition(mouse); sController->setSelection(rectangle(sweepStart, sweepEnd - sweepStart)); } std::string GameWindow::completeLine(std::string line, double width) { int txtAncho, txtAlto, espAncho, espAlto, esp; std::string result = line; TTF_SizeText(font, " ", &espAncho, &espAlto); TTF_SizeText(font, result.c_str(), &txtAncho, &txtAlto); esp = (int)floor((width - txtAncho) / espAncho); if (txtAncho < width) { if (esp * espAncho + txtAncho < width) esp++; if (esp > 0)result.insert(result.size(), esp, ' '); } return result; } SDL_Color GameWindow::getColor(int id) { Uint8 r = (id & 2) * 255; Uint8 g = (id & 1) * 255; Uint8 b = (id & 4) * 255; return{ r, g, b }; } bool GameWindow::isSweeping() { return (sweeping && (mouse.x != mouseDown.x || mouse.y != mouseDown.y)); } <commit_msg>Comandos de creacion<commit_after>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../parser_yaml/graphics_parser.h" #include "../parser_yaml/ruleset_parser.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 || TTF_Init() == -1) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, GraphicsParser& graphicsParser, RulesetParser& rulesetParser) : AClient(owner, player), board(player.board), ancho_pantalla(graphicsParser.getPantalla().ancho), alto_pantalla(graphicsParser.getPantalla().alto), margen_pantalla(graphicsParser.getPantalla().margen_scroll), scroll_speed(graphicsParser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542 - " + owner.getBoard()->name + " - " + player.name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); auto tp = graphicsParser.getPantalla(); font = TTF_OpenFont(FUENTE_DEFAULT, graphicsParser.getPantalla().size_text); if (!font) { Logger::getInstance()->writeError("Error al abrir TTF"); } inputText = ""; minimap = std::make_shared<MiniMap>(*this, graphicsParser); isoview = std::make_shared<IsoView>(*this, rulesetParser); menu = std::make_shared<Menu>(*this, graphicsParser); playersList = std::make_shared<PlayersList>(*this, graphicsParser); chat = std::make_shared<Chat>(*this, graphicsParser); resourcesList = std::make_shared<ResourcesList>(*this, graphicsParser); commandMenu = std::make_shared<CommandMenu>(*this, graphicsParser); selectionMenu = std::make_shared<SelectionMenu>(*this, graphicsParser); sController = std::make_shared<SelectionController>(*this); if (player.entities().size() > 0) sController->setSelection(player.entities().at(0)); focus(); sweeping = false; } GameWindow::~GameWindow() { Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } TTF_CloseFont(font); } SDL_Renderer* GameWindow::getRenderer() { return renderer; } void GameWindow::render() { isoview->draw(); //menu->draw();TODO: MENU DEBERIA CONTENER A COMMANDMENU SELECTIONMENU MINIMAP commandMenu->draw(); selectionMenu->draw(); minimap->draw(); chat->draw(inputText); playersList->draw(); resourcesList->draw(); if (isSweeping()) { r2 boardClick = isoview->screenToBoardPosition(mouseDown); r2 boardMouse = isoview->screenToBoardPosition(mouse); isoview->drawRhombus(boardClick, boardMouse); } SDL_RenderPresent(renderer); return; } void GameWindow::update(){ sController->update(); isoview->update(); processInput(); render(); return; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); boardMouse = isoview->screenToBoardPosition(mouse); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_TEXTINPUT: if(inputText.size() < MAX_LENGTH_MESSAGE && chat->typing) //Max largo del mensaje a ingresar. inputText += e.text.text; break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_c: if(!chat->typing && commandMenu->isVisibleWorker) commandMenu->showOptions = true; break; case SDLK_p: if(!chat->typing && commandMenu->isVisibleProducer) commandMenu->showOptions = true; break; case SDLK_ESCAPE: commandMenu->showOptions = false; break; case SDLK_1: case SDLK_2: case SDLK_3: case SDLK_4: case SDLK_5: { size_t i = e.key.keysym.sym - SDLK_1; if (!chat->typing && commandMenu->showOptions) { if (commandMenu->isVisibleProducer) { auto p = dynamic_cast<Building*>(sController->getSelection().front().get()); if (p) { if (i < p->products.size()) { board.pushCommand(std::make_shared<CreateCommand>(p->getId(),p->products[i].name)); } } } if (commandMenu->isVisibleWorker) { auto w = dynamic_cast<Worker*>(sController->getSelection().front().get()); if (w) { if (i < w->products.size()) { board.pushCommand(std::make_shared<CreateCommand>(w->getId(), w->products[i].name)); } } } } } break; case SDLK_r: if(!chat->typing) owner.restart(); break; case SDLK_s: for (auto e : sController->getSelection()) { if (!chat->typing && e->owner.name == player.name) { board.pushCommand(make_shared<StopCommand>(e->getId())); } } break; case SDLK_F2: chat->typing = !chat->typing; inputText = ""; break; case SDLK_SPACE: if(!chat->typing) focus(); break; case SDLK_BACKSPACE: if (chat->typing && inputText.length() > 0){ inputText.pop_back(); } break; case SDLK_RETURN: if (chat->typing) { chat->messages.push_back(inputText); inputText = ""; } break; } break; case SDL_MOUSEBUTTONDOWN: if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { SDL_GetMouseState(&mouseDown.x, &mouseDown.y); sweeping = true; } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa oss << "; mapa: " << boardMouse.x << "," << boardMouse.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if (EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT) { setSelection(); sweeping = false; } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); std::shared_ptr<Entity> obj = board.findEntity(rectangle(boardMouse,r2(0,0))); for (auto e : sController->getSelection()) { if (e->owner.name == player.name) { if (!(SDL_GetModState()&KMOD_SHIFT)) { board.pushCommand(make_shared<StopCommand>(e->getId())); } board.pushCommand(make_shared<MoveCommand>(e->getId(), boardMouse)); } } } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { if (sController->getSelection().size() > 0) { focus(sController->getSelection().at(0)->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } void GameWindow::setSelection() { r2 sweepStart = isoview->screenToBoardPosition(mouseDown); r2 sweepEnd = isoview->screenToBoardPosition(mouse); sController->setSelection(rectangle(sweepStart, sweepEnd - sweepStart)); } std::string GameWindow::completeLine(std::string line, double width) { int txtAncho, txtAlto, espAncho, espAlto, esp; std::string result = line; TTF_SizeText(font, " ", &espAncho, &espAlto); TTF_SizeText(font, result.c_str(), &txtAncho, &txtAlto); esp = (int)floor((width - txtAncho) / espAncho); if (txtAncho < width) { if (esp * espAncho + txtAncho < width) esp++; if (esp > 0)result.insert(result.size(), esp, ' '); } return result; } SDL_Color GameWindow::getColor(int id) { Uint8 r = (id & 2) * 255; Uint8 g = (id & 1) * 255; Uint8 b = (id & 4) * 255; return{ r, g, b }; } bool GameWindow::isSweeping() { return (sweeping && (mouse.x != mouseDown.x || mouse.y != mouseDown.y)); } <|endoftext|>
<commit_before>/* Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html */ #include <rcore/testutils.hh> #include <ui/uithread.hh> using namespace Rapicorn; static void test_server_smart_handle() { ApplicationImpl &app = ApplicationImpl::the(); // FIXME: use Application_SmartHandle once C++ bindings are ready ApplicationIface *ab = &app; Aida::FieldBuffer8 fb (4); fb.add_object (uint64 ((BaseObject*) ab)); // FIXME: Aida::Coupler &c = *rope_thread_coupler(); // c.reader.reset (fb); ApplicationImpl *am = dynamic_cast<ApplicationImpl*> (ab); assert (am == &app); ApplicationIface *ai = am; assert (ai == ab); } REGISTER_UITHREAD_TEST ("Server/Smart Handle", test_server_smart_handle); static void test_stock_resources() { String s; s = Stock::stock_label ("broken-image"); TASSERT (s.empty() == false); s = Stock::stock_string ("broken-image", "image"); TASSERT (s.empty() == false); Blob b = Stock::stock_image ("broken-image"); TASSERT (b && b.size() > 16); b = Stock::stock_image (" .no.. +such+ -image- ~hCZ75jv27j"); TASSERT (!b && errno != 0); } REGISTER_UITHREAD_TEST ("Server/Stock Resources", test_stock_resources); static void test_application_xurl() { ApplicationImpl &app = ApplicationImpl::the(); bool success; struct Dummy : public ListModelRelayImpl { using ListModelRelayImpl::create_list_model_relay; }; ListModelRelayIface &lmr1 = Dummy::create_list_model_relay (); ListModelIface &lm1 = *lmr1.model(); ListModelRelayIface &lmr2 = Dummy::create_list_model_relay (); ListModelIface &lm2 = *lmr2.model(); ListModelRelayIface &lmr3 = Dummy::create_list_model_relay (); ListModelIface &lm3 = *lmr3.model(); ListModelIface *lmi; String path; // model1 + lmr1 tests lmi = app.xurl_find ("//local/data/unknown"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); path = app.xurl_path (lm1); TASSERT (path == ""); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == true); path = app.xurl_path (lm1); TASSERT (path == "//local/data/model1"); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == false); success = app.xurl_add ("//local/data/model1", lm2); TASSERT (success == false); success = app.xurl_add ("//local/data/unknown", lm1); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == &lm1); success = app.xurl_sub (lm1); TASSERT (success == true); success = app.xurl_sub (lm1); TASSERT (success == false); path = app.xurl_path (lm1); TASSERT (path == ""); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == true); path = app.xurl_path (lm1); TASSERT (path == "//local/data/model1"); // model2 + lmr2 tests lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); path = app.xurl_path (lm2); TASSERT (path == ""); success = app.xurl_sub (lm2); TASSERT (success == false); success = app.xurl_add ("//local/data/model2", lm2); TASSERT (success == true); path = app.xurl_path (lm2); TASSERT (path == "//local/data/model2"); success = app.xurl_add ("//local/data/model2", lm1); TASSERT (success == false); success = app.xurl_add ("//local/data/model2", lm3); TASSERT (success == false); success = app.xurl_add ("//local/data/unknown", lm2); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); success = app.xurl_sub (lm2); TASSERT (success == true); success = app.xurl_sub (lm2); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); success = app.xurl_add ("//local/data/model2", lm2); TASSERT (success == true); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); // model3 + lmr3 tests lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == NULL); path = app.xurl_path (lm3); TASSERT (path == ""); success = app.xurl_add ("//local/data/model3", lm3); TASSERT (success == true); path = app.xurl_path (lm3); TASSERT (path == "//local/data/model3"); success = app.xurl_add ("//local/data/unknown", lm3); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == &lm3); // removal checks lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == &lm1); unref (ref_sink (lmr1)); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); success = app.xurl_sub (lm2); TASSERT (success == true); success = app.xurl_sub (lm2); TASSERT (success == false); unref (ref_sink (lmr2)); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == &lm3); unref (ref_sink (lmr3)); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == NULL); } REGISTER_UITHREAD_TEST ("Server/Application XUrl Map", test_application_xurl); <commit_msg>UI: tests: add primitive TypeCode test<commit_after>/* Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html */ #include <rcore/testutils.hh> #include <ui/uithread.hh> using namespace Rapicorn; static void test_server_smart_handle() { ApplicationImpl &app = ApplicationImpl::the(); // FIXME: use Application_SmartHandle once C++ bindings are ready ApplicationIface *ab = &app; Aida::FieldBuffer8 fb (4); fb.add_object (uint64 ((BaseObject*) ab)); // FIXME: Aida::Coupler &c = *rope_thread_coupler(); // c.reader.reset (fb); ApplicationImpl *am = dynamic_cast<ApplicationImpl*> (ab); assert (am == &app); ApplicationIface *ai = am; assert (ai == ab); } REGISTER_UITHREAD_TEST ("Server/Smart Handle", test_server_smart_handle); static void test_stock_resources() { String s; s = Stock::stock_label ("broken-image"); TASSERT (s.empty() == false); s = Stock::stock_string ("broken-image", "image"); TASSERT (s.empty() == false); Blob b = Stock::stock_image ("broken-image"); TASSERT (b && b.size() > 16); b = Stock::stock_image (" .no.. +such+ -image- ~hCZ75jv27j"); TASSERT (!b && errno != 0); } REGISTER_UITHREAD_TEST ("Server/Stock Resources", test_stock_resources); static void test_application_xurl() { ApplicationImpl &app = ApplicationImpl::the(); bool success; struct Dummy : public ListModelRelayImpl { using ListModelRelayImpl::create_list_model_relay; }; ListModelRelayIface &lmr1 = Dummy::create_list_model_relay (); ListModelIface &lm1 = *lmr1.model(); ListModelRelayIface &lmr2 = Dummy::create_list_model_relay (); ListModelIface &lm2 = *lmr2.model(); ListModelRelayIface &lmr3 = Dummy::create_list_model_relay (); ListModelIface &lm3 = *lmr3.model(); ListModelIface *lmi; String path; // model1 + lmr1 tests lmi = app.xurl_find ("//local/data/unknown"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); path = app.xurl_path (lm1); TASSERT (path == ""); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == true); path = app.xurl_path (lm1); TASSERT (path == "//local/data/model1"); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == false); success = app.xurl_add ("//local/data/model1", lm2); TASSERT (success == false); success = app.xurl_add ("//local/data/unknown", lm1); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == &lm1); success = app.xurl_sub (lm1); TASSERT (success == true); success = app.xurl_sub (lm1); TASSERT (success == false); path = app.xurl_path (lm1); TASSERT (path == ""); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); success = app.xurl_add ("//local/data/model1", lm1); TASSERT (success == true); path = app.xurl_path (lm1); TASSERT (path == "//local/data/model1"); // model2 + lmr2 tests lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); path = app.xurl_path (lm2); TASSERT (path == ""); success = app.xurl_sub (lm2); TASSERT (success == false); success = app.xurl_add ("//local/data/model2", lm2); TASSERT (success == true); path = app.xurl_path (lm2); TASSERT (path == "//local/data/model2"); success = app.xurl_add ("//local/data/model2", lm1); TASSERT (success == false); success = app.xurl_add ("//local/data/model2", lm3); TASSERT (success == false); success = app.xurl_add ("//local/data/unknown", lm2); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); success = app.xurl_sub (lm2); TASSERT (success == true); success = app.xurl_sub (lm2); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); success = app.xurl_add ("//local/data/model2", lm2); TASSERT (success == true); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); // model3 + lmr3 tests lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == NULL); path = app.xurl_path (lm3); TASSERT (path == ""); success = app.xurl_add ("//local/data/model3", lm3); TASSERT (success == true); path = app.xurl_path (lm3); TASSERT (path == "//local/data/model3"); success = app.xurl_add ("//local/data/unknown", lm3); TASSERT (success == false); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == &lm3); // removal checks lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == &lm1); unref (ref_sink (lmr1)); lmi = app.xurl_find ("//local/data/model1"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == &lm2); success = app.xurl_sub (lm2); TASSERT (success == true); success = app.xurl_sub (lm2); TASSERT (success == false); unref (ref_sink (lmr2)); lmi = app.xurl_find ("//local/data/model2"); TASSERT (lmi == NULL); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == &lm3); unref (ref_sink (lmr3)); lmi = app.xurl_find ("//local/data/model3"); TASSERT (lmi == NULL); } REGISTER_UITHREAD_TEST ("Server/Application XUrl Map", test_application_xurl); static void test_type_codes() { ApplicationImpl &app = ApplicationImpl::the(); Aida::TypeCode tc = app.__aida_type_code__(); assert (tc.kind() == Aida::INSTANCE); assert (tc.name() == "Rapicorn::Application"); assert (tc.untyped() == false); } REGISTER_UITHREAD_TEST ("Server/IDL Type Codes", test_type_codes); <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * SimTK Core: SimTK Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK Core biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2006-7 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ /** @file * Defines the standard SimTK core "version" and "about" routines. */ #include "SimTKcommon.h" #include "simbody/internal/common.h" #include <string> #include <cstring> #include <cctype> #define STR(var) #var #define MAKE_VERSION_STRING(maj,min,build) STR(maj.min.build) #define MAKE_COPYRIGHT_STRING(y,a) \ "Copyright (c) " STR(y) " Stanford University, " STR(a) #define MAKE_STRING(a) STR(a) #define GET_VERSION_STRING \ MAKE_VERSION_STRING(SimTK_SIMBODY_MAJOR_VERSION, \ SimTK_SIMBODY_MINOR_VERSION, \ SimTK_SIMBODY_BUILD_VERSION) #define GET_COPYRIGHT_STRING \ MAKE_COPYRIGHT_STRING(SimTK_SIMBODY_COPYRIGHT_YEARS, \ SimTK_SIMBODY_AUTHORS) #define GET_SVN_REVISION_STRING \ MAKE_STRING(SimTK_SIMBODY_SVN_REVISION) #define GET_AUTHORS_STRING \ MAKE_STRING(SimTK_SIMBODY_AUTHORS) #define GET_LIBRARY_STRING \ MAKE_STRING(SimTK_SIMBODY_LIBRARY_NAME) #if defined(SimTK_SIMBODY_BUILDING_SHARED_LIBRARY) #define GET_TYPE_STRING "shared" #elif defined(SimTK_SIMBODY_BUILDING_STATIC_LIBRARY) #define GET_TYPE_STRING "static" #else #define GET_TYPE_STRING "<unknown library type?!>" #endif #ifndef NDEBUG #define GET_DEBUG_STRING "debug" #else #define GET_DEBUG_STRING "release" #endif extern "C" { void SimTK_version_simbody(int* major, int* minor, int* build) { static const char* l = "SimTK library=" GET_LIBRARY_STRING; static const char* t = "SimTK type=" GET_TYPE_STRING; static const char* d = "SimTK debug=" GET_DEBUG_STRING; static const char* v = "SimTK version=" GET_VERSION_STRING; static const char* r = "SimTK svn_revision=" GET_SVN_REVISION_STRING; static const char* c = "SimTK copyright=" GET_COPYRIGHT_STRING; if (major) *major = SimTK_SIMBODY_MAJOR_VERSION; if (minor) *minor = SimTK_SIMBODY_MINOR_VERSION; if (build) *build = SimTK_SIMBODY_BUILD_VERSION; // Force statics to be present in the binary (Release mode otherwise // optimizes them away). volatile int i=0; if (i) { // never true, but compiler doesn't know ... *major = *l + *t + *d + *v + *r + *c; } } void SimTK_about_simbody(const char* key, int maxlen, char* value) { if (maxlen <= 0 || value==0) return; value[0] = '\0'; // in case we don't find a match if (key==0) return; // downshift the key std::string skey(key); for (size_t i=0; i<skey.size(); ++i) skey[i] = std::tolower(skey[i]); char* v = 0; if (skey == "version") v = GET_VERSION_STRING; else if (skey == "library") v = GET_LIBRARY_STRING; else if (skey == "type") v = GET_TYPE_STRING; else if (skey == "copyright") v = GET_COPYRIGHT_STRING; else if (skey == "svn_revision") v = GET_SVN_REVISION_STRING; else if (skey == "authors") v = GET_AUTHORS_STRING; else if (skey == "debug") v = GET_DEBUG_STRING; if (v) { std::strncpy(value,v,maxlen-1); value[maxlen-1] = '\0'; // in case we ran out of room } } } <commit_msg>Fix warning from Snow Leopard gcc.<commit_after>/* -------------------------------------------------------------------------- * * SimTK Core: SimTK Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK Core biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2006-7 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: * * * * 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ /** @file * Defines the standard SimTK core "version" and "about" routines. */ #include "SimTKcommon.h" #include "simbody/internal/common.h" #include <string> #include <cstring> #include <cctype> #define STR(var) #var #define MAKE_VERSION_STRING(maj,min,build) STR(maj.min.build) #define MAKE_COPYRIGHT_STRING(y,a) \ "Copyright (c) " STR(y) " Stanford University, " STR(a) #define MAKE_STRING(a) STR(a) #define GET_VERSION_STRING \ MAKE_VERSION_STRING(SimTK_SIMBODY_MAJOR_VERSION, \ SimTK_SIMBODY_MINOR_VERSION, \ SimTK_SIMBODY_BUILD_VERSION) #define GET_COPYRIGHT_STRING \ MAKE_COPYRIGHT_STRING(SimTK_SIMBODY_COPYRIGHT_YEARS, \ SimTK_SIMBODY_AUTHORS) #define GET_SVN_REVISION_STRING \ MAKE_STRING(SimTK_SIMBODY_SVN_REVISION) #define GET_AUTHORS_STRING \ MAKE_STRING(SimTK_SIMBODY_AUTHORS) #define GET_LIBRARY_STRING \ MAKE_STRING(SimTK_SIMBODY_LIBRARY_NAME) #if defined(SimTK_SIMBODY_BUILDING_SHARED_LIBRARY) #define GET_TYPE_STRING "shared" #elif defined(SimTK_SIMBODY_BUILDING_STATIC_LIBRARY) #define GET_TYPE_STRING "static" #else #define GET_TYPE_STRING "<unknown library type?!>" #endif #ifndef NDEBUG #define GET_DEBUG_STRING "debug" #else #define GET_DEBUG_STRING "release" #endif extern "C" { void SimTK_version_simbody(int* major, int* minor, int* build) { static const char* l = "SimTK library=" GET_LIBRARY_STRING; static const char* t = "SimTK type=" GET_TYPE_STRING; static const char* d = "SimTK debug=" GET_DEBUG_STRING; static const char* v = "SimTK version=" GET_VERSION_STRING; static const char* r = "SimTK svn_revision=" GET_SVN_REVISION_STRING; static const char* c = "SimTK copyright=" GET_COPYRIGHT_STRING; if (major) *major = SimTK_SIMBODY_MAJOR_VERSION; if (minor) *minor = SimTK_SIMBODY_MINOR_VERSION; if (build) *build = SimTK_SIMBODY_BUILD_VERSION; // Force statics to be present in the binary (Release mode otherwise // optimizes them away). volatile int i=0; if (i) { // never true, but compiler doesn't know ... *major = *l + *t + *d + *v + *r + *c; } } void SimTK_about_simbody(const char* key, int maxlen, char* value) { if (maxlen <= 0 || value==0) return; value[0] = '\0'; // in case we don't find a match if (key==0) return; // downshift the key std::string skey(key); for (size_t i=0; i<skey.size(); ++i) skey[i] = std::tolower(skey[i]); const char* v = 0; if (skey == "version") v = GET_VERSION_STRING; else if (skey == "library") v = GET_LIBRARY_STRING; else if (skey == "type") v = GET_TYPE_STRING; else if (skey == "copyright") v = GET_COPYRIGHT_STRING; else if (skey == "svn_revision") v = GET_SVN_REVISION_STRING; else if (skey == "authors") v = GET_AUTHORS_STRING; else if (skey == "debug") v = GET_DEBUG_STRING; if (v) { std::strncpy(value,v,maxlen-1); value[maxlen-1] = '\0'; // in case we ran out of room } } } <|endoftext|>
<commit_before>#include "Chunk.h" #include <cstdlib> uint qHash(const Int3D & coord) { return (coord.x * 8191 + coord.z) * 131071 + coord.y; } Chunk::Chunk(const Int3D &pos, const Int3D &size) : m_pos(pos), m_size(size), m_blocks(m_size.x * m_size.y * m_size.z) { } int Chunk::indexOf(const Int3D & coord) const { Q_ASSERT(0 <= coord.x && coord.x < m_size.x && 0 <= coord.y && coord.y < m_size.y && 0 <= coord.z && coord.z < m_size.z); return coord.y + (coord.z * m_size.y) + (coord.x * m_size.y * m_size.z); } Block Chunk::getBlock(const Int3D & coord) const { return m_blocks.at(indexOf(coord)); } void Chunk::setBlock(const Int3D &coord, const Block &value) { m_blocks.replace(indexOf(coord), value); } <commit_msg>fill chunks with air so we don't see trash<commit_after>#include "Chunk.h" #include <cstdlib> uint qHash(const Int3D & coord) { return (coord.x * 8191 + coord.z) * 131071 + coord.y; } Chunk::Chunk(const Int3D &pos, const Int3D &size) : m_pos(pos), m_size(size), m_blocks(m_size.x * m_size.y * m_size.z) { m_blocks.fill(Block(Block::Air, 0, 0, 0)); } int Chunk::indexOf(const Int3D & coord) const { Q_ASSERT(0 <= coord.x && coord.x < m_size.x && 0 <= coord.y && coord.y < m_size.y && 0 <= coord.z && coord.z < m_size.z); return coord.y + (coord.z * m_size.y) + (coord.x * m_size.y * m_size.z); } Block Chunk::getBlock(const Int3D & coord) const { return m_blocks.at(indexOf(coord)); } void Chunk::setBlock(const Int3D &coord, const Block &value) { m_blocks.replace(indexOf(coord), value); } <|endoftext|>
<commit_before>#include "orbit_mpi.hh" #include "pyORBIT_Object.hh" # #include "wrap_lspacechargecalc.hh" #include "wrap_bunch.hh" #include <iostream> #include "LSpaceChargeCalc.hh" using namespace OrbitUtils; namespace wrap_LSpaceChargeCalc{ #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------- //Python LSpaceChargeCalc class definition //--------------------------------------------------------- //constructor for python class wrapping LSpaceChargeCalc instance //It never will be called directly static PyObject* LSpaceChargeCalc_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { pyORBIT_Object* self; self = (pyORBIT_Object *) type->tp_alloc(type, 0); self->cpp_obj = NULL; //std::cerr<<"The LSpaceChargeCalc new has been called!"<<std::endl; return (PyObject *) self; } //initializator for python LSpaceChargeCalc class //this is implementation of the __init__ method LSpaceChargeCalc(double b_a, double length, int nMacrosMin, int useSpaceCharge, int nBins) static int LSpaceChargeCalc_init(pyORBIT_Object *self, PyObject *args, PyObject *kwds){ pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; double b_a = 1.0; double length = 1.0; int nMacrosMin; int useSpaceCharge; int nBins; if(!PyArg_ParseTuple(args,"ddiii:arguments",&b_a,&length,&nMacrosMin,&useSpaceCharge,&nBins)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc - LSpaceChargeCalc(b_a, length, nMacrosMin, useSpaceCharge, nBins) - constructor needs parameters."); } self->cpp_obj = new LSpaceChargeCalc(b_a, length, nMacrosMin, useSpaceCharge, nBins); ((LSpaceChargeCalc*) self->cpp_obj)->setPyWrapper((PyObject*) self); return 0; } //assignImpedance A routine to import a python complex tuple and convert to c++ impedance array static PyObject* assignImpedance(PyObject *self, PyObject *args){ cout<<"Getting here \n"; pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; PyObject* py_cmplx_arr; if(!PyArg_ParseTuple(args,"O:get_complex_arr",&py_cmplx_arr)){ ORBIT_MPI_Finalize("ERROR! You have to specify a parameter - array of complex numbers!"); } if(PySequence_Check(py_cmplx_arr) != 1){ ORBIT_MPI_Finalize("ERROR! You have to specify a parameter - array of complex numbers!"); } int size = PySequence_Size(py_cmplx_arr); Py_complex cmplx; PyObject* py_cmplx; double real,imag; for(int i = 0; i < size; i++){ py_cmplx = PySequence_Fast_GET_ITEM(py_cmplx_arr, i); if(!PyComplex_Check(py_cmplx)){ ORBIT_MPI_Finalize("ERROR! No complex numbers!"); } cmplx = PyComplex_AsCComplex(py_cmplx); real = cmplx.real; imag = cmplx.imag; cpp_LSpaceChargeCalc->assignImpedanceValue(i,real,imag); } Py_INCREF(Py_None); return Py_None; } //assignImpedanceValue(int, real, real). Wraps the LongSpaceChargeCalc routine assigning an impedance mode static PyObject* LSpaceChargeCalc_assignImpedanceValue(PyObject *self, PyObject *args){ pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; int i = 0; double real= 0.0; double imag = 0.0; if(!PyArg_ParseTuple(args,"idd:arguments",&i,&real,&imag)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc - assignImpedanceValue(i, real,imag) - constructor needs parameters."); } cpp_LSpaceChargeCalc->assignImpedanceValue(i,real,imag); Py_INCREF(Py_None); return Py_None; } //trackBunchBunch(Bunch* bunch) static PyObject* LSpaceChargeCalc_trackBunch(PyObject *self, PyObject *args){ int nVars = PyTuple_Size(args); pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; PyObject* pyBunch; if(!PyArg_ParseTuple(args,"O:trackBunch",&pyBunch)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc.trackBunch(pyBunch) - method needs parameters."); } PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch"); if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc.trackBunch(pyBunch) - pyBunch is not Bunch."); } Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj; cpp_LSpaceChargeCalc->trackBunch(cpp_bunch); Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------- //destructor for python LSpaceChargeCalc class (__del__ method). //----------------------------------------------------- static void LSpaceChargeCalc_del(pyORBIT_Object* self){ LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) self->cpp_obj; if(cpp_LSpaceChargeCalc != NULL){ delete cpp_LSpaceChargeCalc; } self->ob_type->tp_free((PyObject*)self); } // defenition of the methods of the python LSpaceChargeCalc wrapper class // they will be vailable from python level static PyMethodDef LSpaceChargeCalcClassMethods[] = { { "trackBunch", LSpaceChargeCalc_trackBunch, METH_VARARGS,"trackBunch the bunch - trackBunch(pyBunch)"}, { "assignImpedanceValue", LSpaceChargeCalc_assignImpedanceValue, METH_VARARGS,"assigne the impedance for the ith mode - assignImpedanceValue(i,real,imag)"}, { "assignImpedance", assignImpedance, METH_VARARGS,"assigne the impedance for the ith mode - assignImpedance(Z))"}, {NULL} }; // defenition of the members of the python LSpaceChargeCalc wrapper class // they will be vailable from python level static PyMemberDef LSpaceChargeCalcClassMembers [] = { {NULL} }; //new python LSpaceChargeCalc wrapper type definition static PyTypeObject pyORBIT_LSpaceChargeCalc_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "LSpaceChargeCalc", /*tp_name*/ sizeof(pyORBIT_Object), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor) LSpaceChargeCalc_del , /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "The LSpaceChargeCalc python wrapper", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ LSpaceChargeCalcClassMethods, /* tp_methods */ LSpaceChargeCalcClassMembers, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) LSpaceChargeCalc_init, /* tp_init */ 0, /* tp_alloc */ LSpaceChargeCalc_new, /* tp_new */ }; //-------------------------------------------------- //Initialization function of the pyLSpaceChargeCalc class //It will be called from SpaceCharge wrapper initialization //-------------------------------------------------- void initLSpaceChargeCalc(PyObject* module){ if (PyType_Ready(&pyORBIT_LSpaceChargeCalc_Type) < 0) return; Py_INCREF(&pyORBIT_LSpaceChargeCalc_Type); PyModule_AddObject(module, "LSpaceChargeCalc", (PyObject *)&pyORBIT_LSpaceChargeCalc_Type); } #ifdef __cplusplus } #endif //end of namespace wrap_spacecharge } <commit_msg>Took out comment<commit_after>#include "orbit_mpi.hh" #include "pyORBIT_Object.hh" # #include "wrap_lspacechargecalc.hh" #include "wrap_bunch.hh" #include <iostream> #include "LSpaceChargeCalc.hh" using namespace OrbitUtils; namespace wrap_LSpaceChargeCalc{ #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------- //Python LSpaceChargeCalc class definition //--------------------------------------------------------- //constructor for python class wrapping LSpaceChargeCalc instance //It never will be called directly static PyObject* LSpaceChargeCalc_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { pyORBIT_Object* self; self = (pyORBIT_Object *) type->tp_alloc(type, 0); self->cpp_obj = NULL; //std::cerr<<"The LSpaceChargeCalc new has been called!"<<std::endl; return (PyObject *) self; } //initializator for python LSpaceChargeCalc class //this is implementation of the __init__ method LSpaceChargeCalc(double b_a, double length, int nMacrosMin, int useSpaceCharge, int nBins) static int LSpaceChargeCalc_init(pyORBIT_Object *self, PyObject *args, PyObject *kwds){ pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; double b_a = 1.0; double length = 1.0; int nMacrosMin; int useSpaceCharge; int nBins; if(!PyArg_ParseTuple(args,"ddiii:arguments",&b_a,&length,&nMacrosMin,&useSpaceCharge,&nBins)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc - LSpaceChargeCalc(b_a, length, nMacrosMin, useSpaceCharge, nBins) - constructor needs parameters."); } self->cpp_obj = new LSpaceChargeCalc(b_a, length, nMacrosMin, useSpaceCharge, nBins); ((LSpaceChargeCalc*) self->cpp_obj)->setPyWrapper((PyObject*) self); return 0; } //assignImpedance A routine to import a python complex tuple and convert to c++ impedance array static PyObject* assignImpedance(PyObject *self, PyObject *args){ pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; PyObject* py_cmplx_arr; if(!PyArg_ParseTuple(args,"O:get_complex_arr",&py_cmplx_arr)){ ORBIT_MPI_Finalize("ERROR! You have to specify a parameter - array of complex numbers!"); } if(PySequence_Check(py_cmplx_arr) != 1){ ORBIT_MPI_Finalize("ERROR! You have to specify a parameter - array of complex numbers!"); } int size = PySequence_Size(py_cmplx_arr); Py_complex cmplx; PyObject* py_cmplx; double real,imag; for(int i = 0; i < size; i++){ py_cmplx = PySequence_Fast_GET_ITEM(py_cmplx_arr, i); if(!PyComplex_Check(py_cmplx)){ ORBIT_MPI_Finalize("ERROR! No complex numbers!"); } cmplx = PyComplex_AsCComplex(py_cmplx); real = cmplx.real; imag = cmplx.imag; cpp_LSpaceChargeCalc->assignImpedanceValue(i,real,imag); } Py_INCREF(Py_None); return Py_None; } //assignImpedanceValue(int, real, real). Wraps the LongSpaceChargeCalc routine assigning an impedance mode static PyObject* LSpaceChargeCalc_assignImpedanceValue(PyObject *self, PyObject *args){ pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; int i = 0; double real= 0.0; double imag = 0.0; if(!PyArg_ParseTuple(args,"idd:arguments",&i,&real,&imag)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc - assignImpedanceValue(i, real,imag) - constructor needs parameters."); } cpp_LSpaceChargeCalc->assignImpedanceValue(i,real,imag); Py_INCREF(Py_None); return Py_None; } //trackBunchBunch(Bunch* bunch) static PyObject* LSpaceChargeCalc_trackBunch(PyObject *self, PyObject *args){ int nVars = PyTuple_Size(args); pyORBIT_Object* pyLSpaceChargeCalc = (pyORBIT_Object*) self; LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) pyLSpaceChargeCalc->cpp_obj; PyObject* pyBunch; if(!PyArg_ParseTuple(args,"O:trackBunch",&pyBunch)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc.trackBunch(pyBunch) - method needs parameters."); } PyObject* pyORBIT_Bunch_Type = wrap_orbit_bunch::getBunchType("Bunch"); if(!PyObject_IsInstance(pyBunch,pyORBIT_Bunch_Type)){ ORBIT_MPI_Finalize("PyLSpaceChargeCalc.trackBunch(pyBunch) - pyBunch is not Bunch."); } Bunch* cpp_bunch = (Bunch*) ((pyORBIT_Object*)pyBunch)->cpp_obj; cpp_LSpaceChargeCalc->trackBunch(cpp_bunch); Py_INCREF(Py_None); return Py_None; } //----------------------------------------------------- //destructor for python LSpaceChargeCalc class (__del__ method). //----------------------------------------------------- static void LSpaceChargeCalc_del(pyORBIT_Object* self){ LSpaceChargeCalc* cpp_LSpaceChargeCalc = (LSpaceChargeCalc*) self->cpp_obj; if(cpp_LSpaceChargeCalc != NULL){ delete cpp_LSpaceChargeCalc; } self->ob_type->tp_free((PyObject*)self); } // defenition of the methods of the python LSpaceChargeCalc wrapper class // they will be vailable from python level static PyMethodDef LSpaceChargeCalcClassMethods[] = { { "trackBunch", LSpaceChargeCalc_trackBunch, METH_VARARGS,"trackBunch the bunch - trackBunch(pyBunch)"}, { "assignImpedanceValue", LSpaceChargeCalc_assignImpedanceValue, METH_VARARGS,"assigne the impedance for the ith mode - assignImpedanceValue(i,real,imag)"}, { "assignImpedance", assignImpedance, METH_VARARGS,"assigne the impedance for the ith mode - assignImpedance(Z))"}, {NULL} }; // defenition of the members of the python LSpaceChargeCalc wrapper class // they will be vailable from python level static PyMemberDef LSpaceChargeCalcClassMembers [] = { {NULL} }; //new python LSpaceChargeCalc wrapper type definition static PyTypeObject pyORBIT_LSpaceChargeCalc_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "LSpaceChargeCalc", /*tp_name*/ sizeof(pyORBIT_Object), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor) LSpaceChargeCalc_del , /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "The LSpaceChargeCalc python wrapper", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ LSpaceChargeCalcClassMethods, /* tp_methods */ LSpaceChargeCalcClassMembers, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) LSpaceChargeCalc_init, /* tp_init */ 0, /* tp_alloc */ LSpaceChargeCalc_new, /* tp_new */ }; //-------------------------------------------------- //Initialization function of the pyLSpaceChargeCalc class //It will be called from SpaceCharge wrapper initialization //-------------------------------------------------- void initLSpaceChargeCalc(PyObject* module){ if (PyType_Ready(&pyORBIT_LSpaceChargeCalc_Type) < 0) return; Py_INCREF(&pyORBIT_LSpaceChargeCalc_Type); PyModule_AddObject(module, "LSpaceChargeCalc", (PyObject *)&pyORBIT_LSpaceChargeCalc_Type); } #ifdef __cplusplus } #endif //end of namespace wrap_spacecharge } <|endoftext|>
<commit_before>/* This file is part of the KDE project * Copyright (C) 2001, 2002 Rolf Magnus <[email protected]> * Copyright (C) 2007 Tim Beaulen <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * $Id$ */ #include "m3ustreamanalyzer.h" #include <string.h> #include <fieldtypes.h> #include <analysisresult.h> #include <streamlineanalyzer.h> #include <string> // AnalyzerFactory void M3uLineAnalyzerFactory::registerFields(Strigi::FieldRegister& reg) { // track list length is easily obtained via API // tracksField = reg.registerField(); trackPathField = reg.registerField("http://freedesktop.org/standards/xesam/1.0/core#links"); m3uTypeField = reg.registerField("http://freedesktop.org/standards/xesam/1.0/core#formatSubtype"); typeField = reg.typeField; } // Analyzer void M3uLineAnalyzer::startAnalysis(Strigi::AnalysisResult* i) { extensionOk = i->extension() == "m3u" || i->extension() == "M3U"; analysisResult = i; line = 0; count = 0; } void M3uLineAnalyzer::handleLine(const char* data, uint32_t length) { if (!extensionOk) return; ++line; if (length == 0) return; if (*data != '#') { if (line == 1) analysisResult->addValue(factory->m3uTypeField, "simple"); // TODO: Check for a valid url with QUrl analysisResult->addValue(factory->trackPathField, std::string(data, length)); ++count; } else if (line == 1 && strncmp(data, "#EXTM3U", 7) == 0) { analysisResult->addValue(factory->m3uTypeField, "extended"); } } bool M3uLineAnalyzer::isReadyWithStream() { // we can analyze each line and are only done if the extension is not ok return !extensionOk; } void M3uLineAnalyzer::endAnalysis(bool complete) { // tracksField has not been initialized, so don't use it //if (complete && extensionOk) //analysisResult->addValue(factory->tracksField, count); if (complete && extensionOk) analysisResult->addValue(factory->typeField, "http://freedesktop.org/standards/xesam/1.0/core#AudioList"); } <commit_msg>add the field to the factory list of fields.<commit_after>/* This file is part of the KDE project * Copyright (C) 2001, 2002 Rolf Magnus <[email protected]> * Copyright (C) 2007 Tim Beaulen <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation version 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * $Id$ */ #include "m3ustreamanalyzer.h" #include <string.h> #include <fieldtypes.h> #include <analysisresult.h> #include <streamlineanalyzer.h> #include <string> // AnalyzerFactory void M3uLineAnalyzerFactory::registerFields(Strigi::FieldRegister& reg) { // track list length is easily obtained via API // tracksField = reg.registerField(); trackPathField = reg.registerField( "http://freedesktop.org/standards/xesam/1.0/core#links"); m3uTypeField = reg.registerField( "http://freedesktop.org/standards/xesam/1.0/core#formatSubtype"); typeField = reg.typeField; addField(trackPathField); addField(m3uTypeField); addField(typeField); } // Analyzer void M3uLineAnalyzer::startAnalysis(Strigi::AnalysisResult* i) { extensionOk = i->extension() == "m3u" || i->extension() == "M3U"; analysisResult = i; line = 0; count = 0; } void M3uLineAnalyzer::handleLine(const char* data, uint32_t length) { if (!extensionOk) return; ++line; if (length == 0) return; if (*data != '#') { if (line == 1) analysisResult->addValue(factory->m3uTypeField, "simple"); // TODO: Check for a valid url with QUrl analysisResult->addValue(factory->trackPathField, std::string(data, length)); ++count; } else if (line == 1 && strncmp(data, "#EXTM3U", 7) == 0) { analysisResult->addValue(factory->m3uTypeField, "extended"); } } bool M3uLineAnalyzer::isReadyWithStream() { // we can analyze each line and are only done if the extension is not ok return !extensionOk; } void M3uLineAnalyzer::endAnalysis(bool complete) { // tracksField has not been initialized, so don't use it //if (complete && extensionOk) //analysisResult->addValue(factory->tracksField, count); if (complete && extensionOk) analysisResult->addValue(factory->typeField, "http://freedesktop.org/standards/xesam/1.0/core#AudioList"); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ObstacleAvoidance.hpp * This class is used to inject the setpoints of an obstacle avoidance system * into the FlightTasks * * @author Martina Rivizzigno */ #pragma once #include <px4_defines.h> #include <px4_module_params.h> #include <commander/px4_custom_mode.h> #include <drivers/drv_hrt.h> #include <uORB/topics/position_controller_status.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/vehicle_status.h> #include <uORB/topics/vehicle_trajectory_waypoint.h> #include <uORB/topics/position_setpoint.h> #include <matrix/matrix/math.hpp> #include <SubscriptionArray.hpp> class ObstacleAvoidance : public ModuleParams { public: ObstacleAvoidance(ModuleParams *parent); ~ObstacleAvoidance(); bool initializeSubscriptions(SubscriptionArray &subscription_array); /** * Inject setpoints from obstacle avoidance system into FlightTasks. * @param pos_sp, position setpoint * @param vel_sp, velocity setpoint * @param yaw_sp, yaw setpoint * @param yaw_speed_sp, yaw speed setpoint */ void injectAvoidanceSetpoints(matrix::Vector3f &pos_sp, matrix::Vector3f &vel_sp, float &yaw_sp, float &yaw_speed_sp); /** * Updates the desired waypoints to send to the obstacle avoidance system. These messages don't have any direct impact on the flight. * @param curr_wp, current position triplet * @param curr_yaw, current yaw triplet * @param curr_yawspeed, current yaw speed triplet * @param next_wp, next position triplet * @param next_yaw, next yaw triplet * @param next_yawspeed, next yaw speed triplet */ void updateAvoidanceDesiredWaypoints(const matrix::Vector3f &curr_wp, const float curr_yaw, const float curr_yawspeed, const matrix::Vector3f &next_wp, const float next_yaw, const float next_yawspeed, const bool ext_yaw_active); /** * Updates the desired setpoints to send to the obstacle avoidance system. * @param pos_sp, desired position setpoint computed by the active FlightTask * @param vel_sp, desired velocity setpoint computed by the active FlightTask */ void updateAvoidanceDesiredSetpoints(const matrix::Vector3f &pos_sp, const matrix::Vector3f &vel_sp); /** * Checks the vehicle progress between previous and current position waypoint of the triplet. * @param pos, vehicle position * @param prev_wp, previous position triplet * @param target_acceptance_radius, current position triplet xy acceptance radius * @param closest_pt, closest point to the vehicle on the line previous-current position triplet * @param */ void checkAvoidanceProgress(const matrix::Vector3f &pos, const matrix::Vector3f &prev_wp, float target_acceptance_radius, const matrix::Vector2f &closest_pt, const int wp_type); private: uORB::Subscription<vehicle_trajectory_waypoint_s> *_sub_vehicle_trajectory_waypoint{nullptr}; /**< vehicle trajectory waypoint subscription */ uORB::Subscription<vehicle_status_s> *_sub_vehicle_status{nullptr}; /**< vehicle status subscription */ DEFINE_PARAMETERS( (ParamFloat<px4::params::NAV_MC_ALT_RAD>) _param_nav_mc_alt_rad /**< Acceptance radius for multicopter altitude */ ); vehicle_trajectory_waypoint_s _desired_waypoint = {}; /**< desired vehicle trajectory waypoint to be sent to OA */ orb_advert_t _pub_traj_wp_avoidance_desired{nullptr}; /**< trajectory waypoint desired publication */ orb_advert_t _pub_pos_control_status{nullptr}; /**< position controller status publication */ orb_advert_t _pub_vehicle_command{nullptr}; /**< vehicle command do publication */ matrix::Vector3f _curr_wp = {}; /**< current position triplet */ matrix::Vector3f _position = {}; /**< current vehicle position */ matrix::Vector3f _failsafe_position = {}; /**< vehicle position when entered in failsafe */ bool _ext_yaw_active = false; /**< true, if external yaw handling is active */ /** * Publishes vehicle trajectory waypoint desired. */ void _publishAvoidanceDesiredWaypoint(); /** * Publishes vehicle command. */ void _publishVehicleCmdDoLoiter(); }; <commit_msg>ObstacleAvoidance: fix comment<commit_after>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ObstacleAvoidance.hpp * This class is used to inject the setpoints of an obstacle avoidance system * into the FlightTasks * * @author Martina Rivizzigno */ #pragma once #include <px4_defines.h> #include <px4_module_params.h> #include <commander/px4_custom_mode.h> #include <drivers/drv_hrt.h> #include <uORB/topics/position_controller_status.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/vehicle_status.h> #include <uORB/topics/vehicle_trajectory_waypoint.h> #include <uORB/topics/position_setpoint.h> #include <matrix/matrix/math.hpp> #include <SubscriptionArray.hpp> class ObstacleAvoidance : public ModuleParams { public: ObstacleAvoidance(ModuleParams *parent); ~ObstacleAvoidance(); bool initializeSubscriptions(SubscriptionArray &subscription_array); /** * Inject setpoints from obstacle avoidance system into FlightTasks. * @param pos_sp, position setpoint * @param vel_sp, velocity setpoint * @param yaw_sp, yaw setpoint * @param yaw_speed_sp, yaw speed setpoint */ void injectAvoidanceSetpoints(matrix::Vector3f &pos_sp, matrix::Vector3f &vel_sp, float &yaw_sp, float &yaw_speed_sp); /** * Updates the desired waypoints to send to the obstacle avoidance system. These messages don't have any direct impact on the flight. * @param curr_wp, current position triplet * @param curr_yaw, current yaw triplet * @param curr_yawspeed, current yaw speed triplet * @param next_wp, next position triplet * @param next_yaw, next yaw triplet * @param next_yawspeed, next yaw speed triplet */ void updateAvoidanceDesiredWaypoints(const matrix::Vector3f &curr_wp, const float curr_yaw, const float curr_yawspeed, const matrix::Vector3f &next_wp, const float next_yaw, const float next_yawspeed, const bool ext_yaw_active); /** * Updates the desired setpoints to send to the obstacle avoidance system. * @param pos_sp, desired position setpoint computed by the active FlightTask * @param vel_sp, desired velocity setpoint computed by the active FlightTask */ void updateAvoidanceDesiredSetpoints(const matrix::Vector3f &pos_sp, const matrix::Vector3f &vel_sp); /** * Checks the vehicle progress between previous and current position waypoint of the triplet. * @param pos, vehicle position * @param prev_wp, previous position triplet * @param target_acceptance_radius, current position triplet xy acceptance radius * @param closest_pt, closest point to the vehicle on the line previous-current position triplet * @param wp_type, current triplet type */ void checkAvoidanceProgress(const matrix::Vector3f &pos, const matrix::Vector3f &prev_wp, float target_acceptance_radius, const matrix::Vector2f &closest_pt, const int wp_type); private: uORB::Subscription<vehicle_trajectory_waypoint_s> *_sub_vehicle_trajectory_waypoint{nullptr}; /**< vehicle trajectory waypoint subscription */ uORB::Subscription<vehicle_status_s> *_sub_vehicle_status{nullptr}; /**< vehicle status subscription */ DEFINE_PARAMETERS( (ParamFloat<px4::params::NAV_MC_ALT_RAD>) _param_nav_mc_alt_rad /**< Acceptance radius for multicopter altitude */ ); vehicle_trajectory_waypoint_s _desired_waypoint = {}; /**< desired vehicle trajectory waypoint to be sent to OA */ orb_advert_t _pub_traj_wp_avoidance_desired{nullptr}; /**< trajectory waypoint desired publication */ orb_advert_t _pub_pos_control_status{nullptr}; /**< position controller status publication */ orb_advert_t _pub_vehicle_command{nullptr}; /**< vehicle command do publication */ matrix::Vector3f _curr_wp = {}; /**< current position triplet */ matrix::Vector3f _position = {}; /**< current vehicle position */ matrix::Vector3f _failsafe_position = {}; /**< vehicle position when entered in failsafe */ bool _ext_yaw_active = false; /**< true, if external yaw handling is active */ /** * Publishes vehicle trajectory waypoint desired. */ void _publishAvoidanceDesiredWaypoint(); /** * Publishes vehicle command. */ void _publishVehicleCmdDoLoiter(); }; <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konstantin Oblaukhov <[email protected]> // #include "GeoPolygonGraphicsItem.h" #include "GeoDataLinearRing.h" #include "GeoDataPolygon.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "GeoDataStyle.h" namespace Marble { GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataFeature *feature, const GeoDataPolygon* polygon ) : GeoGraphicsItem( feature ), m_polygon( polygon ), m_ring( 0 ) { } GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataFeature *feature, const GeoDataLinearRing* ring ) : GeoGraphicsItem( feature ), m_polygon( 0 ), m_ring( ring ) { } const GeoDataLatLonAltBox& GeoPolygonGraphicsItem::latLonAltBox() const { if( m_polygon ) { return m_polygon->latLonAltBox(); } else if ( m_ring ) { return m_ring->latLonAltBox(); } else { return GeoGraphicsItem::latLonAltBox(); } } void GeoPolygonGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport ) { Q_UNUSED( viewport ); if ( !style() ) { painter->save(); painter->setPen( QPen() ); if ( m_polygon ) { painter->drawPolygon( *m_polygon ); } else if ( m_ring ) { painter->drawPolygon( *m_ring ); } painter->restore(); return; } painter->save(); QPen currentPen = painter->pen(); if ( !style()->polyStyle().outline() ) { currentPen.setColor( Qt::transparent ); } else { if ( currentPen.color() != style()->lineStyle().paintedColor() || currentPen.widthF() != style()->lineStyle().width() ) { currentPen.setColor( style()->lineStyle().paintedColor() ); currentPen.setWidthF( style()->lineStyle().width() ); } if ( currentPen.capStyle() != style()->lineStyle().capStyle() ) currentPen.setCapStyle( style()->lineStyle().capStyle() ); if ( currentPen.style() != style()->lineStyle().penStyle() ) currentPen.setStyle( style()->lineStyle().penStyle() ); if ( painter->mapQuality() != Marble::HighQuality && painter->mapQuality() != Marble::PrintQuality ) { QColor penColor = currentPen.color(); penColor.setAlpha( 255 ); currentPen.setColor( penColor ); } } if ( painter->pen() != currentPen ) painter->setPen( currentPen ); if ( !style()->polyStyle().fill() ) { if ( painter->brush().color() != Qt::transparent ) painter->setBrush( QColor( Qt::transparent ) ); } else { if ( painter->brush().color() != style()->polyStyle().paintedColor() ) { painter->setBrush( style()->polyStyle().paintedColor() ); } } if ( m_polygon ) { painter->drawPolygon( *m_polygon ); } else if ( m_ring ) { painter->drawPolygon( *m_ring ); } painter->restore(); } } <commit_msg>resolve some code duplication<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konstantin Oblaukhov <[email protected]> // #include "GeoPolygonGraphicsItem.h" #include "GeoDataLinearRing.h" #include "GeoDataPolygon.h" #include "GeoPainter.h" #include "ViewportParams.h" #include "GeoDataStyle.h" namespace Marble { GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataFeature *feature, const GeoDataPolygon* polygon ) : GeoGraphicsItem( feature ), m_polygon( polygon ), m_ring( 0 ) { } GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataFeature *feature, const GeoDataLinearRing* ring ) : GeoGraphicsItem( feature ), m_polygon( 0 ), m_ring( ring ) { } const GeoDataLatLonAltBox& GeoPolygonGraphicsItem::latLonAltBox() const { if( m_polygon ) { return m_polygon->latLonAltBox(); } else if ( m_ring ) { return m_ring->latLonAltBox(); } else { return GeoGraphicsItem::latLonAltBox(); } } void GeoPolygonGraphicsItem::paint( GeoPainter* painter, const ViewportParams* viewport ) { Q_UNUSED( viewport ); painter->save(); if ( !style() ) { painter->setPen( QPen() ); } else { QPen currentPen = painter->pen(); if ( !style()->polyStyle().outline() ) { currentPen.setColor( Qt::transparent ); } else { if ( currentPen.color() != style()->lineStyle().paintedColor() || currentPen.widthF() != style()->lineStyle().width() ) { currentPen.setColor( style()->lineStyle().paintedColor() ); currentPen.setWidthF( style()->lineStyle().width() ); } if ( currentPen.capStyle() != style()->lineStyle().capStyle() ) currentPen.setCapStyle( style()->lineStyle().capStyle() ); if ( currentPen.style() != style()->lineStyle().penStyle() ) currentPen.setStyle( style()->lineStyle().penStyle() ); if ( painter->mapQuality() != Marble::HighQuality && painter->mapQuality() != Marble::PrintQuality ) { QColor penColor = currentPen.color(); penColor.setAlpha( 255 ); currentPen.setColor( penColor ); } } if ( painter->pen() != currentPen ) painter->setPen( currentPen ); if ( !style()->polyStyle().fill() ) { if ( painter->brush().color() != Qt::transparent ) painter->setBrush( QColor( Qt::transparent ) ); } else { if ( painter->brush().color() != style()->polyStyle().paintedColor() ) { painter->setBrush( style()->polyStyle().paintedColor() ); } } } if ( m_polygon ) { painter->drawPolygon( *m_polygon ); } else if ( m_ring ) { painter->drawPolygon( *m_ring ); } painter->restore(); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <Hooks.h> #include <text.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () : _enabled (true) { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); } _enabled = context.config.getBoolean ("hooks"); } //////////////////////////////////////////////////////////////////////////////// bool Hooks::enable (bool value) { bool old_value = _enabled; _enabled = value; return old_value; } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before any // processing occurs, i.e first // // Input: // - none // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onLaunch () { context.timer_hooks.start (); if (! _enabled) return; std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; std::vector <std::string> args; int status = execute (*i, args, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { // Only 'add' is possible. Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-exit event is triggered once, after all processing is complete, i.e. // last // // Input: // - read-only line of JSON for each task added/modified // // Output: // - any emitted JSON is ignored // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onExit () { context.timer_hooks.start (); if (! _enabled) return; std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] != '{') { if (status == 0) context.footnote (*line); else context.error (*line); } } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - line of JSON for the task added // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onAdd (std::vector <Task>& changes) { /* context.timer_hooks.start (); if (! _enabled) return; std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input = after.composeJSON () + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); // TODO Not sure if this first/!first thing is good. if (first) { after = newTask; first = false; } else context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); */ } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - line of JSON for the original task // - line of JSON for the modified task, the diff being the modification // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onModify (const Task& before, std::vector <Task>& changes) { /* context.timer_hooks.start (); if (! _enabled) return; std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string afterJSON = after.composeJSON (); std::string input = before.composeJSON () + "\n" + afterJSON + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); // TODO Not sure if this first/!first thing is good. if (first) { after = newTask; first = false; } else context.tdb2.modify (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); */ } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Hooks<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <Hooks.h> #include <text.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () : _enabled (true) { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); } _enabled = context.config.getBoolean ("hooks"); } //////////////////////////////////////////////////////////////////////////////// bool Hooks::enable (bool value) { bool old_value = _enabled; _enabled = value; return old_value; } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before any // processing occurs, i.e first // // Input: // - none // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onLaunch () { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; std::vector <std::string> args; int status = execute (*i, args, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { // Only 'add' is possible. Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-exit event is triggered once, after all processing is complete, i.e. // last // // Input: // - read-only line of JSON for each task added/modified // // Output: // - any emitted JSON is ignored // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onExit () { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] != '{') { if (status == 0) context.footnote (*line); else context.error (*line); } } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - line of JSON for the task added // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onAdd (std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input = changes[0].composeJSON () + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - line of JSON for the original task // - line of JSON for the modified task, the diff being the modification // // Output: // - all emitted JSON lines are added/modified as tasks, if the exit code is // zero, otherwise ignored. // - minimal new task: {"description":"Buy milk"} // - to modify a task include complete JSON // - all emitted non-JSON lines are considered feedback messages if the exit // code is zero, otherwise they are considered errors. // void Hooks::onModify (const Task& before, std::vector <Task>& changes) { if (! _enabled) return; context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string afterJSON = changes[0].composeJSON (); std::string input = before.composeJSON () + "\n" + afterJSON + "\n"; std::string output; std::vector <std::string> args; int status = execute (*i, args, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { changes.clear (); for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') changes.push_back (Task (*line)); else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) if (line->length () && (*line)[0] != '{') context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "stan/math/functions/modified_bessel_second_kind.hpp" #include <gtest/gtest.h> TEST(MathFunctions, modified_bessel_second_kind) { using stan::math::modified_bessel_second_kind; EXPECT_FLOAT_EQ(0.011159676085853024269745195979833489225, modified_bessel_second_kind(0,4.0)); EXPECT_THROW(modified_bessel_second_kind(1,-3.0), std::domain_error); EXPECT_THROW(modified_bessel_second_kind(-1,-3.0), std::domain_error); } <commit_msg>added NaN test for modified_bessel_second_kind<commit_after>#include <stan/math/functions/modified_bessel_second_kind.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> TEST(MathFunctions, modified_bessel_second_kind) { using stan::math::modified_bessel_second_kind; EXPECT_FLOAT_EQ(0.011159676085853024269745195979833489225, modified_bessel_second_kind(0,4.0)); EXPECT_THROW(modified_bessel_second_kind(1,-3.0), std::domain_error); EXPECT_THROW(modified_bessel_second_kind(-1,-3.0), std::domain_error); } TEST(MathFunctions, modified_bessel_second_kind_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::modified_bessel_second_kind(0, nan)); } <|endoftext|>
<commit_before>#ifndef __TRAINING_CORE_HPP #define __TRAINING_CORE_HPP #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "nanopolish_eventalign.h" #include "nanopolish_squiggle_read.h" // The state training data comes in two different // sizes Full and Minimal. The model training functions // only actually need the Minimal data but for exploration // the Full data is useful so left as an option. struct MinimalStateTrainingData { // // Functions // MinimalStateTrainingData(const SquiggleRead& sr, const EventAlignment& ea, uint32_t, const std::string&, const std::string&) { // scale the observation to the expected pore model this->level_mean = sr.get_fully_scaled_level(ea.event_idx, ea.strand_idx); this->log_level_mean = std::log(this->level_mean); this->level_stdv = sr.get_scaled_stdv(ea.event_idx, ea.strand_idx); this->log_level_stdv = std::log(this->level_stdv); this->read_var = sr.pore_model[ea.strand_idx].var; this->log_read_var = std::log(this->read_var); this->read_scale_sd = sr.pore_model[ea.strand_idx].scale_sd; this->log_read_scale_sd = std::log(this->read_scale_sd); this->read_var_sd = sr.pore_model[ea.strand_idx].var_sd; this->log_read_var_sd = std::log(this->read_var_sd); } static void write_header(std::ostream& os) { os << "model\tmodel_kmer\tlevel_mean\tlevel_stdv\tread_var\tread_scale_sd\tread_var_sd"; } void write_tsv(std::ostream& os, const std::string& model_name, const std::string& kmer) const { os << model_name << '\t' << kmer << '\t' << std::fixed << std::setprecision(2) << level_mean << '\t' << level_stdv << '\t' << read_var << '\t' << read_scale_sd << '\t' << read_var_sd; } // // Data // float level_mean; float log_level_mean; float level_stdv; float log_level_stdv; float read_var; float log_read_var; float read_scale_sd; float log_read_scale_sd; float read_var_sd; float log_read_var_sd; }; // struct MinimalStateTrainingData struct FullStateTrainingData : public MinimalStateTrainingData { // // Functions // FullStateTrainingData(const SquiggleRead& sr, const EventAlignment& ea, uint32_t rank, const std::string& prev_kmer, const std::string& next_kmer) : MinimalStateTrainingData(sr, ea, rank, prev_kmer, next_kmer) { this->duration = sr.events[ea.strand_idx][ea.event_idx].duration; this->ref_position = ea.ref_position; this->ref_strand = ea.rc; GaussianParameters model = sr.pore_model[ea.strand_idx].get_scaled_parameters(rank); this->z = (sr.get_drift_corrected_level(ea.event_idx, ea.strand_idx) - model.mean ) / model.stdv; this->prev_kmer = prev_kmer; this->next_kmer = next_kmer; } static void write_header(std::ostream& os) { MinimalStateTrainingData::write_header(os); os << "duration\tref_pos\tref_strand\tz\tprev_kmer\tnext_kmer"; } void write_tsv(std::ostream& os, const std::string& model_name, const std::string& kmer) const { MinimalStateTrainingData::write_tsv(os, model_name, kmer); os << duration << '\t' << ref_position << '\t' << ref_strand << '\t' << z << '\t' << prev_kmer << '\t' << next_kmer; } // // Data // float duration; int ref_position; int ref_strand; float z; std::string prev_kmer; std::string next_kmer; }; // struct FullStateTrainingData typedef MinimalStateTrainingData StateTrainingData; //typedef FullStateTrainingData StateTrainingData; struct GaussianMixture { std::vector< float > log_weights; std::vector< PoreModelStateParams > params; }; // struct GaussianMixture struct InvGaussianMixture { std::vector< float > log_weights; std::vector< PoreModelStateParams > params; }; // struct InvGaussianMixture // training functions GaussianMixture train_gaussian_mixture (const std::vector< StateTrainingData >& data, const GaussianMixture& input_mixture); InvGaussianMixture train_invgaussian_mixture(const std::vector< StateTrainingData >& data, const InvGaussianMixture& input_mixture); #endif <commit_msg>fix: allow default construction in order to resize vectors<commit_after>#ifndef __TRAINING_CORE_HPP #define __TRAINING_CORE_HPP #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "nanopolish_eventalign.h" #include "nanopolish_squiggle_read.h" // The state training data comes in two different // sizes Full and Minimal. The model training functions // only actually need the Minimal data but for exploration // the Full data is useful so left as an option. struct MinimalStateTrainingData { // // Functions // MinimalStateTrainingData() = default; MinimalStateTrainingData(const SquiggleRead& sr, const EventAlignment& ea, uint32_t, const std::string&, const std::string&) { // scale the observation to the expected pore model this->level_mean = sr.get_fully_scaled_level(ea.event_idx, ea.strand_idx); this->log_level_mean = std::log(this->level_mean); this->level_stdv = sr.get_scaled_stdv(ea.event_idx, ea.strand_idx); this->log_level_stdv = std::log(this->level_stdv); this->read_var = sr.pore_model[ea.strand_idx].var; this->log_read_var = std::log(this->read_var); this->read_scale_sd = sr.pore_model[ea.strand_idx].scale_sd; this->log_read_scale_sd = std::log(this->read_scale_sd); this->read_var_sd = sr.pore_model[ea.strand_idx].var_sd; this->log_read_var_sd = std::log(this->read_var_sd); } static void write_header(std::ostream& os) { os << "model\tmodel_kmer\tlevel_mean\tlevel_stdv\tread_var\tread_scale_sd\tread_var_sd"; } void write_tsv(std::ostream& os, const std::string& model_name, const std::string& kmer) const { os << model_name << '\t' << kmer << '\t' << std::fixed << std::setprecision(2) << level_mean << '\t' << level_stdv << '\t' << read_var << '\t' << read_scale_sd << '\t' << read_var_sd; } // // Data // float level_mean; float log_level_mean; float level_stdv; float log_level_stdv; float read_var; float log_read_var; float read_scale_sd; float log_read_scale_sd; float read_var_sd; float log_read_var_sd; }; // struct MinimalStateTrainingData struct FullStateTrainingData : public MinimalStateTrainingData { // // Functions // FullStateTrainingData() = default; FullStateTrainingData(const SquiggleRead& sr, const EventAlignment& ea, uint32_t rank, const std::string& prev_kmer, const std::string& next_kmer) : MinimalStateTrainingData(sr, ea, rank, prev_kmer, next_kmer) { this->duration = sr.events[ea.strand_idx][ea.event_idx].duration; this->ref_position = ea.ref_position; this->ref_strand = ea.rc; GaussianParameters model = sr.pore_model[ea.strand_idx].get_scaled_parameters(rank); this->z = (sr.get_drift_corrected_level(ea.event_idx, ea.strand_idx) - model.mean ) / model.stdv; this->prev_kmer = prev_kmer; this->next_kmer = next_kmer; } static void write_header(std::ostream& os) { MinimalStateTrainingData::write_header(os); os << "duration\tref_pos\tref_strand\tz\tprev_kmer\tnext_kmer"; } void write_tsv(std::ostream& os, const std::string& model_name, const std::string& kmer) const { MinimalStateTrainingData::write_tsv(os, model_name, kmer); os << duration << '\t' << ref_position << '\t' << ref_strand << '\t' << z << '\t' << prev_kmer << '\t' << next_kmer; } // // Data // float duration; int ref_position; int ref_strand; float z; std::string prev_kmer; std::string next_kmer; }; // struct FullStateTrainingData typedef MinimalStateTrainingData StateTrainingData; //typedef FullStateTrainingData StateTrainingData; struct GaussianMixture { std::vector< float > log_weights; std::vector< PoreModelStateParams > params; }; // struct GaussianMixture struct InvGaussianMixture { std::vector< float > log_weights; std::vector< PoreModelStateParams > params; }; // struct InvGaussianMixture // training functions GaussianMixture train_gaussian_mixture (const std::vector< StateTrainingData >& data, const GaussianMixture& input_mixture); InvGaussianMixture train_invgaussian_mixture(const std::vector< StateTrainingData >& data, const InvGaussianMixture& input_mixture); #endif <|endoftext|>
<commit_before>// -*- mode: c++ , coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Object.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <[email protected]> */ namespace tbrpg { /** * Constructor */ Object::Object() { this->class_inheritance = std::vector<short>(); this->class_inheritance.push_back(0); this->actual_instance = (void*)this; this->interface_inheritance = std::vector<std::string>(); this->event_handler = nullptr; } /** * Copy constructor * * @param original The object to clone */ Object::Object(const Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->event_handler = original.event_handler; } /** * Copy constructor * * @param original The object to clone */ Object::Object(Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->event_handler = original.event_handler; } /** * Move constructor * * @param original The object to clone */ Object::Object(Object&& original) { std::swap(this->class_inheritance, original.class_inheritance); std::swap(this->actual_instance, original.actual_instance); std::swap(this->event_handler, original.event_handler); } /** * Fork the object * * @return A fork of the object */ Object* Object::fork() const { return (Object*)(new Object(*this)); } /** * Destructor */ Object::~Object() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Object& Object::operator =(const Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->event_handler = original.event_handler; return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Object& Object::operator =(Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->event_handler = original.event_handler; return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ Object& Object::operator =(Object&& original) { std::swap(this->class_inheritance, original.class_inheritance); std::swap(this->actual_instance, original.actual_instance); std::swap(this->event_handler, original.event_handler); return *this; } /** * Equality evaluator * * @param other The other comparand * @return Whether the instances are equal */ bool Object::operator ==(const Object& other) const { return this == &other; } /** * Inequality evaluator * * @param other The other comparand * @return Whether the instances are not equal */ bool Object::operator !=(const Object& other) const { return (*this == other) == false; } /** * 'Instance of' evaluator * * @param other The other comparand * @return Whether the left comparand is an instance of the right comparand's class */ bool Object::operator >=(const Object& other) const { if (this->class_inheritance.size() < other.class_inheritance.size()) return false; for (size_t i = 0, n = other.class_inheritance.size(); i < n; i++) if (this->class_inheritance[i] != other.class_inheritance[i]) return false; return true; } /** * Reversed 'instance of' evaluator * * @param other The other comparand * @return Whether the right comparand is an instance of the left comparand's class */ bool Object::operator <=(const Object& other) const { return other >= *this; } /** * Checks whether the class implements a specific interface * * @param interface The interface * @return Whether the class implements a specific interface */ bool Object::implements(const std::string& interface) const { for (const std::string& elem : this->interface_inheritance) if (elem == interface) return true; return false; } /** * Gets the actual instance of this object * * @return The actual instance of this object */ void* Object::getActual() const { return this->actual_instance; } /** * Invoked on a custom event * * @param action The action name * @param args The action parameters */ void Object::event(const std::string& action, void* args) { if ((this->event_handler)) (*(this->event_handler))(this, action, args); } /** * Copy method * * @param self The object to modify * @param original The reference object */ void Object::__copy__(Object& self, const Object& original) { self = original; } /** * Hash method * * @return The object's hash code */ size_t Object::hash() const { return (size_t)this; } } <commit_msg>interface_inheritance in copying and moving<commit_after>// -*- mode: c++ , coding: utf-8 -*- /** * tbrpg – Text based roll playing game * * Copyright © 2012, 2013 Mattias Andrée ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Object.hpp" /** * Text based roll playing game * * DD2387 Program construction with C++ * Laboration 3 * * @author Mattias Andrée <[email protected]> */ namespace tbrpg { /** * Constructor */ Object::Object() { this->class_inheritance = std::vector<short>(); this->class_inheritance.push_back(0); this->actual_instance = (void*)this; this->interface_inheritance = std::vector<std::string>(); this->event_handler = nullptr; } /** * Copy constructor * * @param original The object to clone */ Object::Object(const Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->interface_inheritance = original.interface_inheritance; this->event_handler = original.event_handler; } /** * Copy constructor * * @param original The object to clone */ Object::Object(Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->interface_inheritance = original.interface_inheritance; this->event_handler = original.event_handler; } /** * Move constructor * * @param original The object to clone */ Object::Object(Object&& original) { std::swap(this->class_inheritance, original.class_inheritance); std::swap(this->actual_instance, original.actual_instance); std::swap(this->interface_inheritance, original.interface_inheritance); std::swap(this->event_handler, original.event_handler); } /** * Fork the object * * @return A fork of the object */ Object* Object::fork() const { return (Object*)(new Object(*this)); } /** * Destructor */ Object::~Object() { // do nothing } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Object& Object::operator =(const Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->interface_inheritance = original.interface_inheritance; this->event_handler = original.event_handler; return *this; } /** * Assignment operator * * @param original The reference object * @return The invoked object */ Object& Object::operator =(Object& original) { this->class_inheritance = original.class_inheritance; this->actual_instance = original.actual_instance; this->interface_inheritance = original.interface_inheritance; this->event_handler = original.event_handler; return *this; } /** * Move operator * * @param original The moved object, its resourced will be moved * @return The invoked object */ Object& Object::operator =(Object&& original) { std::swap(this->class_inheritance, original.class_inheritance); std::swap(this->actual_instance, original.actual_instance); std::swap(this->interface_inheritance, original.interface_inheritance); std::swap(this->event_handler, original.event_handler); return *this; } /** * Equality evaluator * * @param other The other comparand * @return Whether the instances are equal */ bool Object::operator ==(const Object& other) const { return this == &other; } /** * Inequality evaluator * * @param other The other comparand * @return Whether the instances are not equal */ bool Object::operator !=(const Object& other) const { return (*this == other) == false; } /** * 'Instance of' evaluator * * @param other The other comparand * @return Whether the left comparand is an instance of the right comparand's class */ bool Object::operator >=(const Object& other) const { if (this->class_inheritance.size() < other.class_inheritance.size()) return false; for (size_t i = 0, n = other.class_inheritance.size(); i < n; i++) if (this->class_inheritance[i] != other.class_inheritance[i]) return false; return true; } /** * Reversed 'instance of' evaluator * * @param other The other comparand * @return Whether the right comparand is an instance of the left comparand's class */ bool Object::operator <=(const Object& other) const { return other >= *this; } /** * Checks whether the class implements a specific interface * * @param interface The interface * @return Whether the class implements a specific interface */ bool Object::implements(const std::string& interface) const { for (const std::string& elem : this->interface_inheritance) if (elem == interface) return true; return false; } /** * Gets the actual instance of this object * * @return The actual instance of this object */ void* Object::getActual() const { return this->actual_instance; } /** * Invoked on a custom event * * @param action The action name * @param args The action parameters */ void Object::event(const std::string& action, void* args) { if ((this->event_handler)) (*(this->event_handler))(this, action, args); } /** * Copy method * * @param self The object to modify * @param original The reference object */ void Object::__copy__(Object& self, const Object& original) { self = original; } /** * Hash method * * @return The object's hash code */ size_t Object::hash() const { return (size_t)this; } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <set> #include "Search.h" #include "Utils.h" using namespace std; // // Static Variables // uint64_t nextId = 1; // TODO(gabor) this is not threadsafe inline uint64_t generateUniqueId() { nextId++; } // // Class Path // Path::Path(const uint64_t id, const uint64_t source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source), id(id), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const uint64_t source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const Path& source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source.id), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const word* fact, const uint8_t factLength) : edgeType(255), sourceId(0), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const Path& copy) : id(copy.id), sourceId(copy.sourceId), edgeType(copy.edgeType), factLength(copy.factLength) { for (int i = 0; i < copy.factLength; ++i) { this->fact[i] = copy.fact[i]; } }; Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( id == other.id && sourceId == other.sourceId && edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } void Path::operator=(const Path& copy) { this->id = copy.id; this->sourceId = copy.sourceId; this->edgeType = copy.edgeType; this->factLength = copy.factLength; for (int i = 0; i < copy.factLength; ++i) { this->fact[i] = copy.fact[i]; } } Path* Path::source(SearchType& queue) const { if (sourceId == 0) { return NULL; } else { return queue.findPathById(sourceId); } } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() { this->impl = new queue<Path>(); } BreadthFirstSearch::~BreadthFirstSearch() { delete impl; } void BreadthFirstSearch::push(const Path& toAdd) { while (id2path.size() <= toAdd.id) { id2path.push_back(toAdd); } id2path[toAdd.id] = toAdd; impl->push(toAdd); } const Path BreadthFirstSearch::pop() { const Path frontElement = impl->front(); impl->pop(); return frontElement; } bool BreadthFirstSearch::isEmpty() { return impl->empty(); } Path* BreadthFirstSearch::findPathById(uint64_t id) { return &id2path[id]; } // // Class UCSSearch // UCSSearch::UCSSearch() { this->impl = new priority_queue<Path, vector<Path>, PathCompare>(); // TODO(gabor) binomial_heap_tag } UCSSearch::~UCSSearch() { delete impl; } void UCSSearch::push(const Path& toAdd) { while (id2path.size() <= toAdd.id) { id2path.push_back(toAdd); } id2path[toAdd.id] = toAdd; impl->push(toAdd); } const Path UCSSearch::pop() { const Path frontElement = impl->top(); impl->pop(); return frontElement; } bool UCSSearch::isEmpty() { return impl->empty(); } Path* UCSSearch::findPathById(uint64_t id) { return &id2path[id]; } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // vector<Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<Path*> responses; // Add start state to the fringe fringe->push(Path(queryFact, queryFactLength)); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 1000; printf("started search.\n"); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path parent = fringe->pop(); // Update time time += 1; printf("search tick %lu; popped %s\n", time, toString(*graph, *fringe, &parent).c_str()); if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu / %lu%s] search tick; %lu paths found\n", time / tickOOM, timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 1000000 ? "k" : (tickTime < 1000000000 ? "m" : "") ), responses.size()); } // Add the element to the cache cache->add(parent); // -- Check If Valid -- if (knownFacts->contains(parent.fact, parent.factLength)) { Path* result = new Path(parent); printf("> %s\n", toString(*graph, *fringe, result).c_str()); responses.push_back(result); } // -- Mutations -- for (int indexToMutate = 0; indexToMutate < parent.factLength; ++indexToMutate) { // for each index to mutate... const vector<edge>& mutations = graph->outgoingEdges(parent.fact[indexToMutate]); printf(" mutating index %d; %lu children\n", indexToMutate, mutations.size()); for(vector<edge>::const_iterator it = mutations.begin(); it != mutations.end(); ++it) { // for each possible mutation on that index... if (it->type == 9) { continue; } // TODO(gabor) don't ignore nearest neighbors // ... create the mutated fact word mutated[parent.factLength]; for (int i = 0; i < indexToMutate; ++i) { mutated[i] = parent.fact[i]; } mutated[indexToMutate] = it->sink; for (int i = indexToMutate + 1; i < parent.factLength; ++i) { mutated[i] = parent.fact[i]; } // Create the corresponding search state Path child(parent, mutated, parent.factLength, it->type); // Add the state to the fringe if (!cache->isSeen(child)) { fringe->push(child); } } } } printf("Search complete; %lu paths found\n", responses.size()); return responses; } <commit_msg>Limit search to wordnet jumps<commit_after>#include <cstdio> #include <cstdlib> #include <set> #include "Search.h" #include "Utils.h" using namespace std; // // Static Variables // uint64_t nextId = 1; // TODO(gabor) this is not threadsafe inline uint64_t generateUniqueId() { nextId++; } // // Class Path // Path::Path(const uint64_t id, const uint64_t source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source), id(id), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const uint64_t source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const Path& source, const word* fact, const uint8_t factLength, const edge_type& edgeType) : edgeType(edgeType), sourceId(source.id), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const word* fact, const uint8_t factLength) : edgeType(255), sourceId(0), id(generateUniqueId()), factLength(factLength) { for (int i = 0; i < factLength; ++i) { this->fact[i] = fact[i]; } }; Path::Path(const Path& copy) : id(copy.id), sourceId(copy.sourceId), edgeType(copy.edgeType), factLength(copy.factLength) { for (int i = 0; i < copy.factLength; ++i) { this->fact[i] = copy.fact[i]; } }; Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( id == other.id && sourceId == other.sourceId && edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } void Path::operator=(const Path& copy) { this->id = copy.id; this->sourceId = copy.sourceId; this->edgeType = copy.edgeType; this->factLength = copy.factLength; for (int i = 0; i < copy.factLength; ++i) { this->fact[i] = copy.fact[i]; } } Path* Path::source(SearchType& queue) const { if (sourceId == 0) { return NULL; } else { return queue.findPathById(sourceId); } } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() { this->impl = new queue<Path>(); } BreadthFirstSearch::~BreadthFirstSearch() { delete impl; } void BreadthFirstSearch::push(const Path& toAdd) { while (id2path.size() <= toAdd.id) { id2path.push_back(toAdd); } id2path[toAdd.id] = toAdd; impl->push(toAdd); } const Path BreadthFirstSearch::pop() { const Path frontElement = impl->front(); impl->pop(); return frontElement; } bool BreadthFirstSearch::isEmpty() { return impl->empty(); } Path* BreadthFirstSearch::findPathById(uint64_t id) { return &id2path[id]; } // // Class UCSSearch // UCSSearch::UCSSearch() { this->impl = new priority_queue<Path, vector<Path>, PathCompare>(); // TODO(gabor) binomial_heap_tag } UCSSearch::~UCSSearch() { delete impl; } void UCSSearch::push(const Path& toAdd) { while (id2path.size() <= toAdd.id) { id2path.push_back(toAdd); } id2path[toAdd.id] = toAdd; impl->push(toAdd); } const Path UCSSearch::pop() { const Path frontElement = impl->top(); impl->pop(); return frontElement; } bool UCSSearch::isEmpty() { return impl->empty(); } Path* UCSSearch::findPathById(uint64_t id) { return &id2path[id]; } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // vector<Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<Path*> responses; // Add start state to the fringe fringe->push(Path(queryFact, queryFactLength)); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 1000; printf("started search.\n"); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path parent = fringe->pop(); // Update time time += 1; printf("search tick %lu; popped %s\n", time, toString(*graph, *fringe, &parent).c_str()); if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu / %lu%s] search tick; %lu paths found\n", time / tickOOM, timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 1000000 ? "k" : (tickTime < 1000000000 ? "m" : "") ), responses.size()); } // Add the element to the cache cache->add(parent); // -- Check If Valid -- if (knownFacts->contains(parent.fact, parent.factLength)) { Path* result = new Path(parent); printf("> %s\n", toString(*graph, *fringe, result).c_str()); responses.push_back(result); } // -- Mutations -- for (int indexToMutate = 0; indexToMutate < parent.factLength; ++indexToMutate) { // for each index to mutate... const vector<edge>& mutations = graph->outgoingEdges(parent.fact[indexToMutate]); printf(" mutating index %d; %lu children\n", indexToMutate, mutations.size()); for(vector<edge>::const_iterator it = mutations.begin(); it != mutations.end(); ++it) { // for each possible mutation on that index... if (it->type > 1) { continue; } // TODO(gabor) don't only do WordNet jumps // ... create the mutated fact word mutated[parent.factLength]; for (int i = 0; i < indexToMutate; ++i) { mutated[i] = parent.fact[i]; } mutated[indexToMutate] = it->sink; for (int i = indexToMutate + 1; i < parent.factLength; ++i) { mutated[i] = parent.fact[i]; } // Create the corresponding search state Path child(parent, mutated, parent.factLength, it->type); // Add the state to the fringe if (!cache->isSeen(child)) { fringe->push(child); } } } } printf("Search complete; %lu paths found\n", responses.size()); return responses; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <set> #include <cstring> #include <ctime> #include "Search.h" #include "Utils.h" using namespace std; // // Utilities // /** Check if element |index| is set in the bitmask */ inline bool isSetBit(const uint64_t bitmask[], const uint8_t& index) { uint8_t bucket = index >> 6; uint8_t offset = index % 64; uint64_t mask = 0x1 << offset; return bitmask[bucket] & mask != 0; } /** Set element |index| in the bitmask */ inline bool setBit(uint64_t bitmask[], const uint8_t& index) { uint8_t bucket = index >> 6; uint8_t offset = index % 64; uint64_t mask = 0x1 << offset; bitmask[bucket] = bitmask[bucket] | mask; } // // Class Path // Path::Path(const Path* parentOrNull, const word* fact, uint8_t factLength, edge_type edgeType, const uint64_t fixedBitmask[], uint8_t lastMutatedIndex) : parent(parentOrNull), fact(fact), factLength(factLength), lastMutationIndex(lastMutatedIndex), edgeType(edgeType), fixedBitmask{fixedBitmask[0], fixedBitmask[1], fixedBitmask[2], fixedBitmask[3]} { } Path::Path(const word* fact, uint8_t factLength) : parent(NULL), fact(fact), factLength(factLength), lastMutationIndex(255), edgeType(255), fixedBitmask{0,0,0,0} { } Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() : fringeLength(0), fringeCapacity(1), fringeI(0), poolCapacity(1), poolLength(0), poppedRoot(false), sumOffset(0){ this->fringe = (Path*) malloc(fringeCapacity * sizeof(Path)); this->memoryPool = (word*) malloc(poolCapacity * sizeof(word*)); } BreadthFirstSearch::~BreadthFirstSearch() { free(this->fringe); free(this->memoryPool); delete this->root; } inline const Path* BreadthFirstSearch::push( const Path* parent, uint8_t mutationIndex, uint8_t replaceLength, word replace1, word replace2, edge_type edge) { // Allocate new fact uint8_t mutatedLength = parent->factLength - 1 + replaceLength; // (ensure space) while (poolLength + mutatedLength >= poolCapacity) { // (re-allocate array) word* newPool = (word*) malloc(2 * poolCapacity * sizeof(word*)); if (newPool == NULL) { printf("WARN: could not allocate new fact pool (new length=%lu)]\n", 2*poolCapacity); return NULL; } uint64_t startOffset = ((uint64_t) newPool) - ((uint64_t) memoryPool); memcpy(newPool, memoryPool, poolCapacity * sizeof(word*)); free(memoryPool); memoryPool = newPool; poolCapacity = 2 * poolCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i <fringeLength; ++i) { fringe[i].fact = (word*) (startOffset + ((uint64_t) fringe[i].fact)); } } // (allocate fact) word* mutated = &memoryPool[poolLength]; poolLength += mutatedLength; // (mutate fact) memcpy(mutated, parent->fact, mutationIndex * sizeof(word)); if (replaceLength > 0) { mutated[mutationIndex] = replace1; } if (replaceLength > 1) { mutated[mutationIndex + 1] = replace2; } if (mutationIndex < parent->factLength - 1) { memcpy(&(mutated[mutationIndex + replaceLength]), &(parent->fact[mutationIndex + 1]), (parent->factLength - mutationIndex - 1) * sizeof(word)); } // Compute fixed bitmap uint64_t fixedBitmask[4]; memcpy(fixedBitmask, parent->fixedBitmask, 4 * sizeof(uint64_t)); if (mutationIndex != parent->lastMutationIndex) { setBit(fixedBitmask, parent->lastMutationIndex); } // Allocate new path // (ensure space) while (fringeLength >= fringeCapacity) { // (re-allocate array) Path* newFringe = (Path*) malloc(2 * fringeCapacity * sizeof(Path)); if (newFringe == NULL) { printf("WARN: could not allocate new fringe (new length=%lu)]\n", 2*fringeCapacity); return NULL; } uint64_t startOffset = ((uint64_t) newFringe) - ((uint64_t) fringe); memcpy(newFringe, fringe, fringeCapacity * sizeof(Path)); free(fringe); fringe = newFringe; fringeCapacity = 2 * fringeCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i < fringeLength; ++i) { if (fringe[i].parent != root) { fringe[i].parent = (Path*) (startOffset + ((uint64_t) fringe[i].parent)); } } if (parent != root) { parent = (Path*) (startOffset + ((uint64_t) parent)); } } // (allocate path) new(&fringe[fringeLength]) Path(parent, mutated, mutatedLength, edge, fixedBitmask, mutationIndex); fringeLength += 1; return parent; } const Path* BreadthFirstSearch::peek() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } return &this->fringe[this->fringeI]; } inline const Path* BreadthFirstSearch::pop() { if (this->fringeI == 0 && !poppedRoot) { poppedRoot = true; return root; } this->fringeI += 1; return &this->fringe[this->fringeI - 1]; } inline bool BreadthFirstSearch::isEmpty() { return (fringeI >= fringeLength && poppedRoot) || root == NULL; } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // // A helper to push elements to the queue en bulk inline const Path* flushQueue(SearchType* fringe, const Path* parent, const uint8_t* indexToMutateArr, const word* sinkArr, const uint8_t* typeArr, const uint8_t queueLength) { uint8_t i = 0; while (parent != NULL && i < queueLength) { parent = fringe->push(parent, indexToMutateArr[i], 1, sinkArr[i], 0, typeArr[i]); i += 1; } return parent; } // The main search() function vector<const Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<const Path*> responses; // Create the start state fringe->root = new Path(queryFact, queryFactLength); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 100; std::clock_t startTime = std::clock(); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { // (fringe is empty -- this should basically never be called) printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path* parent = fringe->pop(); // Update time time += 1; if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu%s / %lu%s search tick]; %lu paths found (%lu ms elapsed)\n", time / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), responses.size(), (uint64_t) (1000.0 * ( std::clock() - startTime ) / ((double) CLOCKS_PER_SEC))); } // -- Check If Valid -- printf("Checking %s\n", toString(*graph, parent->fact, parent->factLength).c_str()); if (knownFacts->contains(parent->fact, parent->factLength)) { responses.push_back(parent); } // -- Mutations -- // (variables) uint8_t parentLength = parent->factLength; const uint64_t fixedBitmask[4] = { parent->fixedBitmask[0], parent->fixedBitmask[1], parent->fixedBitmask[2], parent->fixedBitmask[3] }; const word* parentFact = parent->fact; // note: this can change over the course of the search // (mutation queue) uint8_t indexToMutateArr[256]; word sinkArr[256]; uint8_t typeArr[256]; uint8_t queueLength = 0; // (algorithm) for (uint8_t indexToMutate = 0; indexToMutate < parentLength; ++indexToMutate) { // for each index to mutate... if (isSetBit(fixedBitmask, indexToMutate)) { continue; } uint32_t numMutations = 0; const edge* mutations = graph->outgoingEdgesFast(parentFact[indexToMutate], &numMutations); for (int i = 0; i < numMutations; ++i) { // Prune edges to add if (mutations[i].type > 1) { continue; } // TODO(gabor) don't only do WordNet up // Flush if necessary (save memory) if (queueLength >= 256) { parent = flushQueue(fringe, parent, indexToMutateArr, sinkArr, typeArr, queueLength); if (parent == NULL) { printf("Error pushing to stack; returning\n"); return responses; } parentFact = parent->fact; queueLength = 0; } // Add the state to the fringe // These are queued up in order to try to protect the cache; the push() call is // fairly expensive memory-wise. indexToMutateArr[queueLength] = indexToMutate; sinkArr[queueLength] = mutations[i].sink; typeArr[queueLength] = mutations[i].type; printf("\tmutation [%d] %s -> %s (type %s)\n", indexToMutateArr[queueLength], graph->gloss(parent->fact[indexToMutateArr[queueLength]]), graph->gloss(sinkArr[queueLength]), toString(typeArr[queueLength]).c_str()); queueLength += 1; // parent = fringe->push(parent, indexToMutate, 1, mutations[i].sink, 0, mutations[i].type); } } if (flushQueue(fringe, parent, indexToMutateArr, sinkArr, typeArr, queueLength) == NULL) { printf("Error pushing to stack; returning\n"); return responses; } } return responses; } <commit_msg>Remove debugging statements<commit_after>#include <cstdio> #include <cstdlib> #include <set> #include <cstring> #include <ctime> #include "Search.h" #include "Utils.h" using namespace std; // // Utilities // /** Check if element |index| is set in the bitmask */ inline bool isSetBit(const uint64_t bitmask[], const uint8_t& index) { uint8_t bucket = index >> 6; uint8_t offset = index % 64; uint64_t mask = 0x1 << offset; return bitmask[bucket] & mask != 0; } /** Set element |index| in the bitmask */ inline bool setBit(uint64_t bitmask[], const uint8_t& index) { uint8_t bucket = index >> 6; uint8_t offset = index % 64; uint64_t mask = 0x1 << offset; bitmask[bucket] = bitmask[bucket] | mask; } // // Class Path // Path::Path(const Path* parentOrNull, const word* fact, uint8_t factLength, edge_type edgeType, const uint64_t fixedBitmask[], uint8_t lastMutatedIndex) : parent(parentOrNull), fact(fact), factLength(factLength), lastMutationIndex(lastMutatedIndex), edgeType(edgeType), fixedBitmask{fixedBitmask[0], fixedBitmask[1], fixedBitmask[2], fixedBitmask[3]} { } Path::Path(const word* fact, uint8_t factLength) : parent(NULL), fact(fact), factLength(factLength), lastMutationIndex(255), edgeType(255), fixedBitmask{0,0,0,0} { } Path::~Path() { }; bool Path::operator==(const Path& other) const { // Check metadata if ( !( edgeType == other.edgeType && factLength == other.factLength ) ) { return false; } // Check fact content for (int i = 0; i < factLength; ++i) { if (other.fact[i] != fact[i]) { return false; } } // Return true return true; } // // Class SearchType // // // Class BreadthFirstSearch // BreadthFirstSearch::BreadthFirstSearch() : fringeLength(0), fringeCapacity(1), fringeI(0), poolCapacity(1), poolLength(0), poppedRoot(false), sumOffset(0){ this->fringe = (Path*) malloc(fringeCapacity * sizeof(Path)); this->memoryPool = (word*) malloc(poolCapacity * sizeof(word*)); } BreadthFirstSearch::~BreadthFirstSearch() { free(this->fringe); free(this->memoryPool); delete this->root; } inline const Path* BreadthFirstSearch::push( const Path* parent, uint8_t mutationIndex, uint8_t replaceLength, word replace1, word replace2, edge_type edge) { // Allocate new fact uint8_t mutatedLength = parent->factLength - 1 + replaceLength; // (ensure space) while (poolLength + mutatedLength >= poolCapacity) { // (re-allocate array) word* newPool = (word*) malloc(2 * poolCapacity * sizeof(word*)); if (newPool == NULL) { printf("WARN: could not allocate new fact pool (new length=%lu)]\n", 2*poolCapacity); return NULL; } uint64_t startOffset = ((uint64_t) newPool) - ((uint64_t) memoryPool); memcpy(newPool, memoryPool, poolCapacity * sizeof(word*)); free(memoryPool); memoryPool = newPool; poolCapacity = 2 * poolCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i <fringeLength; ++i) { fringe[i].fact = (word*) (startOffset + ((uint64_t) fringe[i].fact)); } } // (allocate fact) word* mutated = &memoryPool[poolLength]; poolLength += mutatedLength; // (mutate fact) memcpy(mutated, parent->fact, mutationIndex * sizeof(word)); if (replaceLength > 0) { mutated[mutationIndex] = replace1; } if (replaceLength > 1) { mutated[mutationIndex + 1] = replace2; } if (mutationIndex < parent->factLength - 1) { memcpy(&(mutated[mutationIndex + replaceLength]), &(parent->fact[mutationIndex + 1]), (parent->factLength - mutationIndex - 1) * sizeof(word)); } // Compute fixed bitmap uint64_t fixedBitmask[4]; memcpy(fixedBitmask, parent->fixedBitmask, 4 * sizeof(uint64_t)); if (mutationIndex != parent->lastMutationIndex) { setBit(fixedBitmask, parent->lastMutationIndex); } // Allocate new path // (ensure space) while (fringeLength >= fringeCapacity) { // (re-allocate array) Path* newFringe = (Path*) malloc(2 * fringeCapacity * sizeof(Path)); if (newFringe == NULL) { printf("WARN: could not allocate new fringe (new length=%lu)]\n", 2*fringeCapacity); return NULL; } uint64_t startOffset = ((uint64_t) newFringe) - ((uint64_t) fringe); memcpy(newFringe, fringe, fringeCapacity * sizeof(Path)); free(fringe); fringe = newFringe; fringeCapacity = 2 * fringeCapacity; // (fix pointers -- and God help me for pointer arithmetic) for (int i = 0; i < fringeLength; ++i) { if (fringe[i].parent != root) { fringe[i].parent = (Path*) (startOffset + ((uint64_t) fringe[i].parent)); } } if (parent != root) { parent = (Path*) (startOffset + ((uint64_t) parent)); } } // (allocate path) new(&fringe[fringeLength]) Path(parent, mutated, mutatedLength, edge, fixedBitmask, mutationIndex); fringeLength += 1; return parent; } const Path* BreadthFirstSearch::peek() { if (!poppedRoot && this->fringeI == 0) { poppedRoot = true; return root; } return &this->fringe[this->fringeI]; } inline const Path* BreadthFirstSearch::pop() { if (this->fringeI == 0 && !poppedRoot) { poppedRoot = true; return root; } this->fringeI += 1; return &this->fringe[this->fringeI - 1]; } inline bool BreadthFirstSearch::isEmpty() { return (fringeI >= fringeLength && poppedRoot) || root == NULL; } // // Class CacheStrategy // // // Class CacheStrategyNone // bool CacheStrategyNone::isSeen(const Path&) { return false; } void CacheStrategyNone::add(const Path&) { } // // Function search() // // A helper to push elements to the queue en bulk inline const Path* flushQueue(SearchType* fringe, const Path* parent, const uint8_t* indexToMutateArr, const word* sinkArr, const uint8_t* typeArr, const uint8_t queueLength) { uint8_t i = 0; while (parent != NULL && i < queueLength) { parent = fringe->push(parent, indexToMutateArr[i], 1, sinkArr[i], 0, typeArr[i]); i += 1; } return parent; } // The main search() function vector<const Path*> Search(Graph* graph, FactDB* knownFacts, const word* queryFact, const uint8_t queryFactLength, SearchType* fringe, CacheStrategy* cache, const uint64_t timeout) { // // Setup // // Create a vector for the return value to occupy vector<const Path*> responses; // Create the start state fringe->root = new Path(queryFact, queryFactLength); // I need the memory to not go away // Initialize timer (number of elements popped from the fringe) uint64_t time = 0; const uint32_t tickTime = 100; std::clock_t startTime = std::clock(); // // Search // while (!fringe->isEmpty() && time < timeout) { // Get the next element from the fringe if (fringe->isEmpty()) { // (fringe is empty -- this should basically never be called) printf("IMPOSSIBLE: the search fringe is empty. This means (a) there are leaf nodes in the graph, and (b) this would have caused a memory leak.\n"); std::exit(1); } const Path* parent = fringe->pop(); // Update time time += 1; if (time % tickTime == 0) { const uint32_t tickOOM = tickTime < 1000 ? 1 : (tickTime < 1000000 ? 1000 : (tickTime < 1000000000 ? 1000000 : 1) ); printf("[%lu%s / %lu%s search tick]; %lu paths found (%lu ms elapsed)\n", time / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), timeout / tickOOM, tickTime < 1000 ? "" : (tickTime < 999999 ? "k" : (tickTime < 999999999 ? "m" : "") ), responses.size(), (uint64_t) (1000.0 * ( std::clock() - startTime ) / ((double) CLOCKS_PER_SEC))); } // -- Check If Valid -- // printf("Checking %s\n", toString(*graph, parent->fact, parent->factLength).c_str()); if (knownFacts->contains(parent->fact, parent->factLength)) { responses.push_back(parent); } // -- Mutations -- // (variables) uint8_t parentLength = parent->factLength; const uint64_t fixedBitmask[4] = { parent->fixedBitmask[0], parent->fixedBitmask[1], parent->fixedBitmask[2], parent->fixedBitmask[3] }; const word* parentFact = parent->fact; // note: this can change over the course of the search // (mutation queue) uint8_t indexToMutateArr[256]; word sinkArr[256]; uint8_t typeArr[256]; uint8_t queueLength = 0; // (algorithm) for (uint8_t indexToMutate = 0; indexToMutate < parentLength; ++indexToMutate) { // for each index to mutate... if (isSetBit(fixedBitmask, indexToMutate)) { continue; } uint32_t numMutations = 0; const edge* mutations = graph->outgoingEdgesFast(parentFact[indexToMutate], &numMutations); for (int i = 0; i < numMutations; ++i) { // Prune edges to add if (mutations[i].type != 1) { continue; } // TODO(gabor) don't only do WordNet down // Flush if necessary (save memory) if (queueLength >= 255) { parent = flushQueue(fringe, parent, indexToMutateArr, sinkArr, typeArr, queueLength); if (parent == NULL) { printf("Error pushing to stack; returning\n"); return responses; } parentFact = parent->fact; queueLength = 0; } // Add the state to the fringe // These are queued up in order to try to protect the cache; the push() call is // fairly expensive memory-wise. indexToMutateArr[queueLength] = indexToMutate; sinkArr[queueLength] = mutations[i].sink; typeArr[queueLength] = mutations[i].type; // printf("\tmutation [%d] %s -> %s (type %s)\n", indexToMutateArr[queueLength], // graph->gloss(parent->fact[indexToMutateArr[queueLength]]), // graph->gloss(sinkArr[queueLength]), // toString(typeArr[queueLength]).c_str()); queueLength += 1; // parent = fringe->push(parent, indexToMutate, 1, mutations[i].sink, 0, mutations[i].type); } } if (flushQueue(fringe, parent, indexToMutateArr, sinkArr, typeArr, queueLength) == NULL) { printf("Error pushing to stack; returning\n"); return responses; } } return responses; } <|endoftext|>
<commit_before>// // Token.cpp // Phantasma // // Created by Thomas Harte on 08/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "Token.h" uint32_t Token::GetValue(CGameState *gameState, uint32_t suggestedValue) { switch(type) { case CONSTANT: return value; case VARIABLE: return gameState->GetVariable(value); default: return suggestedValue; } } <commit_msg>Fleshed out implementation.<commit_after>// // Token.cpp // Phantasma // // Created by Thomas Harte on 08/12/2013. // Copyright (c) 2013 Thomas Harte. All rights reserved. // #include "Token.h" Token::Token(Type _type) { type = _type; } Token::Token(std::string *_string) { type = Token::STRINGLITERAL; string = _string; } Token::Token(Type _type, uint32_t _value) { type = _type; value = _value; } Token::Type Token::getType() { return type; } uint32_t Token::GetValue(CGameState *gameState, uint32_t suggestedValue) { switch(type) { case CONSTANT: return value; case VARIABLE: return gameState->GetVariable(value); default: return suggestedValue; } } Token::~Token() { if(type == Token::STRINGLITERAL && string) delete string; } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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 <QObject> #include <QProcessEnvironment> #include <QStandardPaths> #if defined(Q_OS_WIN32) #include <QSettings> #endif #if defined(Q_OS_LINUX) #include <QApplication> #include <QDir> #include <QFile> #endif #include "platform.h" #if defined(Q_OS_WIN32) const QString gRegistryPath("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"); #endif #if defined(Q_OS_LINUX) const QString gAutoStartPath(QDir::homePath() + "/.config/autostart/nitroshare.desktop"); const QString gDesktopFile( "[Desktop Entry]\n" "Version=1.0\n" "Name=NitroShare\n" "Type=Application\n" "Exec=%1\n" "Terminal=false\n" ); #endif Platform::OperatingSystem Platform::currentOperatingSystem() { #if defined(Q_OS_WIN32) return OperatingSystem::Windows; #elif defined(Q_OS_MACX) return OperatingSystem::OSX; #elif defined(Q_OS_LINUX) return OperatingSystem::Linux; #else return OperatingSystem::Unknown; #endif } Platform::Architecture Platform::currentArchitecture() { // Note: Qt doesn't provide the definitions we need to accurately // determine the CPU architecture - in order to do that, we'll need // to check a few preprocessor definitions ourselves #if defined(__i386__) || defined(_M_IX86) return Architecture::x86; #elif defined(__x86_64__) || defined(_M_X64) return Architecture::x64; #else return Architecture::Unknown; #endif } Platform::DesktopEnvironment Platform::currentDesktopEnvironment() { QString desktop = QProcessEnvironment::systemEnvironment().value("XDG_CURRENT_DESKTOP").toLower(); if(desktop == "unity") { return DesktopEnvironment::Unity; } else if(desktop.startsWith("gnome")) { return DesktopEnvironment::Gnome; } else if(desktop.endsWith("plasma")) { return DesktopEnvironment::KDE; } else if(desktop == "xfce") { return DesktopEnvironment::XFCE; } else if(desktop == "mate") { return DesktopEnvironment::MATE; } else if(desktop.endsWith("cinnamon")) { return DesktopEnvironment::Cinnamon; } else if(desktop == "pantheon") { return DesktopEnvironment::Pantheon; } else { return DesktopEnvironment::Unknown; } } QString Platform::operatingSystemName(OperatingSystem operatingSystem) { switch(operatingSystem) { case OperatingSystem::Windows: return "windows"; case OperatingSystem::OSX: return "osx"; case OperatingSystem::Linux: return "linux"; default: return "unknown"; } } QString Platform::operatingSystemFriendlyName(OperatingSystem operatingSystem) { switch(operatingSystem) { case OperatingSystem::Windows: return QObject::tr("Windows"); case OperatingSystem::OSX: return QObject::tr("OS X"); case OperatingSystem::Linux: return QObject::tr("Linux"); default: return QObject::tr("Unknown"); } } Platform::OperatingSystem Platform::operatingSystemForName(const QString &name) { if(name == "windows") { return OperatingSystem::Windows; } else if(name == "osx") { return OperatingSystem::OSX; } else if(name == "linux") { return OperatingSystem::Linux; } else { return OperatingSystem::Unknown; } } QString Platform::architectureName(Architecture architecture) { switch(architecture) { case Architecture::x86: return "x86"; case Architecture::x64: return "x86_64"; default: return "unknown"; } } bool Platform::useIndicator() { // Detecting the correct icon to display is incredibly difficult - the // algorithm currently being used goes something like this: // - Windows: use QSystemTrayIcon // - OS X: use QSystemTrayIcon // - Linux: // - Unity: use AppIndicator // - Gnome: use AppIndicator // - KDE: use QSystemTrayIcon // - MATE: use AppIndicator // - Cinnamon: use AppIndicator // - Pantheon: use AppIndicator if(currentOperatingSystem() == OperatingSystem::Linux) { switch(currentDesktopEnvironment()) { case DesktopEnvironment::Unity: case DesktopEnvironment::Gnome: case DesktopEnvironment::MATE: case DesktopEnvironment::Cinnamon: case DesktopEnvironment::Pantheon: return true; default: return false; } } // For everything else, use QSystemTrayIcon return false; } bool Platform::autoStart() { #if defined(Q_OS_WIN32) return QSettings(gRegistryPath, QSettings::NativeFormat).contains("NitroShare"); #elif defined(Q_OS_MACX) return false; #elif defined(Q_OS_LINUX) return QFile::exists(gAutoStartPath); #else return false; #endif } bool Platform::setAutoStart(bool enable) { const QString execPath(QApplication::arguments().at(0)); #if defined(Q_OS_WIN32) QSettings settings(gRegistryPath, QSettings::NativeFormat); if (enable) { settings.setValue("NitroShare", execPath); } else { settings.remove("NitroShare"); } return true; #elif defined(Q_OS_MACX) return false; #elif defined(Q_OS_LINUX) if (enable) { QFile file(gAutoStartPath); if (!file.open(QIODevice::WriteOnly)) { return false; } return file.write(gDesktopFile.arg(execPath).toUtf8()) != -1; } else { return QFile::remove(gAutoStartPath); } #else return false; #endif } <commit_msg>Fixed compilation error on Windows.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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 <QApplication> #include <QObject> #include <QProcessEnvironment> #include <QStandardPaths> #if defined(Q_OS_WIN32) #include <QSettings> #endif #if defined(Q_OS_LINUX) #include <QDir> #include <QFile> #endif #include "platform.h" #if defined(Q_OS_WIN32) const QString gRegistryPath("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"); #endif #if defined(Q_OS_LINUX) const QString gAutoStartPath(QDir::homePath() + "/.config/autostart/nitroshare.desktop"); const QString gDesktopFile( "[Desktop Entry]\n" "Version=1.0\n" "Name=NitroShare\n" "Type=Application\n" "Exec=%1\n" "Terminal=false\n" ); #endif Platform::OperatingSystem Platform::currentOperatingSystem() { #if defined(Q_OS_WIN32) return OperatingSystem::Windows; #elif defined(Q_OS_MACX) return OperatingSystem::OSX; #elif defined(Q_OS_LINUX) return OperatingSystem::Linux; #else return OperatingSystem::Unknown; #endif } Platform::Architecture Platform::currentArchitecture() { // Note: Qt doesn't provide the definitions we need to accurately // determine the CPU architecture - in order to do that, we'll need // to check a few preprocessor definitions ourselves #if defined(__i386__) || defined(_M_IX86) return Architecture::x86; #elif defined(__x86_64__) || defined(_M_X64) return Architecture::x64; #else return Architecture::Unknown; #endif } Platform::DesktopEnvironment Platform::currentDesktopEnvironment() { QString desktop = QProcessEnvironment::systemEnvironment().value("XDG_CURRENT_DESKTOP").toLower(); if(desktop == "unity") { return DesktopEnvironment::Unity; } else if(desktop.startsWith("gnome")) { return DesktopEnvironment::Gnome; } else if(desktop.endsWith("plasma")) { return DesktopEnvironment::KDE; } else if(desktop == "xfce") { return DesktopEnvironment::XFCE; } else if(desktop == "mate") { return DesktopEnvironment::MATE; } else if(desktop.endsWith("cinnamon")) { return DesktopEnvironment::Cinnamon; } else if(desktop == "pantheon") { return DesktopEnvironment::Pantheon; } else { return DesktopEnvironment::Unknown; } } QString Platform::operatingSystemName(OperatingSystem operatingSystem) { switch(operatingSystem) { case OperatingSystem::Windows: return "windows"; case OperatingSystem::OSX: return "osx"; case OperatingSystem::Linux: return "linux"; default: return "unknown"; } } QString Platform::operatingSystemFriendlyName(OperatingSystem operatingSystem) { switch(operatingSystem) { case OperatingSystem::Windows: return QObject::tr("Windows"); case OperatingSystem::OSX: return QObject::tr("OS X"); case OperatingSystem::Linux: return QObject::tr("Linux"); default: return QObject::tr("Unknown"); } } Platform::OperatingSystem Platform::operatingSystemForName(const QString &name) { if(name == "windows") { return OperatingSystem::Windows; } else if(name == "osx") { return OperatingSystem::OSX; } else if(name == "linux") { return OperatingSystem::Linux; } else { return OperatingSystem::Unknown; } } QString Platform::architectureName(Architecture architecture) { switch(architecture) { case Architecture::x86: return "x86"; case Architecture::x64: return "x86_64"; default: return "unknown"; } } bool Platform::useIndicator() { // Detecting the correct icon to display is incredibly difficult - the // algorithm currently being used goes something like this: // - Windows: use QSystemTrayIcon // - OS X: use QSystemTrayIcon // - Linux: // - Unity: use AppIndicator // - Gnome: use AppIndicator // - KDE: use QSystemTrayIcon // - MATE: use AppIndicator // - Cinnamon: use AppIndicator // - Pantheon: use AppIndicator if(currentOperatingSystem() == OperatingSystem::Linux) { switch(currentDesktopEnvironment()) { case DesktopEnvironment::Unity: case DesktopEnvironment::Gnome: case DesktopEnvironment::MATE: case DesktopEnvironment::Cinnamon: case DesktopEnvironment::Pantheon: return true; default: return false; } } // For everything else, use QSystemTrayIcon return false; } bool Platform::autoStart() { #if defined(Q_OS_WIN32) return QSettings(gRegistryPath, QSettings::NativeFormat).contains("NitroShare"); #elif defined(Q_OS_MACX) return false; #elif defined(Q_OS_LINUX) return QFile::exists(gAutoStartPath); #else return false; #endif } bool Platform::setAutoStart(bool enable) { const QString execPath(QApplication::arguments().at(0)); #if defined(Q_OS_WIN32) QSettings settings(gRegistryPath, QSettings::NativeFormat); if (enable) { settings.setValue("NitroShare", execPath); } else { settings.remove("NitroShare"); } return true; #elif defined(Q_OS_MACX) return false; #elif defined(Q_OS_LINUX) if (enable) { QFile file(gAutoStartPath); if (!file.open(QIODevice::WriteOnly)) { return false; } return file.write(gDesktopFile.arg(execPath).toUtf8()) != -1; } else { return QFile::remove(gAutoStartPath); } #else return false; #endif } <|endoftext|>
<commit_before>/* Copyright (c) 2003-2010 KenamicK Entertainment 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 "Main.h" #ifdef LINUX_BUILD #include <sys/timeb.h> #include <time.h> #define _ftime ftime struct timeb time_struct; #else /* LINUX_BUILD */ struct _timeb time_struct; #endif /* LINUX_BUILD */ static std::ofstream debug_file; /////////////////////////////////////////////////////////////////////// // Name: FixAngle() // Desc: angle E{ 0, PI*2 ) (RAD) /////////////////////////////////////////////////////////////////////// void FixAngle(float *angle) { float myangle = *angle; bool bfixed = false; while ( !bfixed ) { if ( myangle > PI2 ) { myangle -= PI2; } else if ( myangle < 0.0f ) { myangle += PI2; } else { bfixed = true; } } *angle = myangle; } /////////////////////////////////////////////////////////////////////// // Name: Rad2Deg() // Desc: Keeps radians in the range of (-PI, PI) /////////////////////////////////////////////////////////////////////// float FixRad(float rad) { float fixed_rad = rad; fixed_rad = fixed_rad > PI ? fixed_rad - PI2 : fixed_rad; fixed_rad = fixed_rad < -PI ? PI2 + fixed_rad : fixed_rad; return fixed_rad; } /////////////////////////////////////////////////////////////////////// // Name: Rad2Deg() // Desc: Convert radians (-PI, PI) to degress (0, 360) /////////////////////////////////////////////////////////////////////// float Rad2Deg(float rad) { float fixed_rad = rad > 0.0f ? rad : (PI2 + rad); return fixed_rad * RAD1; } /////////////////////////////////////////////////////////////////////// // Name: Deg2Rad() // Desc: Convert degress (0, 360) to radians (-PI, PI) /////////////////////////////////////////////////////////////////////// float Deg2Rad(float deg) { deg = deg < 0.0 ? 360.0f - deg : deg; deg = deg > 360.0f ? deg - 360.0f : deg; float fixed_rad = deg * DEG1; fixed_rad = fixed_rad > PI ? fixed_rad - PI2 : fixed_rad; fixed_rad = fixed_rad < -PI ? PI2 + fixed_rad : fixed_rad; return fixed_rad; } /////////////////////////////////////////////////////////////////////// // Name: intGetRnd() // Desc: /////////////////////////////////////////////////////////////////////// int intGetRnd ( int min_val, int max_val ) { int range = max_val - min_val; int num = rand() % range; return ( num + min_val ); } /////////////////////////////////////////////////////////////////////// // Name: fGetRnd() // Desc: /////////////////////////////////////////////////////////////////////// float fGetRnd ( float min_val, float max_val ) { return ( ( max_val - min_val ) * ( float ) rand() / ( float ) RAND_MAX ) + min_val; } ///////////////////////////////////////////////////////////////////////// //// Name: GetDistance() //// Desc: Vryshta razstoqnieto m/u 2 tochki ///////////////////////////////////////////////////////////////////////// //Uint16 GetDistance( int x1, int y1, int x2, int y2 ) //{ // int dx = x2 - x1; // int dy = y2 - y1; // float product = (float)( dx*dx + dy*dy ); // // return (Uint16)sqrt( product ); //} ///////////////////////////////////////////////////////////////////////// //// Name: fGetDistance() //// Desc: Vryshta razstoqnieto m/u 2 tochki (FLOAT) ///////////////////////////////////////////////////////////////////////// //float fGetDistance( float x1, float y1, float x2, float y2 ) //{ // float dx = x2 - x1; // float dy = y2 - y1; // // return sqrt( (float)( dx*dx + dy*dy ) ); //} /////////////////////////////////////////////////////////////////////// // Name: GetDistanceNSR() // Desc: (INT) /////////////////////////////////////////////////////////////////////// Uint32 GetDistanceNSR ( int x1, int y1, int x2, int y2 ) { int dx = x2 - x1; int dy = y2 - y1; return ( Uint32 ) ( dx*dx + dy*dy ); } /////////////////////////////////////////////////////////////////////// // Name: GetDistanceNSR() // Desc: (FLOAT) /////////////////////////////////////////////////////////////////////// float fGetDistanceNSR ( float x1, float y1, float x2, float y2 ) { float dx = x2 - x1; float dy = y2 - y1; return ( dx*dx + dy*dy ); } /////////////////////////////////////////////////////////////////////// // Name: InRange() // Desc: check if value is between given range /////////////////////////////////////////////////////////////////////// bool InRange ( float val, float rangeMin, float rangeMax ) { if ( rangeMin > rangeMax ) { if ( val <= rangeMin && val >= rangeMax ) return true; } else if ( rangeMin < rangeMax ) { if ( val <= rangeMax && val >= rangeMin ) return true; } return false; } /////////////////////////////////////////////////////////////////////// // Name: fRangeGetXY() // Desc: Convert one range to another /////////////////////////////////////////////////////////////////////// float fRangeGetXY(int in, int inMin, int inMax, float min, float max) { int inRange = (inMax - inMin); float newRange = (max - min); float result = (((in - inMin) * newRange) / inRange) + min; return result; } /////////////////////////////////////////////////////////////////////// // Name: fRangeGet0255() // Desc: /////////////////////////////////////////////////////////////////////// float fRangeGet0255(int in, float min, float max) { return fRangeGetXY(in, 0, 255, min, max); } /////////////////////////////////////////////////////////////////////// // Name: fRangeGet0255() // Desc: /////////////////////////////////////////////////////////////////////// bool fIsZero(float value) { return fabsf(value) < MIN_FLOAT; } /////////////////////////////////////////////////////////////////////// // Name: GetFormattedTime() // Desc: /////////////////////////////////////////////////////////////////////// inline String GetFormattedTime() { char buf[255]; #ifdef LINUX_BUILD time_t cur_time; tm *ptm = NULL; time ( &cur_time ); ptm = localtime( &cur_time ); sprintf ( buf, "%d:%d:%d", ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); //sprintf ( buf1, "%s", ctime( &cur_time ) ); #else _strtime ( buf ); #endif _ftime ( &time_struct ); sprintf ( buf, "%s.%.3u ", buf, time_struct.millitm ); return buf; } /////////////////////////////////////////////////////////////////////// // Name: OpenLog() // Desc: open global log file /////////////////////////////////////////////////////////////////////// bool OpenLog ( const char* filename ) { String time( GetFormattedTime() ); // open debug file debug_file.open ( "debug.html", std::ios::out ); //ios::ate ); if ( ! debug_file.good() ) return false; debug_file << "<html><head><title>Savage Wheels Log File</title></head><body><h1>Savage Wheels V" << VER_MAJ << "." << VER_MIN << " - Log File</h1>"; debug_file << "<hr/><pre>"; debug_file << time << "Build: " << APP_NAME << " <br/>"; debug_file << time << "Copyright &copy; 2003-2013 KenamicK Entertainment <br />"; debug_file << time << "Opened on: " << __DATE__ << "<br />"; debug_file << time << "Opened at: " << __TIME__ << "<br />"; debug_file << time << LOG_DASH << "<br />"; return true; } /////////////////////////////////////////////////////////////////////// // Name: AppendToLog() // Desc: add a line to global log file /////////////////////////////////////////////////////////////////////// void AppendToLog ( const char *dbgstring ) { String time( GetFormattedTime() ); debug_file << time << dbgstring << "\n"; // XXX: Flushing every time is brutally slow but helps // against losing log info if game suddenly crashes ! debug_file.flush(); } ///////////////////////////////////////////////////////////////////////// //// Name: AppendToMultilog() //// Desc: dobavq nqkolko niz-a kym Log-a ///////////////////////////////////////////////////////////////////////// //void AppendToMultilog( char *dbgstring, ... ) //{ // char *strnext = dbgstring; // va_list arg_list; // char buf1[64]; // //#ifdef LINUX_BUILD // time_t cur_time; // time( &cur_time ); // sprintf( buf1, "%s", ctime( &cur_time ) ); //#else // _strtime( buf1 ); //#endif // // _ftime( &time_struct ); // sprintf( buf1, "%s.%.3u", buf1, time_struct.millitm ); // // debug_file << buf1 << " "; // // va_start( arg_list, dbgstring ); // // while ( strnext != NULL ) // { // debug_file << strnext; // strnext = va_arg( arg_list, char* ); // } // // va_end( arg_list ); // // debug_file << "\n"; // // debug_file.flush(); // //} /////////////////////////////////////////////////////////////////////// // Name: CloseLog() // Desc: close global log file /////////////////////////////////////////////////////////////////////// void CloseLog ( void ) { AppendToLog ( "Game closed." ); debug_file << "\n</pre></body></html>"; debug_file.close(); } /////////////////////////////////////////////////////////////////////// // Name: ExtractFilename() // Desc: /////////////////////////////////////////////////////////////////////// String ExtractFilename ( const String strPath ) { String strResult ( strPath ); String::size_type idx = strResult.find_last_of ( ANY_BACKSLASH ); if ( idx != String::npos ) { strResult.erase ( 0, idx + 1 ); } return strResult; } /////////////////////////////////////////////////////////////////////// // Name: PathExists() // Desc: /////////////////////////////////////////////////////////////////////// bool PathExists ( const String strPath, struct stat* _pStats /*= NULL*/ ) { //#ifndef LINUX_BUILD #if 0 if ( INVALID_FILE_ATTRIBUTES != ::GetFileAttributesA ( strPath.c_str() ) ) { return true; } else { DBG ( "Failed to find file %s! lasterror=%d", strPath.c_str(), GetLastError(), NULL ); } #else if ( _pStats ) { //pStats = _pStats; if ( -1 != stat( strPath.c_str(), _pStats ) ) return true; } else { struct stat _stats; if ( -1 != stat( strPath.c_str(), &_stats ) ) return true; } #endif return false; } <commit_msg>Edited comments<commit_after>/* Copyright (c) 2003-2010 KenamicK Entertainment 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 "Main.h" #ifdef LINUX_BUILD #include <sys/timeb.h> #include <time.h> #define _ftime ftime struct timeb time_struct; #else /* LINUX_BUILD */ struct _timeb time_struct; #endif /* LINUX_BUILD */ static std::ofstream debug_file; /////////////////////////////////////////////////////////////////////// // Name: FixAngle() // Desc: angle E{ 0, PI*2 ) (RAD) /////////////////////////////////////////////////////////////////////// void FixAngle(float *angle) { float myangle = *angle; bool bfixed = false; while ( !bfixed ) { if ( myangle > PI2 ) { myangle -= PI2; } else if ( myangle < 0.0f ) { myangle += PI2; } else { bfixed = true; } } *angle = myangle; } /////////////////////////////////////////////////////////////////////// // Name: Rad2Deg() // Desc: Keeps radians in the range of (-PI, PI) /////////////////////////////////////////////////////////////////////// float FixRad(float rad) { float fixed_rad = rad; fixed_rad = fixed_rad > PI ? fixed_rad - PI2 : fixed_rad; fixed_rad = fixed_rad < -PI ? PI2 + fixed_rad : fixed_rad; return fixed_rad; } /////////////////////////////////////////////////////////////////////// // Name: Rad2Deg() // Desc: Convert radians (-PI, PI) to degress (0, 360) /////////////////////////////////////////////////////////////////////// float Rad2Deg(float rad) { float fixed_rad = rad > 0.0f ? rad : (PI2 + rad); return fixed_rad * RAD1; } /////////////////////////////////////////////////////////////////////// // Name: Deg2Rad() // Desc: Convert degress (0, 360) to radians (-PI, PI) /////////////////////////////////////////////////////////////////////// float Deg2Rad(float deg) { deg = deg < 0.0 ? 360.0f - deg : deg; deg = deg > 360.0f ? deg - 360.0f : deg; float fixed_rad = deg * DEG1; fixed_rad = fixed_rad > PI ? fixed_rad - PI2 : fixed_rad; fixed_rad = fixed_rad < -PI ? PI2 + fixed_rad : fixed_rad; return fixed_rad; } /////////////////////////////////////////////////////////////////////// // Name: intGetRnd() // Desc: /////////////////////////////////////////////////////////////////////// int intGetRnd ( int min_val, int max_val ) { int range = max_val - min_val; int num = rand() % range; return ( num + min_val ); } /////////////////////////////////////////////////////////////////////// // Name: fGetRnd() // Desc: /////////////////////////////////////////////////////////////////////// float fGetRnd ( float min_val, float max_val ) { return ( ( max_val - min_val ) * ( float ) rand() / ( float ) RAND_MAX ) + min_val; } ///////////////////////////////////////////////////////////////////////// //// Name: GetDistance() //// Desc: (Uint) ///////////////////////////////////////////////////////////////////////// //Uint16 GetDistance( int x1, int y1, int x2, int y2 ) //{ // int dx = x2 - x1; // int dy = y2 - y1; // float product = (float)( dx*dx + dy*dy ); // // return (Uint16)sqrt( product ); //} ///////////////////////////////////////////////////////////////////////// //// Name: fGetDistance() //// Desc: (FLOAT) ///////////////////////////////////////////////////////////////////////// //float fGetDistance( float x1, float y1, float x2, float y2 ) //{ // float dx = x2 - x1; // float dy = y2 - y1; // // return sqrt( (float)( dx*dx + dy*dy ) ); //} /////////////////////////////////////////////////////////////////////// // Name: GetDistanceNSR() // Desc: Get unsquared dance (int) /////////////////////////////////////////////////////////////////////// Uint32 GetDistanceNSR ( int x1, int y1, int x2, int y2 ) { int dx = x2 - x1; int dy = y2 - y1; return (Uint32)(dx*dx + dy*dy); } /////////////////////////////////////////////////////////////////////// // Name: GetDistanceNSR() // Desc: Get unsquared dance (float) /////////////////////////////////////////////////////////////////////// float fGetDistanceNSR ( float x1, float y1, float x2, float y2 ) { float dx = x2 - x1; float dy = y2 - y1; return (dx*dx + dy*dy); } /////////////////////////////////////////////////////////////////////// // Name: InRange() // Desc: check if value is between given range /////////////////////////////////////////////////////////////////////// bool InRange ( float val, float rangeMin, float rangeMax ) { if ( rangeMin > rangeMax ) { if ( val <= rangeMin && val >= rangeMax ) return true; } else if ( rangeMin < rangeMax ) { if ( val <= rangeMax && val >= rangeMin ) return true; } return false; } /////////////////////////////////////////////////////////////////////// // Name: fRangeGetXY() // Desc: Convert one range to another /////////////////////////////////////////////////////////////////////// float fRangeGetXY(int in, int inMin, int inMax, float min, float max) { int inRange = (inMax - inMin); float newRange = (max - min); float result = (((in - inMin) * newRange) / inRange) + min; return result; } /////////////////////////////////////////////////////////////////////// // Name: fRangeGet0255() // Desc: /////////////////////////////////////////////////////////////////////// float fRangeGet0255(int in, float min, float max) { return fRangeGetXY(in, 0, 255, min, max); } /////////////////////////////////////////////////////////////////////// // Name: fRangeGet0255() // Desc: /////////////////////////////////////////////////////////////////////// bool fIsZero(float value) { return fabsf(value) < MIN_FLOAT; } /////////////////////////////////////////////////////////////////////// // Name: GetFormattedTime() // Desc: /////////////////////////////////////////////////////////////////////// inline String GetFormattedTime() { char buf[255]; #ifdef LINUX_BUILD time_t cur_time; tm *ptm = NULL; time ( &cur_time ); ptm = localtime( &cur_time ); sprintf ( buf, "%d:%d:%d", ptm->tm_hour, ptm->tm_min, ptm->tm_sec ); //sprintf ( buf1, "%s", ctime( &cur_time ) ); #else _strtime ( buf ); #endif _ftime ( &time_struct ); sprintf ( buf, "%s.%.3u ", buf, time_struct.millitm ); return buf; } /////////////////////////////////////////////////////////////////////// // Name: OpenLog() // Desc: open global log file /////////////////////////////////////////////////////////////////////// bool OpenLog ( const char* filename ) { String time( GetFormattedTime() ); // open debug file debug_file.open ( "debug.html", std::ios::out ); //ios::ate ); if ( ! debug_file.good() ) return false; debug_file << "<html><head><title>Savage Wheels Log File</title></head><body><h1>Savage Wheels V" << VER_MAJ << "." << VER_MIN << " - Log File</h1>"; debug_file << "<hr/><pre>"; debug_file << time << "Build: " << APP_NAME << " <br/>"; debug_file << time << "Copyright &copy; 2003-2013 KenamicK Entertainment <br />"; debug_file << time << "Opened on: " << __DATE__ << "<br />"; debug_file << time << "Opened at: " << __TIME__ << "<br />"; debug_file << time << LOG_DASH << "<br />"; return true; } /////////////////////////////////////////////////////////////////////// // Name: AppendToLog() // Desc: add a line to global log file /////////////////////////////////////////////////////////////////////// void AppendToLog ( const char *dbgstring ) { String time( GetFormattedTime() ); debug_file << time << dbgstring << "\n"; // XXX: Flushing every time is brutally slow but helps // against losing log info if game suddenly crashes ! debug_file.flush(); } ///////////////////////////////////////////////////////////////////////// //// Name: AppendToMultilog() //// Desc: dobavq nqkolko niz-a kym Log-a ///////////////////////////////////////////////////////////////////////// //void AppendToMultilog( char *dbgstring, ... ) //{ // char *strnext = dbgstring; // va_list arg_list; // char buf1[64]; // //#ifdef LINUX_BUILD // time_t cur_time; // time( &cur_time ); // sprintf( buf1, "%s", ctime( &cur_time ) ); //#else // _strtime( buf1 ); //#endif // // _ftime( &time_struct ); // sprintf( buf1, "%s.%.3u", buf1, time_struct.millitm ); // // debug_file << buf1 << " "; // // va_start( arg_list, dbgstring ); // // while ( strnext != NULL ) // { // debug_file << strnext; // strnext = va_arg( arg_list, char* ); // } // // va_end( arg_list ); // // debug_file << "\n"; // // debug_file.flush(); // //} /////////////////////////////////////////////////////////////////////// // Name: CloseLog() // Desc: close global log file /////////////////////////////////////////////////////////////////////// void CloseLog ( void ) { AppendToLog ( "Game closed." ); debug_file << "\n</pre></body></html>"; debug_file.close(); } /////////////////////////////////////////////////////////////////////// // Name: ExtractFilename() // Desc: /////////////////////////////////////////////////////////////////////// String ExtractFilename ( const String strPath ) { String strResult ( strPath ); String::size_type idx = strResult.find_last_of ( ANY_BACKSLASH ); if ( idx != String::npos ) { strResult.erase ( 0, idx + 1 ); } return strResult; } /////////////////////////////////////////////////////////////////////// // Name: PathExists() // Desc: /////////////////////////////////////////////////////////////////////// bool PathExists ( const String strPath, struct stat* _pStats /*= NULL*/ ) { //#ifndef LINUX_BUILD #if 0 if ( INVALID_FILE_ATTRIBUTES != ::GetFileAttributesA ( strPath.c_str() ) ) { return true; } else { DBG ( "Failed to find file %s! lasterror=%d", strPath.c_str(), GetLastError(), NULL ); } #else if ( _pStats ) { //pStats = _pStats; if ( -1 != stat( strPath.c_str(), _pStats ) ) return true; } else { struct stat _stats; if ( -1 != stat( strPath.c_str(), &_stats ) ) return true; } #endif return false; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/io_service.hpp" #include "libtorrent/socket_io.hpp" #include "libtorrent/time.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/escape_string.hpp" #include <boost/bind.hpp> namespace libtorrent { alert::alert() : m_timestamp(time_now()) {} alert::~alert() {} ptime alert::timestamp() const { return m_timestamp; } std::string torrent_alert::message() const { if (!handle.is_valid()) return " - "; if (handle.name().empty()) { char msg[41]; to_hex((char const*)&handle.info_hash()[0], 20, msg); return msg; } return handle.name(); } std::string peer_alert::message() const { error_code ec; return torrent_alert::message() + " peer (" + ip.address().to_string(ec) + ", " + identify_client(pid) + ")"; } std::string tracker_alert::message() const { return torrent_alert::message() + " (" + url + ")"; } std::string read_piece_alert::message() const { char msg[200]; snprintf(msg, sizeof(msg), "%s: piece %s %u", torrent_alert::message().c_str() , buffer ? "successful" : "failed", piece); return msg; } std::string file_completed_alert::message() const { char msg[200 + TORRENT_MAX_PATH]; snprintf(msg, sizeof(msg), "%s: file %d finished downloading" , torrent_alert::message().c_str(), index); return msg; } std::string file_renamed_alert::message() const { char msg[200 + TORRENT_MAX_PATH * 2]; snprintf(msg, sizeof(msg), "%s: file %d renamed to %s", torrent_alert::message().c_str() , index, name.c_str()); return msg; } std::string file_rename_failed_alert::message() const { char ret[200 + TORRENT_MAX_PATH * 2]; snprintf(ret, sizeof(ret), "%s: failed to rename file %d: %s" , torrent_alert::message().c_str(), index, error.message().c_str()); return ret; } std::string performance_alert::message() const { static char const* warning_str[] = { "max outstanding disk writes reached", "max outstanding piece requests reached", "upload limit too low (download rate will suffer)", "download limit too low (upload rate will suffer)", "send buffer watermark too low (upload rate will suffer)" }; return torrent_alert::message() + ": performance warning: " + warning_str[warning_code]; } std::string state_changed_alert::message() const { static char const* state_str[] = {"checking (q)", "checking", "dl metadata" , "downloading", "finished", "seeding", "allocating" , "checking (r)"}; return torrent_alert::message() + ": state changed to: " + state_str[state]; } std::string tracker_error_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s (%d) %s (%d)" , torrent_alert::message().c_str(), status_code , msg.c_str(), times_in_row); return ret; } std::string tracker_warning_alert::message() const { return tracker_alert::message() + " warning: " + msg; } std::string scrape_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s scrape reply: %u %u" , torrent_alert::message().c_str(), incomplete, complete); return ret; } std::string scrape_failed_alert::message() const { return tracker_alert::message() + " scrape failed: " + msg; } std::string tracker_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s received peers: %u" , torrent_alert::message().c_str(), num_peers); return ret; } std::string dht_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s received DHT peers: %u" , torrent_alert::message().c_str(), num_peers); return ret; } std::string tracker_announce_alert::message() const { const static char* event_str[] = {"none", "completed", "started", "stopped"}; return tracker_alert::message() + " sending announce (" + event_str[event] + ")"; } std::string hash_failed_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s hash for piece %u failed" , torrent_alert::message().c_str(), piece_index); return ret; } std::string peer_ban_alert::message() const { return peer_alert::message() + " banned peer"; } std::string peer_unsnubbed_alert::message() const { return peer_alert::message() + " peer unsnubbed"; } std::string peer_snubbed_alert::message() const { return peer_alert::message() + " peer snubbed"; } std::string invalid_request_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer sent an invalid piece request (piece: %u start: %u len: %u)" , torrent_alert::message().c_str(), request.piece, request.start, request.length); return ret; } std::string piece_finished_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s piece: %u finished downloading" , torrent_alert::message().c_str(), piece_index); return ret; } std::string request_dropped_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer dropped block ( piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_timeout_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer timed out request ( piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_finished_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s block finished downloading (piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_downloading_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s requested block (piece: %u block: %u) %s" , torrent_alert::message().c_str(), piece_index, block_index, peer_speedmsg); return ret; } std::string unwanted_block_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s received block not in download queue (piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string listen_failed_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "listening on %s failed: %s" , print_endpoint(endpoint).c_str(), error.message().c_str()); return ret; } std::string listen_succeeded_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "successfully listening on %s", print_endpoint(endpoint).c_str()); return ret; } std::string portmap_error_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; return std::string("could not map port using ") + type_str[map_type] + ": " + error.message(); } std::string portmap_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; char ret[200]; snprintf(ret, sizeof(ret), "successfully mapped port using %s. external port: %u" , type_str[map_type], external_port); return ret; } std::string portmap_log_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; char ret[200]; snprintf(ret, sizeof(ret), "%s: %s", type_str[map_type], msg.c_str()); return ret; } std::string dht_announce_alert::message() const { error_code ec; char ih_hex[41]; to_hex((const char*)&info_hash[0], 20, ih_hex); char msg[200]; snprintf(msg, sizeof(msg), "incoming dht announce: %s:%u (%s)" , ip.to_string(ec).c_str(), port, ih_hex); return msg; } std::string dht_get_peers_alert::message() const { char ih_hex[41]; to_hex((const char*)&info_hash[0], 20, ih_hex); char msg[200]; snprintf(msg, sizeof(msg), "incoming dht get_peers: %s", ih_hex); return msg; } alert_manager::alert_manager(io_service& ios) : m_alert_mask(alert::error_notification) , m_queue_size_limit(queue_size_limit_default) , m_ios(ios) {} alert_manager::~alert_manager() { while (!m_alerts.empty()) { delete m_alerts.front(); m_alerts.pop(); } } alert const* alert_manager::wait_for_alert(time_duration max_wait) { mutex::scoped_lock lock(m_mutex); if (!m_alerts.empty()) return m_alerts.front(); // system_time end = get_system_time() // + boost::posix_time::microseconds(total_microseconds(max_wait)); // apparently this call can be interrupted // prematurely if there are other signals // while (m_condition.timed_wait(lock, end)) // if (!m_alerts.empty()) return m_alerts.front(); ptime start = time_now_hires(); // TODO: change this to use an asio timer instead while (m_alerts.empty()) { lock.unlock(); sleep(50); lock.lock(); if (time_now_hires() - start >= max_wait) return 0; } return m_alerts.front(); } void alert_manager::set_dispatch_function(boost::function<void(alert const&)> const& fun) { mutex::scoped_lock lock(m_mutex); m_dispatch = fun; std::queue<alert*> alerts = m_alerts; while (!m_alerts.empty()) m_alerts.pop(); lock.unlock(); while (!alerts.empty()) { m_dispatch(*alerts.front()); delete alerts.front(); alerts.pop(); } } void dispatch_alert(boost::function<void(alert const&)> dispatcher , alert* alert_) { std::auto_ptr<alert> holder(alert_); dispatcher(*alert_); } void alert_manager::post_alert(const alert& alert_) { mutex::scoped_lock lock(m_mutex); if (m_dispatch) { TORRENT_ASSERT(m_alerts.empty()); m_ios.post(boost::bind(&dispatch_alert, m_dispatch, alert_.clone().release())); return; } if (m_alerts.size() >= m_queue_size_limit) return; m_alerts.push(alert_.clone().release()); m_condition.signal(lock); m_condition.clear(lock); } std::auto_ptr<alert> alert_manager::get() { mutex::scoped_lock lock(m_mutex); TORRENT_ASSERT(!m_alerts.empty()); alert* result = m_alerts.front(); m_alerts.pop(); return std::auto_ptr<alert>(result); } bool alert_manager::pending() const { mutex::scoped_lock lock(m_mutex); return !m_alerts.empty(); } size_t alert_manager::set_alert_queue_size_limit(size_t queue_size_limit_) { mutex::scoped_lock lock(m_mutex); std::swap(m_queue_size_limit, queue_size_limit_); return queue_size_limit_; } } // namespace libtorrent <commit_msg>extended portmap log alert message cap to 600 characters<commit_after>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/io_service.hpp" #include "libtorrent/socket_io.hpp" #include "libtorrent/time.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/escape_string.hpp" #include <boost/bind.hpp> namespace libtorrent { alert::alert() : m_timestamp(time_now()) {} alert::~alert() {} ptime alert::timestamp() const { return m_timestamp; } std::string torrent_alert::message() const { if (!handle.is_valid()) return " - "; if (handle.name().empty()) { char msg[41]; to_hex((char const*)&handle.info_hash()[0], 20, msg); return msg; } return handle.name(); } std::string peer_alert::message() const { error_code ec; return torrent_alert::message() + " peer (" + ip.address().to_string(ec) + ", " + identify_client(pid) + ")"; } std::string tracker_alert::message() const { return torrent_alert::message() + " (" + url + ")"; } std::string read_piece_alert::message() const { char msg[200]; snprintf(msg, sizeof(msg), "%s: piece %s %u", torrent_alert::message().c_str() , buffer ? "successful" : "failed", piece); return msg; } std::string file_completed_alert::message() const { char msg[200 + TORRENT_MAX_PATH]; snprintf(msg, sizeof(msg), "%s: file %d finished downloading" , torrent_alert::message().c_str(), index); return msg; } std::string file_renamed_alert::message() const { char msg[200 + TORRENT_MAX_PATH * 2]; snprintf(msg, sizeof(msg), "%s: file %d renamed to %s", torrent_alert::message().c_str() , index, name.c_str()); return msg; } std::string file_rename_failed_alert::message() const { char ret[200 + TORRENT_MAX_PATH * 2]; snprintf(ret, sizeof(ret), "%s: failed to rename file %d: %s" , torrent_alert::message().c_str(), index, error.message().c_str()); return ret; } std::string performance_alert::message() const { static char const* warning_str[] = { "max outstanding disk writes reached", "max outstanding piece requests reached", "upload limit too low (download rate will suffer)", "download limit too low (upload rate will suffer)", "send buffer watermark too low (upload rate will suffer)" }; return torrent_alert::message() + ": performance warning: " + warning_str[warning_code]; } std::string state_changed_alert::message() const { static char const* state_str[] = {"checking (q)", "checking", "dl metadata" , "downloading", "finished", "seeding", "allocating" , "checking (r)"}; return torrent_alert::message() + ": state changed to: " + state_str[state]; } std::string tracker_error_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s (%d) %s (%d)" , torrent_alert::message().c_str(), status_code , msg.c_str(), times_in_row); return ret; } std::string tracker_warning_alert::message() const { return tracker_alert::message() + " warning: " + msg; } std::string scrape_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s scrape reply: %u %u" , torrent_alert::message().c_str(), incomplete, complete); return ret; } std::string scrape_failed_alert::message() const { return tracker_alert::message() + " scrape failed: " + msg; } std::string tracker_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s received peers: %u" , torrent_alert::message().c_str(), num_peers); return ret; } std::string dht_reply_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s received DHT peers: %u" , torrent_alert::message().c_str(), num_peers); return ret; } std::string tracker_announce_alert::message() const { const static char* event_str[] = {"none", "completed", "started", "stopped"}; return tracker_alert::message() + " sending announce (" + event_str[event] + ")"; } std::string hash_failed_alert::message() const { char ret[400]; snprintf(ret, sizeof(ret), "%s hash for piece %u failed" , torrent_alert::message().c_str(), piece_index); return ret; } std::string peer_ban_alert::message() const { return peer_alert::message() + " banned peer"; } std::string peer_unsnubbed_alert::message() const { return peer_alert::message() + " peer unsnubbed"; } std::string peer_snubbed_alert::message() const { return peer_alert::message() + " peer snubbed"; } std::string invalid_request_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer sent an invalid piece request (piece: %u start: %u len: %u)" , torrent_alert::message().c_str(), request.piece, request.start, request.length); return ret; } std::string piece_finished_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s piece: %u finished downloading" , torrent_alert::message().c_str(), piece_index); return ret; } std::string request_dropped_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer dropped block ( piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_timeout_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s peer timed out request ( piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_finished_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s block finished downloading (piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string block_downloading_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s requested block (piece: %u block: %u) %s" , torrent_alert::message().c_str(), piece_index, block_index, peer_speedmsg); return ret; } std::string unwanted_block_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "%s received block not in download queue (piece: %u block: %u)" , torrent_alert::message().c_str(), piece_index, block_index); return ret; } std::string listen_failed_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "listening on %s failed: %s" , print_endpoint(endpoint).c_str(), error.message().c_str()); return ret; } std::string listen_succeeded_alert::message() const { char ret[200]; snprintf(ret, sizeof(ret), "successfully listening on %s", print_endpoint(endpoint).c_str()); return ret; } std::string portmap_error_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; return std::string("could not map port using ") + type_str[map_type] + ": " + error.message(); } std::string portmap_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; char ret[200]; snprintf(ret, sizeof(ret), "successfully mapped port using %s. external port: %u" , type_str[map_type], external_port); return ret; } std::string portmap_log_alert::message() const { static char const* type_str[] = {"NAT-PMP", "UPnP"}; char ret[600]; snprintf(ret, sizeof(ret), "%s: %s", type_str[map_type], msg.c_str()); return ret; } std::string dht_announce_alert::message() const { error_code ec; char ih_hex[41]; to_hex((const char*)&info_hash[0], 20, ih_hex); char msg[200]; snprintf(msg, sizeof(msg), "incoming dht announce: %s:%u (%s)" , ip.to_string(ec).c_str(), port, ih_hex); return msg; } std::string dht_get_peers_alert::message() const { char ih_hex[41]; to_hex((const char*)&info_hash[0], 20, ih_hex); char msg[200]; snprintf(msg, sizeof(msg), "incoming dht get_peers: %s", ih_hex); return msg; } alert_manager::alert_manager(io_service& ios) : m_alert_mask(alert::error_notification) , m_queue_size_limit(queue_size_limit_default) , m_ios(ios) {} alert_manager::~alert_manager() { while (!m_alerts.empty()) { delete m_alerts.front(); m_alerts.pop(); } } alert const* alert_manager::wait_for_alert(time_duration max_wait) { mutex::scoped_lock lock(m_mutex); if (!m_alerts.empty()) return m_alerts.front(); // system_time end = get_system_time() // + boost::posix_time::microseconds(total_microseconds(max_wait)); // apparently this call can be interrupted // prematurely if there are other signals // while (m_condition.timed_wait(lock, end)) // if (!m_alerts.empty()) return m_alerts.front(); ptime start = time_now_hires(); // TODO: change this to use an asio timer instead while (m_alerts.empty()) { lock.unlock(); sleep(50); lock.lock(); if (time_now_hires() - start >= max_wait) return 0; } return m_alerts.front(); } void alert_manager::set_dispatch_function(boost::function<void(alert const&)> const& fun) { mutex::scoped_lock lock(m_mutex); m_dispatch = fun; std::queue<alert*> alerts = m_alerts; while (!m_alerts.empty()) m_alerts.pop(); lock.unlock(); while (!alerts.empty()) { m_dispatch(*alerts.front()); delete alerts.front(); alerts.pop(); } } void dispatch_alert(boost::function<void(alert const&)> dispatcher , alert* alert_) { std::auto_ptr<alert> holder(alert_); dispatcher(*alert_); } void alert_manager::post_alert(const alert& alert_) { mutex::scoped_lock lock(m_mutex); if (m_dispatch) { TORRENT_ASSERT(m_alerts.empty()); m_ios.post(boost::bind(&dispatch_alert, m_dispatch, alert_.clone().release())); return; } if (m_alerts.size() >= m_queue_size_limit) return; m_alerts.push(alert_.clone().release()); m_condition.signal(lock); m_condition.clear(lock); } std::auto_ptr<alert> alert_manager::get() { mutex::scoped_lock lock(m_mutex); TORRENT_ASSERT(!m_alerts.empty()); alert* result = m_alerts.front(); m_alerts.pop(); return std::auto_ptr<alert>(result); } bool alert_manager::pending() const { mutex::scoped_lock lock(m_mutex); return !m_alerts.empty(); } size_t alert_manager::set_alert_queue_size_limit(size_t queue_size_limit_) { mutex::scoped_lock lock(m_mutex); std::swap(m_queue_size_limit, queue_size_limit_); return queue_size_limit_; } } // namespace libtorrent <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <cstdlib> #include <vector> #include <unistd.h> #include <stdio.h> #include <sys/unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> using namespace std; bool execute (string pass) { char* test[80]; //valid = 1; vector<string> command; string temp= ""; unsigned j = 0; unsigned i = 0; while (i < pass.size()) { for (j = i ; j < pass.size(); ++j) { if (pass.at(j) ==' ') { //this means we are moving to next word. ++j; break; } else { temp = temp + pass.at(j); } } if (temp == "exit") { cout << "exiting! (in parse)" << endl; exit(0); } command.push_back(temp); temp.clear(); //so we can start basing on where we left off in pass string i = j; } unsigned k = 0; for(; k < command.size() ;++k) { string temp_str = command.at(k); test[k] = (char*)temp_str.c_str(); } test[k] = '\0'; pid_t pid = fork(); //if pid is less than 0, then fork failed if (pid < 0) { perror("Fork failed"); exit(-1); } /*run execvp in the child because execvp automatically terminates all processes after it executes*/ if (pid == 0) //child process { //if execvp returns -1, the command did not execute if (execvp(test[0], test) == -1) { perror("exec"); command.clear(); return false; } } if (pid > 0) //parent process { if (wait(0) == -1) { perror("wait"); command.clear(); return false; } } command.clear(); return true; } void parse (vector<string> &input) { vector<string> reverse_input; //reverse the vector of inputs //so we can use pop_back (we could make a quene but we did this instead) for (int i = input.size() - 1; i >= 0; --i) { reverse_input.push_back(input.at(i)); } //check if the 1st command is exit //if it is, exit the program if (input.at(0) == "exit") { input.clear(); reverse_input.clear(); cout << "exiting (exit is only input)" << endl; exit(0); } //execute 1st command; bool valid; int size = reverse_input.size(); valid = execute(reverse_input.at(size - 1)); reverse_input.pop_back(); //parse this vector and execute accordingly for (int i = reverse_input.size() - 1; i >= 0; i = i - 2) { if (reverse_input.at(i) == ";") { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } //always execute a command that follows a semicolon execute(reverse_input.at(i - 1)); reverse_input.pop_back(); reverse_input.pop_back(); } else if (reverse_input.at(i) == "&&") { if (valid == true) //1st command executed properly { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } //execute 2nd command execute(reverse_input.at(i - 1)); } //if the 1st command is NOT valid, we do NOT want to execute the 2nd one /*whether we execute or not, we still want to pop_back() 3 times to move to the next command*/ reverse_input.pop_back(); reverse_input.pop_back(); } else if (reverse_input.at(i) == "||") { if (valid == false) //1st command did not execute { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } execute(reverse_input.at(i - 1)); } //if the 1st command is VALID, we do NOT want to execute the 2nd one /*whether we execute or not, we still want to pop_back() 3 times to move to the next command*/ reverse_input.pop_back(); reverse_input.pop_back(); } } } int main() { //loop until the user exits while (1) { //command line inputted by user char userInput[100]; //get hostname (extra credit) char hostname[80]; gethostname(hostname, sizeof hostname); //print a command prompt (e.g. $) printf("%s $ ", hostname); // cout << "$ "; //read in command as one line cin.getline(userInput, 100); char userInput_no_comments[100]; if(userInput[0] == '\0') { // //keep looping // cout <<"Keep looping" ; } else { //ignore everything after '#' (everything after '#' is a comment) for (int i = 0; userInput[i] != '\0'; ++i) { if (userInput[i] == '#') { break; } userInput_no_comments[i] = userInput[i]; userInput_no_comments[i + 1] = '\0'; } //get connectors from userInput and store it into a vector //but in this vector && and || are stored as & & and | | vector<char> vector_connectors_separated; //FIX THIS LATER IF THERE IS TIME //DOES NOT ACCOUNT FOR JUST '&', JUST '|', OR MORE THAN TWO '&'s OR '|'s //ALSO DOES NOT ACCOUNT FOR MORE THAN ONE ';' IN A ROW for (unsigned i = 0; userInput_no_comments[i] != '\0'; ++i) { if (userInput_no_comments[i] == ';'|| userInput_no_comments[i] == '&' || userInput_no_comments[i] == '|') { vector_connectors_separated.push_back(userInput[i]); } } //NOW COMBIN & and & into && and | and | into || vector<string> vector_connectors; for (unsigned i = 0; i < vector_connectors_separated.size(); ++i) { if (vector_connectors_separated.at(i) == '&') { vector_connectors.push_back("&&"); ++i; } else if (vector_connectors_separated.at(i) == '|') { vector_connectors.push_back("||"); ++i; } else if (vector_connectors_separated.at(i) == ';') { vector_connectors.push_back(";"); } } //use strtok to separate input into "tokens" char* tokens; //command and its arguments char delimiters[] = ";&&||"; tokens = strtok(userInput_no_comments, delimiters); //stores all the commands and its arguments as separate "tokens" vector<char*> vector_tokens; while (tokens != NULL) { // int position =0; // while(()) //remove first whitespace in token if (tokens[0] == ' ') { ++tokens; //go to next character (ignore 1st white space) } vector_tokens.push_back(tokens); tokens = strtok(NULL, delimiters); } //convert the tokens from char* to string vector<string> vector_tokens_str; for (unsigned i = 0; i < vector_tokens.size(); ++i) { char* s = vector_tokens.at(i); string str(s); vector_tokens_str.push_back(str); } //put everything into one vector called input vector<string> input; for (unsigned i = 0; i < vector_tokens_str.size() - 1; ++i) { input.push_back(vector_tokens_str.at(i)); input.push_back(vector_connectors.at(i)); } //add in the last command /*if we put this in the for loop above, it would go out of range, because vector_connectors is smalled than vector_tokens_str by one*/ int size = vector_tokens_str.size(); input.push_back(vector_tokens_str.at(size - 1)); //clearing everyyything vector_tokens_str.clear(); vector_connectors.clear(); vector_connectors_separated.clear(); // userInput = ""; //delete[] userInput; // userInput_no_comments(""); //run execute on commands parse(input); } } return 0; }<commit_msg>took out empty if statement for ENTER<commit_after>#include <iostream> #include <cstring> #include <cstdlib> #include <vector> #include <unistd.h> #include <stdio.h> #include <sys/unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> using namespace std; bool execute (string pass) { char* test[80]; //valid = 1; vector<string> command; string temp= ""; unsigned j = 0; unsigned i = 0; while (i < pass.size()) { for (j = i ; j < pass.size(); ++j) { if (pass.at(j) ==' ') { //this means we are moving to next word. ++j; break; } else { temp = temp + pass.at(j); } } if (temp == "exit") { cout << "exiting! (in parse)" << endl; exit(0); } command.push_back(temp); temp.clear(); //so we can start basing on where we left off in pass string i = j; } unsigned k = 0; for(; k < command.size() ;++k) { string temp_str = command.at(k); test[k] = (char*)temp_str.c_str(); } test[k] = '\0'; pid_t pid = fork(); //if pid is less than 0, then fork failed if (pid < 0) { perror("Fork failed"); exit(-1); } /*run execvp in the child because execvp automatically terminates all processes after it executes*/ if (pid == 0) //child process { //if execvp returns -1, the command did not execute if (execvp(test[0], test) == -1) { perror("exec"); command.clear(); return false; } } if (pid > 0) //parent process { if (wait(0) == -1) { perror("wait"); command.clear(); return false; } } command.clear(); return true; } void parse (vector<string> &input) { vector<string> reverse_input; //reverse the vector of inputs //so we can use pop_back (we could make a quene but we did this instead) for (int i = input.size() - 1; i >= 0; --i) { reverse_input.push_back(input.at(i)); } //check if the 1st command is exit //if it is, exit the program if (input.at(0) == "exit") { input.clear(); reverse_input.clear(); cout << "exiting (exit is only input)" << endl; exit(0); } //execute 1st command; bool valid; int size = reverse_input.size(); valid = execute(reverse_input.at(size - 1)); reverse_input.pop_back(); //parse this vector and execute accordingly for (int i = reverse_input.size() - 1; i >= 0; i = i - 2) { if (reverse_input.at(i) == ";") { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } //always execute a command that follows a semicolon execute(reverse_input.at(i - 1)); reverse_input.pop_back(); reverse_input.pop_back(); } else if (reverse_input.at(i) == "&&") { if (valid == true) //1st command executed properly { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } //execute 2nd command execute(reverse_input.at(i - 1)); } //if the 1st command is NOT valid, we do NOT want to execute the 2nd one /*whether we execute or not, we still want to pop_back() 3 times to move to the next command*/ reverse_input.pop_back(); reverse_input.pop_back(); } else if (reverse_input.at(i) == "||") { if (valid == false) //1st command did not execute { //check for exit command if (reverse_input.at(i - 1) == "exit") { execute(reverse_input.at(i - 1)); } execute(reverse_input.at(i - 1)); } //if the 1st command is VALID, we do NOT want to execute the 2nd one /*whether we execute or not, we still want to pop_back() 3 times to move to the next command*/ reverse_input.pop_back(); reverse_input.pop_back(); } } } int main() { //loop until the user exits while (1) { //command line inputted by user char userInput[100]; //get hostname (extra credit) char hostname[80]; gethostname(hostname, sizeof hostname); //print a command prompt (e.g. $) printf("%s $ ", hostname); // cout << "$ "; //read in command as one line cin.getline(userInput, 100); char userInput_no_comments[100]; // if(userInput[0] == '\0') // { // //if the user enters, nothing will happen and keeps on looping for next input. // } if(userInput[0] != '\0') { //ignore everything after '#' (everything after '#' is a comment) for (int i = 0; userInput[i] != '\0'; ++i) { if (userInput[i] == '#') { break; } userInput_no_comments[i] = userInput[i]; userInput_no_comments[i + 1] = '\0'; } //get connectors from userInput and store it into a vector //but in this vector && and || are stored as & & and | | vector<char> vector_connectors_separated; //FIX THIS LATER IF THERE IS TIME //DOES NOT ACCOUNT FOR JUST '&', JUST '|', OR MORE THAN TWO '&'s OR '|'s //ALSO DOES NOT ACCOUNT FOR MORE THAN ONE ';' IN A ROW for (unsigned i = 0; userInput_no_comments[i] != '\0'; ++i) { if (userInput_no_comments[i] == ';'|| userInput_no_comments[i] == '&' || userInput_no_comments[i] == '|') { vector_connectors_separated.push_back(userInput[i]); } } //NOW COMBIN & and & into && and | and | into || vector<string> vector_connectors; for (unsigned i = 0; i < vector_connectors_separated.size(); ++i) { if (vector_connectors_separated.at(i) == '&') { vector_connectors.push_back("&&"); ++i; } else if (vector_connectors_separated.at(i) == '|') { vector_connectors.push_back("||"); ++i; } else if (vector_connectors_separated.at(i) == ';') { vector_connectors.push_back(";"); } } //use strtok to separate input into "tokens" char* tokens; //command and its arguments char delimiters[] = ";&&||"; tokens = strtok(userInput_no_comments, delimiters); //stores all the commands and its arguments as separate "tokens" vector<char*> vector_tokens; while (tokens != NULL) { // int position =0; // while(()) //remove first whitespace in token if (tokens[0] == ' ') { ++tokens; //go to next character (ignore 1st white space) } vector_tokens.push_back(tokens); tokens = strtok(NULL, delimiters); } //convert the tokens from char* to string vector<string> vector_tokens_str; for (unsigned i = 0; i < vector_tokens.size(); ++i) { char* s = vector_tokens.at(i); string str(s); vector_tokens_str.push_back(str); } //put everything into one vector called input vector<string> input; for (unsigned i = 0; i < vector_tokens_str.size() - 1; ++i) { input.push_back(vector_tokens_str.at(i)); input.push_back(vector_connectors.at(i)); } //add in the last command /*if we put this in the for loop above, it would go out of range, because vector_connectors is smalled than vector_tokens_str by one*/ int size = vector_tokens_str.size(); input.push_back(vector_tokens_str.at(size - 1)); //clearing everyyything vector_tokens_str.clear(); vector_connectors.clear(); vector_connectors_separated.clear(); // userInput = ""; //delete[] userInput; // userInput_no_comments(""); //run execute on commands parse(input); } } return 0; }<|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <unistd.h> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include "../../cvmfs/encrypt.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/util.h" #include "testutil.h" using namespace std; // NOLINT namespace cipher { TEST(T_Encrypt, Entropy) { // Enough entropy for 100,000 256 bit keys? for (unsigned i = 0; i < 100000; ++i) { UniquePtr<Key> k(Key::CreateRandomly(32)); ASSERT_TRUE(k.IsValid()); } } TEST(T_Encrypt, KeyFiles) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string tmp_path; FILE *f = CreateTempFile("./key", 0600, "w+", &tmp_path); ASSERT_TRUE(f != NULL); fclose(f); EXPECT_FALSE(k->SaveToFile("/no/such/file")); EXPECT_TRUE(k->SaveToFile(tmp_path)); UniquePtr<Key> k_restore1(Key::CreateFromFile(tmp_path)); ASSERT_TRUE(k_restore1.IsValid()); EXPECT_EQ(k->size(), k_restore1->size()); EXPECT_EQ( 0, memcmp(k->data(), k_restore1->data(), std::min(k->size(), k_restore1->size())) ); EXPECT_EQ(0, truncate(tmp_path.c_str(), 0)); UniquePtr<Key> k_restore2(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore2.IsValid()); unlink(tmp_path.c_str()); UniquePtr<Key> k_restore3(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore3.IsValid()); } TEST(T_Encrypt, KeyStrings) { UniquePtr<Key> k_invalid_small(Key::CreateFromString("")); EXPECT_FALSE(k_invalid_small.IsValid()); UniquePtr<Key> k_invalid_big( Key::CreateFromString(string(Key::kMaxSize + 1, 'X'))); EXPECT_FALSE(k_invalid_big.IsValid()); UniquePtr<Key> k_max_size( Key::CreateFromString(string(Key::kMaxSize, 'X'))); EXPECT_TRUE(k_max_size.IsValid()); string secret = "This is a secret"; UniquePtr<Key> k(Key::CreateFromString(secret)); ASSERT_TRUE(k.IsValid()); EXPECT_EQ(k->ToBase64(), Base64(secret)); } TEST(T_Encrypt, MemoryKeyDatabase) { MemoryKeyDatabase database; UniquePtr<Key> k(Key::CreateRandomly(32)); string id; EXPECT_TRUE(database.StoreNew(k.weak_ref(), &id)); EXPECT_FALSE(database.StoreNew(k.weak_ref(), &id)); EXPECT_EQ(NULL, database.Find("not available")); const Key *found = database.Find(id); EXPECT_EQ(k.weak_ref(), found); } TEST(T_Encrypt, DecryptWrongEnvelope) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); UniquePtr<Key> k_bad(Key::CreateRandomly(1)); ASSERT_TRUE(k_bad.IsValid()); string ciphertext; string plaintext; int retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext = "X"; ciphertext[0] = 0xF0; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = 0x0F; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = cipher.algorithm() << 4; retval = Cipher::Decrypt(ciphertext, *k_bad, &plaintext); EXPECT_FALSE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); } TEST(T_Encrypt, None) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); } TEST(T_Encrypt, Aes_256_Cbc) { CipherAes256Cbc cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string ciphertext_two; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = cipher.Encrypt(dummy, *k, &ciphertext_two); EXPECT_TRUE(retval); // Initialization vector should differ EXPECT_NE(ciphertext, ciphertext_two); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1 + cipher.block_size()), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, ciphertext.length()-1), *k, &plaintext); EXPECT_EQ("", plaintext); } TEST(T_Encrypt, Aes_256_Cbc_Iv) { CipherAes256Cbc cipher; UniquePtr<cipher::Key> key(cipher::Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(key.IsValid()); // Many Iv requests in a short time should still return unique IVs shash::Md5 md5; for (unsigned i = 0; i < 100000; ++i) { shash::Md5 next_iv = cipher.GenerateIv(*key); ASSERT_NE(md5, next_iv); md5 = next_iv; } } } // namespace cipher <commit_msg>test decryption with wrong key<commit_after>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <unistd.h> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include "../../cvmfs/encrypt.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/util.h" #include "testutil.h" using namespace std; // NOLINT namespace cipher { TEST(T_Encrypt, Entropy) { // Enough entropy for 100,000 256 bit keys? for (unsigned i = 0; i < 100000; ++i) { UniquePtr<Key> k(Key::CreateRandomly(32)); ASSERT_TRUE(k.IsValid()); } } TEST(T_Encrypt, KeyFiles) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string tmp_path; FILE *f = CreateTempFile("./key", 0600, "w+", &tmp_path); ASSERT_TRUE(f != NULL); fclose(f); EXPECT_FALSE(k->SaveToFile("/no/such/file")); EXPECT_TRUE(k->SaveToFile(tmp_path)); UniquePtr<Key> k_restore1(Key::CreateFromFile(tmp_path)); ASSERT_TRUE(k_restore1.IsValid()); EXPECT_EQ(k->size(), k_restore1->size()); EXPECT_EQ( 0, memcmp(k->data(), k_restore1->data(), std::min(k->size(), k_restore1->size())) ); EXPECT_EQ(0, truncate(tmp_path.c_str(), 0)); UniquePtr<Key> k_restore2(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore2.IsValid()); unlink(tmp_path.c_str()); UniquePtr<Key> k_restore3(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore3.IsValid()); } TEST(T_Encrypt, KeyStrings) { UniquePtr<Key> k_invalid_small(Key::CreateFromString("")); EXPECT_FALSE(k_invalid_small.IsValid()); UniquePtr<Key> k_invalid_big( Key::CreateFromString(string(Key::kMaxSize + 1, 'X'))); EXPECT_FALSE(k_invalid_big.IsValid()); UniquePtr<Key> k_max_size( Key::CreateFromString(string(Key::kMaxSize, 'X'))); EXPECT_TRUE(k_max_size.IsValid()); string secret = "This is a secret"; UniquePtr<Key> k(Key::CreateFromString(secret)); ASSERT_TRUE(k.IsValid()); EXPECT_EQ(k->ToBase64(), Base64(secret)); } TEST(T_Encrypt, MemoryKeyDatabase) { MemoryKeyDatabase database; UniquePtr<Key> k(Key::CreateRandomly(32)); string id; EXPECT_TRUE(database.StoreNew(k.weak_ref(), &id)); EXPECT_FALSE(database.StoreNew(k.weak_ref(), &id)); EXPECT_EQ(NULL, database.Find("not available")); const Key *found = database.Find(id); EXPECT_EQ(k.weak_ref(), found); } TEST(T_Encrypt, DecryptWrongEnvelope) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); UniquePtr<Key> k_bad(Key::CreateRandomly(1)); ASSERT_TRUE(k_bad.IsValid()); string ciphertext; string plaintext; int retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext = "X"; ciphertext[0] = 0xF0; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = 0x0F; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = cipher.algorithm() << 4; retval = Cipher::Decrypt(ciphertext, *k_bad, &plaintext); EXPECT_FALSE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); } TEST(T_Encrypt, None) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); } TEST(T_Encrypt, Aes_256_Cbc) { CipherAes256Cbc cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string ciphertext_two; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = cipher.Encrypt(dummy, *k, &ciphertext_two); EXPECT_TRUE(retval); // Initialization vector should differ EXPECT_NE(ciphertext, ciphertext_two); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1 + cipher.block_size()), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, ciphertext.length()-1), *k, &plaintext); EXPECT_EQ("", plaintext); UniquePtr<Key> k2(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k2.IsValid()); Cipher::Decrypt(ciphertext, *k2, &plaintext); EXPECT_EQ("", plaintext); } TEST(T_Encrypt, Aes_256_Cbc_Iv) { CipherAes256Cbc cipher; UniquePtr<cipher::Key> key(cipher::Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(key.IsValid()); // Many Iv requests in a short time should still return unique IVs shash::Md5 md5; for (unsigned i = 0; i < 100000; ++i) { shash::Md5 next_iv = cipher.GenerateIv(*key); ASSERT_NE(md5, next_iv); md5 = next_iv; } } } // namespace cipher <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <vpr/vpr.h> #include <vpr/System.h> #include <vpr/Thread/Thread.h> #include <vpr/Thread/ThreadFunctor.h> #include <vpr/Thread/TSTable.h> #include <vpr/Thread/TSObject.h> #include <vpr/Thread/TSObjectProxy.h> #include <vpr/Thread/ThreadManager.h> #include <cppunit/extensions/MetricRegistry.h> #include <ThreadTest.h> namespace vprTest { static const vpr::Uint32 ThreadTest_INC_COUNT = 5000; void ThreadTest::testCreateJoin() { // Spawn off a bunch of threads (m) // Have each one increment counter n times // join all threads // Make sure counter is of valid value //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread CreateJoin: \n"<<std::flush; const int num_threads(10); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); for(int t=0;t<num_threads;t++) { functors[t] = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::incCounter); // Spawns thread here threads[t] = new vpr::Thread(functors[t]); } for(int t=0;t<num_threads;t++) { if(threads[t]->join() == false) CPPUNIT_ASSERT(false && "Thread was not able to be joined"); delete threads[t]; delete functors[t]; } CppUnit::TestAssert::assertEquals<long>((num_threads*ThreadTest_INC_COUNT), mCounter, CppUnit::SourceLine()); //CPPUNIT_ASSERT(mCounter == (num_threads*50000)); std::cout << " done\n" << std::flush; } void ThreadTest::incCounter(void* arg) { for(vpr::Uint32 i=0;i<ThreadTest_INC_COUNT;i++) { mItemProtectionMutex->acquire(); { long temp_counter = mCounter; mCounter = 0; vpr::System::msleep(20); // Sleep for 20 micro seconds mCounter = temp_counter + 1; } mItemProtectionMutex->release(); //gfx::Thread::yield(); } } void ThreadTest::counter1Func(void* arg) { for(int i=0;i<10000;i++) { vpr::System::msleep(10); // Sleep for 20 micro seconds mCounterMutex.acquire(); { long temp_counter = mCounter; mCounter = 0; vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter = temp_counter + 1; } mCounterMutex.release(); } } long ThreadTest::sampleCompare(int num) { long sampleValue1=0; long sampleValue2=0; if (num==1) { mCounterMutex.acquire(); sampleValue1=mCounter; mCounterMutex.release(); } else { mCounter1Mutex.acquire(); sampleValue1=mCounter1; mCounter1Mutex.release(); } vpr::System::msleep(500 ); if (num==1) { mCounterMutex.acquire(); sampleValue2=mCounter; mCounterMutex.release(); } else { mCounter1Mutex.acquire(); sampleValue2=mCounter1; mCounter1Mutex.release(); } std::cout<<sampleValue1<<" : "<<sampleValue2<<std::endl; return sampleValue2-sampleValue1; } void ThreadTest::testSuspendResume() { //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread SuspendResume: \n"<<std::flush; mCounter=0; // spawn an counter thread vpr::ThreadMemberFunctor<ThreadTest>* counter_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter1Func ); vpr::Thread counter_thread( counter_functor); vpr::System::msleep(100 ); CPPUNIT_ASSERT(sampleCompare(1)!=0 && "Counter doesn't work"); counter_thread.suspend(); vpr::System::msleep(100); CPPUNIT_ASSERT(sampleCompare(1)==0 && "thread can not be suspended"); counter_thread.resume(); vpr::System::msleep(100); CPPUNIT_ASSERT(sampleCompare(1)!=0 && "thread can not be resumed"); counter_thread.kill(); std::cout << " done\n" << std::flush; } void ThreadTest::counter2Func(void* arg) { for(int i=0;i<10000;i++) { vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter1Mutex.acquire(); { long temp_counter = mCounter1; mCounter = 0; vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter1 = temp_counter + 1; } mCounter1Mutex.release(); } } void ThreadTest::testPriority() { //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread Priority: \n"<<std::flush; mCounter=0; mCounter1=0; long diff1=0; long diff2=0; // spawn two counter threads vpr::ThreadMemberFunctor<ThreadTest>* counter1_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter1Func ); vpr::Thread counter1_thread( counter1_functor); vpr::System::msleep(500 ); vpr::ThreadMemberFunctor<ThreadTest>* counter2_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter2Func ); vpr::Thread counter2_thread( counter2_functor); // counter2_thread.suspend(); vpr::System::msleep(500 ); // counter2_thread.resume(); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_HIGH); counter2_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_LOW); vpr::System::msleep(100 ); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_LOW); counter2_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_HIGH); vpr::System::msleep(100 ); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.kill(); counter2_thread.kill(); } void ThreadTest::interactiveTestCPUGrind() { // Spawn off user specified number of threads // Have each grind the CPU until the user enters a value int num_threads(0); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); mStopGrindingCPU = false; // -- GET NUM THREADS -- // std::cout << "CPU grind: Enter num threads:"; std::cin >> num_threads; std::cout << "\nSpawning " << num_threads << " threads.\n"; if(num_threads == 0) return; // -- SPAWN THE THREADS -- // for(int t=0;t<num_threads;t++) { functors.push_back( new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::grindCPUWorker)); threads.push_back( new vpr::Thread(functors[t]) ); } // -- ASK FOR USER STOP -- // char answer; std::cout << "Are the CPUs grinding: (y/n)? --> "; std::cin >> answer; std::cout << std::endl; mStopGrindingCPU = true; for(int t=0;t<num_threads;t++) { if(threads[t]->join() == false) CPPUNIT_ASSERT(false && "Thread was not able to be joined"); delete threads[t]; delete functors[t]; } CPPUNIT_ASSERT((answer == 'y') || (answer == 'Y')); } // This function just grinds the CPU and waits for the flag to flip void ThreadTest::grindCPUWorker(void* arg) { double bogus_sum(0.0); double da_arg(0.1); const double inc(0.005); while(!mStopGrindingCPU) { bogus_sum += (sin(da_arg) + cos(1.0/da_arg)); da_arg += inc; } } void ThreadTest::testThreadStackSize() { // Spawn off a thread and have it consume some stack space mStackSpaceConsumed = 0; mNumRecursions = 200; const long stack_size = 64000; int arg; vpr::ThreadMemberFunctor<ThreadTest>* functor; vpr::Thread* the_thread; functor = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::recurseConsumeResources, &arg); the_thread = new vpr::Thread(functor, vpr::BaseThread::VPR_PRIORITY_NORMAL, vpr::BaseThread::VPR_LOCAL_THREAD, vpr::BaseThread::VPR_JOINABLE_THREAD, stack_size); CPPUNIT_ASSERT(the_thread != NULL); CPPUNIT_ASSERT(the_thread->join() && "Failed to join with testThreadStackSize thread"); //CPPUNIT_ASSERT(mCounter == (num_threads*50000)); } // Recurse and consume some resources // Arg is a pointer to a long void ThreadTest::recurseConsumeResources(void* arg) { // Allocate some stack variables long var1(5), var2(3), var3(7); static long total_sum; total_sum += (var1+var2+var3); CPPUNIT_ASSERT(total_sum > 0); // Just to use the vars mStackSpaceConsumed += (3 * sizeof(long)); mNumRecursions--; if(mNumRecursions > 0) recurseConsumeResources(arg); else return; } // ------------------------------------ // // ---- Thread specific data stuff ---- // // ------------------------------------ // void ThreadTest::testThreadSpecificData() { threadAssertReset(); // Spawn off a bunch of threads (m) // Have each one increment counter n times // join all threads // Make sure counter is of valid value const int num_threads(10); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); std::vector<std::string*> thread_names(num_threads); for(int t=0;t<num_threads;t++) { char buffer[256]; sprintf(buffer, "%d", t); thread_names[t] = new std::string(buffer); functors[t] = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::tsIncCounter, thread_names[t]); // Spawns thread here threads[t] = new vpr::Thread(functors[t]); } for(int t=0;t<num_threads;t++) { /* if(threads[t]->join() == false) { CPPUNIT_ASSERT(false && "Thread was not able to be joined"); } */ threads[t]->join(); delete threads[t]; delete functors[t]; delete thread_names[t]; } checkThreadAssertions(); } /** * @param arg - ptr to std::string id of thread */ void ThreadTest::tsIncCounter(void* arg) { std::string* thread_name = static_cast<std::string*>(arg); std::string test_name("TSDataOverhead"); test_name += (*thread_name); const unsigned long IncCount(100000); (*mTSCounter) = 0; try { CPPUNIT_METRIC_START_TIMING(); for(unsigned long i=0;i<IncCount;i++) { (*mTSCounter) = (*mTSCounter) + 1; // vpr::System::usleep(0); // Sleep for 20 micro seconds } assertTestThread((*mTSCounter) == IncCount); CPPUNIT_METRIC_STOP_TIMING(); CPPUNIT_ASSERT_METRIC_TIMING_LE(test_name, IncCount, 0.075f, 0.1f); // warn at 7.5%, error at 10% } catch (...) { std::cout << "F" << std::flush; } } } // End of vprTest namespace <commit_msg>Fixed some ugliness added in the last revision.<commit_after>#include <iostream> #include <vector> #include <vpr/vpr.h> #include <vpr/System.h> #include <vpr/Thread/Thread.h> #include <vpr/Thread/ThreadFunctor.h> #include <vpr/Thread/TSTable.h> #include <vpr/Thread/TSObject.h> #include <vpr/Thread/TSObjectProxy.h> #include <vpr/Thread/ThreadManager.h> #include <cppunit/extensions/MetricRegistry.h> #include <ThreadTest.h> namespace vprTest { static const vpr::Uint32 ThreadTest_INC_COUNT = 5000; void ThreadTest::testCreateJoin() { // Spawn off a bunch of threads (m) // Have each one increment counter n times // join all threads // Make sure counter is of valid value //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread CreateJoin: \n"<<std::flush; const int num_threads(10); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); for(int t=0;t<num_threads;t++) { functors[t] = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::incCounter); // Spawns thread here threads[t] = new vpr::Thread(functors[t]); } for(int t=0;t<num_threads;t++) { if(threads[t]->join() == false) CPPUNIT_ASSERT(false && "Thread was not able to be joined"); delete threads[t]; delete functors[t]; } CPPUNIT_ASSERT_EQUAL((unsigned long) num_threads * ThreadTest_INC_COUNT, (unsigned long) mCounter); //CPPUNIT_ASSERT(mCounter == (num_threads*50000)); std::cout << " done\n" << std::flush; } void ThreadTest::incCounter(void* arg) { for(vpr::Uint32 i=0;i<ThreadTest_INC_COUNT;i++) { mItemProtectionMutex->acquire(); { long temp_counter = mCounter; mCounter = 0; vpr::System::msleep(20); // Sleep for 20 micro seconds mCounter = temp_counter + 1; } mItemProtectionMutex->release(); //gfx::Thread::yield(); } } void ThreadTest::counter1Func(void* arg) { for(int i=0;i<10000;i++) { vpr::System::msleep(10); // Sleep for 20 micro seconds mCounterMutex.acquire(); { long temp_counter = mCounter; mCounter = 0; vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter = temp_counter + 1; } mCounterMutex.release(); } } long ThreadTest::sampleCompare(int num) { long sampleValue1=0; long sampleValue2=0; if (num==1) { mCounterMutex.acquire(); sampleValue1=mCounter; mCounterMutex.release(); } else { mCounter1Mutex.acquire(); sampleValue1=mCounter1; mCounter1Mutex.release(); } vpr::System::msleep(500 ); if (num==1) { mCounterMutex.acquire(); sampleValue2=mCounter; mCounterMutex.release(); } else { mCounter1Mutex.acquire(); sampleValue2=mCounter1; mCounter1Mutex.release(); } std::cout<<sampleValue1<<" : "<<sampleValue2<<std::endl; return sampleValue2-sampleValue1; } void ThreadTest::testSuspendResume() { //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread SuspendResume: \n"<<std::flush; mCounter=0; // spawn an counter thread vpr::ThreadMemberFunctor<ThreadTest>* counter_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter1Func ); vpr::Thread counter_thread( counter_functor); vpr::System::msleep(100 ); CPPUNIT_ASSERT(sampleCompare(1)!=0 && "Counter doesn't work"); counter_thread.suspend(); vpr::System::msleep(100); CPPUNIT_ASSERT(sampleCompare(1)==0 && "thread can not be suspended"); counter_thread.resume(); vpr::System::msleep(100); CPPUNIT_ASSERT(sampleCompare(1)!=0 && "thread can not be resumed"); counter_thread.kill(); std::cout << " done\n" << std::flush; } void ThreadTest::counter2Func(void* arg) { for(int i=0;i<10000;i++) { vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter1Mutex.acquire(); { long temp_counter = mCounter1; mCounter = 0; vpr::System::msleep(10); // Sleep for 20 micro seconds mCounter1 = temp_counter + 1; } mCounter1Mutex.release(); } } void ThreadTest::testPriority() { //std::cout<<"]==================================================\n"<<std::flush; //std::cout<<" Thread Priority: \n"<<std::flush; mCounter=0; mCounter1=0; long diff1=0; long diff2=0; // spawn two counter threads vpr::ThreadMemberFunctor<ThreadTest>* counter1_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter1Func ); vpr::Thread counter1_thread( counter1_functor); vpr::System::msleep(500 ); vpr::ThreadMemberFunctor<ThreadTest>* counter2_functor = new vpr::ThreadMemberFunctor<ThreadTest>( this, &ThreadTest::counter2Func ); vpr::Thread counter2_thread( counter2_functor); // counter2_thread.suspend(); vpr::System::msleep(500 ); // counter2_thread.resume(); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_HIGH); counter2_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_LOW); vpr::System::msleep(100 ); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_LOW); counter2_thread.setPrio(vpr::BaseThread::VPR_PRIORITY_HIGH); vpr::System::msleep(100 ); diff1=sampleCompare(1); diff2=sampleCompare(2); std::cout<<"diff1= "<<diff1<<" : "<<std::endl; std::cout<<"diff2= "<<diff2<<" : "<<std::endl; // CPPUNIT_ASSERT(abs(diff2-diff1)<2 && "Counters don't work correctly); counter1_thread.kill(); counter2_thread.kill(); } void ThreadTest::interactiveTestCPUGrind() { // Spawn off user specified number of threads // Have each grind the CPU until the user enters a value int num_threads(0); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); mStopGrindingCPU = false; // -- GET NUM THREADS -- // std::cout << "CPU grind: Enter num threads:"; std::cin >> num_threads; std::cout << "\nSpawning " << num_threads << " threads.\n"; if(num_threads == 0) return; // -- SPAWN THE THREADS -- // for(int t=0;t<num_threads;t++) { functors.push_back( new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::grindCPUWorker)); threads.push_back( new vpr::Thread(functors[t]) ); } // -- ASK FOR USER STOP -- // char answer; std::cout << "Are the CPUs grinding: (y/n)? --> "; std::cin >> answer; std::cout << std::endl; mStopGrindingCPU = true; for(int t=0;t<num_threads;t++) { if(threads[t]->join() == false) CPPUNIT_ASSERT(false && "Thread was not able to be joined"); delete threads[t]; delete functors[t]; } CPPUNIT_ASSERT((answer == 'y') || (answer == 'Y')); } // This function just grinds the CPU and waits for the flag to flip void ThreadTest::grindCPUWorker(void* arg) { double bogus_sum(0.0); double da_arg(0.1); const double inc(0.005); while(!mStopGrindingCPU) { bogus_sum += (sin(da_arg) + cos(1.0/da_arg)); da_arg += inc; } } void ThreadTest::testThreadStackSize() { // Spawn off a thread and have it consume some stack space mStackSpaceConsumed = 0; mNumRecursions = 200; const long stack_size = 64000; int arg; vpr::ThreadMemberFunctor<ThreadTest>* functor; vpr::Thread* the_thread; functor = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::recurseConsumeResources, &arg); the_thread = new vpr::Thread(functor, vpr::BaseThread::VPR_PRIORITY_NORMAL, vpr::BaseThread::VPR_LOCAL_THREAD, vpr::BaseThread::VPR_JOINABLE_THREAD, stack_size); CPPUNIT_ASSERT(the_thread != NULL); CPPUNIT_ASSERT(the_thread->join() && "Failed to join with testThreadStackSize thread"); //CPPUNIT_ASSERT(mCounter == (num_threads*50000)); } // Recurse and consume some resources // Arg is a pointer to a long void ThreadTest::recurseConsumeResources(void* arg) { // Allocate some stack variables long var1(5), var2(3), var3(7); static long total_sum; total_sum += (var1+var2+var3); CPPUNIT_ASSERT(total_sum > 0); // Just to use the vars mStackSpaceConsumed += (3 * sizeof(long)); mNumRecursions--; if(mNumRecursions > 0) recurseConsumeResources(arg); else return; } // ------------------------------------ // // ---- Thread specific data stuff ---- // // ------------------------------------ // void ThreadTest::testThreadSpecificData() { threadAssertReset(); // Spawn off a bunch of threads (m) // Have each one increment counter n times // join all threads // Make sure counter is of valid value const int num_threads(10); std::vector<vpr::ThreadMemberFunctor<ThreadTest>*> functors(num_threads); std::vector<vpr::Thread*> threads(num_threads); std::vector<std::string*> thread_names(num_threads); for(int t=0;t<num_threads;t++) { char buffer[256]; sprintf(buffer, "%d", t); thread_names[t] = new std::string(buffer); functors[t] = new vpr::ThreadMemberFunctor<ThreadTest>(this,&ThreadTest::tsIncCounter, thread_names[t]); // Spawns thread here threads[t] = new vpr::Thread(functors[t]); } for(int t=0;t<num_threads;t++) { /* if(threads[t]->join() == false) { CPPUNIT_ASSERT(false && "Thread was not able to be joined"); } */ threads[t]->join(); delete threads[t]; delete functors[t]; delete thread_names[t]; } checkThreadAssertions(); } /** * @param arg - ptr to std::string id of thread */ void ThreadTest::tsIncCounter(void* arg) { std::string* thread_name = static_cast<std::string*>(arg); std::string test_name("TSDataOverhead"); test_name += (*thread_name); const unsigned long IncCount(100000); (*mTSCounter) = 0; try { CPPUNIT_METRIC_START_TIMING(); for(unsigned long i=0;i<IncCount;i++) { (*mTSCounter) = (*mTSCounter) + 1; // vpr::System::usleep(0); // Sleep for 20 micro seconds } assertTestThread((*mTSCounter) == IncCount); CPPUNIT_METRIC_STOP_TIMING(); CPPUNIT_ASSERT_METRIC_TIMING_LE(test_name, IncCount, 0.075f, 0.1f); // warn at 7.5%, error at 10% } catch (...) { std::cout << "F" << std::flush; } } } // End of vprTest namespace <|endoftext|>
<commit_before>/** * \file Exception.hpp * \brief Defines custom exceptions used in framework. */ #ifndef ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #define ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #pragma once #include "Log.hpp" #include <stdexcept> namespace atlas { namespace core { /** * \class Exception * \brief Defines a custom exception. * * This class extends the exception class provided by the STD library * and links it to the existing logging system so error messages * can always be displayed. */ class Exception : public std::exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(const char* msg) : message(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(std::string const& msg) : message(msg) { } /** * Constructs the error message for the exception with the * following format: \verbatim Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } protected: std::string message; }; /** * \class RuntimeException * \brief Defines an exception for runtime errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class RuntimeException : public Exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Runtime Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Runtime Exception : " + message; CRITICAL_LOG(text); return text.c_str(); } }; /** * \class LogicException * \brief Defines an exception for logic errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class LogicException : public Exception { /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Logic Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Logic Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } }; } } #endif<commit_msg>[brief] Documents missing member for Exception class.<commit_after>/** * \file Exception.hpp * \brief Defines custom exceptions used in framework. */ #ifndef ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #define ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #pragma once #include "Log.hpp" #include <stdexcept> namespace atlas { namespace core { /** * \class Exception * \brief Defines a custom exception. * * This class extends the exception class provided by the STD library * and links it to the existing logging system so error messages * can always be displayed. */ class Exception : public std::exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(const char* msg) : message(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(std::string const& msg) : message(msg) { } /** * Constructs the error message for the exception with the * following format: \verbatim Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } protected: /** * \var message * Contains the message that is displayed whenever the exception * is thrown. */ std::string message; }; /** * \class RuntimeException * \brief Defines an exception for runtime errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class RuntimeException : public Exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Runtime Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Runtime Exception : " + message; CRITICAL_LOG(text); return text.c_str(); } }; /** * \class LogicException * \brief Defines an exception for logic errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class LogicException : public Exception { /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Logic Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Logic Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } }; } } #endif<|endoftext|>
<commit_before>#include "entitysystem.h" #include "systems/movementsystem.h" #include "systems/updatesystem.h" #include "systems/chatsystem.h" #include "systems/inventorysystem.h" #include "systems/partysystem.h" #include "systems/mapsystem.h" #include "systems/luasystem.h" #include "connection.h" #include "cmapclient.h" #include <vector> #include <set> using namespace RoseCommon; EntitySystem::EntitySystem() : systemManager_(*this) { systemManager_.add<Systems::MovementSystem>(); systemManager_.add<Systems::UpdateSystem>(); systemManager_.add<Systems::ChatSystem>(); systemManager_.add<Systems::InventorySystem>(); systemManager_.add<Systems::PartySystem>(); systemManager_.add<Systems::MapSystem>(); systemManager_.add<Systems::LuaSystem>(); } EntityManager &EntitySystem::getEntityManager() { return entityManager_; } void EntitySystem::registerEntity(Entity entity) { if (!entity) return; auto basic = entity.component<BasicInfo>(); if (!basic || basic->name_ == "" || !basic->id_) return; nameToEntity_[basic->name_] = entity; idToEntity_[basic->id_] = entity; } Entity EntitySystem::getEntity(const std::string &name) { return nameToEntity_[name]; } Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; } void EntitySystem::update(double dt) { std::lock_guard<std::mutex> lock(access_); while (toDispatch_.size()) { auto tmp = std::move(toDispatch_.front()); systemManager_.dispatch(tmp.first, *tmp.second); toDispatch_.pop(); } systemManager_.update(dt); for (auto it : toDestroy_) { if (it) { saveCharacter(it.component<CharacterInfo>()->charId_, it); auto basic = it.component<BasicInfo>(); nameToEntity_.erase(basic->name_); idToEntity_.erase(basic->id_); it.destroy(); } } toDestroy_.clear(); } void EntitySystem::destroy(Entity entity) { if (!entity) return; std::lock_guard<std::mutex> lock(access_); toDestroy_.push_back(entity); } Entity EntitySystem::create() { return entityManager_.create(); } bool EntitySystem::isNearby(Entity a, Entity b) { return true; // FIXME : actually implement the sight calculation instead of the distance if (!a || !b) return false; auto posa = a.component<Position>(); auto posb = b.component<Position>(); if (!posa || !posb) return false; // FIXME : is it a bug if there is no position? if (posa->map_ != posb->map_) return false; double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_); if (dist > NEARBY_DIST) return false; return true; } bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) { if (!entity) return false; if (systemManager_.wouldDispatch(*packet)) { std::lock_guard<std::mutex> lock(access_); toDispatch_.emplace(std::make_pair(entity, std::move(packet))); return true; } return false; } Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters; Core::InventoryTable inventoryTable; Core::SkillTable skillsTable; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters) .where(characters.id == charId)); std::lock_guard<std::mutex> lock(access_); auto entity = create(); if (static_cast<long>(charRes.front().count) != 1L) { entity.destroy(); return Entity(); } const auto &charRow = charRes.front(); entity.assign<Position>(charRow); entity.assign<BasicInfo>(charRow, id); entity.assign<Stats>(charRow); entity.assign<AdvancedInfo>(charRow); entity.assign<CharacterGraphics>(charRow); entity.assign<CharacterInfo>(charRow, platinium, charId); // TODO : write the pat initialization code auto skills = entity.assign<Skills>(); auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level) .from(skillsTable) .where(skillsTable.charId == charId)); skills->loadFromResult(skillRes); // TODO : write the hotbar table and loading code entity.assign<Hotbar>(); entity.assign<StatusEffects>(); entity.assign<RidingItems>(); entity.assign<BulletItems>(); // TODO : write the inventory code auto inventory = entity.assign<Inventory>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)) .from(inventoryTable) .where(inventoryTable.charId == charId)); inventory->loadFromResult(invRes); Systems::UpdateSystem::calculateSpeed(entity); entity.assign<Quests>(); Core::WishTable wish; auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)) .from(wish) .where(wish.charId == charId)); auto wishlist = entity.assign<Wishlist>(); wishlist->loadFromResult(wishRes); entity.assign<Lua>(); systemManager_.get<Systems::LuaSystem>()->loadScript(entity, "function onInit()\ndisplay('test')\nend"); registerEntity(entity); return entity; } void EntitySystem::saveCharacter(uint32_t charId, Entity entity) { if (!entity) return; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters; using sqlpp::parameter; auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId); entity.component<Position>()->commitToUpdate<decltype(characters)>(update); entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update); entity.component<Stats>()->commitToUpdate<decltype(characters)>(update); entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update); //entity.component<CharacterGraphics>()->commitToUpdate(update); entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update); //entity.component<Hotbar>()->commitToUpdate(update); //entity.component<StatusEffects>()->commitToUpdate(update); //entity.component<RidingItems>()->commitToUpdate(update); //entity.component<BulletItems>()->commitToUpdate(update); conn->run(update); //entity.component<Skills>()->commitToUpdate(updateSkills); Core::InventoryTable inv; auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)) .from(inv) .where(inv.charId == charId)); const auto& items = entity.component<Inventory>()->items_; std::vector<size_t> toDelete; std::vector<size_t> toUpdate; std::set<size_t> modified; std::vector<size_t> toInsert; for (const auto& row : invRes) { if (row.slot >= Inventory::maxItems) toDelete.emplace_back(row.slot); //FIXME: that should never happen else if (!items[row.slot]) toDelete.emplace_back(row.slot); else if (items[row.slot] != Item(row)) toUpdate.emplace_back(row.slot); modified.insert(row.slot); } size_t i = 0; for (const auto& item : items) { if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i); ++i; } for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it)); for (auto it : toUpdate) { auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it); items[it].commitToUpdate<decltype(inv)>(update); conn->run(update); } for (auto it : toInsert) { auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set(); items[it].commitToInsert<decltype(inv)>(insert); insert.insert_list.add(inv.slot = it); insert.insert_list.add(inv.charId = charId); conn->run(insert); } } <commit_msg>Update entitysystem.cpp<commit_after>#include "entitysystem.h" #include "systems/movementsystem.h" #include "systems/updatesystem.h" #include "systems/chatsystem.h" #include "systems/inventorysystem.h" #include "systems/partysystem.h" #include "systems/mapsystem.h" #include "systems/luasystem.h" #include "connection.h" #include "cmapclient.h" #include <vector> #include <set> using namespace RoseCommon; EntitySystem::EntitySystem() : systemManager_(*this) { systemManager_.add<Systems::MovementSystem>(); systemManager_.add<Systems::UpdateSystem>(); systemManager_.add<Systems::ChatSystem>(); systemManager_.add<Systems::InventorySystem>(); systemManager_.add<Systems::PartySystem>(); systemManager_.add<Systems::MapSystem>(); systemManager_.add<Systems::LuaSystem>(); } EntityManager &EntitySystem::getEntityManager() { return entityManager_; } void EntitySystem::registerEntity(Entity entity) { if (!entity) return; auto basic = entity.component<BasicInfo>(); if (!basic || basic->name_ == "" || !basic->id_) return; nameToEntity_[basic->name_] = entity; idToEntity_[basic->id_] = entity; } Entity EntitySystem::getEntity(const std::string &name) { return nameToEntity_[name]; } Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; } void EntitySystem::update(double dt) { std::lock_guard<std::mutex> lock(access_); while (toDispatch_.size()) { auto tmp = std::move(toDispatch_.front()); systemManager_.dispatch(tmp.first, *tmp.second); toDispatch_.pop(); } systemManager_.update(dt); for (auto it : toDestroy_) { if (it) { saveCharacter(it.component<CharacterInfo>()->charId_, it); auto basic = it.component<BasicInfo>(); nameToEntity_.erase(basic->name_); idToEntity_.erase(basic->id_); it.destroy(); } } toDestroy_.clear(); } void EntitySystem::destroy(Entity entity) { if (!entity) return; std::lock_guard<std::mutex> lock(access_); toDestroy_.push_back(entity); } Entity EntitySystem::create() { return entityManager_.create(); } bool EntitySystem::isNearby(Entity a, Entity b) { return true; // FIXME : actually implement the sight calculation instead of the distance if (!a || !b) return false; auto posa = a.component<Position>(); auto posb = b.component<Position>(); if (!posa || !posb) return false; // FIXME : is it a bug if there is no position? if (posa->map_ != posb->map_) return false; double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_); if (dist > NEARBY_DIST) return false; return true; } bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) { if (!entity) return false; if (systemManager_.wouldDispatch(*packet)) { std::lock_guard<std::mutex> lock(access_); toDispatch_.emplace(std::make_pair(entity, std::move(packet))); return true; } return false; } Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) { auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters; Core::InventoryTable inventoryTable; Core::SkillTable skillsTable; auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters)) .from(characters) .where(characters.id == charId)); std::lock_guard<std::mutex> lock(access_); auto entity = create(); if (static_cast<long>(charRes.front().count) != 1L) { entity.destroy(); return Entity(); } const auto &charRow = charRes.front(); entity.assign<Position>(charRow); entity.assign<BasicInfo>(charRow, id); entity.assign<Stats>(charRow); entity.assign<AdvancedInfo>(charRow); entity.assign<CharacterGraphics>(charRow); entity.assign<CharacterInfo>(charRow, platinium, charId); // TODO : write the pat initialization code auto skills = entity.assign<Skills>(); auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level) .from(skillsTable) .where(skillsTable.charId == charId)); skills->loadFromResult(skillRes); // TODO : write the hotbar table and loading code entity.assign<Hotbar>(); entity.assign<StatusEffects>(); entity.assign<RidingItems>(); entity.assign<BulletItems>(); // TODO : write the inventory code auto inventory = entity.assign<Inventory>(); auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable)) .from(inventoryTable) .where(inventoryTable.charId == charId)); inventory->loadFromResult(invRes); Systems::UpdateSystem::calculateSpeed(entity); entity.assign<Quests>(); Core::WishTable wish; auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)) .from(wish) .where(wish.charId == charId)); auto wishlist = entity.assign<Wishlist>(); wishlist->loadFromResult(wishRes); entity.assign<Lua<EntityAPI>>(); systemManager_.get<Systems::LuaSystem>()->loadScript(entity, "function onInit()\ndisplay('test')\nend"); registerEntity(entity); return entity; } void EntitySystem::saveCharacter(uint32_t charId, Entity entity) { if (!entity) return; auto conn = Core::connectionPool.getConnection(Core::osirose); Core::CharacterTable characters; using sqlpp::parameter; auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId); entity.component<Position>()->commitToUpdate<decltype(characters)>(update); entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update); entity.component<Stats>()->commitToUpdate<decltype(characters)>(update); entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update); //entity.component<CharacterGraphics>()->commitToUpdate(update); entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update); //entity.component<Hotbar>()->commitToUpdate(update); //entity.component<StatusEffects>()->commitToUpdate(update); //entity.component<RidingItems>()->commitToUpdate(update); //entity.component<BulletItems>()->commitToUpdate(update); conn->run(update); //entity.component<Skills>()->commitToUpdate(updateSkills); Core::InventoryTable inv; auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)) .from(inv) .where(inv.charId == charId)); const auto& items = entity.component<Inventory>()->items_; std::vector<size_t> toDelete; std::vector<size_t> toUpdate; std::set<size_t> modified; std::vector<size_t> toInsert; for (const auto& row : invRes) { if (row.slot >= Inventory::maxItems) toDelete.emplace_back(row.slot); //FIXME: that should never happen else if (!items[row.slot]) toDelete.emplace_back(row.slot); else if (items[row.slot] != Item(row)) toUpdate.emplace_back(row.slot); modified.insert(row.slot); } size_t i = 0; for (const auto& item : items) { if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i); ++i; } for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it)); for (auto it : toUpdate) { auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it); items[it].commitToUpdate<decltype(inv)>(update); conn->run(update); } for (auto it : toInsert) { auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set(); items[it].commitToInsert<decltype(inv)>(insert); insert.insert_list.add(inv.slot = it); insert.insert_list.add(inv.charId = charId); conn->run(insert); } } <|endoftext|>
<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } #if 0 // isSinglePhysicalObject - For now, the only case that we know that there is // only one memory object in the node is when there is a single global in the // node, and the only composition bit set is Global. // static bool isSinglePhysicalObject(DSNode *N) { assert(N->isComplete() && "Can only tell if this is a complete object!"); return N->isGlobalNode() && N->getGlobals().size() == 1 && !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode(); } #endif // alias - This is the only method here that does anything interesting... AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. #if 0 // This does not correctly handle arrays! // Both point to the same node and same offset, and there is only one // physical memory object represented in the node, return must alias. // // FIXME: This isn't correct because we do not handle array indexing // correctly. if (O1 == O2 && isSinglePhysicalObject(N1)) return MustAlias; // Exactly the same object & offset #endif // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || Result == NoModRef) return Result; if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return Result; } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return Result; } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); DSGraph &GG = *CallerTDGraph.getGlobalsGraph(); DSScalarMap::iterator NI = GG.getScalarMap().find(P); if (NI != GG.getScalarMap().end() && !NI->second.isNull()) { // Otherwise, if the node is only M or R, return this. This can be // useful for globals that should be marked const but are not. DSNode *N = NI->second.getNode(); if (!N->isModified()) Result = (ModRefResult)(Result & ~Mod); if (!N->isRead()) Result = (ModRefResult)(Result & ~Ref); } } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <commit_msg>remove some unsafe code that has long been dead<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || Result == NoModRef) return Result; if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return Result; } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return Result; } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); DSGraph &GG = *CallerTDGraph.getGlobalsGraph(); DSScalarMap::iterator NI = GG.getScalarMap().find(P); if (NI != GG.getScalarMap().end() && !NI->second.isNull()) { // Otherwise, if the node is only M or R, return this. This can be // useful for globals that should be marked const but are not. DSNode *N = NI->second.getNode(); if (!N->isModified()) Result = (ModRefResult)(Result & ~Mod); if (!N->isRead()) Result = (ModRefResult)(Result & ~Ref); } } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <|endoftext|>
<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } #if 0 // isSinglePhysicalObject - For now, the only case that we know that there is // only one memory object in the node is when there is a single global in the // node, and the only composition bit set is Global. // static bool isSinglePhysicalObject(DSNode *N) { assert(N->isComplete() && "Can only tell if this is a complete object!"); return N->isGlobalNode() && N->getGlobals().size() == 1 && !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode(); } #endif // alias - This is the only method here that does anything interesting... AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. #if 0 // This does not correctly handle arrays! // Both point to the same node and same offset, and there is only one // physical memory object represented in the node, return must alias. // // FIXME: This isn't correct because we do not handle array indexing // correctly. if (O1 == O2 && isSinglePhysicalObject(N1)) return MustAlias; // Exactly the same object & offset #endif // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || Result == NoModRef) return Result; if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return Result; } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return Result; } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <commit_msg>slightly improve mod/ref for DSAA by checking the globals graph for fallback<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; public: DSAA() : TD(0) {} //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); void getMustAliases(Value *P, std::vector<Value*> &RetVals); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } #if 0 // isSinglePhysicalObject - For now, the only case that we know that there is // only one memory object in the node is when there is a single global in the // node, and the only composition bit set is Global. // static bool isSinglePhysicalObject(DSNode *N) { assert(N->isComplete() && "Can only tell if this is a complete object!"); return N->isGlobalNode() && N->getGlobals().size() == 1 && !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode(); } #endif // alias - This is the only method here that does anything interesting... AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. #if 0 // This does not correctly handle arrays! // Both point to the same node and same offset, and there is only one // physical memory object represented in the node, return must alias. // // FIXME: This isn't correct because we do not handle array indexing // correctly. if (O1 == O2 && isSinglePhysicalObject(N1)) return MustAlias; // Exactly the same object & offset #endif // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size); Function *F = CS.getCalledFunction(); if (!F || Result == NoModRef) return Result; if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return Result; } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return Result; } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) Result = NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); DSGraph &GG = *CallerTDGraph.getGlobalsGraph(); DSScalarMap::iterator NI = GG.getScalarMap().find(P); if (NI != GG.getScalarMap().end() && !NI->second.isNull()) { // Otherwise, if the node is only M or R, return this. This can be // useful for globals that should be marked const but are not. DSNode *N = NI->second.getNode(); if (!N->isModified()) Result = (ModRefResult)(Result & ~Mod); if (!N->isRead()) Result = (ModRefResult)(Result & ~Ref); } } return Result; } const DSNode *N = NI->second.getNode(); assert(N && "Null pointer in scalar map??"); // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) if (I->second.getNode() == N) { if (I->first->isModified()) NeverWrites = false; if (I->first->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return Result; } if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return Result; } /// getMustAliases - If there are any pointers known that must alias this /// pointer, return them now. This allows alias-set based alias analyses to /// perform a form a value numbering (which is exposed by load-vn). If an alias /// analysis supports this, it should ADD any must aliased pointers to the /// specified vector. /// void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) { #if 0 // This does not correctly handle arrays! // Currently the only must alias information we can provide is to say that // something is equal to a global value. If we already have a global value, // don't get worked up about it. if (!isa<GlobalValue>(P)) { DSGraph *G = getGraphForValue(P); if (!G) G = &TD->getGlobalsGraph(); // The only must alias information we can currently determine occurs when // the node for P is a global node with only one entry. DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P); if (I != G->getScalarMap().end()) { DSNode *N = I->second.getNode(); if (N->isComplete() && isSinglePhysicalObject(N)) RetVals.push_back(N->getGlobals()[0]); } } #endif return AliasAnalysis::getMustAliases(P, RetVals); } <|endoftext|>
<commit_before>// Test that we do not poison the array cookie if the operator new is defined // inside the class. // RUN: %clangxx_asan %s -o %t && %run %t // // XFAIL: android // XFAIL: armv7l-unknown-linux-gnueabihf #include <new> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <assert.h> struct Foo { void *operator new(size_t s) { return Allocate(s); } void *operator new[] (size_t s) { return Allocate(s); } ~Foo(); static void *allocated; static void *Allocate(size_t s) { assert(!allocated); return allocated = ::new char[s]; } }; Foo::~Foo() {} void *Foo::allocated; Foo *getFoo(size_t n) { return new Foo[n]; } int main() { Foo *foo = getFoo(10); fprintf(stderr, "foo : %p\n", foo); fprintf(stderr, "alloc: %p\n", Foo::allocated); assert(reinterpret_cast<uintptr_t>(foo) == reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*)); *reinterpret_cast<uintptr_t*>(Foo::allocated) = 42; return 0; } <commit_msg>[asan] Disable array cookie test on ARM, enable on Android/x86.<commit_after>// Test that we do not poison the array cookie if the operator new is defined // inside the class. // RUN: %clangxx_asan %s -o %t && %run %t // // XFAIL: arm #include <new> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <assert.h> struct Foo { void *operator new(size_t s) { return Allocate(s); } void *operator new[] (size_t s) { return Allocate(s); } ~Foo(); static void *allocated; static void *Allocate(size_t s) { assert(!allocated); return allocated = ::new char[s]; } }; Foo::~Foo() {} void *Foo::allocated; Foo *getFoo(size_t n) { return new Foo[n]; } int main() { Foo *foo = getFoo(10); fprintf(stderr, "foo : %p\n", foo); fprintf(stderr, "alloc: %p\n", Foo::allocated); assert(reinterpret_cast<uintptr_t>(foo) == reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*)); *reinterpret_cast<uintptr_t*>(Foo::allocated) = 42; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2013 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. #if defined(WIN32) || defined(__linux__) #include <errno.h> #include "nacl_io/kernel_wrap.h" #include "nacl_io/kernel_wrap_real.h" // "real" functions, i.e. the unwrapped original functions. For Windows/Linux // host builds we don't wrap, so the real functions aren't accessible. In most // cases, we just fail. int _real_close(int fd) { return ENOSYS; } int _real_fstat(int fd, struct stat *buf) { return 0; } int _real_getdents(int fd, void* nacl_buf, size_t nacl_count, size_t *nread) { return ENOSYS; } int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) { return ENOSYS; } int _real_mkdir(const char* pathname, mode_t mode) { return ENOSYS; } int _real_mmap(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { return ENOSYS; } int _real_munmap(void* addr, size_t length) { return ENOSYS; } int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) { return ENOSYS; } int _real_open_resource(const char* file, int* fd) { return ENOSYS; } int _real_read(int fd, void *buf, size_t count, size_t *nread) { *nread = count; return 0; } int _real_rmdir(const char* pathname) { return ENOSYS; } int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) { int rtn = write(fd, buf, count); if (rtn < 0) return -1; *nwrote = rtn; return 0; } #endif #if defined(__linux__) void kernel_wrap_init() { } void kernel_wrap_uninit() { } #endif <commit_msg>[NaCl IO] Fix ODR violation when building under Chromium.<commit_after>// Copyright (c) 2013 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. // The Chromium build system defines __linux__ even for native client builds, // so guard against __native_client__ being defined as well. #if defined(WIN32) || (defined(__linux__) && !defined(__native_client__)) #include <errno.h> #include "nacl_io/kernel_wrap.h" #include "nacl_io/kernel_wrap_real.h" // "real" functions, i.e. the unwrapped original functions. For Windows/Linux // host builds we don't wrap, so the real functions aren't accessible. In most // cases, we just fail. int _real_close(int fd) { return ENOSYS; } int _real_fstat(int fd, struct stat *buf) { return 0; } int _real_getdents(int fd, void* nacl_buf, size_t nacl_count, size_t *nread) { return ENOSYS; } int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) { return ENOSYS; } int _real_mkdir(const char* pathname, mode_t mode) { return ENOSYS; } int _real_mmap(void** addr, size_t length, int prot, int flags, int fd, off_t offset) { return ENOSYS; } int _real_munmap(void* addr, size_t length) { return ENOSYS; } int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) { return ENOSYS; } int _real_open_resource(const char* file, int* fd) { return ENOSYS; } int _real_read(int fd, void *buf, size_t count, size_t *nread) { *nread = count; return 0; } int _real_rmdir(const char* pathname) { return ENOSYS; } int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) { int rtn = write(fd, buf, count); if (rtn < 0) return -1; *nwrote = rtn; return 0; } #endif // The Chromium build system defines __linux__ even for native client builds, // so guard against __native_client__ being defined as well. #if defined(__linux__) && !defined(__native_client__) void kernel_wrap_init() { } void kernel_wrap_uninit() { } #endif <|endoftext|>
<commit_before>//=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a CheckNSError, a flow-insenstive check // that determines if an Objective-C class interface correctly returns // a non-void return type. // // File under feature request PR 2600. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace ento; static bool IsNSError(QualType T, IdentifierInfo *II); static bool IsCFError(QualType T, IdentifierInfo *II); //===----------------------------------------------------------------------===// // NSErrorMethodChecker //===----------------------------------------------------------------------===// namespace { class NSErrorMethodChecker : public Checker< check::ASTDecl<ObjCMethodDecl> > { mutable IdentifierInfo *II; public: NSErrorMethodChecker() : II(0) { } void checkASTDecl(const ObjCMethodDecl *D, AnalysisManager &mgr, BugReporter &BR) const; }; } void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D, AnalysisManager &mgr, BugReporter &BR) const { if (!D->isThisDeclarationADefinition()) return; if (!D->getReturnType()->isVoidType()) return; if (!II) II = &D->getASTContext().Idents.get("NSError"); bool hasNSError = false; for (const auto *I : D->params()) { if (IsNSError(I->getType(), II)) { hasNSError = true; break; } } if (hasNSError) { const char *err = "Method accepting NSError** " "should have a non-void return value to indicate whether or not an " "error occurred"; PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing NSError**", "Coding conventions (Apple)", err, L); } } //===----------------------------------------------------------------------===// // CFErrorFunctionChecker //===----------------------------------------------------------------------===// namespace { class CFErrorFunctionChecker : public Checker< check::ASTDecl<FunctionDecl> > { mutable IdentifierInfo *II; public: CFErrorFunctionChecker() : II(0) { } void checkASTDecl(const FunctionDecl *D, AnalysisManager &mgr, BugReporter &BR) const; }; } void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D, AnalysisManager &mgr, BugReporter &BR) const { if (!D->doesThisDeclarationHaveABody()) return; if (!D->getReturnType()->isVoidType()) return; if (!II) II = &D->getASTContext().Idents.get("CFErrorRef"); bool hasCFError = false; for (auto I : D->params()) { if (IsCFError(I->getType(), II)) { hasCFError = true; break; } } if (hasCFError) { const char *err = "Function accepting CFErrorRef* " "should have a non-void return value to indicate whether or not an " "error occurred"; PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*", "Coding conventions (Apple)", err, L); } } //===----------------------------------------------------------------------===// // NSOrCFErrorDerefChecker //===----------------------------------------------------------------------===// namespace { class NSErrorDerefBug : public BugType { public: NSErrorDerefBug(const CheckerBase *Checker) : BugType(Checker, "NSError** null dereference", "Coding conventions (Apple)") {} }; class CFErrorDerefBug : public BugType { public: CFErrorDerefBug(const CheckerBase *Checker) : BugType(Checker, "CFErrorRef* null dereference", "Coding conventions (Apple)") {} }; } namespace { class NSOrCFErrorDerefChecker : public Checker< check::Location, check::Event<ImplicitNullDerefEvent> > { mutable IdentifierInfo *NSErrorII, *CFErrorII; public: bool ShouldCheckNSError, ShouldCheckCFError; NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0), ShouldCheckNSError(0), ShouldCheckCFError(0) { } void checkLocation(SVal loc, bool isLoad, const Stmt *S, CheckerContext &C) const; void checkEvent(ImplicitNullDerefEvent event) const; }; } typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag; REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag) REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag) template <typename T> static bool hasFlag(SVal val, ProgramStateRef state) { if (SymbolRef sym = val.getAsSymbol()) if (const unsigned *attachedFlags = state->get<T>(sym)) return *attachedFlags; return false; } template <typename T> static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) { // We tag the symbol that the SVal wraps. if (SymbolRef sym = val.getAsSymbol()) C.addTransition(state->set<T>(sym, true)); } static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) { const StackFrameContext * SFC = C.getLocationContext()->getCurrentStackFrame(); if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) { const MemRegion* R = X->getRegion(); if (const VarRegion *VR = R->getAs<VarRegion>()) if (const StackArgumentsSpaceRegion * stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace())) if (stackReg->getStackFrame() == SFC) return VR->getValueType(); } return QualType(); } void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad, const Stmt *S, CheckerContext &C) const { if (!isLoad) return; if (loc.isUndef() || !loc.getAs<Loc>()) return; ASTContext &Ctx = C.getASTContext(); ProgramStateRef state = C.getState(); // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting // SVal so that we can later check it when handling the // ImplicitNullDerefEvent event. // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of // function ? QualType parmT = parameterTypeFromSVal(loc, C); if (parmT.isNull()) return; if (!NSErrorII) NSErrorII = &Ctx.Idents.get("NSError"); if (!CFErrorII) CFErrorII = &Ctx.Idents.get("CFErrorRef"); if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) { setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C); return; } if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) { setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C); return; } } void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const { if (event.IsLoad) return; SVal loc = event.Location; ProgramStateRef state = event.SinkNode->getState(); BugReporter &BR = *event.BR; bool isNSError = hasFlag<NSErrorOut>(loc, state); bool isCFError = false; if (!isNSError) isCFError = hasFlag<CFErrorOut>(loc, state); if (!(isNSError || isCFError)) return; // Storing to possible null NSError/CFErrorRef out parameter. SmallString<128> Buf; llvm::raw_svector_ostream os(Buf); os << "Potential null dereference. According to coding standards "; os << (isNSError ? "in 'Creating and Returning NSError Objects' the parameter" : "documented in CoreFoundation/CFError.h the parameter"); os << " may be null"; BugType *bug = 0; if (isNSError) bug = new NSErrorDerefBug(this); else bug = new CFErrorDerefBug(this); BugReport *report = new BugReport(*bug, os.str(), event.SinkNode); BR.emitReport(report); } static bool IsNSError(QualType T, IdentifierInfo *II) { const PointerType* PPT = T->getAs<PointerType>(); if (!PPT) return false; const ObjCObjectPointerType* PT = PPT->getPointeeType()->getAs<ObjCObjectPointerType>(); if (!PT) return false; const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); // FIXME: Can ID ever be NULL? if (ID) return II == ID->getIdentifier(); return false; } static bool IsCFError(QualType T, IdentifierInfo *II) { const PointerType* PPT = T->getAs<PointerType>(); if (!PPT) return false; const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>(); if (!TT) return false; return TT->getDecl()->getIdentifier() == II; } void ento::registerNSErrorChecker(CheckerManager &mgr) { mgr.registerChecker<NSErrorMethodChecker>(); NSOrCFErrorDerefChecker *checker = mgr.registerChecker<NSOrCFErrorDerefChecker>(); checker->ShouldCheckNSError = true; } void ento::registerCFErrorChecker(CheckerManager &mgr) { mgr.registerChecker<CFErrorFunctionChecker>(); NSOrCFErrorDerefChecker *checker = mgr.registerChecker<NSOrCFErrorDerefChecker>(); checker->ShouldCheckCFError = true; } <commit_msg>NSOrCFErrorDerefChecker: Don't leak bug type. Similar to r208110/r208155. Found by LSan.<commit_after>//=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a CheckNSError, a flow-insenstive check // that determines if an Objective-C class interface correctly returns // a non-void return type. // // File under feature request PR 2600. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace ento; static bool IsNSError(QualType T, IdentifierInfo *II); static bool IsCFError(QualType T, IdentifierInfo *II); //===----------------------------------------------------------------------===// // NSErrorMethodChecker //===----------------------------------------------------------------------===// namespace { class NSErrorMethodChecker : public Checker< check::ASTDecl<ObjCMethodDecl> > { mutable IdentifierInfo *II; public: NSErrorMethodChecker() : II(0) { } void checkASTDecl(const ObjCMethodDecl *D, AnalysisManager &mgr, BugReporter &BR) const; }; } void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D, AnalysisManager &mgr, BugReporter &BR) const { if (!D->isThisDeclarationADefinition()) return; if (!D->getReturnType()->isVoidType()) return; if (!II) II = &D->getASTContext().Idents.get("NSError"); bool hasNSError = false; for (const auto *I : D->params()) { if (IsNSError(I->getType(), II)) { hasNSError = true; break; } } if (hasNSError) { const char *err = "Method accepting NSError** " "should have a non-void return value to indicate whether or not an " "error occurred"; PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing NSError**", "Coding conventions (Apple)", err, L); } } //===----------------------------------------------------------------------===// // CFErrorFunctionChecker //===----------------------------------------------------------------------===// namespace { class CFErrorFunctionChecker : public Checker< check::ASTDecl<FunctionDecl> > { mutable IdentifierInfo *II; public: CFErrorFunctionChecker() : II(0) { } void checkASTDecl(const FunctionDecl *D, AnalysisManager &mgr, BugReporter &BR) const; }; } void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D, AnalysisManager &mgr, BugReporter &BR) const { if (!D->doesThisDeclarationHaveABody()) return; if (!D->getReturnType()->isVoidType()) return; if (!II) II = &D->getASTContext().Idents.get("CFErrorRef"); bool hasCFError = false; for (auto I : D->params()) { if (IsCFError(I->getType(), II)) { hasCFError = true; break; } } if (hasCFError) { const char *err = "Function accepting CFErrorRef* " "should have a non-void return value to indicate whether or not an " "error occurred"; PathDiagnosticLocation L = PathDiagnosticLocation::create(D, BR.getSourceManager()); BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*", "Coding conventions (Apple)", err, L); } } //===----------------------------------------------------------------------===// // NSOrCFErrorDerefChecker //===----------------------------------------------------------------------===// namespace { class NSErrorDerefBug : public BugType { public: NSErrorDerefBug(const CheckerBase *Checker) : BugType(Checker, "NSError** null dereference", "Coding conventions (Apple)") {} }; class CFErrorDerefBug : public BugType { public: CFErrorDerefBug(const CheckerBase *Checker) : BugType(Checker, "CFErrorRef* null dereference", "Coding conventions (Apple)") {} }; } namespace { class NSOrCFErrorDerefChecker : public Checker< check::Location, check::Event<ImplicitNullDerefEvent> > { mutable IdentifierInfo *NSErrorII, *CFErrorII; mutable std::unique_ptr<NSErrorDerefBug> NSBT; mutable std::unique_ptr<CFErrorDerefBug> CFBT; public: bool ShouldCheckNSError, ShouldCheckCFError; NSOrCFErrorDerefChecker() : NSErrorII(0), CFErrorII(0), ShouldCheckNSError(0), ShouldCheckCFError(0) { } void checkLocation(SVal loc, bool isLoad, const Stmt *S, CheckerContext &C) const; void checkEvent(ImplicitNullDerefEvent event) const; }; } typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag; REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag) REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag) template <typename T> static bool hasFlag(SVal val, ProgramStateRef state) { if (SymbolRef sym = val.getAsSymbol()) if (const unsigned *attachedFlags = state->get<T>(sym)) return *attachedFlags; return false; } template <typename T> static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) { // We tag the symbol that the SVal wraps. if (SymbolRef sym = val.getAsSymbol()) C.addTransition(state->set<T>(sym, true)); } static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) { const StackFrameContext * SFC = C.getLocationContext()->getCurrentStackFrame(); if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) { const MemRegion* R = X->getRegion(); if (const VarRegion *VR = R->getAs<VarRegion>()) if (const StackArgumentsSpaceRegion * stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace())) if (stackReg->getStackFrame() == SFC) return VR->getValueType(); } return QualType(); } void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad, const Stmt *S, CheckerContext &C) const { if (!isLoad) return; if (loc.isUndef() || !loc.getAs<Loc>()) return; ASTContext &Ctx = C.getASTContext(); ProgramStateRef state = C.getState(); // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting // SVal so that we can later check it when handling the // ImplicitNullDerefEvent event. // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of // function ? QualType parmT = parameterTypeFromSVal(loc, C); if (parmT.isNull()) return; if (!NSErrorII) NSErrorII = &Ctx.Idents.get("NSError"); if (!CFErrorII) CFErrorII = &Ctx.Idents.get("CFErrorRef"); if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) { setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C); return; } if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) { setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C); return; } } void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const { if (event.IsLoad) return; SVal loc = event.Location; ProgramStateRef state = event.SinkNode->getState(); BugReporter &BR = *event.BR; bool isNSError = hasFlag<NSErrorOut>(loc, state); bool isCFError = false; if (!isNSError) isCFError = hasFlag<CFErrorOut>(loc, state); if (!(isNSError || isCFError)) return; // Storing to possible null NSError/CFErrorRef out parameter. SmallString<128> Buf; llvm::raw_svector_ostream os(Buf); os << "Potential null dereference. According to coding standards "; os << (isNSError ? "in 'Creating and Returning NSError Objects' the parameter" : "documented in CoreFoundation/CFError.h the parameter"); os << " may be null"; BugType *bug = 0; if (isNSError) { if (!NSBT) NSBT.reset(new NSErrorDerefBug(this)); bug = NSBT.get(); } else { if (!CFBT) CFBT.reset(new CFErrorDerefBug(this)); bug = CFBT.get(); } BugReport *report = new BugReport(*bug, os.str(), event.SinkNode); BR.emitReport(report); } static bool IsNSError(QualType T, IdentifierInfo *II) { const PointerType* PPT = T->getAs<PointerType>(); if (!PPT) return false; const ObjCObjectPointerType* PT = PPT->getPointeeType()->getAs<ObjCObjectPointerType>(); if (!PT) return false; const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); // FIXME: Can ID ever be NULL? if (ID) return II == ID->getIdentifier(); return false; } static bool IsCFError(QualType T, IdentifierInfo *II) { const PointerType* PPT = T->getAs<PointerType>(); if (!PPT) return false; const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>(); if (!TT) return false; return TT->getDecl()->getIdentifier() == II; } void ento::registerNSErrorChecker(CheckerManager &mgr) { mgr.registerChecker<NSErrorMethodChecker>(); NSOrCFErrorDerefChecker *checker = mgr.registerChecker<NSOrCFErrorDerefChecker>(); checker->ShouldCheckNSError = true; } void ento::registerCFErrorChecker(CheckerManager &mgr) { mgr.registerChecker<CFErrorFunctionChecker>(); NSOrCFErrorDerefChecker *checker = mgr.registerChecker<NSOrCFErrorDerefChecker>(); checker->ShouldCheckCFError = true; } <|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> int main( int argc, char** argv ){ using namespace cv; if(argc != 2){ std::cerr << "usage: ./blurs <filename>" << std::endl; return -1; } namedWindow("Original", CV_WINDOW_KEEPRATIO); namedWindow("Blur", CV_WINDOW_KEEPRATIO); Mat imgOriginal, imgBlur; imgOriginal = imread(argv[1]); if(!imgOriginal.data){ std::cerr << "could not read img!" << std::endl; return -1; } //TODO return 0; } <commit_msg>finished blur example<commit_after>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> int main( int argc, char** argv ){ using namespace cv; if(argc != 2){ std::cerr << "usage: ./blurs <filename>" << std::endl; return -1; } namedWindow("Original", CV_WINDOW_KEEPRATIO); namedWindow("Gauss", CV_WINDOW_KEEPRATIO); namedWindow("Median", CV_WINDOW_KEEPRATIO); namedWindow("Bilateral", CV_WINDOW_KEEPRATIO); Mat imgOriginal, imgGauss, imgMedian, imgBilateral; imgOriginal = imread(argv[1]); if(!imgOriginal.data){ std::cerr << "could not read img!" << std::endl; return -1; } Size ksize(11, 11); cv::GaussianBlur(imgOriginal, imgGauss, ksize, 0); cv::medianBlur(imgOriginal, imgMedian, 11); double sigmaColor = 10, simgaSpace = 10; cv::bilateralFilter(imgOriginal, imgBilateral, 10, sigmaColor, simgaSpace, 0); imshow("Original", imgOriginal); imshow("Gauss", imgGauss); imshow("Median", imgMedian); imshow("Bilateral", imgBilateral); while(waitKey(0) != 27){}; //wait until ESC is hit return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMaximumProjectionImageFilterTest3.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. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCommand.h" #include "itkSimpleFilterWatcher.h" #include "itkMaximumProjectionImageFilter.h" #include "itkExtractImageFilter.h" int itkMaximumProjectionImageFilterTest3(int argc, char * argv[]) { if( argc < 4 ) { std::cerr << "Missing parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << "Dimension Inputimage Outputimage " << std::endl; return EXIT_FAILURE; } int dim = atoi(argv[1]); typedef unsigned char PType; typedef itk::Image< PType, 3 > IType; typedef itk::Image< PType, 2 > IType2; typedef itk::ImageFileReader< IType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); typedef itk::MaximumProjectionImageFilter< IType, IType2 > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( reader->GetOutput() ); filter->SetProjectionDimension( dim ); // to be sure that the result is ok with several threads, even on a single // proc computer filter->SetNumberOfThreads( 2 ); // itk::SimpleFilterWatcher watcher(filter, "filter"); typedef itk::ImageFileWriter< IType2 > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[3] ); try { writer->Update(); } catch ( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>STYLE: Fixing style violations, and making more explicit typedefs.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMaximumProjectionImageFilterTest3.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. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCommand.h" #include "itkSimpleFilterWatcher.h" #include "itkMaximumProjectionImageFilter.h" #include "itkExtractImageFilter.h" int itkMaximumProjectionImageFilterTest3(int argc, char * argv[]) { if( argc < 4 ) { std::cerr << "Missing parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << "Dimension Inputimage Outputimage " << std::endl; return EXIT_FAILURE; } int dim = atoi(argv[1]); typedef unsigned char PixelType; typedef itk::Image< PixelType, 3 > ImageType; typedef itk::Image< PixelType, 2 > Image2DType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); typedef itk::MaximumProjectionImageFilter< ImageType, Image2DType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( reader->GetOutput() ); filter->SetProjectionDimension( dim ); // to be sure that the result is ok with several threads, even on a single // proc computer filter->SetNumberOfThreads( 2 ); itk::SimpleFilterWatcher watcher(filter, "filter"); typedef itk::ImageFileWriter< Image2DType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[3] ); try { writer->Update(); } catch ( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "stdio.h" #include "unistd.h" #include "sys/time.h" #include "mpi.h" #include "master.h" #include "failure.h" #include "protocol.h" #include "log.h" #include "tools.h" Master::Master(const std::string &program, Engine &engine, DAG &dag, const std::string &dagfile, const std::string &outfile, const std::string &errfile) { this->program = program; this->dagfile = dagfile; this->outfile = dagfile + "." + outfile; this->errfile = dagfile + "." + errfile; this->engine = &engine; this->dag = &dag; total_count = 0; success_count = 0; failed_count = 0; } Master::~Master() { } void Master::submit_task(Task *task, int worker) { int rc; log_debug("Submitting task %s to worker %d", task->name.c_str(), worker); rc = send_request(task->name, task->command, task->extra_id, worker); if (rc != 0 ) { myfailure("Sending task failed"); } this->total_count++; } void Master::wait_for_result() { log_trace("Waiting for task to finish"); std::string name; int exitcode; double start_time; double end_time; int worker; recv_response(name, start_time, end_time, exitcode, worker); // Mark worker idle log_trace("Worker %d is idle", worker); this->mark_worker_idle(worker); // Mark task finished if (exitcode == 0) { log_debug("Task %s finished with exitcode %d", name.c_str(), exitcode); this->success_count++; } else { log_error("Task %s failed with exitcode %d", name.c_str(), exitcode); this->failed_count++; } Task *t = this->dag->get_task(name); this->engine->mark_task_finished(t, exitcode); } void Master::add_worker(int worker) { this->mark_worker_idle(worker); } bool Master::has_idle_worker() { return !this->idle.empty(); } int Master::next_idle_worker() { if (!this->has_idle_worker()) { myfailure("No idle workers"); } int worker = this->idle.front(); this->idle.pop(); return worker; } void Master::mark_worker_idle(int worker) { this->idle.push(worker); } void Master::merge_task_stdio(FILE *dest, const std::string &srcfile, const std::string &stream) { log_trace("Merging %s file: %s", stream.c_str(), srcfile.c_str()); FILE *src = fopen(srcfile.c_str(), "r"); if (src == NULL) { // The file may not exist if the worker didn't run any tasks, just print a warning if (errno == ENOENT) { log_warn("No %s file: %s", stream.c_str(), srcfile.c_str()); return; } else { myfailures("Unable to open task %s file: %s", stream.c_str(), srcfile.c_str()); } } char buf[BUFSIZ]; while (1) { int r = fread(buf, 1, BUFSIZ, src); if (r < 0) { myfailures("Error reading source file: %s", srcfile.c_str()); } if (r == 0) { break; } int w = fwrite(buf, 1, r, dest); if (w < r) { myfailures("Error writing to dest file"); } } fclose(src); if (unlink(srcfile.c_str())) { myfailures("Unable to delete task %s file: %s", stream.c_str(), srcfile.c_str()); } } int Master::run() { // Start time of workflow struct timeval start; gettimeofday(&start, NULL); int numprocs; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); int numworkers = numprocs - 1; if (numworkers == 0) { myfailure("Need at least 1 worker"); } log_info("Master starting with %d workers", numworkers); // First, send out the paths to the outfile/errfile send_stdio_paths(this->outfile, this->errfile); // Queue up the workers for (int i=1; i<=numworkers; i++) { this->add_worker(i); } // While DAG has tasks to run while (!this->engine->is_finished()) { // Submit as many tasks as we can while (this->engine->has_ready_task() && this->has_idle_worker()) { int worker = this->next_idle_worker(); Task *task = this->engine->next_ready_task(); this->submit_task(task, worker); } if (!this->engine->has_ready_task()) { log_debug("No ready tasks"); } if (!this->has_idle_worker()) { log_debug("No idle workers"); } this->wait_for_result(); } log_info("Workflow finished"); // Finish time of workflow struct timeval finish; gettimeofday(&finish, NULL); // Tell workers to exit // TODO Change this to MPI_Bcast log_trace("Sending workers shutdown messages"); for (int i=1; i<=numworkers; i++) { send_shutdown(i); } log_trace("Waiting for workers to finish"); double total_runtime = collect_total_runtimes(); log_info("Total runtime of tasks: %f", total_runtime); double stime = start.tv_sec + (start.tv_usec/1000000.0); double ftime = finish.tv_sec + (finish.tv_usec/1000000.0); double walltime = ftime - stime; log_info("Wall time: %lf seconds", walltime); // Compute resource utilization if (total_runtime > 0) { double master_util = total_runtime / (walltime * numprocs); double worker_util = total_runtime / (walltime * numworkers); log_info("Resource utilization (with master): %lf", master_util); log_info("Resource utilization (without master): %lf", worker_util); } // Merge stdout/stderr from all tasks log_trace("Merging stdio from workers"); FILE *outf = stdout; if (outfile != "stdout") { fopen(this->outfile.c_str(), "w"); if (outf == NULL) { myfailures("Unable to open stdout file: %s\n", this->outfile.c_str()); } } FILE *errf = stderr; if (errfile != "stderr") { fopen(this->errfile.c_str(), "w"); if (errf == NULL) { myfailures("Unable to open stderr file: %s\n", this->outfile.c_str()); } } // Collect all stdout/stderr char dotrank[25]; for (int i=1; i<=numworkers; i++) { sprintf(dotrank, ".%d", i); std::string toutfile = this->outfile; toutfile += dotrank; this->merge_task_stdio(outf, toutfile, "stdout"); std::string terrfile = this->errfile; terrfile += dotrank; this->merge_task_stdio(errf, terrfile, "stderr"); } // pegasus cluster output - used for provenance char buf[BUFSIZ]; char stat[10]; char date[32]; if (this->engine->is_failed()) { strcpy(stat, "failed"); } else { strcpy(stat, "ok"); } iso2date(stime, date, sizeof(date)); sprintf(buf, "[cluster-summary stat=\"%s\" tasks=%ld, succeeded=%ld, failed=%ld, extra=%d," " start=\"%s\", duration=%.3f, pid=%d, app=\"%s\"]\n", stat, this->total_count, this->success_count, this->failed_count, 0, date, walltime * numprocs, /* duration is for all cores */ getpid(), this->program.c_str()); fwrite(buf, 1, strlen(buf), outf); if (errfile != "stderr") { fclose(errf); } if (outfile != "stdout") { fclose(outf); } if (this->engine->max_failures_reached()) { log_error("Max myfailures reached: DAG prematurely aborted"); } if (this->engine->is_failed()) { log_error("Workflow failed"); return 1; } else { log_info("Workflow suceeded"); return 0; } } <commit_msg>Fix outfile and errfile bug<commit_after>#include "stdio.h" #include "unistd.h" #include "sys/time.h" #include "mpi.h" #include "master.h" #include "failure.h" #include "protocol.h" #include "log.h" #include "tools.h" Master::Master(const std::string &program, Engine &engine, DAG &dag, const std::string &dagfile, const std::string &outfile, const std::string &errfile) { this->program = program; this->dagfile = dagfile; this->outfile = outfile; this->errfile = errfile; this->engine = &engine; this->dag = &dag; total_count = 0; success_count = 0; failed_count = 0; } Master::~Master() { } void Master::submit_task(Task *task, int worker) { int rc; log_debug("Submitting task %s to worker %d", task->name.c_str(), worker); rc = send_request(task->name, task->command, task->extra_id, worker); if (rc != 0 ) { myfailure("Sending task failed"); } this->total_count++; } void Master::wait_for_result() { log_trace("Waiting for task to finish"); std::string name; int exitcode; double start_time; double end_time; int worker; recv_response(name, start_time, end_time, exitcode, worker); // Mark worker idle log_trace("Worker %d is idle", worker); this->mark_worker_idle(worker); // Mark task finished if (exitcode == 0) { log_debug("Task %s finished with exitcode %d", name.c_str(), exitcode); this->success_count++; } else { log_error("Task %s failed with exitcode %d", name.c_str(), exitcode); this->failed_count++; } Task *t = this->dag->get_task(name); this->engine->mark_task_finished(t, exitcode); } void Master::add_worker(int worker) { this->mark_worker_idle(worker); } bool Master::has_idle_worker() { return !this->idle.empty(); } int Master::next_idle_worker() { if (!this->has_idle_worker()) { myfailure("No idle workers"); } int worker = this->idle.front(); this->idle.pop(); return worker; } void Master::mark_worker_idle(int worker) { this->idle.push(worker); } void Master::merge_task_stdio(FILE *dest, const std::string &srcfile, const std::string &stream) { log_trace("Merging %s file: %s", stream.c_str(), srcfile.c_str()); FILE *src = fopen(srcfile.c_str(), "r"); if (src == NULL) { // The file may not exist if the worker didn't run any tasks, just print a warning if (errno == ENOENT) { log_warn("No %s file: %s", stream.c_str(), srcfile.c_str()); return; } else { myfailures("Unable to open task %s file: %s", stream.c_str(), srcfile.c_str()); } } char buf[BUFSIZ]; while (1) { int r = fread(buf, 1, BUFSIZ, src); if (r < 0) { myfailures("Error reading source file: %s", srcfile.c_str()); } if (r == 0) { break; } int w = fwrite(buf, 1, r, dest); if (w < r) { myfailures("Error writing to dest file"); } } fclose(src); if (unlink(srcfile.c_str())) { myfailures("Unable to delete task %s file: %s", stream.c_str(), srcfile.c_str()); } } int Master::run() { // Start time of workflow struct timeval start; gettimeofday(&start, NULL); int numprocs; MPI_Comm_size(MPI_COMM_WORLD, &numprocs); int numworkers = numprocs - 1; if (numworkers == 0) { myfailure("Need at least 1 worker"); } log_info("Master starting with %d workers", numworkers); // First, send out the paths to the outfile/errfile send_stdio_paths(this->outfile, this->errfile); // Queue up the workers for (int i=1; i<=numworkers; i++) { this->add_worker(i); } // While DAG has tasks to run while (!this->engine->is_finished()) { // Submit as many tasks as we can while (this->engine->has_ready_task() && this->has_idle_worker()) { int worker = this->next_idle_worker(); Task *task = this->engine->next_ready_task(); this->submit_task(task, worker); } if (!this->engine->has_ready_task()) { log_debug("No ready tasks"); } if (!this->has_idle_worker()) { log_debug("No idle workers"); } this->wait_for_result(); } log_info("Workflow finished"); // Finish time of workflow struct timeval finish; gettimeofday(&finish, NULL); // Tell workers to exit // TODO Change this to MPI_Bcast log_trace("Sending workers shutdown messages"); for (int i=1; i<=numworkers; i++) { send_shutdown(i); } log_trace("Waiting for workers to finish"); double total_runtime = collect_total_runtimes(); log_info("Total runtime of tasks: %f", total_runtime); double stime = start.tv_sec + (start.tv_usec/1000000.0); double ftime = finish.tv_sec + (finish.tv_usec/1000000.0); double walltime = ftime - stime; log_info("Wall time: %lf seconds", walltime); // Compute resource utilization if (total_runtime > 0) { double master_util = total_runtime / (walltime * numprocs); double worker_util = total_runtime / (walltime * numworkers); log_info("Resource utilization (with master): %lf", master_util); log_info("Resource utilization (without master): %lf", worker_util); } // Merge stdout/stderr from all tasks log_trace("Merging stdio from workers"); FILE *outf = stdout; if (outfile != "stdout") { outf = fopen(this->outfile.c_str(), "w"); if (outf == NULL) { myfailures("Unable to open stdout file: %s\n", this->outfile.c_str()); } } FILE *errf = stderr; if (errfile != "stderr") { errf = fopen(this->errfile.c_str(), "w"); if (errf == NULL) { myfailures("Unable to open stderr file: %s\n", this->outfile.c_str()); } } // Collect all stdout/stderr char dotrank[25]; for (int i=1; i<=numworkers; i++) { sprintf(dotrank, ".%d", i); std::string toutfile = this->outfile; toutfile += dotrank; this->merge_task_stdio(outf, toutfile, "stdout"); std::string terrfile = this->errfile; terrfile += dotrank; this->merge_task_stdio(errf, terrfile, "stderr"); } // pegasus cluster output - used for provenance char buf[BUFSIZ]; char stat[10]; char date[32]; if (this->engine->is_failed()) { strcpy(stat, "failed"); } else { strcpy(stat, "ok"); } iso2date(stime, date, sizeof(date)); sprintf(buf, "[cluster-summary stat=\"%s\" tasks=%ld, succeeded=%ld, failed=%ld, extra=%d," " start=\"%s\", duration=%.3f, pid=%d, app=\"%s\"]\n", stat, this->total_count, this->success_count, this->failed_count, 0, date, walltime * numprocs, /* duration is for all cores */ getpid(), this->program.c_str()); fwrite(buf, 1, strlen(buf), outf); if (errfile != "stderr") { fclose(errf); } if (outfile != "stdout") { fclose(outf); } if (this->engine->max_failures_reached()) { log_error("Max failures reached: DAG prematurely aborted"); } if (this->engine->is_failed()) { log_error("Workflow failed"); return 1; } else { log_info("Workflow suceeded"); return 0; } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !std::isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && std::isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !std::isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && std::isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <commit_msg>replaced dependency on locale dependent isspace<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> #include <cstring> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; inline bool isspace(char c) { const static char* ws = " \t\n\r\f\v"; return std::strchr(ws, c); } // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <|endoftext|>
<commit_before>#include "Class/DlOpen.hpp" #include "Class/Parsed.hpp" #include "ClassResolver.hpp" #include <iostream> static int _result = 0; extern "C" void ZN4java4lang6System4exitEi(int code) { std::cerr << "java/lang/System.exit(I)V called with code: " << code << std::endl; _result = code; } int main(int argc, char ** argv) { if (argc != 2) { std::cerr << "Test must be called with the path to the test class" << std::endl; return 1; } auto classdb = Espresso::VM::ClassResolver(); classdb.addClass(new Espresso::VM::Class::DlOpen("java/lang/Object")); classdb.addClass(new Espresso::VM::Class::DlOpen("java/lang/System")); auto cls = Espresso::ClassParser::Class(argv[1]); classdb.addClass(new Espresso::VM::Class::Parsed(cls)); // Remaining Tasks: // 1. Pass CR to VM // 2. Ask VM to init "argv[1]" // 3. ... // 4. Profit! if (_result != 99) { std::cerr << "java/lang/System.exit(I)V was not properly called" << std::endl; return 99; } return 0; } <commit_msg>evolving Milestone 1 test<commit_after>#include "Class/DlOpen.hpp" #include "Class/Parsed.hpp" #include "ClassResolver.hpp" #include <iostream> static int _result = 0; extern "C" void ZN4java4lang6System4exitEi(int code) { std::cerr << "java/lang/System.exit(I)V called with code: " << code << std::endl; _result = code; } int main(int argc, char ** argv) { if (argc != 2) { std::cerr << "Test must be called with the path to the test class" << std::endl; return 1; } auto classdb = Espresso::VM::ClassResolver(); classdb.addClass(new Espresso::VM::Class::DlOpen("java/lang/Object")); classdb.addClass(new Espresso::VM::Class::DlOpen("java/lang/System")); auto cls = Espresso::ClassParser::Class(argv[1]); if (!cls) { std::cerr << argv[1] << " wasn't loaded: " << cls.error() << std::endl; return 1; } auto pcls = new Espresso::VM::Class::Parsed(cls); classdb.addClass(pcls); void (*fn)() = (void (*)())pcls->findMethod("<clinit>", "()V"); if (!fn) { std::cerr << argv[1] << " does not contain <clinit>()V" << std::endl; return 1; } fn(); if (_result != 99) { std::cerr << "java/lang/System.exit(I)V was not properly called" << std::endl; return 99; } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QCoreApplication> #include <qllcpsocket.h> #include <qnearfieldmanager.h> #include <qnearfieldtarget.h> #include "qnfctestcommon.h" #include "qnfctestutil.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QNearFieldTarget*) Q_DECLARE_METATYPE(QLlcpSocket::Error) Q_DECLARE_METATYPE(QLlcpSocket::State) class tst_qllcpsocketlocal : public QObject { Q_OBJECT public: tst_qllcpsocketlocal(); private Q_SLOTS: // ALERT: Handshake required, do NOT change the sequence of handshaking testcases. void testCase0(); // Intial handshake - work with tst_qllcpsocketremote testCase0 void testCase1(); // handshake 1,2 - work with tst_qllcpsocketremote testCase1 void testCase2(); // handshake 3 - work with tst_qllcpsocketremote testCase2 void testCase3(); void coverageTest1(); void negTestCase1(); void negTestCase2(); //void negTestCase3(); //void negTestCase4(); void cleanupTest(); private: QNearFieldManager *m_nfcManager; //own QNearFieldTarget *m_target; // not own quint8 m_port; QLlcpSocket *m_socket; }; tst_qllcpsocketlocal::tst_qllcpsocketlocal() { qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error"); qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::State"); } /*! Description: Init test case for NFC LLCP connection-less mode socket - local peer TestScenario: Touch a NFC device with LLCP connection-less service actived TestExpectedResults: Signal of target detected has been found. */ void tst_qllcpsocketlocal::testCase0() { m_nfcManager = new QNearFieldManager; QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget); QString message("Local Wait touch"); QNfcTestUtil::ShowMessage(message); QTRY_VERIFY(!targetDetectedSpy.isEmpty()); m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>(); QVERIFY(m_target!=NULL); QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess); m_port = 35; m_socket = new QLlcpSocket; } /*! Description: Send the message and Receive the acknowledged identical message TestScenario: 1. Local peer temps to read datagram without bind 2. Local peer binds to the remote peer 3. Local peer sends the "testcase1 string" message to the remote peer 4. Local peer receives the above message sending from the remote peer TestExpectedResults: 1. Local peer fails to read datagram without bind 2. Local peer binds to local port successfully. 3. The message has be sent to remote peer. 4. The message has been received from remote peer. */ void tst_qllcpsocketlocal::testCase1() { QString message("testcase1 string"); //QLlcpSocket socket(this); // STEP 1. readDatagram must be called before bind QByteArray tmpForReadArray; tmpForReadArray.resize(127); qint64 ret = m_socket->readDatagram(tmpForReadArray.data(), tmpForReadArray.size()); QVERIFY(ret == -1); QCOMPARE(m_socket->state(), QLlcpSocket::UnconnectedState); QSignalSpy stateChangedSpy(m_socket, SIGNAL(stateChanged(QLlcpSocket::State))); // STEP 2: bind the local port for current socket QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead())); bool retBool = m_socket->bind(m_port); QVERIFY(retBool); QVERIFY(!stateChangedSpy.isEmpty()); QCOMPARE(m_socket->state(), QLlcpSocket::BoundState); QString messageBox("handshake 1"); QNfcTestUtil::ShowMessage(messageBox); // STEP 3: Local peer sends the message to the remote peer QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error))); QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64))); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); m_socket->writeDatagram(data,strSize,m_target, m_port); QTRY_VERIFY(bytesWrittenSpy.count() == 1); QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal qint64 writtenSize = arguments.at(0).value<qint64>(); QCOMPARE(writtenSize, strSize); QString messageBox2("handshake 2"); QNfcTestUtil::ShowMessage(messageBox2); // STEP 4: Receive data from remote peer QTRY_VERIFY(!readyReadSpy.isEmpty()); QByteArray datagram; while (m_socket->hasPendingDatagrams()) { datagram.resize(m_socket->pendingDatagramSize()); quint8 remotePort = 0; qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size(),&m_target, &remotePort); QVERIFY(readSize != -1); QVERIFY(remotePort > 0); } // verify the echoed string is same as the original string QString receivedMessage = datagram.data(); QVERIFY(message == receivedMessage); // make sure the no error signal emitted QVERIFY(errorSpy.isEmpty()); } /*! Description: waitForBytesWritten test TestScenario: 1. Local peer sends the "testcase2 string str1" message to the remote peer 2. Local peer sends the "testcase2 string str2" message to the remote peer 3. Local peer waits for the bytes written 4. call waitForBytesWritten TestExpectedResults: 1. Local peer write datagram successfully firstly 2. Local peer write datagram successfully secondly 3. call waitForBytesWritten successfully 4. call waitForBytesWritten successfully */ /* void tst_qllcpsocketlocal::testCase2() { // STEP 1: QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64))); QString message("testcase2 string str1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 val = m_socket->writeDatagram(data,strSize,m_target, m_port); QVERIFY(val != -1); // STEP 2: QString message2("testcase2 string str2"); QByteArray tmpArray2(message2.toAscii()); const char* data2 = tmpArray2.data(); qint64 strSize2 = message2.size(); qint64 val2 = m_socket->writeDatagram(data2,strSize2,m_target, m_port); QVERIFY(val2 != -1); // STEP 3: const int Timeout = 2 * 1000; bool ret = m_socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); // STEP 4: ret = m_socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); QString messageBox("handshake 3"); QNfcTestUtil::ShowMessage(messageBox); QVERIFY(ret == true); } */ void tst_qllcpsocketlocal::testCase2() { QLlcpSocket *socket = new QLlcpSocket; quint8 localPort = 38; // STEP 1: QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); QString message("testcase2 string str1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 val = socket->writeDatagram(data,strSize,m_target, localPort); QVERIFY(val != -1); // STEP 2: QString message2("testcase2 string str2"); QByteArray tmpArray2(message2.toAscii()); const char* data2 = tmpArray2.data(); qint64 strSize2 = message2.size(); qint64 val2 = socket->writeDatagram(data2,strSize2,m_target, localPort); QVERIFY(val2 != -1); // STEP 3: const int Timeout = 2 * 1000; bool ret = socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); // STEP 4: ret = socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); QString messageBox("handshake 3"); QNfcTestUtil::ShowMessage(messageBox); // STEP 5: const int Timeout = 1 * 1000; m_socket->waitForBytesWritten(Timeout); delete socket; QVERIFY(ret == true); } /*! Description: coverage testcase - targeted for sender doCancel */ void tst_qllcpsocketlocal::testCase3() { QLlcpSocket *localSocket= new QLlcpSocket; // STEP 1: QString message("string1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); localSocket->writeDatagram(data,strSize,m_target, m_port); delete localSocket; } /*! Description: coverage testcase - invalid usage of connection-oriented API */ void tst_qllcpsocketlocal::coverageTest1() { QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error))); m_socket->connectToService(m_target,"uri"); QTRY_VERIFY(errorSpy.count() == 1); QVERIFY(m_socket->error() == QLlcpSocket::UnknownSocketError); m_socket->disconnectFromService(); QTRY_VERIFY(errorSpy.count() == 2); QVERIFY(m_socket->waitForConnected() == false); QVERIFY(m_socket->waitForDisconnected() == false); QString message = "Oops, must follow a port parameter"; QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 ret = m_socket->writeDatagram(data,strSize); QVERIFY(ret == -1); } /*! Description: writeDatagram negative testcase I - invalid port num & wait* functions */ void tst_qllcpsocketlocal::negTestCase1() { QLlcpSocket localSocket; QString message = "Oops, Invalid port num for writeDatagram"; QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint8 invalidPort = -1; qint64 ret = localSocket.writeDatagram(data,strSize,m_target, invalidPort); QVERIFY(ret == -1); const int Timeout = 1 * 500; bool retBool = localSocket.waitForBytesWritten(Timeout); QVERIFY(retBool == false); //Cover QLLCPUnConnected::WaitForReadyRead retBool = localSocket.waitForReadyRead(Timeout); QVERIFY(retBool == false); //Cover QLLCPBind::WaitForReadyRead() retBool = localSocket.waitForReadyRead(Timeout); QVERIFY(retBool == false); } /*! Description: bind negative test - double bind */ void tst_qllcpsocketlocal::negTestCase2() { // bind again will cause failure bool ret2 = m_socket->bind(m_port); QVERIFY(ret2 == false); delete m_socket; m_socket = NULL; } /*! Description: bind negative test - invalid port num */ /* void tst_qllcpsocketlocal::negTestCase3() { QLlcpSocket localSocket; bool ret = localSocket.bind(65); QVERIFY(ret == false); } */ /*! Description: bind negative test - invalid port num II */ /* void tst_qllcpsocketlocal::negTestCase4() { QLlcpSocket localSocket; int reservedPort = 15; bool ret = localSocket.bind(reservedPort); QVERIFY(ret == false); } */ void tst_qllcpsocketlocal::cleanupTest() { delete m_nfcManager; delete m_socket; } QTEST_MAIN(tst_qllcpsocketlocal); #include "tst_qllcpsocketlocal.moc" <commit_msg>fix the typo to pass build<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QCoreApplication> #include <qllcpsocket.h> #include <qnearfieldmanager.h> #include <qnearfieldtarget.h> #include "qnfctestcommon.h" #include "qnfctestutil.h" QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QNearFieldTarget*) Q_DECLARE_METATYPE(QLlcpSocket::Error) Q_DECLARE_METATYPE(QLlcpSocket::State) class tst_qllcpsocketlocal : public QObject { Q_OBJECT public: tst_qllcpsocketlocal(); private Q_SLOTS: // ALERT: Handshake required, do NOT change the sequence of handshaking testcases. void testCase0(); // Intial handshake - work with tst_qllcpsocketremote testCase0 void testCase1(); // handshake 1,2 - work with tst_qllcpsocketremote testCase1 void testCase2(); // handshake 3 - work with tst_qllcpsocketremote testCase2 void testCase3(); void coverageTest1(); void negTestCase1(); void negTestCase2(); //void negTestCase3(); //void negTestCase4(); void cleanupTest(); private: QNearFieldManager *m_nfcManager; //own QNearFieldTarget *m_target; // not own quint8 m_port; QLlcpSocket *m_socket; }; tst_qllcpsocketlocal::tst_qllcpsocketlocal() { qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::Error"); qRegisterMetaType<QNearFieldTarget *>("QLlcpSocket::State"); } /*! Description: Init test case for NFC LLCP connection-less mode socket - local peer TestScenario: Touch a NFC device with LLCP connection-less service actived TestExpectedResults: Signal of target detected has been found. */ void tst_qllcpsocketlocal::testCase0() { m_nfcManager = new QNearFieldManager; QSignalSpy targetDetectedSpy(m_nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); m_nfcManager->startTargetDetection(QNearFieldTarget::AnyTarget); QString message("Local Wait touch"); QNfcTestUtil::ShowMessage(message); QTRY_VERIFY(!targetDetectedSpy.isEmpty()); m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>(); QVERIFY(m_target!=NULL); QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess); m_port = 35; m_socket = new QLlcpSocket; } /*! Description: Send the message and Receive the acknowledged identical message TestScenario: 1. Local peer temps to read datagram without bind 2. Local peer binds to the remote peer 3. Local peer sends the "testcase1 string" message to the remote peer 4. Local peer receives the above message sending from the remote peer TestExpectedResults: 1. Local peer fails to read datagram without bind 2. Local peer binds to local port successfully. 3. The message has be sent to remote peer. 4. The message has been received from remote peer. */ void tst_qllcpsocketlocal::testCase1() { QString message("testcase1 string"); //QLlcpSocket socket(this); // STEP 1. readDatagram must be called before bind QByteArray tmpForReadArray; tmpForReadArray.resize(127); qint64 ret = m_socket->readDatagram(tmpForReadArray.data(), tmpForReadArray.size()); QVERIFY(ret == -1); QCOMPARE(m_socket->state(), QLlcpSocket::UnconnectedState); QSignalSpy stateChangedSpy(m_socket, SIGNAL(stateChanged(QLlcpSocket::State))); // STEP 2: bind the local port for current socket QSignalSpy readyReadSpy(m_socket, SIGNAL(readyRead())); bool retBool = m_socket->bind(m_port); QVERIFY(retBool); QVERIFY(!stateChangedSpy.isEmpty()); QCOMPARE(m_socket->state(), QLlcpSocket::BoundState); QString messageBox("handshake 1"); QNfcTestUtil::ShowMessage(messageBox); // STEP 3: Local peer sends the message to the remote peer QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error))); QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64))); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); m_socket->writeDatagram(data,strSize,m_target, m_port); QTRY_VERIFY(bytesWrittenSpy.count() == 1); QList<QVariant> arguments = bytesWrittenSpy.takeFirst(); // take the first signal qint64 writtenSize = arguments.at(0).value<qint64>(); QCOMPARE(writtenSize, strSize); QString messageBox2("handshake 2"); QNfcTestUtil::ShowMessage(messageBox2); // STEP 4: Receive data from remote peer QTRY_VERIFY(!readyReadSpy.isEmpty()); QByteArray datagram; while (m_socket->hasPendingDatagrams()) { datagram.resize(m_socket->pendingDatagramSize()); quint8 remotePort = 0; qint64 readSize = m_socket->readDatagram(datagram.data(), datagram.size(),&m_target, &remotePort); QVERIFY(readSize != -1); QVERIFY(remotePort > 0); } // verify the echoed string is same as the original string QString receivedMessage = datagram.data(); QVERIFY(message == receivedMessage); // make sure the no error signal emitted QVERIFY(errorSpy.isEmpty()); } /*! Description: waitForBytesWritten test TestScenario: 1. Local peer sends the "testcase2 string str1" message to the remote peer 2. Local peer sends the "testcase2 string str2" message to the remote peer 3. Local peer waits for the bytes written 4. call waitForBytesWritten TestExpectedResults: 1. Local peer write datagram successfully firstly 2. Local peer write datagram successfully secondly 3. call waitForBytesWritten successfully 4. call waitForBytesWritten successfully */ /* void tst_qllcpsocketlocal::testCase2() { // STEP 1: QSignalSpy bytesWrittenSpy(m_socket, SIGNAL(bytesWritten(qint64))); QString message("testcase2 string str1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 val = m_socket->writeDatagram(data,strSize,m_target, m_port); QVERIFY(val != -1); // STEP 2: QString message2("testcase2 string str2"); QByteArray tmpArray2(message2.toAscii()); const char* data2 = tmpArray2.data(); qint64 strSize2 = message2.size(); qint64 val2 = m_socket->writeDatagram(data2,strSize2,m_target, m_port); QVERIFY(val2 != -1); // STEP 3: const int Timeout = 2 * 1000; bool ret = m_socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); // STEP 4: ret = m_socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); QString messageBox("handshake 3"); QNfcTestUtil::ShowMessage(messageBox); QVERIFY(ret == true); } */ void tst_qllcpsocketlocal::testCase2() { QLlcpSocket *socket = new QLlcpSocket; quint8 localPort = 38; // STEP 1: QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); QString message("testcase2 string str1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 val = socket->writeDatagram(data,strSize,m_target, localPort); QVERIFY(val != -1); // STEP 2: QString message2("testcase2 string str2"); QByteArray tmpArray2(message2.toAscii()); const char* data2 = tmpArray2.data(); qint64 strSize2 = message2.size(); qint64 val2 = socket->writeDatagram(data2,strSize2,m_target, localPort); QVERIFY(val2 != -1); // STEP 3: const int Timeout = 2 * 1000; bool ret = socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); // STEP 4: ret = socket->waitForBytesWritten(Timeout); QVERIFY(ret == true); QString messageBox("handshake 3"); QNfcTestUtil::ShowMessage(messageBox); // STEP 5: const int Timeout1 = 1 * 1000; m_socket->waitForBytesWritten(Timeout1); delete socket; QVERIFY(ret == true); } /*! Description: coverage testcase - targeted for sender doCancel */ void tst_qllcpsocketlocal::testCase3() { QLlcpSocket *localSocket= new QLlcpSocket; // STEP 1: QString message("string1"); QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); localSocket->writeDatagram(data,strSize,m_target, m_port); delete localSocket; } /*! Description: coverage testcase - invalid usage of connection-oriented API */ void tst_qllcpsocketlocal::coverageTest1() { QSignalSpy errorSpy(m_socket, SIGNAL(error(QLlcpSocket::Error))); m_socket->connectToService(m_target,"uri"); QTRY_VERIFY(errorSpy.count() == 1); QVERIFY(m_socket->error() == QLlcpSocket::UnknownSocketError); m_socket->disconnectFromService(); QTRY_VERIFY(errorSpy.count() == 2); QVERIFY(m_socket->waitForConnected() == false); QVERIFY(m_socket->waitForDisconnected() == false); QString message = "Oops, must follow a port parameter"; QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint64 ret = m_socket->writeDatagram(data,strSize); QVERIFY(ret == -1); } /*! Description: writeDatagram negative testcase I - invalid port num & wait* functions */ void tst_qllcpsocketlocal::negTestCase1() { QLlcpSocket localSocket; QString message = "Oops, Invalid port num for writeDatagram"; QByteArray tmpArray(message.toAscii()); const char* data = tmpArray.data(); qint64 strSize = message.size(); qint8 invalidPort = -1; qint64 ret = localSocket.writeDatagram(data,strSize,m_target, invalidPort); QVERIFY(ret == -1); const int Timeout = 1 * 500; bool retBool = localSocket.waitForBytesWritten(Timeout); QVERIFY(retBool == false); //Cover QLLCPUnConnected::WaitForReadyRead retBool = localSocket.waitForReadyRead(Timeout); QVERIFY(retBool == false); //Cover QLLCPBind::WaitForReadyRead() retBool = localSocket.waitForReadyRead(Timeout); QVERIFY(retBool == false); } /*! Description: bind negative test - double bind */ void tst_qllcpsocketlocal::negTestCase2() { // bind again will cause failure bool ret2 = m_socket->bind(m_port); QVERIFY(ret2 == false); delete m_socket; m_socket = NULL; } /*! Description: bind negative test - invalid port num */ /* void tst_qllcpsocketlocal::negTestCase3() { QLlcpSocket localSocket; bool ret = localSocket.bind(65); QVERIFY(ret == false); } */ /*! Description: bind negative test - invalid port num II */ /* void tst_qllcpsocketlocal::negTestCase4() { QLlcpSocket localSocket; int reservedPort = 15; bool ret = localSocket.bind(reservedPort); QVERIFY(ret == false); } */ void tst_qllcpsocketlocal::cleanupTest() { delete m_nfcManager; delete m_socket; } QTEST_MAIN(tst_qllcpsocketlocal); #include "tst_qllcpsocketlocal.moc" <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. #ifndef __MESOS_SLAVE_ISOLATOR_HPP__ #define __MESOS_SLAVE_ISOLATOR_HPP__ #include <list> #include <string> #include <mesos/resources.hpp> #include <mesos/slave/containerizer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/hashset.hpp> #include <stout/option.hpp> #include <stout/try.hpp> namespace mesos { namespace slave { class Isolator { public: virtual ~Isolator() {} // Returns true if this isolator supports nested containers. This // method is designed to allow isolators to opt-in to support nested // containers. virtual bool supportsNesting() { return false; } // Recover containers from the run states and the orphan containers // (known to the launcher but not known to the slave) detected by // the launcher. virtual process::Future<Nothing> recover( const std::list<ContainerState>& states, const hashset<ContainerID>& orphans) { return Nothing(); } // Prepare for isolation of the executor. Any steps that require // execution in the containerized context (e.g. inside a network // namespace) can be returned in the optional CommandInfo and they // will be run by the Launcher. // TODO(idownes): Any URIs or Environment in the CommandInfo will be // ignored; only the command value is used. virtual process::Future<Option<ContainerLaunchInfo>> prepare( const ContainerID& containerId, const ContainerConfig& containerConfig) { return None(); } // Isolate the executor. virtual process::Future<Nothing> isolate( const ContainerID& containerId, pid_t pid) { return Nothing(); } // Watch the containerized executor and report if any resource // constraint impacts the container, e.g., the kernel killing some // processes. virtual process::Future<ContainerLimitation> watch( const ContainerID& containerId) { return process::Future<ContainerLimitation>(); } // Update the resources allocated to the container. virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources) { return Nothing(); } // Gather resource usage statistics for the container. virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId) { return ResourceStatistics(); } // Get the run-time status of isolator specific properties // associated with the container. virtual process::Future<ContainerStatus> status( const ContainerID& containerId) { return ContainerStatus(); }; // Clean up a terminated container. This is called after the // executor and all processes in the container have terminated. // It's likely that isolator `cleanup` is called for an unknown // container (see MESOS-6059). Therefore, the isolator should ignore // the cleanup is the container is unknown to it. In any case, the // `cleanup` won't be called multiple times for a container. Also, // if `prepare` is called, the cleanup is guaranteed to be called // after `prepare` finishes (or fails). virtual process::Future<Nothing> cleanup( const ContainerID& containerId) { return Nothing(); } }; } // namespace slave { } // namespace mesos { #endif // __MESOS_SLAVE_ISOLATOR_HPP__ <commit_msg>Removed extra ';' from "isolator.hpp".<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. #ifndef __MESOS_SLAVE_ISOLATOR_HPP__ #define __MESOS_SLAVE_ISOLATOR_HPP__ #include <list> #include <string> #include <mesos/resources.hpp> #include <mesos/slave/containerizer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/hashset.hpp> #include <stout/option.hpp> #include <stout/try.hpp> namespace mesos { namespace slave { class Isolator { public: virtual ~Isolator() {} // Returns true if this isolator supports nested containers. This // method is designed to allow isolators to opt-in to support nested // containers. virtual bool supportsNesting() { return false; } // Recover containers from the run states and the orphan containers // (known to the launcher but not known to the slave) detected by // the launcher. virtual process::Future<Nothing> recover( const std::list<ContainerState>& states, const hashset<ContainerID>& orphans) { return Nothing(); } // Prepare for isolation of the executor. Any steps that require // execution in the containerized context (e.g. inside a network // namespace) can be returned in the optional CommandInfo and they // will be run by the Launcher. // TODO(idownes): Any URIs or Environment in the CommandInfo will be // ignored; only the command value is used. virtual process::Future<Option<ContainerLaunchInfo>> prepare( const ContainerID& containerId, const ContainerConfig& containerConfig) { return None(); } // Isolate the executor. virtual process::Future<Nothing> isolate( const ContainerID& containerId, pid_t pid) { return Nothing(); } // Watch the containerized executor and report if any resource // constraint impacts the container, e.g., the kernel killing some // processes. virtual process::Future<ContainerLimitation> watch( const ContainerID& containerId) { return process::Future<ContainerLimitation>(); } // Update the resources allocated to the container. virtual process::Future<Nothing> update( const ContainerID& containerId, const Resources& resources) { return Nothing(); } // Gather resource usage statistics for the container. virtual process::Future<ResourceStatistics> usage( const ContainerID& containerId) { return ResourceStatistics(); } // Get the run-time status of isolator specific properties // associated with the container. virtual process::Future<ContainerStatus> status( const ContainerID& containerId) { return ContainerStatus(); } // Clean up a terminated container. This is called after the // executor and all processes in the container have terminated. // It's likely that isolator `cleanup` is called for an unknown // container (see MESOS-6059). Therefore, the isolator should ignore // the cleanup is the container is unknown to it. In any case, the // `cleanup` won't be called multiple times for a container. Also, // if `prepare` is called, the cleanup is guaranteed to be called // after `prepare` finishes (or fails). virtual process::Future<Nothing> cleanup( const ContainerID& containerId) { return Nothing(); } }; } // namespace slave { } // namespace mesos { #endif // __MESOS_SLAVE_ISOLATOR_HPP__ <|endoftext|>