text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* @file Reader.cpp
* @author Pallamidessi Joseph
* @version 1.0
*
* @section LICENSE
*
* 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 at
* http://www.gnu.org/copyleft/gpl.html
**/
#include "Reader.hpp"
Reader::Reader(char* path,AudioMonitorModule* sendingModule,MonitorParameter* params):mPathTo(path),mSendingModule(sendingModule),mParams(params){
mSendingModule->setParams(params);
}
void Reader::readAndSend(){
boost::filesystem::fstream fs;
std::string buffer;
fs.open(boost::filesystem::system_complete(mPathTo),std::ios_base::in);
boost::filesystem::path extension=mPathTo.extension();
while(std::getline(fs,buffer)){
if(testLine(extension,buffer)){
mParams->processBuffer(buffer);
usleep(mParams->getTime());
mSendingModule->send();
}
else{
if(extension.compare(".dat")==0){
std::getline(fs,buffer);
}
}
}
}
Reader::~Reader(){
}
/*Check the current line, return true if it's a data line, false otherwise*/
bool Reader::testLine(boost::filesystem::path extension,std::string line){
char firstChar=0;
if(extension.compare(".csv")==0) {
firstChar=line[0];
if (firstChar>='A'&& firstChar<='z'){
return false;
}
else{
return true;
}
}
else if(extension.compare(".dat")==0) {
firstChar=line[0];
if (firstChar=='#') {
return false;
}
else {
return true;
}
}
return true;
}
void Reader::start(){
mThread=boost::thread(&Reader::readAndSend,this);
}
void Reader::join(){
mThread.join();
}
<commit_msg>Add implementation comment and reorganized some blocs<commit_after>/**
* @file Reader.cpp
* @author Pallamidessi Joseph
* @version 1.0
*
* @section LICENSE
*
* 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 at
* http://www.gnu.org/copyleft/gpl.html
**/
#include "Reader.hpp"
/*Constructor/Destructor----------------------------------------------------------*/
Reader::Reader(char* path,AudioMonitorModule* sendingModule,MonitorParameter* params)
:mPathTo(path),mSendingModule(sendingModule),mParams(params){
mSendingModule->setParams(params);
}
Reader::~Reader(){
}
/*Methods-------------------------------------------------------------------------*/
void Reader::readAndSend(){
boost::filesystem::fstream fs;
std::string buffer;
fs.open(boost::filesystem::system_complete(mPathTo),std::ios_base::in);
boost::filesystem::path extension=mPathTo.extension();
/*Read a line,than wait the specified time and send the message*/
while(std::getline(fs,buffer)){
if(testLine(extension,buffer)){
mParams->processBuffer(buffer);
usleep(mParams->getTime());
mSendingModule->send();
}
else{
if(extension.compare(".dat")==0){ //Jump an extra line after
std::getline(fs,buffer); //an non data line in a .dat file
}
}
}
}
/*Check the current line, return true if it's a data line, false otherwise*/
bool Reader::testLine(boost::filesystem::path extension,std::string line){
char firstChar=0;
/*CSV case*/
if(extension.compare(".csv")==0) {
firstChar=line[0];
if (firstChar>='A'&& firstChar<='z'){
return false;
}
else{
return true;
}
}
/*DAT case*/
else if(extension.compare(".dat")==0) {
firstChar=line[0];
if (firstChar=='#') {
return false;
}
else {
return true;
}
}
/*Not a supported extension : always false*/
return false;
}
/*Start the lecture on the thread*/
void Reader::start(){
mThread=boost::thread(&Reader::readAndSend,this);
}
/*Wait for the encapsulated thread to finish*/
void Reader::join(){
mThread.join();
}
<|endoftext|> |
<commit_before>#include <curses.h>
#include <stdio.h>
#include <string.h>
#include "../include/debugC.h"
#include "../include/machine.h"
using namespace std;
debugC::debugC(machine* BFM){
localMachine = BFM;
}
debugC::~debugC(){
delete this;
}
void debugC::setupDebugger(){
initscr();
raw();
noecho();
start_color();
curs_set(0);
keypad(stdscr, TRUE);
init_pair(1, COLOR_WHITE, COLOR_GREEN);
attron(A_BOLD);
printw("\t\t\tBr**nfuck Curses Debugger");
stackWindow = subwin(stdscr, 18, 7, 1, 0);
wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
mvwprintw(stackWindow, 0, 1, "Stack");
tapeWindow = subwin(stdscr, 5, 72, 1, 8);
wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(tapeWindow, 0, 2, "Tape");
haltWindow = subwin(stdscr, 5, 20, 14, 8);
wborder(haltWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(haltWindow, 0, 2, "");
outputWindow = subwin(stdscr, 5, 20, 14, 29);
wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(outputWindow, 0, 2, "Output");
codeWindow = subwin(stdscr, 8, 72, 6, 8);
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
}
void debugC::tearDown(){
delwin(stackWindow);
delwin(tapeWindow);
delwin(haltWindow);
delwin(outputWindow);
delwin(codeWindow);
delwin(stdscr);
endwin();
printf("\rFinished debugging\n");
exit(0);
}
void debugC::redrawStackWindow(int stackHeight){
//stack is only redrawn when it changes, don't waste time changing every iteration
int top = localMachine->getStackTop();
int* stack = localMachine->getStack();
for(int y = 0; y < 16; y++){
mvwprintw(stackWindow, 16-y, 1, " ");
if(y <= top){
char* currentElement;
sprintf(currentElement, "%i", stack[y]);
mvwprintw(stackWindow, 16-y, 1, currentElement);
}
}
wrefresh(stackWindow);
}
void debugC::redrawTapeWindow(){
char* tmp = (char*)malloc(20);
int dataPointer = localMachine->getDataPointer();
int n = 1;
for(int i = -1; i < 17; i++){
if(!i)
wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);
mvwprintw(tapeWindow, 2, n, "%d|", localMachine->getTapeAt(dataPointer+i));
wattroff(tapeWindow, COLOR_PAIR(1));
n+=(to_string(localMachine->getTapeAt(dataPointer+i)).length())+1;
}
clearok(tapeWindow, true);
wrefresh(tapeWindow);
}
void debugC::redrawCodeWindow(){
string sourceToDraw = localMachine->getSource();
wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
while(n < localMachine->getSource().length()){
if(n == localMachine->getSourceIterator())
wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
waddch(codeWindow, sourceToDraw[n]);
wattroff(codeWindow, COLOR_PAIR(1));
//When moving to a new line, start at x=1 instead of 0
getyx(codeWindow, tmpY, tmpX);
if(tmpX == 0)
wmove(codeWindow, tmpY, 1);
n++;
}
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
wrefresh(codeWindow);
}
void debugC::redrawOutputWindow(){
FILE* abyss = fopen("/dev/null", "w");
int returnedOutput = localMachine->NAO(abyss);
char* output; sprintf(output, "%i", returnedOutput);
mvwprintw(outputWindow, 1, 1, " ");
mvwprintw(outputWindow, 1, 1, output);
wrefresh(outputWindow);
fclose(abyss);
}
void debugC::redrawHaltWindow(){
clearok(haltWindow, true);
mvwprintw(haltWindow, 1, 1, "Halted!");
mvwprintw(haltWindow, 2, 1, "DP: %i", localMachine->getDataPointer());
mvwprintw(haltWindow, 3, 1, "Cell: %i", localMachine->getTapeAt(localMachine->getDataPointer()));
wrefresh(haltWindow);
}
void debugC::updateScreen(){
redrawTapeWindow();
redrawCodeWindow();
}
char debugC::step(int mod){
//have the machine return the operator that was just processed
char retOperator = localMachine->processChar(mod);
if(retOperator == '.')
redrawOutputWindow();
if(retOperator == '@')
redrawHaltWindow();
return retOperator;
}
void debugC::specialActions(char op){
switch(op){
case ',': //Pause curses for stdin
endwin();
printf("\r>>>");
break;
case '!': //end curses and stop debugging;
tearDown();
break;
}
}
void debugC::processUntilHalt(){
while(step(1) != '@');
}
//begin debugger, create window with curses
void debugC::start(string source){
setupDebugger();
updateScreen();
int stackHeight = -1;
int input;
while((input = getch()) != '!'){ //Exit debugger on !
char nextOp = source[localMachine->getSourceIterator()];
specialActions(nextOp);
if(input == '>')
step(1);
else if(input == '?')
processUntilHalt();
//Only update the stack window if it actually changes
if(stackHeight != localMachine->getStackTop()){
stackHeight = localMachine->getStackTop();
redrawStackWindow(stackHeight);
}
updateScreen();
}
tearDown();
};
<commit_msg>Fixed segfault on output<commit_after>#include <curses.h>
#include <stdio.h>
#include <string.h>
#include "../include/debugC.h"
#include "../include/machine.h"
using namespace std;
debugC::debugC(machine* BFM){
localMachine = BFM;
}
debugC::~debugC(){
delete this;
}
void debugC::setupDebugger(){
initscr();
raw();
noecho();
start_color();
curs_set(0);
keypad(stdscr, TRUE);
init_pair(1, COLOR_WHITE, COLOR_GREEN);
attron(A_BOLD);
printw("\t\t\tBr**nfuck Curses Debugger");
stackWindow = subwin(stdscr, 18, 7, 1, 0);
wborder(stackWindow, '|', '|', '-', '-', '|', '|', 'x', 'x');
mvwprintw(stackWindow, 0, 1, "Stack");
tapeWindow = subwin(stdscr, 5, 72, 1, 8);
wborder(tapeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(tapeWindow, 0, 2, "Tape");
haltWindow = subwin(stdscr, 5, 20, 14, 8);
wborder(haltWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(haltWindow, 0, 2, "");
outputWindow = subwin(stdscr, 5, 20, 14, 29);
wborder(outputWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(outputWindow, 0, 2, "Output");
codeWindow = subwin(stdscr, 8, 72, 6, 8);
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
}
void debugC::tearDown(){
delwin(stackWindow);
delwin(tapeWindow);
delwin(haltWindow);
delwin(outputWindow);
delwin(codeWindow);
delwin(stdscr);
endwin();
printf("\rFinished debugging\n");
exit(0);
}
void debugC::redrawStackWindow(int stackHeight){
//stack is only redrawn when it changes, don't waste time changing every iteration
int top = localMachine->getStackTop();
int* stack = localMachine->getStack();
for(int y = 0; y < 16; y++){
mvwprintw(stackWindow, 16-y, 1, " ");
if(y <= top){
char* currentElement;
sprintf(currentElement, "%i", stack[y]);
mvwprintw(stackWindow, 16-y, 1, currentElement);
}
}
wrefresh(stackWindow);
}
void debugC::redrawTapeWindow(){
char* tmp = (char*)malloc(20);
int dataPointer = localMachine->getDataPointer();
int n = 1;
for(int i = -1; i < 17; i++){
if(!i)
wattron(tapeWindow, COLOR_PAIR(1) | A_BOLD);
mvwprintw(tapeWindow, 2, n, "%d|", localMachine->getTapeAt(dataPointer+i));
wattroff(tapeWindow, COLOR_PAIR(1));
n+=(to_string(localMachine->getTapeAt(dataPointer+i)).length())+1;
}
clearok(tapeWindow, true);
wrefresh(tapeWindow);
}
void debugC::redrawCodeWindow(){
string sourceToDraw = localMachine->getSource();
wmove(codeWindow, 1, 1); int n = 0, tmpY, tmpX;
while(n < localMachine->getSource().length()){
if(n == localMachine->getSourceIterator())
wattron(codeWindow, COLOR_PAIR(1) | A_BOLD);
waddch(codeWindow, sourceToDraw[n]);
wattroff(codeWindow, COLOR_PAIR(1));
//When moving to a new line, start at x=1 instead of 0
getyx(codeWindow, tmpY, tmpX);
if(tmpX == 0)
wmove(codeWindow, tmpY, 1);
n++;
}
wborder(codeWindow, '|', '|', '-', '-', 'x', 'x', 'x', 'x');
mvwprintw(codeWindow, 0, 2, "Source code");
wrefresh(codeWindow);
}
void debugC::redrawOutputWindow(){
FILE* abyss = fopen("/dev/null", "w");
int returnedOutput = localMachine->NAO(abyss);
char* output = (char*)malloc(256); sprintf(output, "%i", returnedOutput);
mvwprintw(outputWindow, 1, 1, " ");
mvwprintw(outputWindow, 1, 1, output);
wrefresh(outputWindow);
fclose(abyss);
}
void debugC::redrawHaltWindow(){
clearok(haltWindow, true);
mvwprintw(haltWindow, 1, 1, "Halted!");
mvwprintw(haltWindow, 2, 1, "DP: %i", localMachine->getDataPointer());
mvwprintw(haltWindow, 3, 1, "Cell: %i", localMachine->getTapeAt(localMachine->getDataPointer()));
wrefresh(haltWindow);
}
void debugC::updateScreen(){
redrawTapeWindow();
redrawCodeWindow();
}
char debugC::step(int mod){
//have the machine return the operator that was just processed
char retOperator = localMachine->processChar(mod);
if(retOperator == '.')
redrawOutputWindow();
if(retOperator == '@')
redrawHaltWindow();
return retOperator;
}
void debugC::specialActions(char op){
switch(op){
case ',': //Pause curses for stdin
endwin();
printf("\r>>>");
break;
case '!': //end curses and stop debugging;
tearDown();
break;
}
}
void debugC::processUntilHalt(){
while(step(1) != '@');
}
//begin debugger, create window with curses
void debugC::start(string source){
setupDebugger();
updateScreen();
int stackHeight = -1;
int input;
while((input = getch()) != '!'){ //Exit debugger on !
char nextOp = source[localMachine->getSourceIterator()];
specialActions(nextOp);
if(input == '>')
step(1);
else if(input == '?')
processUntilHalt();
//Only update the stack window if it actually changes
if(stackHeight != localMachine->getStackTop()){
stackHeight = localMachine->getStackTop();
redrawStackWindow(stackHeight);
}
updateScreen();
}
tearDown();
};
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"
#include "hw3d_opengl_common.h"
namespace Hw3D
{
Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt ®ion, bool readOnly)
{
if(region.Width() < 0 || region.Height() < 0)
{
DO_THROW(Err::InvalidParam, "Attempted to lock a region with zero width or height");
}
GLenum err;
glBindTexture(GL_TEXTURE_2D, m_textureName);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding texture:" + GetGlErrorString(err));
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_bufferObject);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding buffer: " + GetGlErrorString(err));
}
auto offset = (region.Left() + region.Top() * GetSize().Width) * 4;
auto length = (region.Width() + (region.Height() - 1) * GetSize().Width) * 4;
GLbitfield flags = GL_MAP_READ_BIT;
if(!readOnly)
{
flags |= GL_MAP_WRITE_BIT;
}
auto ptr = glMapBufferRange(
GL_PIXEL_UNPACK_BUFFER,
offset,
length,
flags);
//auto ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed mapping texture buffer: " + GetGlErrorString(err));
}
if(ptr == nullptr)
{
DO_THROW(Err::CriticalError, "Failed mapping texture buffer");
}
Texture::Lock l;
l.Buffer = reinterpret_cast<uint8_t*>(ptr);
l.Pitch = GetSize().Width * 4;
return l;
}
void OpenGlTexture::UnlockRegion()
{
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
}
GLuint OpenGlTexture::GetTextureName()
{
return m_textureName;
}
OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
Texture(dimensions, fmt),
m_textureName(0),
m_bufferObject(0)
{
glGenTextures(1, &m_textureName);
if(m_textureName == GL_INVALID_VALUE)
{
m_textureName = 0;
DO_THROW(Err::CriticalError, "Failed allocating texture");
}
glBindTexture(GL_TEXTURE_2D, m_textureName);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glTexImage2D(
GL_TEXTURE_2D,
0,
GetGlInternalFormat(fmt),
dimensions.Width,
dimensions.Height,
0,
GetGlFormat(fmt),
GetGlDataType(fmt),
nullptr
);
GLenum err;
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "glTexImage2D failed: " + GetGlErrorString(err));
}
glGenBuffers(1, &m_bufferObject);
if(m_bufferObject == GL_INVALID_VALUE)
{
DO_THROW(Err::CriticalError, "Failed allocating PBO");
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_bufferObject);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding buffer: " + GetGlErrorString(err));
}
glBufferData(GL_PIXEL_UNPACK_BUFFER, dimensions.Width * dimensions.Height * 4, nullptr, GL_STREAM_DRAW);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed allocating buffer data: " + GetGlErrorString(err));
}
//glBufferData(GL_PIXEL_UNPACK_BUFFER, num_bytes, NULL, GL_STREAM_DRAW);
}
OpenGlTexture::~OpenGlTexture()
{
glDeleteBuffers(1, &m_bufferObject);
glDeleteTextures(1, &m_textureName);
}
}
<commit_msg>Hopefully more correct use of PBO<commit_after>#include <GL/glew.h>
#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"
#include "hw3d_opengl_common.h"
namespace Hw3D
{
Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt ®ion, bool readOnly)
{
if(region.Width() < 0 || region.Height() < 0)
{
DO_THROW(Err::InvalidParam, "Attempted to lock a region with zero width or height");
}
GLenum err;
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_bufferObject);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding buffer: " + GetGlErrorString(err));
}
auto offset = (region.Left() + region.Top() * GetSize().Width) * 4;
auto length = (region.Width() + (region.Height() - 1) * GetSize().Width) * 4;
GLbitfield flags = GL_MAP_READ_BIT;
if(!readOnly)
{
flags |= GL_MAP_WRITE_BIT;
}
auto ptr = glMapBufferRange(
GL_PIXEL_UNPACK_BUFFER,
offset,
length,
flags);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed mapping texture buffer: " + GetGlErrorString(err));
}
if(ptr == nullptr)
{
DO_THROW(Err::CriticalError, "Failed mapping buffer object");
}
Texture::Lock l;
l.Buffer = reinterpret_cast<uint8_t*>(ptr);
l.Pitch = GetSize().Width * 4;
return l;
}
void OpenGlTexture::UnlockRegion()
{
GLenum err;
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed unmapping buffer object: " + GetGlErrorString(err));
}
glBindTexture(GL_TEXTURE_2D, m_textureName);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding texture: " + GetGlErrorString(err));
}
glTexImage2D(
GL_TEXTURE_2D,
0,
GetGlInternalFormat(D3DFormat()),
GetSize().Width,
GetSize().Height,
0,
GetGlFormat(D3DFormat()),
GetGlDataType(D3DFormat()),
nullptr
);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed copying data to texture: " + GetGlErrorString(err));
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "glBindBuffer failed: " + GetGlErrorString(err));
}
}
GLuint OpenGlTexture::GetTextureName()
{
return m_textureName;
}
OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
Texture(dimensions, fmt),
m_textureName(0),
m_bufferObject(0)
{
GLenum err;
// Create texture
glGenTextures(1, &m_textureName);
if(m_textureName == GL_INVALID_VALUE)
{
m_textureName = 0;
DO_THROW(Err::CriticalError, "Failed allocating texture");
}
glBindTexture(GL_TEXTURE_2D, m_textureName);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "glBindTexture failed: " + GetGlErrorString(err));
}
glTexImage2D(
GL_TEXTURE_2D,
0,
GetGlInternalFormat(fmt),
dimensions.Width,
dimensions.Height,
0,
GetGlFormat(fmt),
GetGlDataType(fmt),
nullptr
);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "glTexImage2D failed: " + GetGlErrorString(err));
}
// Create buffer object that will be used for transfers during Lock/Unlock
glGenBuffers(1, &m_bufferObject);
if(m_bufferObject == GL_INVALID_VALUE)
{
DO_THROW(Err::CriticalError, "Failed allocating PBO");
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_bufferObject);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed binding buffer: " + GetGlErrorString(err));
}
glBufferData(GL_PIXEL_UNPACK_BUFFER, dimensions.Width * dimensions.Height * 4, nullptr, GL_STREAM_DRAW);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "Failed allocating buffer data: " + GetGlErrorString(err));
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
if((err = glGetError()) != GL_NO_ERROR)
{
DO_THROW(Err::CriticalError, "glBindBuffer failed: " + GetGlErrorString(err));
}
//glBufferData(GL_PIXEL_UNPACK_BUFFER, num_bytes, NULL, GL_STREAM_DRAW);
}
OpenGlTexture::~OpenGlTexture()
{
glDeleteBuffers(1, &m_bufferObject);
glDeleteTextures(1, &m_textureName);
}
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: preferencesEntry.C,v 1.6 2004/09/29 18:58:15 amoll Exp $
//
#include <BALL/VIEW/KERNEL/preferencesEntry.h>
#include <BALL/VIEW/DATATYPE/colorRGBA.h>
#include <qslider.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qtextedit.h>
#include <qbuttongroup.h>
#include <qcolordialog.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
PreferencesEntry::PreferencesEntry()
{
}
PreferencesEntry::~PreferencesEntry()
{
}
void PreferencesEntry::writePreferenceEntries(INIFile& inifile)
{
inifile.appendSection(inifile_section_name_);
HashSet<QWidget*>::Iterator it = preferences_objects_.begin();
for (; it != preferences_objects_.end(); it++)
{
String name = (**it).name();
if (name == "")
{
Log.error() << "Unnamed Preferences object!" << std::endl;
continue;
}
if (RTTI::isKindOf<QSlider>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QSlider*)(*it))->value()));
}
else if (RTTI::isKindOf<QLabel>(**it))
{
inifile.insertValue(inifile_section_name_, name, getLabelColor_((QLabel*)*it));
}
else if (RTTI::isKindOf<QTextEdit>(**it))
{
inifile.insertValue(inifile_section_name_, name, ((QTextEdit*)(*it))->text().ascii());
}
else if (RTTI::isKindOf<QCheckBox>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QCheckBox*)*it)->isChecked()));
}
else if (RTTI::isKindOf<QComboBox>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QComboBox*)*it)->currentItem()));
}
else if (RTTI::isKindOf<QButtonGroup>(**it))
{
QButtonGroup* qbg = dynamic_cast<QButtonGroup*>(*it);
int id = -1;
if (qbg != 0)
{
if (qbg->selected() == 0) continue;
id = qbg->id(qbg->selected());
}
inifile.insertValue(inifile_section_name_, name, String(id));
}
else
{
Log.error() << "Unknown QWidget " << name << " in "
<< __FILE__ << " " << __LINE__ << std::endl;
continue;
}
}
}
void PreferencesEntry::readPreferenceEntries(const INIFile& inifile)
{
HashSet<QWidget*>::Iterator it = preferences_objects_.begin();
for (; it != preferences_objects_.end(); it++)
{
if (!inifile.hasEntry(inifile_section_name_, (**it).name())) continue;
String value = inifile.getValue(inifile_section_name_, (**it).name());
try
{
if (RTTI::isKindOf<QSlider>(**it))
{
((QSlider*) *it)->setValue(value.toInt());
}
else if (RTTI::isKindOf<QLabel>(**it))
{
setLabelColor_((QLabel*)*it, ColorRGBA(value));
}
else if (RTTI::isKindOf<QTextEdit>(**it))
{
((QTextEdit*)(*it))->setText(value);
}
else if (RTTI::isKindOf<QCheckBox>(**it))
{
((QCheckBox*) *it)->setChecked(value == "1");
}
else if (RTTI::isKindOf<QComboBox>(**it))
{
if (value.toUnsignedInt() >= (Position)((QComboBox*) *it)->count()) continue;
((QComboBox*) *it)->setCurrentItem(value.toInt());
}
else if (RTTI::isKindOf<QButtonGroup>(**it))
{
((QButtonGroup*) *it)->setButton(value.toInt());
}
else
{
Log.error() << "Unknown QWidget in " << __FILE__ << __LINE__ << std::endl;
continue;
}
}
catch(...)
{
Log.error() << "Invalid entry in INIFile: " << (**it).name() << " " << value << std::endl;
}
}
}
void PreferencesEntry::registerObject_(QWidget* widget)
{
if (widget == 0) return;
if (widget->name() == "")
{
Log.error() << "Unnamed Preferences object!" << std::endl;
return;
}
if (preferences_objects_.has(widget))
{
Log.error() << "Widget " << widget << " with name " << widget->name() << " was already added!" << std::endl;
return;
}
preferences_objects_.insert(widget);
}
void PreferencesEntry::setLabelColor_(QLabel* label, const ColorRGBA& color)
{
label->setBackgroundColor(color.getQColor());
}
ColorRGBA PreferencesEntry::getLabelColor_(QLabel* label) const
{
return ColorRGBA(label->backgroundColor());
}
void PreferencesEntry::chooseColor_(QLabel* label)
{
QColor qcolor = QColorDialog::getColor(label->backgroundColor());
if (!qcolor.isValid()) return;
label->setBackgroundColor(qcolor);
}
} // namespace VIEW
} // namespace BALL
<commit_msg>*** empty log message ***<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: preferencesEntry.C,v 1.7 2004/09/29 20:38:00 oliver Exp $
//
#include <BALL/VIEW/KERNEL/preferencesEntry.h>
#include <BALL/VIEW/DATATYPE/colorRGBA.h>
#include <qslider.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qtextedit.h>
#include <qbuttongroup.h>
#include <qcolordialog.h>
using namespace std;
namespace BALL
{
namespace VIEW
{
PreferencesEntry::PreferencesEntry()
{
}
PreferencesEntry::~PreferencesEntry()
{
}
void PreferencesEntry::writePreferenceEntries(INIFile& inifile)
{
inifile.appendSection(inifile_section_name_);
HashSet<QWidget*>::Iterator it = preferences_objects_.begin();
for (; it != preferences_objects_.end(); it++)
{
String name = (**it).name();
if (name == "")
{
Log.error() << "Unnamed Preferences object!" << std::endl;
continue;
}
if (RTTI::isKindOf<QSlider>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QSlider*)(*it))->value()));
}
else if (RTTI::isKindOf<QLabel>(**it))
{
inifile.insertValue(inifile_section_name_, name, getLabelColor_((QLabel*)*it));
}
else if (RTTI::isKindOf<QTextEdit>(**it))
{
inifile.insertValue(inifile_section_name_, name, ((QTextEdit*)(*it))->text().ascii());
}
else if (RTTI::isKindOf<QCheckBox>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QCheckBox*)*it)->isChecked()));
}
else if (RTTI::isKindOf<QComboBox>(**it))
{
inifile.insertValue(inifile_section_name_, name, String(((QComboBox*)*it)->currentItem()));
}
else if (RTTI::isKindOf<QButtonGroup>(**it))
{
QButtonGroup* qbg = dynamic_cast<QButtonGroup*>(*it);
int id = -1;
if (qbg != 0)
{
if (qbg->selected() == 0)
{
id = qbg->id(qbg->selected());
}
}
inifile.insertValue(inifile_section_name_, name, String(id));
}
else
{
Log.error() << "Unknown QWidget " << name << " in "
<< __FILE__ << " " << __LINE__ << std::endl;
continue;
}
}
}
void PreferencesEntry::readPreferenceEntries(const INIFile& inifile)
{
HashSet<QWidget*>::Iterator it = preferences_objects_.begin();
for (; it != preferences_objects_.end(); it++)
{
if (!inifile.hasEntry(inifile_section_name_, (**it).name())) continue;
String value = inifile.getValue(inifile_section_name_, (**it).name());
try
{
if (RTTI::isKindOf<QSlider>(**it))
{
((QSlider*) *it)->setValue(value.toInt());
}
else if (RTTI::isKindOf<QLabel>(**it))
{
setLabelColor_((QLabel*)*it, ColorRGBA(value));
}
else if (RTTI::isKindOf<QTextEdit>(**it))
{
((QTextEdit*)(*it))->setText(value);
}
else if (RTTI::isKindOf<QCheckBox>(**it))
{
((QCheckBox*) *it)->setChecked(value == "1");
}
else if (RTTI::isKindOf<QComboBox>(**it))
{
if (value.toUnsignedInt() >= (Position)((QComboBox*) *it)->count()) continue;
((QComboBox*) *it)->setCurrentItem(value.toInt());
}
else if (RTTI::isKindOf<QButtonGroup>(**it))
{
((QButtonGroup*) *it)->setButton(value.toInt());
}
else
{
Log.error() << "Unknown QWidget in " << __FILE__ << __LINE__ << std::endl;
continue;
}
}
catch(...)
{
Log.error() << "Invalid entry in INIFile: " << (**it).name() << " " << value << std::endl;
}
}
}
void PreferencesEntry::registerObject_(QWidget* widget)
{
if (widget == 0) return;
if (widget->name() == "")
{
Log.error() << "Unnamed Preferences object!" << std::endl;
return;
}
if (preferences_objects_.has(widget))
{
Log.error() << "Widget " << widget << " with name " << widget->name() << " was already added!" << std::endl;
return;
}
preferences_objects_.insert(widget);
}
void PreferencesEntry::setLabelColor_(QLabel* label, const ColorRGBA& color)
{
label->setBackgroundColor(color.getQColor());
}
ColorRGBA PreferencesEntry::getLabelColor_(QLabel* label) const
{
return ColorRGBA(label->backgroundColor());
}
void PreferencesEntry::chooseColor_(QLabel* label)
{
QColor qcolor = QColorDialog::getColor(label->backgroundColor());
if (!qcolor.isValid()) return;
label->setBackgroundColor(qcolor);
}
} // namespace VIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct opts_t
{
bool initeq = false;
bool anyeq = false;
bool fwd = false;
bool bwd = false;
bool nop = false;
};
struct FmcombineWorker
{
const opts_t &opts;
Design *design;
Module *original = nullptr;
Module *module = nullptr;
IdString orig_type, combined_type;
FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) :
opts(opts), design(design), original(design->module(orig_type)),
orig_type(orig_type), combined_type(stringf("$fmcombine%s", orig_type.c_str()))
{
}
SigSpec import_sig(SigSpec sig, const string &suffix)
{
SigSpec newsig;
for (auto chunk : sig.chunks()) {
if (chunk.wire != nullptr)
chunk.wire = module->wire(chunk.wire->name.str() + suffix);
newsig.append(chunk);
}
return newsig;
}
Cell *import_prim_cell(Cell *cell, const string &suffix)
{
Cell *c = module->addCell(cell->name.str() + suffix, cell->type);
c->parameters = cell->parameters;
c->attributes = cell->attributes;
for (auto &conn : cell->connections())
c->setPort(conn.first, import_sig(conn.second, suffix));
return c;
}
void import_hier_cell(Cell *cell)
{
if (!cell->parameters.empty())
log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell));
FmcombineWorker sub_worker(design, cell->type, opts);
sub_worker.generate();
Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type);
// c->parameters = cell->parameters;
c->attributes = cell->attributes;
for (auto &conn : cell->connections()) {
c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold"));
c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate"));
}
}
void generate()
{
if (design->module(combined_type)) {
// log("Combined module %s already exists.\n", log_id(combined_type));
return;
}
log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type));
module = design->addModule(combined_type);
for (auto wire : original->wires()) {
module->addWire(wire->name.str() + "_gold", wire);
module->addWire(wire->name.str() + "_gate", wire);
}
module->fixup_ports();
for (auto cell : original->cells()) {
if (design->module(cell->type) == nullptr) {
if (opts.anyeq && cell->type.in(ID($anyseq), ID($anyconst))) {
Cell *gold = import_prim_cell(cell, "_gold");
for (auto &conn : cell->connections())
module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first));
} else {
Cell *gold = import_prim_cell(cell, "_gold");
Cell *gate = import_prim_cell(cell, "_gate");
if (opts.initeq) {
if (cell->type.in(ID($ff), ID($dff), ID($dffe),
ID($dffsr), ID($adff), ID($dlatch), ID($dlatchsr))) {
SigSpec gold_q = gold->getPort(ID::Q);
SigSpec gate_q = gate->getPort(ID::Q);
SigSpec en = module->Initstate(NEW_ID);
SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q);
module->addAssume(NEW_ID, eq, en);
}
}
}
} else {
import_hier_cell(cell);
}
}
for (auto &conn : original->connections()) {
module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold"));
module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate"));
}
if (opts.nop)
return;
CellTypes ct;
ct.setup_internals_eval();
ct.setup_stdcells_eval();
SigMap sigmap(module);
dict<SigBit, SigBit> data_bit_to_eq_net;
dict<Cell*, SigSpec> cell_to_eq_nets;
dict<SigSpec, SigSpec> reduce_db;
dict<SigSpec, SigSpec> invert_db;
for (auto cell : original->cells())
{
if (!ct.cell_known(cell->type))
continue;
for (auto &conn : cell->connections())
{
if (!cell->output(conn.first))
continue;
SigSpec A = import_sig(conn.second, "_gold");
SigSpec B = import_sig(conn.second, "_gate");
SigBit EQ = module->Eq(NEW_ID, A, B);
for (auto bit : sigmap({A, B}))
data_bit_to_eq_net[bit] = EQ;
cell_to_eq_nets[cell].append(EQ);
}
}
for (auto cell : original->cells())
{
if (!ct.cell_known(cell->type))
continue;
bool skip_cell = !cell_to_eq_nets.count(cell);
pool<SigBit> src_eq_bits;
for (auto &conn : cell->connections())
{
if (skip_cell)
break;
if (cell->output(conn.first))
continue;
SigSpec A = import_sig(conn.second, "_gold");
SigSpec B = import_sig(conn.second, "_gate");
for (auto bit : sigmap({A, B})) {
if (data_bit_to_eq_net.count(bit))
src_eq_bits.insert(data_bit_to_eq_net.at(bit));
else
skip_cell = true;
}
}
if (!skip_cell) {
SigSpec antecedent = SigSpec(src_eq_bits);
antecedent.sort_and_unify();
if (GetSize(antecedent) > 1) {
if (reduce_db.count(antecedent) == 0)
reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent);
antecedent = reduce_db.at(antecedent);
}
SigSpec consequent = cell_to_eq_nets.at(cell);
consequent.sort_and_unify();
if (GetSize(consequent) > 1) {
if (reduce_db.count(consequent) == 0)
reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent);
consequent = reduce_db.at(consequent);
}
if (opts.fwd)
module->addAssume(NEW_ID, consequent, antecedent);
if (opts.bwd)
{
if (invert_db.count(antecedent) == 0)
invert_db[antecedent] = module->Not(NEW_ID, antecedent);
if (invert_db.count(consequent) == 0)
invert_db[consequent] = module->Not(NEW_ID, consequent);
module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent));
}
}
}
}
};
struct FmcombinePass : public Pass {
FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" fmcombine [options] module_name gold_cell gate_cell\n");
// log(" fmcombine [options] @gold_cell @gate_cell\n");
log("\n");
log("This pass takes two cells, which are instances of the same module, and replaces\n");
log("them with one instance of a special 'combined' module, that effectively\n");
log("contains two copies of the original module, plus some formal properties.\n");
log("\n");
log("This is useful for formal test benches that check what differences in behavior\n");
log("a slight difference in input causes in a module.\n");
log("\n");
log(" -initeq\n");
log(" Insert assumptions that initially all FFs in both circuits have the\n");
log(" same initial values.\n");
log("\n");
log(" -anyeq\n");
log(" Do not duplicate $anyseq/$anyconst cells.\n");
log("\n");
log(" -fwd\n");
log(" Insert forward hint assumptions into the combined module.\n");
log("\n");
log(" -bwd\n");
log(" Insert backward hint assumptions into the combined module.\n");
log(" (Backward hints are logically equivalend to fordward hits, but\n");
log(" some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n");
log("\n");
log(" -nop\n");
log(" Don't insert hint assumptions into the combined module.\n");
log(" (This should not provide any speedup over the original design, but\n");
log(" strangely sometimes it does.)\n");
log("\n");
log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
opts_t opts;
Module *module = nullptr;
Cell *gold_cell = nullptr;
Cell *gate_cell = nullptr;
log_header(design, "Executing FMCOMBINE pass.\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
// if (args[argidx] == "-o" && argidx+1 < args.size()) {
// filename = args[++argidx];
// continue;
// }
if (args[argidx] == "-initeq") {
opts.initeq = true;
continue;
}
if (args[argidx] == "-anyeq") {
opts.anyeq = true;
continue;
}
if (args[argidx] == "-fwd") {
opts.fwd = true;
continue;
}
if (args[argidx] == "-bwd") {
opts.bwd = true;
continue;
}
if (args[argidx] == "-nop") {
opts.nop = true;
continue;
}
break;
}
if (argidx+2 == args.size())
{
string gold_name = args[argidx++];
string gate_name = args[argidx++];
log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet.");
}
else if (argidx+3 == args.size())
{
IdString module_name = RTLIL::escape_id(args[argidx++]);
IdString gold_name = RTLIL::escape_id(args[argidx++]);
IdString gate_name = RTLIL::escape_id(args[argidx++]);
module = design->module(module_name);
if (module == nullptr)
log_cmd_error("Module %s not found.\n", log_id(module_name));
gold_cell = module->cell(gold_name);
if (gold_cell == nullptr)
log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module));
gate_cell = module->cell(gate_name);
if (gate_cell == nullptr)
log_cmd_error("Gate cell %s not found in module %s.\n", log_id(gate_name), log_id(module));
}
else
{
log_cmd_error("Invalid number of arguments.\n");
}
// extra_args(args, argidx, design);
if (opts.nop && (opts.fwd || opts.bwd))
log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n");
if (!opts.nop && !opts.fwd && !opts.bwd)
opts.fwd = true;
if (gold_cell->type != gate_cell->type)
log_cmd_error("Types of gold and gate cells do not match.\n");
if (!gold_cell->parameters.empty())
log_cmd_error("Gold cell has unresolved instance parameters.\n");
if (!gate_cell->parameters.empty())
log_cmd_error("Gate cell has unresolved instance parameters.\n");
FmcombineWorker worker(design, gold_cell->type, opts);
worker.generate();
IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell)));
Cell *cell = module->addCell(combined_cell_name, worker.combined_type);
cell->attributes = gold_cell->attributes;
cell->add_strpool_attribute(ID::src, gate_cell->get_strpool_attribute(ID::src));
log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell));
for (auto &conn : gold_cell->connections())
cell->setPort(conn.first.str() + "_gold", conn.second);
module->remove(gold_cell);
for (auto &conn : gate_cell->connections())
cell->setPort(conn.first.str() + "_gate", conn.second);
module->remove(gate_cell);
}
} FmcombinePass;
PRIVATE_NAMESPACE_END
<commit_msg>fmcombine: use the master ff cell type list<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct opts_t
{
bool initeq = false;
bool anyeq = false;
bool fwd = false;
bool bwd = false;
bool nop = false;
};
struct FmcombineWorker
{
const opts_t &opts;
Design *design;
Module *original = nullptr;
Module *module = nullptr;
IdString orig_type, combined_type;
FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) :
opts(opts), design(design), original(design->module(orig_type)),
orig_type(orig_type), combined_type(stringf("$fmcombine%s", orig_type.c_str()))
{
}
SigSpec import_sig(SigSpec sig, const string &suffix)
{
SigSpec newsig;
for (auto chunk : sig.chunks()) {
if (chunk.wire != nullptr)
chunk.wire = module->wire(chunk.wire->name.str() + suffix);
newsig.append(chunk);
}
return newsig;
}
Cell *import_prim_cell(Cell *cell, const string &suffix)
{
Cell *c = module->addCell(cell->name.str() + suffix, cell->type);
c->parameters = cell->parameters;
c->attributes = cell->attributes;
for (auto &conn : cell->connections())
c->setPort(conn.first, import_sig(conn.second, suffix));
return c;
}
void import_hier_cell(Cell *cell)
{
if (!cell->parameters.empty())
log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell));
FmcombineWorker sub_worker(design, cell->type, opts);
sub_worker.generate();
Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type);
// c->parameters = cell->parameters;
c->attributes = cell->attributes;
for (auto &conn : cell->connections()) {
c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold"));
c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate"));
}
}
void generate()
{
if (design->module(combined_type)) {
// log("Combined module %s already exists.\n", log_id(combined_type));
return;
}
log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type));
module = design->addModule(combined_type);
for (auto wire : original->wires()) {
module->addWire(wire->name.str() + "_gold", wire);
module->addWire(wire->name.str() + "_gate", wire);
}
module->fixup_ports();
for (auto cell : original->cells()) {
if (design->module(cell->type) == nullptr) {
if (opts.anyeq && cell->type.in(ID($anyseq), ID($anyconst))) {
Cell *gold = import_prim_cell(cell, "_gold");
for (auto &conn : cell->connections())
module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first));
} else {
Cell *gold = import_prim_cell(cell, "_gold");
Cell *gate = import_prim_cell(cell, "_gate");
if (opts.initeq) {
if (RTLIL::builtin_ff_cell_types().count(cell->type)) {
SigSpec gold_q = gold->getPort(ID::Q);
SigSpec gate_q = gate->getPort(ID::Q);
SigSpec en = module->Initstate(NEW_ID);
SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q);
module->addAssume(NEW_ID, eq, en);
}
}
}
} else {
import_hier_cell(cell);
}
}
for (auto &conn : original->connections()) {
module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold"));
module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate"));
}
if (opts.nop)
return;
CellTypes ct;
ct.setup_internals_eval();
ct.setup_stdcells_eval();
SigMap sigmap(module);
dict<SigBit, SigBit> data_bit_to_eq_net;
dict<Cell*, SigSpec> cell_to_eq_nets;
dict<SigSpec, SigSpec> reduce_db;
dict<SigSpec, SigSpec> invert_db;
for (auto cell : original->cells())
{
if (!ct.cell_known(cell->type))
continue;
for (auto &conn : cell->connections())
{
if (!cell->output(conn.first))
continue;
SigSpec A = import_sig(conn.second, "_gold");
SigSpec B = import_sig(conn.second, "_gate");
SigBit EQ = module->Eq(NEW_ID, A, B);
for (auto bit : sigmap({A, B}))
data_bit_to_eq_net[bit] = EQ;
cell_to_eq_nets[cell].append(EQ);
}
}
for (auto cell : original->cells())
{
if (!ct.cell_known(cell->type))
continue;
bool skip_cell = !cell_to_eq_nets.count(cell);
pool<SigBit> src_eq_bits;
for (auto &conn : cell->connections())
{
if (skip_cell)
break;
if (cell->output(conn.first))
continue;
SigSpec A = import_sig(conn.second, "_gold");
SigSpec B = import_sig(conn.second, "_gate");
for (auto bit : sigmap({A, B})) {
if (data_bit_to_eq_net.count(bit))
src_eq_bits.insert(data_bit_to_eq_net.at(bit));
else
skip_cell = true;
}
}
if (!skip_cell) {
SigSpec antecedent = SigSpec(src_eq_bits);
antecedent.sort_and_unify();
if (GetSize(antecedent) > 1) {
if (reduce_db.count(antecedent) == 0)
reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent);
antecedent = reduce_db.at(antecedent);
}
SigSpec consequent = cell_to_eq_nets.at(cell);
consequent.sort_and_unify();
if (GetSize(consequent) > 1) {
if (reduce_db.count(consequent) == 0)
reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent);
consequent = reduce_db.at(consequent);
}
if (opts.fwd)
module->addAssume(NEW_ID, consequent, antecedent);
if (opts.bwd)
{
if (invert_db.count(antecedent) == 0)
invert_db[antecedent] = module->Not(NEW_ID, antecedent);
if (invert_db.count(consequent) == 0)
invert_db[consequent] = module->Not(NEW_ID, consequent);
module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent));
}
}
}
}
};
struct FmcombinePass : public Pass {
FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" fmcombine [options] module_name gold_cell gate_cell\n");
// log(" fmcombine [options] @gold_cell @gate_cell\n");
log("\n");
log("This pass takes two cells, which are instances of the same module, and replaces\n");
log("them with one instance of a special 'combined' module, that effectively\n");
log("contains two copies of the original module, plus some formal properties.\n");
log("\n");
log("This is useful for formal test benches that check what differences in behavior\n");
log("a slight difference in input causes in a module.\n");
log("\n");
log(" -initeq\n");
log(" Insert assumptions that initially all FFs in both circuits have the\n");
log(" same initial values.\n");
log("\n");
log(" -anyeq\n");
log(" Do not duplicate $anyseq/$anyconst cells.\n");
log("\n");
log(" -fwd\n");
log(" Insert forward hint assumptions into the combined module.\n");
log("\n");
log(" -bwd\n");
log(" Insert backward hint assumptions into the combined module.\n");
log(" (Backward hints are logically equivalend to fordward hits, but\n");
log(" some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n");
log("\n");
log(" -nop\n");
log(" Don't insert hint assumptions into the combined module.\n");
log(" (This should not provide any speedup over the original design, but\n");
log(" strangely sometimes it does.)\n");
log("\n");
log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
opts_t opts;
Module *module = nullptr;
Cell *gold_cell = nullptr;
Cell *gate_cell = nullptr;
log_header(design, "Executing FMCOMBINE pass.\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
// if (args[argidx] == "-o" && argidx+1 < args.size()) {
// filename = args[++argidx];
// continue;
// }
if (args[argidx] == "-initeq") {
opts.initeq = true;
continue;
}
if (args[argidx] == "-anyeq") {
opts.anyeq = true;
continue;
}
if (args[argidx] == "-fwd") {
opts.fwd = true;
continue;
}
if (args[argidx] == "-bwd") {
opts.bwd = true;
continue;
}
if (args[argidx] == "-nop") {
opts.nop = true;
continue;
}
break;
}
if (argidx+2 == args.size())
{
string gold_name = args[argidx++];
string gate_name = args[argidx++];
log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet.");
}
else if (argidx+3 == args.size())
{
IdString module_name = RTLIL::escape_id(args[argidx++]);
IdString gold_name = RTLIL::escape_id(args[argidx++]);
IdString gate_name = RTLIL::escape_id(args[argidx++]);
module = design->module(module_name);
if (module == nullptr)
log_cmd_error("Module %s not found.\n", log_id(module_name));
gold_cell = module->cell(gold_name);
if (gold_cell == nullptr)
log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module));
gate_cell = module->cell(gate_name);
if (gate_cell == nullptr)
log_cmd_error("Gate cell %s not found in module %s.\n", log_id(gate_name), log_id(module));
}
else
{
log_cmd_error("Invalid number of arguments.\n");
}
// extra_args(args, argidx, design);
if (opts.nop && (opts.fwd || opts.bwd))
log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n");
if (!opts.nop && !opts.fwd && !opts.bwd)
opts.fwd = true;
if (gold_cell->type != gate_cell->type)
log_cmd_error("Types of gold and gate cells do not match.\n");
if (!gold_cell->parameters.empty())
log_cmd_error("Gold cell has unresolved instance parameters.\n");
if (!gate_cell->parameters.empty())
log_cmd_error("Gate cell has unresolved instance parameters.\n");
FmcombineWorker worker(design, gold_cell->type, opts);
worker.generate();
IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell)));
Cell *cell = module->addCell(combined_cell_name, worker.combined_type);
cell->attributes = gold_cell->attributes;
cell->add_strpool_attribute(ID::src, gate_cell->get_strpool_attribute(ID::src));
log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell));
for (auto &conn : gold_cell->connections())
cell->setPort(conn.first.str() + "_gold", conn.second);
module->remove(gold_cell);
for (auto &conn : gate_cell->connections())
cell->setPort(conn.first.str() + "_gate", conn.second);
module->remove(gate_cell);
}
} FmcombinePass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <ctime>
#include "array_prepare.h"
void prepare_array(pipeline_data& data)
{
srand((unsigned int)time(nullptr));
for (unsigned int i = 0; i < data.array_size; i++)
data.unsorted_array[i] = rand() % (data.max_number + 1 - data.min_number) + data.min_number;
memcpy(data.sorted_array, data.unsorted_array, sizeof(int) * data.array_size);
}<commit_msg>Fixed random array generation.<commit_after>#include <cstdlib>
#include <ctime>
#include "array_prepare.h"
void prepare_array(pipeline_data& data)
{
static bool seeded = false;
if (!seeded)
{
seeded = true;
srand((unsigned int)time(nullptr));
}
for (unsigned int i = 0; i < data.array_size; i++)
data.unsorted_array[i] = rand() % (data.max_number + 1 - data.min_number) + data.min_number;
memcpy(data.sorted_array, data.unsorted_array, sizeof(int) * data.array_size);
}<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "console/console_application.h"
#include "build/version.h"
#include "qt_base/qt_logging.h"
namespace console {
namespace {
const char kActivateWindow[] = "activate_window";
const char kOpenFile[] = "open_file:";
} // namespace
Application::Application(int& argc, char* argv[])
: qt_base::Application(argc, argv)
{
setOrganizationName(QStringLiteral("Aspia"));
setApplicationName(QStringLiteral("Console"));
setApplicationVersion(QStringLiteral(ASPIA_VERSION_STRING));
setAttribute(Qt::AA_DisableWindowContextHelpButton, true);
connect(this, &Application::messageReceived, [this](const QByteArray& message)
{
if (message.startsWith(kActivateWindow))
{
emit windowActivated();
}
else if (message.startsWith(kOpenFile))
{
QString file_path = QString::fromUtf8(message).remove(kOpenFile);
if (file_path.isEmpty())
return;
emit fileOpened(file_path);
}
else
{
LOG(LS_ERROR) << "Unhandled message";
}
});
if (!hasLocale(settings_.locale()))
settings_.setLocale(QStringLiteral(DEFAULT_LOCALE));
setLocale(settings_.locale());
}
// static
Application* Application::instance()
{
return static_cast<Application*>(QApplication::instance());
}
void Application::activateWindow()
{
sendMessage(kActivateWindow);
}
void Application::openFile(const QString& file_path)
{
QByteArray message(kOpenFile);
message.append(file_path.toUtf8());
sendMessage(message);
}
} // namespace console
<commit_msg>Disable "quit at last window closed" for console application.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "console/console_application.h"
#include "build/version.h"
#include "qt_base/qt_logging.h"
namespace console {
namespace {
const char kActivateWindow[] = "activate_window";
const char kOpenFile[] = "open_file:";
} // namespace
Application::Application(int& argc, char* argv[])
: qt_base::Application(argc, argv)
{
setOrganizationName(QStringLiteral("Aspia"));
setApplicationName(QStringLiteral("Console"));
setApplicationVersion(QStringLiteral(ASPIA_VERSION_STRING));
setAttribute(Qt::AA_DisableWindowContextHelpButton, true);
setQuitOnLastWindowClosed(false);
connect(this, &Application::messageReceived, [this](const QByteArray& message)
{
if (message.startsWith(kActivateWindow))
{
emit windowActivated();
}
else if (message.startsWith(kOpenFile))
{
QString file_path = QString::fromUtf8(message).remove(kOpenFile);
if (file_path.isEmpty())
return;
emit fileOpened(file_path);
}
else
{
LOG(LS_ERROR) << "Unhandled message";
}
});
if (!hasLocale(settings_.locale()))
settings_.setLocale(QStringLiteral(DEFAULT_LOCALE));
setLocale(settings_.locale());
}
// static
Application* Application::instance()
{
return static_cast<Application*>(QApplication::instance());
}
void Application::activateWindow()
{
sendMessage(kActivateWindow);
}
void Application::openFile(const QString& file_path)
{
QByteArray message(kOpenFile);
message.append(file_path.toUtf8());
sendMessage(message);
}
} // namespace console
<|endoftext|> |
<commit_before>
#include <cppexpose/json/JSON.h>
#include <iostream>
#include <cppassist/string/conversion.h>
#include <cppassist/logging/logging.h>
#include <cppexpose/base/Tokenizer.h>
#include <cppexpose/variant/Variant.h>
using namespace cppassist;
using namespace cppexpose;
namespace
{
bool readValue(Variant & value, Tokenizer::Token & token, Tokenizer & tokenizer);
bool readArray(Variant & root, Tokenizer & tokenizer);
bool readObject(Variant & root, Tokenizer & tokenizer);
const char * const g_hexdig = "0123456789ABCDEF";
std::string escapeString(const std::string & in)
{
std::string out = "";
for (unsigned char c : in)
{
if (c >= ' ' && c <= '~' && c != '\\' && c != '"')
{
out.append(1, c);
}
else
{
out = out + '\\';
switch(c) {
case '"': out = out + "\""; break;
case '\\': out = out + "\\"; break;
case '\t': out = out + "t"; break;
case '\r': out = out + "r"; break;
case '\n': out = out + "n"; break;
default:
out = out + "x";
out.append(1, g_hexdig[c >> 4]);
out.append(1, g_hexdig[c & 0xF]);
break;
}
}
}
return out;
}
std::string jsonStringify(const Variant & root, bool beautify, const std::string & indent)
{
// Variant is an object
if (root.isVariantMap())
{
// Quick output: {} if empty
if (root.asMap()->empty()) return "{}";
// Begin output
std::string json = "{"; // [TODO] maybe a stringstream can be more performant
if (beautify)
json += "\n";
// Add all variables
bool first = true;
for (auto it : *root.asMap())
{
// Add separator (",")
if (!first)
json += beautify ? ",\n" : ",";
else
first = false;
// Get variable
const std::string & name = it.first;
const cppexpose::Variant & var = it.second;
// Get value
std::string value;
if (var.isVariantMap() || var.isVariantArray())
{
value = jsonStringify(var, beautify, indent + " ");
}
else if (var.isNull())
{
value = "null";
}
else
{
value = escapeString(jsonStringify(var, beautify, ""));
if (var.hasType<std::string>())
{
value = "\"" + value + "\"";
}
}
// Add value to JSON
json += (beautify ? (indent + " \"" + name + "\": " + value) : ("\"" + name + "\":" + value));
}
// Finish JSON
json += (beautify ? "\n" + indent + "}" : "}");
return json;
}
// Variant is an array
else if (root.isVariantArray())
{
// Quick output: [] if empty
if (root.asArray()->empty())
return "[]";
// Begin output
std::string json = "["; // [TODO] maybe a stringstream can be more performant
if (beautify) json += "\n";
// Add all elements
bool first = true;
for (const cppexpose::Variant & var : *root.asArray())
{
// Add separator (",")
if (!first)
json += beautify ? ",\n" : ",";
else
first = false;
// Get value
std::string value;
if (var.isVariantMap() || var.isVariantArray())
{
value = jsonStringify(var, beautify, indent + " ");
}
else if (var.isNull())
{
value = "null";
}
else
{
value = escapeString(jsonStringify(var, beautify, ""));
if (var.hasType<std::string>())
{
value = "\"" + value + "\"";
}
}
// Add value to JSON
json += (beautify ? (indent + " " + value) : value);
}
// Finish JSON
json += (beautify ? "\n" + indent + "]" : "]");
return json;
}
// Primitive data types
else if (root.canConvert<std::string>())
{
return root.toString();
}
// Invalid type for JSON output
else
{
return "null";
}
}
Tokenizer createJSONTokenizer()
{
// Create tokenizer for JSON
Tokenizer tokenizer;
tokenizer.setOptions(
Tokenizer::OptionParseStrings
| Tokenizer::OptionParseNumber
| Tokenizer::OptionParseBoolean
| Tokenizer::OptionParseNull
| Tokenizer::OptionCStyleComments
| Tokenizer::OptionCppStyleComments
);
tokenizer.setQuotationMarks("\"");
tokenizer.setSingleCharacters("{}[],:");
return tokenizer;
}
bool readValue(Variant & value, Tokenizer::Token & token, Tokenizer & tokenizer)
{
if (token.content == "{")
{
return readObject(value, tokenizer);
}
else if (token.content == "[")
{
return readArray(value, tokenizer);
}
else if (token.type == Tokenizer::TokenString ||
token.type == Tokenizer::TokenNumber ||
token.type == Tokenizer::TokenBoolean ||
token.type == Tokenizer::TokenNull)
{
value = token.value;
return true;
}
else
{
cppassist::critical()
<< "Syntax error: value, object or array expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
bool readArray(Variant & root, Tokenizer & tokenizer)
{
// Create array
root = Variant::array();
// Read next token
Tokenizer::Token token = tokenizer.parseToken();
// Empty array?
if (token.content == "]")
{
return true;
}
// Read array values
while (true)
{
// Add new value to array
root.asArray()->push_back(Variant());
Variant & value = (*root.asArray())[root.asArray()->size() - 1];
// Read value
if (!readValue(value, token, tokenizer))
{
return false;
}
// Read next token
token = tokenizer.parseToken();
// Expect ',' or ']'
if (token.content == ",")
{
// Read next token
token = tokenizer.parseToken();
}
else if (token.content == "]")
{
// End of array
return true;
}
else
{
// Unexpected token
cppassist::critical()
<< "Unexpected token in array: '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
// Couldn't actually happen but makes compilers happy
return false;
}
bool readObject(Variant & root, Tokenizer & tokenizer)
{
// Create object
root = Variant::map();
// Read next token
Tokenizer::Token token = tokenizer.parseToken();
// Empty object?
if (token.content == "}")
{
return true;
}
// Read object members
while (true)
{
// Expect name of field
if (token.type != Tokenizer::TokenString)
{
cppassist::critical()
<< "Syntax error: object member name expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
std::string name = token.value.toString();
// Read next token
token = tokenizer.parseToken();
// Expect ':'
if (token.content != ":")
{
cppassist::critical()
<< "Syntax error: ':' expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
// Read next token
token = tokenizer.parseToken();
// Add new value to object
(*root.asMap())[name] = Variant();
Variant & value = (*root.asMap())[name];
// Read value
if (!readValue(value, token, tokenizer))
{
return false;
}
// Read next token
token = tokenizer.parseToken();
// Expect ',' or '}'
if (token.content == ",")
{
// Read next token
token = tokenizer.parseToken();
}
else if (token.content == "}")
{
// End of object
return true;
}
else
{
// Unexpected token
cppassist::critical()
<< "Unexpected token in object: '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
// Couldn't actually happen but makes compilers happy
return false;
}
bool readDocument(Variant & root, Tokenizer & tokenizer)
{
// The first value in a document must be either an object or an array
Tokenizer::Token token = tokenizer.parseToken();
if (token.content == "{")
{
return readObject(root, tokenizer);
}
else if (token.content == "[")
{
return readArray(root, tokenizer);
}
else
{
cppassist::critical()
<< "A valid JSON document must be either an array or an object value."
<< std::endl;
return false;
}
}
} // namespace
namespace cppexpose
{
std::string JSON::stringify(const Variant & root, JSON::OutputMode outputMode)
{
return jsonStringify(root, outputMode == Beautify, "");
}
bool JSON::load(Variant & root, const std::string & filename)
{
auto tokenizer = createJSONTokenizer();
// Load file
if (!tokenizer.loadDocument(filename))
{
return false;
}
// Begin parsing
return readDocument(root, tokenizer);
}
bool JSON::parse(Variant & root, const std::string & document)
{
auto tokenizer = createJSONTokenizer();
// Set document
tokenizer.setDocument(document);
// Begin parsing
return readDocument(root, tokenizer);
}
} // namespace cppexpose
<commit_msg>Rewrite JSON.stringify() to internally use streams<commit_after>
#include <cppexpose/json/JSON.h>
#include <iostream>
#include <cppassist/string/conversion.h>
#include <cppassist/logging/logging.h>
#include <cppexpose/base/Tokenizer.h>
#include <cppexpose/variant/Variant.h>
using namespace cppassist;
using namespace cppexpose;
namespace
{
bool readValue(Variant & value, Tokenizer::Token & token, Tokenizer & tokenizer);
bool readArray(Variant & root, Tokenizer & tokenizer);
bool readObject(Variant & root, Tokenizer & tokenizer);
const char * const g_hexdig = "0123456789ABCDEF";
std::string escapeString(const std::string & in)
{
std::string out = "";
for (unsigned char c : in)
{
if (c >= ' ' && c <= '~' && c != '\\' && c != '"')
{
out.append(1, c);
}
else
{
out = out + '\\';
switch(c) {
case '"': out = out + "\""; break;
case '\\': out = out + "\\"; break;
case '\t': out = out + "t"; break;
case '\r': out = out + "r"; break;
case '\n': out = out + "n"; break;
default:
out = out + "x";
out.append(1, g_hexdig[c >> 4]);
out.append(1, g_hexdig[c & 0xF]);
break;
}
}
}
return out;
}
std::ostream & jsonStringify(std::ostream & stream, const Variant & root, bool beautify, const std::string & indent)
{
// Variant is an object
if (root.isVariantMap())
{
// Quick output: {} if empty
if (root.asMap()->empty()){
stream << "{}";
return stream;
}
// Begin output
stream << "{";
if (beautify)
stream << "\n";
// Add all variables
bool first = true;
for (auto it : *root.asMap())
{
// Add separator (",")
if (!first)
stream << (beautify ? ",\n" : ",");
else
first = false;
// Get variable
const std::string & name = it.first;
const cppexpose::Variant & var = it.second;
// Get value
std::stringstream value;
if (var.isVariantMap() || var.isVariantArray())
{
jsonStringify(value, var, beautify, indent + " ");
}
else if (var.isNull())
{
value << "null";
}
else
{
std::stringstream unescaped;
jsonStringify(unescaped, var, beautify, "");
auto escaped = escapeString(unescaped.str());
if (var.hasType<std::string>())
value << "\"" << escaped << "\"";
else
value << escaped;
}
// Add value to JSON
stream << (beautify ? (indent + " \"" + name + "\": " + value.str()) : ("\"" + name + "\":" + value.str()));
}
// Finish JSON
stream << (beautify ? "\n" + indent + "}" : "}");
return stream;
}
// Variant is an array
else if (root.isVariantArray())
{
// Quick output: [] if empty
if (root.asArray()->empty())
{
stream << "[]";
return stream;
}
// Begin output
stream << "[";
if (beautify) stream << "\n";
// Add all elements
bool first = true;
for (const cppexpose::Variant & var : *root.asArray())
{
// Add separator (",")
if (!first)
stream << (beautify ? ",\n" : ",");
else
first = false;
// Get value
std::stringstream value;
if (var.isVariantMap() || var.isVariantArray())
{
jsonStringify(value, var, beautify, indent + " ");
}
else if (var.isNull())
{
value << "null";
}
else
{
std::stringstream unescaped;
jsonStringify(unescaped, var, beautify, "");
auto escaped = escapeString(unescaped.str());
if (var.hasType<std::string>())
value << "\"" << escaped << "\"";
else
value << escaped;
}
// Add value to JSON
stream << (beautify ? (indent + " " + value.str()) : value.str());
}
// Finish JSON
stream << (beautify ? "\n" + indent + "]" : "]");
return stream;
}
// Primitive data types
else if (root.canConvert<std::string>())
{
stream << root.toString();
return stream;
}
// Invalid type for JSON output
else
{
stream << "null";
return stream;
}
}
Tokenizer createJSONTokenizer()
{
// Create tokenizer for JSON
Tokenizer tokenizer;
tokenizer.setOptions(
Tokenizer::OptionParseStrings
| Tokenizer::OptionParseNumber
| Tokenizer::OptionParseBoolean
| Tokenizer::OptionParseNull
| Tokenizer::OptionCStyleComments
| Tokenizer::OptionCppStyleComments
);
tokenizer.setQuotationMarks("\"");
tokenizer.setSingleCharacters("{}[],:");
return tokenizer;
}
bool readValue(Variant & value, Tokenizer::Token & token, Tokenizer & tokenizer)
{
if (token.content == "{")
{
return readObject(value, tokenizer);
}
else if (token.content == "[")
{
return readArray(value, tokenizer);
}
else if (token.type == Tokenizer::TokenString ||
token.type == Tokenizer::TokenNumber ||
token.type == Tokenizer::TokenBoolean ||
token.type == Tokenizer::TokenNull)
{
value = token.value;
return true;
}
else
{
cppassist::critical()
<< "Syntax error: value, object or array expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
bool readArray(Variant & root, Tokenizer & tokenizer)
{
// Create array
root = Variant::array();
// Read next token
Tokenizer::Token token = tokenizer.parseToken();
// Empty array?
if (token.content == "]")
{
return true;
}
// Read array values
while (true)
{
// Add new value to array
root.asArray()->push_back(Variant());
Variant & value = (*root.asArray())[root.asArray()->size() - 1];
// Read value
if (!readValue(value, token, tokenizer))
{
return false;
}
// Read next token
token = tokenizer.parseToken();
// Expect ',' or ']'
if (token.content == ",")
{
// Read next token
token = tokenizer.parseToken();
}
else if (token.content == "]")
{
// End of array
return true;
}
else
{
// Unexpected token
cppassist::critical()
<< "Unexpected token in array: '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
// Couldn't actually happen but makes compilers happy
return false;
}
bool readObject(Variant & root, Tokenizer & tokenizer)
{
// Create object
root = Variant::map();
// Read next token
Tokenizer::Token token = tokenizer.parseToken();
// Empty object?
if (token.content == "}")
{
return true;
}
// Read object members
while (true)
{
// Expect name of field
if (token.type != Tokenizer::TokenString)
{
cppassist::critical()
<< "Syntax error: object member name expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
std::string name = token.value.toString();
// Read next token
token = tokenizer.parseToken();
// Expect ':'
if (token.content != ":")
{
cppassist::critical()
<< "Syntax error: ':' expected. Found '"
<< token.content
<< "'"
<< std::endl;
return false;
}
// Read next token
token = tokenizer.parseToken();
// Add new value to object
(*root.asMap())[name] = Variant();
Variant & value = (*root.asMap())[name];
// Read value
if (!readValue(value, token, tokenizer))
{
return false;
}
// Read next token
token = tokenizer.parseToken();
// Expect ',' or '}'
if (token.content == ",")
{
// Read next token
token = tokenizer.parseToken();
}
else if (token.content == "}")
{
// End of object
return true;
}
else
{
// Unexpected token
cppassist::critical()
<< "Unexpected token in object: '"
<< token.content
<< "'"
<< std::endl;
return false;
}
}
// Couldn't actually happen but makes compilers happy
return false;
}
bool readDocument(Variant & root, Tokenizer & tokenizer)
{
// The first value in a document must be either an object or an array
Tokenizer::Token token = tokenizer.parseToken();
if (token.content == "{")
{
return readObject(root, tokenizer);
}
else if (token.content == "[")
{
return readArray(root, tokenizer);
}
else
{
cppassist::critical()
<< "A valid JSON document must be either an array or an object value."
<< std::endl;
return false;
}
}
} // namespace
namespace cppexpose
{
std::string JSON::stringify(const Variant & root, JSON::OutputMode outputMode)
{
std::stringstream stream;
jsonStringify(stream, root, outputMode == Beautify, "");
return stream.str();
}
bool JSON::load(Variant & root, const std::string & filename)
{
auto tokenizer = createJSONTokenizer();
// Load file
if (!tokenizer.loadDocument(filename))
{
return false;
}
// Begin parsing
return readDocument(root, tokenizer);
}
bool JSON::parse(Variant & root, const std::string & document)
{
auto tokenizer = createJSONTokenizer();
// Set document
tokenizer.setDocument(document);
// Begin parsing
return readDocument(root, tokenizer);
}
} // namespace cppexpose
<|endoftext|> |
<commit_before>/*
* HashUil.cpp
*
* Created on: 30 Aug 2013
* Author: nicholas
*/
#include <boost/program_options.hpp>
#include <cstdio>
namespace po = boost::program_options;
using namespace std;
int main(int argc, char* argv[]) {
po::options_description desc = po::options_description("Allowed options");
desc.add_options()
("help", "Display this help message")
("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list")
("prune", "Remove non-existing file paths from the database")
("path", po::value<vector<string> >()->multitoken(), "Paths to process")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help") > 0) {
cout << desc << "\n";
exit(0);
}else if(vm.count("path") == 0){
cout << "No paths given, aborting.\n";
exit(1);
}else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){
cout << "No operation selected, aborting.\n";
exit(2);
}
if(vm.count("filter")){
cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n";
}
if(vm.count("prune")) {
cout << "Pruning database.\n";
}
// cout << "Folders to process:\n" << vm["path"].as<vector<string> >() << "\n";
// workaround for printing paths
cout << "Folders to process:\n";
vector<string> paths = vm["path"].as<vector<string> >();
for(vector<string>::iterator ite = paths.begin(); ite != paths.end(); ++ite) {
cout << *ite << "\n";
}
}
<commit_msg>Added positional options for folders<commit_after>/*
* HashUil.cpp
*
* Created on: 30 Aug 2013
* Author: nicholas
*/
#include <boost/program_options.hpp>
#include <cstdio>
namespace po = boost::program_options;
using namespace std;
int main(int argc, char* argv[]) {
po::options_description desc = po::options_description("Allowed options");
po::positional_options_description pos;
pos.add("path", -1);
desc.add_options()
("help", "Display this help message")
("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list")
("prune", "Remove non-existing file paths from the database")
("path", po::value<vector<string> >()->multitoken(), "Paths to process")
;
po::variables_map vm;
po::store(po::command_line_parser(argc,argv).options(desc).positional(pos).run(), vm);
po::notify(vm);
if(vm.count("help") > 0) {
cout << desc << "\n";
exit(0);
}else if(vm.count("path") == 0){
cout << "No paths given, aborting.\n";
exit(1);
}else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){
cout << "No operation selected, aborting.\n";
exit(2);
}
if(vm.count("filter")){
cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n";
}
if(vm.count("prune")) {
cout << "Pruning database.\n";
}
// cout << "Folders to process:\n" << vm["path"].as<vector<string> >() << "\n";
// workaround for printing paths
cout << "Folders to process:\n";
vector<string> paths = vm["path"].as<vector<string> >();
for(vector<string>::iterator ite = paths.begin(); ite != paths.end(); ++ite) {
cout << *ite << "\n";
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/common/stat_logger.hpp
*
* Logger for Stat-Lines, which creates basic JSON lines
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_COMMON_STAT_LOGGER_HEADER
#define THRILL_COMMON_STAT_LOGGER_HEADER
#include <thrill/api/context.hpp>
#include <thrill/common/logger.hpp>
#include <iostream>
#include <string>
#include <type_traits>
namespace thrill {
namespace common {
static const bool stats_enabled = true;
template <bool Enabled>
class StatLogger
{ };
template <>
class StatLogger<true>
{
protected:
//! collector stream
std::basic_ostringstream<
char, std::char_traits<char>, LoggerAllocator<char> > oss_;
size_t elements_ = 0;
public:
StatLogger(Context& ctx) {
oss_ << "{\"WorkerID\":" << ctx.my_rank();
elements_ = 2;
}
StatLogger() {
oss_ << "{";
}
//! output and escape std::string
StatLogger& operator << (const std::string& str) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
oss_ << "\"";
// from: http://stackoverflow.com/a/7725289
for (auto iter = str.begin(); iter != str.end(); iter++) {
switch (*iter) {
case '\\': oss_ << "\\\\";
break;
case '"': oss_ << "\\\"";
break;
case '/': oss_ << "\\/";
break;
case '\b': oss_ << "\\b";
break;
case '\f': oss_ << "\\f";
break;
case '\n': oss_ << "\\n";
break;
case '\r': oss_ << "\\r";
break;
case '\t': oss_ << "\\t";
break;
default: oss_ << *iter;
break;
}
}
elements_++;
oss_ << "\"";
return *this;
}
//! output any type, including io manipulators
template <typename AnyType>
StatLogger& operator << (const AnyType& at) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
elements_++;
if (std::is_integral<AnyType>::value || std::is_floating_point<AnyType>::value) {
oss_ << at;
}
else if (std::is_same<AnyType, bool>::value) {
if (at) {
oss_ << "true";
}
else {
oss_ << "false";
}
}
else {
oss_ << "\"" << at << "\"";
}
return *this;
}
//! destructor: output a } and a newline
~StatLogger() {
assert(elements_ % 2 == 0);
oss_ << "}\n";
std::cout << oss_.str();
}
};
template <>
class StatLogger<false>
{
public:
template <typename AnyType>
StatLogger& operator << (const AnyType&) {
return *this;
}
};
#define STAT_NO_RANK ::thrill::common::StatLogger<::thrill::common::stats_enabled>()
//! Creates a common::StatLogger with {"WorkerID":my rank in the beginning
#define STAT(ctx) ::thrill::common::StatLogger<::thrill::common::stats_enabled>(ctx)
} // namespace common
} // namespace thrill
#endif // !THRILL_COMMON_STAT_LOGGER_HEADER
/******************************************************************************/
<commit_msg>STATC command to output stats with a context called context_<commit_after>/*******************************************************************************
* thrill/common/stat_logger.hpp
*
* Logger for Stat-Lines, which creates basic JSON lines
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_COMMON_STAT_LOGGER_HEADER
#define THRILL_COMMON_STAT_LOGGER_HEADER
#include <thrill/api/context.hpp>
#include <thrill/common/logger.hpp>
#include <iostream>
#include <string>
#include <type_traits>
namespace thrill {
namespace common {
static const bool stats_enabled = true;
template <bool Enabled>
class StatLogger
{ };
template <>
class StatLogger<true>
{
protected:
//! collector stream
std::basic_ostringstream<
char, std::char_traits<char>, LoggerAllocator<char> > oss_;
size_t elements_ = 0;
public:
StatLogger(Context& ctx) {
oss_ << "{\"WorkerID\":" << ctx.my_rank();
elements_ = 2;
}
StatLogger() {
oss_ << "{";
}
//! output and escape std::string
StatLogger& operator << (const std::string& str) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
oss_ << "\"";
// from: http://stackoverflow.com/a/7725289
for (auto iter = str.begin(); iter != str.end(); iter++) {
switch (*iter) {
case '\\': oss_ << "\\\\";
break;
case '"': oss_ << "\\\"";
break;
case '/': oss_ << "\\/";
break;
case '\b': oss_ << "\\b";
break;
case '\f': oss_ << "\\f";
break;
case '\n': oss_ << "\\n";
break;
case '\r': oss_ << "\\r";
break;
case '\t': oss_ << "\\t";
break;
default: oss_ << *iter;
break;
}
}
elements_++;
oss_ << "\"";
return *this;
}
//! output any type, including io manipulators
template <typename AnyType>
StatLogger& operator << (const AnyType& at) {
if (elements_ > 0) {
if (elements_ % 2 == 0) {
oss_ << ",";
}
else {
oss_ << ":";
}
}
elements_++;
if (std::is_integral<AnyType>::value || std::is_floating_point<AnyType>::value) {
oss_ << at;
}
else if (std::is_same<AnyType, bool>::value) {
if (at) {
oss_ << "true";
}
else {
oss_ << "false";
}
}
else {
oss_ << "\"" << at << "\"";
}
return *this;
}
//! destructor: output a } and a newline
~StatLogger() {
assert(elements_ % 2 == 0);
oss_ << "}\n";
std::cout << oss_.str();
}
};
template <>
class StatLogger<false>
{
public:
template <typename AnyType>
StatLogger& operator << (const AnyType&) {
return *this;
}
};
#define STAT_NO_RANK ::thrill::common::StatLogger<::thrill::common::stats_enabled>()
//! Creates a common::StatLogger with {"WorkerID":my rank in the beginning
#define STAT(ctx) ::thrill::common::StatLogger<::thrill::common::stats_enabled>(ctx)
#define STATC ::thrill::common::StatLogger<::thrill::common::stats_enabled>(context_)
} // namespace common
} // namespace thrill
#endif // !THRILL_COMMON_STAT_LOGGER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>/*
Generic Console Output Support
Copyright (C) 1998-2001 by Jorrit Tyberghein
Copyright (c) 2004-2005 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <stdio.h>
#include "cssysdef.h"
#include "csgeom/math.h"
#include "csutil/ansiparse.h"
#include "csutil/csstring.h"
#include "csutil/csuctransform.h"
#include "csutil/sysfunc.h"
// Replacement for printf(); exact same prototype/functionality as printf()
int csPrintf (char const* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csPrintfV (str, args);
va_end (args);
return rc;
}
static int cs_fputsn (FILE* file, const char* str, size_t len)
{
size_t wstrSize = len + 1;
CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize);
csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len);
int n = 0;
const wchar_t* wcsPtr = wstr;
#if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \
&& defined(CS_HAVE_WCSNRTOMBS)
if (fwide (file, 0) > 0)
{
return fputws (wstr, file);
}
else
{
size_t numwcs = wcslen (wstr);
const wchar_t* wcsEnd = wcsPtr + numwcs;
mbstate_t oldstate, mbs;
memset (&mbs, 0, sizeof (mbs));
char mbstr[64];
size_t mbslen;
while (numwcs > 0)
{
memset (mbstr, 0, sizeof (mbstr));
memcpy (&oldstate, &mbs, sizeof (mbs));
mbslen = wcsnrtombs (mbstr, &wcsPtr, numwcs, sizeof (mbstr) - 1, &mbs);
if (mbslen == (size_t)-1)
{
if (errno == EILSEQ)
{
/* At least on OS/X wcsPtr is not updated in case of a conversion
error, so kludge around it */
if (mbstr[0] == 0)
{
// Catch char that couldn't be encoded, print ? instead
if (fputc ('?', file) == EOF) return EOF;
if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr))
{
wcsPtr++;
if (CS_UC_IS_LOW_SURROGATE (*wcsPtr))
wcsPtr++;
}
else
wcsPtr++;
numwcs = wcsEnd - wcsPtr;
}
else
{
// Try converting only a substring
numwcs = csMin (numwcs-1, strlen (mbstr));
memcpy (&mbs, &oldstate, sizeof (mbs));
}
continue;
}
break;
}
else
{
if (fputs (mbstr, file) == EOF) return EOF;
numwcs = (wcsPtr == 0) ? 0 : wcsEnd - wcsPtr;
}
}
return (int)len;
}
#endif
// Use a cheap Wide-to-ASCII conversion.
const wchar_t* ch = wcsPtr;
while (len-- > 0)
{
if (*ch < 0x80)
{
if (fputc ((char)*ch, file) == EOF) return EOF;
n++;
}
else
{
if (fputc ('?', file) == EOF) return EOF;
n++;
}
ch++;
}
return n;
}
static int csFPutStr (FILE* file, const char* str)
{
bool isTTY = isatty (fileno (file));
int ret = 0;
size_t ansiCommandLen;
csAnsiParser::CommandClass cmdClass;
size_t textLen;
// Check for ANSI codes
while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen))
{
int rc;
if (isTTY && (cmdClass != csAnsiParser::classNone)
&& (cmdClass != csAnsiParser::classUnknown))
{
// Only let known codes through
rc = cs_fputsn (file, str, ansiCommandLen);
if (rc == EOF)
return EOF;
ret += rc;
}
if (textLen > 0)
{
rc = cs_fputsn (file, str + ansiCommandLen, textLen);
if (rc == EOF)
return EOF;
ret += rc;
}
str += ansiCommandLen + textLen;
}
return ret;
}
// Replacement for vprintf()
int csPrintfV(char const* str, va_list args)
{
csString temp;
temp.FormatV (str, args);
return csFPutStr (stdout, temp);
}
int csFPrintf (FILE* file, const char* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csFPrintfV (file, str, args);
va_end (args);
return rc;
}
int csFPrintfV (FILE* file, const char* str, va_list args)
{
csString temp;
temp.FormatV (str, args);
return csFPutStr (file, temp);
}
int csPrintfErrV (const char* str, va_list arg)
{
int rc = csFPrintfV (stderr, str, arg);
fflush (stderr);
return rc;
}
int csPrintfErr (const char* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csFPrintfV (stderr, str, args);
va_end (args);
return rc;
}
<commit_msg>Improve output when a character is encountered that can't be converted to multibyte characters for output<commit_after>/*
Generic Console Output Support
Copyright (C) 1998-2001 by Jorrit Tyberghein
Copyright (c) 2004-2005 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <stdio.h>
#include "cssysdef.h"
#include "csgeom/math.h"
#include "csutil/ansiparse.h"
#include "csutil/csstring.h"
#include "csutil/csuctransform.h"
#include "csutil/sysfunc.h"
// Replacement for printf(); exact same prototype/functionality as printf()
int csPrintf (char const* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csPrintfV (str, args);
va_end (args);
return rc;
}
static int cs_fputsn (FILE* file, const char* str, size_t len)
{
size_t wstrSize = len + 1;
CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize);
csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len);
int n = 0;
const wchar_t* wcsPtr = wstr;
#if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \
&& defined(CS_HAVE_WCSNRTOMBS)
if (fwide (file, 0) > 0)
{
return fputws (wstr, file);
}
else
{
size_t numwcs = wcslen (wstr);
const wchar_t* wcsEnd = wcsPtr + numwcs;
mbstate_t oldstate, mbs;
memset (&mbs, 0, sizeof (mbs));
char mbstr[64];
size_t mbslen;
while (numwcs > 0)
{
memset (mbstr, 0, sizeof (mbstr));
memcpy (&oldstate, &mbs, sizeof (mbs));
const wchar_t* wcsOld = wcsPtr;
mbslen = wcsnrtombs (mbstr, &wcsPtr, numwcs, sizeof (mbstr) - 1, &mbs);
if (mbslen == (size_t)-1)
{
if (errno == EILSEQ)
{
/* At least on OS/X wcsPtr is not updated in case of a conversion
error, so kludge around it */
if (mbstr[0] == 0)
{
// Catch char that couldn't be encoded, print ? instead
if (fputc ('?', file) == EOF) return EOF;
if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr))
{
wcsPtr++;
if (CS_UC_IS_LOW_SURROGATE (*wcsPtr))
wcsPtr++;
}
else
wcsPtr++;
numwcs = wcsEnd - wcsPtr;
}
else
{
// Try converting only a substring
numwcs = csMin (numwcs-1, strlen (mbstr));
memcpy (&mbs, &oldstate, sizeof (mbs));
wcsPtr = wcsOld;
}
continue;
}
break;
}
else
{
if (fputs (mbstr, file) == EOF) return EOF;
numwcs = (wcsPtr == 0) ? 0 : wcsEnd - wcsPtr;
}
}
return (int)len;
}
#endif
// Use a cheap Wide-to-ASCII conversion.
const wchar_t* ch = wcsPtr;
while (len-- > 0)
{
if (*ch < 0x80)
{
if (fputc ((char)*ch, file) == EOF) return EOF;
n++;
}
else
{
if (fputc ('?', file) == EOF) return EOF;
n++;
}
ch++;
}
return n;
}
static int csFPutStr (FILE* file, const char* str)
{
bool isTTY = isatty (fileno (file));
int ret = 0;
size_t ansiCommandLen;
csAnsiParser::CommandClass cmdClass;
size_t textLen;
// Check for ANSI codes
while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen))
{
int rc;
if (isTTY && (cmdClass != csAnsiParser::classNone)
&& (cmdClass != csAnsiParser::classUnknown))
{
// Only let known codes through
rc = cs_fputsn (file, str, ansiCommandLen);
if (rc == EOF)
return EOF;
ret += rc;
}
if (textLen > 0)
{
rc = cs_fputsn (file, str + ansiCommandLen, textLen);
if (rc == EOF)
return EOF;
ret += rc;
}
str += ansiCommandLen + textLen;
}
return ret;
}
// Replacement for vprintf()
int csPrintfV(char const* str, va_list args)
{
csString temp;
temp.FormatV (str, args);
return csFPutStr (stdout, temp);
}
int csFPrintf (FILE* file, const char* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csFPrintfV (file, str, args);
va_end (args);
return rc;
}
int csFPrintfV (FILE* file, const char* str, va_list args)
{
csString temp;
temp.FormatV (str, args);
return csFPutStr (file, temp);
}
int csPrintfErrV (const char* str, va_list arg)
{
int rc = csFPrintfV (stderr, str, arg);
fflush (stderr);
return rc;
}
int csPrintfErr (const char* str, ...)
{
va_list args;
va_start (args, str);
int const rc = csFPrintfV (stderr, str, args);
va_end (args);
return rc;
}
<|endoftext|> |
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "gui-precomp.h" // Precompiled headers
#include <mrpt/gui/CGlCanvasBase.h>
#include <mrpt/opengl/opengl_api.h>
#include <mrpt/system/CTicTac.h>
#if MRPT_HAS_OPENGL_GLUT
#ifdef _WIN32
// Windows:
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#ifdef HAVE_FREEGLUT_EXT_H
#include <GL/freeglut_ext.h>
#endif
#endif
#endif // MRPT_HAS_OPENGL_GLUT
using namespace mrpt;
using namespace mrpt::gui;
using namespace mrpt::opengl;
using namespace std;
using mrpt::system::CTicTac;
float CGlCanvasBase::SENSIBILITY_DEG_PER_PIXEL = 0.1f;
CGlCanvasBase::~CGlCanvasBase()
{
// Ensure all OpenGL resources are freed before the opengl context is gone:
if (m_openGLScene) m_openGLScene->unloadShaders();
}
void CGlCanvasBase::setMinimumZoom(float zoom) { m_minZoom = zoom; }
void CGlCanvasBase::setMaximumZoom(float zoom) { m_maxZoom = zoom; }
void CGlCanvasBase::setMousePos(int x, int y)
{
m_mouseClickX = x;
m_mouseClickY = y;
}
void CGlCanvasBase::setMouseClicked(bool is) { mouseClicked = is; }
void CGlCanvasBase::updateZoom(CamaraParams& params, int x, int y) const
{
float zoom = params.cameraZoomDistance * exp(0.01f * (y - m_mouseClickY));
if (zoom <= m_minZoom || (m_maxZoom != -1.0f && m_maxZoom <= zoom)) return;
params.cameraZoomDistance = zoom;
if (params.cameraZoomDistance < 0.01f) params.cameraZoomDistance = 0.01f;
float Az = -0.05f * (x - m_mouseClickX);
float D = 0.001f * params.cameraZoomDistance;
params.cameraPointingZ += D * Az;
}
void CGlCanvasBase::updateZoom(CamaraParams& params, float delta) const
{
float zoom = params.cameraZoomDistance * (1 - 0.03f * (delta / 120.0f));
if (zoom <= m_minZoom || (m_maxZoom != -1.0f && m_maxZoom <= zoom)) return;
params.cameraZoomDistance = zoom;
}
void CGlCanvasBase::updateRotate(CamaraParams& params, int x, int y) const
{
const float dis = max(0.01f, (params.cameraZoomDistance));
float eye_x =
params.cameraPointingX + dis * cos(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
float eye_y =
params.cameraPointingY + dis * sin(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
float eye_z =
params.cameraPointingZ + dis * sin(DEG2RAD(params.cameraElevationDeg));
// Orbit camera:
float A_AzimuthDeg = -SENSIBILITY_DEG_PER_PIXEL * (x - m_mouseClickX);
params.cameraAzimuthDeg += A_AzimuthDeg;
float A_ElevationDeg = SENSIBILITY_DEG_PER_PIXEL * (y - m_mouseClickY);
params.setElevationDeg(params.cameraElevationDeg + A_ElevationDeg);
// Move cameraPointing pos:
params.cameraPointingX =
eye_x - dis * cos(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
params.cameraPointingY =
eye_y - dis * sin(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
params.cameraPointingZ =
eye_z - dis * sin(DEG2RAD(params.cameraElevationDeg));
}
void CGlCanvasBase::updateOrbitCamera(CamaraParams& params, int x, int y) const
{
params.cameraAzimuthDeg -= 0.2f * (x - m_mouseClickX);
params.setElevationDeg(
params.cameraElevationDeg + 0.2f * (y - m_mouseClickY));
}
void CGlCanvasBase::updateLastPos(int x, int y)
{
m_mouseLastX = x;
m_mouseLastY = y;
}
void CGlCanvasBase::resizeViewport(int w, int h)
{
#if MRPT_HAS_OPENGL_GLUT
if (w == -1 || h == -1) return;
glViewport(0, 0, (GLint)w, (GLint)h);
#endif
}
void CGlCanvasBase::clearColors()
{
#if MRPT_HAS_OPENGL_GLUT
glClearColor(clearColorR, clearColorG, clearColorB, clearColorA);
#endif
}
void CGlCanvasBase::updatePan(CamaraParams& params, int x, int y) const
{
float Ay = -(x - m_mouseClickX);
float Ax = -(y - m_mouseClickY);
float D = 0.001f * params.cameraZoomDistance;
params.cameraPointingX += D * (Ax * cos(DEG2RAD(params.cameraAzimuthDeg)) -
Ay * sin(DEG2RAD(params.cameraAzimuthDeg)));
params.cameraPointingY += D * (Ax * sin(DEG2RAD(params.cameraAzimuthDeg)) +
Ay * cos(DEG2RAD(params.cameraAzimuthDeg)));
}
CGlCanvasBase::CamaraParams CGlCanvasBase::cameraParams() const
{
return m_cameraParams;
}
const CGlCanvasBase::CamaraParams& CGlCanvasBase::getRefCameraParams() const
{
return m_cameraParams;
}
void CGlCanvasBase::setCameraParams(const CGlCanvasBase::CamaraParams& params)
{
m_cameraParams = params;
}
float CGlCanvasBase::getZoomDistance() const
{
return m_cameraParams.cameraZoomDistance;
}
void CGlCanvasBase::setZoomDistance(float zoom)
{
m_cameraParams.cameraZoomDistance = zoom;
}
CCamera& CGlCanvasBase::updateCameraParams(CCamera& cam) const
{
cam.setPointingAt(
m_cameraParams.cameraPointingX, m_cameraParams.cameraPointingY,
m_cameraParams.cameraPointingZ);
cam.setZoomDistance(m_cameraParams.cameraZoomDistance);
cam.setAzimuthDegrees(m_cameraParams.cameraAzimuthDeg);
cam.setElevationDegrees(m_cameraParams.cameraElevationDeg);
cam.setProjectiveModel(m_cameraParams.cameraIsProjective);
cam.setProjectiveFOVdeg(m_cameraParams.cameraFOV);
return cam;
}
void CGlCanvasBase::setUseCameraFromScene(bool is) { useCameraFromScene = is; }
bool CGlCanvasBase::getUseCameraFromScene() const { return useCameraFromScene; }
void CGlCanvasBase::setAzimuthDegrees(float ang)
{
m_cameraParams.cameraAzimuthDeg = ang;
}
void CGlCanvasBase::setElevationDegrees(float ang)
{
m_cameraParams.cameraElevationDeg = ang;
}
float CGlCanvasBase::getAzimuthDegrees() const
{
return m_cameraParams.cameraAzimuthDeg;
}
float CGlCanvasBase::getElevationDegrees() const
{
return m_cameraParams.cameraElevationDeg;
}
void CGlCanvasBase::setCameraProjective(bool is)
{
m_cameraParams.cameraIsProjective = is;
}
bool CGlCanvasBase::isCameraProjective() const
{
return m_cameraParams.cameraIsProjective;
}
void CGlCanvasBase::setCameraFOV(float FOV) { m_cameraParams.cameraFOV = FOV; }
float CGlCanvasBase::cameraFOV() const { return m_cameraParams.cameraFOV; }
void CGlCanvasBase::setClearColors(float r, float g, float b, float a)
{
clearColorR = r;
clearColorG = g;
clearColorB = b;
clearColorA = a;
}
float CGlCanvasBase::getClearColorR() const { return clearColorR; }
float CGlCanvasBase::getClearColorG() const { return clearColorG; }
float CGlCanvasBase::getClearColorB() const { return clearColorB; }
float CGlCanvasBase::getClearColorA() const { return clearColorA; }
void CGlCanvasBase::setOpenGLSceneRef(COpenGLScene::Ptr scene)
{
m_openGLScene = scene;
}
void CGlCanvasBase::setCameraPointing(float pointX, float pointY, float pointZ)
{
m_cameraParams.cameraPointingX = pointX;
m_cameraParams.cameraPointingY = pointY;
m_cameraParams.cameraPointingZ = pointZ;
}
float CGlCanvasBase::getCameraPointingX() const
{
return m_cameraParams.cameraPointingX;
}
float CGlCanvasBase::getCameraPointingY() const
{
return m_cameraParams.cameraPointingY;
}
float CGlCanvasBase::getCameraPointingZ() const
{
return m_cameraParams.cameraPointingZ;
}
double CGlCanvasBase::renderCanvas(int width, int height)
{
#if MRPT_HAS_OPENGL_GLUT
CTicTac tictac;
double At = 0.1;
try
{
// Flush & swap buffers to disply new image:
glFinish();
swapBuffers();
CHECK_OPENGL_ERROR();
// Call PreRender user code:
preRender();
CHECK_OPENGL_ERROR();
// Set static configs:
glEnable(GL_DEPTH_TEST);
CHECK_OPENGL_ERROR();
// Set the viewport
resizeViewport((GLsizei)width, (GLsizei)height);
// Set the background color:
clearColors();
if (m_openGLScene)
{
// Set the camera params in the scene:
if (!useCameraFromScene)
{
COpenGLViewport::Ptr view = m_openGLScene->getViewport("main");
if (!view)
{
THROW_EXCEPTION(
"Fatal error: there is no 'main' viewport in the 3D "
"scene!");
}
mrpt::opengl::CCamera& cam = view->getCamera();
updateCameraParams(cam);
}
tictac.Tic();
// Draw primitives:
m_openGLScene->render();
} // end if "m_openGLScene!=nullptr"
postRender();
At = tictac.Tac();
}
catch (const std::exception& e)
{
const std::string err_msg =
std::string("[CGLCanvasBase::Render] Exception:\n") +
mrpt::exception_to_str(e);
std::cerr << err_msg;
renderError(err_msg);
}
return At;
#else
THROW_EXCEPTION("Cant render: MRPT was built without OpenGL");
#endif
}
void CGlCanvasBase::CamaraParams::setElevationDeg(float deg)
{
cameraElevationDeg = deg;
if (cameraElevationDeg < -90.0f)
cameraElevationDeg = -90.0f;
else if (cameraElevationDeg > 90.0f)
cameraElevationDeg = 90.0f;
}
<commit_msg>roll back change order of opengl finish<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "gui-precomp.h" // Precompiled headers
#include <mrpt/gui/CGlCanvasBase.h>
#include <mrpt/opengl/opengl_api.h>
#include <mrpt/system/CTicTac.h>
#if MRPT_HAS_OPENGL_GLUT
#ifdef _WIN32
// Windows:
#include <windows.h>
#endif
#ifdef __APPLE__
#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#ifdef HAVE_FREEGLUT_EXT_H
#include <GL/freeglut_ext.h>
#endif
#endif
#endif // MRPT_HAS_OPENGL_GLUT
using namespace mrpt;
using namespace mrpt::gui;
using namespace mrpt::opengl;
using namespace std;
using mrpt::system::CTicTac;
float CGlCanvasBase::SENSIBILITY_DEG_PER_PIXEL = 0.1f;
CGlCanvasBase::~CGlCanvasBase()
{
// Ensure all OpenGL resources are freed before the opengl context is gone:
if (m_openGLScene) m_openGLScene->unloadShaders();
}
void CGlCanvasBase::setMinimumZoom(float zoom) { m_minZoom = zoom; }
void CGlCanvasBase::setMaximumZoom(float zoom) { m_maxZoom = zoom; }
void CGlCanvasBase::setMousePos(int x, int y)
{
m_mouseClickX = x;
m_mouseClickY = y;
}
void CGlCanvasBase::setMouseClicked(bool is) { mouseClicked = is; }
void CGlCanvasBase::updateZoom(CamaraParams& params, int x, int y) const
{
float zoom = params.cameraZoomDistance * exp(0.01f * (y - m_mouseClickY));
if (zoom <= m_minZoom || (m_maxZoom != -1.0f && m_maxZoom <= zoom)) return;
params.cameraZoomDistance = zoom;
if (params.cameraZoomDistance < 0.01f) params.cameraZoomDistance = 0.01f;
float Az = -0.05f * (x - m_mouseClickX);
float D = 0.001f * params.cameraZoomDistance;
params.cameraPointingZ += D * Az;
}
void CGlCanvasBase::updateZoom(CamaraParams& params, float delta) const
{
float zoom = params.cameraZoomDistance * (1 - 0.03f * (delta / 120.0f));
if (zoom <= m_minZoom || (m_maxZoom != -1.0f && m_maxZoom <= zoom)) return;
params.cameraZoomDistance = zoom;
}
void CGlCanvasBase::updateRotate(CamaraParams& params, int x, int y) const
{
const float dis = max(0.01f, (params.cameraZoomDistance));
float eye_x =
params.cameraPointingX + dis * cos(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
float eye_y =
params.cameraPointingY + dis * sin(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
float eye_z =
params.cameraPointingZ + dis * sin(DEG2RAD(params.cameraElevationDeg));
// Orbit camera:
float A_AzimuthDeg = -SENSIBILITY_DEG_PER_PIXEL * (x - m_mouseClickX);
params.cameraAzimuthDeg += A_AzimuthDeg;
float A_ElevationDeg = SENSIBILITY_DEG_PER_PIXEL * (y - m_mouseClickY);
params.setElevationDeg(params.cameraElevationDeg + A_ElevationDeg);
// Move cameraPointing pos:
params.cameraPointingX =
eye_x - dis * cos(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
params.cameraPointingY =
eye_y - dis * sin(DEG2RAD(params.cameraAzimuthDeg)) *
cos(DEG2RAD(params.cameraElevationDeg));
params.cameraPointingZ =
eye_z - dis * sin(DEG2RAD(params.cameraElevationDeg));
}
void CGlCanvasBase::updateOrbitCamera(CamaraParams& params, int x, int y) const
{
params.cameraAzimuthDeg -= 0.2f * (x - m_mouseClickX);
params.setElevationDeg(
params.cameraElevationDeg + 0.2f * (y - m_mouseClickY));
}
void CGlCanvasBase::updateLastPos(int x, int y)
{
m_mouseLastX = x;
m_mouseLastY = y;
}
void CGlCanvasBase::resizeViewport(int w, int h)
{
#if MRPT_HAS_OPENGL_GLUT
if (w == -1 || h == -1) return;
glViewport(0, 0, (GLint)w, (GLint)h);
#endif
}
void CGlCanvasBase::clearColors()
{
#if MRPT_HAS_OPENGL_GLUT
glClearColor(clearColorR, clearColorG, clearColorB, clearColorA);
#endif
}
void CGlCanvasBase::updatePan(CamaraParams& params, int x, int y) const
{
float Ay = -(x - m_mouseClickX);
float Ax = -(y - m_mouseClickY);
float D = 0.001f * params.cameraZoomDistance;
params.cameraPointingX += D * (Ax * cos(DEG2RAD(params.cameraAzimuthDeg)) -
Ay * sin(DEG2RAD(params.cameraAzimuthDeg)));
params.cameraPointingY += D * (Ax * sin(DEG2RAD(params.cameraAzimuthDeg)) +
Ay * cos(DEG2RAD(params.cameraAzimuthDeg)));
}
CGlCanvasBase::CamaraParams CGlCanvasBase::cameraParams() const
{
return m_cameraParams;
}
const CGlCanvasBase::CamaraParams& CGlCanvasBase::getRefCameraParams() const
{
return m_cameraParams;
}
void CGlCanvasBase::setCameraParams(const CGlCanvasBase::CamaraParams& params)
{
m_cameraParams = params;
}
float CGlCanvasBase::getZoomDistance() const
{
return m_cameraParams.cameraZoomDistance;
}
void CGlCanvasBase::setZoomDistance(float zoom)
{
m_cameraParams.cameraZoomDistance = zoom;
}
CCamera& CGlCanvasBase::updateCameraParams(CCamera& cam) const
{
cam.setPointingAt(
m_cameraParams.cameraPointingX, m_cameraParams.cameraPointingY,
m_cameraParams.cameraPointingZ);
cam.setZoomDistance(m_cameraParams.cameraZoomDistance);
cam.setAzimuthDegrees(m_cameraParams.cameraAzimuthDeg);
cam.setElevationDegrees(m_cameraParams.cameraElevationDeg);
cam.setProjectiveModel(m_cameraParams.cameraIsProjective);
cam.setProjectiveFOVdeg(m_cameraParams.cameraFOV);
return cam;
}
void CGlCanvasBase::setUseCameraFromScene(bool is) { useCameraFromScene = is; }
bool CGlCanvasBase::getUseCameraFromScene() const { return useCameraFromScene; }
void CGlCanvasBase::setAzimuthDegrees(float ang)
{
m_cameraParams.cameraAzimuthDeg = ang;
}
void CGlCanvasBase::setElevationDegrees(float ang)
{
m_cameraParams.cameraElevationDeg = ang;
}
float CGlCanvasBase::getAzimuthDegrees() const
{
return m_cameraParams.cameraAzimuthDeg;
}
float CGlCanvasBase::getElevationDegrees() const
{
return m_cameraParams.cameraElevationDeg;
}
void CGlCanvasBase::setCameraProjective(bool is)
{
m_cameraParams.cameraIsProjective = is;
}
bool CGlCanvasBase::isCameraProjective() const
{
return m_cameraParams.cameraIsProjective;
}
void CGlCanvasBase::setCameraFOV(float FOV) { m_cameraParams.cameraFOV = FOV; }
float CGlCanvasBase::cameraFOV() const { return m_cameraParams.cameraFOV; }
void CGlCanvasBase::setClearColors(float r, float g, float b, float a)
{
clearColorR = r;
clearColorG = g;
clearColorB = b;
clearColorA = a;
}
float CGlCanvasBase::getClearColorR() const { return clearColorR; }
float CGlCanvasBase::getClearColorG() const { return clearColorG; }
float CGlCanvasBase::getClearColorB() const { return clearColorB; }
float CGlCanvasBase::getClearColorA() const { return clearColorA; }
void CGlCanvasBase::setOpenGLSceneRef(COpenGLScene::Ptr scene)
{
m_openGLScene = scene;
}
void CGlCanvasBase::setCameraPointing(float pointX, float pointY, float pointZ)
{
m_cameraParams.cameraPointingX = pointX;
m_cameraParams.cameraPointingY = pointY;
m_cameraParams.cameraPointingZ = pointZ;
}
float CGlCanvasBase::getCameraPointingX() const
{
return m_cameraParams.cameraPointingX;
}
float CGlCanvasBase::getCameraPointingY() const
{
return m_cameraParams.cameraPointingY;
}
float CGlCanvasBase::getCameraPointingZ() const
{
return m_cameraParams.cameraPointingZ;
}
double CGlCanvasBase::renderCanvas(int width, int height)
{
#if MRPT_HAS_OPENGL_GLUT
CTicTac tictac;
double At = 0.1;
try
{
// Call PreRender user code:
preRender();
CHECK_OPENGL_ERROR();
// Set static configs:
glEnable(GL_DEPTH_TEST);
CHECK_OPENGL_ERROR();
// Set the viewport
resizeViewport((GLsizei)width, (GLsizei)height);
// Set the background color:
clearColors();
if (m_openGLScene)
{
// Set the camera params in the scene:
if (!useCameraFromScene)
{
COpenGLViewport::Ptr view = m_openGLScene->getViewport("main");
if (!view)
{
THROW_EXCEPTION(
"Fatal error: there is no 'main' viewport in the 3D "
"scene!");
}
mrpt::opengl::CCamera& cam = view->getCamera();
updateCameraParams(cam);
}
tictac.Tic();
// Draw primitives:
m_openGLScene->render();
} // end if "m_openGLScene!=nullptr"
postRender();
// Flush & swap buffers to disply new image:
glFinish();
swapBuffers();
CHECK_OPENGL_ERROR();
At = tictac.Tac();
}
catch (const std::exception& e)
{
const std::string err_msg =
std::string("[CGLCanvasBase::Render] Exception:\n") +
mrpt::exception_to_str(e);
std::cerr << err_msg;
renderError(err_msg);
}
return At;
#else
THROW_EXCEPTION("Cant render: MRPT was built without OpenGL");
#endif
}
void CGlCanvasBase::CamaraParams::setElevationDeg(float deg)
{
cameraElevationDeg = deg;
if (cameraElevationDeg < -90.0f)
cameraElevationDeg = -90.0f;
else if (cameraElevationDeg > 90.0f)
cameraElevationDeg = 90.0f;
}
<|endoftext|> |
<commit_before>#include <list>
#include <vector>
using namespace std;
#include <climits>
#include "algorithms.h"
#include "graph.h"
#include "heuristics.h"
#include "stats.h"
#include "node_heap.h"
// These algorithms 'close' nodes by flagging them with the id of the
// current problem being solved. This saves us unclosing every node
// after solving each path.
int problem_id = 1;
inline void init_new_problem(Graph & graph, Stats & stats) {
++ stats.num_problems;
++ problem_id;
// check integer overflow; problem_ids are no longer unique, so reset.
if (problem_id == 0) {
for (size_t ii = 0; ii < graph.graph_view.size(); ++ ii)
graph.graph_view[ii]->closed_id = 0;
problem_id = 1;
}
}
inline void reconstruct_path(Node* start, Node* current,
unsigned int (*cost)(Node*, Node*),
Stats & stats) {
while (current != start) {
stats.path_cost += cost(current->whence, current);
++ stats.path_length;
current = current->whence;
}
}
/// A-star with no optimizations, not even sorting the open list.
/// Additionally contains some validations on the result.
void astar_basic(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
typedef vector<Node*>::iterator iter;
static vector<Node*> open_list;
start->open = true;
start->relax(0, h(start, goal), NULL);
open_list.push_back(start);
// Pop the best node off the open_list
while (!open_list.empty()) {
int g = 0, fmin = INT_MAX;
iter ii_best;
for (iter ii = open_list.begin(); ii != open_list.end(); ++ ii) {
Node * nd = *ii;
if (nd->f > fmin)
continue;
if (nd->f <= fmin || nd->g > g) {
fmin = nd->f;
g = nd->g;
ii_best = ii;
}
}
Node *expand_me = *ii_best;
expand_me->open = false;
// remove it by replacing it with the back() node
*ii_best = open_list.back();
open_list.pop_back();
// expand and close the best
if (expand_me == gg)
break;
expand_me->expand(problem_id);
++ stats.nodes_expanded;
// Add each neighbor
for (vector_iter ii = expand_me->neighbors_out.begin();
ii != expand_me->neighbors_out.end(); ++ ii) {
Node* add_me = *ii;
if (add_me->closed(problem_id))
continue;
int g = expand_me->g + cost(expand_me, add_me);
if (!add_me->open) { // If it's not open, open it
add_me->open = true;
add_me->relax(g, h(add_me, goal), expand_me);
open_list.push_back(add_me);
}
else if (add_me->g > g) { // If it is open, relax it
add_me->relax(g, h(add_me, goal), expand_me);
}
}
}
// Stats collection & cleanup
stats.open_list_size += open_list.size();
reconstruct_path(start, goal, graph.cost, stats);
for (vector_iter ii = open_list.begin(); ii != open_list.end(); ++ ii)
(*ii)->open = false;
open_list.clear();
}
/// A* with a binary heap.
void astar_heap(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
typedef vector<Node*>::iterator iter;
static vector<Node*> open_list;
start->open = true;
start->relax(0, h(start, goal), NULL);
node_heap::push(open_list, start);
while (!open_list.empty()) {
// Pop the best node off the open_list (+ goal check)
Node* expand_me = open_list.front();
if (expand_me == goal)
break;
++ stats.nodes_expanded;
expand_me->expand(problem_id);
node_heap::pop(open_list);
// Add each neighbor
for (iter ii = expand_me->neighbors_out.begin(), end = expand_me->neighbors_out.end();
ii != end; ++ ii) {
Node* add_me = *ii;
if (add_me->closed(problem_id))
continue;
// NOTE: you can implement greedy best-first search by setting g = 0 here,
// or weighted A* by scaling h up by some scalar > 1.
const int g = expand_me->g + cost(expand_me, add_me);
if (!add_me->open) { // If it's not open, open it
add_me->open = true;
add_me->relax(g, h(add_me, goal), expand_me);
node_heap::push(open_list, add_me);
}
else if (g < add_me->g) { // If it is open, relax it
add_me->relax(g, add_me->f - add_me->g, expand_me);
node_heap::repair(open_list, add_me->heap_index);
}
}
}
// Stats collection & cleanup
stats.open_list_size += open_list.size();
reconstruct_path(start, goal, graph.cost, stats);
for (vector_iter ii = open_list.begin(); ii != open_list.end(); ++ ii)
(*ii)->open = false;
open_list.clear();
}
/// Fringe search (Bjornsson, Enzenberger, Holte, and Schaeffer '05).
// Like other algorithms in the A* family, fringe search expands nodes one ply
// of f values at a time. Fringe search does this in a depth-first fashion,
// favoring the expansion of recently touched nodes, which can be accommodated
// by inserting entries into a linked list.
//
// Without aggressive compiler optimizations, Fringe Search beats A* handily.
void fringe_search(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
static list<Node*> Fringe;
typedef list<Node*>::iterator iter;
Fringe.push_back(start);
start->open = true;
start->relax(0, h(start, goal), NULL);
start->fringe_index = Fringe.begin();
bool found = false;
int flimit = start->f;
do {
int fnext = INT_MAX;
iter ff = Fringe.begin();
while (ff != Fringe.end()) {
Node* expand_me = *ff;
int f = expand_me->g + h(expand_me, gg);
// Consider this node (is `expand_me' outside our depth?)
if (f > flimit) {
// keep track of smallest next depth
if (f < fnext) {
fnext = f;
}
++ ff;
continue; // skip this one (for now)
}
else if (expand_me == gg) {
// is `expand_me' the goal and within our depth?
found = true;
break;
}
// Expand this node: relax its neighbors' g-values and
// put them on the fringe directly AFTER `expand_me'
++ stats.nodes_expanded;
for (vector<Node*>::iterator jj = expand_me->neighbors_out.begin();
jj != expand_me->neighbors_out.end(); ++ jj) {
Node* relax_me = *jj;
int g = expand_me->g + cost(expand_me, relax_me);
// jj is or has been on the fringe?
if (relax_me->open || relax_me->closed == problem_id) {
// is this a worse path?
if (g >= relax_me->g)
continue;
}
iter insertion_point = ff;
++ insertion_point;
if (!relax_me->open) {
// if not already open, insert jj after expand_me
relax_me->fringe_index = Fringe.insert(insertion_point, relax_me);
relax_me->open = true;
}
else if (*insertion_point != relax_me) {
// if open, move it to right after expand_me
Fringe.erase(relax_me->fringe_index);
relax_me->fringe_index = Fringe.insert(insertion_point, relax_me);
}
relax_me->g = g;
relax_me->whence = expand_me;
}
// Remove expand_me from Fringe
expand_me->open = false;
expand_me->closed = problem_id;
expand_me->fringe_index = Fringe.end();
ff = Fringe.erase(ff);
}
// Increase the depth and scan the fringe again
flimit = fnext;
} while (!found && !Fringe.empty());
// Stats collection & cleanup
stats.open_list_size += Fringe.size();
reconstruct_path(start, goal, graph.cost, stats);
for (list_iter ff = Fringe.begin(); ff != Fringe.end(); ++ ff)
(*ff)->open = false;
Fringe.clear();
}
/// Basic learning real-time search
void lrta_basic(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
while (start != goal) {
Node* best_neighbor = 0;
unsigned int best_f = INT_MAX;
stats.nodes_expanded += 1;
for (size_t ii = 0; ii < start->neighbors_out.size(); ++ ii) {
Node* neighb = start->neighbors_out[ii];
// set default heuristic value if it isn't set
if (!(neighb->closed(problem_id))) {
neighb->expand(problem_id);
neighb->f = h(neighb, goal);
}
unsigned int f = cost(ss, neighb) + neighb->f;
if (!best_neighbor || f < best_f) {
best_neighbor = neighb;
best_f = f;
}
else if (f == best_f && stats.nodes_expanded % 2)
best_neighbor = neighb;
}
start->f = best_f; // learning update
stats.path_cost += graph.cost(start, best_neighbor);
start = best_neighbor;
}
stats.path_length = stats.nodes_expanded;
}
<commit_msg>clean up astar_basic and astar_heap algorithms<commit_after>#include <list>
#include <vector>
using namespace std;
#include <climits>
#include "algorithms.h"
#include "graph.h"
#include "heuristics.h"
#include "stats.h"
#include "node_heap.h"
typedef list<Node*>::iterator list_iter;
typedef vector<Node*>::iterator vector_iter;
// These algorithms 'close' nodes by flagging them with the id of the
// current problem being solved. This saves us unclosing every node
// after solving each path.
int problem_id = 1;
inline void init_new_problem(Graph & graph, Stats & stats) {
++ stats.num_problems;
++ problem_id;
// check integer overflow; problem_ids are no longer unique, so reset.
if (problem_id == 0) {
for (size_t ii = 0; ii < graph.graph_view.size(); ++ ii)
graph.graph_view[ii]->closed_id = 0;
problem_id = 1;
}
}
inline void reconstruct_path(Node* start, Node* current,
unsigned int (*cost)(Node*, Node*),
Stats & stats) {
while (current != start) {
stats.path_cost += cost(current->whence, current);
++ stats.path_length;
current = current->whence;
}
}
/// A-star with no optimizations, not even sorting the open list.
/// Additionally contains some validations on the result.
void astar_basic(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
init_new_problem(graph, stats);
static vector<Node*> open_list;
start->open = true;
start->relax(0, h(start, goal), NULL);
open_list.push_back(start);
while (!open_list.empty()) {
int fmin = INT_MAX;
vector_iter best_on_open_list;
// Pop the best node off the open_list via linear scan
for (vector_iter node = open_list.begin();
node != open_list.end(); ++ node) {
if ((*node)->f < fmin) {
fmin = (*node)->f;
best_on_open_list = node;
}
}
Node* expand_me = *best_on_open_list;
if (expand_me == goal)
break;
expand_me->expand(problem_id);
++ stats.nodes_expanded;
// remove it by overwriting it with the back() node
*best_on_open_list = open_list.back();
open_list.pop_back();
// Add each neighbor
for (vector_iter ii = expand_me->neighbors_out.begin();
ii != expand_me->neighbors_out.end(); ++ ii) {
Node* add_me = *ii;
if (add_me->closed(problem_id))
continue;
const int g = expand_me->g + graph.cost(expand_me, add_me);
if (!add_me->open) { // If it's not open, open it
add_me->open = true;
add_me->relax(g, h(add_me, goal), expand_me);
open_list.push_back(add_me);
}
else if (add_me->g > g) { // If it is open, relax it
add_me->relax(g, h(add_me, goal), expand_me);
}
}
}
// Stats collection & cleanup
stats.open_list_size += open_list.size();
reconstruct_path(start, goal, graph.cost, stats);
for (vector_iter ii = open_list.begin(); ii != open_list.end(); ++ ii)
(*ii)->open = false;
open_list.clear();
}
/// A* with a binary heap.
void astar_heap(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
init_new_problem(graph, stats);
static vector<Node*> open_list;
start->open = true;
start->relax(0, h(start, goal), NULL);
node_heap::push(open_list, start);
while (!open_list.empty()) {
// Pop the best node off the open_list (+ goal check)
Node* expand_me = open_list.front();
if (expand_me == goal)
break;
++ stats.nodes_expanded;
expand_me->expand(problem_id);
node_heap::pop(open_list);
// Add each neighbor
for (vector_iter ii = expand_me->neighbors_out.begin();
ii != expand_me->neighbors_out.end(); ++ ii) {
Node* add_me = *ii;
if (add_me->closed(problem_id))
continue;
const int g = expand_me->g + graph.cost(expand_me, add_me);
if (!add_me->open) { // If it's not open, open it
add_me->open = true;
add_me->relax(g, h(add_me, goal), expand_me);
node_heap::push(open_list, add_me);
}
else if (g < add_me->g) { // If it is open, relax it
add_me->relax(g, add_me->f - add_me->g, expand_me);
node_heap::repair(open_list, add_me->heap_index);
}
}
}
// Stats collection & cleanup
stats.open_list_size += open_list.size();
reconstruct_path(start, goal, graph.cost, stats);
for (vector_iter ii = open_list.begin(); ii != open_list.end(); ++ ii)
(*ii)->open = false;
open_list.clear();
}
/// Fringe search (Bjornsson, Enzenberger, Holte, and Schaeffer '05).
// Like other algorithms in the A* family, fringe search expands nodes one ply
// of f values at a time. Fringe search does this in a depth-first fashion,
// favoring the expansion of recently touched nodes, which can be accommodated
// by inserting entries into a linked list.
//
// Without aggressive compiler optimizations, Fringe Search beats A* handily.
void fringe_search(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
static list<Node*> Fringe;
typedef list<Node*>::iterator iter;
Fringe.push_back(start);
start->open = true;
start->relax(0, h(start, goal), NULL);
start->fringe_index = Fringe.begin();
bool found = false;
int flimit = start->f;
do {
int fnext = INT_MAX;
iter ff = Fringe.begin();
while (ff != Fringe.end()) {
Node* expand_me = *ff;
int f = expand_me->g + h(expand_me, gg);
// Consider this node (is `expand_me' outside our depth?)
if (f > flimit) {
// keep track of smallest next depth
if (f < fnext) {
fnext = f;
}
++ ff;
continue; // skip this one (for now)
}
else if (expand_me == gg) {
// is `expand_me' the goal and within our depth?
found = true;
break;
}
// Expand this node: relax its neighbors' g-values and
// put them on the fringe directly AFTER `expand_me'
++ stats.nodes_expanded;
for (vector<Node*>::iterator jj = expand_me->neighbors_out.begin();
jj != expand_me->neighbors_out.end(); ++ jj) {
Node* relax_me = *jj;
int g = expand_me->g + cost(expand_me, relax_me);
// jj is or has been on the fringe?
if (relax_me->open || relax_me->closed == problem_id) {
// is this a worse path?
if (g >= relax_me->g)
continue;
}
iter insertion_point = ff;
++ insertion_point;
if (!relax_me->open) {
// if not already open, insert jj after expand_me
relax_me->fringe_index = Fringe.insert(insertion_point, relax_me);
relax_me->open = true;
}
else if (*insertion_point != relax_me) {
// if open, move it to right after expand_me
Fringe.erase(relax_me->fringe_index);
relax_me->fringe_index = Fringe.insert(insertion_point, relax_me);
}
relax_me->g = g;
relax_me->whence = expand_me;
}
// Remove expand_me from Fringe
expand_me->open = false;
expand_me->closed = problem_id;
expand_me->fringe_index = Fringe.end();
ff = Fringe.erase(ff);
}
// Increase the depth and scan the fringe again
flimit = fnext;
} while (!found && !Fringe.empty());
// Stats collection & cleanup
stats.open_list_size += Fringe.size();
reconstruct_path(start, goal, graph.cost, stats);
for (list_iter ff = Fringe.begin(); ff != Fringe.end(); ++ ff)
(*ff)->open = false;
Fringe.clear();
}
/// Basic learning real-time search
void lrta_basic(Graph & graph, Node* start, Node* goal, Stats & stats,
unsigned int (*h)(Node* n1, Node* n2)) {
unsigned int (*cost)(Node*, Node*) = graph.cost;
init_new_problem(graph, stats);
while (start != goal) {
Node* best_neighbor = 0;
unsigned int best_f = INT_MAX;
stats.nodes_expanded += 1;
for (size_t ii = 0; ii < start->neighbors_out.size(); ++ ii) {
Node* neighb = start->neighbors_out[ii];
// set default heuristic value if it isn't set
if (!(neighb->closed(problem_id))) {
neighb->expand(problem_id);
neighb->f = h(neighb, goal);
}
unsigned int f = cost(ss, neighb) + neighb->f;
if (!best_neighbor || f < best_f) {
best_neighbor = neighb;
best_f = f;
}
else if (f == best_f && stats.nodes_expanded % 2)
best_neighbor = neighb;
}
start->f = best_f; // learning update
stats.path_cost += graph.cost(start, best_neighbor);
start = best_neighbor;
}
stats.path_length = stats.nodes_expanded;
}
<|endoftext|> |
<commit_before>#ifdef NG_PYTHON
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
#include <../general/ngpython.hpp>
#include <mystdlib.h>
#include "meshing.hpp"
using namespace netgen;
namespace bp = boost::python;
template <typename T, int BASE = 0, typename TIND = int>
void ExportArray ()
{
string name = string("Array_") + typeid(T).name();
bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str())
.def ("__len__", &Array<T,BASE,TIND>::Size)
.def ("__getitem__",
FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T&
{
if (i < BASE || i >= BASE+self.Size())
bp::exec("raise IndexError()\n");
return self[i];
}),
bp::return_value_policy<bp::reference_existing_object>())
.def ("__iter__",
bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }),
FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; })))
;
}
void ExportNetgenMeshing()
{
ModuleScope module("meshing");
bp::class_<PointIndex>("PointId", bp::init<int>())
.def("__repr__", &ToString<PointIndex>)
.def("__str__", &ToString<PointIndex>)
.add_property("nr", &PointIndex::operator int)
;
/*
bp::class_<Point<3>> ("Point")
.def(bp::init<double,double,double>())
;
*/
bp::class_<MeshPoint /* ,bp::bases<Point<3>> */ >("MeshPoint")
// .def(bp::init<Point<3>>())
.add_property("p", FunctionPointer([](const MeshPoint & self)
{
bp::list l;
l.append ( self[0] );
l.append ( self[1] );
l.append ( self[2] );
return bp::tuple(l);
}))
;
bp::class_<Element>("Element3D")
.add_property("index", &Element::GetIndex, &Element::SetIndex)
.add_property("vertices",
FunctionPointer ([](const Element & self) -> bp::list
{
bp::list li;
for (int i = 0; i < self.GetNV(); i++)
li.append (self[i]);
return li;
}))
;
bp::class_<Element2d>("Element2D")
.add_property("index", &Element2d::GetIndex, &Element2d::SetIndex)
.add_property("vertices",
FunctionPointer([](const Element2d & self) -> bp::list
{
bp::list li;
for (int i = 0; i < self.GetNV(); i++)
li.append(self[i]);
return li;
}))
;
ExportArray<Element>();
ExportArray<Element2d>();
ExportArray<MeshPoint,PointIndex::BASE,PointIndex>();
;
bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh")
.def("__str__", &ToString<Mesh>)
.def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load))
.def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save))
.def("Elements3D",
static_cast<Array<Element>&(Mesh::*)()> (&Mesh::VolumeElements),
bp::return_value_policy<bp::reference_existing_object>())
.def("Elements2D",
static_cast<Array<Element2d>&(Mesh::*)()> (&Mesh::SurfaceElements),
bp::return_value_policy<bp::reference_existing_object>())
.def("Points",
static_cast<Mesh::T_POINTS&(Mesh::*)()> (&Mesh::Points),
bp::return_value_policy<bp::reference_existing_object>())
.def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi)
{
return self[pi];
}))
.def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p)
{
return self.AddPoint (Point3d(p));
}))
.def("__init__", bp::make_constructor
(FunctionPointer ([]()
{
auto tmp = new Mesh();
return tmp;
})),
"create empty mesh"
)
;
typedef MeshingParameters MP;
bp::class_<MP> ("MeshingParameters", bp::init<>())
.def("__init__", bp::make_constructor
(FunctionPointer ([](double maxh)
{
auto tmp = new MeshingParameters;
tmp->maxh = maxh;
return tmp;
}),
bp::default_call_policies(), // need it to use arguments
(bp::arg("maxh")=1000)),
"create meshing parameters"
)
.def("__str__", &ToString<MP>)
.add_property("maxh",
FunctionPointer ([](const MP & mp ) { return mp.maxh; }),
FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))
;
bp::def("SetTestoutFile", FunctionPointer ([] (const string & filename)
{
delete testout;
testout = new ofstream (filename);
}));
bp::def("SetMessageImportance", FunctionPointer ([] (int importance)
{
int old = printmessage_importance;
printmessage_importance = importance;
return old;
}));
}
BOOST_PYTHON_MODULE(libmesh) {
ExportNetgenMeshing();
}
#endif
<commit_msg>mesh default constructor<commit_after>#ifdef NG_PYTHON
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
#include <../general/ngpython.hpp>
#include <mystdlib.h>
#include "meshing.hpp"
using namespace netgen;
namespace bp = boost::python;
template <typename T, int BASE = 0, typename TIND = int>
void ExportArray ()
{
string name = string("Array_") + typeid(T).name();
bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str())
.def ("__len__", &Array<T,BASE,TIND>::Size)
.def ("__getitem__",
FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T&
{
if (i < BASE || i >= BASE+self.Size())
bp::exec("raise IndexError()\n");
return self[i];
}),
bp::return_value_policy<bp::reference_existing_object>())
.def ("__iter__",
bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }),
FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; })))
;
}
void ExportNetgenMeshing()
{
ModuleScope module("meshing");
bp::class_<PointIndex>("PointId", bp::init<int>())
.def("__repr__", &ToString<PointIndex>)
.def("__str__", &ToString<PointIndex>)
.add_property("nr", &PointIndex::operator int)
;
/*
bp::class_<Point<3>> ("Point")
.def(bp::init<double,double,double>())
;
*/
bp::class_<MeshPoint /* ,bp::bases<Point<3>> */ >("MeshPoint")
// .def(bp::init<Point<3>>())
.add_property("p", FunctionPointer([](const MeshPoint & self)
{
bp::list l;
l.append ( self[0] );
l.append ( self[1] );
l.append ( self[2] );
return bp::tuple(l);
}))
;
bp::class_<Element>("Element3D")
.add_property("index", &Element::GetIndex, &Element::SetIndex)
.add_property("vertices",
FunctionPointer ([](const Element & self) -> bp::list
{
bp::list li;
for (int i = 0; i < self.GetNV(); i++)
li.append (self[i]);
return li;
}))
;
bp::class_<Element2d>("Element2D")
.add_property("index", &Element2d::GetIndex, &Element2d::SetIndex)
.add_property("vertices",
FunctionPointer([](const Element2d & self) -> bp::list
{
bp::list li;
for (int i = 0; i < self.GetNV(); i++)
li.append(self[i]);
return li;
}))
;
ExportArray<Element>();
ExportArray<Element2d>();
ExportArray<MeshPoint,PointIndex::BASE,PointIndex>();
;
bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh", bp::no_init)
.def(bp::init<>("create empty mesh"))
.def("__str__", &ToString<Mesh>)
.def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load))
.def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save))
.def("Elements3D",
static_cast<Array<Element>&(Mesh::*)()> (&Mesh::VolumeElements),
bp::return_value_policy<bp::reference_existing_object>())
.def("Elements2D",
static_cast<Array<Element2d>&(Mesh::*)()> (&Mesh::SurfaceElements),
bp::return_value_policy<bp::reference_existing_object>())
.def("Points",
static_cast<Mesh::T_POINTS&(Mesh::*)()> (&Mesh::Points),
bp::return_value_policy<bp::reference_existing_object>())
.def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi)
{
return self[pi];
}))
.def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p)
{
return self.AddPoint (Point3d(p));
}))
/*
.def("__init__", bp::make_constructor
(FunctionPointer ([]()
{
cout << "create new mesh" << endl;
auto tmp = make_shared<Mesh>();
return tmp;
})),
"create empty mesh"
)
*/
;
typedef MeshingParameters MP;
bp::class_<MP> ("MeshingParameters", bp::init<>())
.def("__init__", bp::make_constructor
(FunctionPointer ([](double maxh)
{
auto tmp = new MeshingParameters;
tmp->maxh = maxh;
return tmp;
}),
bp::default_call_policies(), // need it to use arguments
(bp::arg("maxh")=1000)),
"create meshing parameters"
)
.def("__str__", &ToString<MP>)
.add_property("maxh",
FunctionPointer ([](const MP & mp ) { return mp.maxh; }),
FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))
;
bp::def("SetTestoutFile", FunctionPointer ([] (const string & filename)
{
delete testout;
testout = new ofstream (filename);
}));
bp::def("SetMessageImportance", FunctionPointer ([] (int importance)
{
int old = printmessage_importance;
printmessage_importance = importance;
return old;
}));
}
BOOST_PYTHON_MODULE(libmesh) {
ExportNetgenMeshing();
}
#endif
<|endoftext|> |
<commit_before>/*
* Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 <iostream>
#include <unistd.h>
#include <stdlib.h>
#include "maxds3231m.h"
using namespace upm;
struct DS3231Exception : public std::exception {
std::string message;
DS3231Exception (std::string msg) : message (msg) { }
~DS3231Exception () throw () { }
const char* what() const throw () { return message.c_str(); }
};
MAXDS3231M::MAXDS3231M (int bus, int devAddr) {
m_name = "MAXDS3231M";
m_i2cAddr = devAddr;
m_bus = bus;
m_i2Ctx = mraa_i2c_init(m_bus);
mraa_result_t ret = mraa_i2c_address(m_i2Ctx, m_i2cAddr);
if (ret != MRAA_SUCCESS) {
throw DS3231Exception ("Couldn't initilize I2C.");
}
}
MAXDS3231M::~MAXDS3231M() {
mraa_i2c_stop(m_i2Ctx);
}
void
MAXDS3231M::setDate (Time3231 &time) {
uint8_t *data = (uint8_t *)&time;
i2cWriteReg_N (TIME_CAL_ADDR, 7, data);
}
bool
MAXDS3231M::getDate (Time3231 &time) {
uint8_t buffer[7];
// We need 7 bytes of data.
if (i2cReadReg_N (TIME_CAL_ADDR, 7, buffer) > 6) {
uint8_t century = (buffer[5] & 0x80) >> 7;
time.second = BCDtoDEC(buffer[0]);
time.minute = BCDtoDEC(buffer[1]);
time.hour = BCDtoDEC(buffer[2]);
time.day = BCDtoDEC(buffer[4]);
time.month = BCDtoDEC(buffer[5] & 0x1F);
time.year = (century == 1) ? 2000 + BCDtoDEC(buffer[6]) : 1900 + BCDtoDEC(buffer[6]);
time.weekDay = BCDtoDEC(buffer[3]);
return true;
}
return false;
}
uint16_t
MAXDS3231M::getTemperature () {
uint8_t buffer[2];
uint16_t tempRaw = 0;
i2cReadReg_N (TEMPERATURE_ADDR, 2, buffer);
tempRaw = (((int16_t)buffer[0]) << 8) | buffer[1];
return tempRaw;
}
/*
* **************
* private area
* **************
*/
uint16_t
MAXDS3231M::i2cReadReg_N (int reg, unsigned int len, uint8_t * buffer) {
int readByte = 0;
if (m_i2Ctx == NULL) {
throw DS3231Exception ("Couldn't find initilized I2C.");
}
mraa_i2c_address(m_i2Ctx, m_i2cAddr);
mraa_i2c_write_byte(m_i2Ctx, reg);
mraa_i2c_address(m_i2Ctx, m_i2cAddr);
readByte = mraa_i2c_read(m_i2Ctx, buffer, len);
return readByte;
}
mraa_result_t
MAXDS3231M::i2cWriteReg_N (uint8_t reg, unsigned int len, uint8_t * buffer) {
mraa_result_t error = MRAA_SUCCESS;
if (m_i2Ctx == NULL) {
throw DS3231Exception ("Couldn't find initilized I2C.");
}
error = mraa_i2c_address (m_i2Ctx, m_i2cAddr);
error = mraa_i2c_write (m_i2Ctx, buffer, len);
return error;
}
uint8_t
MAXDS3231M::DECtoBSD(uint8_t data) {
return ((data / 10 * 16) + (data % 10));
}
uint8_t
MAXDS3231M::BCDtoDEC(uint8_t data) {
return ((data / 16 * 10) + (data % 16));
}
<commit_msg>maxds3231m :: fix to getTemperature method<commit_after>/*
* Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 <iostream>
#include <unistd.h>
#include <stdlib.h>
#include "maxds3231m.h"
using namespace upm;
struct DS3231Exception : public std::exception {
std::string message;
DS3231Exception (std::string msg) : message (msg) { }
~DS3231Exception () throw () { }
const char* what() const throw () { return message.c_str(); }
};
MAXDS3231M::MAXDS3231M (int bus, int devAddr) {
m_name = "MAXDS3231M";
m_i2cAddr = devAddr;
m_bus = bus;
m_i2Ctx = mraa_i2c_init(m_bus);
mraa_result_t ret = mraa_i2c_address(m_i2Ctx, m_i2cAddr);
if (ret != MRAA_SUCCESS) {
throw DS3231Exception ("Couldn't initilize I2C.");
}
}
MAXDS3231M::~MAXDS3231M() {
mraa_i2c_stop(m_i2Ctx);
}
void
MAXDS3231M::setDate (Time3231 &time) {
uint8_t *data = (uint8_t *)&time;
i2cWriteReg_N (TIME_CAL_ADDR, 7, data);
}
bool
MAXDS3231M::getDate (Time3231 &time) {
uint8_t buffer[7];
// We need 7 bytes of data.
if (i2cReadReg_N (TIME_CAL_ADDR, 7, buffer) > 6) {
uint8_t century = (buffer[5] & 0x80) >> 7;
time.second = BCDtoDEC(buffer[0]);
time.minute = BCDtoDEC(buffer[1]);
time.hour = BCDtoDEC(buffer[2]);
time.day = BCDtoDEC(buffer[4]);
time.month = BCDtoDEC(buffer[5] & 0x1F);
time.year = (century == 1) ? 2000 + BCDtoDEC(buffer[6]) : 1900 + BCDtoDEC(buffer[6]);
time.weekDay = BCDtoDEC(buffer[3]);
return true;
}
return false;
}
uint16_t
MAXDS3231M::getTemperature () {
uint8_t buffer[2];
uint8_t msb = 0;
uint8_t lsb = 0;
i2cReadReg_N (TEMPERATURE_ADDR, 2, buffer);
msb = buffer[0];
lsb = buffer[1] >> 6;
if ((msb & 0x80) != 0)
msb |= ~((1 << 8) - 1); // if negative get two's complement
return 0.25 * lsb + msb;
}
/*
* **************
* private area
* **************
*/
uint16_t
MAXDS3231M::i2cReadReg_N (int reg, unsigned int len, uint8_t * buffer) {
int readByte = 0;
if (m_i2Ctx == NULL) {
throw DS3231Exception ("Couldn't find initilized I2C.");
}
mraa_i2c_address(m_i2Ctx, m_i2cAddr);
mraa_i2c_write_byte(m_i2Ctx, reg);
mraa_i2c_address(m_i2Ctx, m_i2cAddr);
readByte = mraa_i2c_read(m_i2Ctx, buffer, len);
return readByte;
}
mraa_result_t
MAXDS3231M::i2cWriteReg_N (uint8_t reg, unsigned int len, uint8_t * buffer) {
mraa_result_t error = MRAA_SUCCESS;
if (m_i2Ctx == NULL) {
throw DS3231Exception ("Couldn't find initilized I2C.");
}
error = mraa_i2c_address (m_i2Ctx, m_i2cAddr);
error = mraa_i2c_write (m_i2Ctx, buffer, len);
return error;
}
uint8_t
MAXDS3231M::DECtoBSD(uint8_t data) {
return ((data / 10 * 16) + (data % 10));
}
uint8_t
MAXDS3231M::BCDtoDEC(uint8_t data) {
return ((data / 16 * 10) + (data % 16));
}
<|endoftext|> |
<commit_before>//////////////////////////////////
//
// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5
//
//////////////////////////////////
#include <iostream> // std::cout
#include <fstream> // std::ifsteam
#include <utility> // std::pair
#include <vector> // std::vector
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/spirit/include/qi.hpp>
int main(int argc, char*argv[]){
if (argc != 2)
{
std::cerr << "No file!!!" << std::endl;
return -1;
}
std::ifstream file(argv[1]); // std::ifstream::in ??
std::string str;
/* start get number of vertices */
getline(file, str);
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::parse;
int n;
auto it = str.begin();
bool r = parse(it, str.end(),
int_[([&n](int i){n = i;})] >> int_);
/* end get number of vertices */
/* start get list of edges and weights */
typedef std::pair<int, int> Edge;
std::vector<Edge> Edges; // vector to store std::pair of edges.
std::vector<int> Weights; // vector to weights as integers.
while (getline(file,str)){ // get graph line-by-line.
int Vert1;
int Vert2;
double Weight; // are all weights integer-valued ??
auto it = str.begin(); // initialize iterator for qi::parse.
bool r = parse(it, str.end(), // parse graph.
int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);
Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.
Edges.push_back(edge);
Weights.push_back(Weight);
}
/* end get list of edges and weights */
typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty; // initialize type to store weights on edges.
// adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph; // create graph.
Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.
// here, the graph should be built... Find shortest path.
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.
std::vector<vertex_descriptor> parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.
std::vector<int> distances(boost::num_vertices(g));
// find shortest distances.
boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));
/* start find longest-shortest path */
int maxDistance = 0;
int maxVertex = 0;
// create iterator over vertices.
// vertexPair.first is the iterated element, and .second is the end-index of all vertices.
typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vertexPair;
for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.
{
// replace maxDistance if a greater distance is found, and maxDistance must be less than "infinity" (of 32-bit signed integer).
if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
// if distance == maxDistance, check if vertex index is smaller.
if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
}
// output vertex and distance of the longest-shortest path.
std::cout << "RESULT VERTEX " << maxVertex << std::endl;
std::cout << "RESULT DIST " << maxDistance << std::endl;
/* end find longest-shortest path */
file.close();
return 0;
}
<commit_msg>added timer for ex5<commit_after>//////////////////////////////////
//
// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5 -lboost_timer
//
//////////////////////////////////
#include <iostream> // std::cout
#include <fstream> // std::ifsteam
#include <utility> // std::pair
#include <vector> // std::vector
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/timer/timer.hpp>
int main(int argc, char*argv[]){
if (argc != 2)
{
std::cerr << "No file!!!" << std::endl;
return -1;
}
std::ifstream file(argv[1]); // std::ifstream::in ??
std::string str;
boost::timer::cpu_timer timer;
/* start get number of vertices */
getline(file, str);
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::parse;
int n;
auto it = str.begin();
bool r = parse(it, str.end(),
int_[([&n](int i){n = i;})] >> int_);
/* end get number of vertices */
/* start get list of edges and weights */
typedef std::pair<int, int> Edge;
std::vector<Edge> Edges; // vector to store std::pair of edges.
std::vector<int> Weights; // vector to weights as integers.
while (getline(file,str)){ // get graph line-by-line.
int Vert1;
int Vert2;
double Weight; // are all weights integer-valued ??
auto it = str.begin(); // initialize iterator for qi::parse.
bool r = parse(it, str.end(), // parse graph.
int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);
Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.
Edges.push_back(edge);
Weights.push_back(Weight);
}
/* end get list of edges and weights */
typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty; // initialize type to store weights on edges.
// adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph; // create graph.
Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.
// here, the graph should be built... Find shortest path.
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.
std::vector<vertex_descriptor> parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.
std::vector<int> distances(boost::num_vertices(g));
// find shortest distances.
boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));
/* start find longest-shortest path */
int maxDistance = 0;
int maxVertex = 0;
// create iterator over vertices.
// vertexPair.first is the iterated element, and .second is the end-index of all vertices.
typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vertexPair;
for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.
{
// replace maxDistance if a greater distance is found, and maxDistance must be less than "infinity" (of 32-bit signed integer).
if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
// if distance == maxDistance, check if vertex index is smaller.
if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
}
boost::timer::cpu_times times = timer.elapsed();
// output vertex and distance of the longest-shortest path.
std::cout << "RESULT VERTEX " << maxVertex << std::endl;
std::cout << "RESULT DIST " << maxDistance << std::endl;
/* end find longest-shortest path */
// print CPU- and Wall-Time.
// boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.
std::cout << std::endl;
std::cout << "WALL-CLOCK " << times.wall / 1e9 << "s" << std::endl;
std::cout << "USER TIME " << times.user / 1e9 << "s" << std::endl;
file.close();
return 0;
}
<|endoftext|> |
<commit_before>/**
* Skeleton.cpp
* Contributors:
* * Arthur Sonzogni (author)
* Licence:
* * Public Domain
*/
#include "Skeleton.hpp"
#include <stdexcept>
#include <iostream>
#define GLM_FORCE_RADIANS
#include <glm/gtx/matrix_operation.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define DEGTORAD 0.01745329251f
Skeleton::Skeleton(const std::string& filename)
{
std::ifstream stream;
stream.open(filename);
if (not stream.is_open())
throw std::invalid_argument(std::string("Can't open the file ") + filename);
std::string line;
std::stringstream sstream;
while(std::getline(stream,line))
{
sstream << line << " ";
}
readHierarchy(sstream);
readMotion(sstream);
stream.close();
}
void Skeleton::readHierarchy(std::stringstream& stream)
{
std::string hierarchy,root, name;
stream >> hierarchy >> root >> name;
bool valid = true;
valid &= ( hierarchy == "HIERARCHY" );
valid &= ( root == "ROOT" );
valid &= bool(stream);
if (not valid)
throw std::runtime_error("Invalid BVH file");
else
{
this->name = name;
readSkeleton(stream);
}
}
void Skeleton::readMotion(std::stringstream& stream)
{
// this function assign frame and frameTime
// it read also data with the function addFrameData
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
}
void SkeletonPart::readSkeleton(std::stringstream& stream)
{
// This function reads the BVH file between two curly braces
std::string line;
std::string word;
while(stream >> word)
{
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
if (word == "}")
{
return;
}
}
throw std::runtime_error("Invalid BVH file");
}
void SkeletonPart::addChannel(const std::string& name)
{
if ( name == "Xposition") { motionData.push_back(MotionData()); motionData.back().channel = TX; }
else if ( name == "Yposition") { motionData.push_back(MotionData()); motionData.back().channel = TY; }
else if ( name == "Zposition") { motionData.push_back(MotionData()); motionData.back().channel = TZ; }
else if ( name == "Xrotation") { motionData.push_back(MotionData()); motionData.back().channel = RX; }
else if ( name == "Yrotation") { motionData.push_back(MotionData()); motionData.back().channel = RY; }
else if ( name == "Zrotation") { motionData.push_back(MotionData()); motionData.back().channel = RZ; }
else throw std::invalid_argument("Invalid BVH file, cannot add the channel " + name);
}
void SkeletonPart::addFrameData(std::stringstream& data)
{
// this function read data for every channel and addFrameData for every children
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
}
SkeletonPart::~SkeletonPart()
{
for(auto child = children.begin(); child != children.end(); ++child)
{
delete *child;
}
}
glm::mat4 SkeletonPart::applyTransformation(int frame, glm::mat4 transformation)
{
// compute the new transformation
glm::mat4 xRot(1.f),yRot(1.f),zRot(1.f);
glm::vec3 tOffset(0.f);
for(auto channel = motionData.begin(); channel != motionData.end(); ++channel)
{
//if (frame < channel -> data.size())
switch(channel -> channel)
{
case TX : tOffset += channel -> data[frame] * glm::vec3(1.f,0.f,0.f); break;
case TY : tOffset += channel -> data[frame] * glm::vec3(0.f,1.f,0.f); break;
case TZ : tOffset += channel -> data[frame] * glm::vec3(0.f,0.f,1.f); break;
case RX : xRot = glm::rotate(xRot, DEGTORAD * channel -> data[frame] , glm::vec3(1.f,0.f,0.f)); break;
case RY : yRot = glm::rotate(yRot, DEGTORAD * channel -> data[frame] , glm::vec3(0.f,1.f,0.f)); break;
case RZ : zRot = glm::rotate(zRot, DEGTORAD * channel -> data[frame] , glm::vec3(0.f,0.f,1.f)); break;
}
}
transformation = transformation * glm::translate(glm::mat4(1.f),offset + tOffset);
transformation = transformation * zRot * yRot * xRot;
return transformation;
}
glm::mat4 SkeletonPart::applyRestTransformation(glm::mat4 transformation)
{
return transformation * glm::translate(glm::mat4(1.f),offset);
}
void SkeletonPart::getWireframe(int frame, std::vector<glm::vec3>& output, glm::mat4 transformation, const glm::vec3& reference)
{
transformation = applyTransformation(frame, transformation);
glm::vec3 myPosition = glm::vec3( transformation * glm::vec4(0.f,0.f,0.f,1.f) );
// add a line
output.push_back(reference);
output.push_back(myPosition);
// add line on every children
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWireframe(frame,output,transformation,myPosition);
}
void Skeleton::getWireframe(int frame, std::vector<glm::vec3>& output)
{
SkeletonPart::getWireframe(frame, output, glm::mat4(1.f), glm::vec3(0.f));
}
void SkeletonPart::getTransformation(int frame, std::vector<glm::mat4>& output, glm::mat4 transformation, glm::mat4 rest)
{
transformation = applyTransformation(frame,transformation);
rest = applyRestTransformation(rest);
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getTransformation(frame,output,transformation,rest);
}
void Skeleton::getTransformation(int frame, std::vector<glm::mat4>& output)
{
SkeletonPart::getTransformation(frame,output,glm::mat4(1.f),glm::mat4(1.0));
}
void SkeletonPart::getWeight(PointWeight& output, const glm::vec3& p, int& i, glm::mat4 transformation)
{
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
float weight = 1.0;
// TODO end
output.insert(weight,i);
++i;
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWeight(output,p,i,transformation);
}
void Skeleton::getWeight(PointWeight& output, const glm::vec3& p)
{
int i = 0;
glm::mat4 transformation = applyRestTransformation(glm::mat4(1.f));
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWeight(output,p,i,transformation);
}
int Skeleton::getFrameMirror(float time)
{
int frameMiroir = time / frameTime;
frameMiroir = frameMiroir % ( 2 * frame );
if (frameMiroir >= frame )
frameMiroir = 2 * frame - frameMiroir - 1;
return frameMiroir;
}
<commit_msg>add warning if there is no data when reading<commit_after>/**
* Skeleton.cpp
* Contributors:
* * Arthur Sonzogni (author)
* Licence:
* * Public Domain
*/
#include "Skeleton.hpp"
#include <stdexcept>
#include <iostream>
#define GLM_FORCE_RADIANS
#include <glm/gtx/matrix_operation.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define DEGTORAD 0.01745329251f
Skeleton::Skeleton(const std::string& filename)
{
std::ifstream stream;
stream.open(filename);
if (not stream.is_open())
throw std::invalid_argument(std::string("Can't open the file ") + filename);
std::string line;
std::stringstream sstream;
while(std::getline(stream,line))
{
sstream << line << " ";
}
readHierarchy(sstream);
readMotion(sstream);
stream.close();
}
void Skeleton::readHierarchy(std::stringstream& stream)
{
std::string hierarchy,root, name;
stream >> hierarchy >> root >> name;
bool valid = true;
valid &= ( hierarchy == "HIERARCHY" );
valid &= ( root == "ROOT" );
valid &= bool(stream);
if (not valid)
throw std::runtime_error("Invalid BVH file");
else
{
this->name = name;
readSkeleton(stream);
}
}
void Skeleton::readMotion(std::stringstream& stream)
{
// this function assign frame and frameTime
// it read also data with the function addFrameData
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
}
void SkeletonPart::readSkeleton(std::stringstream& stream)
{
// This function reads the BVH file between two curly braces
std::string line;
std::string word;
while(stream >> word)
{
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
if (word == "}")
{
return;
}
}
throw std::runtime_error("Invalid BVH file");
}
void SkeletonPart::addChannel(const std::string& name)
{
if ( name == "Xposition") { motionData.push_back(MotionData()); motionData.back().channel = TX; }
else if ( name == "Yposition") { motionData.push_back(MotionData()); motionData.back().channel = TY; }
else if ( name == "Zposition") { motionData.push_back(MotionData()); motionData.back().channel = TZ; }
else if ( name == "Xrotation") { motionData.push_back(MotionData()); motionData.back().channel = RX; }
else if ( name == "Yrotation") { motionData.push_back(MotionData()); motionData.back().channel = RY; }
else if ( name == "Zrotation") { motionData.push_back(MotionData()); motionData.back().channel = RZ; }
else throw std::invalid_argument("Invalid BVH file, cannot add the channel " + name);
}
void SkeletonPart::addFrameData(std::stringstream& data)
{
// this function read data for every channel and addFrameData for every children
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
}
SkeletonPart::~SkeletonPart()
{
for(auto child = children.begin(); child != children.end(); ++child)
{
delete *child;
}
}
glm::mat4 SkeletonPart::applyTransformation(int frame, glm::mat4 transformation)
{
// compute the new transformation
glm::mat4 xRot(1.f),yRot(1.f),zRot(1.f);
glm::vec3 tOffset(0.f);
for(auto channel = motionData.begin(); channel != motionData.end(); ++channel)
{
if (frame < channel -> data.size())
switch(channel -> channel)
{
case TX : tOffset += channel -> data[frame] * glm::vec3(1.f,0.f,0.f); break;
case TY : tOffset += channel -> data[frame] * glm::vec3(0.f,1.f,0.f); break;
case TZ : tOffset += channel -> data[frame] * glm::vec3(0.f,0.f,1.f); break;
case RX : xRot = glm::rotate(xRot, DEGTORAD * channel -> data[frame] , glm::vec3(1.f,0.f,0.f)); break;
case RY : yRot = glm::rotate(yRot, DEGTORAD * channel -> data[frame] , glm::vec3(0.f,1.f,0.f)); break;
case RZ : zRot = glm::rotate(zRot, DEGTORAD * channel -> data[frame] , glm::vec3(0.f,0.f,1.f)); break;
}
else
throw std::range_error("There is no frame here");
}
transformation = transformation * glm::translate(glm::mat4(1.f),offset + tOffset);
transformation = transformation * zRot * yRot * xRot;
return transformation;
}
glm::mat4 SkeletonPart::applyRestTransformation(glm::mat4 transformation)
{
return transformation * glm::translate(glm::mat4(1.f),offset);
}
void SkeletonPart::getWireframe(int frame, std::vector<glm::vec3>& output, glm::mat4 transformation, const glm::vec3& reference)
{
transformation = applyTransformation(frame, transformation);
glm::vec3 myPosition = glm::vec3( transformation * glm::vec4(0.f,0.f,0.f,1.f) );
// add a line
output.push_back(reference);
output.push_back(myPosition);
// add line on every children
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWireframe(frame,output,transformation,myPosition);
}
void Skeleton::getWireframe(int frame, std::vector<glm::vec3>& output)
{
SkeletonPart::getWireframe(frame, output, glm::mat4(1.f), glm::vec3(0.f));
}
void SkeletonPart::getTransformation(int frame, std::vector<glm::mat4>& output, glm::mat4 transformation, glm::mat4 rest)
{
transformation = applyTransformation(frame,transformation);
rest = applyRestTransformation(rest);
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getTransformation(frame,output,transformation,rest);
}
void Skeleton::getTransformation(int frame, std::vector<glm::mat4>& output)
{
SkeletonPart::getTransformation(frame,output,glm::mat4(1.f),glm::mat4(1.0));
}
void SkeletonPart::getWeight(PointWeight& output, const glm::vec3& p, int& i, glm::mat4 transformation)
{
// TODO
static bool isDisplayed = false;
if (not isDisplayed)
{
isDisplayed = true;
std::cerr << std::endl << "Please implement the line " << __LINE__ << " file : " << __FILE__ << std::endl << std::endl;
}
float weight = 1.0;
// TODO end
output.insert(weight,i);
++i;
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWeight(output,p,i,transformation);
}
void Skeleton::getWeight(PointWeight& output, const glm::vec3& p)
{
int i = 0;
glm::mat4 transformation = applyRestTransformation(glm::mat4(1.f));
for(auto child = children.begin(); child != children.end(); ++child)
(**child).getWeight(output,p,i,transformation);
}
int Skeleton::getFrameMirror(float time)
{
int frameMiroir = time / frameTime;
frameMiroir = frameMiroir % ( 2 * frame );
if (frameMiroir >= frame )
frameMiroir = 2 * frame - frameMiroir - 1;
return frameMiroir;
}
<|endoftext|> |
<commit_before>#pragma once
#include "messages/limitedqueuesnapshot.hpp"
#include <memory>
#include <mutex>
#include <vector>
namespace chatterino {
namespace messages {
template <typename T>
class LimitedQueue
{
public:
LimitedQueue(int limit = 100, int buffer = 25)
: _offset(0)
, _limit(limit)
, _buffer(buffer)
{
_vector = std::make_shared<std::vector<T>>();
_vector->reserve(_limit + _buffer);
}
void clear()
{
std::lock_guard<std::mutex> lock(_mutex);
_vector = std::make_shared<std::vector<T>>();
_vector->reserve(_limit + _buffer);
_offset = 0;
}
// return true if an item was deleted
// deleted will be set if the item was deleted
bool appendItem(const T &item, T &deleted)
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vector->size() >= _limit) {
// vector is full
if (_offset == _buffer) {
deleted = _vector->at(_offset);
// create new vector
auto newVector = std::make_shared<std::vector<T>>();
newVector->reserve(_limit + _buffer);
for (unsigned int i = 0; i < _limit; ++i) {
newVector->push_back(_vector->at(i + _offset));
}
newVector->push_back(item);
_offset = 0;
_vector = newVector;
return true;
} else {
deleted = _vector->at(_offset);
// append item and increment offset("deleting" first element)
_vector->push_back(item);
_offset++;
return true;
}
} else {
// append item
_vector->push_back(item);
return false;
}
}
messages::LimitedQueueSnapshot<T> getSnapshot()
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vector->size() < _limit) {
return LimitedQueueSnapshot<T>(_vector, _offset, _vector->size());
} else {
return LimitedQueueSnapshot<T>(_vector, _offset, _limit);
}
}
private:
std::shared_ptr<std::vector<T>> _vector;
std::mutex _mutex;
unsigned int _offset;
unsigned int _limit;
unsigned int _buffer;
};
} // namespace messages
} // namespace chatterino
<commit_msg>increased limit for messages to 1000<commit_after>#pragma once
#include "messages/limitedqueuesnapshot.hpp"
#include <memory>
#include <mutex>
#include <vector>
namespace chatterino {
namespace messages {
template <typename T>
class LimitedQueue
{
public:
LimitedQueue(int limit = 1000, int buffer = 250)
: _offset(0)
, _limit(limit)
, _buffer(buffer)
{
_vector = std::make_shared<std::vector<T>>();
_vector->reserve(_limit + _buffer);
}
void clear()
{
std::lock_guard<std::mutex> lock(_mutex);
_vector = std::make_shared<std::vector<T>>();
_vector->reserve(_limit + _buffer);
_offset = 0;
}
// return true if an item was deleted
// deleted will be set if the item was deleted
bool appendItem(const T &item, T &deleted)
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vector->size() >= _limit) {
// vector is full
if (_offset == _buffer) {
deleted = _vector->at(_offset);
// create new vector
auto newVector = std::make_shared<std::vector<T>>();
newVector->reserve(_limit + _buffer);
for (unsigned int i = 0; i < _limit; ++i) {
newVector->push_back(_vector->at(i + _offset));
}
newVector->push_back(item);
_offset = 0;
_vector = newVector;
return true;
} else {
deleted = _vector->at(_offset);
// append item and increment offset("deleting" first element)
_vector->push_back(item);
_offset++;
return true;
}
} else {
// append item
_vector->push_back(item);
return false;
}
}
messages::LimitedQueueSnapshot<T> getSnapshot()
{
std::lock_guard<std::mutex> lock(_mutex);
if (_vector->size() < _limit) {
return LimitedQueueSnapshot<T>(_vector, _offset, _vector->size());
} else {
return LimitedQueueSnapshot<T>(_vector, _offset, _limit);
}
}
private:
std::shared_ptr<std::vector<T>> _vector;
std::mutex _mutex;
unsigned int _offset;
unsigned int _limit;
unsigned int _buffer;
};
} // namespace messages
} // namespace chatterino
<|endoftext|> |
<commit_before>//===-- tsan_platform_mac.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
// Mac-specific code.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_MAC
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_posix.h"
#include "sanitizer_common/sanitizer_procmaps.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
#include "tsan_platform.h"
#include "tsan_rtl.h"
#include "tsan_flags.h"
#include <mach/mach.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <sched.h>
namespace __tsan {
#if !SANITIZER_GO
static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) {
atomic_uintptr_t *a = (atomic_uintptr_t *)dst;
void *val = (void *)atomic_load_relaxed(a);
atomic_signal_fence(memory_order_acquire); // Turns the previous load into
// acquire wrt signals.
if (UNLIKELY(val == nullptr)) {
val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
CHECK(val);
void *cmp = nullptr;
if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val,
memory_order_acq_rel)) {
internal_munmap(val, size);
val = cmp;
}
}
return val;
}
// On OS X, accessing TLVs via __thread or manually by using pthread_key_* is
// problematic, because there are several places where interceptors are called
// when TLVs are not accessible (early process startup, thread cleanup, ...).
// The following provides a "poor man's TLV" implementation, where we use the
// shadow memory of the pointer returned by pthread_self() to store a pointer to
// the ThreadState object. The main thread's ThreadState is stored separately
// in a static variable, because we need to access it even before the
// shadow memory is set up.
static uptr main_thread_identity = 0;
ALIGNED(64) static char main_thread_state[sizeof(ThreadState)];
ThreadState **cur_thread_location() {
ThreadState **thread_identity = (ThreadState **)pthread_self();
return ((uptr)thread_identity == main_thread_identity) ? nullptr
: thread_identity;
}
ThreadState *cur_thread() {
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr || main_thread_identity == 0) {
return (ThreadState *)&main_thread_state;
}
ThreadState **fake_tls = (ThreadState **)MemToShadow((uptr)thr_state_loc);
ThreadState *thr = (ThreadState *)SignalSafeGetOrAllocate(
(uptr *)fake_tls, sizeof(ThreadState));
return thr;
}
// TODO(kuba.brecka): This is not async-signal-safe. In particular, we call
// munmap first and then clear `fake_tls`; if we receive a signal in between,
// handler will try to access the unmapped ThreadState.
void cur_thread_finalize() {
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr) {
// Calling dispatch_main() or xpc_main() actually invokes pthread_exit to
// exit the main thread. Let's keep the main thread's ThreadState.
return;
}
ThreadState **fake_tls = (ThreadState **)MemToShadow((uptr)thr_state_loc);
internal_munmap(*fake_tls, sizeof(ThreadState));
*fake_tls = nullptr;
}
#endif
void FlushShadowMemory() {
}
static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) {
vm_address_t address = start;
vm_address_t end_address = end;
uptr resident_pages = 0;
uptr dirty_pages = 0;
while (address < end_address) {
vm_size_t vm_region_size;
mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
vm_region_extended_info_data_t vm_region_info;
mach_port_t object_name;
kern_return_t ret = vm_region_64(
mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO,
(vm_region_info_t)&vm_region_info, &count, &object_name);
if (ret != KERN_SUCCESS) break;
resident_pages += vm_region_info.pages_resident;
dirty_pages += vm_region_info.pages_dirtied;
address += vm_region_size;
}
*res = resident_pages * GetPageSizeCached();
*dirty = dirty_pages * GetPageSizeCached();
}
void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
uptr shadow_res, shadow_dirty;
uptr meta_res, meta_dirty;
uptr trace_res, trace_dirty;
RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty);
RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty);
RegionMemUsage(TraceMemBeg(), TraceMemEnd(), &trace_res, &trace_dirty);
#if !SANITIZER_GO
uptr low_res, low_dirty;
uptr high_res, high_dirty;
uptr heap_res, heap_dirty;
RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty);
RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty);
RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty);
#else // !SANITIZER_GO
uptr app_res, app_dirty;
RegionMemUsage(AppMemBeg(), AppMemEnd(), &app_res, &app_dirty);
#endif
StackDepotStats *stacks = StackDepotGetStats();
internal_snprintf(buf, buf_size,
"shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"traces (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#if !SANITIZER_GO
"low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#else // !SANITIZER_GO
"app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#endif
"stacks: %ld unique IDs, %ld kB allocated\n"
"threads: %ld total, %ld live\n"
"------------------------------\n",
ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024,
MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024,
TraceMemBeg(), TraceMemEnd(), trace_res / 1024, trace_dirty / 1024,
#if !SANITIZER_GO
LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024,
HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024,
HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024,
#else // !SANITIZER_GO
AppMemBeg(), AppMemEnd(), app_res / 1024, app_dirty / 1024,
#endif
stacks->n_uniq_ids, stacks->allocated / 1024,
nthread, nlive);
}
#if !SANITIZER_GO
void InitializeShadowMemoryPlatform() { }
// On OS X, GCD worker threads are created without a call to pthread_create. We
// need to properly register these threads with ThreadCreate and ThreadStart.
// These threads don't have a parent thread, as they are created "spuriously".
// We're using a libpthread API that notifies us about a newly created thread.
// The `thread == pthread_self()` check indicates this is actually a worker
// thread. If it's just a regular thread, this hook is called on the parent
// thread.
typedef void (*pthread_introspection_hook_t)(unsigned int event,
pthread_t thread, void *addr,
size_t size);
extern "C" pthread_introspection_hook_t pthread_introspection_hook_install(
pthread_introspection_hook_t hook);
static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1;
static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3;
static pthread_introspection_hook_t prev_pthread_introspection_hook;
static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
void *addr, size_t size) {
if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
if (thread == pthread_self()) {
// The current thread is a newly created GCD worker thread.
ThreadState *thr = cur_thread();
Processor *proc = ProcCreate();
ProcWire(proc, thr);
ThreadState *parent_thread_state = nullptr; // No parent.
int tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true);
CHECK_NE(tid, 0);
ThreadStart(thr, tid, GetTid(), /*workerthread*/ true);
}
} else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
if (thread == pthread_self()) {
ThreadState *thr = cur_thread();
if (thr->tctx) {
DestroyThreadState();
}
}
}
if (prev_pthread_introspection_hook != nullptr)
prev_pthread_introspection_hook(event, thread, addr, size);
}
#endif
void InitializePlatformEarly() {
}
void InitializePlatform() {
DisableCoreDumperIfNecessary();
#if !SANITIZER_GO
CheckAndProtect();
CHECK_EQ(main_thread_identity, 0);
main_thread_identity = (uptr)pthread_self();
prev_pthread_introspection_hook =
pthread_introspection_hook_install(&my_pthread_introspection_hook);
#endif
}
#if !SANITIZER_GO
void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
// The pointer to the ThreadState object is stored in the shadow memory
// of the tls.
uptr tls_end = tls_addr + tls_size;
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr) {
MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, tls_size);
} else {
uptr thr_state_start = (uptr)thr_state_loc;
uptr thr_state_end = thr_state_start + sizeof(uptr);
CHECK_GE(thr_state_start, tls_addr);
CHECK_LE(thr_state_start, tls_addr + tls_size);
CHECK_GE(thr_state_end, tls_addr);
CHECK_LE(thr_state_end, tls_addr + tls_size);
MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr,
thr_state_start - tls_addr);
MemoryRangeImitateWrite(thr, /*pc=*/2, thr_state_end,
tls_end - thr_state_end);
}
}
#endif
#if !SANITIZER_GO
// Note: this function runs with async signals enabled,
// so it must not touch any tsan state.
int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
void *abstime), void *c, void *m, void *abstime,
void(*cleanup)(void *arg), void *arg) {
// pthread_cleanup_push/pop are hardcore macros mess.
// We can't intercept nor call them w/o including pthread.h.
int res;
pthread_cleanup_push(cleanup, arg);
res = fn(c, m, abstime);
pthread_cleanup_pop(0);
return res;
}
#endif
} // namespace __tsan
#endif // SANITIZER_MAC
<commit_msg>[tsan] Add a max VM address check for Darwin/AArch64<commit_after>//===-- tsan_platform_mac.cc ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
// Mac-specific code.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_MAC
#include "sanitizer_common/sanitizer_atomic.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_posix.h"
#include "sanitizer_common/sanitizer_procmaps.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
#include "tsan_platform.h"
#include "tsan_rtl.h"
#include "tsan_flags.h"
#include <mach/mach.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <sched.h>
namespace __tsan {
#if !SANITIZER_GO
static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) {
atomic_uintptr_t *a = (atomic_uintptr_t *)dst;
void *val = (void *)atomic_load_relaxed(a);
atomic_signal_fence(memory_order_acquire); // Turns the previous load into
// acquire wrt signals.
if (UNLIKELY(val == nullptr)) {
val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
CHECK(val);
void *cmp = nullptr;
if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val,
memory_order_acq_rel)) {
internal_munmap(val, size);
val = cmp;
}
}
return val;
}
// On OS X, accessing TLVs via __thread or manually by using pthread_key_* is
// problematic, because there are several places where interceptors are called
// when TLVs are not accessible (early process startup, thread cleanup, ...).
// The following provides a "poor man's TLV" implementation, where we use the
// shadow memory of the pointer returned by pthread_self() to store a pointer to
// the ThreadState object. The main thread's ThreadState is stored separately
// in a static variable, because we need to access it even before the
// shadow memory is set up.
static uptr main_thread_identity = 0;
ALIGNED(64) static char main_thread_state[sizeof(ThreadState)];
ThreadState **cur_thread_location() {
ThreadState **thread_identity = (ThreadState **)pthread_self();
return ((uptr)thread_identity == main_thread_identity) ? nullptr
: thread_identity;
}
ThreadState *cur_thread() {
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr || main_thread_identity == 0) {
return (ThreadState *)&main_thread_state;
}
ThreadState **fake_tls = (ThreadState **)MemToShadow((uptr)thr_state_loc);
ThreadState *thr = (ThreadState *)SignalSafeGetOrAllocate(
(uptr *)fake_tls, sizeof(ThreadState));
return thr;
}
// TODO(kuba.brecka): This is not async-signal-safe. In particular, we call
// munmap first and then clear `fake_tls`; if we receive a signal in between,
// handler will try to access the unmapped ThreadState.
void cur_thread_finalize() {
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr) {
// Calling dispatch_main() or xpc_main() actually invokes pthread_exit to
// exit the main thread. Let's keep the main thread's ThreadState.
return;
}
ThreadState **fake_tls = (ThreadState **)MemToShadow((uptr)thr_state_loc);
internal_munmap(*fake_tls, sizeof(ThreadState));
*fake_tls = nullptr;
}
#endif
void FlushShadowMemory() {
}
static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) {
vm_address_t address = start;
vm_address_t end_address = end;
uptr resident_pages = 0;
uptr dirty_pages = 0;
while (address < end_address) {
vm_size_t vm_region_size;
mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
vm_region_extended_info_data_t vm_region_info;
mach_port_t object_name;
kern_return_t ret = vm_region_64(
mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO,
(vm_region_info_t)&vm_region_info, &count, &object_name);
if (ret != KERN_SUCCESS) break;
resident_pages += vm_region_info.pages_resident;
dirty_pages += vm_region_info.pages_dirtied;
address += vm_region_size;
}
*res = resident_pages * GetPageSizeCached();
*dirty = dirty_pages * GetPageSizeCached();
}
void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
uptr shadow_res, shadow_dirty;
uptr meta_res, meta_dirty;
uptr trace_res, trace_dirty;
RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty);
RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty);
RegionMemUsage(TraceMemBeg(), TraceMemEnd(), &trace_res, &trace_dirty);
#if !SANITIZER_GO
uptr low_res, low_dirty;
uptr high_res, high_dirty;
uptr heap_res, heap_dirty;
RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty);
RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty);
RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty);
#else // !SANITIZER_GO
uptr app_res, app_dirty;
RegionMemUsage(AppMemBeg(), AppMemEnd(), &app_res, &app_dirty);
#endif
StackDepotStats *stacks = StackDepotGetStats();
internal_snprintf(buf, buf_size,
"shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"traces (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#if !SANITIZER_GO
"low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
"heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#else // !SANITIZER_GO
"app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n"
#endif
"stacks: %ld unique IDs, %ld kB allocated\n"
"threads: %ld total, %ld live\n"
"------------------------------\n",
ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024,
MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024,
TraceMemBeg(), TraceMemEnd(), trace_res / 1024, trace_dirty / 1024,
#if !SANITIZER_GO
LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024,
HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024,
HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024,
#else // !SANITIZER_GO
AppMemBeg(), AppMemEnd(), app_res / 1024, app_dirty / 1024,
#endif
stacks->n_uniq_ids, stacks->allocated / 1024,
nthread, nlive);
}
#if !SANITIZER_GO
void InitializeShadowMemoryPlatform() { }
// On OS X, GCD worker threads are created without a call to pthread_create. We
// need to properly register these threads with ThreadCreate and ThreadStart.
// These threads don't have a parent thread, as they are created "spuriously".
// We're using a libpthread API that notifies us about a newly created thread.
// The `thread == pthread_self()` check indicates this is actually a worker
// thread. If it's just a regular thread, this hook is called on the parent
// thread.
typedef void (*pthread_introspection_hook_t)(unsigned int event,
pthread_t thread, void *addr,
size_t size);
extern "C" pthread_introspection_hook_t pthread_introspection_hook_install(
pthread_introspection_hook_t hook);
static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1;
static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3;
static pthread_introspection_hook_t prev_pthread_introspection_hook;
static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
void *addr, size_t size) {
if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) {
if (thread == pthread_self()) {
// The current thread is a newly created GCD worker thread.
ThreadState *thr = cur_thread();
Processor *proc = ProcCreate();
ProcWire(proc, thr);
ThreadState *parent_thread_state = nullptr; // No parent.
int tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true);
CHECK_NE(tid, 0);
ThreadStart(thr, tid, GetTid(), /*workerthread*/ true);
}
} else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) {
if (thread == pthread_self()) {
ThreadState *thr = cur_thread();
if (thr->tctx) {
DestroyThreadState();
}
}
}
if (prev_pthread_introspection_hook != nullptr)
prev_pthread_introspection_hook(event, thread, addr, size);
}
#endif
void InitializePlatformEarly() {
#if defined(__aarch64__)
uptr max_vm = GetMaxVirtualAddress() + 1;
if (max_vm != kHiAppMemEnd) {
Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n",
max_vm, kHiAppMemEnd);
Die();
}
#endif
}
void InitializePlatform() {
DisableCoreDumperIfNecessary();
#if !SANITIZER_GO
CheckAndProtect();
CHECK_EQ(main_thread_identity, 0);
main_thread_identity = (uptr)pthread_self();
prev_pthread_introspection_hook =
pthread_introspection_hook_install(&my_pthread_introspection_hook);
#endif
}
#if !SANITIZER_GO
void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
// The pointer to the ThreadState object is stored in the shadow memory
// of the tls.
uptr tls_end = tls_addr + tls_size;
ThreadState **thr_state_loc = cur_thread_location();
if (thr_state_loc == nullptr) {
MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, tls_size);
} else {
uptr thr_state_start = (uptr)thr_state_loc;
uptr thr_state_end = thr_state_start + sizeof(uptr);
CHECK_GE(thr_state_start, tls_addr);
CHECK_LE(thr_state_start, tls_addr + tls_size);
CHECK_GE(thr_state_end, tls_addr);
CHECK_LE(thr_state_end, tls_addr + tls_size);
MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr,
thr_state_start - tls_addr);
MemoryRangeImitateWrite(thr, /*pc=*/2, thr_state_end,
tls_end - thr_state_end);
}
}
#endif
#if !SANITIZER_GO
// Note: this function runs with async signals enabled,
// so it must not touch any tsan state.
int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
void *abstime), void *c, void *m, void *abstime,
void(*cleanup)(void *arg), void *arg) {
// pthread_cleanup_push/pop are hardcore macros mess.
// We can't intercept nor call them w/o including pthread.h.
int res;
pthread_cleanup_push(cleanup, arg);
res = fn(c, m, abstime);
pthread_cleanup_pop(0);
return res;
}
#endif
} // namespace __tsan
#endif // SANITIZER_MAC
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ MTU3 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/mtu3.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"
#include "common/format.hpp"
/// F_PCLKA は変換パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKA
# error "mtu_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MTU 制御クラス
@param[in] MTU MTU ユニット
@param[in] MTASK メイン割り込みタスク
@param[in] OTASK オーバーフロー割り込みタスク
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class MTUX, class MTASK = utils::null_task, class OTASK = utils::null_task>
class mtu_io {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エッジ・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class edge_type : uint8_t {
positive, ///< 立ち上がり
negative, ///< 立下り
dual, ///< 両エッジ
};
private:
struct task_t {
volatile uint32_t tgr_adr_;
volatile uint32_t cap_count_;
volatile uint16_t cap_tick_;
volatile uint16_t ovf_tick_;
volatile uint16_t ovf_limit_;
volatile uint16_t ovf_count_;
task_t() : tgr_adr_(MTUX::TGRA.address()), cap_count_(0),
cap_tick_(0), ovf_tick_(0),
ovf_limit_(1221), ovf_count_(0) { }
void clear() {
cap_tick_ = 0;
ovf_tick_ = 0;
cap_count_ = 0;
ovf_count_ = 0;
}
void load_cap() {
cap_count_ = (static_cast<uint32_t>(ovf_tick_) << 16) | rd16_(tgr_adr_);
}
};
static task_t task_t_;
static MTASK mtask_;
static OTASK otask_;
uint32_t clk_base_;
static INTERRUPT_FUNC void cap_task_()
{
++task_t_.cap_tick_;
task_t_.load_cap();
mtask_();
task_t_.ovf_tick_ = 0;
}
static INTERRUPT_FUNC void ovf_task_()
{
++task_t_.ovf_tick_;
if(task_t_.ovf_tick_ >= task_t_.ovf_limit_) {
task_t_.ovf_tick_ = 0;
MTUX::TCNT = 0;
++task_t_.ovf_count_;
}
otask_();
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mtu_io() noexcept : clk_base_(F_PCLKA) { }
//-----------------------------------------------------------------//
/*!
@brief ベース・クロックの設定
@param[in] clk ベース・クロック
*/
//-----------------------------------------------------------------//
void set_base_clock(uint32_t clk) noexcept { clk_base_ = clk; }
//-----------------------------------------------------------------//
/*!
@brief ベース・クロックの取得
@return ベース・クロック
*/
//-----------------------------------------------------------------//
uint32_t get_base_clock() const noexcept { return clk_base_; }
//-----------------------------------------------------------------//
/*!
@brief インプットキャプチャ開始 @n
※カウントクロックは「set_limit_clock」により @n
変更が可能。
@param[in] ch 入力チャネル
@param[in] et エッジ・タイプ
@param[in] level 割り込みレベル(割り込みを使わない場合エラー)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start_capture(typename MTUX::channel ch, edge_type et, uint8_t level) noexcept
{
if(level == 0) return false;
if(MTUX::get_peripheral() == peripheral::MTU5) { // MTU5 はインプットキャプチャとして利用不可
return false;
}
uint8_t idx = static_cast<uint8_t>(ch);
if(idx >= 4) return false;
power_cfg::turn(MTUX::get_peripheral());
MTUX::enable_port(ch);
uint8_t etd = 0;
switch(et) {
case edge_type::positive: etd = 0b1000; break;
case edge_type::negative: etd = 0b1001; break;
case edge_type::dual: etd = 0b1011; break;
default: break;
}
MTUX::TIOR.set(ch, etd);
uint8_t dv = 0;
static const uint8_t cclr[4] = { 0b001, 0b010, 0b101, 0b110 };
// CKEG: 立ち上がりエッジでカウントアップ
MTUX::TCR = MTUX::TCR.TPSC.b(dv)
| MTUX::TCR.CKEG.b(0b00)
| MTUX::TCR.CCLR.b(cclr[idx]); // ※インプットキャプチャ入力で TCNT はクリア
MTUX::TCR2 = 0x00;
MTUX::TMDR1 = 0x00; // 通常動作
if(level > 0) {
set_interrupt_task(ovf_task_, static_cast<uint32_t>(MTUX::get_vec(MTUX::interrupt::OVF)));
icu_mgr::set_level(MTUX::get_vec(MTUX::interrupt::OVF), level);
ICU::VECTOR cvec = MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch));
set_interrupt_task(cap_task_, static_cast<uint32_t>(cvec));
icu_mgr::set_level(MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch)), level);
MTUX::TIER = (1 << static_cast<uint8_t>(ch)) | MTUX::TIER.TCIEV.b();
}
task_t_.clear();
// 各チャネルに相当するジャネラルレジスタ
task_t_.tgr_adr_ = MTUX::TGRA.address() + static_cast<uint32_t>(ch) * 2;
wr16_(task_t_.tgr_adr_, 0x0000);
MTUX::TCNT = 0;
MTUX::enable();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ、リミットの設定
@param[in] limit インプット・キャプチャ、リミット
*/
//-----------------------------------------------------------------//
void set_capture_limit(uint16_t limit) noexcept
{
task_t_.limit_ovf_ = limit;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャのオーバーフローカウント取得
@return インプット・キャプチャのオーバーフローカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_ovf() const noexcept
{
return task_t_.ovf_count_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャカウント取得
@return インプット・キャプチャカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_tick() const noexcept
{
return task_t_.cap_tick_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ値を取得
@return インプット・キャプチャ値
*/
//-----------------------------------------------------------------//
uint32_t get_capture() const noexcept
{
return task_t_.cap_count_;
}
//-----------------------------------------------------------------//
/*!
@brief MTASK クラスの参照
@return MTASK クラス
*/
//-----------------------------------------------------------------//
static MTASK& at_main_task() noexcept { return mtask_; }
//-----------------------------------------------------------------//
/*!
@brief OTASK クラスの参照
@return OTASK クラス
*/
//-----------------------------------------------------------------//
static OTASK& at_ovfl_task() noexcept { return otask_; }
};
template <class MTUX, class MTASK, class OTASK>
typename mtu_io<MTUX, MTASK, OTASK>::task_t mtu_io<MTUX, MTASK, OTASK>::task_t_;
template <class MTUX, class MTASK, class OTASK> MTASK mtu_io<MTUX, MTASK, OTASK>::mtask_;
template <class MTUX, class MTASK, class OTASK> OTASK mtu_io<MTUX, MTASK, OTASK>::otask_;
}
<commit_msg>add output API<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ MTU3 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/mtu3.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"
#include "common/format.hpp"
/// F_PCLKA は変換パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKA
# error "mtu_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MTU 制御クラス
@param[in] MTU MTU ユニット
@param[in] MTASK メイン割り込みタスク
@param[in] OTASK オーバーフロー割り込みタスク
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class MTUX, class MTASK = utils::null_task, class OTASK = utils::null_task>
class mtu_io {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief キャプチャー・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class capture_type : uint8_t {
positive, ///< 立ち上がり
negative, ///< 立下り
dual, ///< 両エッジ
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief アウトプット・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class output_type : uint8_t {
low_to_high, ///< 初期0で、変化で1
high_to_low, ///< 初期1で、変化で0
toggle, ///< トグル出力
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief キャプチャー構造体
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct capture_t {
volatile uint32_t all_count_;
volatile uint16_t ovfw_limit_; ///< オーバーフローの最大値
volatile uint16_t ovfw_count_;
capture_t() : all_count_(0),
ovfw_limit_(F_PCLKA / 65536), // タイムアウト1秒
ovfw_count_(0)
{ }
void clear() {
all_count_ = 0;
ovfw_count_ = 0;
}
};
private:
uint32_t clk_base_;
struct task_t {
volatile uint32_t tgr_adr_; // TGR の実アドレス
volatile uint32_t main_tick_;
volatile uint32_t ovfw_tick_;
capture_t cap_;
task_t() : tgr_adr_(MTUX::TGRA.address()),
main_tick_(0), ovfw_tick_(0), cap_() { }
};
static task_t tt_;
static MTASK mtask_;
static OTASK otask_;
static INTERRUPT_FUNC void cap_task_()
{
++tt_.main_tick_;
tt_.cap_.all_count_ = (tt_.ovfw_tick_ << 16) | rd16_(tt_.tgr_adr_);
mtask_();
tt_.ovfw_tick_ = 0;
}
static INTERRUPT_FUNC void ovf_task_()
{
++tt_.ovfw_tick_;
if(tt_.ovfw_tick_ >= tt_.cap_.ovfw_limit_) {
tt_.ovfw_tick_ = 0;
MTUX::TCNT = 0;
++tt_.cap_.ovfw_count_;
}
otask_();
}
static INTERRUPT_FUNC void out_task_()
{
++tt_.main_tick_;
mtask_();
}
// ch: A, B, C, D (0 to 3)
// dv: 0 to 10
void set_TCR_(typename MTUX::channel ch, uint8_t dv)
{
static const uint8_t ckt[] = {
0b000000, // (0) 1/1
0b001000, // (1) 1/2
0b000001, // (2) 1/4
0b010000, // (3) 1/8
0b000010, // (4) 1/16
0b011000, // (5) 1/32
0b000011, // (6) 1/64
0b100000, // (7) 1/128(NG: 1/256)
0b100000, // (8) 1/256
0b101000, // (9) 1/512(NG: 1/1024)
0b101000, // (10) 1/1024
};
static const uint8_t cclr[4] = { 0b001, 0b010, 0b101, 0b110 };
MTUX::TCR = MTUX::TCR.TPSC.b(ckt[dv] & 7)
| MTUX::TCR.CKEG.b(0b00)
| MTUX::TCR.CCLR.b(cclr[static_cast<uint8_t>(ch)]);
MTUX::TCR2 = MTUX::TCR2.TPSC2.b((ckt[dv] >> 3) & 7);
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mtu_io() noexcept : clk_base_(F_PCLKA) { }
//-----------------------------------------------------------------//
/*!
@brief ベース・クロック(インプット・キャプチャ)の設定 @n
※MTU3 モジュールへの供給クロックのN分の1を設定
@param[in] clk ベース・クロック
*/
//-----------------------------------------------------------------//
void set_base_clock(uint32_t clk) noexcept {
uint32_t a = F_PCLKA;
while(a < clk) {
a <<= 1;
}
clk_base_ = a;
}
//-----------------------------------------------------------------//
/*!
@brief ベース・クロックの取得
@return ベース・クロック
*/
//-----------------------------------------------------------------//
uint32_t get_base_clock() const noexcept { return clk_base_; }
//-----------------------------------------------------------------//
/*!
@brief 出力開始(コンペア・マッチ・タイマー)
@param[in] ch 出力チャネル
@param[in] ot 出力タイプ
@param[in] frq 出力周波数
@param[in] level 割り込みレベル
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start_output(typename MTUX::channel ch, output_type ot, uint32_t frq, uint8_t level = 0) noexcept
{
power_cfg::turn(MTUX::get_peripheral());
MTUX::enable_port(ch);
uint8_t dv = 0;
uint32_t match = F_PCLKA / frq;
while(match < 65536) {
++dv;
bool mod = match & 1;
match /= 2;
if(mod) ++match;
}
if(dv > 10) {
// overflow clock divide...
return false;
}
uint8_t ctd = 0;
switch(ot) {
case output_type::low_to_high: ctd = 0b0010; break;
case output_type::high_to_low: ctd = 0b0101; break;
case output_type::toggle:
{
ctd = 0b0111;
bool mod = match & 1;
match /= 2;
if(mod) ++match;
}
break;
default: break;
}
MTUX::TIOR.set(ch, ctd);
set_TCR_(ch, dv);
MTUX::TMDR1 = 0x00; // 通常動作
if(level > 0) {
ICU::VECTOR cvec = MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch));
set_interrupt_task(out_task_, static_cast<uint32_t>(cvec));
icu_mgr::set_level(MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch)), level);
MTUX::TIER = (1 << static_cast<uint8_t>(ch)) | MTUX::TIER.TCIEV.b();
}
// 各チャネルに相当するジャネラルレジスタ
tt_.tgr_adr_ = MTUX::TGRA.address() + static_cast<uint32_t>(ch) * 2;
wr16_(tt_.tgr_adr_, match - 1);
MTUX::TCNT = 0;
MTUX::enable();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief インプットキャプチャ開始 @n
※カウントクロックは「set_limit_clock」により @n
変更が可能。
@param[in] ch 入力チャネル
@param[in] ct キャプチャ・タイプ
@param[in] level 割り込みレベル(割り込みを使わない場合エラー)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start_capture(typename MTUX::channel ch, capture_type ct, uint8_t level) noexcept
{
if(level == 0) return false;
if(MTUX::get_peripheral() == peripheral::MTU5) { // MTU5 はインプットキャプチャとして利用不可
return false;
}
power_cfg::turn(MTUX::get_peripheral());
MTUX::enable_port(ch);
uint8_t ctd = 0;
switch(ct) {
case capture_type::positive: ctd = 0b1000; break;
case capture_type::negative: ctd = 0b1001; break;
case capture_type::dual: ctd = 0b1011; break;
default: break;
}
MTUX::TIOR.set(ch, ctd);
uint32_t dv = F_PCLKA / clk_base_;
--dv;
if(dv >= 10) dv = 10;
set_TCR_(ch, dv);
MTUX::TMDR1 = 0x00; // 通常動作
if(level > 0) {
set_interrupt_task(ovf_task_, static_cast<uint32_t>(MTUX::get_vec(MTUX::interrupt::OVF)));
icu_mgr::set_level(MTUX::get_vec(MTUX::interrupt::OVF), level);
ICU::VECTOR cvec = MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch));
set_interrupt_task(cap_task_, static_cast<uint32_t>(cvec));
icu_mgr::set_level(MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch)), level);
MTUX::TIER = (1 << static_cast<uint8_t>(ch)) | MTUX::TIER.TCIEV.b();
}
tt_.cap_.clear();
// 各チャネルに相当するジャネラルレジスタ
tt_.tgr_adr_ = MTUX::TGRA.address() + static_cast<uint32_t>(ch) * 2;
wr16_(tt_.tgr_adr_, 0x0000);
MTUX::TCNT = 0;
MTUX::enable();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief キャプチャ構造体の参照(RO)
@return キャプチャ構造体
*/
//-----------------------------------------------------------------//
const capture_t& get_capture() const noexcept { return tt_.cap_; }
//-----------------------------------------------------------------//
/*!
@brief キャプチャ構造体の参照
@return キャプチャ構造体
*/
//-----------------------------------------------------------------//
capture_t& at_capture() noexcept { return tt_.cap_; }
//-----------------------------------------------------------------//
/*!
@brief MTASK クラスの参照
@return MTASK クラス
*/
//-----------------------------------------------------------------//
static MTASK& at_main_task() noexcept { return mtask_; }
//-----------------------------------------------------------------//
/*!
@brief OTASK クラスの参照
@return OTASK クラス
*/
//-----------------------------------------------------------------//
static OTASK& at_ovfl_task() noexcept { return otask_; }
};
template <class MTUX, class MTASK, class OTASK>
typename mtu_io<MTUX, MTASK, OTASK>::task_t mtu_io<MTUX, MTASK, OTASK>::tt_;
template <class MTUX, class MTASK, class OTASK> MTASK mtu_io<MTUX, MTASK, OTASK>::mtask_;
template <class MTUX, class MTASK, class OTASK> OTASK mtu_io<MTUX, MTASK, OTASK>::otask_;
}
<|endoftext|> |
<commit_before>/**
* @file nmf_test.cpp
* @author Mohan Rajendran
*
* Test file for NMF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/amf/amf.hpp>
#include <mlpack/methods/amf/init_rules/random_acol_init.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_div.hpp>
#include <mlpack/methods/amf/update_rules/nmf_als.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(NMFTest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::amf;
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Default case.
*/
BOOST_AUTO_TEST_CASE(NMFDefaultTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 0.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.012);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random Acol initialization distance minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFAcolDistTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
const size_t r = 12;
SimpleResidueTermination srt(1e-7, 10000);
AMF<SimpleResidueTermination,RandomAcolInitialization<> >
nmf(srt);
nmf.Apply(v, r, w, h);
mat wh = w * h;
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.012);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random initialization divergence minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFRandomDivTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<SimpleResidueTermination,
RandomInitialization,
NMFMultiplicativeDivergenceUpdate> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 0.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.012);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix. This uses the random initialization and alternating least
* squares update rule.
*/
BOOST_AUTO_TEST_CASE(NMFALSTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
SimpleResidueTermination srt(1e-12, 50000);
AMF<SimpleResidueTermination, RandomAcolInitialization<>, NMFALSUpdate>
nmf(srt);
nmf.Apply(v, r, w, h);
const mat wh = w * h;
// Make sure reconstruction error is not too high. 8% tolerance. It seems
// like ALS doesn't converge to results that are as good. It also seems to be
// particularly sensitive to initial conditions.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.08);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. Random Acol initialization,
* distance minimization update.
*/
BOOST_AUTO_TEST_CASE(SparseNMFAcolDistTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(20, 20, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 20; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 15;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomAcolInitialization<> > nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed); // Set random seed so results are the same.
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h;
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. This uses the random
* initialization and alternating least squares update rule.
*/
BOOST_AUTO_TEST_CASE(SparseNMFALSTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(10, 10, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 10; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 5;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomInitialization, NMFALSUpdate> nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed);
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h; // In general vp won't be sparse.
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Slightly loosen tolerances for NMF tests.<commit_after>/**
* @file nmf_test.cpp
* @author Mohan Rajendran
*
* Test file for NMF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/amf/amf.hpp>
#include <mlpack/methods/amf/init_rules/random_acol_init.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_div.hpp>
#include <mlpack/methods/amf/update_rules/nmf_als.hpp>
#include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(NMFTest);
using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::amf;
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Default case.
*/
BOOST_AUTO_TEST_CASE(NMFDefaultTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 1.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random Acol initialization distance minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFAcolDistTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
const size_t r = 12;
SimpleResidueTermination srt(1e-7, 10000);
AMF<SimpleResidueTermination,RandomAcolInitialization<> >
nmf(srt);
nmf.Apply(v, r, w, h);
mat wh = w * h;
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix. Random initialization divergence minimization update.
*/
BOOST_AUTO_TEST_CASE(NMFRandomDivTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
AMF<SimpleResidueTermination,
RandomInitialization,
NMFMultiplicativeDivergenceUpdate> nmf;
nmf.Apply(v, r, w, h);
mat wh = w * h;
// Make sure reconstruction error is not too high. 1.5% tolerance.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.015);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix. This uses the random initialization and alternating least
* squares update rule.
*/
BOOST_AUTO_TEST_CASE(NMFALSTest)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w = randu<mat>(20, 12);
mat h = randu<mat>(12, 20);
mat v = w * h;
size_t r = 12;
SimpleResidueTermination srt(1e-12, 50000);
AMF<SimpleResidueTermination, RandomAcolInitialization<>, NMFALSUpdate>
nmf(srt);
nmf.Apply(v, r, w, h);
const mat wh = w * h;
// Make sure reconstruction error is not too high. 8% tolerance. It seems
// like ALS doesn't converge to results that are as good. It also seems to be
// particularly sensitive to initial conditions.
BOOST_REQUIRE_SMALL(arma::norm(v - wh, "fro") / arma::norm(v, "fro"),
0.08);
}
/**
* Check the if the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. Random Acol initialization,
* distance minimization update.
*/
BOOST_AUTO_TEST_CASE(SparseNMFAcolDistTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(20, 20, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 20; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 15;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomAcolInitialization<> > nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed); // Set random seed so results are the same.
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h;
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
/**
* Check that the product of the calculated factorization is close to the
* input matrix, with a sparse input matrix. This uses the random
* initialization and alternating least squares update rule.
*/
BOOST_AUTO_TEST_CASE(SparseNMFALSTest)
{
// We have to ensure that the residues aren't NaNs. This can happen when a
// matrix is created with all zeros in a column or row.
double denseResidue = std::numeric_limits<double>::quiet_NaN();
double sparseResidue = std::numeric_limits<double>::quiet_NaN();
mat vp, dvp; // Resulting matrices.
while (sparseResidue != sparseResidue && denseResidue != denseResidue)
{
mlpack::math::RandomSeed(std::time(NULL));
mat w, h;
sp_mat v;
v.sprandu(10, 10, 0.3);
// Ensure there is at least one nonzero element in every row and column.
for (size_t i = 0; i < 10; ++i)
v(i, i) += 1e-5;
mat dv(v); // Make a dense copy.
mat dw, dh;
size_t r = 5;
SimpleResidueTermination srt(1e-10, 10000);
AMF<SimpleResidueTermination, RandomInitialization, NMFALSUpdate> nmf(srt);
const size_t seed = mlpack::math::RandInt(1000000);
mlpack::math::RandomSeed(seed);
nmf.Apply(v, r, w, h);
mlpack::math::RandomSeed(seed);
nmf.Apply(dv, r, dw, dh);
// Reconstruct matrices.
vp = w * h; // In general vp won't be sparse.
dvp = dw * dh;
denseResidue = arma::norm(v - vp, "fro");
sparseResidue = arma::norm(dv - dvp, "fro");
}
// Make sure the results are about equal for the W and H matrices.
BOOST_REQUIRE_SMALL(arma::norm(vp - dvp, "fro") / arma::norm(vp, "fro"),
1e-5);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2014 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 navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/err.h>
#include <uORB/uORB.h>
#include <uORB/topics/mission.h>
#include <uORB/topics/home_position.h>
#include "rtl.h"
RTL::RTL() :
SuperBlock(NULL, "RTL"),
_mavlink_fd(-1),
_rtl_state(RTL_STATE_NONE),
_home_position({}),
_param_return_alt(this, "RETURN_ALT"),
_param_descend_alt(this, "DESCEND_ALT"),
_param_land_delay(this, "LAND_DELAY"),
_loiter_radius(50),
_acceptance_radius(50)
{
/* load initial params */
updateParams();
}
RTL::~RTL()
{
}
void
RTL::set_home_position(const home_position_s *new_home_position)
{
memcpy(&_home_position, new_home_position, sizeof(home_position_s));
}
bool
RTL::get_current_rtl_item(const vehicle_global_position_s *global_position, mission_item_s *new_mission_item)
{
/* Open mavlink fd */
if (_mavlink_fd < 0) {
/* try to open the mavlink log device every once in a while */
_mavlink_fd = open(MAVLINK_LOG_DEVICE, 0);
}
/* decide if we need climb */
if (_rtl_state == RTL_STATE_NONE) {
if (global_position->alt < _home_position.alt + _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
} else {
_rtl_state = RTL_STATE_RETURN;
}
}
/* if switching directly to return state, set altitude setpoint to current altitude */
if (_rtl_state == RTL_STATE_RETURN) {
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = global_position->alt;
}
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _home_position.alt + _param_return_alt.get();
/* TODO understand and fix this */
// if (_vstatus.condition_landed) {
// climb_alt = fmaxf(climb_alt, _global_pos.alt + _parameters.rtl_alt);
// }
new_mission_item->lat = global_position->lat;
new_mission_item->lon = global_position->lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = climb_alt;
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_TAKEOFF;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: climb to %d meters above home",
(int)(climb_alt - _home_position.alt));
break;
}
case RTL_STATE_RETURN: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
/* TODO: add this again */
// don't change altitude
// if (_pos_sp_triplet.previous.valid) {
// /* if previous setpoint is valid then use it to calculate heading to home */
// new_mission_item->yaw = get_bearing_to_next_waypoint(_pos_sp_triplet.previous.lat, _pos_sp_triplet.previous.lon, new_mission_item->lat, new_mission_item->lon);
// } else {
// /* else use current position */
// new_mission_item->yaw = get_bearing_to_next_waypoint(_global_pos.lat, _global_pos.lon, new_mission_item->lat, new_mission_item->lon);
// }
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_WAYPOINT;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: return at %d meters above home",
(int)(new_mission_item->altitude - _home_position.alt));
break;
}
case RTL_STATE_DESCEND: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = _home_position.alt + _param_descend_alt.get();
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_WAYPOINT;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = _param_land_delay.get() > -0.001f;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: descend to %d meters above home",
(int)(new_mission_item->altitude - _home_position.alt));
break;
}
case RTL_STATE_LAND: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = _home_position.alt;
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_LAND;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: land at home");
break;
}
case RTL_STATE_FINISHED: {
/* nothing to do, report fail */
return false;
}
default:
return false;
}
return true;
}
bool
RTL::get_next_rtl_item(mission_item_s *new_mission_item)
{
/* TODO implement */
return false;
}
void
RTL::move_to_next()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < 0) {
_rtl_state = RTL_STATE_FINISHED;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_FINISHED;
break;
case RTL_STATE_FINISHED:
break;
default:
break;
}
}<commit_msg>navigator: corrected the RTL waypoint types<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2014 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 navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/err.h>
#include <uORB/uORB.h>
#include <uORB/topics/mission.h>
#include <uORB/topics/home_position.h>
#include "rtl.h"
RTL::RTL() :
SuperBlock(NULL, "RTL"),
_mavlink_fd(-1),
_rtl_state(RTL_STATE_NONE),
_home_position({}),
_param_return_alt(this, "RETURN_ALT"),
_param_descend_alt(this, "DESCEND_ALT"),
_param_land_delay(this, "LAND_DELAY"),
_loiter_radius(50),
_acceptance_radius(50)
{
/* load initial params */
updateParams();
}
RTL::~RTL()
{
}
void
RTL::set_home_position(const home_position_s *new_home_position)
{
memcpy(&_home_position, new_home_position, sizeof(home_position_s));
}
bool
RTL::get_current_rtl_item(const vehicle_global_position_s *global_position, mission_item_s *new_mission_item)
{
/* Open mavlink fd */
if (_mavlink_fd < 0) {
/* try to open the mavlink log device every once in a while */
_mavlink_fd = open(MAVLINK_LOG_DEVICE, 0);
}
/* decide if we need climb */
if (_rtl_state == RTL_STATE_NONE) {
if (global_position->alt < _home_position.alt + _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
} else {
_rtl_state = RTL_STATE_RETURN;
}
}
/* if switching directly to return state, set altitude setpoint to current altitude */
if (_rtl_state == RTL_STATE_RETURN) {
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = global_position->alt;
}
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _home_position.alt + _param_return_alt.get();
/* TODO understand and fix this */
// if (_vstatus.condition_landed) {
// climb_alt = fmaxf(climb_alt, _global_pos.alt + _parameters.rtl_alt);
// }
new_mission_item->lat = global_position->lat;
new_mission_item->lon = global_position->lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = climb_alt;
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_WAYPOINT;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: climb to %d meters above home",
(int)(climb_alt - _home_position.alt));
break;
}
case RTL_STATE_RETURN: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
/* TODO: add this again */
// don't change altitude
// if (_pos_sp_triplet.previous.valid) {
// /* if previous setpoint is valid then use it to calculate heading to home */
// new_mission_item->yaw = get_bearing_to_next_waypoint(_pos_sp_triplet.previous.lat, _pos_sp_triplet.previous.lon, new_mission_item->lat, new_mission_item->lon);
// } else {
// /* else use current position */
// new_mission_item->yaw = get_bearing_to_next_waypoint(_global_pos.lat, _global_pos.lon, new_mission_item->lat, new_mission_item->lon);
// }
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_WAYPOINT;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: return at %d meters above home",
(int)(new_mission_item->altitude - _home_position.alt));
break;
}
case RTL_STATE_DESCEND: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = _home_position.alt + _param_descend_alt.get();
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = _param_land_delay.get() > -0.001f;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: descend to %d meters above home",
(int)(new_mission_item->altitude - _home_position.alt));
break;
}
case RTL_STATE_LAND: {
new_mission_item->lat = _home_position.lat;
new_mission_item->lon = _home_position.lon;
new_mission_item->altitude_is_relative = false;
new_mission_item->altitude = _home_position.alt;
new_mission_item->yaw = NAN;
new_mission_item->loiter_radius = _loiter_radius;
new_mission_item->loiter_direction = 1;
new_mission_item->nav_cmd = NAV_CMD_LAND;
new_mission_item->acceptance_radius = _acceptance_radius;
new_mission_item->time_inside = 0.0f;
new_mission_item->pitch_min = 0.0f;
new_mission_item->autocontinue = true;
new_mission_item->origin = ORIGIN_ONBOARD;
mavlink_log_info(_mavlink_fd, "#audio: RTL: land at home");
break;
}
case RTL_STATE_FINISHED: {
/* nothing to do, report fail */
return false;
}
default:
return false;
}
return true;
}
bool
RTL::get_next_rtl_item(mission_item_s *new_mission_item)
{
/* TODO implement */
return false;
}
void
RTL::move_to_next()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < 0) {
_rtl_state = RTL_STATE_FINISHED;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_FINISHED;
break;
case RTL_STATE_FINISHED:
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>#include "contour.hpp"
ContourTransition::ContourTransition( cv::Mat& image )
{
copy_data( image );
}
void ContourTransition::bw_push_transition(std::vector<IndexTransition> const & indexTransition)
{
std::for_each(indexTransition.begin(), indexTransition.end(), [ this ](auto& el){
matDataTrans( el.row, el.col ).transition = el.transition;
});
}
void ContourTransition::copy_data( cv::Mat& image )
{
set_transition_to_no();
matDataTrans.create( image.rows, image.cols );
for(int row = 0; row < matDataTrans.rows; row++ )
for(int col = 0; col < matDataTrans.cols; col++ )
{
matDataTrans(row, col).pixel = *image.ptr(row, col);
}
}
void ContourTransition::set_transition_to_no()
{
for(int row = 0; row < matDataTrans.rows; row++ )
for(int col = 0; col < matDataTrans.cols; col++ )
{
matDataTrans(row, col).transition = Transition::no;
}
}
Preprocess::Preprocess( cv::Mat_<double> filterKernel_, cv::Mat srcImg_ ) : srcImgSize(srcImg_.rows, srcImg_.cols)
{
filterKernel = filterKernel_.clone();
}
cv::Mat Preprocess::get_thick_kernel( cv::Mat& image, int dilationSize )
{
cv::Mat thickKernel = image.clone();
cv::Mat gray, edge, draw;
cvtColor(image, gray, CV_BGR2GRAY);
blur( gray, gray, cv::Size(7, 7) );
int apertureSize = 5;
Canny( gray, edge, 80, 500, apertureSize, true);//
edge.convertTo(thickKernel, CV_8U);
//dilate here
cv::Mat element = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilationSize + 1, 2*dilationSize+1 ),
cv::Point( dilationSize, dilationSize ) );
/// Apply the dilation operation
dilate( thickKernel, thickKernel, element );
return thickKernel;
}
ContourTransition Preprocess::get_correction_edge( cv::Mat const & thickKernel, std::vector<IndexTransition> const & indexTransition )
{
if(filterKernel.rows % 2 != 0 | filterKernel.cols % 2 != 0 )
std::cout << "\nnot even filterKernel Preprocess::get_correction_edge\n";
cv::Mat thickKernelBorder;
cv::copyMakeBorder( thickKernel, thickKernelBorder, filterKernel.rows / 2, filterKernel.rows / 2, filterKernel.cols / 2, filterKernel.cols / 2, cv::BORDER_REFLECT);//to be safe
cv::Rect rct( filterKernel.cols, filterKernel.rows, thickKernel.cols + filterKernel.cols, thickKernel.rows + filterKernel.rows);//TBD
cv::Mat kernelSilentBorder = thickKernelBorder(rct);
cv::Mat_<Transition> matTrans = this->cvt_it_to_matT( indexTransition );
}
Transition Preprocess::get_direction( int const row, int const col, cv::Mat_<Transition> matTransSilentBorder )
{
Transition result{ empty };
std::pair<double, uint> histo[ transDirCombo ];
for( int i = 0; i < transDirCombo; i++ )
{
histo[i] = std::pair<double, uint>( 0.0, i );
}
for(int _row = row - filterKernel.rows / 2; _row < row + filterKernel.rows; _row++ )
for(int _col = col - filterKernel.cols/2; _col < col + filterKernel.cols; _col++ )
{
histo[ matTransSilentBorder(_row, _col) >> distinctDir ].second += filterKernel(_row - row + filterKernel.rows, _col - col + filterKernel.cols );
}
/*
uint currentMax = 0;
uint secondMax = 0;
for( int i = 0; i< transDirCombo; i++)//find two max
{
if (histo[i] > histo[currentMax])
{
secondMax = currentMax;
currentMax = i;
}
}
*/
double normalizer = 0;
for( int i = 0; i < transDirCombo; i++ )
{
normalizer += histo[i].first;
}
std::pair<double, uint> orgHisto[ transDirCombo ];
std::copy( histo, histo + transDirCombo, orgHisto );
for( int i = 0; i < transDirCombo; i++ )
{
for( int j = 0; j < transDirCombo; j++ )
{
if( i & j == i )
{
histo[i].first += orgHisto[j].first;
}
}
}
for( int i = 0; i < transDirCombo; i++ )
{
if( histo[i].first / normalizer > 0.25 );
}
result <<= distinctDir;
if( DataProcess::is_noise_detection( result ))
return Transition::unknown;
return result;
}
cv::Mat_<Transition> Preprocess::cvt_it_to_matT( std::vector<IndexTransition> const & indexTransition )
{
cv::Mat_<Transition> result;
cv::Mat_<Transition> tmpResult( srcImgSize, Transition::no );
std::for_each( indexTransition.begin(), indexTransition.end(), [&tmpResult]( auto& el){
tmpResult( el.row, el.col) = el.transition;
});
cv::copyMakeBorder( tmpResult, result, filterKernel.rows / 2, filterKernel.rows / 2, filterKernel.cols / 2, filterKernel.cols / 2, cv::BORDER_REFLECT);//to be safe
return result;
}
cv::Mat_<double> MakeFilter::get_square_filter( int filterSize )
{
if( filterSize % 2 == 0)
filterSize -= 1;
cv::Mat_<double> result( cv::Size2i( filterSize, filterSize ), 1/( filterSize * filterSize ) );
return result;
}<commit_msg>get_direction finished<commit_after>#include "contour.hpp"
ContourTransition::ContourTransition( cv::Mat& image )
{
copy_data( image );
}
void ContourTransition::bw_push_transition(std::vector<IndexTransition> const & indexTransition)
{
std::for_each(indexTransition.begin(), indexTransition.end(), [ this ](auto& el){
matDataTrans( el.row, el.col ).transition = el.transition;
});
}
void ContourTransition::copy_data( cv::Mat& image )
{
set_transition_to_no();
matDataTrans.create( image.rows, image.cols );
for(int row = 0; row < matDataTrans.rows; row++ )
for(int col = 0; col < matDataTrans.cols; col++ )
{
matDataTrans(row, col).pixel = *image.ptr(row, col);
}
}
void ContourTransition::set_transition_to_no()
{
for(int row = 0; row < matDataTrans.rows; row++ )
for(int col = 0; col < matDataTrans.cols; col++ )
{
matDataTrans(row, col).transition = Transition::no;
}
}
Preprocess::Preprocess( cv::Mat_<double> filterKernel_, cv::Mat srcImg_ ) : srcImgSize(srcImg_.rows, srcImg_.cols)
{
filterKernel = filterKernel_.clone();
}
cv::Mat Preprocess::get_thick_kernel( cv::Mat& image, int dilationSize )
{
cv::Mat thickKernel = image.clone();
cv::Mat gray, edge, draw;
cvtColor(image, gray, CV_BGR2GRAY);
blur( gray, gray, cv::Size(7, 7) );
int apertureSize = 5;
Canny( gray, edge, 80, 500, apertureSize, true);//
edge.convertTo(thickKernel, CV_8U);
//dilate here
cv::Mat element = cv::getStructuringElement( cv::MORPH_ELLIPSE,
cv::Size( 2*dilationSize + 1, 2*dilationSize+1 ),
cv::Point( dilationSize, dilationSize ) );
/// Apply the dilation operation
dilate( thickKernel, thickKernel, element );
return thickKernel;
}
ContourTransition Preprocess::get_correction_edge( cv::Mat const & thickKernel, std::vector<IndexTransition> const & indexTransition )
{
if(filterKernel.rows % 2 != 0 | filterKernel.cols % 2 != 0 )
std::cout << "\nnot even filterKernel Preprocess::get_correction_edge\n";
cv::Mat thickKernelBorder;
cv::copyMakeBorder( thickKernel, thickKernelBorder, filterKernel.rows / 2, filterKernel.rows / 2, filterKernel.cols / 2, filterKernel.cols / 2, cv::BORDER_REFLECT);//to be safe
cv::Rect rct( filterKernel.cols, filterKernel.rows, thickKernel.cols + filterKernel.cols, thickKernel.rows + filterKernel.rows);//TBD
cv::Mat kernelSilentBorder = thickKernelBorder(rct);
cv::Mat_<Transition> matTrans = this->cvt_it_to_matT( indexTransition );
}
Transition Preprocess::get_direction( int const row, int const col, cv::Mat_<Transition> matTransSilentBorder )
{
Transition result{ empty };
std::pair<double, uint> histo[ transDirCombo ];
for( int i = 0; i < transDirCombo; i++ )
{
histo[i] = std::pair<double, uint>( 0.0, i );
}
for(int _row = row - filterKernel.rows / 2; _row <= row + filterKernel.rows / 2; _row++ )
for(int _col = col - filterKernel.cols/2; _col <= col + filterKernel.cols / 2; _col++ )
{
histo[ matTransSilentBorder(_row, _col) >> distinctDir ].second += filterKernel(_row - row + filterKernel.rows / 2, _col - col + filterKernel.cols / 2 );
}
std::pair<double, uint> orgHisto[ transDirCombo ];
std::copy( histo, histo + transDirCombo, orgHisto );
for( int i = 0; i < transDirCombo; i++ )//concatenate similar transition probability
{
for( int j = 0; j < transDirCombo; j++ )
{
if( i & j == i )
{
histo[i].first += orgHisto[j].first;
}
}
}
std::sort(histo, histo + transDirCombo, std::greater<std::pair<double, uint>>());
if( histo[0].first / histo[1].first > 2 )
{
result = static_cast<Transition>( histo[0].second << distinctDir );
if( DataProcess::is_noise_detection( result ))
{
return Transition::unknown;
}
else
{
return result;
}
}
else
{
result = static_cast<Transition>( ( histo[0].second | histo[1].second )<< distinctDir );
if( DataProcess::is_noise_detection( result ))
{
return Transition::unknown;
}
else
{
return result;
}
}
}
cv::Mat_<Transition> Preprocess::cvt_it_to_matT( std::vector<IndexTransition> const & indexTransition )
{
cv::Mat_<Transition> result;
cv::Mat_<Transition> tmpResult( srcImgSize, Transition::no );
std::for_each( indexTransition.begin(), indexTransition.end(), [&tmpResult]( auto& el){
tmpResult( el.row, el.col) = el.transition;
});
cv::copyMakeBorder( tmpResult, result, filterKernel.rows / 2, filterKernel.rows / 2, filterKernel.cols / 2, filterKernel.cols / 2, cv::BORDER_REFLECT);//to be safe
return result;
}
cv::Mat_<double> MakeFilter::get_square_filter( int filterSize )
{
if( filterSize % 2 == 0)
filterSize -= 1;
cv::Mat_<double> result( cv::Size2i( filterSize, filterSize ), 1/( filterSize * filterSize ) );
return result;
}<|endoftext|> |
<commit_before>#include "CppUnitTest.h"
#include "JsonArray.h"
#include "JsonObject.h"
using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests
{
TEST_CLASS(Issue10)
{
struct Person {
int id;
char name[32];
};
Person persons[2];
public:
TEST_METHOD_INITIALIZE(Initialize)
{
Person boss;
boss.id = 1;
strcpy(boss.name, "Jeff");
Person employee;
employee.id = 2;
strcpy(employee.name, "John");
persons[0] = boss;
persons[1] = employee;
}
TEST_METHOD(WrongWayToAddObjectInAnArray)
{
JsonArray<2> json;
for (int i = 0; i < 2; i++)
{
JsonObject<2> object;
object["id"] = persons[i].id;
object["name"] = persons[i].name;
json.add(object);
}
char buffer[256];
json.printTo(buffer, sizeof(buffer));
Assert::AreEqual("[]", buffer);
}
TEST_METHOD(RightWayToAddObjectInAnArray)
{
JsonArray<2> json;
JsonObject<2> object[2];
for (int i = 0; i < 1; i++)
{
object[i] = JsonObject<2>();
object[i]["id"] = persons[i].id;
object[i]["name"] = persons[i].name;
json.add(object[i]);
}
char buffer[256];
json.printTo(buffer, sizeof(buffer));
Assert::AreEqual("[TODO]", buffer);
}
};
}<commit_msg>Fixed tests<commit_after>#include "CppUnitTest.h"
#include "JsonArray.h"
#include "JsonObject.h"
using namespace ArduinoJson::Generator;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace JsonGeneratorTests
{
TEST_CLASS(Issue10)
{
struct Person {
int id;
char name[32];
};
Person persons[2];
public:
TEST_METHOD_INITIALIZE(Initialize)
{
Person boss;
boss.id = 1;
strcpy(boss.name, "Jeff");
Person employee;
employee.id = 2;
strcpy(employee.name, "John");
persons[0] = boss;
persons[1] = employee;
}
TEST_METHOD(WrongWayToAddObjectInAnArray)
{
JsonArray<2> json;
for (int i = 0; i < 2; i++)
{
JsonObject<2> object;
object["id"] = persons[i].id;
object["name"] = persons[i].name;
json.add(object); // <- Adding a reference to a temporary variable
}
char buffer[256];
json.printTo(buffer, sizeof(buffer));
// the same values are repeated, that's normal
Assert::AreEqual("[{\"id\":2,\"name\":\"John\"},{\"id\":2,\"name\":\"John\"}]", buffer);
}
TEST_METHOD(RightWayToAddObjectInAnArray)
{
JsonArray<2> json;
JsonObject<2> object[2];
for (int i = 0; i < 2; i++)
{
object[i]["id"] = persons[i].id;
object[i]["name"] = persons[i].name;
json.add(object[i]);
}
char buffer[256];
json.printTo(buffer, sizeof(buffer));
Assert::AreEqual("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]", buffer);
}
};
}<|endoftext|> |
<commit_before>#pragma once
#include <sstream>
#include <stdexcept>
#include <deque>
namespace nervana {
class conststring
{
public:
template<size_t SIZE>
constexpr conststring(const char(&p)[SIZE]) :
_string(p),
_size(SIZE)
{
}
constexpr char operator[](size_t i) const {
return i < _size ? _string[i] : throw std::out_of_range("");
}
constexpr const char* get_ptr(size_t offset) const {
return &_string[ offset ];
}
constexpr size_t size() const { return _size; }
private:
const char* _string;
size_t _size;
};
constexpr const char* find_last(conststring s, size_t offset, char ch) {
return offset == 0 ? s.get_ptr(0) : (s[offset] == ch ? s.get_ptr(offset+1) : find_last(s, offset-1, ch));
}
constexpr const char* find_last(conststring s, char ch) {
return find_last(s, s.size()-1, ch);
}
constexpr const char* get_file_name(conststring s) {
return find_last(s, '/');
}
enum class LOG_TYPE {
_LOG_TYPE_ERROR,
_LOG_TYPE_WARNING,
_LOG_TYPE_INFO,
};
class log_helper {
public:
log_helper(LOG_TYPE, const char* file, int line, const char* func);
~log_helper();
std::ostream& stream() { return _stream; }
private:
std::stringstream _stream;
};
class logger {
friend class log_helper;
public:
static void set_log_path(const std::string& path);
static void start();
static void stop();
private:
static void log_item(const std::string& s);
static void process_event(const std::string& s);
static void thread_entry(void* param);
static std::string log_path;
static std::deque<std::string> queue;
};
#define ERR nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_ERROR, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define WARN nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_WARNING, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define INFO nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_INFO, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define ERR_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_ERROR, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
#define WARN_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_WARNING, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
#define INFO_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_INFO, get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
}
<commit_msg>Completes namespacing for logging macro (#4)<commit_after>#pragma once
#include <sstream>
#include <stdexcept>
#include <deque>
namespace nervana {
class conststring
{
public:
template<size_t SIZE>
constexpr conststring(const char(&p)[SIZE]) :
_string(p),
_size(SIZE)
{
}
constexpr char operator[](size_t i) const {
return i < _size ? _string[i] : throw std::out_of_range("");
}
constexpr const char* get_ptr(size_t offset) const {
return &_string[ offset ];
}
constexpr size_t size() const { return _size; }
private:
const char* _string;
size_t _size;
};
constexpr const char* find_last(conststring s, size_t offset, char ch) {
return offset == 0 ? s.get_ptr(0) : (s[offset] == ch ? s.get_ptr(offset+1) : find_last(s, offset-1, ch));
}
constexpr const char* find_last(conststring s, char ch) {
return find_last(s, s.size()-1, ch);
}
constexpr const char* get_file_name(conststring s) {
return find_last(s, '/');
}
enum class LOG_TYPE {
_LOG_TYPE_ERROR,
_LOG_TYPE_WARNING,
_LOG_TYPE_INFO,
};
class log_helper {
public:
log_helper(LOG_TYPE, const char* file, int line, const char* func);
~log_helper();
std::ostream& stream() { return _stream; }
private:
std::stringstream _stream;
};
class logger {
friend class log_helper;
public:
static void set_log_path(const std::string& path);
static void start();
static void stop();
private:
static void log_item(const std::string& s);
static void process_event(const std::string& s);
static void thread_entry(void* param);
static std::string log_path;
static std::deque<std::string> queue;
};
#define ERR nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_ERROR, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define WARN nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_WARNING, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define INFO nervana::log_helper(nervana::LOG_TYPE::_LOG_TYPE_INFO, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__).stream()
#define ERR_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_ERROR, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
#define WARN_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_WARNING, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
#define INFO_OBJ(obj) nervana::log_helper obj(nervana::LOG_TYPE::_LOG_TYPE_INFO, nervana::get_file_name(__FILE__), __LINE__, __PRETTY_FUNCTION__)
}
<|endoftext|> |
<commit_before>// @(#)root/quadp:$Id$
// Author: Eddy Offermann May 2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/*************************************************************************
* Parts of this file are copied from the OOQP distribution and *
* are subject to the following license: *
* *
* COPYRIGHT 2001 UNIVERSITY OF CHICAGO *
* *
* The copyright holder hereby grants you royalty-free rights to use, *
* reproduce, prepare derivative works, and to redistribute this software*
* to others, provided that any changes are clearly documented. This *
* software was authored by: *
* *
* E. MICHAEL GERTZ gertz@mcs.anl.gov *
* Mathematics and Computer Science Division *
* Argonne National Laboratory *
* 9700 S. Cass Avenue *
* Argonne, IL 60439-4844 *
* *
* STEPHEN J. WRIGHT swright@cs.wisc.edu *
* Computer Sciences Department *
* University of Wisconsin *
* 1210 West Dayton Street *
* Madison, WI 53706 FAX: (608)262-9777 *
* *
* Any questions or comments may be directed to one of the authors. *
* *
* ARGONNE NATIONAL LABORATORY (ANL), WITH FACILITIES IN THE STATES OF *
* ILLINOIS AND IDAHO, IS OWNED BY THE UNITED STATES GOVERNMENT, AND *
* OPERATED BY THE UNIVERSITY OF CHICAGO UNDER PROVISION OF A CONTRACT *
* WITH THE DEPARTMENT OF ENERGY. *
*************************************************************************/
#include "Riostream.h"
#include "TQpDataSparse.h"
//////////////////////////////////////////////////////////////////////////
// //
// TQpDataSparse //
// //
// Data for the sparse QP formulation //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TQpDataSparse)
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(Int_t nx,Int_t my,Int_t mz)
: TQpDataBase(nx,my,mz)
{
// Constructor
fQ.ResizeTo(fNx,fNx);
fA.ResizeTo(fMy,fNx);
fC.ResizeTo(fMz,fNx);
}
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(TVectorD &c_in, TMatrixDSparse &Q_in,
TVectorD &xlow_in,TVectorD &ixlow_in,
TVectorD &xupp_in,TVectorD &ixupp_in,
TMatrixDSparse &A_in, TVectorD &bA_in,
TMatrixDSparse &C_in,
TVectorD &clow_in,TVectorD &iclow_in,
TVectorD &cupp_in,TVectorD &icupp_in)
{
// Constructor
fG .ResizeTo(c_in) ; fG = c_in;
fBa .ResizeTo(bA_in) ; fBa = bA_in;
fXloBound.ResizeTo(xlow_in) ; fXloBound = xlow_in;
fXloIndex.ResizeTo(ixlow_in); fXloIndex = ixlow_in;
fXupBound.ResizeTo(xupp_in) ; fXupBound = xupp_in;
fXupIndex.ResizeTo(ixupp_in); fXupIndex = ixupp_in;
fCloBound.ResizeTo(clow_in) ; fCloBound = clow_in;
fCloIndex.ResizeTo(iclow_in); fCloIndex = iclow_in;
fCupBound.ResizeTo(cupp_in) ; fCupBound = cupp_in;
fCupIndex.ResizeTo(icupp_in); fCupIndex = icupp_in;
fNx = fG.GetNrows();
fQ.Use(Q_in);
if (A_in.GetNrows() > 0) {
fA.Use(A_in);
fMy = fA.GetNrows();
} else
fMy = 0;
if (C_in.GetNrows()) {
fC.Use(C_in);
fMz = fC.GetNrows();
} else
fMz = 0;
fQ.Print();
fA.Print();
fC.Print();
printf("fNx: %d\n",fNx);
printf("fMy: %d\n",fMy);
printf("fMz: %d\n",fMz);
}
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(const TQpDataSparse &another) : TQpDataBase(another)
{
// Copy constructor
*this = another;
}
//______________________________________________________________________________
void TQpDataSparse::SetNonZeros(Int_t nnzQ,Int_t nnzA,Int_t nnzC)
{
// Allocate space for the appropriate number of non-zeros in the matrices
fQ.SetSparseIndex(nnzQ);
fA.SetSparseIndex(nnzA);
fC.SetSparseIndex(nnzC);
}
//______________________________________________________________________________
void TQpDataSparse::Qmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x )
{
// calculate y = beta*y + alpha*(fQ*x)
y *= beta;
if (fQ.GetNoElements() > 0)
y += alpha*(fQ*x);
}
//______________________________________________________________________________
void TQpDataSparse::Amult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fA*x)
y *= beta;
if (fA.GetNoElements() > 0)
y += alpha*(fA*x);
}
//______________________________________________________________________________
void TQpDataSparse::Cmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fC*x)
y *= beta;
if (fC.GetNoElements() > 0)
y += alpha*(fC*x);
}
//______________________________________________________________________________
void TQpDataSparse::ATransmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fA^T*x)
y *= beta;
if (fA.GetNoElements() > 0)
y += alpha*(TMatrixDSparse(TMatrixDSparse::kTransposed,fA)*x);
}
//______________________________________________________________________________
void TQpDataSparse::CTransmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fC^T*x)
y *= beta;
if (fC.GetNoElements() > 0)
y += alpha*(TMatrixDSparse(TMatrixDSparse::kTransposed,fC)*x);
}
//______________________________________________________________________________
Double_t TQpDataSparse::DataNorm()
{
// Return the largest component of several vectors in the data class
Double_t norm = 0.0;
Double_t componentNorm = fG.NormInf();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fQ_abs(fQ);
componentNorm = (fQ_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
componentNorm = fBa.NormInf();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fA_abs(fQ);
componentNorm = (fA_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fC_abs(fQ);
componentNorm = (fC_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fXloBound.MatchesNonZeroPattern(fXloIndex));
componentNorm = fXloBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fXupBound.MatchesNonZeroPattern(fXupIndex));
componentNorm = fXupBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fCloBound.MatchesNonZeroPattern(fCloIndex));
componentNorm = fCloBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fCupBound.MatchesNonZeroPattern(fCupIndex));
componentNorm = fCupBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
return norm;
}
//______________________________________________________________________________
void TQpDataSparse::Print(Option_t * /*opt*/) const
{
// Print class members
fQ.Print("Q");
fG.Print("c");
fXloBound.Print("xlow");
fXloIndex.Print("ixlow");
fXupBound.Print("xupp");
fXupIndex.Print("ixupp");
fA.Print("A");
fBa.Print("b");
fC.Print("C");
fCloBound.Print("clow");
fCloIndex.Print("iclow");
fCupBound.Print("cupp");
fCupIndex.Print("icupp");
}
//______________________________________________________________________________
void TQpDataSparse::PutQIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the Hessian Q into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fQ);
}
//______________________________________________________________________________
void TQpDataSparse::PutAIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the constraint matrix A into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fA);
}
//______________________________________________________________________________
void TQpDataSparse::PutCIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the constraint matrix C into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fC);
}
//______________________________________________________________________________
void TQpDataSparse::GetDiagonalOfQ(TVectorD &dq)
{
// Return in vector dq the diagonal of matrix fQ
const Int_t n = TMath::Min(fQ.GetNrows(),fQ.GetNcols());
dq.ResizeTo(n);
dq = TMatrixDSparseDiag(fQ);
}
//______________________________________________________________________________
Double_t TQpDataSparse::ObjectiveValue(TQpVar *vars)
{
// Return value of the objective function
TVectorD tmp(fG);
this->Qmult(1.0,tmp,0.5,vars->fX);
return tmp*vars->fX;
}
//______________________________________________________________________________
void TQpDataSparse::DataRandom(TVectorD &x,TVectorD &y,TVectorD &z,TVectorD &s)
{
// Choose randomly a QP problem
Double_t ix = 3074.20374;
TVectorD xdual(fNx);
this->RandomlyChooseBoundedVariables(x,xdual,fXloBound,fXloIndex,fXupBound,fXupIndex,ix,.25,.25,.25);
TVectorD sprime(fMz);
this->RandomlyChooseBoundedVariables(sprime,z,fCloBound,fCloIndex,fCupBound,fCupIndex,ix,.25,.25,.5);
fQ.RandomizePD(0.0,1.0,ix);
fA.Randomize(-10.0,10.0,ix);
fC.Randomize(-10.0,10.0,ix);
y .Randomize(-10.0,10.0,ix);
// fG = - fQ x + A^T y + C^T z + xdual
fG = xdual;
fG -= fQ*x;
fG += TMatrixDSparse(TMatrixDSparse::kTransposed,fA)*y;
fG += TMatrixDSparse(TMatrixDSparse::kTransposed,fC)*z;
fBa = fA*x;
s = fC*x;
// Now compute the real q = s-sprime
const TVectorD q = s-sprime;
// Adjust fCloBound and fCupBound appropriately
Add(fCloBound,1.0,q);
Add(fCupBound,1.0,q);
fCloBound.SelectNonZeros(fCloIndex);
fCupBound.SelectNonZeros(fCupIndex);
}
//______________________________________________________________________________
TQpDataSparse &TQpDataSparse::operator=(const TQpDataSparse &source)
{
// Assignment operator
if (this != &source) {
TQpDataBase::operator=(source);
fQ.ResizeTo(source.fQ); fQ = source.fQ;
fA.ResizeTo(source.fA); fA = source.fA;
fC.ResizeTo(source.fC); fC = source.fC;
}
return *this;
}
<commit_msg>remove a print out<commit_after>// @(#)root/quadp:$Id$
// Author: Eddy Offermann May 2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/*************************************************************************
* Parts of this file are copied from the OOQP distribution and *
* are subject to the following license: *
* *
* COPYRIGHT 2001 UNIVERSITY OF CHICAGO *
* *
* The copyright holder hereby grants you royalty-free rights to use, *
* reproduce, prepare derivative works, and to redistribute this software*
* to others, provided that any changes are clearly documented. This *
* software was authored by: *
* *
* E. MICHAEL GERTZ gertz@mcs.anl.gov *
* Mathematics and Computer Science Division *
* Argonne National Laboratory *
* 9700 S. Cass Avenue *
* Argonne, IL 60439-4844 *
* *
* STEPHEN J. WRIGHT swright@cs.wisc.edu *
* Computer Sciences Department *
* University of Wisconsin *
* 1210 West Dayton Street *
* Madison, WI 53706 FAX: (608)262-9777 *
* *
* Any questions or comments may be directed to one of the authors. *
* *
* ARGONNE NATIONAL LABORATORY (ANL), WITH FACILITIES IN THE STATES OF *
* ILLINOIS AND IDAHO, IS OWNED BY THE UNITED STATES GOVERNMENT, AND *
* OPERATED BY THE UNIVERSITY OF CHICAGO UNDER PROVISION OF A CONTRACT *
* WITH THE DEPARTMENT OF ENERGY. *
*************************************************************************/
#include "Riostream.h"
#include "TQpDataSparse.h"
//////////////////////////////////////////////////////////////////////////
// //
// TQpDataSparse //
// //
// Data for the sparse QP formulation //
// //
//////////////////////////////////////////////////////////////////////////
ClassImp(TQpDataSparse)
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(Int_t nx,Int_t my,Int_t mz)
: TQpDataBase(nx,my,mz)
{
// Constructor
fQ.ResizeTo(fNx,fNx);
fA.ResizeTo(fMy,fNx);
fC.ResizeTo(fMz,fNx);
}
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(TVectorD &c_in, TMatrixDSparse &Q_in,
TVectorD &xlow_in,TVectorD &ixlow_in,
TVectorD &xupp_in,TVectorD &ixupp_in,
TMatrixDSparse &A_in, TVectorD &bA_in,
TMatrixDSparse &C_in,
TVectorD &clow_in,TVectorD &iclow_in,
TVectorD &cupp_in,TVectorD &icupp_in)
{
// Constructor
fG .ResizeTo(c_in) ; fG = c_in;
fBa .ResizeTo(bA_in) ; fBa = bA_in;
fXloBound.ResizeTo(xlow_in) ; fXloBound = xlow_in;
fXloIndex.ResizeTo(ixlow_in); fXloIndex = ixlow_in;
fXupBound.ResizeTo(xupp_in) ; fXupBound = xupp_in;
fXupIndex.ResizeTo(ixupp_in); fXupIndex = ixupp_in;
fCloBound.ResizeTo(clow_in) ; fCloBound = clow_in;
fCloIndex.ResizeTo(iclow_in); fCloIndex = iclow_in;
fCupBound.ResizeTo(cupp_in) ; fCupBound = cupp_in;
fCupIndex.ResizeTo(icupp_in); fCupIndex = icupp_in;
fNx = fG.GetNrows();
fQ.Use(Q_in);
if (A_in.GetNrows() > 0) {
fA.Use(A_in);
fMy = fA.GetNrows();
} else
fMy = 0;
if (C_in.GetNrows()) {
fC.Use(C_in);
fMz = fC.GetNrows();
} else
fMz = 0;
// fQ.Print();
// fA.Print();
// fC.Print();
// printf("fNx: %d\n",fNx);
// printf("fMy: %d\n",fMy);
// printf("fMz: %d\n",fMz);
}
//______________________________________________________________________________
TQpDataSparse::TQpDataSparse(const TQpDataSparse &another) : TQpDataBase(another)
{
// Copy constructor
*this = another;
}
//______________________________________________________________________________
void TQpDataSparse::SetNonZeros(Int_t nnzQ,Int_t nnzA,Int_t nnzC)
{
// Allocate space for the appropriate number of non-zeros in the matrices
fQ.SetSparseIndex(nnzQ);
fA.SetSparseIndex(nnzA);
fC.SetSparseIndex(nnzC);
}
//______________________________________________________________________________
void TQpDataSparse::Qmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x )
{
// calculate y = beta*y + alpha*(fQ*x)
y *= beta;
if (fQ.GetNoElements() > 0)
y += alpha*(fQ*x);
}
//______________________________________________________________________________
void TQpDataSparse::Amult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fA*x)
y *= beta;
if (fA.GetNoElements() > 0)
y += alpha*(fA*x);
}
//______________________________________________________________________________
void TQpDataSparse::Cmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fC*x)
y *= beta;
if (fC.GetNoElements() > 0)
y += alpha*(fC*x);
}
//______________________________________________________________________________
void TQpDataSparse::ATransmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fA^T*x)
y *= beta;
if (fA.GetNoElements() > 0)
y += alpha*(TMatrixDSparse(TMatrixDSparse::kTransposed,fA)*x);
}
//______________________________________________________________________________
void TQpDataSparse::CTransmult(Double_t beta,TVectorD &y,Double_t alpha,const TVectorD &x)
{
// calculate y = beta*y + alpha*(fC^T*x)
y *= beta;
if (fC.GetNoElements() > 0)
y += alpha*(TMatrixDSparse(TMatrixDSparse::kTransposed,fC)*x);
}
//______________________________________________________________________________
Double_t TQpDataSparse::DataNorm()
{
// Return the largest component of several vectors in the data class
Double_t norm = 0.0;
Double_t componentNorm = fG.NormInf();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fQ_abs(fQ);
componentNorm = (fQ_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
componentNorm = fBa.NormInf();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fA_abs(fQ);
componentNorm = (fA_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
TMatrixDSparse fC_abs(fQ);
componentNorm = (fC_abs.Abs()).Max();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fXloBound.MatchesNonZeroPattern(fXloIndex));
componentNorm = fXloBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fXupBound.MatchesNonZeroPattern(fXupIndex));
componentNorm = fXupBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fCloBound.MatchesNonZeroPattern(fCloIndex));
componentNorm = fCloBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
R__ASSERT(fCupBound.MatchesNonZeroPattern(fCupIndex));
componentNorm = fCupBound.NormInf();
if (componentNorm > norm) norm = componentNorm;
return norm;
}
//______________________________________________________________________________
void TQpDataSparse::Print(Option_t * /*opt*/) const
{
// Print class members
fQ.Print("Q");
fG.Print("c");
fXloBound.Print("xlow");
fXloIndex.Print("ixlow");
fXupBound.Print("xupp");
fXupIndex.Print("ixupp");
fA.Print("A");
fBa.Print("b");
fC.Print("C");
fCloBound.Print("clow");
fCloIndex.Print("iclow");
fCupBound.Print("cupp");
fCupIndex.Print("icupp");
}
//______________________________________________________________________________
void TQpDataSparse::PutQIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the Hessian Q into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fQ);
}
//______________________________________________________________________________
void TQpDataSparse::PutAIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the constraint matrix A into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fA);
}
//______________________________________________________________________________
void TQpDataSparse::PutCIntoAt(TMatrixDBase &m,Int_t row,Int_t col)
{
// Insert the constraint matrix C into the matrix M at index (row,col) for the fundamental
// linear system
m.SetSub(row,col,fC);
}
//______________________________________________________________________________
void TQpDataSparse::GetDiagonalOfQ(TVectorD &dq)
{
// Return in vector dq the diagonal of matrix fQ
const Int_t n = TMath::Min(fQ.GetNrows(),fQ.GetNcols());
dq.ResizeTo(n);
dq = TMatrixDSparseDiag(fQ);
}
//______________________________________________________________________________
Double_t TQpDataSparse::ObjectiveValue(TQpVar *vars)
{
// Return value of the objective function
TVectorD tmp(fG);
this->Qmult(1.0,tmp,0.5,vars->fX);
return tmp*vars->fX;
}
//______________________________________________________________________________
void TQpDataSparse::DataRandom(TVectorD &x,TVectorD &y,TVectorD &z,TVectorD &s)
{
// Choose randomly a QP problem
Double_t ix = 3074.20374;
TVectorD xdual(fNx);
this->RandomlyChooseBoundedVariables(x,xdual,fXloBound,fXloIndex,fXupBound,fXupIndex,ix,.25,.25,.25);
TVectorD sprime(fMz);
this->RandomlyChooseBoundedVariables(sprime,z,fCloBound,fCloIndex,fCupBound,fCupIndex,ix,.25,.25,.5);
fQ.RandomizePD(0.0,1.0,ix);
fA.Randomize(-10.0,10.0,ix);
fC.Randomize(-10.0,10.0,ix);
y .Randomize(-10.0,10.0,ix);
// fG = - fQ x + A^T y + C^T z + xdual
fG = xdual;
fG -= fQ*x;
fG += TMatrixDSparse(TMatrixDSparse::kTransposed,fA)*y;
fG += TMatrixDSparse(TMatrixDSparse::kTransposed,fC)*z;
fBa = fA*x;
s = fC*x;
// Now compute the real q = s-sprime
const TVectorD q = s-sprime;
// Adjust fCloBound and fCupBound appropriately
Add(fCloBound,1.0,q);
Add(fCupBound,1.0,q);
fCloBound.SelectNonZeros(fCloIndex);
fCupBound.SelectNonZeros(fCupIndex);
}
//______________________________________________________________________________
TQpDataSparse &TQpDataSparse::operator=(const TQpDataSparse &source)
{
// Assignment operator
if (this != &source) {
TQpDataBase::operator=(source);
fQ.ResizeTo(source.fQ); fQ = source.fQ;
fA.ResizeTo(source.fA); fA = source.fA;
fC.ResizeTo(source.fC); fC = source.fC;
}
return *this;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 10000;
// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 5000;
// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";
// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
public:
MockExtensionView(const GURL& url, Profile* profile)
: ExtensionView(url, profile), got_message_(false) {
InitHidden();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kAlertTimeoutMs);
ui_test_utils::RunMessageLoop();
}
bool got_message() { return got_message_; }
private:
virtual void RunJavaScriptMessage(
const std::wstring& message,
const std::wstring& default_prompt,
const GURL& frame_url,
const int flags,
IPC::Message* reply_msg,
bool* did_suppress_message) {
got_message_ = true;
MessageLoopForUI::current()->Quit();
// Call super, otherwise we'll leak reply_msg.
ExtensionView::RunJavaScriptMessage(
message, default_prompt, frame_url, flags,
reply_msg, did_suppress_message);
}
bool got_message_;
};
// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
public:
explicit ExtensionLoadedObserver() : extension_(NULL) {
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
}
Extension* WaitForExtension() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kLoadTimeoutMs);
ui_test_utils::RunMessageLoop();
return extension_;
}
private:
virtual void Observe(NotificationType type, const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_LOADED) {
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (size_t i = 0; i < (*extensions).size(); i++) {
if ((*extensions)[i]->id() == kExtensionId) {
extension_ = (*extensions)[i];
MessageLoopForUI::current()->Quit();
break;
}
}
} else {
NOTREACHED();
}
}
NotificationRegistrar registrar_;
Extension* extension_;
};
} // namespace
class ExtensionViewTest : public InProcessBrowserTest {
public:
virtual void SetUp() {
// Initialize the error reporter here, otherwise BrowserMain will create it
// with the wrong MessageLoop.
ExtensionErrorReporter::Init(false);
InProcessBrowserTest::SetUp();
}
};
// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, DISABLED_Index) {
// Create an observer first to be sure we have the notification registered
// before it's sent.
ExtensionLoadedObserver observer;
// Get the path to our extension.
FilePath path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
path = path.AppendASCII("extensions").
AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
ASSERT_TRUE(file_util::DirectoryExists(path)); // sanity check
// Load it.
Profile* profile = browser()->profile();
profile->GetExtensionsService()->Init();
profile->GetExtensionsService()->LoadExtension(path);
// Now wait for it to load, and grab a pointer to it.
Extension* extension = observer.WaitForExtension();
ASSERT_TRUE(extension);
GURL url = Extension::GetResourceURL(extension->url(), "toolstrip.html");
// Start the extension process and wait for it to show a javascript alert.
MockExtensionView view(url, profile);
EXPECT_TRUE(view.got_message());
}
<commit_msg>Extra disable ExtensionViewTest.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/extensions/extension_view.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// How long to wait for the extension to put up a javascript alert before giving
// up.
const int kAlertTimeoutMs = 10000;
// How long to wait for the extension to load before giving up.
const int kLoadTimeoutMs = 5000;
// The extension we're using as our test case.
const char* kExtensionId = "00123456789abcdef0123456789abcdef0123456";
// This class starts up an extension process and waits until it tries to put
// up a javascript alert.
class MockExtensionView : public ExtensionView {
public:
MockExtensionView(const GURL& url, Profile* profile)
: ExtensionView(url, profile), got_message_(false) {
InitHidden();
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kAlertTimeoutMs);
ui_test_utils::RunMessageLoop();
}
bool got_message() { return got_message_; }
private:
virtual void RunJavaScriptMessage(
const std::wstring& message,
const std::wstring& default_prompt,
const GURL& frame_url,
const int flags,
IPC::Message* reply_msg,
bool* did_suppress_message) {
got_message_ = true;
MessageLoopForUI::current()->Quit();
// Call super, otherwise we'll leak reply_msg.
ExtensionView::RunJavaScriptMessage(
message, default_prompt, frame_url, flags,
reply_msg, did_suppress_message);
}
bool got_message_;
};
// This class waits for a specific extension to be loaded.
class ExtensionLoadedObserver : public NotificationObserver {
public:
explicit ExtensionLoadedObserver() : extension_(NULL) {
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
}
Extension* WaitForExtension() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, kLoadTimeoutMs);
ui_test_utils::RunMessageLoop();
return extension_;
}
private:
virtual void Observe(NotificationType type, const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSIONS_LOADED) {
ExtensionList* extensions = Details<ExtensionList>(details).ptr();
for (size_t i = 0; i < (*extensions).size(); i++) {
if ((*extensions)[i]->id() == kExtensionId) {
extension_ = (*extensions)[i];
MessageLoopForUI::current()->Quit();
break;
}
}
} else {
NOTREACHED();
}
}
NotificationRegistrar registrar_;
Extension* extension_;
};
} // namespace
class ExtensionViewTest : public InProcessBrowserTest {
public:
virtual void SetUp() {
// Initialize the error reporter here, otherwise BrowserMain will create it
// with the wrong MessageLoop.
ExtensionErrorReporter::Init(false);
InProcessBrowserTest::SetUp();
}
};
// Tests that ExtensionView starts an extension process and runs the script
// contained in the extension's "index.html" file.
IN_PROC_BROWSER_TEST_F(ExtensionViewTest, DISABLED_Index) {
#if 0
// Create an observer first to be sure we have the notification registered
// before it's sent.
ExtensionLoadedObserver observer;
// Get the path to our extension.
FilePath path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &path));
path = path.AppendASCII("extensions").
AppendASCII("good").AppendASCII("extension1").AppendASCII("1");
ASSERT_TRUE(file_util::DirectoryExists(path)); // sanity check
// Load it.
Profile* profile = browser()->profile();
profile->GetExtensionsService()->Init();
profile->GetExtensionsService()->LoadExtension(path);
// Now wait for it to load, and grab a pointer to it.
Extension* extension = observer.WaitForExtension();
ASSERT_TRUE(extension);
GURL url = Extension::GetResourceURL(extension->url(), "toolstrip.html");
// Start the extension process and wait for it to show a javascript alert.
MockExtensionView view(url, profile);
EXPECT_TRUE(view.got_message());
#endif
}
<|endoftext|> |
<commit_before>#pragma once
//=========================================================================//
/*! @file
@brief DMAC マネージャー @n
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=========================================================================//
#include "common/renesas.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"
/// RX24T には DMAC が無い為、エラーにする。
#ifdef SIG_RX24T
# error "dmac_man.hpp not support for RX24T"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DMAC マネージャー・クラス
@param[in] DMAC DMA コントローラー
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template<class DMAC, class TASK = utils::null_task>
class dmac_man {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 転送タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class trans_type : uint8_t {
SN_DP_8, ///< ソース固定、ディストネーション+(8 bits)
SP_DN_8, ///< ソース+、ディストネーション固定(8 bits)
SN_DP_16, ///< ソース固定、ディストネーション+(16 bits)
SP_DN_16, ///< ソース+、ディストネーション固定(16 bits)
SN_DP_32, ///< ソース固定、ディストネーション+(32 bits)
SP_DN_32, ///< ソース+、ディストネーション固定(32 bits)
};
private:
static TASK task_;
uint8_t level_;
static INTERRUPT_FUNC void dmac_task_() noexcept
{
task_();
DMAC::DMSTS.DTIF = 0;
}
void set_vector_(uint32_t lvl, ICU::VECTOR vec) const noexcept
{
if(lvl) {
set_interrupt_task(dmac_task_, static_cast<uint32_t>(vec));
} else {
set_interrupt_task(nullptr, static_cast<uint32_t>(vec));
}
icu_mgr::set_level(DMAC::get_peripheral(), lvl);
}
static bool trans_inc_(uint32_t src_adr, uint32_t dst_adr, uint32_t len) noexcept
{
uint8_t sz = 0;
if(len < 4) ;
else if((src_adr & 3) == 0 && (dst_adr & 3) == 0 && (len & 3) == 0) { // 32 bits DMA
sz = 2;
len >>= 2;
} else if((src_adr & 1) == 0 && (dst_adr & 1) == 0 && (len & 1) == 0) { // 16 bits DMA
sz = 1;
len >>= 1;
}
if(len > 65535) return false;
// 転送元 (+1)、転送先 (+1)
DMAC::DMAMD = DMAC::DMAMD.DM.b(0b10) | DMAC::DMAMD.SM.b(0b10);
DMAC::DMTMD = DMAC::DMTMD.DCTG.b(0b00) | DMAC::DMTMD.SZ.b(sz) |
DMAC::DMTMD.DTS.b(0b10) | DMAC::DMTMD.MD.b(0b00);
DMAC::DMSAR = src_adr;
DMAC::DMDAR = dst_adr;
DMAC::DMCRA = len;
return true;
}
static bool trans_dec_(uint32_t src_adr, uint32_t dst_adr, uint32_t len) noexcept
{
uint8_t sz = 0;
if(len < 4) ;
else if((src_adr & 3) == 0 && (dst_adr & 3) == 0 && (len & 3) == 0) { // 32 bits DMA
sz = 2;
len >>= 2;
} else if((src_adr & 1) == 0 && (dst_adr & 1) == 0 && (len & 1) == 0) { // 16 bits DMA
sz = 1;
len >>= 1;
}
if(len > 65535) return false;
// 転送元 (-1)、転送先 (-1)
DMAC::DMAMD = DMAC::DMAMD.DM.b(0b11) | DMAC::DMAMD.SM.b(0b11);
DMAC::DMTMD = DMAC::DMTMD.DCTG.b(0b00) | DMAC::DMTMD.SZ.b(sz) |
DMAC::DMTMD.DTS.b(0b10) | DMAC::DMTMD.MD.b(0b00);
DMAC::DMSAR = src_adr + len - sz;
DMAC::DMDAR = dst_adr + len - sz;
DMAC::DMCRA = len;
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
dmac_man() noexcept : level_(0) { }
//-----------------------------------------------------------------//
/*!
@brief 開始(メモリー操作関係)
@param[in] lvl 割り込みレベル(0以上)@n
※無指定(0)なら割り込みを起動しない。
*/
//-----------------------------------------------------------------//
void start(uint32_t lvl = 0) noexcept
{
power_cfg::turn(DMAC::get_peripheral());
set_vector_(lvl, DMAC::get_vec());
level_ = lvl;
DMAST.DMST = 1;
}
//-----------------------------------------------------------------//
/*!
@brief 割り込み要因による開始
@param[in] tft 転送タイプ
@param[in] src 元アドレス
@param[in] dst 先アドレス
@param[in] lim 転送リミット
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start(trans_type tft, uint32_t src, uint32_t dst, uint32_t lim) noexcept
{
power_cfg::turn(DMAC::get_peripheral());
#if 0
// 転送元 (+1)、転送先 (+1)
DMAC::DMAMD = DMAC::DMAMD.DM.b(0b10) | DMAC::DMAMD.SM.b(0b10);
DMAC::DMTMD = DMAC::DMTMD.DCTG.b(0b00) | DMAC::DMTMD.SZ.b(sz) |
DMAC::DMTMD.DTS.b(0b10) | DMAC::DMTMD.MD.b(0b00);
#endif
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 動作中か検査
@return 動作中なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const noexcept {
return DMAC::DMSTS.ACT();
}
//-----------------------------------------------------------------//
/*!
@brief 定数で埋める
@param[out] org 定数先頭 @n
定数をあらかじめ先頭に書き込んでおく
@param[in] frz 定数サイズ(バイト)
@param[in] len 埋める数(バイト)
@param[in] tae 終了時タスクを起動する場合「true」
@return 出来ない場合「false」
*/
//-----------------------------------------------------------------//
bool fill(void* org, uint32_t frz, uint32_t len, bool tae = false) noexcept
{
if(org == nullptr || frz == 0 || len == 0 || frz > len) return false;
DMAC::DMCNT.DTE = 0; // 念のため停止させる。
uint32_t src_adr = reinterpret_cast<uint32_t>(org);
uint32_t dst_adr = src_adr + frz;
len -= frz;
if(!trans_inc_(src_adr, dst_adr, len)) {
return false;
}
if(tae && level_ > 0) {
DMAC::DMINT.DTIE = 1;
} else {
DMAC::DMINT.DTIE = 0;
}
DMAC::DMCNT.DTE = 1;
// CLRS=0 の場合、1回の転送で終了
DMAC::DMREQ = DMAC::DMREQ.SWREQ.b() | DMAC::DMREQ.CLRS.b();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 定数で埋める
@param[out] org 定数先頭 @n
@param[in] val 定数
@param[in] len 埋める数(バイト)
@param[in] tae 終了時タスクを起動する場合「true」
@return 出来ない場合「false」
*/
//-----------------------------------------------------------------//
bool memset(void* org, uint8_t val, uint32_t len, bool tae = false) noexcept
{
if(org == nullptr || len == 0) return false;
uint8_t* dst = static_cast<uint8_t*>(org);
*dst++ = val;
uint32_t frz = 1;
uint32_t adr = reinterpret_cast<uint32_t>(org);
if((adr & 1) == 0 && (len & 1) == 0 && len > 2) {
++frz;
*dst++ = val;
}
if((adr & 3) == 0 && (len & 3) == 0 && len > 4) {
frz += 2;
*dst++ = val;
*dst++ = val;
}
return fill(org, frz, len, tae);
}
//-----------------------------------------------------------------//
/*!
@brief コピー・メモリー @n
オーバーラップする場合は、コピーする順番を自動で変更 @n
※特定の値で埋める場合は「fill」を使う。
@param[in] src コピー元
@param[in] dst コピー先
@param[in] len コピー数(バイト単位)@n
※アドレスが 32 ビット単位の場合、最大 65535 x4 バイト
※アドレスが 16 ビット単位の場合、最大 65535 x2 バイト
※アドレスが 8 ビット単位の場合、最大 65535 x1 バイト
@param[in] tae 終了時タスクを起動する場合「true」
@return コピーが出来ない場合「false」(パラメーターが異常)
*/
//-----------------------------------------------------------------//
bool copy(const void* src, void* dst, uint32_t len, bool tae = false) const noexcept
{
if(len == 0 || src == nullptr || dst == nullptr) return false;
DMAC::DMCNT.DTE = 0; // 念のため停止させる。
uint32_t src_adr = reinterpret_cast<uint32_t>(src);
uint32_t dst_adr = reinterpret_cast<uint32_t>(dst);
bool ret = false;
if(dst_adr < (src_adr + len)) {
ret = trans_dec_(src_adr, dst_adr, len);
} else {
ret = trans_inc_(src_adr, dst_adr, len);
}
if(!ret) {
return false;
}
if(tae && level_ > 0) {
DMAC::DMINT.DTIE = 1;
} else {
DMAC::DMINT.DTIE = 0;
}
DMAC::DMCNT.DTE = 1;
// CLRS=0 の場合、1回の転送で終了
DMAC::DMREQ = DMAC::DMREQ.SWREQ.b() | DMAC::DMREQ.CLRS.b();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief TASK クラスの参照
@return TASK クラス
*/
//-----------------------------------------------------------------//
static TASK& at_task() noexcept { return task_; }
};
template <class DMAC, class TASK> TASK dmac_man<DMAC, TASK>::task_;
}
<commit_msg>remove: remove/move<commit_after><|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <GL/gl.h>
#include <string>
#include "guichan/opengl/openglgraphics.hpp"
#include "guichan/exception.hpp"
namespace gcn
{
OpenGLGraphics::OpenGLGraphics()
{
setTargetPlane(640, 480);
mAlpha = false;
} // end OpenGLGraphics
OpenGLGraphics::OpenGLGraphics(int width, int height)
{
setTargetPlane(width, height);
} // end OpenGLGrapics
OpenGLGraphics::~OpenGLGraphics()
{
} // end ~OpenGLGraphics
void OpenGLGraphics::_beginDraw()
{
glPushAttrib(
GL_COLOR_BUFFER_BIT |
GL_CURRENT_BIT |
GL_DEPTH_BUFFER_BIT |
GL_ENABLE_BIT |
GL_FOG_BIT |
GL_LIGHTING_BIT |
GL_LINE_BIT |
GL_POINT_BIT |
GL_POLYGON_BIT |
GL_SCISSOR_BIT |
GL_STENCIL_BUFFER_BIT |
GL_TEXTURE_BIT |
GL_TRANSFORM_BIT
);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, (double)mWidth, (double)mHeight, 0.0, -1.0, 1.0);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
pushClipArea(Rectangle(0, 0, mWidth, mHeight));
} // end _beginDraw
void OpenGLGraphics::_endDraw()
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
popClipArea();
} // _endDraw
bool OpenGLGraphics::pushClipArea(Rectangle area)
{
bool result = Graphics::pushClipArea(area);
glScissor(mClipStack.top().x,
mHeight - mClipStack.top().y - mClipStack.top().height,
mClipStack.top().width,
mClipStack.top().height);
return result;
} // end pushClipArea
void OpenGLGraphics::popClipArea()
{
Graphics::popClipArea();
if (mClipStack.empty())
{
return;
}
glScissor(mClipStack.top().x,
mHeight - mClipStack.top().y - mClipStack.top().height,
mClipStack.top().width,
mClipStack.top().height);
} // end popClipArea
void OpenGLGraphics::setTargetPlane(int width, int height)
{
mWidth = width;
mHeight = height;
} // end setTargetPlane
void OpenGLGraphics::drawImage(const Image* image, int srcX, int srcY,
int dstX, int dstY, int width,
int height)
{
dstX += mClipStack.top().xOffset;
dstY += mClipStack.top().yOffset;
// The following code finds the real width and height of the texture.
// OpenGL only supports texture sizes that are powers of two
int realImageWidth = 1;
int realImageHeight = 1;
while (realImageWidth < image->getWidth())
{
realImageWidth *= 2;
}
while (realImageHeight < image->getHeight())
{
realImageHeight *= 2;
}
// Find OpenGL texture coordinates
float texX1 = srcX / (float)realImageWidth;
float texY1 = srcY / (float)realImageHeight;
float texX2 = (srcX+width) / (float)realImageWidth;
float texY2 = (srcY+height) / (float)realImageHeight;
// Please dont look too closely at the next line, it is not pretty.
// It uses the image data as a pointer to a GLuint
glBindTexture(GL_TEXTURE_2D, *((GLuint *)(image->_getData())));
glEnable(GL_TEXTURE_2D);
// Check if blending already is enabled
if (!mAlpha)
{
glEnable(GL_BLEND);
}
// Draw a textured quad -- the image
glBegin(GL_QUADS);
glTexCoord2f(texX1, texY1);
glVertex3i(dstX, dstY, 0);
glTexCoord2f(texX1, texY2);
glVertex3i(dstX, dstY + height, 0);
glTexCoord2f(texX2, texY2);
glVertex3i(dstX + width, dstY + height, 0);
glTexCoord2f(texX2, texY1);
glVertex3i(dstX + width, dstY, 0);
glEnd();
glDisable(GL_TEXTURE_2D);
// Don't disable blending if the color has alpha
if (!mAlpha)
{
glDisable(GL_BLEND);
}
} // drawImage
void OpenGLGraphics::drawPoint(int x, int y)
{
x += mClipStack.top().xOffset;
y += mClipStack.top().yOffset;
glBegin(GL_POINTS);
glVertex3i(x, y, 0);
glEnd();
} // end drawPoint
void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)
{
x1 += mClipStack.top().xOffset;
y1 += mClipStack.top().yOffset;
x2 += mClipStack.top().xOffset;
y2 += mClipStack.top().yOffset;
glBegin(GL_LINES);
glVertex3f(x1+0.5f, y1+0.5f, 0);
glVertex3f(x2+0.5f, y2+0.5f, 0);
glEnd();
glBegin(GL_POINTS);
glVertex3f(x2+0.5f, y2+0.5f, 0);
glEnd();
} // end drawLine
void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)
{
glBegin(GL_LINE_LOOP);
glVertex3f(rectangle.x + mClipStack.top().xOffset + 0.5f,
rectangle.y + mClipStack.top().yOffset + 0.5f, 0);
glVertex3f(rectangle.x + rectangle.width - 0.5f + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset + 0.5f, 0);
glVertex3f(rectangle.x + rectangle.width - 0.5f + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset - 0.5f, 0);
glVertex3f(rectangle.x + mClipStack.top().xOffset + 0.5f,
rectangle.y + rectangle.height + mClipStack.top().yOffset - 0.5f, 0);
glEnd();
} // end drawRectangle
void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)
{
glBegin(GL_QUADS);
glVertex3i(rectangle.x + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + rectangle.width + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + rectangle.width + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset, 0);
glEnd();
} // end fillRectangle
void OpenGLGraphics::setColor(const Color& color)
{
mColor = color;
glColor4f(color.r/255.0,
color.g/255.0,
color.b/255.0,
color.a/255.0);
mAlpha = color.a != 255;
if (mAlpha)
{
glEnable(GL_BLEND);
}
}
const Color& OpenGLGraphics::getColor()
{
return mColor;
}
} // end gcn
<commit_msg>Added checks and OpenGL fixes for the AmigaOS 4 platform thanks to Steffen Haeuser.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifdef __amigaos4__
#include <mgl/gl.h>
#define glVertex3i glVertex3f
#else
#include <GL/gl.h>
#endif
#include <string>
#include "guichan/opengl/openglgraphics.hpp"
#include "guichan/exception.hpp"
namespace gcn
{
OpenGLGraphics::OpenGLGraphics()
{
setTargetPlane(640, 480);
mAlpha = false;
}
OpenGLGraphics::OpenGLGraphics(int width, int height)
{
setTargetPlane(width, height);
}
OpenGLGraphics::~OpenGLGraphics()
{
}
void OpenGLGraphics::_beginDraw()
{
glPushAttrib(
GL_COLOR_BUFFER_BIT |
GL_CURRENT_BIT |
GL_DEPTH_BUFFER_BIT |
GL_ENABLE_BIT |
GL_FOG_BIT |
GL_LIGHTING_BIT |
GL_LINE_BIT |
GL_POINT_BIT |
GL_POLYGON_BIT |
GL_SCISSOR_BIT |
GL_STENCIL_BUFFER_BIT |
GL_TEXTURE_BIT |
GL_TRANSFORM_BIT
);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, (double)mWidth, (double)mHeight, 0.0, -1.0, 1.0);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
pushClipArea(Rectangle(0, 0, mWidth, mHeight));
}
void OpenGLGraphics::_endDraw()
{
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
popClipArea();
}
bool OpenGLGraphics::pushClipArea(Rectangle area)
{
bool result = Graphics::pushClipArea(area);
glScissor(mClipStack.top().x,
mHeight - mClipStack.top().y - mClipStack.top().height,
mClipStack.top().width,
mClipStack.top().height);
return result;
}
void OpenGLGraphics::popClipArea()
{
Graphics::popClipArea();
if (mClipStack.empty())
{
return;
}
glScissor(mClipStack.top().x,
mHeight - mClipStack.top().y - mClipStack.top().height,
mClipStack.top().width,
mClipStack.top().height);
}
void OpenGLGraphics::setTargetPlane(int width, int height)
{
mWidth = width;
mHeight = height;
}
void OpenGLGraphics::drawImage(const Image* image, int srcX, int srcY,
int dstX, int dstY, int width,
int height)
{
dstX += mClipStack.top().xOffset;
dstY += mClipStack.top().yOffset;
// The following code finds the real width and height of the texture.
// OpenGL only supports texture sizes that are powers of two
int realImageWidth = 1;
int realImageHeight = 1;
while (realImageWidth < image->getWidth())
{
realImageWidth *= 2;
}
while (realImageHeight < image->getHeight())
{
realImageHeight *= 2;
}
// Find OpenGL texture coordinates
float texX1 = srcX / (float)realImageWidth;
float texY1 = srcY / (float)realImageHeight;
float texX2 = (srcX+width) / (float)realImageWidth;
float texY2 = (srcY+height) / (float)realImageHeight;
// Please dont look too closely at the next line, it is not pretty.
// It uses the image data as a pointer to a GLuint
glBindTexture(GL_TEXTURE_2D, *((GLuint *)(image->_getData())));
glEnable(GL_TEXTURE_2D);
// Check if blending already is enabled
if (!mAlpha)
{
glEnable(GL_BLEND);
}
// Draw a textured quad -- the image
glBegin(GL_QUADS);
glTexCoord2f(texX1, texY1);
glVertex3i(dstX, dstY, 0);
glTexCoord2f(texX1, texY2);
glVertex3i(dstX, dstY + height, 0);
glTexCoord2f(texX2, texY2);
glVertex3i(dstX + width, dstY + height, 0);
glTexCoord2f(texX2, texY1);
glVertex3i(dstX + width, dstY, 0);
glEnd();
glDisable(GL_TEXTURE_2D);
// Don't disable blending if the color has alpha
if (!mAlpha)
{
glDisable(GL_BLEND);
}
}
void OpenGLGraphics::drawPoint(int x, int y)
{
x += mClipStack.top().xOffset;
y += mClipStack.top().yOffset;
glBegin(GL_POINTS);
glVertex3i(x, y, 0);
glEnd();
}
void OpenGLGraphics::drawLine(int x1, int y1, int x2, int y2)
{
x1 += mClipStack.top().xOffset;
y1 += mClipStack.top().yOffset;
x2 += mClipStack.top().xOffset;
y2 += mClipStack.top().yOffset;
glBegin(GL_LINES);
glVertex3f(x1+0.5f, y1+0.5f, 0);
glVertex3f(x2+0.5f, y2+0.5f, 0);
glEnd();
glBegin(GL_POINTS);
glVertex3f(x2+0.5f, y2+0.5f, 0);
glEnd();
}
void OpenGLGraphics::drawRectangle(const Rectangle& rectangle)
{
glBegin(GL_LINE_LOOP);
glVertex3f(rectangle.x + mClipStack.top().xOffset + 0.5f,
rectangle.y + mClipStack.top().yOffset + 0.5f, 0);
glVertex3f(rectangle.x + rectangle.width - 0.5f + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset + 0.5f, 0);
glVertex3f(rectangle.x + rectangle.width - 0.5f + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset - 0.5f, 0);
glVertex3f(rectangle.x + mClipStack.top().xOffset + 0.5f,
rectangle.y + rectangle.height + mClipStack.top().yOffset - 0.5f, 0);
glEnd();
}
void OpenGLGraphics::fillRectangle(const Rectangle& rectangle)
{
glBegin(GL_QUADS);
glVertex3i(rectangle.x + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + rectangle.width + mClipStack.top().xOffset,
rectangle.y + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + rectangle.width + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset, 0);
glVertex3i(rectangle.x + mClipStack.top().xOffset,
rectangle.y + rectangle.height + mClipStack.top().yOffset, 0);
glEnd();
}
void OpenGLGraphics::setColor(const Color& color)
{
mColor = color;
glColor4f(color.r/255.0,
color.g/255.0,
color.b/255.0,
color.a/255.0);
mAlpha = color.a != 255;
if (mAlpha)
{
glEnable(GL_BLEND);
}
}
const Color& OpenGLGraphics::getColor()
{
return mColor;
}
}
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2015 by Contributors
* \file slice_channel.cc
* \brief
* \author Bing Xu
*/
#include "./slice_channel-inl.h"
namespace mxnet {
namespace op {
template<>
Operator* CreateOp<cpu>(SliceChannelParam param, int dtype) {
Operator* op = nullptr;
MSHADOW_TYPE_SWITCH(dtype, DType, {
op = new SliceChannelOp<cpu, DType>(param);
})
return op;
}
Operator* SliceChannelProp::CreateOperatorEx(Context ctx,
std::vector<TShape>* in_shape,
std::vector<int>* in_type) const {
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(SliceChannelParam);
MXNET_REGISTER_OP_PROPERTY(SliceChannel, SliceChannelProp)
.describe(R"code(Split an array along a particular axis into multiple sub-arrays.
Assume the input array has shape ``(d_0, ..., d_n)`` and we slice it into *m*
(``num_outputs=m``) subarrays along axis *k*, then we will obtain a list of *m*
arrays with each of which has shape ``(d_0, ..., d_k/m, ..., d_n)``.
For example::
x = [[1, 2],
[3, 4],
[5, 6],
[7, 8]] // 4x2 array
y = split(x, axis=0, num_outputs=4) // a list of 4 arrays
y[0] = [[ 1., 2.]] // 1x2 array
z = split(x, axis=0, num_outputs=2) // a list of 2 arrays
z[0] = [[ 1., 2.],
[ 3., 4.]]
When setting optional argument ``squeeze_axis=1``, then the *k*-dimension will
be removed from the shape if it becomes 1::
y = split(x, axis=0, num_outputs=4, squeeze_axis=1)
y[0] = [ 1., 2.] // (2,) vector
)code" ADD_FILELINE)
.set_return_type("NDArray-or-Symbol[]")
.add_arguments(SliceChannelParam::__FIELDS__());
NNVM_REGISTER_OP(SliceChannel).add_alias("split");
} // namespace op
} // namespace mxnet
<commit_msg>fix ndarray split (#5791)<commit_after>/*!
* Copyright (c) 2015 by Contributors
* \file slice_channel.cc
* \brief
* \author Bing Xu
*/
#include "./slice_channel-inl.h"
namespace mxnet {
namespace op {
template<>
Operator* CreateOp<cpu>(SliceChannelParam param, int dtype) {
Operator* op = nullptr;
MSHADOW_TYPE_SWITCH(dtype, DType, {
op = new SliceChannelOp<cpu, DType>(param);
})
return op;
}
Operator* SliceChannelProp::CreateOperatorEx(Context ctx,
std::vector<TShape>* in_shape,
std::vector<int>* in_type) const {
DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}
DMLC_REGISTER_PARAMETER(SliceChannelParam);
MXNET_REGISTER_OP_PROPERTY(SliceChannel, SliceChannelProp)
.describe(R"code(Split an array along a particular axis into multiple sub-arrays.
Assume the input array has shape ``(d_0, ..., d_n)`` and we slice it into *m*
(``num_outputs=m``) subarrays along axis *k*, then we will obtain a list of *m*
arrays with each of which has shape ``(d_0, ..., d_k/m, ..., d_n)``.
For example::
x = [[1, 2],
[3, 4],
[5, 6],
[7, 8]] // 4x2 array
y = split(x, axis=0, num_outputs=4) // a list of 4 arrays
y[0] = [[ 1., 2.]] // 1x2 array
z = split(x, axis=0, num_outputs=2) // a list of 2 arrays
z[0] = [[ 1., 2.],
[ 3., 4.]]
When setting optional argument ``squeeze_axis=1``, then the *k*-dimension will
be removed from the shape if it becomes 1::
y = split(x, axis=0, num_outputs=4, squeeze_axis=1)
y[0] = [ 1., 2.] // (2,) vector
)code" ADD_FILELINE)
.set_return_type("NDArray-or-Symbol[]")
.add_argument("data", "NDArray-or-Symbol", "Source input")
.add_arguments(SliceChannelParam::__FIELDS__());
NNVM_REGISTER_OP(SliceChannel).add_alias("split");
} // namespace op
} // namespace mxnet
<|endoftext|> |
<commit_before>/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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 including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*/
#include <osg/GLU>
#include <osg/FrameBufferObject>
// define GL values not provided by some GL headers.
#ifndef GL_TABLE_TOO_LARGE
#define GL_TABLE_TOO_LARGE 0x8031
#endif
#ifndef GL_STACK_OVERFLOW
#define GL_STACK_OVERFLOW 0x0503
#endif
#ifndef GL_STACK_UNDERFLOW
#define GL_STACK_UNDERFLOW 0x0504
#endif
namespace osg
{
static unsigned char *__gluNurbsErrors[] = {
(unsigned char*) " ",
(unsigned char*) "spline order un-supported",
(unsigned char*) "too few knots",
(unsigned char*) "valid knot range is empty",
(unsigned char*) "decreasing knot sequence knot",
(unsigned char*) "knot multiplicity greater than order of spline",
(unsigned char*) "gluEndCurve() must follow gluBeginCurve()",
(unsigned char*) "gluBeginCurve() must precede gluEndCurve()",
(unsigned char*) "missing or extra geometric data",
(unsigned char*) "can't draw piecewise linear trimming curves",
(unsigned char*) "missing or extra domain data",
(unsigned char*) "missing or extra domain data",
(unsigned char*) "gluEndTrim() must precede gluEndSurface()",
(unsigned char*) "gluBeginSurface() must precede gluEndSurface()",
(unsigned char*) "curve of improper type passed as trim curve",
(unsigned char*) "gluBeginSurface() must precede gluBeginTrim()",
(unsigned char*) "gluEndTrim() must follow gluBeginTrim()",
(unsigned char*) "gluBeginTrim() must precede gluEndTrim()",
(unsigned char*) "invalid or missing trim curve",
(unsigned char*) "gluBeginTrim() must precede gluPwlCurve()",
(unsigned char*) "piecewise linear trimming curve referenced twice",
(unsigned char*) "piecewise linear trimming curve and nurbs curve mixed",
(unsigned char*) "improper usage of trim data type",
(unsigned char*) "nurbs curve referenced twice",
(unsigned char*) "nurbs curve and piecewise linear trimming curve mixed",
(unsigned char*) "nurbs surface referenced twice",
(unsigned char*) "invalid property",
(unsigned char*) "gluEndSurface() must follow gluBeginSurface()",
(unsigned char*) "intersecting or misoriented trim curves",
(unsigned char*) "intersecting trim curves",
(unsigned char*) "UNUSED",
(unsigned char*) "unconnected trim curves",
(unsigned char*) "unknown knot error",
(unsigned char*) "negative vertex count encountered",
(unsigned char*) "negative byte-stride encounteed",
(unsigned char*) "unknown type descriptor",
(unsigned char*) "null control point reference",
(unsigned char*) "duplicate point on piecewise linear trimming curve",
};
const unsigned char *__gluNURBSErrorString( int errnum )
{
return __gluNurbsErrors[errnum];
}
static unsigned char *__gluTessErrors[] = {
(unsigned char*) " ",
(unsigned char*) "gluTessBeginPolygon() must precede a gluTessEndPolygon()",
(unsigned char*) "gluTessBeginContour() must precede a gluTessEndContour()",
(unsigned char*) "gluTessEndPolygon() must follow a gluTessBeginPolygon()",
(unsigned char*) "gluTessEndContour() must follow a gluTessBeginContour()",
(unsigned char*) "a coordinate is too large",
(unsigned char*) "need combine callback",
};
const unsigned char *__gluTessErrorString( int errnum )
{
return __gluTessErrors[errnum];
} /* __glTessErrorString() */
struct token_string
{
GLuint Token;
const char *String;
};
static const struct token_string Errors[] = {
{ GL_NO_ERROR, "no error" },
{ GL_INVALID_ENUM, "invalid enumerant" },
{ GL_INVALID_VALUE, "invalid value" },
{ GL_INVALID_OPERATION, "invalid operation" },
{ GL_STACK_OVERFLOW, "stack overflow" },
{ GL_STACK_UNDERFLOW, "stack underflow" },
{ GL_OUT_OF_MEMORY, "out of memory" },
{ GL_TABLE_TOO_LARGE, "table too large" },
{ GL_INVALID_FRAMEBUFFER_OPERATION_EXT, "invalid framebuffer operation" },
/* GLU */
{ GLU_INVALID_ENUM, "invalid enumerant" },
{ GLU_INVALID_VALUE, "invalid value" },
{ GLU_OUT_OF_MEMORY, "out of memory" },
{ GLU_INCOMPATIBLE_GL_VERSION, "incompatible gl version" },
{ GLU_INVALID_OPERATION, "invalid operation" },
{ ~0, NULL } /* end of list indicator */
};
const GLubyte* gluErrorString(GLenum errorCode)
{
int i;
for (i = 0; Errors[i].String; i++) {
if (Errors[i].Token == errorCode)
return (const GLubyte *) Errors[i].String;
}
if ((errorCode >= GLU_TESS_ERROR1) && (errorCode <= GLU_TESS_ERROR6)) {
return (const GLubyte *) __gluTessErrorString(errorCode - (GLU_TESS_ERROR1 - 1));
}
return (const GLubyte *) 0;
}
} // end of namespace osg<commit_msg>Fixed warning<commit_after>/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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 including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*/
#include <osg/GLU>
#include <osg/FrameBufferObject>
// define GL values not provided by some GL headers.
#ifndef GL_TABLE_TOO_LARGE
#define GL_TABLE_TOO_LARGE 0x8031
#endif
#ifndef GL_STACK_OVERFLOW
#define GL_STACK_OVERFLOW 0x0503
#endif
#ifndef GL_STACK_UNDERFLOW
#define GL_STACK_UNDERFLOW 0x0504
#endif
namespace osg
{
static unsigned char *__gluNurbsErrors[] = {
(unsigned char*) " ",
(unsigned char*) "spline order un-supported",
(unsigned char*) "too few knots",
(unsigned char*) "valid knot range is empty",
(unsigned char*) "decreasing knot sequence knot",
(unsigned char*) "knot multiplicity greater than order of spline",
(unsigned char*) "gluEndCurve() must follow gluBeginCurve()",
(unsigned char*) "gluBeginCurve() must precede gluEndCurve()",
(unsigned char*) "missing or extra geometric data",
(unsigned char*) "can't draw piecewise linear trimming curves",
(unsigned char*) "missing or extra domain data",
(unsigned char*) "missing or extra domain data",
(unsigned char*) "gluEndTrim() must precede gluEndSurface()",
(unsigned char*) "gluBeginSurface() must precede gluEndSurface()",
(unsigned char*) "curve of improper type passed as trim curve",
(unsigned char*) "gluBeginSurface() must precede gluBeginTrim()",
(unsigned char*) "gluEndTrim() must follow gluBeginTrim()",
(unsigned char*) "gluBeginTrim() must precede gluEndTrim()",
(unsigned char*) "invalid or missing trim curve",
(unsigned char*) "gluBeginTrim() must precede gluPwlCurve()",
(unsigned char*) "piecewise linear trimming curve referenced twice",
(unsigned char*) "piecewise linear trimming curve and nurbs curve mixed",
(unsigned char*) "improper usage of trim data type",
(unsigned char*) "nurbs curve referenced twice",
(unsigned char*) "nurbs curve and piecewise linear trimming curve mixed",
(unsigned char*) "nurbs surface referenced twice",
(unsigned char*) "invalid property",
(unsigned char*) "gluEndSurface() must follow gluBeginSurface()",
(unsigned char*) "intersecting or misoriented trim curves",
(unsigned char*) "intersecting trim curves",
(unsigned char*) "UNUSED",
(unsigned char*) "unconnected trim curves",
(unsigned char*) "unknown knot error",
(unsigned char*) "negative vertex count encountered",
(unsigned char*) "negative byte-stride encounteed",
(unsigned char*) "unknown type descriptor",
(unsigned char*) "null control point reference",
(unsigned char*) "duplicate point on piecewise linear trimming curve",
};
const unsigned char *__gluNURBSErrorString( int errnum )
{
return __gluNurbsErrors[errnum];
}
static unsigned char *__gluTessErrors[] = {
(unsigned char*) " ",
(unsigned char*) "gluTessBeginPolygon() must precede a gluTessEndPolygon()",
(unsigned char*) "gluTessBeginContour() must precede a gluTessEndContour()",
(unsigned char*) "gluTessEndPolygon() must follow a gluTessBeginPolygon()",
(unsigned char*) "gluTessEndContour() must follow a gluTessBeginContour()",
(unsigned char*) "a coordinate is too large",
(unsigned char*) "need combine callback",
};
const unsigned char *__gluTessErrorString( int errnum )
{
return __gluTessErrors[errnum];
} /* __glTessErrorString() */
struct token_string
{
GLuint Token;
const char *String;
};
static const struct token_string Errors[] = {
{ GL_NO_ERROR, "no error" },
{ GL_INVALID_ENUM, "invalid enumerant" },
{ GL_INVALID_VALUE, "invalid value" },
{ GL_INVALID_OPERATION, "invalid operation" },
{ GL_STACK_OVERFLOW, "stack overflow" },
{ GL_STACK_UNDERFLOW, "stack underflow" },
{ GL_OUT_OF_MEMORY, "out of memory" },
{ GL_TABLE_TOO_LARGE, "table too large" },
{ GL_INVALID_FRAMEBUFFER_OPERATION_EXT, "invalid framebuffer operation" },
/* GLU */
{ GLU_INVALID_ENUM, "invalid enumerant" },
{ GLU_INVALID_VALUE, "invalid value" },
{ GLU_OUT_OF_MEMORY, "out of memory" },
{ GLU_INCOMPATIBLE_GL_VERSION, "incompatible gl version" },
{ GLU_INVALID_OPERATION, "invalid operation" },
{ ~0u, NULL } /* end of list indicator */
};
const GLubyte* gluErrorString(GLenum errorCode)
{
int i;
for (i = 0; Errors[i].String; i++) {
if (Errors[i].Token == errorCode)
return (const GLubyte *) Errors[i].String;
}
if ((errorCode >= GLU_TESS_ERROR1) && (errorCode <= GLU_TESS_ERROR6)) {
return (const GLubyte *) __gluTessErrorString(errorCode - (GLU_TESS_ERROR1 - 1));
}
return (const GLubyte *) 0;
}
} // end of namespace osg<|endoftext|> |
<commit_before>// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/BoundingSphere>
#include <osg/CopyOp>
#include <osg/Group>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Object>
#include <osg/State>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_OBJECT_REFLECTOR(osg::Group)
I_BaseType(osg::Node);
I_Constructor0();
I_ConstructorWithDefaults2(IN, const osg::Group &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY);
I_Method0(osg::Object *, cloneType);
I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop);
I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj);
I_Method0(const char *, className);
I_Method0(const char *, libraryName);
I_Method1(void, accept, IN, osg::NodeVisitor &, nv);
I_Method0(osg::Group *, asGroup);
I_Method0(const osg::Group *, asGroup);
I_Method1(void, traverse, IN, osg::NodeVisitor &, nv);
I_Method1(bool, addChild, IN, osg::Node *, child);
I_Method2(bool, insertChild, IN, unsigned int, index, IN, osg::Node *, child);
I_Method1(bool, removeChild, IN, osg::Node *, child);
I_Method1(bool, removeChild, IN, unsigned int, pos);
I_Method2(bool, removeChildren, IN, unsigned int, pos, IN, unsigned int, numChildrenToRemove);
I_Method2(bool, replaceChild, IN, osg::Node *, origChild, IN, osg::Node *, newChild);
I_Method0(unsigned int, getNumChildren);
I_Method2(bool, setChild, IN, unsigned int, i, IN, osg::Node *, node);
I_Method1(osg::Node *, getChild, IN, unsigned int, i);
I_Method1(const osg::Node *, getChild, IN, unsigned int, i);
I_Method1(bool, containsNode, IN, const osg::Node *, node);
I_Method1(unsigned int, getChildIndex, IN, const osg::Node *, node);
I_MethodWithDefaults1(void, releaseGLObjects, IN, osg::State *, x, 0);
I_Method0(osg::BoundingSphere, computeBound);
I_ArrayProperty_GSA(osg::Node *, Child, Children, unsigned int, bool);
END_REFLECTOR
TYPE_NAME_ALIAS(std::vector< osg::ref_ptr< osg::Node > >, osg::NodeList);
BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osg::Node >)
I_Constructor0();
I_Constructor1(IN, osg::Node *, t);
I_Constructor1(IN, const osg::ref_ptr< osg::Node > &, rp);
I_Method0(bool, valid);
I_Method0(osg::Node *, get);
I_Method0(const osg::Node *, get);
I_Method0(osg::Node *, take);
I_Method0(osg::Node *, release);
I_ReadOnlyProperty(osg::Node *, );
END_REFLECTOR
STD_VECTOR_REFLECTOR(std::vector< osg::ref_ptr< osg::Node > >);
<commit_msg>Updated wrappers<commit_after>// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/BoundingSphere>
#include <osg/CopyOp>
#include <osg/Group>
#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Object>
#include <osg/State>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_OBJECT_REFLECTOR(osg::Group)
I_BaseType(osg::Node);
I_Constructor0();
I_ConstructorWithDefaults2(IN, const osg::Group &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY);
I_Method0(osg::Object *, cloneType);
I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop);
I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj);
I_Method0(const char *, className);
I_Method0(const char *, libraryName);
I_Method1(void, accept, IN, osg::NodeVisitor &, nv);
I_Method0(osg::Group *, asGroup);
I_Method0(const osg::Group *, asGroup);
I_Method1(void, traverse, IN, osg::NodeVisitor &, nv);
I_Method1(bool, addChild, IN, osg::Node *, child);
I_Method2(bool, insertChild, IN, unsigned int, index, IN, osg::Node *, child);
I_Method1(bool, removeChild, IN, osg::Node *, child);
I_MethodWithDefaults2(bool, removeChild, IN, unsigned int, pos, , IN, unsigned int, numChildrenToRemove, 1);
I_Method2(bool, removeChildren, IN, unsigned int, pos, IN, unsigned int, numChildrenToRemove);
I_Method2(bool, replaceChild, IN, osg::Node *, origChild, IN, osg::Node *, newChild);
I_Method0(unsigned int, getNumChildren);
I_Method2(bool, setChild, IN, unsigned int, i, IN, osg::Node *, node);
I_Method1(osg::Node *, getChild, IN, unsigned int, i);
I_Method1(const osg::Node *, getChild, IN, unsigned int, i);
I_Method1(bool, containsNode, IN, const osg::Node *, node);
I_Method1(unsigned int, getChildIndex, IN, const osg::Node *, node);
I_MethodWithDefaults1(void, releaseGLObjects, IN, osg::State *, x, 0);
I_Method0(osg::BoundingSphere, computeBound);
I_ArrayProperty_GSA(osg::Node *, Child, Children, unsigned int, bool);
END_REFLECTOR
TYPE_NAME_ALIAS(std::vector< osg::ref_ptr< osg::Node > >, osg::NodeList);
BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osg::Node >)
I_Constructor0();
I_Constructor1(IN, osg::Node *, t);
I_Constructor1(IN, const osg::ref_ptr< osg::Node > &, rp);
I_Method0(bool, valid);
I_Method0(osg::Node *, get);
I_Method0(const osg::Node *, get);
I_Method0(osg::Node *, take);
I_Method0(osg::Node *, release);
I_ReadOnlyProperty(osg::Node *, );
END_REFLECTOR
STD_VECTOR_REFLECTOR(std::vector< osg::ref_ptr< osg::Node > >);
<|endoftext|> |
<commit_before>/** @file
@brief Regstry to maintain instantiated loggers and global settings.
@date 2016
@author
Sensics, Inc.
<http://sensics.com>
*/
// Copyright 2016 Sensics, Inc.
//
// 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.
// Internal Includes
#include <osvr/Util/LogRegistry.h>
#include <osvr/Util/Log.h>
#include <osvr/Util/Logger.h>
#include <osvr/Util/LogLevel.h>
#include <osvr/Util/PlatformConfig.h>
// Library/third-party includes
#include <spdlog/spdlog.h>
#include <spdlog/sinks/ansicolor_sink.h>
#include <boost/filesystem.hpp>
// Standard includes
// - none
namespace osvr {
namespace util {
namespace log {
LogRegistry& LogRegistry::instance()
{
static LogRegistry instance_;
return instance_;
}
LoggerPtr LogRegistry::getOrCreateLogger(const std::string& logger_name)
{
// If logger already exists, return a copy of it
auto spd_logger = spdlog::get(logger_name);
if (spd_logger)
return std::make_shared<Logger>(spd_logger);
// Bummer, it didn't exist. We'll create one from scratch.
spd_logger = spdlog::details::registry::instance().create(logger_name, begin(sinks_), end(sinks_));
spd_logger->set_pattern("%b %d %T.%e %l [%n]: %v");
spd_logger->set_level(spdlog::level::trace);
spd_logger->flush_on(spdlog::level::err);
return std::make_shared<Logger>(spd_logger);
}
void setPattern(const std::string& pattern)
{
spdlog::set_pattern(pattern.c_str());
}
void setLevel(LogLevel severity)
{
spdlog::set_level(static_cast<spdlog::level::level_enum>(severity));
}
LogRegistry::LogRegistry() : sinks_()
{
// Set default pattern and level
spdlog::set_pattern("%b %d %T.%e %l [%n]: %v");
spdlog::set_level(static_cast<spdlog::level::level_enum>(LogLevel::info));
// Instantiate console and file sinks
// Console sink
auto console_out = spdlog::sinks::stderr_sink_mt::instance();
auto color_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(console_out); // taste the rainbow!
#if defined(OSVR_LINUX) || defined(OSVR_MACOSX)
sinks_.push_back(color_sink);
#elif defined(OSVR_ANDROID)
auto android_sink = spdlog::sinks::android_sink_mt("OSVR");
sinks_.push_back(android_sink);
#else
// No color for Windows yet (and not tested on other platforms)
sinks_.push_back(console_out);
#endif
// File sink - rotates daily
size_t q_size = 1048576; // queue size must be power of 2
spdlog::set_async_mode(q_size);
namespace fs = boost::filesystem;
auto base_name = fs::path(getLoggingDirectory(true));
if (!base_name.empty()) {
base_name /= "osvr";
auto daily_file_sink = std::make_shared<spdlog::sinks::daily_file_sink_mt>(base_name.string().c_str(), "log", 0, 0, false);
sinks_.push_back(daily_file_sink);
}
}
LogRegistry::~LogRegistry()
{
// do nothing
}
} // end namespace log
} // end namespace util
} // end namespace osvr
<commit_msg>Improve logic in logger creation function.<commit_after>/** @file
@brief Regstry to maintain instantiated loggers and global settings.
@date 2016
@author
Sensics, Inc.
<http://sensics.com>
*/
// Copyright 2016 Sensics, Inc.
//
// 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.
// Internal Includes
#include <osvr/Util/LogRegistry.h>
#include <osvr/Util/Log.h>
#include <osvr/Util/Logger.h>
#include <osvr/Util/LogLevel.h>
#include <osvr/Util/PlatformConfig.h>
// Library/third-party includes
#include <spdlog/spdlog.h>
#include <spdlog/sinks/ansicolor_sink.h>
#include <boost/filesystem.hpp>
// Standard includes
// - none
namespace osvr {
namespace util {
namespace log {
LogRegistry& LogRegistry::instance()
{
static LogRegistry instance_;
return instance_;
}
LoggerPtr LogRegistry::getOrCreateLogger(const std::string& logger_name)
{
// If logger already exists, return a copy of it
auto spd_logger = spdlog::get(logger_name);
if (!spd_logger) {
// Bummer, it didn't exist. We'll create one from scratch.
spd_logger = spdlog::details::registry::instance().create(logger_name, begin(sinks_), end(sinks_));
}
spd_logger->set_pattern("%b %d %T.%e %l [%n]: %v");
spd_logger->set_level(spdlog::level::trace);
spd_logger->flush_on(spdlog::level::err);
return std::make_shared<Logger>(spd_logger);
}
void setPattern(const std::string& pattern)
{
spdlog::set_pattern(pattern.c_str());
}
void setLevel(LogLevel severity)
{
spdlog::set_level(static_cast<spdlog::level::level_enum>(severity));
}
LogRegistry::LogRegistry() : sinks_()
{
// Set default pattern and level
spdlog::set_pattern("%b %d %T.%e %l [%n]: %v");
spdlog::set_level(static_cast<spdlog::level::level_enum>(LogLevel::info));
// Instantiate console and file sinks
// Console sink
auto console_out = spdlog::sinks::stderr_sink_mt::instance();
auto color_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(console_out); // taste the rainbow!
#if defined(OSVR_LINUX) || defined(OSVR_MACOSX)
sinks_.push_back(color_sink);
#elif defined(OSVR_ANDROID)
auto android_sink = spdlog::sinks::android_sink_mt("OSVR");
sinks_.push_back(android_sink);
#else
// No color for Windows yet (and not tested on other platforms)
sinks_.push_back(console_out);
#endif
// File sink - rotates daily
size_t q_size = 1048576; // queue size must be power of 2
spdlog::set_async_mode(q_size);
namespace fs = boost::filesystem;
auto base_name = fs::path(getLoggingDirectory(true));
if (!base_name.empty()) {
base_name /= "osvr";
auto daily_file_sink = std::make_shared<spdlog::sinks::daily_file_sink_mt>(base_name.string().c_str(), "log", 0, 0, false);
sinks_.push_back(daily_file_sink);
}
}
LogRegistry::~LogRegistry()
{
// do nothing
}
} // end namespace log
} // end namespace util
} // end namespace osvr
<|endoftext|> |
<commit_before>/*
Odometer.cpp
Source: https://github.com/DrGFreeman/RasPiBot202.V2
MIT License
Copyright (c) 2017 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
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.
*/
/*
An odometer class for a differential drive robot
*/
#include <Odometer.h>
#include <math.h>
// Constructor
Odometer::Odometer(float tickDist, float track)
{
// Set tick distance and track properties
_tickDist = tickDist;
_track = track;
// Initialize variables
_x = 0;
_y = 0;
_phi = 0;
_speedLeft = 0;
_speedRight = 0;
_omega = 0;
_lastCountLeft = 0;
_lastCountRight = 0;
_lastUpdateTime = micros();
}
// Return the angular velocity in rad/s
float Odometer::getOmega()
{
return _omega;
}
// Return the phi angle
float Odometer::getPhi()
{
return _phi;
}
// Return the speed in distance unit / s
float Odometer::getSpeed()
{
return (_speedLeft + _speedRight) / 2;
}
// Return the left speed in distance unit / s
float Odometer::getSpeedLeft()
{
return _speedLeft;
}
// Return the right speed in distance unit / s
float Odometer::getSpeedRight()
{
return _speedRight;
}
// Return the time step between last two update calls in micro seconds
unsigned int Odometer::getTimeStep()
{
return _timeStep;
}
// Return the X position
float Odometer::getX()
{
return _x;
}
// Return the Y position
float Odometer::getY()
{
return _y;
}
// Update position and speed with new encoder counts
void Odometer::update(int countLeft, int countRight)
{
// Calculate time step since last update
unsigned long currentTime = micros();
_timeStep = currentTime - _lastUpdateTime;
// Store current time for next update
_lastUpdateTime = currentTime;
// Calculate difference in counts since last update
int diffLeft = countLeft - _lastCountLeft;
int diffRight = countRight - _lastCountRight;
// Store current counts for next update
_lastCountLeft = countLeft;
_lastCountRight = countRight;
// Calculate displacement
float distLeft = diffLeft * _tickDist;
float distRight = diffRight * _tickDist;
float distCenter = (distLeft + distRight) / 2;
float deltaPhi = (distRight - distLeft) / _track;
// Calculate new Position
_x += distCenter * cos(_phi);
_y += distCenter * sin(_phi);
_phi = (_phi + deltaPhi);
// Keep _phi within 0 & 2 * Pi
if (_phi > 2 * M_PI)
{
_phi -= 2 * M_PI;
}
else if (_phi < 0)
{
_phi += 2 * M_PI;
}
// Calculate speed
_speedLeft = distLeft / float(_timeStep / 1E6);
_speedRight = distRight / float(_timeStep / 1E6);
_omega = deltaPhi / float(_timeStep / 1E6);;
}
<commit_msg>Modified phi angle calculation in update method<commit_after>/*
Odometer.cpp
Source: https://github.com/DrGFreeman/RasPiBot202.V2
MIT License
Copyright (c) 2017 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
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.
*/
/*
An odometer class for a differential drive robot
*/
#include <Odometer.h>
#include <math.h>
// Constructor
Odometer::Odometer(float tickDist, float track)
{
// Set tick distance and track properties
_tickDist = tickDist;
_track = track;
// Initialize variables
_x = 0;
_y = 0;
_phi = 0;
_speedLeft = 0;
_speedRight = 0;
_omega = 0;
_lastCountLeft = 0;
_lastCountRight = 0;
_lastUpdateTime = micros();
}
// Return the angular velocity in rad/s
float Odometer::getOmega()
{
return _omega;
}
// Return the phi angle
float Odometer::getPhi()
{
return _phi;
}
// Return the speed in distance unit / s
float Odometer::getSpeed()
{
return (_speedLeft + _speedRight) / 2;
}
// Return the left speed in distance unit / s
float Odometer::getSpeedLeft()
{
return _speedLeft;
}
// Return the right speed in distance unit / s
float Odometer::getSpeedRight()
{
return _speedRight;
}
// Return the time step between last two update calls in micro seconds
unsigned int Odometer::getTimeStep()
{
return _timeStep;
}
// Return the X position
float Odometer::getX()
{
return _x;
}
// Return the Y position
float Odometer::getY()
{
return _y;
}
// Update position and speed with new encoder counts
void Odometer::update(int countLeft, int countRight)
{
// Calculate time step since last update
unsigned long currentTime = micros();
_timeStep = currentTime - _lastUpdateTime;
// Store current time for next update
_lastUpdateTime = currentTime;
// Calculate difference in counts since last update
int diffLeft = countLeft - _lastCountLeft;
int diffRight = countRight - _lastCountRight;
// Store current counts for next update
_lastCountLeft = countLeft;
_lastCountRight = countRight;
// Calculate displacement
float distLeft = diffLeft * _tickDist;
float distRight = diffRight * _tickDist;
float distCenter = (distLeft + distRight) / 2;
float deltaPhi = (distRight - distLeft) / _track;
// Calculate new Position
_x += distCenter * cos(_phi);
_y += distCenter * sin(_phi);
_phi += deltaPhi;
// Keep _phi within 0 & 2 * Pi
if (_phi > 2 * M_PI)
{
_phi -= 2 * M_PI;
}
else if (_phi < 0)
{
_phi += 2 * M_PI;
}
// Calculate speed
_speedLeft = distLeft / float(_timeStep / 1E6);
_speedRight = distRight / float(_timeStep / 1E6);
_omega = deltaPhi / float(_timeStep / 1E6);;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <fstream>
#include <iterator>
#include <exception>
#include <string.h>
#include <numeric>
#include <iomanip>
#include <sstream>
#include <string>
#include "LIEF/logging++.hpp"
#include "mbedtls/md5.h"
#include "LIEF/exception.hpp"
#include "LIEF/PE/utils.hpp"
#include "LIEF/PE/Binary.hpp"
#include "LIEF/PE/Import.hpp"
#include "utils/ordinals_lookup_tables/libraries_table.hpp"
namespace LIEF {
namespace PE {
bool is_pe(const std::string& file) {
std::ifstream binary(file, std::ios::in | std::ios::binary);
if (not binary) {
LOG(ERROR) << "Unable to open the file!";
return false;
}
uint64_t file_size;
binary.unsetf(std::ios::skipws);
binary.seekg(0, std::ios::end);
file_size = binary.tellg();
binary.seekg(0, std::ios::beg);
if (file_size < sizeof(pe_dos_header)) {
LOG(ERROR) << "File too small";
return false;
}
char magic[2];
pe_dos_header dos_header;
binary.read(magic, sizeof(magic));
if (magic[0] != 'M' or magic[1] != 'Z') {
return false;
}
binary.seekg(0, std::ios::beg);
binary.read(reinterpret_cast<char*>(&dos_header), sizeof(pe_dos_header));
if (dos_header.AddressOfNewExeHeader >= file_size) {
return false;
}
char signature[sizeof(PE_Magic)];
binary.seekg(dos_header.AddressOfNewExeHeader, std::ios::beg);
binary.read(signature, sizeof(PE_Magic));
return std::equal(std::begin(signature), std::end(signature), std::begin(PE_Magic));
}
bool is_pe(const std::vector<uint8_t>& raw) {
if (raw.size() < sizeof(pe_dos_header)) {
return false;
}
const pe_dos_header* dos_header = reinterpret_cast<const pe_dos_header*>(raw.data());
if (raw[0] != 'M' or raw[1] != 'Z') {
return false;
}
if ((dos_header->AddressOfNewExeHeader + sizeof(pe_header)) >= raw.size()) {
return false;
}
char signature[sizeof(PE_Magic)];
std::copy(
reinterpret_cast<const uint8_t*>(raw.data() + dos_header->AddressOfNewExeHeader),
reinterpret_cast<const uint8_t*>(raw.data() + dos_header->AddressOfNewExeHeader) + sizeof(signature),
signature);
return std::equal(std::begin(signature), std::end(signature), std::begin(PE_Magic));
}
PE_TYPE get_type(const std::string& file) {
if (not is_pe(file)) {
throw LIEF::bad_format("This file is not a PE binary");
}
std::ifstream binary(file, std::ios::in | std::ios::binary);
if (not binary) {
throw LIEF::bad_file("Unable to open the file");
}
pe_dos_header dos_header;
pe32_optional_header optional_header;
binary.seekg(0, std::ios::beg);
binary.read(reinterpret_cast<char*>(&dos_header), sizeof(pe_dos_header));
binary.seekg(dos_header.AddressOfNewExeHeader + sizeof(pe_header), std::ios::beg);
binary.read(reinterpret_cast<char*>(&optional_header), sizeof(pe32_optional_header));
PE_TYPE type = static_cast<PE_TYPE>(optional_header.Magic);
if (type == PE_TYPE::PE32 or type == PE_TYPE::PE32_PLUS) {
return type;
} else {
throw LIEF::bad_format("This file is not PE32 or PE32+");
}
}
PE_TYPE get_type(const std::vector<uint8_t>& raw) {
if (not is_pe(raw)) {
throw LIEF::bad_format("This file is not a PE binary");
}
const pe_dos_header* dos_header;
const pe32_optional_header* optional_header;
dos_header = reinterpret_cast<const pe_dos_header*>(raw.data());
optional_header = reinterpret_cast<const pe32_optional_header*>(
raw.data() +
dos_header->AddressOfNewExeHeader +
sizeof(pe_header));
PE_TYPE type = static_cast<PE_TYPE>(optional_header->Magic);
if (type == PE_TYPE::PE32 or type == PE_TYPE::PE32_PLUS) {
return type;
} else {
throw LIEF::bad_format("This file is not PE32 or PE32+");
}
}
std::string get_imphash(const Binary& binary) {
uint8_t md5_buffer[16];
if (not binary.has_imports()) {
return std::to_string(0);
}
auto to_lower = [] (const std::string& str) {
std::string lower = str;
std::transform(
std::begin(str),
std::end(str),
std::begin(lower),
::tolower);
return lower;
};
it_const_imports imports = binary.imports();
std::string import_list;
for (const Import& imp : imports) {
Import resolved = resolve_ordinals(imp);
size_t point_index = resolved.name().find_last_of(".");
std::string name_without_ext = resolved.name().substr(0, point_index);
std::string ext = resolved.name().substr(point_index, resolved.name().size());
std::string entries_string;
for (const ImportEntry& e : resolved.entries()) {
if (e.is_ordinal()) {
entries_string += name_without_ext + ".#" + std::to_string(e.ordinal());
} else {
entries_string += name_without_ext + "." + e.name();
}
}
import_list += to_lower(entries_string);
}
std::sort(
std::begin(import_list),
std::end(import_list),
std::less<char>());
mbedtls_md5(
reinterpret_cast<const uint8_t*>(import_list.data()),
import_list.size(),
md5_buffer);
std::string output_hex = std::accumulate(
std::begin(md5_buffer),
std::end(md5_buffer),
std::string{},
[] (const std::string& a, uint8_t b) {
std::stringstream ss;
ss << std::hex;
ss << std::setw(2) << std::setfill('0') << static_cast<uint32_t>(b);
return a + ss.str();
});
return output_hex;
}
Import resolve_ordinals(const Import& import, bool strict) {
it_const_import_entries entries = import.entries();
if (std::all_of(
std::begin(entries),
std::end(entries),
[] (const ImportEntry& entry) {
return not entry.is_ordinal();
})) {
VLOG(VDEBUG) << "All imports use name. No ordinal!";
return import;
}
std::string name = import.name();
std::transform(
std::begin(name),
std::end(name),
std::begin(name),
::tolower);
auto&& it_library_lookup = ordinals_library_tables.find(name);
if (it_library_lookup == std::end(ordinals_library_tables)) {
std::string msg = "Ordinal lookup table for '" + name + "' not implemented";
if (strict) {
throw not_found(msg);
}
VLOG(VDEBUG) << msg;
return import;
}
Import resolved_import = import;
for (ImportEntry& entry : resolved_import.entries()) {
if (entry.is_ordinal()) {
VLOG(VDEBUG) << "Dealing with: " << entry;
auto&& it_entry = it_library_lookup->second.find(static_cast<uint32_t>(entry.ordinal()));
if (it_entry == std::end(it_library_lookup->second)) {
if (strict) {
throw not_found("Unable to resolve ordinal: " + std::to_string(entry.ordinal()));
}
VLOG(VDEBUG) << "Unable to resolve ordinal:" << std::hex << entry.ordinal();
continue;
}
entry.data(0);
entry.name(it_entry->second);
}
}
return resolved_import;
}
}
}
<commit_msg>Fix possible out of bound reads in utils.cpp<commit_after>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <fstream>
#include <iterator>
#include <exception>
#include <string.h>
#include <numeric>
#include <iomanip>
#include <sstream>
#include <string>
#include "LIEF/logging++.hpp"
#include "mbedtls/md5.h"
#include "LIEF/exception.hpp"
#include "LIEF/PE/utils.hpp"
#include "LIEF/PE/Binary.hpp"
#include "LIEF/PE/Import.hpp"
#include "utils/ordinals_lookup_tables/libraries_table.hpp"
namespace LIEF {
namespace PE {
bool is_pe(const std::string& file) {
std::ifstream binary(file, std::ios::in | std::ios::binary);
if (not binary) {
LOG(ERROR) << "Unable to open the file!";
return false;
}
uint64_t file_size;
binary.unsetf(std::ios::skipws);
binary.seekg(0, std::ios::end);
file_size = binary.tellg();
binary.seekg(0, std::ios::beg);
if (file_size < sizeof(pe_dos_header)) {
LOG(ERROR) << "File too small";
return false;
}
char magic[2];
pe_dos_header dos_header;
binary.read(magic, sizeof(magic));
if (magic[0] != 'M' or magic[1] != 'Z') {
return false;
}
binary.seekg(0, std::ios::beg);
binary.read(reinterpret_cast<char*>(&dos_header), sizeof(pe_dos_header));
if (dos_header.AddressOfNewExeHeader >= file_size) {
return false;
}
char signature[sizeof(PE_Magic)];
binary.seekg(dos_header.AddressOfNewExeHeader, std::ios::beg);
binary.read(signature, sizeof(PE_Magic));
return std::equal(std::begin(signature), std::end(signature), std::begin(PE_Magic));
}
bool is_pe(const std::vector<uint8_t>& raw) {
if (raw.size() < sizeof(pe_dos_header)) {
return false;
}
const pe_dos_header* dos_header = reinterpret_cast<const pe_dos_header*>(raw.data());
if (raw[0] != 'M' or raw[1] != 'Z') {
return false;
}
if ((dos_header->AddressOfNewExeHeader + sizeof(pe_header)) >= raw.size()) {
return false;
}
VectorStream raw_stream(raw);
raw_stream.setpos(dos_header->AddressOfNewExeHeader);
auto signature = raw_stream.read_array<char>(sizeof(PE_Magic), /* check bounds */ true);
return std::equal(signature, signature + sizeof(PE_Magic), std::begin(PE_Magic));
}
PE_TYPE get_type(const std::string& file) {
if (not is_pe(file)) {
throw LIEF::bad_format("This file is not a PE binary");
}
std::ifstream binary(file, std::ios::in | std::ios::binary);
if (not binary) {
throw LIEF::bad_file("Unable to open the file");
}
pe_dos_header dos_header;
pe32_optional_header optional_header;
binary.seekg(0, std::ios::beg);
binary.read(reinterpret_cast<char*>(&dos_header), sizeof(pe_dos_header));
binary.seekg(dos_header.AddressOfNewExeHeader + sizeof(pe_header), std::ios::beg);
binary.read(reinterpret_cast<char*>(&optional_header), sizeof(pe32_optional_header));
PE_TYPE type = static_cast<PE_TYPE>(optional_header.Magic);
if (type == PE_TYPE::PE32 or type == PE_TYPE::PE32_PLUS) {
return type;
} else {
throw LIEF::bad_format("This file is not PE32 or PE32+");
}
}
PE_TYPE get_type(const std::vector<uint8_t>& raw) {
if (not is_pe(raw)) {
throw LIEF::bad_format("This file is not a PE binary");
}
VectorStream raw_stream = VectorStream(raw);
const pe_dos_header* dos_header = &raw_stream.read<pe_dos_header>();
raw_stream.setpos(dos_header->AddressOfNewExeHeader + sizeof(pe_header));
const pe32_optional_header* optional_header = &raw_stream.read<pe32_optional_header>();
PE_TYPE type = static_cast<PE_TYPE>(optional_header->Magic);
if (type == PE_TYPE::PE32 or type == PE_TYPE::PE32_PLUS) {
return type;
} else {
throw LIEF::bad_format("This file is not PE32 or PE32+");
}
}
std::string get_imphash(const Binary& binary) {
uint8_t md5_buffer[16];
if (not binary.has_imports()) {
return std::to_string(0);
}
auto to_lower = [] (const std::string& str) {
std::string lower = str;
std::transform(
std::begin(str),
std::end(str),
std::begin(lower),
::tolower);
return lower;
};
it_const_imports imports = binary.imports();
std::string import_list;
for (const Import& imp : imports) {
Import resolved = resolve_ordinals(imp);
size_t point_index = resolved.name().find_last_of(".");
std::string name_without_ext = resolved.name().substr(0, point_index);
std::string ext = resolved.name().substr(point_index, resolved.name().size());
std::string entries_string;
for (const ImportEntry& e : resolved.entries()) {
if (e.is_ordinal()) {
entries_string += name_without_ext + ".#" + std::to_string(e.ordinal());
} else {
entries_string += name_without_ext + "." + e.name();
}
}
import_list += to_lower(entries_string);
}
std::sort(
std::begin(import_list),
std::end(import_list),
std::less<char>());
mbedtls_md5(
reinterpret_cast<const uint8_t*>(import_list.data()),
import_list.size(),
md5_buffer);
std::string output_hex = std::accumulate(
std::begin(md5_buffer),
std::end(md5_buffer),
std::string{},
[] (const std::string& a, uint8_t b) {
std::stringstream ss;
ss << std::hex;
ss << std::setw(2) << std::setfill('0') << static_cast<uint32_t>(b);
return a + ss.str();
});
return output_hex;
}
Import resolve_ordinals(const Import& import, bool strict) {
it_const_import_entries entries = import.entries();
if (std::all_of(
std::begin(entries),
std::end(entries),
[] (const ImportEntry& entry) {
return not entry.is_ordinal();
})) {
VLOG(VDEBUG) << "All imports use name. No ordinal!";
return import;
}
std::string name = import.name();
std::transform(
std::begin(name),
std::end(name),
std::begin(name),
::tolower);
auto&& it_library_lookup = ordinals_library_tables.find(name);
if (it_library_lookup == std::end(ordinals_library_tables)) {
std::string msg = "Ordinal lookup table for '" + name + "' not implemented";
if (strict) {
throw not_found(msg);
}
VLOG(VDEBUG) << msg;
return import;
}
Import resolved_import = import;
for (ImportEntry& entry : resolved_import.entries()) {
if (entry.is_ordinal()) {
VLOG(VDEBUG) << "Dealing with: " << entry;
auto&& it_entry = it_library_lookup->second.find(static_cast<uint32_t>(entry.ordinal()));
if (it_entry == std::end(it_library_lookup->second)) {
if (strict) {
throw not_found("Unable to resolve ordinal: " + std::to_string(entry.ordinal()));
}
VLOG(VDEBUG) << "Unable to resolve ordinal:" << std::hex << entry.ordinal();
continue;
}
entry.data(0);
entry.name(it_entry->second);
}
}
return resolved_import;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Fabia Serra Arrizabalaga
*
* This file is part of Crea
*
* Crea 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 (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "Particle.h"
Particle::Particle(){
isAlive = true;
opacity = 255;
isTouched = false;
immortal = false;
bounces = false;
steers = false;
infiniteWalls = false;
sizeAge = false;
opacityAge = false;
colorAge = false;
flickersAge = false;
isEmpty = false;
drawLine = false;
drawStroke = false;
strokeWidth = 1.2;
limitSpeed = false;
bounceDamping = true;
damping = 0.3;
age = 0;
width = ofGetWidth();
height = ofGetHeight();
}
void Particle::setup(float id, ofPoint pos, ofPoint vel, ofColor color, float initialRadius, float lifetime){
this->id = id;
this->pos = pos;
this->vel = vel;
this->color = color;
this->initialRadius = initialRadius;
this->lifetime = lifetime;
this->radius = initialRadius;
this->mass = initialRadius * initialRadius * 0.005f;
this->prevPos = pos;
this->iniPos = pos;
this->originalHue = color.getHue();
}
void Particle::update(float dt){
if(isAlive){
// Update position
acc = frc/mass; // Newton's second law F = m*a
vel += acc*dt; // Euler's method
vel *= friction; // Decay velocity
if(limitSpeed) limitVelocity();
pos += vel*dt;
frc.set(0, 0); // Restart force
// Update age and check if particle has to die
age += dt;
if(!immortal && age >= lifetime) isAlive = false;
else if(immortal) age = fmodf(age, lifetime);
// Decrease particle radius with age
if (sizeAge) radius = initialRadius * (1.0f - (age/lifetime));
// Decrease particle opacity with age
if (opacityAge) opacity *= (1.0f - (age/lifetime));
if (flickersAge && (age/lifetime) > 0.8 && ofRandomf() > 0.6) opacity *= 0.2;
// Change particle color with age
if (colorAge){
color.setSaturation(ofMap(age, 0, lifetime, 255, 128));
color.setHue(ofMap(age, 0, lifetime, originalHue, originalHue-80));
}
// // hackish way to make particles glitter when they slow down a lot
// if(vel.x * vel.x + vel.y * vel.y < 5) {
// vel.x = ofRandom(-10, 10);
// vel.y = ofRandom(-10, 10);
// }
// Bounce particle with the window margins
if(bounces){
marginsBounce();
}
else if(steers){
marginsSteer();
}
else if(infiniteWalls){
marginsWrap();
}
}
}
void Particle::draw(){
if(isAlive){
ofPushStyle();
ofSetColor(color, opacity);
if(isEmpty){
ofNoFill();
ofSetLineWidth(2);
}
else{
ofFill();
}
if(!drawLine){
int resolution = ofMap(fabs(radius), 0, 10, 6, 22, true);
ofSetCircleResolution(resolution);
ofCircle(pos, radius);
if(drawStroke){
ofPushStyle();
ofNoFill();
ofSetLineWidth(strokeWidth);
ofSetColor(0, opacity);
ofCircle(pos, radius);
ofPopStyle();
}
}
else{
// if(pos.squareDistance(prevPos) >= 25) ofLine(pos, pos-vel.getNormalized()*5);
// else ofLine(pos, prevPos);
// prevPos = pos;
ofSetLineWidth(ofMap(radius, 0, 15, 1, 5, true));
ofLine(pos, pos-vel.getNormalized()*radius);
}
ofPopStyle();
}
}
void Particle::addForce(ofPoint force){
frc += force;
}
void Particle::addNoise(float angle, float turbulence, float dt){
// Perlin noise
float noise = ofNoise(pos.x * 0.005f, pos.y * 0.005f, dt * 0.1f) * angle;
ofPoint noiseVector(cos(noise), sin(noise));
if(!immortal) frc += noiseVector * turbulence * age; // if immortal this doesn't affect, age == 0
else frc += noiseVector * turbulence;
}
void Particle::addRepulsionForce(Particle &p, float radiusSqrd, float scale){
// ----------- (1) make a vector of where this particle p is:
ofPoint posOfForce;
posOfForce.set(p.pos.x, p.pos.y);
// ----------- (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// ----------- (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// ----------- (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc += dir * scale * pct;
p.frc -= dir * scale * pct;
}
}
void Particle::addRepulsionForce(Particle &p, float scale){
// ----------- (1) make radius of repulsion equal particles radius sum
float radius = this->radius + p.radius;
float radiusSqrd = radius*radius;
// ----------- (2) call addRepulsion force with the computed radius
addRepulsionForce(p, radiusSqrd, scale);
}
void Particle::addRepulsionForce(float x, float y, float radiusSqrd, float scale){
// ----------- (1) make a vector of where this position is:
ofPoint posOfForce;
posOfForce.set(x, y);
// ----------- (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// ----------- (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// ----------- (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc += dir * scale * pct;
}
}
void Particle::addAttractionForce(Particle &p, float radiusSqrd, float scale){
// ----------- (1) make a vector of where this particle p is:
ofPoint posOfForce;
posOfForce.set(p.pos.x, p.pos.y);
// ----------- (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// ----------- (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// ----------- (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc -= dir * scale * pct;
p.frc += dir * scale * pct;
}
}
void Particle::addAttractionForce(float x, float y, float radiusSqrd, float scale){
// ----------- (1) make a vector of where this position is:
ofPoint posOfForce;
posOfForce.set(x, y);
// ----------- (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// ----------- (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// ----------- (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc -= dir * scale * pct;
}
}
//------------------------------------------------------------------
void Particle::returnToOrigin(float spd){
ofPoint dirToOrigin = iniPos - pos;
dirToOrigin.normalize();
float distSqrd = pos.squareDistance(iniPos);
if(distSqrd > 0){
float F = ofMap(distSqrd, 0, 100, 0, 250*spd, true);
dirToOrigin *= F;
}
frc += dirToOrigin;
// pos.x = spd * iniPos.x + (1-spd) * pos.x;
// pos.y = spd * iniPos.y + (1-spd) * pos.y;
// pos.x = spd * catchX + (1-spd) * pos.x; - Zachs equation
// xeno math explianed
// A------B--------------------C
// A is beginning, C is end
// say you wanna move .25 of the remaining dist each iteration
// your first iteration you moved to B, wich is 0.25 of the distance between A and C
// the next iteration you will move .25 the distance between B and C
// let the next iteration be called 'new'
// pos.new = pos.b + (pos.c-pos.b)*0.25
// now let's simplify this equation
// pos.new = pos.b(1-.25) + pos.c(.25)
// since pos.new and pos.b are analogous to pos.x
// and pos.c is analogous to catchX
// we can write pos.x = pos.x(1-.25) + catchX(.25)
// this equation is the same as Zachs Lieberman simplified equation
}
void Particle::addFlockingForces(Particle &p){
ofPoint dir = pos - p.pos;
float distSqrd = pos.squareDistance(p.pos);
if(0.01f < distSqrd && distSqrd < flockingRadiusSqrd){ // if neighbor particle within zone radius...
float percent = distSqrd/flockingRadiusSqrd;
// Separate
if(percent < lowThresh){ // ... and is within the lower threshold limits, separate
float F = (lowThresh/percent - 1.0f) * separationStrength;
dir = dir.getNormalized() * F;
frc += dir;
p.frc -= dir;
}
// Align
else if(percent < highThresh){ // ... else if it is within the higher threshold limits, align
float threshDelta = highThresh - lowThresh;
float adjustedPercent = (percent - lowThresh) / threshDelta;
float F = (0.5f - cos(adjustedPercent * M_PI * 2.0f) * 0.5f + 0.5f) * alignmentStrength;
frc += p.vel.getNormalized() * F;
p.frc += vel.getNormalized() * F;
}
// Attract
else{ // ... else, attract
float threshDelta = 1.0f - highThresh;
float adjustedPercent = (percent - highThresh) / threshDelta;
float F = (0.5f - cos(adjustedPercent * M_PI * 2.0f) * 0.5f + 0.5f) * attractionStrength;
dir = dir.getNormalized() * F;
frc -= dir;
p.frc += dir;
}
}
}
void Particle::pullToCenter(){
ofPoint center(width/2, height/2);
ofPoint dirToCenter = pos - center;
float distToCenterSqrd = dirToCenter.lengthSquared();
float distThresh = 900.0f;
if(distToCenterSqrd > distThresh){
dirToCenter.normalize();
float pullStrength = 0.000015f;
frc -= dirToCenter * ( ( distToCenterSqrd - distThresh ) * pullStrength );
}
}
void Particle::seek(ofPoint target, float radiusSqrd){
ofPoint dirToTarget = target - pos;
dirToTarget.normalize();
float distSqrd = pos.squareDistance(target);
if(distSqrd < radiusSqrd){
float F = ofMap(distSqrd, 0, radiusSqrd, 0, 70);
dirToTarget *= F;
}
else{
dirToTarget *= 70.0;
}
frc += dirToTarget;
}
void Particle::seek(ofPoint target){
ofPoint dirToTarget = target - pos;
dirToTarget.normalize();
dirToTarget *= ofRandom(15, 60);
vel += dirToTarget;
}
void Particle::marginsBounce(){
bool isBouncing = false;
if(pos.x > width-radius){
pos.x = width-radius;
vel.x *= -1.0;
}
else if(pos.x < radius){
pos.x = radius;
vel.x *= -1.0;
}
if(pos.y > height-radius){
pos.y = height-radius;
vel.y *= -1.0;
isBouncing = true;
}
else if(pos.y < radius){
pos.y = radius;
vel.y *= -1.0;
isBouncing = true;
}
if (isBouncing && bounceDamping){
vel *= damping;
}
}
void Particle::marginsSteer(){
float margin = radius*10;
if(pos.x > width-margin){
vel.x -= ofMap(pos.x, width-margin, width, maxSpeed/1000.0, maxSpeed/10.0);
}
else if(pos.x < margin){
vel.x += ofMap(pos.x, 0, margin, maxSpeed/1000.0, maxSpeed/10.0);
}
if(pos.y > height-margin){
vel.y -= ofMap(pos.y, height-margin, height, maxSpeed/1000.0, maxSpeed/10.0);
}
else if(pos.y < margin){
vel.y += ofMap(pos.y, 0, margin, maxSpeed/1000.0, maxSpeed/10.0);
}
}
void Particle::marginsWrap(){
if(pos.x-radius > (float)width){
pos.x = -radius;
}
else if(pos.x+radius < 0.0){
pos.x = width;
}
if(pos.y-radius > (float)height){
pos.y = -radius;
}
else if(pos.y+radius < 0.0){
pos.y = height;
}
}
void Particle::contourBounce(ofPolyline contour){
unsigned int index;
if(contour.inside(pos)){
ofPoint contactPoint = contour.getClosestPoint(pos, &index);
ofVec2f normal = contour.getNormalAtIndex(index);
vel = vel - 2*vel.dot(normal)*normal;
if(bounceDamping) vel *= damping;
}
}
void Particle::kill(){
isAlive = false;
}
void Particle::limitVelocity(){
if(vel.lengthSquared() > (maxSpeed*maxSpeed)){
vel.normalize();
vel *= maxSpeed;
}
}
<commit_msg>increment strength force for seek and returnToOrigin plus a few more changes.<commit_after>/*
* Copyright (C) 2015 Fabia Serra Arrizabalaga
*
* This file is part of Crea
*
* Crea 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 (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "Particle.h"
Particle::Particle(){
isAlive = true;
opacity = 255;
isTouched = false;
immortal = false;
bounces = false;
steers = false;
infiniteWalls = false;
sizeAge = false;
opacityAge = false;
colorAge = false;
flickersAge = false;
isEmpty = false;
drawLine = false;
drawStroke = false;
strokeWidth = 1.2;
limitSpeed = false;
bounceDamping = true;
damping = 0.6;
age = 0;
width = ofGetWidth();
height = ofGetHeight();
}
void Particle::setup(float id, ofPoint pos, ofPoint vel, ofColor color, float initialRadius, float lifetime){
this->id = id;
this->pos = pos;
this->vel = vel;
this->color = color;
this->initialRadius = initialRadius;
this->lifetime = lifetime;
this->radius = initialRadius;
this->mass = initialRadius * initialRadius * 0.005f;
this->prevPos = pos;
this->iniPos = pos;
this->originalHue = color.getHue();
}
void Particle::update(float dt){
if(isAlive){
// Update position
acc = frc/mass; // Newton's second law F = m*a
vel += acc*dt; // Euler's method
vel *= friction; // Decay velocity
if(limitSpeed) limitVelocity();
pos += vel*dt;
frc.set(0, 0); // Restart force
// Update age and check if particle has to die
age += dt;
if(!immortal && age >= lifetime) isAlive = false;
else if(immortal) age = fmodf(age, lifetime);
// Decrease particle radius with age
if (sizeAge) radius = initialRadius * (1.0f - (age/lifetime));
// Decrease particle opacity with age
if (opacityAge) opacity *= (1.0f - (age/lifetime));
if (flickersAge && (age/lifetime) > 0.8 && ofRandomf() > 0.6) opacity *= 0.2;
// Change particle color with age
if (colorAge){
color.setSaturation(ofMap(age, 0, lifetime, 255, 128));
color.setHue(ofMap(age, 0, lifetime, originalHue, originalHue-80));
}
// // hackish way to make particles glitter when they slow down a lot
// if(vel.x * vel.x + vel.y * vel.y < 5) {
// vel.x = ofRandom(-10, 10);
// vel.y = ofRandom(-10, 10);
// }
// Bounce particle with the window margins
if(bounces){
marginsBounce();
}
else if(steers){
marginsSteer();
}
else if(infiniteWalls){
marginsWrap();
}
}
}
void Particle::draw(){
if(isAlive){
ofPushStyle();
ofSetColor(color, opacity);
if(isEmpty){
ofNoFill();
ofSetLineWidth(2);
}
else{
ofFill();
}
if(!drawLine){
int resolution = ofMap(fabs(radius), 0, 10, 6, 22, true);
ofSetCircleResolution(resolution);
ofCircle(pos, radius);
if(drawStroke){
ofPushStyle();
ofNoFill();
ofSetLineWidth(strokeWidth);
ofSetColor(0, opacity);
ofCircle(pos, radius);
ofPopStyle();
}
}
else{
// if(pos.squareDistance(prevPos) >= 25) ofLine(pos, pos-vel.getNormalized()*5);
// else ofLine(pos, prevPos);
// prevPos = pos;
ofSetLineWidth(ofMap(radius, 0, 15, 1, 5, true));
ofLine(pos, pos-vel.getNormalized()*radius);
}
ofPopStyle();
}
}
void Particle::addForce(ofPoint force){
frc += force;
}
void Particle::addNoise(float angle, float turbulence, float dt){
// Perlin noise
float noise = ofNoise(pos.x * 0.005f, pos.y * 0.005f, dt * 0.1f) * angle;
ofPoint noiseVector(cos(noise), sin(noise));
if(!immortal) frc += noiseVector * turbulence * age; // if immortal this doesn't affect, age == 0
else frc += noiseVector * turbulence;
}
void Particle::addRepulsionForce(Particle &p, float radiusSqrd, float scale){
// (1) make a vector of where this particle p is:
ofPoint posOfForce;
posOfForce.set(p.pos.x, p.pos.y);
// (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// (4) if so, update both forces
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc += dir * scale * pct;
p.frc -= dir * scale * pct;
}
}
void Particle::addRepulsionForce(Particle &p, float scale){
// (1) make radius of repulsion equal to particle's radius sum
float radius = this->radius + p.radius;
float radiusSqrd = radius*radius;
// (2) call addRepulsion force with the computed radius
addRepulsionForce(p, radiusSqrd, scale);
}
void Particle::addRepulsionForce(float x, float y, float radiusSqrd, float scale){
// (1) make a vector of where this position is:
ofPoint posOfForce;
posOfForce.set(x, y);
// (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc += dir * scale * pct;
}
}
void Particle::addAttractionForce(Particle &p, float radiusSqrd, float scale){
// (1) make a vector of where this particle p is:
ofPoint posOfForce;
posOfForce.set(p.pos.x, p.pos.y);
// (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// (4) if so, update both forces
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc -= dir * scale * pct;
p.frc += dir * scale * pct;
}
}
void Particle::addAttractionForce(float x, float y, float radiusSqrd, float scale){
// (1) make a vector of where this position is:
ofPoint posOfForce;
posOfForce.set(x, y);
// (2) calculate the difference & length
ofPoint dir = pos - posOfForce;
float distSqrd = pos.squareDistance(posOfForce); // faster than length or distance (no square root)
// (3) check close enough
bool closeEnough = true;
if (radiusSqrd > 0){
if (distSqrd > radiusSqrd){
closeEnough = false;
}
}
// (4) if so, update force
if (closeEnough == true){
float pct = 1 - (distSqrd / radiusSqrd); // stronger on the inside
dir.normalize();
frc -= dir * scale * pct;
}
}
//------------------------------------------------------------------
void Particle::returnToOrigin(float spd){
ofPoint dirToOrigin = iniPos - pos;
dirToOrigin.normalize();
float distSqrd = pos.squareDistance(iniPos);
if(distSqrd > 0){
float F = ofMap(distSqrd, 0, 300, 0, 250*spd, true);
dirToOrigin *= F;
}
frc += dirToOrigin;
// pos.x = spd * iniPos.x + (1-spd) * pos.x;
// pos.y = spd * iniPos.y + (1-spd) * pos.y;
// pos.x = spd * catchX + (1-spd) * pos.x; - Zachs equation
// xeno math explianed
// A------B--------------------C
// A is beginning, C is end
// say you wanna move .25 of the remaining dist each iteration
// your first iteration you moved to B, wich is 0.25 of the distance between A and C
// the next iteration you will move .25 the distance between B and C
// let the next iteration be called 'new'
// pos.new = pos.b + (pos.c-pos.b)*0.25
// now let's simplify this equation
// pos.new = pos.b(1-.25) + pos.c(.25)
// since pos.new and pos.b are analogous to pos.x
// and pos.c is analogous to catchX
// we can write pos.x = pos.x(1-.25) + catchX(.25)
// this equation is the same as Zachs Lieberman simplified equation
}
void Particle::addFlockingForces(Particle &p){
ofPoint dir = pos - p.pos;
float distSqrd = pos.squareDistance(p.pos);
if(0.01f < distSqrd && distSqrd < flockingRadiusSqrd){ // if neighbor particle within zone radius...
float percent = distSqrd/flockingRadiusSqrd;
// Separate
if(percent < lowThresh){ // ... and is within the lower threshold limits, separate
float F = (lowThresh/percent - 1.0f) * separationStrength;
dir = dir.getNormalized() * F;
frc += dir;
p.frc -= dir;
}
// Align
else if(percent < highThresh){ // ... else if it is within the higher threshold limits, align
float threshDelta = highThresh - lowThresh;
float adjustedPercent = (percent - lowThresh) / threshDelta;
float F = (0.5f - cos(adjustedPercent * M_PI * 2.0f) * 0.5f + 0.5f) * alignmentStrength;
frc += p.vel.getNormalized() * F;
p.frc += vel.getNormalized() * F;
}
// Attract
else{ // ... else, attract
float threshDelta = 1.0f - highThresh;
float adjustedPercent = (percent - highThresh) / threshDelta;
float F = (0.5f - cos(adjustedPercent * M_PI * 2.0f) * 0.5f + 0.5f) * attractionStrength;
dir = dir.getNormalized() * F;
frc -= dir;
p.frc += dir;
}
}
}
void Particle::pullToCenter(){
ofPoint center(width/2, height/2);
ofPoint dirToCenter = pos - center;
float distToCenterSqrd = dirToCenter.lengthSquared();
float distThresh = 900.0f;
if(distToCenterSqrd > distThresh){
dirToCenter.normalize();
float pullStrength = 0.000015f;
frc -= dirToCenter * ( ( distToCenterSqrd - distThresh ) * pullStrength );
}
}
void Particle::seek(ofPoint target, float radiusSqrd){
ofPoint dirToTarget = target - pos;
dirToTarget.normalize();
float distSqrd = pos.squareDistance(target);
if(distSqrd < radiusSqrd){
float F = ofMap(distSqrd, 0, radiusSqrd, 0, 200);
dirToTarget *= F;
}
else{
dirToTarget *= 200.0;
}
frc += dirToTarget;
}
void Particle::seek(ofPoint target){
ofPoint dirToTarget = target - pos;
dirToTarget.normalize();
dirToTarget *= ofRandom(20, 300);
vel += dirToTarget;
}
void Particle::marginsBounce(){
bool isBouncing = false;
if(pos.x > width-radius){
pos.x = width-radius;
vel.x *= -1.0;
}
else if(pos.x < radius){
pos.x = radius;
vel.x *= -1.0;
}
if(pos.y > height-radius){
pos.y = height-radius;
vel.y *= -1.0;
isBouncing = true;
}
else if(pos.y < radius){
pos.y = radius;
vel.y *= -1.0;
isBouncing = true;
}
if (isBouncing && bounceDamping){
vel *= damping;
}
}
void Particle::marginsSteer(){
float margin = radius*10;
if(pos.x > width-margin){
vel.x -= ofMap(pos.x, width-margin, width, maxSpeed/1000.0, maxSpeed/10.0);
}
else if(pos.x < margin){
vel.x += ofMap(pos.x, 0, margin, maxSpeed/1000.0, maxSpeed/10.0);
}
if(pos.y > height-margin){
vel.y -= ofMap(pos.y, height-margin, height, maxSpeed/1000.0, maxSpeed/10.0);
}
else if(pos.y < margin){
vel.y += ofMap(pos.y, 0, margin, maxSpeed/1000.0, maxSpeed/10.0);
}
}
void Particle::marginsWrap(){
if(pos.x-radius > (float)width){
pos.x = -radius;
}
else if(pos.x+radius < 0.0){
pos.x = width;
}
if(pos.y-radius > (float)height){
pos.y = -radius;
}
else if(pos.y+radius < 0.0){
pos.y = height;
}
}
void Particle::contourBounce(ofPolyline contour){
unsigned int index;
if(contour.inside(pos)){
ofPoint contactPoint = contour.getClosestPoint(pos, &index);
ofVec2f normal = contour.getNormalAtIndex(index);
vel = vel - 2*vel.dot(normal)*normal;
if(bounceDamping) vel *= damping;
}
}
void Particle::kill(){
isAlive = false;
}
void Particle::limitVelocity(){
if(vel.lengthSquared() > (maxSpeed*maxSpeed)){
vel.normalize();
vel *= maxSpeed;
}
}
<|endoftext|> |
<commit_before>//
// Pipeline.cpp
// Cinder-Pipeline
//
// Created by Jean-Pierre Mouilleseaux on 19 Apr 2014.
// Copyright 2014 Chorded Constructions. All rights reserved.
//
#include "Pipeline.h"
#include "cinder/Utilities.h"
using namespace ci;
namespace Cinder { namespace Pipeline {
PipelineRef Pipeline::create() {
return PipelineRef(new Pipeline())->shared_from_this();
}
Pipeline::Pipeline() {
}
Pipeline::~Pipeline() {
}
#pragma mark -
void Pipeline::setup(const Vec2i size) {
#if defined(DEBUG)
const char* renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
cinder::app::console() << "GL_RENDERER: " << renderer << std::endl;
const char* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
cinder::app::console() << "GL_VENDOR: " << vendor << std::endl;
const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
cinder::app::console() << "GL_VERSION: " << version << std::endl;
const char* shadingLanguageVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
cinder::app::console() << "GL_SHADING_LANGUAGE_VERSION: " << shadingLanguageVersion << std::endl;
std::string extensionsString = std::string(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
std::vector<std::string> extensions = split(extensionsString, " ");
extensions.erase(std::remove_if(extensions.begin(), extensions.end(), [](const std::string& s){ return s.empty(); }));
cinder::app::console() << "GL_EXTENSIONS: " << std::endl;
for (auto e : extensions) {
cinder::app::console() << " " << e << std::endl;
}
GLint dims[2];
glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
cinder::app::console() << "GL_MAX_VIEWPORT_DIMS: " << dims[0] << "x" << dims[1] << std::endl;
GLint texSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);
cinder::app::console() << "GL_MAX_TEXTURE_SIZE: " << texSize << std::endl;
glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &texSize);
cinder::app::console() << "GL_MAX_3D_TEXTURE_SIZE: " << texSize << std::endl;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texSize);
cinder::app::console() << "GL_MAX_TEXTURE_IMAGE_UNITS: " << texSize << std::endl;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &texSize);
cinder::app::console() << "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: " << texSize << std::endl;
glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &texSize);
cinder::app::console() << "GL_MAX_COLOR_ATTACHMENTS: " << texSize << std::endl;
cinder::app::console() << "-------------" << std::endl;
#endif
gl::Fbo::Format format;
format.enableColorBuffer(true, 3);
format.enableDepthBuffer(false);
// format.setWrap(GL_CLAMP, GL_CLAMP);
// format.setMagFilter(GL_NEAREST);
// format.setMinFilter(GL_LINEAR);
mFBO = gl::Fbo(size.x, size.y, format);
mFBO.bindFramebuffer(); {
const GLenum buffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
glDrawBuffers(3, buffers);
gl::setViewport(mFBO.getBounds());
gl::clear();
} mFBO.unbindFramebuffer();
// for (size_t idx = 0; idx < 3; ++idx) {
// mFBO.getTexture(idx).setWrap(GL_CLAMP, GL_CLAMP);
// }
}
gl::Texture& Pipeline::evaluate(const NodeRef& node) {
// build branch list
std::deque<std::deque<NodeRef>> branches;
std::deque<NodeRef> branch;
std::deque<NodeRef> stack;
NodeRef n = node;
while (n) {
branch.push_front(n);
// TODO - replace with RTTI to determine if n is a SourceNodeRef
if (n->getInputNodes().empty()) {
branches.push_front(branch);
branch = std::deque<NodeRef>();
if (stack.empty()) {
n = nullptr;
} else {
n = stack.front();
stack.pop_front();
}
} else {
if (n->getInputNodes().size() > 1) {
branches.push_front(branch);
branch = std::deque<NodeRef>();
stack.push_front(n->getInputNodes()[0]);
n = n->getInputNodes()[1];
} else {
n = n->getInputNodes()[0];
}
}
}
// render branches
unsigned int outAttachment = 0;
mFBO.bindFramebuffer(); {
gl::pushMatrices(); {
gl::setMatricesWindow(mFBO.getSize(), false);
std::vector<int> attachments = {0, 1, 2};
std::vector<int> storedAttachments;
for (std::deque<NodeRef> branch : branches) {
size_t attachmentIndex = 0;
outAttachment = attachments.at(attachmentIndex);
int inAttachment = -1;
int inAltAttachment = -1;
for (NodeRef n : branch) {
switch (n->getInputNodes().size()) {
case 0:
n->render(mFBO, outAttachment);
inAttachment = outAttachment;
break;
case 1:
attachmentIndex = (attachmentIndex + 1) % attachments.size();
outAttachment = attachments.at(attachmentIndex);
n->render(mFBO, inAttachment, mFBO, outAttachment);
inAttachment = outAttachment;
break;
case 2:
inAttachment = storedAttachments.at(0);
inAltAttachment = storedAttachments.at(1);
storedAttachments.clear();
attachments = {0, 1, 2};
attachmentIndex = outAttachment;
n->render(mFBO, inAttachment, mFBO, inAltAttachment, mFBO, outAttachment);
inAttachment = outAttachment;
break;
default:
break;
}
}
storedAttachments.push_back(outAttachment);
attachments.erase(std::find(attachments.begin(), attachments.end(), outAttachment));
}
} gl::popMatrices();
} mFBO.unbindFramebuffer();
return mFBO.getTexture(outAttachment);
}
}}
<commit_msg>add first pass at an ASCII visualization of a render tree<commit_after>//
// Pipeline.cpp
// Cinder-Pipeline
//
// Created by Jean-Pierre Mouilleseaux on 19 Apr 2014.
// Copyright 2014 Chorded Constructions. All rights reserved.
//
#include "Pipeline.h"
#include "cinder/Utilities.h"
using namespace ci;
namespace Cinder { namespace Pipeline {
PipelineRef Pipeline::create() {
return PipelineRef(new Pipeline())->shared_from_this();
}
Pipeline::Pipeline() {
}
Pipeline::~Pipeline() {
}
#pragma mark -
void Pipeline::setup(const Vec2i size) {
#if defined(DEBUG)
const char* renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
cinder::app::console() << "GL_RENDERER: " << renderer << std::endl;
const char* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
cinder::app::console() << "GL_VENDOR: " << vendor << std::endl;
const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
cinder::app::console() << "GL_VERSION: " << version << std::endl;
const char* shadingLanguageVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
cinder::app::console() << "GL_SHADING_LANGUAGE_VERSION: " << shadingLanguageVersion << std::endl;
std::string extensionsString = std::string(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
std::vector<std::string> extensions = split(extensionsString, " ");
extensions.erase(std::remove_if(extensions.begin(), extensions.end(), [](const std::string& s){ return s.empty(); }));
cinder::app::console() << "GL_EXTENSIONS: " << std::endl;
for (auto e : extensions) {
cinder::app::console() << " " << e << std::endl;
}
GLint dims[2];
glGetIntegerv(GL_MAX_VIEWPORT_DIMS, dims);
cinder::app::console() << "GL_MAX_VIEWPORT_DIMS: " << dims[0] << "x" << dims[1] << std::endl;
GLint texSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);
cinder::app::console() << "GL_MAX_TEXTURE_SIZE: " << texSize << std::endl;
glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &texSize);
cinder::app::console() << "GL_MAX_3D_TEXTURE_SIZE: " << texSize << std::endl;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texSize);
cinder::app::console() << "GL_MAX_TEXTURE_IMAGE_UNITS: " << texSize << std::endl;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &texSize);
cinder::app::console() << "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: " << texSize << std::endl;
glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &texSize);
cinder::app::console() << "GL_MAX_COLOR_ATTACHMENTS: " << texSize << std::endl;
cinder::app::console() << "-------------" << std::endl;
#endif
gl::Fbo::Format format;
format.enableColorBuffer(true, 3);
format.enableDepthBuffer(false);
// format.setWrap(GL_CLAMP, GL_CLAMP);
// format.setMagFilter(GL_NEAREST);
// format.setMinFilter(GL_LINEAR);
mFBO = gl::Fbo(size.x, size.y, format);
mFBO.bindFramebuffer(); {
const GLenum buffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
glDrawBuffers(3, buffers);
gl::setViewport(mFBO.getBounds());
gl::clear();
} mFBO.unbindFramebuffer();
// for (size_t idx = 0; idx < 3; ++idx) {
// mFBO.getTexture(idx).setWrap(GL_CLAMP, GL_CLAMP);
// }
}
gl::Texture& Pipeline::evaluate(const NodeRef& node) {
// build branch list
std::deque<std::deque<NodeRef>> branches;
std::deque<NodeRef> branch;
std::deque<NodeRef> stack;
NodeRef n = node;
while (n) {
branch.push_front(n);
// TODO - replace with RTTI to determine if n is a SourceNodeRef
if (n->getInputNodes().empty()) {
branches.push_front(branch);
branch = std::deque<NodeRef>();
if (stack.empty()) {
n = nullptr;
} else {
n = stack.front();
stack.pop_front();
}
} else {
if (n->getInputNodes().size() > 1) {
branches.push_front(branch);
branch = std::deque<NodeRef>();
stack.push_front(n->getInputNodes()[0]);
n = n->getInputNodes()[1];
} else {
n = n->getInputNodes()[0];
}
}
}
// ASCII visualization
cinder::app::console() << "" << std::endl;
unsigned int count = 0;
for (std::deque<NodeRef> branch : branches) {
if (branch.at(0)->getInputNodes().size() != 0) {
unsigned int spaceCount = count * 5 + count * 3;
cinder::app::console() << std::string(spaceCount, ' ');
}
for (NodeRef node : branch) {
if (node->getInputNodes().empty()) {
cinder::app::console() << "[SRC]";
} else {
cinder::app::console() << "[???]";
}
cinder::app::console() << " > ";
}
cinder::app::console() << std::endl;
if (count == 0 || branch.size() > count) {
count = branch.size();
} else if (branch.at(0)->getInputNodes().size() != 0) {
count += branch.size();
}
}
// render branches
unsigned int outAttachment = 0;
mFBO.bindFramebuffer(); {
gl::pushMatrices(); {
gl::setMatricesWindow(mFBO.getSize(), false);
std::vector<int> attachments = {0, 1, 2};
std::vector<int> storedAttachments;
for (std::deque<NodeRef> branch : branches) {
size_t attachmentIndex = 0;
outAttachment = attachments.at(attachmentIndex);
int inAttachment = -1;
int inAltAttachment = -1;
for (NodeRef n : branch) {
switch (n->getInputNodes().size()) {
case 0:
n->render(mFBO, outAttachment);
inAttachment = outAttachment;
break;
case 1:
attachmentIndex = (attachmentIndex + 1) % attachments.size();
outAttachment = attachments.at(attachmentIndex);
n->render(mFBO, inAttachment, mFBO, outAttachment);
inAttachment = outAttachment;
break;
case 2:
inAttachment = storedAttachments.at(0);
inAltAttachment = storedAttachments.at(1);
storedAttachments.clear();
attachments = {0, 1, 2};
attachmentIndex = outAttachment;
n->render(mFBO, inAttachment, mFBO, inAltAttachment, mFBO, outAttachment);
inAttachment = outAttachment;
break;
default:
break;
}
}
storedAttachments.push_back(outAttachment);
attachments.erase(std::find(attachments.begin(), attachments.end(), outAttachment));
}
} gl::popMatrices();
} mFBO.unbindFramebuffer();
return mFBO.getTexture(outAttachment);
}
}}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_INHERITANCE_090217_HPP
# define LUABIND_INHERITANCE_090217_HPP
# include <cassert>
# include <limits>
# include <map>
# include <memory>
# include <vector>
# include <luabind/typeid.hpp>
namespace luabind { namespace detail {
typedef void*(*cast_function)(void*);
typedef std::size_t class_id;
class_id const unknown_class = std::numeric_limits<class_id>::max();
class class_rep;
class LUABIND_API cast_graph
{
public:
cast_graph();
~cast_graph();
// `src` and `p` here describe the *most derived* object. This means that
// for a polymorphic type, the pointer must be cast with
// dynamic_cast<void*> before being passed in here, and `src` has to
// match typeid(*p).
std::pair<void*, std::size_t> cast(
void* p, class_id src, class_id target
, class_id dynamic_id, void const* dynamic_ptr) const;
void insert(class_id src, class_id target, cast_function cast);
private:
class impl;
std::auto_ptr<impl> m_impl;
};
// Maps a type_id to a class_id. Note that this actually partitions the
// id-space into two, using one half for "local" ids; ids that are used only as
// keys into the conversion cache. This is needed because we need a unique key
// even for types that hasn't been registered explicitly.
class class_id_map
{
public:
class_id_map();
class_id get(type_id const& type) const;
class_id get_local(type_id const& type);
void put(class_id id, type_id const& type);
private:
typedef std::map<type_id, class_id> map_type;
map_type m_classes;
class_id m_local_id;
static class_id const local_id_base;
};
inline class_id_map::class_id_map()
: m_local_id(local_id_base)
{}
inline class_id class_id_map::get(type_id const& type) const
{
map_type::const_iterator i = m_classes.find(type);
if (i == m_classes.end() || i->second >= local_id_base)
return unknown_class;
return i->second;
}
inline class_id class_id_map::get_local(type_id const& type)
{
std::pair<map_type::iterator, bool> result = m_classes.insert(
std::make_pair(type, 0));
if (result.second)
result.first->second = m_local_id++;
assert(m_local_id >= local_id_base);
return result.first->second;
}
inline void class_id_map::put(class_id id, type_id const& type)
{
assert(id < local_id_base);
std::pair<map_type::iterator, bool> result = m_classes.insert(
std::make_pair(type, 0));
assert(
result.second
|| result.first->second == id
|| result.first->second >= local_id_base
);
if (!result.second && result.first->second >= local_id_base)
{
--m_local_id;
}
result.first->second = id;
assert(m_local_id >= local_id_base);
}
class class_map
{
public:
class_rep* get(class_id id) const;
void put(class_id id, class_rep* cls);
private:
std::vector<class_rep*> m_classes;
};
inline class_rep* class_map::get(class_id id) const
{
if (id >= m_classes.size())
return 0;
return m_classes[id];
}
inline void class_map::put(class_id id, class_rep* cls)
{
if (id >= m_classes.size())
m_classes.resize(id + 1);
m_classes[id] = cls;
}
template <class S, class T>
struct static_cast_
{
static void* execute(void* p)
{
return static_cast<T*>(static_cast<S*>(p));
}
};
template <class S, class T>
struct dynamic_cast_
{
static void* execute(void* p)
{
return dynamic_cast<T*>(static_cast<S*>(p));
}
};
// Thread safe class_id allocation.
LUABIND_API class_id allocate_class_id();
template <class T>
struct registered_class
{
static class_id const id;
};
template <class T>
class_id const registered_class<T>::id = allocate_class_id();
template <class T>
struct registered_class<T const>
: registered_class<T>
{};
}} // namespace luabind::detail
#endif // LUABIND_INHERITANCE_090217_HPP
<commit_msg>Use boost::scoped_ptr<> for pimpl.<commit_after>// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LUABIND_INHERITANCE_090217_HPP
# define LUABIND_INHERITANCE_090217_HPP
# include <cassert>
# include <limits>
# include <map>
# include <memory>
# include <vector>
# include <luabind/typeid.hpp>
# include <boost/scoped_ptr.hpp>
namespace luabind { namespace detail {
typedef void*(*cast_function)(void*);
typedef std::size_t class_id;
class_id const unknown_class = std::numeric_limits<class_id>::max();
class class_rep;
class LUABIND_API cast_graph
{
public:
cast_graph();
~cast_graph();
// `src` and `p` here describe the *most derived* object. This means that
// for a polymorphic type, the pointer must be cast with
// dynamic_cast<void*> before being passed in here, and `src` has to
// match typeid(*p).
std::pair<void*, std::size_t> cast(
void* p, class_id src, class_id target
, class_id dynamic_id, void const* dynamic_ptr) const;
void insert(class_id src, class_id target, cast_function cast);
private:
class impl;
boost::scoped_ptr<impl> m_impl;
};
// Maps a type_id to a class_id. Note that this actually partitions the
// id-space into two, using one half for "local" ids; ids that are used only as
// keys into the conversion cache. This is needed because we need a unique key
// even for types that hasn't been registered explicitly.
class class_id_map
{
public:
class_id_map();
class_id get(type_id const& type) const;
class_id get_local(type_id const& type);
void put(class_id id, type_id const& type);
private:
typedef std::map<type_id, class_id> map_type;
map_type m_classes;
class_id m_local_id;
static class_id const local_id_base;
};
inline class_id_map::class_id_map()
: m_local_id(local_id_base)
{}
inline class_id class_id_map::get(type_id const& type) const
{
map_type::const_iterator i = m_classes.find(type);
if (i == m_classes.end() || i->second >= local_id_base)
return unknown_class;
return i->second;
}
inline class_id class_id_map::get_local(type_id const& type)
{
std::pair<map_type::iterator, bool> result = m_classes.insert(
std::make_pair(type, 0));
if (result.second)
result.first->second = m_local_id++;
assert(m_local_id >= local_id_base);
return result.first->second;
}
inline void class_id_map::put(class_id id, type_id const& type)
{
assert(id < local_id_base);
std::pair<map_type::iterator, bool> result = m_classes.insert(
std::make_pair(type, 0));
assert(
result.second
|| result.first->second == id
|| result.first->second >= local_id_base
);
if (!result.second && result.first->second >= local_id_base)
{
--m_local_id;
}
result.first->second = id;
assert(m_local_id >= local_id_base);
}
class class_map
{
public:
class_rep* get(class_id id) const;
void put(class_id id, class_rep* cls);
private:
std::vector<class_rep*> m_classes;
};
inline class_rep* class_map::get(class_id id) const
{
if (id >= m_classes.size())
return 0;
return m_classes[id];
}
inline void class_map::put(class_id id, class_rep* cls)
{
if (id >= m_classes.size())
m_classes.resize(id + 1);
m_classes[id] = cls;
}
template <class S, class T>
struct static_cast_
{
static void* execute(void* p)
{
return static_cast<T*>(static_cast<S*>(p));
}
};
template <class S, class T>
struct dynamic_cast_
{
static void* execute(void* p)
{
return dynamic_cast<T*>(static_cast<S*>(p));
}
};
// Thread safe class_id allocation.
LUABIND_API class_id allocate_class_id();
template <class T>
struct registered_class
{
static class_id const id;
};
template <class T>
class_id const registered_class<T>::id = allocate_class_id();
template <class T>
struct registered_class<T const>
: registered_class<T>
{};
}} // namespace luabind::detail
#endif // LUABIND_INHERITANCE_090217_HPP
<|endoftext|> |
<commit_before>/**
* @project zqrpc
* @file src/RpcServer.cc
* @author S Roychowdhury <sroycode @ gmail DOT com>
* @version 0.1
*
* @section LICENSE
*
* Copyright (c) 2014 S Roychowdhury
*
* 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.
*
* @section DESCRIPTION
*
* RpcServer.cc : Server Implemantation
*
*/
#include <boost/bind.hpp>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/common.h>
#include "zqrpc/RpcHeaders.hh"
#include "zqrpc/RpcServer.hh"
#include "zqrpc/RpcWorker.hh"
zqrpc::RpcServer::RpcServer(zmq::context_t* context,const char* suffix) :
context_(context),
use_inproc_workil( std::string(ZQRPC_INPROC_WORKIL)+std::string(suffix) ),
use_inproc_worker( std::string(ZQRPC_INPROC_WORKER)+std::string(suffix) ),
use_inproc_pcontrol( std::string(ZQRPC_INPROC_PCONTROL)+std::string(suffix) ),
rpc_frontend_(context_,ZMQ_ROUTER,"ROUTER"),
rpc_backend_(context_,ZMQ_DEALER,"DEALER"),
rpc_control_(context_,ZMQ_DEALER,"CONTROL"),
started_(0)
{
DLOG(INFO) << use_inproc_workil << std::endl;
DLOG(INFO) << use_inproc_worker << std::endl;
DLOG(INFO) << use_inproc_pcontrol << std::endl;
}
zqrpc::RpcServer::~RpcServer()
{
Close();
}
void zqrpc::RpcServer::EndPoint(const char* url)
{
rpc_bind_vec_.push_back(std::string(url));
}
void zqrpc::RpcServer::RegisterService(zqrpc::ServiceBase* service)
{
const google::protobuf::ServiceDescriptor *descriptor = service->GetDescriptor();
for (int i = 0; i < descriptor->method_count(); ++i) {
const google::protobuf::MethodDescriptor *method = descriptor->method(i);
const google::protobuf::Message *request = &service->GetRequestPrototype(method);
const google::protobuf::Message *response = &service->GetResponsePrototype(method);
RpcMethod *rpc_method = new RpcMethod(service, request, response, method);
std::string opcode=std::string(method->full_name());
// uint32_t opcode = ZQRPC_HASHFN(methodname.c_str(),methodname.length());
RpcMethodMapT::const_iterator iter = rpc_method_map_.find(opcode);
if (iter == rpc_method_map_.end())
rpc_method_map_[opcode] = rpc_method;
}
}
void zqrpc::RpcServer::RemoveService(zqrpc::ServiceBase* service)
{
const google::protobuf::ServiceDescriptor *descriptor = service->GetDescriptor();
for (int i = 0; i < descriptor->method_count(); ++i) {
const google::protobuf::MethodDescriptor *method = descriptor->method(i);
std::string opcode=std::string(method->full_name());
// uint32_t opcode = ZQRPC_HASHFN(methodname.c_str(),methodname.length());
RpcMethodMapT::iterator iter = rpc_method_map_.find(opcode);
if (iter != rpc_method_map_.end()) delete iter->second;
}
}
void zqrpc::RpcServer::Start(std::size_t noof_threads)
{
try {
for (RpcBindVecT::const_iterator it = rpc_bind_vec_.begin(); it!=rpc_bind_vec_.end(); ++it) {
rpc_frontend_.bind(it->c_str());
}
rpc_frontend_.bind(use_inproc_workil.c_str());
rpc_backend_.bind(use_inproc_worker.c_str());
rpc_control_.bind(use_inproc_pcontrol.c_str());
started_=true;
for(std::size_t i = 0; i < noof_threads; ++i) {
threads_.push_back( new boost::thread(zqrpc::RpcWorker(context_, rpc_method_map_)) );
}
ProxyStart();
DLOG(INFO) << "Loop Ended " << std::endl;
} catch(const ProxyException& e) {
DLOG(INFO) << "Proxy Exception: " << std::endl;
} catch(const zmq::error_t& e) {
DLOG(INFO) << "Start Exception: " << e.what() << std::endl;
}
}
void zqrpc::RpcServer::Close()
{
/**
// delete all methods
for (RpcMethodMapT::iterator it = rpc_method_map_.begin(); it != rpc_method_map_.end();) {
RpcMethod *rpc_method = it->second;
++it;
delete rpc_method;
}
*/
// unbind , inprocs cannot be unbound
if (started_) {
DLOG(INFO) << "server close called, started " << started_ << std::endl;
for (RpcBindVecT::iterator it = rpc_bind_vec_.begin(); it != rpc_bind_vec_.end(); ++it) {
rpc_frontend_.unbind((*it).c_str());
}
started_=false;
DLOG(INFO) << "stopping workers " << threads_.size() << std::endl;
WorkerStop( threads_.size() );
int jc=0;
DLOG(INFO) << "joining threads " << jc << std::endl;
for (zqrpc::RpcServer::ThreadPtrVecT::iterator it = threads_.begin();it!=threads_.end();) {
DLOG(INFO) << "joining threads " << ++jc << std::endl;
boost::thread* t = *it;
++it;
t->join();
}
DLOG(INFO) << "proxy terminate called" << std::endl;
ProxyStop();
DLOG(INFO) << "proxy terminated" << std::endl;
}
rpc_frontend_.close();
rpc_backend_.close();
rpc_control_.close();
}
void zqrpc::RpcServer::ProxyStart()
{
zmq::socket_t* frontend_ = &rpc_frontend_.socket_;
zmq::socket_t* backend_ = &rpc_backend_.socket_;
zmq::socket_t* control_ = &rpc_control_.socket_;
return zmq::proxy_steerable(*frontend_,*backend_,NULL,*control_);
}
void zqrpc::RpcServer::ProxyStop()
{
ZSocket rpc_c_(context_,ZMQ_DEALER,"TERMIN");
rpc_c_.connect(use_inproc_pcontrol.c_str());
rpc_c_.SendString("TERMINATE");
rpc_c_.disconnect(use_inproc_pcontrol.c_str());
rpc_c_.close();
}
void zqrpc::RpcServer::WorkerStop(std::size_t nos)
{
ZSocket rpc_c_(context_,ZMQ_DEALER,"WSTOP");
rpc_c_.connect(use_inproc_workil.c_str());
for (std::size_t i=0;i<nos;++i) {
rpc_c_.SendString("TERMINATE");
}
rpc_c_.disconnect(use_inproc_workil.c_str());
rpc_c_.close();
}
<commit_msg>Fri Dec 12 17:44:18 IST 2014<commit_after>/**
* @project zqrpc
* @file src/RpcServer.cc
* @author S Roychowdhury <sroycode @ gmail DOT com>
* @version 0.1
*
* @section LICENSE
*
* Copyright (c) 2014 S Roychowdhury
*
* 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.
*
* @section DESCRIPTION
*
* RpcServer.cc : Server Implemantation
*
*/
#include <boost/bind.hpp>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/common.h>
#include "zqrpc/RpcHeaders.hh"
#include "zqrpc/RpcServer.hh"
#include "zqrpc/RpcWorker.hh"
zqrpc::RpcServer::RpcServer(zmq::context_t* context,const char* suffix) :
context_(context),
use_inproc_workil( std::string(ZQRPC_INPROC_WORKIL)+std::string(suffix) ),
use_inproc_worker( std::string(ZQRPC_INPROC_WORKER)+std::string(suffix) ),
use_inproc_pcontrol( std::string(ZQRPC_INPROC_PCONTROL)+std::string(suffix) ),
rpc_frontend_(context_,ZMQ_ROUTER,"ROUTER"),
rpc_backend_(context_,ZMQ_DEALER,"DEALER"),
rpc_control_(context_,ZMQ_DEALER,"CONTROL"),
started_(0)
{
}
zqrpc::RpcServer::~RpcServer()
{
Close();
}
void zqrpc::RpcServer::EndPoint(const char* url)
{
rpc_bind_vec_.push_back(std::string(url));
}
void zqrpc::RpcServer::RegisterService(zqrpc::ServiceBase* service)
{
const google::protobuf::ServiceDescriptor *descriptor = service->GetDescriptor();
for (int i = 0; i < descriptor->method_count(); ++i) {
const google::protobuf::MethodDescriptor *method = descriptor->method(i);
const google::protobuf::Message *request = &service->GetRequestPrototype(method);
const google::protobuf::Message *response = &service->GetResponsePrototype(method);
RpcMethod *rpc_method = new RpcMethod(service, request, response, method);
std::string opcode=std::string(method->full_name());
// uint32_t opcode = ZQRPC_HASHFN(methodname.c_str(),methodname.length());
RpcMethodMapT::const_iterator iter = rpc_method_map_.find(opcode);
if (iter == rpc_method_map_.end())
rpc_method_map_[opcode] = rpc_method;
}
}
void zqrpc::RpcServer::RemoveService(zqrpc::ServiceBase* service)
{
const google::protobuf::ServiceDescriptor *descriptor = service->GetDescriptor();
for (int i = 0; i < descriptor->method_count(); ++i) {
const google::protobuf::MethodDescriptor *method = descriptor->method(i);
std::string opcode=std::string(method->full_name());
// uint32_t opcode = ZQRPC_HASHFN(methodname.c_str(),methodname.length());
RpcMethodMapT::iterator iter = rpc_method_map_.find(opcode);
if (iter != rpc_method_map_.end()) delete iter->second;
}
}
void zqrpc::RpcServer::Start(std::size_t noof_threads)
{
try {
for (RpcBindVecT::const_iterator it = rpc_bind_vec_.begin(); it!=rpc_bind_vec_.end(); ++it) {
rpc_frontend_.bind(it->c_str());
}
rpc_frontend_.bind(use_inproc_workil.c_str());
rpc_backend_.bind(use_inproc_worker.c_str());
rpc_control_.bind(use_inproc_pcontrol.c_str());
started_=true;
for(std::size_t i = 0; i < noof_threads; ++i) {
threads_.push_back( new boost::thread(zqrpc::RpcWorker(context_, rpc_method_map_)) );
}
ProxyStart();
DLOG(INFO) << "Loop Ended " << std::endl;
} catch(const ProxyException& e) {
DLOG(INFO) << "Proxy Exception: " << std::endl;
} catch(const zmq::error_t& e) {
DLOG(INFO) << "Start Exception: " << e.what() << std::endl;
}
}
void zqrpc::RpcServer::Close()
{
/**
// delete all methods
for (RpcMethodMapT::iterator it = rpc_method_map_.begin(); it != rpc_method_map_.end();) {
RpcMethod *rpc_method = it->second;
++it;
delete rpc_method;
}
*/
// unbind , inprocs cannot be unbound
if (started_) {
DLOG(INFO) << "server close called, started " << started_ << std::endl;
for (RpcBindVecT::iterator it = rpc_bind_vec_.begin(); it != rpc_bind_vec_.end(); ++it) {
rpc_frontend_.unbind((*it).c_str());
}
started_=false;
DLOG(INFO) << "stopping workers " << threads_.size() << std::endl;
WorkerStop( threads_.size() );
int jc=0;
DLOG(INFO) << "joining threads " << jc << std::endl;
for (zqrpc::RpcServer::ThreadPtrVecT::iterator it = threads_.begin();it!=threads_.end();) {
DLOG(INFO) << "joining threads " << ++jc << std::endl;
boost::thread* t = *it;
++it;
t->join();
}
DLOG(INFO) << "proxy terminate called" << std::endl;
ProxyStop();
DLOG(INFO) << "proxy terminated" << std::endl;
}
rpc_frontend_.close();
rpc_backend_.close();
rpc_control_.close();
}
void zqrpc::RpcServer::ProxyStart()
{
zmq::socket_t* frontend_ = &rpc_frontend_.socket_;
zmq::socket_t* backend_ = &rpc_backend_.socket_;
zmq::socket_t* control_ = &rpc_control_.socket_;
return zmq::proxy_steerable(*frontend_,*backend_,NULL,*control_);
}
void zqrpc::RpcServer::ProxyStop()
{
ZSocket rpc_c_(context_,ZMQ_DEALER,"TERMIN");
rpc_c_.connect(use_inproc_pcontrol.c_str());
rpc_c_.SendString("TERMINATE");
rpc_c_.disconnect(use_inproc_pcontrol.c_str());
rpc_c_.close();
}
void zqrpc::RpcServer::WorkerStop(std::size_t nos)
{
ZSocket rpc_c_(context_,ZMQ_DEALER,"WSTOP");
rpc_c_.connect(use_inproc_workil.c_str());
for (std::size_t i=0;i<nos;++i) {
rpc_c_.SendString("TERMINATE");
}
rpc_c_.disconnect(use_inproc_workil.c_str());
rpc_c_.close();
}
<|endoftext|> |
<commit_before>#include "Func.h"
#include "Function.h"
#include "IR.h"
#include "IRMutator.h"
#include "Schedule.h"
#include "Var.h"
namespace Halide {
LoopLevel::LoopLevel(Internal::IntrusivePtr<Internal::FunctionContents> f,
const std::string &var_name,
bool is_rvar)
: function_contents(f), var_name(var_name), is_rvar(is_rvar) {}
LoopLevel::LoopLevel(Internal::Function f, VarOrRVar v) : LoopLevel(f.get_contents(), v.name(), v.is_rvar) {}
LoopLevel::LoopLevel(Func f, VarOrRVar v) : LoopLevel(f.function().get_contents(), v.name(), v.is_rvar) {}
std::string LoopLevel::func_name() const {
if (function_contents.get() != nullptr) {
return Internal::Function(function_contents).name();
}
return "";
}
Func LoopLevel::func() const {
internal_assert(!is_inline() && !is_root());
internal_assert(function_contents.get() != nullptr);
return Func(Internal::Function(function_contents));
}
VarOrRVar LoopLevel::var() const {
internal_assert(!is_inline() && !is_root());
return VarOrRVar(var_name, is_rvar);
}
bool LoopLevel::is_inline() const {
return var_name.empty();
}
/*static*/
LoopLevel LoopLevel::root() {
return LoopLevel(nullptr, "__root", false);
}
bool LoopLevel::is_root() const {
return var_name == "__root";
}
std::string LoopLevel::to_string() const {
return (function_contents.get() ? Internal::Function(function_contents).name() : "") + "." + var_name;
}
bool LoopLevel::match(const std::string &loop) const {
return Internal::starts_with(loop, func_name() + ".") &&
Internal::ends_with(loop, "." + var_name);
}
bool LoopLevel::match(const LoopLevel &other) const {
// Must compare by name, not by pointer, since in() can make copies
// that we need to consider equivalent
return (func_name() == other.func_name() &&
(var_name == other.var_name ||
Internal::ends_with(var_name, "." + other.var_name) ||
Internal::ends_with(other.var_name, "." + var_name)));
}
bool LoopLevel::operator==(const LoopLevel &other) const {
// Must compare by name, not by pointer, since in() can make copies
// that we need to consider equivalent
return func_name() == other.func_name() && var_name == other.var_name;
}
namespace Internal {
typedef std::map<IntrusivePtr<FunctionContents>, IntrusivePtr<FunctionContents>> DeepCopyMap;
IntrusivePtr<FunctionContents> deep_copy_function_contents_helper(
const IntrusivePtr<FunctionContents> &src,
DeepCopyMap &copied_map);
/** A schedule for a halide function, which defines where, when, and
* how it should be evaluated. */
struct ScheduleContents {
mutable RefCount ref_count;
LoopLevel store_level, compute_level;
std::vector<ReductionVariable> rvars;
std::vector<Split> splits;
std::vector<Dim> dims;
std::vector<StorageDim> storage_dims;
std::vector<Bound> bounds;
std::map<std::string, IntrusivePtr<Internal::FunctionContents>> wrappers;
bool memoized;
bool touched;
bool allow_race_conditions;
ScheduleContents() : memoized(false), touched(false), allow_race_conditions(false) {};
// Pass an IRMutator through to all Exprs referenced in the ScheduleContents
void mutate(IRMutator *mutator) {
for (ReductionVariable &r : rvars) {
if (r.min.defined()) {
r.min = mutator->mutate(r.min);
}
if (r.extent.defined()) {
r.extent = mutator->mutate(r.extent);
}
}
for (Split &s : splits) {
if (s.factor.defined()) {
s.factor = mutator->mutate(s.factor);
}
}
for (Bound &b : bounds) {
if (b.min.defined()) {
b.min = mutator->mutate(b.min);
}
if (b.extent.defined()) {
b.extent = mutator->mutate(b.extent);
}
if (b.modulus.defined()) {
b.modulus = mutator->mutate(b.modulus);
}
if (b.remainder.defined()) {
b.remainder = mutator->mutate(b.remainder);
}
}
}
};
template<>
EXPORT RefCount &ref_count<ScheduleContents>(const ScheduleContents *p) {
return p->ref_count;
}
template<>
EXPORT void destroy<ScheduleContents>(const ScheduleContents *p) {
delete p;
}
Schedule::Schedule() : contents(new ScheduleContents) {}
Schedule Schedule::deep_copy(
std::map<IntrusivePtr<FunctionContents>, IntrusivePtr<FunctionContents>> &copied_map) const {
internal_assert(contents.defined()) << "Cannot deep-copy undefined Schedule\n";
Schedule copy;
copy.contents->store_level = contents->store_level;
copy.contents->compute_level = contents->compute_level;
copy.contents->rvars = contents->rvars;
copy.contents->splits = contents->splits;
copy.contents->dims = contents->dims;
copy.contents->storage_dims = contents->storage_dims;
copy.contents->bounds = contents->bounds;
copy.contents->memoized = contents->memoized;
copy.contents->touched = contents->touched;
copy.contents->allow_race_conditions = contents->allow_race_conditions;
// Deep-copy wrapper functions. If function has already been deep-copied before,
// i.e. it's in the 'copied_map', use the deep-copied version from the map instead
// of creating a new deep-copy
for (const auto &iter : contents->wrappers) {
IntrusivePtr<FunctionContents> &copied_func = copied_map[iter.second];
if (copied_func.defined()) {
copy.contents->wrappers[iter.first] = copied_func;
} else {
copy.contents->wrappers[iter.first] = deep_copy_function_contents_helper(iter.second, copied_map);
copied_map[iter.second] = copy.contents->wrappers[iter.first];
}
}
internal_assert(copy.contents->wrappers.size() == contents->wrappers.size());
return copy;
}
bool &Schedule::memoized() {
return contents->memoized;
}
bool Schedule::memoized() const {
return contents->memoized;
}
bool &Schedule::touched() {
return contents->touched;
}
bool Schedule::touched() const {
return contents->touched;
}
const std::vector<Split> &Schedule::splits() const {
return contents->splits;
}
std::vector<Split> &Schedule::splits() {
return contents->splits;
}
std::vector<Dim> &Schedule::dims() {
return contents->dims;
}
const std::vector<Dim> &Schedule::dims() const {
return contents->dims;
}
std::vector<StorageDim> &Schedule::storage_dims() {
return contents->storage_dims;
}
const std::vector<StorageDim> &Schedule::storage_dims() const {
return contents->storage_dims;
}
std::vector<Bound> &Schedule::bounds() {
return contents->bounds;
}
const std::vector<Bound> &Schedule::bounds() const {
return contents->bounds;
}
std::vector<ReductionVariable> &Schedule::rvars() {
return contents->rvars;
}
const std::vector<ReductionVariable> &Schedule::rvars() const {
return contents->rvars;
}
std::map<std::string, IntrusivePtr<Internal::FunctionContents>> &Schedule::wrappers() {
return contents->wrappers;
}
const std::map<std::string, IntrusivePtr<Internal::FunctionContents>> &Schedule::wrappers() const {
return contents->wrappers;
}
void Schedule::add_wrapper(const std::string &f,
const IntrusivePtr<Internal::FunctionContents> &wrapper) {
if (contents->wrappers.count(f)) {
if (f.empty()) {
user_warning << "Replacing previous definition of global wrapper in function \""
<< f << "\"\n";
} else {
internal_error << "Wrapper redefinition in function \"" << f << "\" is not allowed\n";
}
}
contents->wrappers[f] = wrapper;
}
LoopLevel &Schedule::store_level() {
return contents->store_level;
}
LoopLevel &Schedule::compute_level() {
return contents->compute_level;
}
const LoopLevel &Schedule::store_level() const {
return contents->store_level;
}
const LoopLevel &Schedule::compute_level() const {
return contents->compute_level;
}
bool &Schedule::allow_race_conditions() {
return contents->allow_race_conditions;
}
bool Schedule::allow_race_conditions() const {
return contents->allow_race_conditions;
}
void Schedule::accept(IRVisitor *visitor) const {
for (const ReductionVariable &r : rvars()) {
if (r.min.defined()) {
r.min.accept(visitor);
}
if (r.extent.defined()) {
r.extent.accept(visitor);
}
}
for (const Split &s : splits()) {
if (s.factor.defined()) {
s.factor.accept(visitor);
}
}
for (const Bound &b : bounds()) {
if (b.min.defined()) {
b.min.accept(visitor);
}
if (b.extent.defined()) {
b.extent.accept(visitor);
}
if (b.modulus.defined()) {
b.modulus.accept(visitor);
}
if (b.remainder.defined()) {
b.remainder.accept(visitor);
}
}
}
void Schedule::mutate(IRMutator *mutator) {
if (contents.defined()) {
contents->mutate(mutator);
}
}
} // namespace Internal
} // namespace Halide
<commit_msg>.get() -> .defined()<commit_after>#include "Func.h"
#include "Function.h"
#include "IR.h"
#include "IRMutator.h"
#include "Schedule.h"
#include "Var.h"
namespace Halide {
LoopLevel::LoopLevel(Internal::IntrusivePtr<Internal::FunctionContents> f,
const std::string &var_name,
bool is_rvar)
: function_contents(f), var_name(var_name), is_rvar(is_rvar) {}
LoopLevel::LoopLevel(Internal::Function f, VarOrRVar v) : LoopLevel(f.get_contents(), v.name(), v.is_rvar) {}
LoopLevel::LoopLevel(Func f, VarOrRVar v) : LoopLevel(f.function().get_contents(), v.name(), v.is_rvar) {}
std::string LoopLevel::func_name() const {
if (function_contents.defined()) {
return Internal::Function(function_contents).name();
}
return "";
}
Func LoopLevel::func() const {
internal_assert(!is_inline() && !is_root());
internal_assert(function_contents.defined());
return Func(Internal::Function(function_contents));
}
VarOrRVar LoopLevel::var() const {
internal_assert(!is_inline() && !is_root());
return VarOrRVar(var_name, is_rvar);
}
bool LoopLevel::is_inline() const {
return var_name.empty();
}
/*static*/
LoopLevel LoopLevel::root() {
return LoopLevel(nullptr, "__root", false);
}
bool LoopLevel::is_root() const {
return var_name == "__root";
}
std::string LoopLevel::to_string() const {
return (function_contents.defined() ? Internal::Function(function_contents).name() : "") + "." + var_name;
}
bool LoopLevel::match(const std::string &loop) const {
return Internal::starts_with(loop, func_name() + ".") &&
Internal::ends_with(loop, "." + var_name);
}
bool LoopLevel::match(const LoopLevel &other) const {
// Must compare by name, not by pointer, since in() can make copies
// that we need to consider equivalent
return (func_name() == other.func_name() &&
(var_name == other.var_name ||
Internal::ends_with(var_name, "." + other.var_name) ||
Internal::ends_with(other.var_name, "." + var_name)));
}
bool LoopLevel::operator==(const LoopLevel &other) const {
// Must compare by name, not by pointer, since in() can make copies
// that we need to consider equivalent
return func_name() == other.func_name() && var_name == other.var_name;
}
namespace Internal {
typedef std::map<IntrusivePtr<FunctionContents>, IntrusivePtr<FunctionContents>> DeepCopyMap;
IntrusivePtr<FunctionContents> deep_copy_function_contents_helper(
const IntrusivePtr<FunctionContents> &src,
DeepCopyMap &copied_map);
/** A schedule for a halide function, which defines where, when, and
* how it should be evaluated. */
struct ScheduleContents {
mutable RefCount ref_count;
LoopLevel store_level, compute_level;
std::vector<ReductionVariable> rvars;
std::vector<Split> splits;
std::vector<Dim> dims;
std::vector<StorageDim> storage_dims;
std::vector<Bound> bounds;
std::map<std::string, IntrusivePtr<Internal::FunctionContents>> wrappers;
bool memoized;
bool touched;
bool allow_race_conditions;
ScheduleContents() : memoized(false), touched(false), allow_race_conditions(false) {};
// Pass an IRMutator through to all Exprs referenced in the ScheduleContents
void mutate(IRMutator *mutator) {
for (ReductionVariable &r : rvars) {
if (r.min.defined()) {
r.min = mutator->mutate(r.min);
}
if (r.extent.defined()) {
r.extent = mutator->mutate(r.extent);
}
}
for (Split &s : splits) {
if (s.factor.defined()) {
s.factor = mutator->mutate(s.factor);
}
}
for (Bound &b : bounds) {
if (b.min.defined()) {
b.min = mutator->mutate(b.min);
}
if (b.extent.defined()) {
b.extent = mutator->mutate(b.extent);
}
if (b.modulus.defined()) {
b.modulus = mutator->mutate(b.modulus);
}
if (b.remainder.defined()) {
b.remainder = mutator->mutate(b.remainder);
}
}
}
};
template<>
EXPORT RefCount &ref_count<ScheduleContents>(const ScheduleContents *p) {
return p->ref_count;
}
template<>
EXPORT void destroy<ScheduleContents>(const ScheduleContents *p) {
delete p;
}
Schedule::Schedule() : contents(new ScheduleContents) {}
Schedule Schedule::deep_copy(
std::map<IntrusivePtr<FunctionContents>, IntrusivePtr<FunctionContents>> &copied_map) const {
internal_assert(contents.defined()) << "Cannot deep-copy undefined Schedule\n";
Schedule copy;
copy.contents->store_level = contents->store_level;
copy.contents->compute_level = contents->compute_level;
copy.contents->rvars = contents->rvars;
copy.contents->splits = contents->splits;
copy.contents->dims = contents->dims;
copy.contents->storage_dims = contents->storage_dims;
copy.contents->bounds = contents->bounds;
copy.contents->memoized = contents->memoized;
copy.contents->touched = contents->touched;
copy.contents->allow_race_conditions = contents->allow_race_conditions;
// Deep-copy wrapper functions. If function has already been deep-copied before,
// i.e. it's in the 'copied_map', use the deep-copied version from the map instead
// of creating a new deep-copy
for (const auto &iter : contents->wrappers) {
IntrusivePtr<FunctionContents> &copied_func = copied_map[iter.second];
if (copied_func.defined()) {
copy.contents->wrappers[iter.first] = copied_func;
} else {
copy.contents->wrappers[iter.first] = deep_copy_function_contents_helper(iter.second, copied_map);
copied_map[iter.second] = copy.contents->wrappers[iter.first];
}
}
internal_assert(copy.contents->wrappers.size() == contents->wrappers.size());
return copy;
}
bool &Schedule::memoized() {
return contents->memoized;
}
bool Schedule::memoized() const {
return contents->memoized;
}
bool &Schedule::touched() {
return contents->touched;
}
bool Schedule::touched() const {
return contents->touched;
}
const std::vector<Split> &Schedule::splits() const {
return contents->splits;
}
std::vector<Split> &Schedule::splits() {
return contents->splits;
}
std::vector<Dim> &Schedule::dims() {
return contents->dims;
}
const std::vector<Dim> &Schedule::dims() const {
return contents->dims;
}
std::vector<StorageDim> &Schedule::storage_dims() {
return contents->storage_dims;
}
const std::vector<StorageDim> &Schedule::storage_dims() const {
return contents->storage_dims;
}
std::vector<Bound> &Schedule::bounds() {
return contents->bounds;
}
const std::vector<Bound> &Schedule::bounds() const {
return contents->bounds;
}
std::vector<ReductionVariable> &Schedule::rvars() {
return contents->rvars;
}
const std::vector<ReductionVariable> &Schedule::rvars() const {
return contents->rvars;
}
std::map<std::string, IntrusivePtr<Internal::FunctionContents>> &Schedule::wrappers() {
return contents->wrappers;
}
const std::map<std::string, IntrusivePtr<Internal::FunctionContents>> &Schedule::wrappers() const {
return contents->wrappers;
}
void Schedule::add_wrapper(const std::string &f,
const IntrusivePtr<Internal::FunctionContents> &wrapper) {
if (contents->wrappers.count(f)) {
if (f.empty()) {
user_warning << "Replacing previous definition of global wrapper in function \""
<< f << "\"\n";
} else {
internal_error << "Wrapper redefinition in function \"" << f << "\" is not allowed\n";
}
}
contents->wrappers[f] = wrapper;
}
LoopLevel &Schedule::store_level() {
return contents->store_level;
}
LoopLevel &Schedule::compute_level() {
return contents->compute_level;
}
const LoopLevel &Schedule::store_level() const {
return contents->store_level;
}
const LoopLevel &Schedule::compute_level() const {
return contents->compute_level;
}
bool &Schedule::allow_race_conditions() {
return contents->allow_race_conditions;
}
bool Schedule::allow_race_conditions() const {
return contents->allow_race_conditions;
}
void Schedule::accept(IRVisitor *visitor) const {
for (const ReductionVariable &r : rvars()) {
if (r.min.defined()) {
r.min.accept(visitor);
}
if (r.extent.defined()) {
r.extent.accept(visitor);
}
}
for (const Split &s : splits()) {
if (s.factor.defined()) {
s.factor.accept(visitor);
}
}
for (const Bound &b : bounds()) {
if (b.min.defined()) {
b.min.accept(visitor);
}
if (b.extent.defined()) {
b.extent.accept(visitor);
}
if (b.modulus.defined()) {
b.modulus.accept(visitor);
}
if (b.remainder.defined()) {
b.remainder.accept(visitor);
}
}
}
void Schedule::mutate(IRMutator *mutator) {
if (contents.defined()) {
contents->mutate(mutator);
}
}
} // namespace Internal
} // namespace Halide
<|endoftext|> |
<commit_before>/* See Project CHIP LICENSE file for licensing information. */
#include <platform/logging/LogV.h>
#include <core/CHIPConfig.h>
#include <platform/CHIPDeviceConfig.h>
#include <src/lib/support/CodeUtils.h>
#include <support/logging/Constants.h>
#include <cstring>
#define K32W_LOG_MODULE_NAME chip
#define EOL_CHARS "\r\n" /* End of Line Characters */
#define EOL_CHARS_LEN 2 /* Length of EOL */
/* maximum value for uint32_t is 4294967295 - 10 bytes + 2 bytes for the brackets */
static constexpr uint8_t timestamp_max_len_bytes = 12;
/* one byte for the category + 2 bytes for the brackets */
static constexpr uint8_t category_max_len_bytes = 3;
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <openthread/platform/logging.h>
#include <utils/uart.h>
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD
static bool isLogInitialized;
extern uint8_t gOtLogUartInstance;
extern "C" void K32WWriteBlocking(const uint8_t * aBuf, uint32_t len);
extern "C" uint32_t otPlatAlarmMilliGetNow(void);
namespace chip {
namespace Logging {
namespace Platform {
void GetMessageString(char * buf, uint8_t bufLen, const char * module, uint8_t category)
{
int writtenLen = 0;
const char * categoryString;
/* bufLen must accommodate the length of the timestamp + length of the category +
* length of the module + 2 bytes for the module's brackets +
* 1 byte for the terminating character.
*/
assert(bufLen >= (timestamp_max_len_bytes + category_max_len_bytes + (strlen(module) + 2) + 1));
writtenLen = snprintf(buf, bufLen, "[%lu]", otPlatAlarmMilliGetNow());
bufLen -= writtenLen;
buf += writtenLen;
if (category != kLogCategory_None)
{
switch (category)
{
case kLogCategory_Error:
categoryString = "E";
break;
case kLogCategory_Progress:
categoryString = "P";
break;
case kLogCategory_Detail:
categoryString = "D";
break;
default:
categoryString = "U";
}
writtenLen = snprintf(buf, bufLen, "[%s]", categoryString);
bufLen -= writtenLen;
buf += writtenLen;
}
writtenLen = snprintf(buf + writtenLen, bufLen, "[%s]", module);
}
} // namespace Platform
} // namespace Logging
} // namespace chip
void FillPrefix(char * buf, uint8_t bufLen, const char * module, uint8_t category)
{
chip::Logging::Platform::GetMessageString(buf, bufLen, module, category);
}
namespace chip {
namespace DeviceLayer {
/**
* Called whenever a log message is emitted by CHIP or LwIP.
*
* This function is intended be overridden by the application to, e.g.,
* schedule output of queued log entries.
*/
void __attribute__((weak)) OnLogOutput(void) {}
} // namespace DeviceLayer
} // namespace chip
void GenericLog(const char * format, va_list arg, const char * module, uint8_t category)
{
#if K32W_LOG_ENABLED
char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - 1] = { 0 };
size_t prefixLen, writtenLen;
if (!isLogInitialized)
{
isLogInitialized = true;
gOtLogUartInstance = 0;
otPlatUartEnable();
}
/* Prefix is composed of [Time Reference][Debug String][Module Name String] */
FillPrefix(formattedMsg, CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - 1, module, category);
prefixLen = strlen(formattedMsg);
// Append the log message.
writtenLen = vsnprintf(formattedMsg + prefixLen, CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - prefixLen - EOL_CHARS_LEN, format, arg);
VerifyOrDie(writtenLen > 0);
memcpy(formattedMsg + prefixLen + writtenLen, EOL_CHARS, EOL_CHARS_LEN);
K32WWriteBlocking((const uint8_t *) formattedMsg, strlen(formattedMsg));
// Let the application know that a log message has been emitted.
chip::DeviceLayer::OnLogOutput();
#endif // K32W_LOG_ENABLED
}
namespace chip {
namespace Logging {
namespace Platform {
/**
* CHIP log output function.
*/
void LogV(const char * module, uint8_t category, const char * msg, va_list v)
{
(void) module;
(void) category;
#if K32W_LOG_ENABLED
GenericLog(msg, v, module, category);
// Let the application know that a log message has been emitted.
DeviceLayer::OnLogOutput();
#endif // K32W_LOG_ENABLED
}
} // namespace Platform
} // namespace Logging
} // namespace chip
#undef K32W_LOG_MODULE_NAME
#define K32W_LOG_MODULE_NAME lwip
/**
* LwIP log output function.
*/
extern "C" void LwIPLog(const char * msg, ...)
{
va_list v;
const char * module = "LWIP";
va_start(v, msg);
GenericLog(msg, v, module, chip::Logging::kLogCategory_None);
va_end(v);
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#undef K32W_LOG_MODULE_NAME
#define K32W_LOG_MODULE_NAME thread
extern "C" void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char * aFormat, ...)
{
va_list v;
const char * module = "OT";
(void) aLogLevel;
(void) aLogRegion;
va_start(v, aFormat);
GenericLog(aFormat, v, module, chip::Logging::kLogCategory_None);
va_end(v);
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD
<commit_msg>[K32W] Logging: Fix K32W buffer index (#8471)<commit_after>/* See Project CHIP LICENSE file for licensing information. */
#include <platform/logging/LogV.h>
#include <core/CHIPConfig.h>
#include <platform/CHIPDeviceConfig.h>
#include <src/lib/support/CodeUtils.h>
#include <support/logging/Constants.h>
#include <cstring>
#define K32W_LOG_MODULE_NAME chip
#define EOL_CHARS "\r\n" /* End of Line Characters */
#define EOL_CHARS_LEN 2 /* Length of EOL */
/* maximum value for uint32_t is 4294967295 - 10 bytes + 2 bytes for the brackets */
static constexpr uint8_t timestamp_max_len_bytes = 12;
/* one byte for the category + 2 bytes for the brackets */
static constexpr uint8_t category_max_len_bytes = 3;
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <openthread/platform/logging.h>
#include <utils/uart.h>
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD
static bool isLogInitialized;
extern uint8_t gOtLogUartInstance;
extern "C" void K32WWriteBlocking(const uint8_t * aBuf, uint32_t len);
extern "C" uint32_t otPlatAlarmMilliGetNow(void);
namespace chip {
namespace Logging {
namespace Platform {
void GetMessageString(char * buf, uint8_t bufLen, const char * module, uint8_t category)
{
int writtenLen = 0;
const char * categoryString;
/* bufLen must accommodate the length of the timestamp + length of the category +
* length of the module + 2 bytes for the module's brackets +
* 1 byte for the terminating character.
*/
assert(bufLen >= (timestamp_max_len_bytes + category_max_len_bytes + (strlen(module) + 2) + 1));
writtenLen = snprintf(buf, bufLen, "[%lu]", otPlatAlarmMilliGetNow());
bufLen -= writtenLen;
buf += writtenLen;
if (category != kLogCategory_None)
{
switch (category)
{
case kLogCategory_Error:
categoryString = "E";
break;
case kLogCategory_Progress:
categoryString = "P";
break;
case kLogCategory_Detail:
categoryString = "D";
break;
default:
categoryString = "U";
}
writtenLen = snprintf(buf, bufLen, "[%s]", categoryString);
bufLen -= writtenLen;
buf += writtenLen;
}
writtenLen = snprintf(buf, bufLen, "[%s]", module);
}
} // namespace Platform
} // namespace Logging
} // namespace chip
void FillPrefix(char * buf, uint8_t bufLen, const char * module, uint8_t category)
{
chip::Logging::Platform::GetMessageString(buf, bufLen, module, category);
}
namespace chip {
namespace DeviceLayer {
/**
* Called whenever a log message is emitted by CHIP or LwIP.
*
* This function is intended be overridden by the application to, e.g.,
* schedule output of queued log entries.
*/
void __attribute__((weak)) OnLogOutput(void) {}
} // namespace DeviceLayer
} // namespace chip
void GenericLog(const char * format, va_list arg, const char * module, uint8_t category)
{
#if K32W_LOG_ENABLED
char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - 1] = { 0 };
size_t prefixLen, writtenLen;
if (!isLogInitialized)
{
isLogInitialized = true;
gOtLogUartInstance = 0;
otPlatUartEnable();
}
/* Prefix is composed of [Time Reference][Debug String][Module Name String] */
FillPrefix(formattedMsg, CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - 1, module, category);
prefixLen = strlen(formattedMsg);
// Append the log message.
writtenLen = vsnprintf(formattedMsg + prefixLen, CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE - prefixLen - EOL_CHARS_LEN, format, arg);
VerifyOrDie(writtenLen > 0);
memcpy(formattedMsg + prefixLen + writtenLen, EOL_CHARS, EOL_CHARS_LEN);
K32WWriteBlocking((const uint8_t *) formattedMsg, strlen(formattedMsg));
// Let the application know that a log message has been emitted.
chip::DeviceLayer::OnLogOutput();
#endif // K32W_LOG_ENABLED
}
namespace chip {
namespace Logging {
namespace Platform {
/**
* CHIP log output function.
*/
void LogV(const char * module, uint8_t category, const char * msg, va_list v)
{
(void) module;
(void) category;
#if K32W_LOG_ENABLED
GenericLog(msg, v, module, category);
// Let the application know that a log message has been emitted.
DeviceLayer::OnLogOutput();
#endif // K32W_LOG_ENABLED
}
} // namespace Platform
} // namespace Logging
} // namespace chip
#undef K32W_LOG_MODULE_NAME
#define K32W_LOG_MODULE_NAME lwip
/**
* LwIP log output function.
*/
extern "C" void LwIPLog(const char * msg, ...)
{
va_list v;
const char * module = "LWIP";
va_start(v, msg);
GenericLog(msg, v, module, chip::Logging::kLogCategory_None);
va_end(v);
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#undef K32W_LOG_MODULE_NAME
#define K32W_LOG_MODULE_NAME thread
extern "C" void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char * aFormat, ...)
{
va_list v;
const char * module = "OT";
(void) aLogLevel;
(void) aLogRegion;
va_start(v, aFormat);
GenericLog(aFormat, v, module, chip::Logging::kLogCategory_None);
va_end(v);
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD
<|endoftext|> |
<commit_before>/**
* File : Atomic.cpp
* Author : Emir Uner
* Summary : Atomic increment/decrement implementations for Linux.
*/
/**
* This file is part of XCOM.
*
* Copyright (C) 2003 Emir Uner
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <xcom/Integral.hpp>
#include <asm/atomic.h>
extern "C"
xcom::Int xcomInterlockedIncrement(xcom::Int* num)
{
xcom::Int newVal = *num + 1;
atomic_inc(reinterpret_cast<atomic_t*>(num));
return newVal;
}
extern "C"
xcom::Int xcomInterlockedDecrement(xcom::Int* num)
{
xcom::Int newVal = *num - 1;
atomic_dec(reinterpret_cast<atomic_t*>(num));
return newVal;
}
<commit_msg>fixed atomic inc/dec for linux platform. Using c++ intrinsics<commit_after>/**
* File : Atomic.cpp
* Author : Emir Uner
* Summary : Atomic increment/decrement implementations for Linux.
*/
/**
* This file is part of XCOM.
*
* Copyright (C) 2003 Emir Uner
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <xcom/Integral.hpp>
extern "C"
xcom::Int xcomInterlockedIncrement(xcom::Int* num)
{
xcom::Int newVal = *num + 1;
__atomic_fetch_add(num, 1, __ATOMIC_SEQ_CST);
return newVal;
}
extern "C"
xcom::Int xcomInterlockedDecrement(xcom::Int* num)
{
xcom::Int newVal = *num - 1;
__atomic_fetch_add(num, -1, __ATOMIC_SEQ_CST);
return newVal;
}
<|endoftext|> |
<commit_before>#include <string.h>
#include "lpc17xx_pinsel.h"
#include "lpc17xx_uart.h"
#include "interface/uart.h"
#include "pipeline.h"
#include "atcommander.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "util/timer.h"
#include "gpio.h"
// Only UART1 supports hardware flow control, so this has to be UART1
#define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1
#define UART_STATUS_PORT 0
#define UART_STATUS_PIN 18
#ifdef BLUEBOARD
#define UART1_FUNCNUM 2
#define UART1_PORTNUM 2
#define UART1_TX_PINNUM 0
#define UART1_RX_PINNUM 1
#define UART1_FLOW_PORTNUM UART1_PORTNUM
#define UART1_FLOW_FUNCNUM UART1_FUNCNUM
#define UART1_CTS1_PINNUM 2
#define UART1_RTS1_PINNUM 7
#else
// Ford OpenXC CAN Translator Prototype
#define UART1_FUNCNUM 1
#define UART1_PORTNUM 0
#define UART1_TX_PINNUM 15
#define UART1_RX_PINNUM 16
#define UART1_FLOW_PORTNUM 2
#define UART1_FLOW_FUNCNUM 2
#define UART1_RTS1_PINNUM 2
#define UART1_CTS1_PINNUM 7
#endif
namespace gpio = openxc::gpio;
using openxc::util::time::delayMs;
using openxc::pipeline::Pipeline;
using openxc::util::bytebuffer::processQueue;
using openxc::gpio::GpioValue;
using openxc::gpio::GpioDirection;
extern const AtCommanderPlatform AT_PLATFORM_RN42;
extern Pipeline pipeline;
__IO int32_t RTS_STATE;
__IO FlagStatus TRANSMIT_INTERRUPT_STATUS;
/* Disable request to send through RTS line. We cannot handle any more data
* right now.
*/
void pauseReceive() {
if(RTS_STATE == ACTIVE) {
// Disable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE);
RTS_STATE = INACTIVE;
}
}
/* Enable request to send through RTS line. We can handle more data now. */
void resumeReceive() {
if (RTS_STATE == INACTIVE) {
// Enable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE);
RTS_STATE = ACTIVE;
}
}
void disableTransmitInterrupt() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE);
}
void enableTransmitInterrupt() {
TRANSMIT_INTERRUPT_STATUS = SET;
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE);
}
void handleReceiveInterrupt() {
while(!QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
uint8_t byte;
uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING);
if(received > 0) {
QUEUE_PUSH(uint8_t, &pipeline.uart->receiveQueue, byte);
if(QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
pauseReceive();
}
} else {
break;
}
}
}
void handleTransmitInterrupt() {
disableTransmitInterrupt();
while(UART_CheckBusy(UART1_DEVICE) == SET);
while(!QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
uint8_t byte = QUEUE_PEEK(uint8_t, &pipeline.uart->sendQueue);
if(UART_Send(UART1_DEVICE, &byte, 1, NONE_BLOCKING)) {
QUEUE_POP(uint8_t, &pipeline.uart->sendQueue);
} else {
break;
}
}
if(QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
disableTransmitInterrupt();
TRANSMIT_INTERRUPT_STATUS = RESET;
} else {
enableTransmitInterrupt();
}
}
extern "C" {
void UART1_IRQHandler() {
uint32_t interruptSource = UART_GetIntId(UART1_DEVICE)
& UART_IIR_INTID_MASK;
switch(interruptSource) {
case UART1_IIR_INTID_MODEM: {
// Check Modem status
uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1);
// Check CTS status change flag
if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) {
// if CTS status is active, continue to send data
if (modemStatus & UART1_MODEM_STAT_CTS) {
UART_TxCmd(UART1_DEVICE, ENABLE);
} else {
// Otherwise, Stop current transmission immediately
UART_TxCmd(UART1_DEVICE, DISABLE);
}
}
break;
}
case UART_IIR_INTID_RDA:
case UART_IIR_INTID_CTI:
handleReceiveInterrupt();
break;
case UART_IIR_INTID_THRE:
handleTransmitInterrupt();
break;
default:
break;
}
}
}
void openxc::interface::uart::read(UartDevice* device, bool (*callback)(uint8_t*)) {
if(device != NULL) {
if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) {
processQueue(&device->receiveQueue, callback);
if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) {
resumeReceive();
}
}
}
}
/* Auto flow control does work, but it turns the uart write functions into
* blocking functions, which drags USB down. Instead we handle it manually so we
* can make them asynchronous and let USB run at full speed.
*/
void configureFlowControl() {
if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) {
// Enable UART Transmit
UART_TxCmd(UART1_DEVICE, ENABLE);
}
// Enable Modem status interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE);
// Enable CTS1 signal transition interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE);
resumeReceive();
}
void configureUartPins() {
PINSEL_CFG_Type PinCfg;
PinCfg.Funcnum = UART1_FUNCNUM;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = UART1_PORTNUM;
PinCfg.Pinnum = UART1_TX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = UART1_FLOW_PORTNUM;
PinCfg.Funcnum = UART1_FLOW_FUNCNUM;
PinCfg.Pinnum = UART1_CTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
}
void configureFifo() {
UART_FIFO_CFG_Type fifoConfig;
UART_FIFOConfigStructInit(&fifoConfig);
UART_FIFOConfig(UART1_DEVICE, &fifoConfig);
}
void configureUart(int baud) {
UART_CFG_Type UARTConfigStruct;
UART_ConfigStructInit(&UARTConfigStruct);
UARTConfigStruct.Baud_rate = baud;
UART_Init(UART1_DEVICE, &UARTConfigStruct);
}
void configureInterrupts() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE);
enableTransmitInterrupt();
/* preemption = 1, sub-priority = 1 */
NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01));
NVIC_EnableIRQ(UART1_IRQn);
}
void writeByte(uint8_t byte) {
UART_SendByte(UART1_DEVICE, byte);
}
int readByte() {
if(!QUEUE_EMPTY(uint8_t, &pipeline.uart->receiveQueue)) {
return QUEUE_POP(uint8_t, &pipeline.uart->receiveQueue);
}
return -1;
}
// TODO this is stupid, fix the at-commander API
void delay(long unsigned int delayInMs) {
delayMs(delayInMs);
}
void openxc::interface::uart::initialize(UartDevice* device) {
if(device == NULL) {
debug("Can't initialize a NULL UartDevice");
return;
}
initializeCommon(device);
configureUartPins();
configureUart(BAUD_RATE);
configureFifo();
configureFlowControl();
configureInterrupts();
TRANSMIT_INTERRUPT_STATUS = RESET;
// Configure P0.18 as an input, pulldown
LPC_PINCON->PINMODE1 |= (1 << 5);
// Ensure BT reset line is held high.
LPC_GPIO1->FIODIR |= (1 << 17);
debug("Done.");
gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN,
GpioDirection::GPIO_DIRECTION_INPUT);
AtCommanderConfig config = {AT_PLATFORM_RN42};
config.baud_rate_initializer = configureUart;
config.write_function = writeByte;
config.read_function = readByte;
config.delay_function = delay;
config.log_function = NULL;
delayMs(1000);
if(at_commander_set_baud(&config, BAUD_RATE)) {
at_commander_reboot(&config);
} else {
debug("Unable to set baud rate of attached UART device");
}
debug("Done.");
}
void openxc::interface::uart::processSendQueue(UartDevice* device) {
if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) {
if(TRANSMIT_INTERRUPT_STATUS == RESET) {
handleTransmitInterrupt();
} else {
enableTransmitInterrupt();
}
}
}
bool openxc::interface::uart::connected(UartDevice* device) {
return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN)
!= GpioValue::GPIO_VALUE_LOW;
}
<commit_msg>Add debugging when setting baud rate on LPC17xx.<commit_after>#include <string.h>
#include "lpc17xx_pinsel.h"
#include "lpc17xx_uart.h"
#include "interface/uart.h"
#include "pipeline.h"
#include "atcommander.h"
#include "util/bytebuffer.h"
#include "util/log.h"
#include "util/timer.h"
#include "gpio.h"
// Only UART1 supports hardware flow control, so this has to be UART1
#define UART1_DEVICE (LPC_UART_TypeDef*)LPC_UART1
#define UART_STATUS_PORT 0
#define UART_STATUS_PIN 18
#ifdef BLUEBOARD
#define UART1_FUNCNUM 2
#define UART1_PORTNUM 2
#define UART1_TX_PINNUM 0
#define UART1_RX_PINNUM 1
#define UART1_FLOW_PORTNUM UART1_PORTNUM
#define UART1_FLOW_FUNCNUM UART1_FUNCNUM
#define UART1_CTS1_PINNUM 2
#define UART1_RTS1_PINNUM 7
#else
// Ford OpenXC CAN Translator Prototype
#define UART1_FUNCNUM 1
#define UART1_PORTNUM 0
#define UART1_TX_PINNUM 15
#define UART1_RX_PINNUM 16
#define UART1_FLOW_PORTNUM 2
#define UART1_FLOW_FUNCNUM 2
#define UART1_RTS1_PINNUM 2
#define UART1_CTS1_PINNUM 7
#endif
namespace gpio = openxc::gpio;
using openxc::util::time::delayMs;
using openxc::util::log::debugNoNewline;
using openxc::pipeline::Pipeline;
using openxc::util::bytebuffer::processQueue;
using openxc::gpio::GpioValue;
using openxc::gpio::GpioDirection;
extern const AtCommanderPlatform AT_PLATFORM_RN42;
extern Pipeline pipeline;
__IO int32_t RTS_STATE;
__IO FlagStatus TRANSMIT_INTERRUPT_STATUS;
/* Disable request to send through RTS line. We cannot handle any more data
* right now.
*/
void pauseReceive() {
if(RTS_STATE == ACTIVE) {
// Disable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, INACTIVE);
RTS_STATE = INACTIVE;
}
}
/* Enable request to send through RTS line. We can handle more data now. */
void resumeReceive() {
if (RTS_STATE == INACTIVE) {
// Enable request to send through RTS line
UART_FullModemForcePinState(LPC_UART1, UART1_MODEM_PIN_RTS, ACTIVE);
RTS_STATE = ACTIVE;
}
}
void disableTransmitInterrupt() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, DISABLE);
}
void enableTransmitInterrupt() {
TRANSMIT_INTERRUPT_STATUS = SET;
UART_IntConfig(UART1_DEVICE, UART_INTCFG_THRE, ENABLE);
}
void handleReceiveInterrupt() {
while(!QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
uint8_t byte;
uint32_t received = UART_Receive(UART1_DEVICE, &byte, 1, NONE_BLOCKING);
if(received > 0) {
QUEUE_PUSH(uint8_t, &pipeline.uart->receiveQueue, byte);
if(QUEUE_FULL(uint8_t, &pipeline.uart->receiveQueue)) {
pauseReceive();
}
} else {
break;
}
}
}
void handleTransmitInterrupt() {
disableTransmitInterrupt();
while(UART_CheckBusy(UART1_DEVICE) == SET);
while(!QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
uint8_t byte = QUEUE_PEEK(uint8_t, &pipeline.uart->sendQueue);
if(UART_Send(UART1_DEVICE, &byte, 1, NONE_BLOCKING)) {
QUEUE_POP(uint8_t, &pipeline.uart->sendQueue);
} else {
break;
}
}
if(QUEUE_EMPTY(uint8_t, &pipeline.uart->sendQueue)) {
disableTransmitInterrupt();
TRANSMIT_INTERRUPT_STATUS = RESET;
} else {
enableTransmitInterrupt();
}
}
extern "C" {
void UART1_IRQHandler() {
uint32_t interruptSource = UART_GetIntId(UART1_DEVICE)
& UART_IIR_INTID_MASK;
switch(interruptSource) {
case UART1_IIR_INTID_MODEM: {
// Check Modem status
uint8_t modemStatus = UART_FullModemGetStatus(LPC_UART1);
// Check CTS status change flag
if (modemStatus & UART1_MODEM_STAT_DELTA_CTS) {
// if CTS status is active, continue to send data
if (modemStatus & UART1_MODEM_STAT_CTS) {
UART_TxCmd(UART1_DEVICE, ENABLE);
} else {
// Otherwise, Stop current transmission immediately
UART_TxCmd(UART1_DEVICE, DISABLE);
}
}
break;
}
case UART_IIR_INTID_RDA:
case UART_IIR_INTID_CTI:
handleReceiveInterrupt();
break;
case UART_IIR_INTID_THRE:
handleTransmitInterrupt();
break;
default:
break;
}
}
}
void openxc::interface::uart::read(UartDevice* device, bool (*callback)(uint8_t*)) {
if(device != NULL) {
if(!QUEUE_EMPTY(uint8_t, &device->receiveQueue)) {
processQueue(&device->receiveQueue, callback);
if(!QUEUE_FULL(uint8_t, &device->receiveQueue)) {
resumeReceive();
}
}
}
}
/* Auto flow control does work, but it turns the uart write functions into
* blocking functions, which drags USB down. Instead we handle it manually so we
* can make them asynchronous and let USB run at full speed.
*/
void configureFlowControl() {
if (UART_FullModemGetStatus(LPC_UART1) & UART1_MODEM_STAT_CTS) {
// Enable UART Transmit
UART_TxCmd(UART1_DEVICE, ENABLE);
}
// Enable Modem status interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_MS, ENABLE);
// Enable CTS1 signal transition interrupt
UART_IntConfig(UART1_DEVICE, UART1_INTCFG_CTS, ENABLE);
resumeReceive();
}
void configureUartPins() {
PINSEL_CFG_Type PinCfg;
PinCfg.Funcnum = UART1_FUNCNUM;
PinCfg.OpenDrain = 0;
PinCfg.Pinmode = 0;
PinCfg.Portnum = UART1_PORTNUM;
PinCfg.Pinnum = UART1_TX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RX_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Portnum = UART1_FLOW_PORTNUM;
PinCfg.Funcnum = UART1_FLOW_FUNCNUM;
PinCfg.Pinnum = UART1_CTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
PinCfg.Pinnum = UART1_RTS1_PINNUM;
PINSEL_ConfigPin(&PinCfg);
}
void configureFifo() {
UART_FIFO_CFG_Type fifoConfig;
UART_FIFOConfigStructInit(&fifoConfig);
UART_FIFOConfig(UART1_DEVICE, &fifoConfig);
}
void configureUart(int baud) {
UART_CFG_Type UARTConfigStruct;
UART_ConfigStructInit(&UARTConfigStruct);
UARTConfigStruct.Baud_rate = baud;
UART_Init(UART1_DEVICE, &UARTConfigStruct);
}
void configureInterrupts() {
UART_IntConfig(UART1_DEVICE, UART_INTCFG_RBR, ENABLE);
enableTransmitInterrupt();
/* preemption = 1, sub-priority = 1 */
NVIC_SetPriority(UART1_IRQn, ((0x01<<3)|0x01));
NVIC_EnableIRQ(UART1_IRQn);
}
void writeByte(uint8_t byte) {
UART_SendByte(UART1_DEVICE, byte);
}
int readByte() {
if(!QUEUE_EMPTY(uint8_t, &pipeline.uart->receiveQueue)) {
return QUEUE_POP(uint8_t, &pipeline.uart->receiveQueue);
}
return -1;
}
// TODO this is stupid, fix the at-commander API
void delay(long unsigned int delayInMs) {
delayMs(delayInMs);
}
void openxc::interface::uart::initialize(UartDevice* device) {
if(device == NULL) {
debug("Can't initialize a NULL UartDevice");
return;
}
initializeCommon(device);
configureUartPins();
configureUart(BAUD_RATE);
configureFifo();
configureFlowControl();
configureInterrupts();
TRANSMIT_INTERRUPT_STATUS = RESET;
// Configure P0.18 as an input, pulldown
LPC_PINCON->PINMODE1 |= (1 << 5);
// Ensure BT reset line is held high.
LPC_GPIO1->FIODIR |= (1 << 17);
debug("Done.");
gpio::setDirection(UART_STATUS_PORT, UART_STATUS_PIN,
GpioDirection::GPIO_DIRECTION_INPUT);
AtCommanderConfig config = {AT_PLATFORM_RN42};
config.baud_rate_initializer = configureUart;
config.write_function = writeByte;
config.read_function = readByte;
config.delay_function = delay;
config.log_function = debugNoNewline;
delayMs(1000);
if(at_commander_set_baud(&config, BAUD_RATE)) {
debug("Successfully set baud rate");
at_commander_reboot(&config);
} else {
debug("Unable to set baud rate of attached UART device");
}
debug("Done.");
}
void openxc::interface::uart::processSendQueue(UartDevice* device) {
if(!QUEUE_EMPTY(uint8_t, &device->sendQueue)) {
if(TRANSMIT_INTERRUPT_STATUS == RESET) {
handleTransmitInterrupt();
} else {
enableTransmitInterrupt();
}
}
}
bool openxc::interface::uart::connected(UartDevice* device) {
return device != NULL && gpio::getValue(UART_STATUS_PORT, UART_STATUS_PIN)
!= GpioValue::GPIO_VALUE_LOW;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// Plugin manager
//==============================================================================
#include "plugin.h"
#include "pluginmanager.h"
//==============================================================================
#include <QCoreApplication>
#include <QDir>
//==============================================================================
namespace OpenCOR {
//==============================================================================
PluginManager::PluginManager(QCoreApplication *pApp, const bool &pGuiMode) :
mPlugins(Plugins()),
mLoadedPlugins(Plugins()),
mCorePlugin(0)
{
// Retrieve OpenCOR's plugins directory
// Note: the plugin's directory is set in main()...
mPluginsDir = QCoreApplication::libraryPaths().first()+QDir::separator()+pApp->applicationName();
// Retrieve the list of plugins available for loading
QFileInfoList fileInfoList = QDir(mPluginsDir).entryInfoList(QStringList("*"+PluginExtension),
QDir::Files);
QStringList fileNames = QStringList();
foreach (const QFileInfo &file, fileInfoList)
fileNames << QDir::toNativeSeparators(file.canonicalFilePath());
// Determine which plugins, if any, are needed by others and which, if any,
// are selectable
QMap<QString, PluginInfo *> pluginsInfo = QMap<QString, PluginInfo *>();
QMap<QString, QString> pluginsError = QMap<QString, QString>();
QStringList neededPlugins = QStringList();
QStringList wantedPlugins = QStringList();
foreach (const QString &fileName, fileNames) {
QString pluginError;
PluginInfo *pluginInfo = Plugin::info(fileName, pluginError);
// Note: if there is some plugin information, then it will get owned by
// the plugin itself. So, it's the plugin's responsibility to
// delete it (see Plugin::~Plugin())...
QString pluginName = Plugin::name(fileName);
pluginsInfo.insert(pluginName, pluginInfo);
pluginsError.insert(pluginName, pluginError);
if (pluginInfo) {
// Keep track of the plugin's full dependencies
QStringList pluginFullDependencies = Plugin::fullDependencies(mPluginsDir, pluginName);
pluginInfo->setFullDependencies(pluginFullDependencies);
// Keep track of the plugin itself, should it be selectable and
// requested by the user (if we are in GUI mode) or have CLI support
// (if we are in CLI mode)
if ( ( pGuiMode && pluginInfo->isSelectable() && Plugin::load(pluginName))
|| (!pGuiMode && pluginInfo->hasCliSupport())) {
// Keep track of the plugin's dependencies
neededPlugins << pluginsInfo.value(pluginName)->fullDependencies();
// Also keep track of the plugin itself
wantedPlugins << pluginName;
}
}
}
// Remove possible duplicates in our list of needed plugins
neededPlugins.removeDuplicates();
// We now have all our needed and wanted plugins with our needed plugins
// nicely sorted based on their dependencies with one another. So, retrieve
// their file name
QStringList plugins = neededPlugins+wantedPlugins;
QStringList pluginFileNames = QStringList();
plugins.removeDuplicates();
// Note: we shouldn't have to remove duplicates, but better be safe than
// sorry (indeed, a selectable plugin may be (wrongly) needed by
// another plugin)...
foreach (const QString &plugin, plugins)
pluginFileNames << Plugin::fileName(mPluginsDir, plugin);
// If we are in GUI mode, then we want to know about all the plugins,
// including the ones that are not to be loaded (so that we can refer to
// them, in the plugins window, as either not wanted or not needed)
if (pGuiMode) {
pluginFileNames << fileNames;
pluginFileNames.removeDuplicates();
}
// Deal with all the plugins we need and want
foreach (const QString &pluginFileName, pluginFileNames) {
QString pluginName = Plugin::name(pluginFileName);
Plugin *plugin = new Plugin(pluginFileName, pluginsInfo.value(pluginName),
pluginsError.value(pluginName),
plugins.contains(pluginName), this);
// Keep track of the Core plugin, if it's the one we are dealing with,
// as well as keep track of the plugin in general
if (!pluginName.compare(CorePluginName))
mCorePlugin = plugin;
mPlugins << plugin;
if (plugin->status() == Plugin::Loaded)
mLoadedPlugins << plugin;
}
}
//==============================================================================
PluginManager::~PluginManager()
{
// Delete all of the plugins
foreach (Plugin *plugin, mPlugins)
delete plugin;
}
//==============================================================================
Plugins PluginManager::plugins() const
{
// Return a list of all our plugins, whether loaded
return mPlugins;
}
//==============================================================================
Plugins PluginManager::loadedPlugins() const
{
// Return a list of our loaded plugins
return mLoadedPlugins;
}
//==============================================================================
QString PluginManager::pluginsDir() const
{
// Return the plugins directory
return mPluginsDir;
}
//==============================================================================
Plugin * PluginManager::plugin(const QString &pName) const
{
// Return the plugin which name is the one we have been passed
foreach (Plugin *plugin, mPlugins)
if (!pName.compare(plugin->name()))
// This is the plugin we are after, so...
return plugin;
// The plugin we are after wasn't found, so...
return 0;
}
//==============================================================================
Plugin * PluginManager::corePlugin() const
{
// Return our Core plugin
return mCorePlugin;
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Fixed the issue with some plugin selections crashing OpenCOR on restarting (closes #439).<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// Plugin manager
//==============================================================================
#include "plugin.h"
#include "pluginmanager.h"
//==============================================================================
#include <QCoreApplication>
#include <QDir>
//==============================================================================
namespace OpenCOR {
//==============================================================================
PluginManager::PluginManager(QCoreApplication *pApp, const bool &pGuiMode) :
mPlugins(Plugins()),
mLoadedPlugins(Plugins()),
mCorePlugin(0)
{
// Retrieve OpenCOR's plugins directory
// Note: the plugin's directory is set in main()...
mPluginsDir = QCoreApplication::libraryPaths().first()+QDir::separator()+pApp->applicationName();
// Retrieve the list of plugins available for loading
QFileInfoList fileInfoList = QDir(mPluginsDir).entryInfoList(QStringList("*"+PluginExtension),
QDir::Files);
QStringList fileNames = QStringList();
foreach (const QFileInfo &file, fileInfoList)
fileNames << QDir::toNativeSeparators(file.canonicalFilePath());
// Determine which plugins, if any, are needed by others and which, if any,
// are selectable
QMap<QString, PluginInfo *> pluginsInfo = QMap<QString, PluginInfo *>();
QMap<QString, QString> pluginsError = QMap<QString, QString>();
QStringList neededPlugins = QStringList();
QStringList wantedPlugins = QStringList();
foreach (const QString &fileName, fileNames) {
QString pluginError;
PluginInfo *pluginInfo = Plugin::info(fileName, pluginError);
// Note: if there is some plugin information, then it will get owned by
// the plugin itself. So, it's the plugin's responsibility to
// delete it (see Plugin::~Plugin())...
QString pluginName = Plugin::name(fileName);
pluginsInfo.insert(pluginName, pluginInfo);
pluginsError.insert(pluginName, pluginError);
if (pluginInfo) {
// Keep track of the plugin's full dependencies
QStringList pluginFullDependencies = Plugin::fullDependencies(mPluginsDir, pluginName);
pluginInfo->setFullDependencies(pluginFullDependencies);
// Keep track of the plugin itself, should it be selectable and
// requested by the user (if we are in GUI mode) or have CLI support
// (if we are in CLI mode)
if ( ( pGuiMode && pluginInfo->isSelectable() && Plugin::load(pluginName))
|| (!pGuiMode && pluginInfo->hasCliSupport())) {
// Keep track of the plugin's dependencies
neededPlugins << pluginsInfo.value(pluginName)->fullDependencies();
// Also keep track of the plugin itself
wantedPlugins << pluginName;
}
}
}
// Remove possible duplicates in our list of needed plugins
neededPlugins.removeDuplicates();
// We now have all our needed and wanted plugins with our needed plugins
// nicely sorted based on their dependencies with one another. So, retrieve
// their file name
QStringList plugins = neededPlugins+wantedPlugins;
QStringList pluginFileNames = QStringList();
plugins.removeDuplicates();
// Note: we shouldn't have to remove duplicates, but better be safe than
// sorry (indeed, a selectable plugin may be (wrongly) needed by
// another plugin)...
foreach (const QString &plugin, plugins)
pluginFileNames << Plugin::fileName(mPluginsDir, plugin);
// If we are in GUI mode, then we want to know about all the plugins,
// including the ones that are not to be loaded (so that we can refer to
// them, in the plugins window, as either not wanted or not needed)
if (pGuiMode) {
pluginFileNames << fileNames;
pluginFileNames.removeDuplicates();
}
// Deal with all the plugins we need and want
foreach (const QString &pluginFileName, pluginFileNames) {
QString pluginName = Plugin::name(pluginFileName);
Plugin *plugin = new Plugin(pluginFileName, pluginsInfo.value(pluginName),
pluginsError.value(pluginName),
plugins.contains(pluginName), this);
// Keep track of the plugin and of the Core plugin, in particular, if it
// is loaded
mPlugins << plugin;
if (plugin->status() == Plugin::Loaded) {
mLoadedPlugins << plugin;
if (!pluginName.compare(CorePluginName))
mCorePlugin = plugin;
}
}
}
//==============================================================================
PluginManager::~PluginManager()
{
// Delete all of the plugins
foreach (Plugin *plugin, mPlugins)
delete plugin;
}
//==============================================================================
Plugins PluginManager::plugins() const
{
// Return a list of all our plugins, whether loaded
return mPlugins;
}
//==============================================================================
Plugins PluginManager::loadedPlugins() const
{
// Return a list of our loaded plugins
return mLoadedPlugins;
}
//==============================================================================
QString PluginManager::pluginsDir() const
{
// Return the plugins directory
return mPluginsDir;
}
//==============================================================================
Plugin * PluginManager::plugin(const QString &pName) const
{
// Return the plugin which name is the one we have been passed
foreach (Plugin *plugin, mPlugins)
if (!pName.compare(plugin->name()))
// This is the plugin we are after, so...
return plugin;
// The plugin we are after wasn't found, so...
return 0;
}
//==============================================================================
Plugin * PluginManager::corePlugin() const
{
// Return our Core plugin
return mCorePlugin;
}
//==============================================================================
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
int read_message(stream_socket& s, char* buffer)
{
using namespace libtorrent::detail;
error_code ec;
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return -1;
}
char* ptr = buffer;
int length = read_int32(ptr);
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return -1;
}
return length;
}
void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer)
{
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa"; // peer-id
error_code ec;
std::memcpy(handshake + 28, ih.begin(), 20);
std::generate(handshake + 48, handshake + 68, &rand);
libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE HANDSHAKE: %s\n", ec.message().c_str());
return;
}
}
void send_interested(stream_socket& s)
{
char msg[] = "\0\0\0\x01\x02";
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND INTERESTED: %s\n", ec.message().c_str());
return;
}
}
void send_request(stream_socket& s, int piece, int block)
{
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* ptr = msg + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, sizeof(msg)-1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
}
// makes sure that pieces that are allowed and then
// rejected aren't requested again
void requester_thread(torrent_info const* ti, tcp::endpoint const* ep, io_service* ios)
{
sha1_hash const& ih = ti->info_hash();
stream_socket s(*ios);
error_code ec;
s.connect(*ep, ec);
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char recv_buffer[16 * 1024 + 1000];
do_handshake(s, ih, recv_buffer);
send_interested(s);
// build a list of all pieces and request them all!
std::vector<int> pieces(ti->num_pieces());
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
int block = 0;
int blocks_per_piece = ti->piece_length() / 16 / 1024;
int outstanding_reqs = 0;
while (true)
{
while (outstanding_reqs < 16)
{
send_request(s, pieces.back(), block++);
++outstanding_reqs;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
if (pieces.empty())
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
}
int length = read_message(s, recv_buffer);
if (length == -1) return;
int msg = recv_buffer[0];
if (msg == 7) --outstanding_reqs;
}
}
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<thread*> threads;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
threads.push_back(new thread(boost::bind(&requester_thread, &ti, &ep, &ios)));
libtorrent::sleep(10);
}
for (int i = 0; i < num_connections; ++i)
{
threads.back()->join();
delete threads.back();
threads.pop_back();
}
return 0;
}
<commit_msg>make connection_tester run in a single thread<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih)
: s(ios)
, read_pos(0)
, state(handshaking)
, pieces(num_pieces)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
{
// build a list of all pieces and request them all!
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
}
stream_socket s;
char buffer[17*1024];
int read_pos;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
void on_connect(error_code const& ec)
{
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
boost::asio::async_write(s, libtorrent::asio::buffer(h, sizeof(handshake) - 1)
, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
{
free(h);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
boost::asio::async_read(s, libtorrent::asio::buffer(buffer, 68)
, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
return;
}
work();
}
void write_request()
{
if (pieces.empty()) return;
int piece = pieces.back();
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++block;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
}
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
{
free(m);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
++outstanding_requests;
work();
}
void work()
{
if (pieces.empty() && outstanding_requests == 0)
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
// send requests
if (outstanding_requests < 20 && !pieces.empty())
{
write_request();
return;
}
// read message
boost::asio::async_read(s, asio::buffer(buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
return;
}
boost::asio::async_read(s, asio::buffer(buffer, length)
, boost::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
int msg = read_uint8(ptr);
if (msg == 7) --outstanding_requests;
work();
}
};
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<peer_conn*> conns;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0]));
libtorrent::sleep(1);
}
ios.run();
return 0;
}
<|endoftext|> |
<commit_before>#ifdef INTERFACE_DEFINITION
#define PURE = 0
#else
#define PURE
#endif
virtual Mode viewMode() const PURE;
virtual QStringList viewMimeTypes() const PURE;
virtual QString viewDefaultFileExtension() const PURE;
virtual bool showBusyWidget(const QString &pFileName) PURE;
virtual bool hasViewWidget(const QString &pFileName) PURE;
virtual QWidget * viewWidget(const QString &pFileName) PURE;
virtual void removeViewWidget(const QString &pFileName) PURE;
virtual QString viewName() const PURE;
virtual QIcon fileTabIcon(const QString &pFileName) const PURE;
#undef PURE
<commit_msg>Single Cell view + SED-ML: some work towards supporting the import of a basic simulation from SED-ML (#825) [ci skip].<commit_after>#ifdef INTERFACE_DEFINITION
#define PURE = 0
#else
#define PURE
#endif
virtual Mode viewMode() const PURE;
virtual QStringList viewMimeTypes() const PURE;
virtual QString viewDefaultFileExtension() const PURE;
virtual bool showBusyWidget(const QString &pFileName) PURE;
// Note: this method is called by the central widget to determine whether it
// should be showing its busy widget before calling viewWidget() for
// the given file name. The central widget will automatically show its
// busy widget if the file is a remote one, but in the case of a local
// SED-ML file or a local COMBINE archive, it cannot tell whether it
// should show its busy widget since it depends on the referenced
// model, i.e. whether it references a local model or a remote one.
// So, since the central widget has no knowledge of file types, we
// need to ask the plugin to tell us what to do...
virtual bool hasViewWidget(const QString &pFileName) PURE;
virtual QWidget * viewWidget(const QString &pFileName) PURE;
virtual void removeViewWidget(const QString &pFileName) PURE;
virtual QString viewName() const PURE;
virtual QIcon fileTabIcon(const QString &pFileName) const PURE;
#undef PURE
<|endoftext|> |
<commit_before>// If possible disable interrupts whilst switching pin direction. Sadly
// there is no generic Arduino function to read the current interrupt
// status, only to enable and disable interrupts. As a result the
// protection against spurious signals on the I2C bus is only available
// for AVR architectures where ATOMIC_BLOCK is defined.
#if defined(ARDUINO_ARCH_AVR)
#include <util/atomic.h>
#endif
#include <SoftWire.h>
// Force SDA low
void SoftWire::sdaLow(const SoftWire *p)
{
uint8_t sda = p->getSda();
#ifdef ATOMIC_BLOCK
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#endif
{
digitalWrite(sda, LOW);
pinMode(sda, OUTPUT);
}
}
// Release SDA to float high
void SoftWire::sdaHigh(const SoftWire *p)
{
pinMode(p->getSda(), p->getInputMode());
}
// Force SCL low
void SoftWire::sclLow(const SoftWire *p)
{
uint8_t scl = p->getScl();
#ifdef ATOMIC_BLOCK
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#endif
{
digitalWrite(scl, LOW);
pinMode(scl, OUTPUT);
}
}
// Release SCL to float high
void SoftWire::sclHigh(const SoftWire *p)
{
pinMode(p->getScl(), p->getInputMode());
}
// Read SDA (for data read)
uint8_t SoftWire::readSda(const SoftWire *p)
{
return digitalRead(p->getSda());
}
// Read SCL (to detect clock-stretching)
uint8_t SoftWire::readScl(const SoftWire *p)
{
return digitalRead(p->getScl());
}
// For testing the CRC-8 calculator may be useful:
// http://smbus.org/faq/crc8Applet.htm
uint8_t SoftWire::crc8_update(uint8_t crc, uint8_t data)
{
const uint16_t polynomial = 0x107;
crc ^= data;
for (uint8_t i = 8; i; --i) {
if (crc & 0x80)
crc = (uint16_t(crc) << 1) ^ polynomial;
else
crc <<= 1;
}
return crc;
}
SoftWire::SoftWire(uint8_t sda, uint8_t scl) :
_sda(sda),
_scl(scl),
_inputMode(INPUT), // Pullups disabled by default
_delay_us(defaultDelay_us),
_timeout_ms(defaultTimeout_ms),
_rxBuffer(NULL),
_rxBufferSize(0),
_rxBufferIndex(0),
_rxBufferBytesRead(0),
_txAddress(8), // First non-reserved address
_txBuffer(NULL),
_txBufferSize(0),
_txBufferIndex(0),
_sdaLow(sdaLow),
_sdaHigh(sdaHigh),
_sclLow(sclLow),
_sclHigh(sclHigh),
_readSda(readSda),
_readScl(readScl)
{
;
}
void SoftWire::begin(void) const
{
/*
// Release SDA and SCL
_sdaHigh(this);
delayMicroseconds(_delay_us);
_sclHigh(this);
*/
stop();
}
SoftWire::result_t SoftWire::stop(void) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
return ack;
}
SoftWire::result_t SoftWire::llStart(uint8_t rawAddr) const
{
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
return llWrite(rawAddr);
}
SoftWire::result_t SoftWire::llRepeatedStart(uint8_t rawAddr) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
return llWrite(rawAddr);
}
SoftWire::result_t SoftWire::llStartWait(uint8_t rawAddr) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
while (!timeout.isExpired()) {
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
switch (llWrite(rawAddr)) {
case ack:
return ack;
case nack:
stop();
default:
// timeout, and anything else we don't know about
stop();
return timedOut;
}
}
return timedOut;
}
SoftWire::result_t SoftWire::llWrite(uint8_t data) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
for (uint8_t i = 8; i; --i) {
// Force SCL low
_sclLow(this);
if (data & 0x80) {
// Release SDA
_sdaHigh(this);
}
else {
// Force SDA low
_sdaLow(this);
}
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
data <<= 1;
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
}
// Get ACK
// Force SCL low
_sclLow(this);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
result_t res = (_readSda(this) == LOW ? ack : nack);
delayMicroseconds(_delay_us);
// Keep SCL low between bytes
_sclLow(this);
return res;
}
SoftWire::result_t SoftWire::llRead(uint8_t &data, bool sendAck) const
{
data = 0;
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
for (uint8_t i = 8; i; --i) {
data <<= 1;
// Force SCL low
_sclLow(this);
// Release SDA (from previous ACK)
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Read clock stretch
while (_readScl(this) == LOW)
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
if (_readSda(this))
data |= 1;
}
// Put ACK/NACK
// Force SCL low
_sclLow(this);
if (sendAck) {
// Force SDA low
_sdaLow(this);
}
else {
// Release SDA
_sdaHigh(this);
}
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Wait for SCL to return high
while (_readScl(this) == LOW)
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
delayMicroseconds(_delay_us);
// Keep SCL low between bytes
_sclLow(this);
return ack;
}
int SoftWire::available(void)
{
return _rxBufferBytesRead - _rxBufferIndex;
}
size_t SoftWire::write(uint8_t data)
{
if (_txBufferIndex >= _txBufferSize) {
setWriteError();
return 0;
}
_txBuffer[_txBufferIndex++] = data;
return 1;
}
// Unlike the Wire version this function returns the actual amount of data written into the buffer
size_t SoftWire::write(const uint8_t *data, size_t quantity)
{
size_t r = 0;
for (size_t i = 0; i < quantity; ++i) {
r += write(data[i]);
}
return r;
}
int SoftWire::read(void)
{
if (_rxBufferIndex < _rxBufferBytesRead)
return _rxBuffer[++_rxBufferIndex];
else
return -1;
}
int SoftWire::peek(void)
{
if (_rxBufferIndex < _rxBufferBytesRead)
return _rxBuffer[_rxBufferIndex];
else
return -1;
}
// Restore pins to inputs, with no pullups
void SoftWire::end(void)
{
enablePullups(false);
_sdaHigh(this);
_sclHigh(this);
}
void SoftWire::setClock(uint32_t frequency)
{
uint32_t period_us = uint32_t(1000000UL) / frequency;
if (period_us < 2)
period_us = 2;
else if (period_us > 2 * 255)
period_us = 2* 255;
setDelay_us(period_us / 2);
}
void SoftWire::beginTransmission(uint8_t address)
{
_txAddress = address;
_txBufferIndex = 0;
}
uint8_t SoftWire::endTransmission(uint8_t sendStop)
{
uint8_t r = endTransmissionInner();
if (sendStop)
stop();
return r;
}
uint8_t SoftWire::endTransmissionInner(void) const
{
// TODO: Consider repeated start conditions
result_t r = start(_txAddress, writeMode);
if (r == nack)
return 2;
else if (r == timedOut)
return 4;
for (uint8_t i = 0; i < _txBufferIndex; ++i) {
r = llWrite(_txBuffer[i]);
if (r == nack)
return 3;
else if (r == timedOut)
return 4;
}
return 0;
}
uint8_t SoftWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
_rxBufferIndex = 0;
_rxBufferBytesRead = 0;
if (start(address, readMode) == 0) {
for (uint8_t i = 0; i < quantity; ++i) {
if (i >= _rxBufferSize)
break; // Don't write beyond buffer
result_t res = llRead(_rxBuffer[i], i != (quantity - 1));
if (res != ack)
break;
++_rxBufferBytesRead;
}
}
if (sendStop)
stop();
return _rxBufferBytesRead;
}
<commit_msg>Bgufix for read()<commit_after>// If possible disable interrupts whilst switching pin direction. Sadly
// there is no generic Arduino function to read the current interrupt
// status, only to enable and disable interrupts. As a result the
// protection against spurious signals on the I2C bus is only available
// for AVR architectures where ATOMIC_BLOCK is defined.
#if defined(ARDUINO_ARCH_AVR)
#include <util/atomic.h>
#endif
#include <SoftWire.h>
// Force SDA low
void SoftWire::sdaLow(const SoftWire *p)
{
uint8_t sda = p->getSda();
#ifdef ATOMIC_BLOCK
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#endif
{
digitalWrite(sda, LOW);
pinMode(sda, OUTPUT);
}
}
// Release SDA to float high
void SoftWire::sdaHigh(const SoftWire *p)
{
pinMode(p->getSda(), p->getInputMode());
}
// Force SCL low
void SoftWire::sclLow(const SoftWire *p)
{
uint8_t scl = p->getScl();
#ifdef ATOMIC_BLOCK
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#endif
{
digitalWrite(scl, LOW);
pinMode(scl, OUTPUT);
}
}
// Release SCL to float high
void SoftWire::sclHigh(const SoftWire *p)
{
pinMode(p->getScl(), p->getInputMode());
}
// Read SDA (for data read)
uint8_t SoftWire::readSda(const SoftWire *p)
{
return digitalRead(p->getSda());
}
// Read SCL (to detect clock-stretching)
uint8_t SoftWire::readScl(const SoftWire *p)
{
return digitalRead(p->getScl());
}
// For testing the CRC-8 calculator may be useful:
// http://smbus.org/faq/crc8Applet.htm
uint8_t SoftWire::crc8_update(uint8_t crc, uint8_t data)
{
const uint16_t polynomial = 0x107;
crc ^= data;
for (uint8_t i = 8; i; --i) {
if (crc & 0x80)
crc = (uint16_t(crc) << 1) ^ polynomial;
else
crc <<= 1;
}
return crc;
}
SoftWire::SoftWire(uint8_t sda, uint8_t scl) :
_sda(sda),
_scl(scl),
_inputMode(INPUT), // Pullups disabled by default
_delay_us(defaultDelay_us),
_timeout_ms(defaultTimeout_ms),
_rxBuffer(NULL),
_rxBufferSize(0),
_rxBufferIndex(0),
_rxBufferBytesRead(0),
_txAddress(8), // First non-reserved address
_txBuffer(NULL),
_txBufferSize(0),
_txBufferIndex(0),
_sdaLow(sdaLow),
_sdaHigh(sdaHigh),
_sclLow(sclLow),
_sclHigh(sclHigh),
_readSda(readSda),
_readScl(readScl)
{
;
}
void SoftWire::begin(void) const
{
/*
// Release SDA and SCL
_sdaHigh(this);
delayMicroseconds(_delay_us);
_sclHigh(this);
*/
stop();
}
SoftWire::result_t SoftWire::stop(void) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
return ack;
}
SoftWire::result_t SoftWire::llStart(uint8_t rawAddr) const
{
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
return llWrite(rawAddr);
}
SoftWire::result_t SoftWire::llRepeatedStart(uint8_t rawAddr) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
// Force SCL low
_sclLow(this);
delayMicroseconds(_delay_us);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
return llWrite(rawAddr);
}
SoftWire::result_t SoftWire::llStartWait(uint8_t rawAddr) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
while (!timeout.isExpired()) {
// Force SDA low
_sdaLow(this);
delayMicroseconds(_delay_us);
switch (llWrite(rawAddr)) {
case ack:
return ack;
case nack:
stop();
default:
// timeout, and anything else we don't know about
stop();
return timedOut;
}
}
return timedOut;
}
SoftWire::result_t SoftWire::llWrite(uint8_t data) const
{
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
for (uint8_t i = 8; i; --i) {
// Force SCL low
_sclLow(this);
if (data & 0x80) {
// Release SDA
_sdaHigh(this);
}
else {
// Force SDA low
_sdaLow(this);
}
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
data <<= 1;
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
}
// Get ACK
// Force SCL low
_sclLow(this);
// Release SDA
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
result_t res = (_readSda(this) == LOW ? ack : nack);
delayMicroseconds(_delay_us);
// Keep SCL low between bytes
_sclLow(this);
return res;
}
SoftWire::result_t SoftWire::llRead(uint8_t &data, bool sendAck) const
{
data = 0;
AsyncDelay timeout(_timeout_ms, AsyncDelay::MILLIS);
for (uint8_t i = 8; i; --i) {
data <<= 1;
// Force SCL low
_sclLow(this);
// Release SDA (from previous ACK)
_sdaHigh(this);
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Read clock stretch
while (_readScl(this) == LOW)
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
if (_readSda(this))
data |= 1;
}
// Put ACK/NACK
// Force SCL low
_sclLow(this);
if (sendAck) {
// Force SDA low
_sdaLow(this);
}
else {
// Release SDA
_sdaHigh(this);
}
delayMicroseconds(_delay_us);
// Release SCL
if (!sclHighAndStretch(timeout))
return timedOut;
delayMicroseconds(_delay_us);
// Wait for SCL to return high
while (_readScl(this) == LOW)
if (timeout.isExpired()) {
stop(); // Reset bus
return timedOut;
}
delayMicroseconds(_delay_us);
// Keep SCL low between bytes
_sclLow(this);
return ack;
}
int SoftWire::available(void)
{
return _rxBufferBytesRead - _rxBufferIndex;
}
size_t SoftWire::write(uint8_t data)
{
if (_txBufferIndex >= _txBufferSize) {
setWriteError();
return 0;
}
_txBuffer[_txBufferIndex++] = data;
return 1;
}
// Unlike the Wire version this function returns the actual amount of data written into the buffer
size_t SoftWire::write(const uint8_t *data, size_t quantity)
{
size_t r = 0;
for (size_t i = 0; i < quantity; ++i) {
r += write(data[i]);
}
return r;
}
int SoftWire::read(void)
{
if (_rxBufferIndex < _rxBufferBytesRead)
return _rxBuffer[_rxBufferIndex++];
else
return -1;
}
int SoftWire::peek(void)
{
if (_rxBufferIndex < _rxBufferBytesRead)
return _rxBuffer[_rxBufferIndex];
else
return -1;
}
// Restore pins to inputs, with no pullups
void SoftWire::end(void)
{
enablePullups(false);
_sdaHigh(this);
_sclHigh(this);
}
void SoftWire::setClock(uint32_t frequency)
{
uint32_t period_us = uint32_t(1000000UL) / frequency;
if (period_us < 2)
period_us = 2;
else if (period_us > 2 * 255)
period_us = 2* 255;
setDelay_us(period_us / 2);
}
void SoftWire::beginTransmission(uint8_t address)
{
_txAddress = address;
_txBufferIndex = 0;
}
uint8_t SoftWire::endTransmission(uint8_t sendStop)
{
uint8_t r = endTransmissionInner();
if (sendStop)
stop();
return r;
}
uint8_t SoftWire::endTransmissionInner(void) const
{
// TODO: Consider repeated start conditions
result_t r = start(_txAddress, writeMode);
if (r == nack)
return 2;
else if (r == timedOut)
return 4;
for (uint8_t i = 0; i < _txBufferIndex; ++i) {
r = llWrite(_txBuffer[i]);
if (r == nack)
return 3;
else if (r == timedOut)
return 4;
}
return 0;
}
uint8_t SoftWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
_rxBufferIndex = 0;
_rxBufferBytesRead = 0;
if (start(address, readMode) == 0) {
for (uint8_t i = 0; i < quantity; ++i) {
if (i >= _rxBufferSize)
break; // Don't write beyond buffer
result_t res = llRead(_rxBuffer[i], i != (quantity - 1));
if (res != ack)
break;
++_rxBufferBytesRead;
}
}
if (sendStop)
stop();
return _rxBufferBytesRead;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
int read_message(stream_socket& s, char* buffer)
{
using namespace libtorrent::detail;
error_code ec;
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return -1;
}
char* ptr = buffer;
int length = read_int32(ptr);
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return -1;
}
return length;
}
void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer)
{
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa"; // peer-id
error_code ec;
std::memcpy(handshake + 28, ih.begin(), 20);
std::generate(handshake + 48, handshake + 68, &rand);
libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR RECEIVE HANDSHAKE: %s\n", ec.message().c_str());
return;
}
}
void send_interested(stream_socket& s)
{
char msg[] = "\0\0\0\x01\x02";
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND INTERESTED: %s\n", ec.message().c_str());
return;
}
}
void send_request(stream_socket& s, int piece, int block)
{
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* ptr = msg + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
libtorrent::asio::write(s, libtorrent::asio::buffer(msg, sizeof(msg)-1)
, libtorrent::asio::transfer_all(), ec);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
}
// makes sure that pieces that are allowed and then
// rejected aren't requested again
void requester_thread(torrent_info const* ti, tcp::endpoint const* ep, io_service* ios)
{
sha1_hash const& ih = ti->info_hash();
stream_socket s(*ios);
error_code ec;
s.connect(*ep, ec);
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char recv_buffer[16 * 1024 + 1000];
do_handshake(s, ih, recv_buffer);
send_interested(s);
// build a list of all pieces and request them all!
std::vector<int> pieces(ti->num_pieces());
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
int block = 0;
int blocks_per_piece = ti->piece_length() / 16 / 1024;
int outstanding_reqs = 0;
while (true)
{
while (outstanding_reqs < 16)
{
send_request(s, pieces.back(), block++);
++outstanding_reqs;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
if (pieces.empty())
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
}
int length = read_message(s, recv_buffer);
if (length == -1) return;
int msg = recv_buffer[0];
if (msg == 7) --outstanding_reqs;
}
}
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<thread*> threads;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
threads.push_back(new thread(boost::bind(&requester_thread, &ti, &ep, &ios)));
libtorrent::sleep(10);
}
for (int i = 0; i < num_connections; ++i)
{
threads.back()->join();
delete threads.back();
threads.pop_back();
}
return 0;
}
<commit_msg>make connection_tester run in a single thread<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih)
: s(ios)
, read_pos(0)
, state(handshaking)
, pieces(num_pieces)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
{
// build a list of all pieces and request them all!
for (int i = 0; i < pieces.size(); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
}
stream_socket s;
char buffer[17*1024];
int read_pos;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
void on_connect(error_code const& ec)
{
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
boost::asio::async_write(s, libtorrent::asio::buffer(h, sizeof(handshake) - 1)
, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
{
free(h);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
boost::asio::async_read(s, libtorrent::asio::buffer(buffer, 68)
, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
return;
}
work();
}
void write_request()
{
if (pieces.empty()) return;
int piece = pieces.back();
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++block;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
}
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
{
free(m);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
++outstanding_requests;
work();
}
void work()
{
if (pieces.empty() && outstanding_requests == 0)
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
// send requests
if (outstanding_requests < 20 && !pieces.empty())
{
write_request();
return;
}
// read message
boost::asio::async_read(s, asio::buffer(buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
return;
}
boost::asio::async_read(s, asio::buffer(buffer, length)
, boost::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
int msg = read_uint8(ptr);
if (msg == 7) --outstanding_requests;
work();
}
};
int main(int argc, char const* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
address_v4 addr = address_v4::from_string(argv[2]);
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
error_code ec;
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<peer_conn*> conns;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0]));
libtorrent::sleep(1);
}
ios.run();
return 0;
}
<|endoftext|> |
<commit_before>//************************************************************/
//
// Spectrum
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 19.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include "SPXROOT.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"
int main(int argc, char *argv[]) {
if((argc - 1) < 1) {
std::cout << "@usage: Spectrum <steering_file>" << std::endl;
exit(0);
}
std::string file;
std::cout << "==================================" << std::endl;
std::cout << " Spectrum " << std::endl;
std::cout << "==================================" << std::endl <<std::endl;
TApplication *spectrum = new TApplication("Spectrum",0,0);
spectrum->SetReturnFromRun(true);
file = std::string(argv[1]);
SPXSteeringFile steeringFile = SPXSteeringFile(file);
//=========================================================
// Configuration
//=========================================================
try {
steeringFile.ParseAll(true);
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
exit(-1);
}
//=========================================================
// Analysis
//=========================================================
try {
SPXAnalysis analysis = SPXAnalysis(&steeringFile);
analysis.Run();
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
exit(-1);
}
spectrum->Run(kTRUE);
return 0;
}
<commit_msg>Suppressing display of the ROOT Canvas, outputting a PNG instead<commit_after>//************************************************************/
//
// Spectrum
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 19.09.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#include <iostream>
#include "SPXROOT.h"
#include "SPXSteeringFile.h"
#include "SPXAnalysis.h"
#include "SPXException.h"
int main(int argc, char *argv[]) {
if((argc - 1) < 1) {
std::cout << "@usage: Spectrum <steering_file>" << std::endl;
exit(0);
}
std::string file;
std::cout << "==================================" << std::endl;
std::cout << " Spectrum " << std::endl;
std::cout << "==================================" << std::endl <<std::endl;
TApplication *spectrum = new TApplication("Spectrum",0,0);
spectrum->SetReturnFromRun(true);
file = std::string(argv[1]);
SPXSteeringFile steeringFile = SPXSteeringFile(file);
//=========================================================
// Configuration
//=========================================================
try {
steeringFile.ParseAll(true);
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Could not parse the steering file: " << file << std::endl;
exit(-1);
}
//=========================================================
// Analysis
//=========================================================
try {
SPXAnalysis analysis = SPXAnalysis(&steeringFile);
analysis.Run();
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
std::cerr << "FATAL: Unable to perform successful analysis" << std::endl;
exit(-1);
}
//spectrum->Run(kTRUE);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCommonFlags.h"
#include "SkThreadPool.h"
DEFINE_string(config, "565 8888 pdf gpu nonrendering angle",
"Options: 565 8888 pdf gpu nonrendering msaa4 msaa16 nvprmsaa4 nvprmsaa16 "
"gpunull gpudebug angle mesa");
DEFINE_bool(cpu, true, "master switch for running CPU-bound work.");
DEFINE_bool(dryRun, false,
"just print the tests that would be run, without actually running them.");
DEFINE_bool(gpu, true, "master switch for running GPU-bound work.");
DEFINE_string(gpuAPI, "", "Force use of specific gpu API. Using \"gl\" "
"forces OpenGL API. Using \"gles\" forces OpenGL ES API. "
"Defaults to empty string, which selects the API native to the "
"system.");
DEFINE_bool2(leaks, l, false, "show leaked ref cnt'd objects.");
DEFINE_string2(match, m, NULL,
"[~][^]substring[$] [...] of GM name to run.\n"
"Multiple matches may be separated by spaces.\n"
"~ causes a matching GM to always be skipped\n"
"^ requires the start of the GM to match\n"
"$ requires the end of the GM to match\n"
"^ and $ requires an exact match\n"
"If a GM does not match any list entry,\n"
"it is skipped unless some list entry starts with ~");
DEFINE_bool2(quiet, q, false, "if true, don't print status updates.");
DEFINE_bool(resetGpuContext, true, "Reset the GrContext before running each test.");
DEFINE_bool(abandonGpuContext, false, "Abandon the GrContext after running each test. "
"Implies --resetGpuContext.");
DEFINE_bool2(single, z, false, "run tests on a single thread internally.");
DEFINE_string(skps, "", "Directory to read skps from.");
DEFINE_int32(threads, SkThreadPool::kThreadPerCore,
"run threadsafe tests on a threadpool with this many threads.");
DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
DEFINE_bool2(veryVerbose, V, false, "tell individual tests to be verbose.");
<commit_msg>Default --skps to ./skps<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCommonFlags.h"
#include "SkThreadPool.h"
DEFINE_string(config, "565 8888 pdf gpu nonrendering angle",
"Options: 565 8888 pdf gpu nonrendering msaa4 msaa16 nvprmsaa4 nvprmsaa16 "
"gpunull gpudebug angle mesa");
DEFINE_bool(cpu, true, "master switch for running CPU-bound work.");
DEFINE_bool(dryRun, false,
"just print the tests that would be run, without actually running them.");
DEFINE_bool(gpu, true, "master switch for running GPU-bound work.");
DEFINE_string(gpuAPI, "", "Force use of specific gpu API. Using \"gl\" "
"forces OpenGL API. Using \"gles\" forces OpenGL ES API. "
"Defaults to empty string, which selects the API native to the "
"system.");
DEFINE_bool2(leaks, l, false, "show leaked ref cnt'd objects.");
DEFINE_string2(match, m, NULL,
"[~][^]substring[$] [...] of GM name to run.\n"
"Multiple matches may be separated by spaces.\n"
"~ causes a matching GM to always be skipped\n"
"^ requires the start of the GM to match\n"
"$ requires the end of the GM to match\n"
"^ and $ requires an exact match\n"
"If a GM does not match any list entry,\n"
"it is skipped unless some list entry starts with ~");
DEFINE_bool2(quiet, q, false, "if true, don't print status updates.");
DEFINE_bool(resetGpuContext, true, "Reset the GrContext before running each test.");
DEFINE_bool(abandonGpuContext, false, "Abandon the GrContext after running each test. "
"Implies --resetGpuContext.");
DEFINE_bool2(single, z, false, "run tests on a single thread internally.");
DEFINE_string(skps, "skps", "Directory to read skps from.");
DEFINE_int32(threads, SkThreadPool::kThreadPerCore,
"run threadsafe tests on a threadpool with this many threads.");
DEFINE_bool2(verbose, v, false, "enable verbose output from the test driver.");
DEFINE_bool2(veryVerbose, V, false, "tell individual tests to be verbose.");
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost 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 ``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 <bifrost/affinity.h>
#include "assert.hpp"
#ifndef BF_OPENMP
#define BF_OPENMP 1
#endif
#if BF_OPENMP == 1
#include <omp.h>
#endif
#include <pthread.h>
//#include <sched.h>
#include <unistd.h>
#include <errno.h>
// Note: Pass core_id = -1 to unbind
BFstatus bfAffinitySetCore(int core) {
#if defined __linux__ && __linux__
// Check for valid core
int ncore = sysconf(_SC_NPROCESSORS_ONLN);
BF_ASSERT(core >= -1 && core < ncore, BF_STATUS_INVALID_ARGUMENT);
// Create core mask
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
if( core >= 0 ) {
// Set specified core
CPU_SET(core, &cpuset);
}
else {
// Set all cores (i.e., 'un-bind')
for( int c=0; c<ncore; ++c ) {
CPU_SET(c, &cpuset);
}
}
// Apply to current thread
pthread_t tid = pthread_self();
// Set affinity (note: non-portable)
int ret = pthread_setaffinity_np(tid, sizeof(cpu_set_t), &cpuset);
//int ret = sched_setaffinity(tid, sizeof(cpu_set_t), &cpuset);
if( ret == 0 ) {
return BF_STATUS_SUCCESS;
}
else {
return BF_STATUS_INVALID_ARGUMENT;
}
#else
#warning CPU core binding/affinity not supported on this OS
return BF_STATUS_UNSUPPORTED;
#endif
}
BFstatus bfAffinityGetCore(int* core) {
#if defined __linux__ && __linux__
BF_ASSERT(core, BF_STATUS_INVALID_POINTER);
pthread_t tid = pthread_self();
cpu_set_t cpuset;
BF_ASSERT(!pthread_getaffinity_np(tid, sizeof(cpu_set_t), &cpuset),
BF_STATUS_INTERNAL_ERROR);
if( CPU_COUNT(&cpuset) > 1 ) {
// Return -1 if more than one core is set
// TODO: Should really check if all cores are set, otherwise fail
*core = -1;
return BF_STATUS_SUCCESS;
}
else {
int ncore = sysconf(_SC_NPROCESSORS_ONLN);
for( int c=0; c<ncore; ++c ) {
if( CPU_ISSET(c, &cpuset) ) {
*core = c;
return BF_STATUS_SUCCESS;
}
}
}
// No cores are set! (Not sure if this is possible)
return BF_STATUS_INVALID_STATE;
#else
#warning CPU core binding/affinity not supported on this OS
return BF_STATUS_UNSUPPORTED;
#endif
}
BFstatus bfAffinitySetOpenMPCores(BFsize nthread,
const int* thread_cores) {
#if BF_OPENMP == 1
int host_core = -1;
// TODO: Check these for errors
bfAffinityGetCore(&host_core);
bfAffinitySetCore(-1); // Unbind host core to unconstrain OpenMP threads
omp_set_num_threads(nthread);
#pragma omp parallel for schedule(static, 1)
for( BFsize t=0; t<nthread; ++t ) {
int tid = omp_get_thread_num();
bfAffinitySetCore(thread_cores[tid]);
}
return bfAffinitySetCore(host_core);
#else
#warning CPU core binding/affinity not supported on this OS
return BF_STATUS_UNSUPPORTED;
#endif
}
<commit_msg>Worked on bringing affinity to mac.<commit_after>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost 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 ``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 <bifrost/affinity.h>
#include "assert.hpp"
#ifndef BF_OPENMP
#define BF_OPENMP 1
#endif
#if BF_OPENMP == 1
#include <omp.h>
#endif
#include <pthread.h>
//#include <sched.h>
#include <unistd.h>
#include <errno.h>
#if defined __APPLE__ && __APPLE__
// Based on information from:
// http://www.hybridkernel.com/2015/01/18/binding_threads_to_cores_osx.html
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/thread_act.h>
typedef struct cpu_set {
uint32_t count;
} cpu_set_t;
static inline void
CPU_ZERO(cpu_set_t *cs) { cs->count = 0; }
static inline void
CPU_SET(int num, cpu_set_t *cs) { cs->count |= (1 << num); }
static inline int
CPU_ISSET(int num, cpu_set_t *cs) { return (cs->count & (1 << num)); }
static inline int
CPU_COUNT(cpu_set_t *cs) {
int count = 0;
for(int i=0; i<8*sizeof(cpu_set_t); i++) {
count += CPU_ISSET(i, cs);
}
return count;
}
int pthread_getaffinity_np(pthread_t thread,
size_t cpu_size,
cpu_set_t *cpu_set) {
thread_port_t mach_thread;
mach_msg_type_number_t count;
boolean_t get_default;
thread_affinity_policy_data_t policy;
mach_thread = pthread_mach_thread_np(thread);
thread_policy_get(mach_thread, THREAD_AFFINITY_POLICY,
(thread_policy_t)&policy, &count,
&get_default);
cpu_set->count |= (1<<(policy.affinity_tag));
return 0;
}
int pthread_setaffinity_np(pthread_t thread,
size_t cpu_size,
cpu_set_t *cpu_set) {
thread_port_t mach_thread;
int core = 0;
for (core=0; core<8*cpu_size; core++) {
if (CPU_ISSET(core, cpu_set)) break;
}
thread_affinity_policy_data_t policy = { core };
mach_thread = pthread_mach_thread_np(thread);
thread_policy_set(mach_thread, THREAD_AFFINITY_POLICY,
(thread_policy_t)&policy, 1);
return 0;
}
#endif
// Note: Pass core_id = -1 to unbind
BFstatus bfAffinitySetCore(int core) {
#if (defined __linux__ && __linux__) || (defined __APPLE__ && __APPLE__)
// Check for valid core
int ncore = sysconf(_SC_NPROCESSORS_ONLN);
BF_ASSERT(core >= -1 && core < ncore, BF_STATUS_INVALID_ARGUMENT);
// Create core mask
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
if( core >= 0 ) {
// Set specified core
CPU_SET(core, &cpuset);
}
else {
// Set all cores (i.e., 'un-bind')
for( int c=0; c<ncore; ++c ) {
CPU_SET(c, &cpuset);
}
}
// Apply to current thread
pthread_t tid = pthread_self();
// Set affinity (note: non-portable)
int ret = pthread_setaffinity_np(tid, sizeof(cpu_set_t), &cpuset);
//int ret = sched_setaffinity(tid, sizeof(cpu_set_t), &cpuset);
if( ret == 0 ) {
return BF_STATUS_SUCCESS;
}
else {
return BF_STATUS_INVALID_ARGUMENT;
}
#else
#warning CPU core binding/affinity not supported on this OS
return BF_STATUS_UNSUPPORTED;
#endif
}
BFstatus bfAffinityGetCore(int* core) {
#if (defined __linux__ && __linux__) || (defined __APPLE__ && __APPLE__)
BF_ASSERT(core, BF_STATUS_INVALID_POINTER);
pthread_t tid = pthread_self();
cpu_set_t cpuset;
BF_ASSERT(!pthread_getaffinity_np(tid, sizeof(cpu_set_t), &cpuset),
BF_STATUS_INTERNAL_ERROR);
if( CPU_COUNT(&cpuset) > 1 ) {
// Return -1 if more than one core is set
// TODO: Should really check if all cores are set, otherwise fail
*core = -1;
return BF_STATUS_SUCCESS;
}
else {
int ncore = sysconf(_SC_NPROCESSORS_ONLN);
for( int c=0; c<ncore; ++c ) {
if( CPU_ISSET(c, &cpuset) ) {
*core = c;
return BF_STATUS_SUCCESS;
}
}
}
// No cores are set! (Not sure if this is possible)
return BF_STATUS_INVALID_STATE;
#else
#warning CPU core binding/affinity not supported on this OS
return BF_STATUS_UNSUPPORTED;
#endif
}
BFstatus bfAffinitySetOpenMPCores(BFsize nthread,
const int* thread_cores) {
#if BF_OPENMP == 1
int host_core = -1;
// TODO: Check these for errors
bfAffinityGetCore(&host_core);
bfAffinitySetCore(-1); // Unbind host core to unconstrain OpenMP threads
omp_set_num_threads(nthread);
#pragma omp parallel for schedule(static, 1)
for( BFsize t=0; t<nthread; ++t ) {
int tid = omp_get_thread_num();
bfAffinitySetCore(thread_cores[tid]);
}
return bfAffinitySetCore(host_core);
#else
return BF_STATUS_UNSUPPORTED;
#endif
}
<|endoftext|> |
<commit_before>#include "libirc/atom.h"
#include <stdexcept>
namespace irc {
namespace atom {
AtomicNumber::AtomicNumber(size_t an) {
if (!periodic_table::valid_atomic_number(an)) {
throw std::logic_error("Invalid atomic number.");
}
atomic_number = an;
}
AtomicNumber::AtomicNumber(const std::string& symbol)
: AtomicNumber(periodic_table::atomic_number(symbol)) {}
std::string symbol(const AtomicNumber& an) noexcept {
return periodic_table::symbols[an.atomic_number];
}
double mass(const AtomicNumber& an) noexcept {
return periodic_table::masses[an.atomic_number];
}
double covalent_radius(const AtomicNumber& an) noexcept {
return periodic_table::covalent_radii[an.atomic_number];
}
double vdw_radius(const AtomicNumber& an) noexcept {
return periodic_table::vdw_radii[an.atomic_number];
}
// TODO: constexpr for C++14
bool is_NOFPSCl(const AtomicNumber& an) noexcept {
const size_t n{an.atomic_number};
return (n == 7 or n == 8 or n == 9 or n == 15 or n == 16 or n == 17);
}
std::ostream& operator<<(std::ostream& out, const AtomicNumber& an) {
out << an.atomic_number;
return out;
}
} // namespace atom
} // namespace irc
<commit_msg>Increase coverage<commit_after>#include "libirc/atom.h"
#include <stdexcept>
namespace irc {
namespace atom {
AtomicNumber::AtomicNumber(size_t an) {
if (!periodic_table::valid_atomic_number(an)) {
throw std::logic_error("Invalid atomic number.");
}
atomic_number = an;
}
AtomicNumber::AtomicNumber(const std::string& symbol)
: AtomicNumber(periodic_table::atomic_number(symbol)) {}
std::string symbol(const AtomicNumber& an) noexcept {
return periodic_table::symbols[an.atomic_number];
}
double mass(const AtomicNumber& an) noexcept {
return periodic_table::masses[an.atomic_number];
}
double covalent_radius(const AtomicNumber& an) noexcept {
return periodic_table::covalent_radii[an.atomic_number];
}
double vdw_radius(const AtomicNumber& an) noexcept {
return periodic_table::vdw_radii[an.atomic_number];
}
// TODO: constexpr for C++14
bool is_NOFPSCl(const AtomicNumber& an) noexcept {
const size_t n{an.atomic_number};
return (n == 7 or n == 8 or n == 9 or n == 15 or n == 16 or n == 17);
}
} // namespace atom
} // namespace irc
<|endoftext|> |
<commit_before>// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Crypto.h"
#include "openssl/evp.h"
#include "openssl/aes.h"
#include "include/ceph_fs.h"
#include "config.h"
#include "common/armor.h"
#include <errno.h>
int get_random_bytes(char *buf, int len)
{
char *t = buf;
int fd = ::open("/dev/urandom", O_RDONLY);
int l = len;
if (fd < 0)
return -errno;
while (l) {
int r = ::read(fd, t, l);
if (r < 0) {
::close(fd);
return -errno;
}
t += r;
l -= r;
}
::close(fd);
return 0;
}
static int get_random_bytes(int len, bufferlist& bl)
{
char buf[len];
get_random_bytes(buf, len);
bl.append(buf, len);
return 0;
}
void generate_random_string(string& s, int len)
{
char buf[len+1];
get_random_bytes(buf, len);
buf[len] = 0;
s = buf;
}
// ---------------------------------------------------
class CryptoNone : public CryptoHandler {
public:
CryptoNone() {}
~CryptoNone() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
int CryptoNone::create(bufferptr& secret)
{
return 0;
}
int CryptoNone::validate_secret(bufferptr& secret)
{
return 0;
}
int CryptoNone::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
int CryptoNone::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
// ---------------------------------------------------
#define AES_KEY_LEN AES_BLOCK_SIZE
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = CEPH_AES_IV;
int CryptoAES::create(bufferptr& secret)
{
bufferlist bl;
int r = get_random_bytes(AES_KEY_LEN, bl);
if (r < 0)
return r;
secret = buffer::ptr(bl.c_str(), bl.length());
return 0;
}
int CryptoAES::validate_secret(bufferptr& secret)
{
if (secret.length() < AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return -EINVAL;
}
return 0;
}
int CryptoAES::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
int in_len = in.length();
const unsigned char *in_buf;
int max_out = (in_len + AES_BLOCK_SIZE) & ~(AES_BLOCK_SIZE -1);
int total_out = 0;
int outlen;
#define OUT_BUF_EXTRA 128
unsigned char outbuf[max_out + OUT_BUF_EXTRA];
if (secret.length() < AES_KEY_LEN) {
derr(0) << "key is too short" << dendl;
return false;
}
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
bool ret = false;
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
outlen = max_out - total_out;
in_buf = (const unsigned char *)it->c_str();
if (!EVP_EncryptUpdate(&ctx, &outbuf[total_out], &outlen, in_buf, it->length()))
goto out;
total_out += outlen;
}
if (!EVP_EncryptFinal_ex(&ctx, outbuf + total_out, &outlen))
goto out;
total_out += outlen;
out.append((const char *)outbuf, total_out);
ret = true;
out:
EVP_CIPHER_CTX_cleanup(&ctx);
return ret;
}
int CryptoAES::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
int in_len = in.length();
int dec_len = 0;
int total_dec_len = 0;
unsigned char dec_data[in_len];
int result = 0;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
int res = EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if (res == 1) {
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
const unsigned char *in_buf = (const unsigned char *)it->c_str();
res = EVP_DecryptUpdate(ctx, &dec_data[total_dec_len],
&dec_len, in_buf, it->length());
total_dec_len += dec_len;
if (res != 1) {
dout(0) << "EVP_DecryptUpdate error" << dendl;
result = -1;
}
}
} else {
dout(0) << "EVP_DecryptInit_ex error" << dendl;
result = -1;
}
if (!result) {
EVP_DecryptFinal_ex(ctx,
&dec_data[total_dec_len],
&dec_len);
total_dec_len += dec_len;
out.append((const char *)dec_data, total_dec_len);
}
EVP_CIPHER_CTX_free(ctx);
return result;
}
// ---------------------------------------------------
static CryptoNone crypto_none;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_NONE:
return &crypto_none;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
// ---------------------------------------------------
int CryptoKey::set_secret(int type, bufferptr& s)
{
this->type = type;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
int ret = h->validate_secret(s);
if (ret < 0)
return ret;
secret = s;
return 0;
}
int CryptoKey::create(int t)
{
type = t;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->create(secret);
}
int CryptoKey::encrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->encrypt(this->secret, in, out);
}
int CryptoKey::decrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->decrypt(this->secret, in, out);
}
void CryptoKey::print(ostream &out) const
{
string a;
encode_base64(a);
out << a;
}
void CryptoKey::to_str(string& s)
{
int len = secret.length() * 4;
char buf[len];
hex2str(secret.c_str(), secret.length(), buf, len);
s = buf;
}
<commit_msg>auth: fix cast<commit_after>// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Crypto.h"
#include "openssl/evp.h"
#include "openssl/aes.h"
#include "include/ceph_fs.h"
#include "config.h"
#include "common/armor.h"
#include <errno.h>
int get_random_bytes(char *buf, int len)
{
char *t = buf;
int fd = ::open("/dev/urandom", O_RDONLY);
int l = len;
if (fd < 0)
return -errno;
while (l) {
int r = ::read(fd, t, l);
if (r < 0) {
::close(fd);
return -errno;
}
t += r;
l -= r;
}
::close(fd);
return 0;
}
static int get_random_bytes(int len, bufferlist& bl)
{
char buf[len];
get_random_bytes(buf, len);
bl.append(buf, len);
return 0;
}
void generate_random_string(string& s, int len)
{
char buf[len+1];
get_random_bytes(buf, len);
buf[len] = 0;
s = buf;
}
// ---------------------------------------------------
class CryptoNone : public CryptoHandler {
public:
CryptoNone() {}
~CryptoNone() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
int CryptoNone::create(bufferptr& secret)
{
return 0;
}
int CryptoNone::validate_secret(bufferptr& secret)
{
return 0;
}
int CryptoNone::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
int CryptoNone::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
out = in;
return 0;
}
// ---------------------------------------------------
#define AES_KEY_LEN AES_BLOCK_SIZE
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
int create(bufferptr& secret);
int validate_secret(bufferptr& secret);
int encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
int decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = (const unsigned char *)CEPH_AES_IV;
int CryptoAES::create(bufferptr& secret)
{
bufferlist bl;
int r = get_random_bytes(AES_KEY_LEN, bl);
if (r < 0)
return r;
secret = buffer::ptr(bl.c_str(), bl.length());
return 0;
}
int CryptoAES::validate_secret(bufferptr& secret)
{
if (secret.length() < AES_KEY_LEN) {
dout(0) << "key is too short" << dendl;
return -EINVAL;
}
return 0;
}
int CryptoAES::encrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
int in_len = in.length();
const unsigned char *in_buf;
int max_out = (in_len + AES_BLOCK_SIZE) & ~(AES_BLOCK_SIZE -1);
int total_out = 0;
int outlen;
#define OUT_BUF_EXTRA 128
unsigned char outbuf[max_out + OUT_BUF_EXTRA];
if (secret.length() < AES_KEY_LEN) {
derr(0) << "key is too short" << dendl;
return false;
}
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
bool ret = false;
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
outlen = max_out - total_out;
in_buf = (const unsigned char *)it->c_str();
if (!EVP_EncryptUpdate(&ctx, &outbuf[total_out], &outlen, in_buf, it->length()))
goto out;
total_out += outlen;
}
if (!EVP_EncryptFinal_ex(&ctx, outbuf + total_out, &outlen))
goto out;
total_out += outlen;
out.append((const char *)outbuf, total_out);
ret = true;
out:
EVP_CIPHER_CTX_cleanup(&ctx);
return ret;
}
int CryptoAES::decrypt(bufferptr& secret, const bufferlist& in, bufferlist& out)
{
const unsigned char *key = (const unsigned char *)secret.c_str();
int in_len = in.length();
int dec_len = 0;
int total_dec_len = 0;
unsigned char dec_data[in_len];
int result = 0;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
int res = EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if (res == 1) {
for (std::list<bufferptr>::const_iterator it = in.buffers().begin();
it != in.buffers().end(); it++) {
const unsigned char *in_buf = (const unsigned char *)it->c_str();
res = EVP_DecryptUpdate(ctx, &dec_data[total_dec_len],
&dec_len, in_buf, it->length());
total_dec_len += dec_len;
if (res != 1) {
dout(0) << "EVP_DecryptUpdate error" << dendl;
result = -1;
}
}
} else {
dout(0) << "EVP_DecryptInit_ex error" << dendl;
result = -1;
}
if (!result) {
EVP_DecryptFinal_ex(ctx,
&dec_data[total_dec_len],
&dec_len);
total_dec_len += dec_len;
out.append((const char *)dec_data, total_dec_len);
}
EVP_CIPHER_CTX_free(ctx);
return result;
}
// ---------------------------------------------------
static CryptoNone crypto_none;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_NONE:
return &crypto_none;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
// ---------------------------------------------------
int CryptoKey::set_secret(int type, bufferptr& s)
{
this->type = type;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
int ret = h->validate_secret(s);
if (ret < 0)
return ret;
secret = s;
return 0;
}
int CryptoKey::create(int t)
{
type = t;
created = g_clock.now();
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->create(secret);
}
int CryptoKey::encrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->encrypt(this->secret, in, out);
}
int CryptoKey::decrypt(const bufferlist& in, bufferlist& out)
{
CryptoHandler *h = ceph_crypto_mgr.get_crypto(type);
if (!h)
return -EOPNOTSUPP;
return h->decrypt(this->secret, in, out);
}
void CryptoKey::print(ostream &out) const
{
string a;
encode_base64(a);
out << a;
}
void CryptoKey::to_str(string& s)
{
int len = secret.length() * 4;
char buf[len];
hex2str(secret.c_str(), secret.length(), buf, len);
s = buf;
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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 (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 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 "authdb.hh"
#include "mysql/soci-mysql.h"
#include <thread>
using namespace soci;
// The dreaded chrono::steady_clock which is not supported for gcc < 4.7
#include <chrono>
using namespace std;
using namespace chrono;
#ifdef USE_MONOTONIC_CLOCK
namespace std {
typedef monotonic_clock steady_clock;
}
#endif
void SociAuthDB::declareConfig(GenericStruct *mc) {
// ODBC-specific configuration keys
ConfigItemDescriptor items[] = {
{String, "soci-password-request",
"Soci SQL request to execute to obtain the password.\n"
"Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, "
"and\n -':authid' : the authorization username.\n"
"The use of the :id parameter is mandatory.",
"select password from accounts where id = :id and domain = :domain and authid=:authid"},
{Integer, "soci-poolsize",
"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will "
"allow each thread to get a connection.\n"
"The threads are blocked until a connection is released back to the pool, so increasing the pool size will "
"allow more connections to occur simultaneously.\n"
"On the other hand, you should not keep too many open connections to your DB at the same time.",
"100"},
{String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n"
"Depending on your Soci package and the modules you installed, this could be 'mysql', "
"'oracle', 'postgresql' or something else.",
"mysql"},
{String, "soci-connection-string", "The configuration parameters of the Soci backend.\n"
"The basic format is \"key=value key2=value2\". For a mysql backend, this "
"is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n"
"Please refer to the Soci documentation of your backend, for intance: "
"http://soci.sourceforge.net/doc/3.2/backends/mysql.html",
"db=mydb user=myuser password='mypass' host=myhost.com"},
{Integer, "soci-max-queue-size",
"Amount of queries that will be allowed to be queued before bailing password "
"requests.\n This value should be chosen accordingly with 'soci-poolsize', so "
"that you have a coherent behavior.\n This limit is here mainly as a safeguard "
"against out-of-control growth of the queue in the event of a flood or big "
"delays in the database backend.",
"1000"},
config_item_end};
mc->addChildrenValues(items);
}
SociAuthDB::SociAuthDB() : conn_pool(NULL) {
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
poolSize = ma->get<ConfigInt>("soci-poolsize")->read();
connection_string = ma->get<ConfigString>("soci-connection-string")->read();
backend = ma->get<ConfigString>("soci-backend")->read();
get_password_request = ma->get<ConfigString>("soci-password-request")->read();
unsigned int max_queue_size = (unsigned int)ma->get<ConfigInt>("soci-max-queue-size")->read();
conn_pool = new connection_pool(poolSize);
thread_pool = new ThreadPool(poolSize, max_queue_size);
LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(),
(int)poolSize);
for (size_t i = 0; i < poolSize; i++) {
conn_pool->at(i).open(backend, connection_string);
}
}
SociAuthDB::~SociAuthDB() {
delete thread_pool; // will automatically shut it down, clearing threads
delete conn_pool;
}
void SociAuthDB::reconnectSession(soci::session &session) {
SLOGE << "[SOCI] Trying close/reconnect on " << session.get_backend_name() << " session";
session.close();
session.reconnect();
}
#define DURATION_MS(start, stop) (unsigned long) duration_cast<milliseconds>((stop) - (start)).count()
void SociAuthDB::getPasswordWithPool(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
steady_clock::time_point start = steady_clock::now();
// will grab a connection from the pool. This is thread safe
session sql(*conn_pool);
std::string pass;
steady_clock::time_point stop = steady_clock::now();
SLOGD << "[SOCI] Pool acquired in " << DURATION_MS(start, stop) << "ms";
start = stop;
try {
sql << get_password_request, into(pass), use(id, "id"), use(domain, "domain"), use(authid, "authid");
stop = steady_clock::now();
SLOGD << "[SOCI] Got pass for " << id << " in " << DURATION_MS(start, stop) << "ms";
cachePassword(createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);
if (listener) listener->onResult(PASSWORD_FOUND, pass);
} catch (mysql_soci_error const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] MySQL error after " << DURATION_MS(start, stop) << "ms : " << e.err_num_ << " " << e.what();
if (listener) listener->onResult(PASSWORD_NOT_FOUND, pass);
reconnectSession(sql);
} catch (exception const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] Some other error after " << DURATION_MS(start, stop) << "ms : " << e.what();
if (listener) listener->onResult(PASSWORD_NOT_FOUND, pass);
reconnectSession(sql);
}
}
#pragma mark - Inherited virtuals
void SociAuthDB::getPasswordFromBackend(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
// create a thread to grab a pool connection and use it to retrieve the auth information
auto func = bind(&SociAuthDB::getPasswordWithPool, this, id, domain, authid, listener);
bool success = thread_pool->Enqueue(func);
if (success == FALSE) {
// Enqueue() can fail when the queue is full, so we have to act on that
SLOGE << "[SOCI] Auth queue is full, cannot fullfil password request for " << id << " / " << domain << " / "
<< authid;
if (listener) listener->onResult(AUTH_ERROR, "");
}
return;
}
<commit_msg>fix bug in soci implementation: when a password is not found, this doesn't trigger an exception.<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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 (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 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 "authdb.hh"
#include "mysql/soci-mysql.h"
#include <thread>
using namespace soci;
// The dreaded chrono::steady_clock which is not supported for gcc < 4.7
#include <chrono>
using namespace std;
using namespace chrono;
#ifdef USE_MONOTONIC_CLOCK
namespace std {
typedef monotonic_clock steady_clock;
}
#endif
void SociAuthDB::declareConfig(GenericStruct *mc) {
// ODBC-specific configuration keys
ConfigItemDescriptor items[] = {
{String, "soci-password-request",
"Soci SQL request to execute to obtain the password.\n"
"Named parameters are:\n -':id' : the user found in the from header,\n -':domain' : the authorization realm, "
"and\n -':authid' : the authorization username.\n"
"The use of the :id parameter is mandatory.",
"select password from accounts where id = :id and domain = :domain and authid=:authid"},
{Integer, "soci-poolsize",
"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will "
"allow each thread to get a connection.\n"
"The threads are blocked until a connection is released back to the pool, so increasing the pool size will "
"allow more connections to occur simultaneously.\n"
"On the other hand, you should not keep too many open connections to your DB at the same time.",
"100"},
{String, "soci-backend", "Choose the type of backend that Soci will use for the connection.\n"
"Depending on your Soci package and the modules you installed, this could be 'mysql', "
"'oracle', 'postgresql' or something else.",
"mysql"},
{String, "soci-connection-string", "The configuration parameters of the Soci backend.\n"
"The basic format is \"key=value key2=value2\". For a mysql backend, this "
"is a valid config: \"db=mydb user=user password='pass' host=myhost.com\".\n"
"Please refer to the Soci documentation of your backend, for intance: "
"http://soci.sourceforge.net/doc/3.2/backends/mysql.html",
"db=mydb user=myuser password='mypass' host=myhost.com"},
{Integer, "soci-max-queue-size",
"Amount of queries that will be allowed to be queued before bailing password "
"requests.\n This value should be chosen accordingly with 'soci-poolsize', so "
"that you have a coherent behavior.\n This limit is here mainly as a safeguard "
"against out-of-control growth of the queue in the event of a flood or big "
"delays in the database backend.",
"1000"},
config_item_end};
mc->addChildrenValues(items);
}
SociAuthDB::SociAuthDB() : conn_pool(NULL) {
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
poolSize = ma->get<ConfigInt>("soci-poolsize")->read();
connection_string = ma->get<ConfigString>("soci-connection-string")->read();
backend = ma->get<ConfigString>("soci-backend")->read();
get_password_request = ma->get<ConfigString>("soci-password-request")->read();
unsigned int max_queue_size = (unsigned int)ma->get<ConfigInt>("soci-max-queue-size")->read();
conn_pool = new connection_pool(poolSize);
thread_pool = new ThreadPool(poolSize, max_queue_size);
LOGD("[SOCI] Authentication provider for backend %s created. Pooled for %d connections", backend.c_str(),
(int)poolSize);
for (size_t i = 0; i < poolSize; i++) {
conn_pool->at(i).open(backend, connection_string);
}
}
SociAuthDB::~SociAuthDB() {
delete thread_pool; // will automatically shut it down, clearing threads
delete conn_pool;
}
void SociAuthDB::reconnectSession(soci::session &session) {
SLOGE << "[SOCI] Trying close/reconnect on " << session.get_backend_name() << " session";
session.close();
session.reconnect();
}
#define DURATION_MS(start, stop) (unsigned long) duration_cast<milliseconds>((stop) - (start)).count()
void SociAuthDB::getPasswordWithPool(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
steady_clock::time_point start = steady_clock::now();
// will grab a connection from the pool. This is thread safe
session sql(*conn_pool);
std::string pass;
steady_clock::time_point stop = steady_clock::now();
SLOGD << "[SOCI] Pool acquired in " << DURATION_MS(start, stop) << "ms";
start = stop;
try {
sql << get_password_request, into(pass), use(id, "id"), use(domain, "domain"), use(authid, "authid");
stop = steady_clock::now();
SLOGD << "[SOCI] Got pass for " << id << " in " << DURATION_MS(start, stop) << "ms";
cachePassword(createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);
if (listener){
listener->onResult(pass.empty() ? PASSWORD_NOT_FOUND : PASSWORD_FOUND, pass);
}
} catch (mysql_soci_error const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] MySQL error after " << DURATION_MS(start, stop) << "ms : " << e.err_num_ << " " << e.what();
if (listener) listener->onResult(PASSWORD_NOT_FOUND, pass);
reconnectSession(sql);
} catch (exception const &e) {
stop = steady_clock::now();
SLOGE << "[SOCI] Some other error after " << DURATION_MS(start, stop) << "ms : " << e.what();
if (listener) listener->onResult(PASSWORD_NOT_FOUND, pass);
reconnectSession(sql);
}
}
#pragma mark - Inherited virtuals
void SociAuthDB::getPasswordFromBackend(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
// create a thread to grab a pool connection and use it to retrieve the auth information
auto func = bind(&SociAuthDB::getPasswordWithPool, this, id, domain, authid, listener);
bool success = thread_pool->Enqueue(func);
if (success == FALSE) {
// Enqueue() can fail when the queue is full, so we have to act on that
SLOGE << "[SOCI] Auth queue is full, cannot fullfil password request for " << id << " / " << domain << " / "
<< authid;
if (listener) listener->onResult(AUTH_ERROR, "");
}
return;
}
<|endoftext|> |
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_SIGNAL_HPP_
#define _QITYPE_SIGNAL_HPP_
#include <qi/atomic.hpp>
#include <qi/eventloop.hpp>
#include <qitype/signature.hpp>
#include <qitype/functiontype.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/enable_shared_from_this.hpp>
namespace qi {
class ManageablePrivate;
class SignalSubscriber;
/** User classes can inherit from Manageable to benefit from Event loop
* management
*/
class QITYPE_API Manageable
{
public:
Manageable();
~Manageable();
Manageable(const Manageable& b);
void operator = (const Manageable& b);
EventLoop* eventLoop() const;
void moveToEventLoop(EventLoop* eventLoop);
ManageablePrivate* _p;
};
class GenericObject;
typedef boost::shared_ptr<GenericObject> ObjectPtr;
typedef boost::weak_ptr<GenericObject> ObjectWeakPtr;
class SignalBasePrivate;
class QITYPE_API SignalBase
{
public:
explicit SignalBase(const std::string& signature);
SignalBase();
~SignalBase();
SignalBase(const SignalBase& b);
SignalBase& operator = (const SignalBase& b);
virtual std::string signature() const;
typedef unsigned int Link;
template<typename FUNCTION_TYPE>
Link connect(FUNCTION_TYPE f, EventLoop* ctx = getDefaultObjectEventLoop());
Link connect(qi::ObjectPtr target, unsigned int slot);
Link connect(GenericFunction callback, EventLoop* ctx = getDefaultObjectEventLoop());
Link connect(const SignalSubscriber& s);
bool disconnectAll();
/** Disconnect a SignalHandler. The associated callback will not be called
* anymore as soon as this function returns, but might be called in an
* other thread while this function runs.
*/
bool disconnect(const Link& link);
void trigger(const GenericFunctionParameters& params);
void operator()(
qi::AutoGenericValuePtr p1 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p2 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p3 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p4 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p5 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p6 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p7 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p8 = qi::AutoGenericValuePtr());
std::vector<SignalSubscriber> subscribers();
static const SignalBase::Link invalidLink;
public:
boost::shared_ptr<SignalBasePrivate> _p;
};
template<typename FUNCTION_TYPE>
inline SignalBase::Link SignalBase::connect(FUNCTION_TYPE callback, EventLoop* ctx)
{
return connect(makeGenericFunction(callback), ctx);
}
template<typename T>
class Signal: public SignalBase, public boost::function<T>
{
public:
Signal();
Signal(const Signal<T>& b);
Signal<T>& operator = (const Signal<T>& b);
virtual std::string signature() const;
using boost::function<T>::operator();
inline SignalBase::Link connect(boost::function<T> f, EventLoop* ctx=getDefaultObjectEventLoop())
{
return SignalBase::connect(f, ctx);
}
inline SignalBase::Link connect(GenericFunction f, EventLoop* ctx=getDefaultObjectEventLoop())
{
return SignalBase::connect(f, ctx);
}
/// Auto-disconnects on target destruction
inline SignalBase::Link connect(qi::ObjectPtr target, unsigned int slot)
{
return SignalBase::connect(target, slot);
}
/// IF O is a shared_ptr, will auto-disconnect if object is destroyed
template<typename O, typename MF>
inline SignalBase::Link connect(O* target, MF method, EventLoop* ctx=getDefaultObjectEventLoop());
template<typename O, typename MF>
inline SignalBase::Link connect(boost::shared_ptr<O> target, MF method, EventLoop* ctx=getDefaultObjectEventLoop());
};
namespace detail
{
/// Interface for a weak-lock recursive mechanism: if lock fail, unregister callback
class WeakLock
{
public:
virtual ~WeakLock(){}
virtual bool tryLock() = 0;
virtual void unlock() = 0;
virtual WeakLock* clone() = 0;
};
}
/** Event subscriber info.
*
* Only one of handler or target must be set.
*/
class QITYPE_API SignalSubscriber
: public boost::enable_shared_from_this<SignalSubscriber>
{
public:
SignalSubscriber()
: weakLock(0), target(0), method(0), enabled(true)
{}
SignalSubscriber(GenericFunction func, EventLoop* ctx = getDefaultObjectEventLoop(), detail::WeakLock* lock = 0);
SignalSubscriber(qi::ObjectPtr target, unsigned int method);
template<typename O, typename MF>
SignalSubscriber(O* ptr, MF function, EventLoop* ctx = getDefaultObjectEventLoop());
template<typename O, typename MF>
SignalSubscriber(boost::shared_ptr<O> ptr, MF function, EventLoop* ctx = getDefaultObjectEventLoop());
SignalSubscriber(const SignalSubscriber& b);
~SignalSubscriber();
void operator = (const SignalSubscriber& b);
void call(const GenericFunctionParameters& args);
//wait till all threads are inactive except the current thread.
void waitForInactive();
void addActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
void removeActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
public:
// Source information
SignalBase* source;
/// Uid that can be passed to GenericObject::disconnect()
SignalBase::Link linkId;
// Target information, kept here to be able to introspect a Subscriber
// Mode 1: Direct functor call
GenericFunction handler;
detail::WeakLock* weakLock; // try to acquire weakLocker, disconnect if cant
boost::function<EventLoop*(void)> eventLoopGetter;
// Mode 2: metaCall
ObjectWeakPtr* target;
unsigned int method;
boost::mutex mutex;
// Fields below are protected by lock
// If enabled is set to false while lock is acquired,
// No more callback will trigger (activeThreads will se no push-back)
bool enabled;
// Number of calls in progress.
// Each entry there is a subscriber call that can no longuer be aborted
std::vector<boost::thread::id> activeThreads; // order not preserved
};
typedef boost::shared_ptr<SignalSubscriber> SignalSubscriberPtr;
}
#include <qitype/details/signal.hxx>
QI_NO_TYPE(qi::SignalBase)
#endif // _QITYPE_SIGNAL_HPP_
<commit_msg>Signal: add virtual destructor<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_SIGNAL_HPP_
#define _QITYPE_SIGNAL_HPP_
#include <qi/atomic.hpp>
#include <qi/eventloop.hpp>
#include <qitype/signature.hpp>
#include <qitype/functiontype.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/enable_shared_from_this.hpp>
namespace qi {
class ManageablePrivate;
class SignalSubscriber;
/** User classes can inherit from Manageable to benefit from Event loop
* management
*/
class QITYPE_API Manageable
{
public:
Manageable();
~Manageable();
Manageable(const Manageable& b);
void operator = (const Manageable& b);
EventLoop* eventLoop() const;
void moveToEventLoop(EventLoop* eventLoop);
ManageablePrivate* _p;
};
class GenericObject;
typedef boost::shared_ptr<GenericObject> ObjectPtr;
typedef boost::weak_ptr<GenericObject> ObjectWeakPtr;
class SignalBasePrivate;
class QITYPE_API SignalBase
{
public:
explicit SignalBase(const std::string& signature);
SignalBase();
virtual ~SignalBase();
SignalBase(const SignalBase& b);
SignalBase& operator = (const SignalBase& b);
virtual std::string signature() const;
typedef unsigned int Link;
template<typename FUNCTION_TYPE>
Link connect(FUNCTION_TYPE f, EventLoop* ctx = getDefaultObjectEventLoop());
Link connect(qi::ObjectPtr target, unsigned int slot);
Link connect(GenericFunction callback, EventLoop* ctx = getDefaultObjectEventLoop());
Link connect(const SignalSubscriber& s);
bool disconnectAll();
/** Disconnect a SignalHandler. The associated callback will not be called
* anymore as soon as this function returns, but might be called in an
* other thread while this function runs.
*/
bool disconnect(const Link& link);
void trigger(const GenericFunctionParameters& params);
void operator()(
qi::AutoGenericValuePtr p1 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p2 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p3 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p4 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p5 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p6 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p7 = qi::AutoGenericValuePtr(),
qi::AutoGenericValuePtr p8 = qi::AutoGenericValuePtr());
std::vector<SignalSubscriber> subscribers();
static const SignalBase::Link invalidLink;
public:
boost::shared_ptr<SignalBasePrivate> _p;
};
template<typename FUNCTION_TYPE>
inline SignalBase::Link SignalBase::connect(FUNCTION_TYPE callback, EventLoop* ctx)
{
return connect(makeGenericFunction(callback), ctx);
}
template<typename T>
class Signal: public SignalBase, public boost::function<T>
{
public:
Signal();
Signal(const Signal<T>& b);
Signal<T>& operator = (const Signal<T>& b);
virtual std::string signature() const;
using boost::function<T>::operator();
inline SignalBase::Link connect(boost::function<T> f, EventLoop* ctx=getDefaultObjectEventLoop())
{
return SignalBase::connect(f, ctx);
}
inline SignalBase::Link connect(GenericFunction f, EventLoop* ctx=getDefaultObjectEventLoop())
{
return SignalBase::connect(f, ctx);
}
/// Auto-disconnects on target destruction
inline SignalBase::Link connect(qi::ObjectPtr target, unsigned int slot)
{
return SignalBase::connect(target, slot);
}
/// IF O is a shared_ptr, will auto-disconnect if object is destroyed
template<typename O, typename MF>
inline SignalBase::Link connect(O* target, MF method, EventLoop* ctx=getDefaultObjectEventLoop());
template<typename O, typename MF>
inline SignalBase::Link connect(boost::shared_ptr<O> target, MF method, EventLoop* ctx=getDefaultObjectEventLoop());
};
namespace detail
{
/// Interface for a weak-lock recursive mechanism: if lock fail, unregister callback
class WeakLock
{
public:
virtual ~WeakLock(){}
virtual bool tryLock() = 0;
virtual void unlock() = 0;
virtual WeakLock* clone() = 0;
};
}
/** Event subscriber info.
*
* Only one of handler or target must be set.
*/
class QITYPE_API SignalSubscriber
: public boost::enable_shared_from_this<SignalSubscriber>
{
public:
SignalSubscriber()
: weakLock(0), target(0), method(0), enabled(true)
{}
SignalSubscriber(GenericFunction func, EventLoop* ctx = getDefaultObjectEventLoop(), detail::WeakLock* lock = 0);
SignalSubscriber(qi::ObjectPtr target, unsigned int method);
template<typename O, typename MF>
SignalSubscriber(O* ptr, MF function, EventLoop* ctx = getDefaultObjectEventLoop());
template<typename O, typename MF>
SignalSubscriber(boost::shared_ptr<O> ptr, MF function, EventLoop* ctx = getDefaultObjectEventLoop());
SignalSubscriber(const SignalSubscriber& b);
~SignalSubscriber();
void operator = (const SignalSubscriber& b);
void call(const GenericFunctionParameters& args);
//wait till all threads are inactive except the current thread.
void waitForInactive();
void addActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
void removeActive(bool acquireLock, boost::thread::id tid = boost::this_thread::get_id());
public:
// Source information
SignalBase* source;
/// Uid that can be passed to GenericObject::disconnect()
SignalBase::Link linkId;
// Target information, kept here to be able to introspect a Subscriber
// Mode 1: Direct functor call
GenericFunction handler;
detail::WeakLock* weakLock; // try to acquire weakLocker, disconnect if cant
boost::function<EventLoop*(void)> eventLoopGetter;
// Mode 2: metaCall
ObjectWeakPtr* target;
unsigned int method;
boost::mutex mutex;
// Fields below are protected by lock
// If enabled is set to false while lock is acquired,
// No more callback will trigger (activeThreads will se no push-back)
bool enabled;
// Number of calls in progress.
// Each entry there is a subscriber call that can no longuer be aborted
std::vector<boost::thread::id> activeThreads; // order not preserved
};
typedef boost::shared_ptr<SignalSubscriber> SignalSubscriberPtr;
}
#include <qitype/details/signal.hxx>
QI_NO_TYPE(qi::SignalBase)
#endif // _QITYPE_SIGNAL_HPP_
<|endoftext|> |
<commit_before>///
/// @file main.cpp
/// @brief primecount console application.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "cmdoptions.hpp"
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <calculator.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <PhiTiny.hpp>
#include <S1.hpp>
#include <S2.hpp>
#include <stdint.h>
#include <exception>
#include <iostream>
#include <limits>
#include <string>
#ifdef HAVE_MPI
#include <mpi.h>
#endif
using namespace std;
using namespace primecount;
namespace primecount {
int64_t to_int64(maxint_t x)
{
if (x > numeric_limits<int64_t>::max())
throw primecount_error("this is a 63-bit function, x must be < 2^63");
return (int64_t) x;
}
maxint_t P2(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("P2(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
if (x <= numeric_limits<int64_t>::max())
return P2((int64_t) x, y, threads);
else
return P2(x, y, threads);
}
maxint_t S1(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S1(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S1((int64_t) x, y, c, threads);
else
return S1(x, y, c, threads);
}
maxint_t S2_trivial(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_trivial(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S2_trivial((int64_t) x, y, z, c, threads);
else
return S2_trivial(x, y, z, c, threads);
}
maxint_t S2_easy(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_easy(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S2_easy((int64_t) x, y, z, c, threads);
else
return S2_easy(x, y, z, c, threads);
}
maxint_t S2_hard(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_hard(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
// TODO: find better S2_hard approximation formula
maxint_t s2_hard_approx = Ri(x);
if (x <= numeric_limits<int64_t>::max())
return S2_hard((int64_t) x, y, z, c, (int64_t) s2_hard_approx, threads);
else
return S2_hard(x, y, z, c, s2_hard_approx, threads);
}
} // namespace
int main (int argc, char* argv[])
{
#ifdef HAVE_MPI
MPI_Init(&argc, &argv);
#endif
try
{
CmdOptions opt = parseOptions(argc, argv);
double time = get_wtime();
maxint_t x = opt.x;
maxint_t res = 0;
int threads = opt.threads;
switch (opt.option)
{
case OPTION_DELEGLISE_RIVAT:
res = pi_deleglise_rivat(x, threads); break;
case OPTION_DELEGLISE_RIVAT1:
res = pi_deleglise_rivat1(to_int64(x)); break;
case OPTION_DELEGLISE_RIVAT2:
res = pi_deleglise_rivat2(to_int64(x)); break;
case OPTION_DELEGLISE_RIVAT_PARALLEL1:
res = pi_deleglise_rivat_parallel1(to_int64(x), threads); break;
case OPTION_DELEGLISE_RIVAT_PARALLEL2:
res = pi_deleglise_rivat_parallel2(to_int64(x), threads); break;
case OPTION_LEGENDRE:
res = pi_legendre(to_int64(x), threads); break;
case OPTION_LEHMER:
res = pi_lehmer(to_int64(x), threads); break;
case OPTION_LMO:
res = pi_lmo(to_int64(x), threads); break;
case OPTION_LMO1:
res = pi_lmo1(to_int64(x)); break;
case OPTION_LMO2:
res = pi_lmo2(to_int64(x)); break;
case OPTION_LMO3:
res = pi_lmo3(to_int64(x)); break;
case OPTION_LMO4:
res = pi_lmo4(to_int64(x)); break;
case OPTION_LMO5:
res = pi_lmo5(to_int64(x)); break;
case OPTION_LMO_PARALLEL1:
res = pi_lmo_parallel1(to_int64(x), threads); break;
case OPTION_LMO_PARALLEL2:
res = pi_lmo_parallel2(to_int64(x), threads); break;
case OPTION_LMO_PARALLEL3:
res = pi_lmo_parallel3(to_int64(x), threads); break;
case OPTION_MEISSEL:
res = pi_meissel(to_int64(x), threads); break;
case OPTION_PRIMESIEVE:
res = pi_primesieve(to_int64(x), threads); break;
case OPTION_P2:
res = P2(x, threads); break;
case OPTION_PI:
res = pi(x, threads); break;
case OPTION_LI:
res = Li(x); break;
case OPTION_LIINV:
res = Li_inverse(x); break;
case OPTION_RI:
res = Ri(x); break;
case OPTION_RIINV:
res = Ri_inverse(x); break;
case OPTION_NTHPRIME:
res = nth_prime(to_int64(x), threads); break;
case OPTION_S1:
res = S1(x, threads); break;
case OPTION_S2_EASY:
res = S2_easy(x, threads); break;
case OPTION_S2_HARD:
res = S2_hard(x, threads); break;
case OPTION_S2_TRIVIAL:
res = S2_trivial(x, threads); break;
#ifdef HAVE_INT128_T
case OPTION_DELEGLISE_RIVAT_PARALLEL3:
res = pi_deleglise_rivat_parallel3(x, threads); break;
#endif
}
if (print_result())
{
if (print_status())
cout << endl;
cout << res << endl;
if (opt.time)
print_seconds(get_wtime() - time);
}
}
catch (calculator::error& e)
{
#ifdef HAVE_MPI
MPI_Finalize();
#endif
cerr << e.what() << "." << endl
<< "Try `primecount --help' for more information." << endl;
return 1;
}
catch (exception& e)
{
#ifdef HAVE_MPI
MPI_Finalize();
#endif
cerr << "Error: " << e.what() << "." << endl
<< "Try `primecount --help' for more information." << endl;
return 1;
}
#ifdef HAVE_MPI
MPI_Finalize();
#endif
return 0;
}
<commit_msg>Remove comment<commit_after>///
/// @file main.cpp
/// @brief primecount console application.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "cmdoptions.hpp"
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <calculator.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <PhiTiny.hpp>
#include <S1.hpp>
#include <S2.hpp>
#include <stdint.h>
#include <exception>
#include <iostream>
#include <limits>
#include <string>
#ifdef HAVE_MPI
#include <mpi.h>
#endif
using namespace std;
using namespace primecount;
namespace primecount {
int64_t to_int64(maxint_t x)
{
if (x > numeric_limits<int64_t>::max())
throw primecount_error("this is a 63-bit function, x must be < 2^63");
return (int64_t) x;
}
maxint_t P2(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("P2(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
if (x <= numeric_limits<int64_t>::max())
return P2((int64_t) x, y, threads);
else
return P2(x, y, threads);
}
maxint_t S1(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S1(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S1((int64_t) x, y, c, threads);
else
return S1(x, y, c, threads);
}
maxint_t S2_trivial(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_trivial(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S2_trivial((int64_t) x, y, z, c, threads);
else
return S2_trivial(x, y, z, c, threads);
}
maxint_t S2_easy(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_easy(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
if (x <= numeric_limits<int64_t>::max())
return S2_easy((int64_t) x, y, z, c, threads);
else
return S2_easy(x, y, z, c, threads);
}
maxint_t S2_hard(maxint_t x, int threads)
{
if (x < 1)
return 0;
double alpha = get_alpha_deleglise_rivat(x);
string limit = get_max_x(alpha);
if (x > to_maxint(limit))
throw primecount_error("S2_hard(x): x must be <= " + limit);
if (print_status())
set_print_variables(true);
int64_t y = (int64_t) (iroot<3>(x) * alpha);
int64_t z = (int64_t) (x / y);
int64_t c = PhiTiny::get_c(y);
maxint_t s2_hard_approx = Ri(x);
if (x <= numeric_limits<int64_t>::max())
return S2_hard((int64_t) x, y, z, c, (int64_t) s2_hard_approx, threads);
else
return S2_hard(x, y, z, c, s2_hard_approx, threads);
}
} // namespace
int main (int argc, char* argv[])
{
#ifdef HAVE_MPI
MPI_Init(&argc, &argv);
#endif
try
{
CmdOptions opt = parseOptions(argc, argv);
double time = get_wtime();
maxint_t x = opt.x;
maxint_t res = 0;
int threads = opt.threads;
switch (opt.option)
{
case OPTION_DELEGLISE_RIVAT:
res = pi_deleglise_rivat(x, threads); break;
case OPTION_DELEGLISE_RIVAT1:
res = pi_deleglise_rivat1(to_int64(x)); break;
case OPTION_DELEGLISE_RIVAT2:
res = pi_deleglise_rivat2(to_int64(x)); break;
case OPTION_DELEGLISE_RIVAT_PARALLEL1:
res = pi_deleglise_rivat_parallel1(to_int64(x), threads); break;
case OPTION_DELEGLISE_RIVAT_PARALLEL2:
res = pi_deleglise_rivat_parallel2(to_int64(x), threads); break;
case OPTION_LEGENDRE:
res = pi_legendre(to_int64(x), threads); break;
case OPTION_LEHMER:
res = pi_lehmer(to_int64(x), threads); break;
case OPTION_LMO:
res = pi_lmo(to_int64(x), threads); break;
case OPTION_LMO1:
res = pi_lmo1(to_int64(x)); break;
case OPTION_LMO2:
res = pi_lmo2(to_int64(x)); break;
case OPTION_LMO3:
res = pi_lmo3(to_int64(x)); break;
case OPTION_LMO4:
res = pi_lmo4(to_int64(x)); break;
case OPTION_LMO5:
res = pi_lmo5(to_int64(x)); break;
case OPTION_LMO_PARALLEL1:
res = pi_lmo_parallel1(to_int64(x), threads); break;
case OPTION_LMO_PARALLEL2:
res = pi_lmo_parallel2(to_int64(x), threads); break;
case OPTION_LMO_PARALLEL3:
res = pi_lmo_parallel3(to_int64(x), threads); break;
case OPTION_MEISSEL:
res = pi_meissel(to_int64(x), threads); break;
case OPTION_PRIMESIEVE:
res = pi_primesieve(to_int64(x), threads); break;
case OPTION_P2:
res = P2(x, threads); break;
case OPTION_PI:
res = pi(x, threads); break;
case OPTION_LI:
res = Li(x); break;
case OPTION_LIINV:
res = Li_inverse(x); break;
case OPTION_RI:
res = Ri(x); break;
case OPTION_RIINV:
res = Ri_inverse(x); break;
case OPTION_NTHPRIME:
res = nth_prime(to_int64(x), threads); break;
case OPTION_S1:
res = S1(x, threads); break;
case OPTION_S2_EASY:
res = S2_easy(x, threads); break;
case OPTION_S2_HARD:
res = S2_hard(x, threads); break;
case OPTION_S2_TRIVIAL:
res = S2_trivial(x, threads); break;
#ifdef HAVE_INT128_T
case OPTION_DELEGLISE_RIVAT_PARALLEL3:
res = pi_deleglise_rivat_parallel3(x, threads); break;
#endif
}
if (print_result())
{
if (print_status())
cout << endl;
cout << res << endl;
if (opt.time)
print_seconds(get_wtime() - time);
}
}
catch (calculator::error& e)
{
#ifdef HAVE_MPI
MPI_Finalize();
#endif
cerr << e.what() << "." << endl
<< "Try `primecount --help' for more information." << endl;
return 1;
}
catch (exception& e)
{
#ifdef HAVE_MPI
MPI_Finalize();
#endif
cerr << "Error: " << e.what() << "." << endl
<< "Try `primecount --help' for more information." << endl;
return 1;
}
#ifdef HAVE_MPI
MPI_Finalize();
#endif
return 0;
}
<|endoftext|> |
<commit_before>#ifndef AUTOMATA_HPP__
#define AUTOMATA_HPP__
#include "state.hpp"
template <typename Tstates, size_t Tstart = 0>
struct Automata {
typedef Tstates states;
static const size_t start = Tstart;
template <typename T>
struct push_state {
typedef
Automata<
typename mseq::push<states, T>::type,
start
> type;
};
template <size_t Tnew_start>
struct start_state {
private:
typedef
Automata<states, Tnew_start>
NewAutomata;
template <typename T>
using functor = typename id_is<Tnew_start>::template functor<T>;
public:
typedef
typename std::enable_if<
mseq::some<states, functor>::value,
NewAutomata
>::type type;
};
};
#endif
<commit_msg>Add create_edge,get_edges_for + Rename push_state + Add final state for Automata<commit_after>#ifndef AUTOMATA_HPP__
#define AUTOMATA_HPP__
#include "edge.hpp"
#include "state.hpp"
template <typename Tstates = mseq::empty, size_t Tstart = 0, typename Tedges = mseq::empty>
struct Automata {
typedef Tedges edges;
typedef Tstates states;
static const size_t start = Tstart;
template <size_t Tn, bool Tfinal = false>
struct create_state {
typedef
Automata<
typename mseq::push<states, State<Tn, Tfinal> >::type,
start
> type;
};
template <size_t Tnew_start>
struct start_state {
private:
typedef
Automata<states, Tnew_start>
NewAutomata;
template <typename T>
using functor = typename id_is<Tnew_start>::template functor<T>;
public:
typedef
typename std::enable_if<
mseq::some<states, functor>::value,
NewAutomata
>::type type;
};
template <size_t Tid>
struct get_state {
private:
template <typename T>
using functor = typename id_is<Tid>::template functor<T>;
public:
typedef
typename mseq::find<states, functor>::type
type;
};
template <size_t Tlhs, size_t Trhs, char Tc>
struct create_edge {
typedef
Automata<
states,
start,
typename mseq::push<edges, Edge<Tlhs, Trhs, Tc> >::type
> type;
};
template <size_t Tid>
struct get_edges_for {
private:
template <typename T>
using functor = typename lhs_is<Tid>::template functor<T>;
public:
typedef
typename mseq::filter<edges, functor>::type
type;
};
};
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <vector>
#include <algorithm>
#include <tr1/unordered_set>
#define PAGE_SIZE 4096
#define SCALE_FACTOR 100
#include "../workload.h"
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "stat file\n");
exit(1);
}
char *name = argv[1];
int fd = open(name, O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
long max_pos = 0;
/* get the file size */
struct stat stats;
if (fstat(fd, &stats) < 0) {
perror("fstat");
exit(1);
}
long file_size = stats.st_size;
/* the numbers of accesses of each page */
int num_accesses = (int) (file_size / sizeof(workload_t));
workload_t *workloads = new workload_t[num_accesses];
ssize_t ret = read(fd, (void *) workloads, file_size);
std::tr1::unordered_set<off_t> pages;
int num_reads = 0;
int num_writes = 0;
int max_size = 0;
int min_size = INT_MAX;
long tot_size = 0;
for (int i = 0; i < num_accesses; i++) {
off_t page_off = ROUND_PAGE(workloads[i].off);
if (max_size < workloads[i].size)
max_size = workloads[i].size;
if (min_size > workloads[i].size)
min_size = workloads[i].size;
tot_size += workloads[i].size;
off_t last_page = ROUNDUP_PAGE(workloads[i].off + workloads[i].size);
int num_pages = (last_page - page_off) / PAGE_SIZE;
for (; page_off < last_page; page_off += PAGE_SIZE)
pages.insert(page_off);
if (workloads[i].read)
num_reads += num_pages;
else
num_writes += num_pages;
}
printf("min request size: %d, max req size: %d, avg size: %ld\n",
min_size, max_size, tot_size / num_accesses);
printf("there are %d reads\n", num_reads);
printf("there are %d writes\n", num_writes);
printf("there are %ld accessed pages\n", pages.size());
}
<commit_msg>print number of accesses in workload stat.<commit_after>#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <vector>
#include <algorithm>
#include <tr1/unordered_set>
#define PAGE_SIZE 4096
#define SCALE_FACTOR 100
#include "../workload.h"
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "stat file\n");
exit(1);
}
char *name = argv[1];
int fd = open(name, O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
long max_pos = 0;
/* get the file size */
struct stat stats;
if (fstat(fd, &stats) < 0) {
perror("fstat");
exit(1);
}
long file_size = stats.st_size;
/* the numbers of accesses of each page */
int num_accesses = (int) (file_size / sizeof(workload_t));
workload_t *workloads = new workload_t[num_accesses];
ssize_t ret = read(fd, (void *) workloads, file_size);
std::tr1::unordered_set<off_t> pages;
int num_reads = 0;
int num_writes = 0;
int max_size = 0;
int min_size = INT_MAX;
long tot_size = 0;
for (int i = 0; i < num_accesses; i++) {
off_t page_off = ROUND_PAGE(workloads[i].off);
if (max_size < workloads[i].size)
max_size = workloads[i].size;
if (min_size > workloads[i].size)
min_size = workloads[i].size;
tot_size += workloads[i].size;
off_t last_page = ROUNDUP_PAGE(workloads[i].off + workloads[i].size);
int num_pages = (last_page - page_off) / PAGE_SIZE;
for (; page_off < last_page; page_off += PAGE_SIZE)
pages.insert(page_off);
if (workloads[i].read)
num_reads += num_pages;
else
num_writes += num_pages;
}
printf("min request size: %d, max req size: %d, avg size: %ld\n",
min_size, max_size, tot_size / num_accesses);
printf("there are %d accesses\n", num_accesses);
printf("there are %d reads\n", num_reads);
printf("there are %d writes\n", num_writes);
printf("there are %ld accessed pages\n", pages.size());
}
<|endoftext|> |
<commit_before>// @(#)root/main:$Name: $:$Id: ssh2rpd.cxx,v 1.9 2005/10/07 10:28:54 rdm Exp $
// Author: G Ganis 10/5/2007
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Launching program for remote ROOT sessions //
// //
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "TInterpreter.h"
#include "TROOT.h"
#include "TApplication.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
static Int_t MakeCleanupScript(Int_t loglevel);
static FILE *RedirectOutput(TString &logfile, const char *loc);
static const char *apname = "roots";
//______________________________________________________________________________
int main(int argc, char **argv)
{
// The main program: start a TApplication which connects back to the client.
// Prepare the application
if (argc < 4) {
fprintf(stderr, "%s: insufficient input:"
" client URL must to be provided\n", apname);
gSystem->Exit(1);
}
// Parse the debug level
int loglevel = -1;
TString argdbg(argv[3]);
if (argdbg.BeginsWith("-d=")) {
argdbg.ReplaceAll("-d=","");
loglevel = argdbg.Atoi();
}
if (loglevel > 0) {
fprintf(stderr,"%s: Starting remote session on %s\n", apname, gSystem->HostName());
if (loglevel > 1) {
fprintf(stderr,"%s: argc: %d\n", apname, argc);
for (Int_t i = 0; i < argc; i++)
fprintf(stderr,"%s: argv[%d]: %s\n", apname, i, argv[i]);
}
}
// Cleanup script
if (MakeCleanupScript(loglevel) != 0)
fprintf(stderr,"%s: Error: failed to create cleanup script\n", apname);
// Redirect the output
TString logfile;
FILE *fLog = RedirectOutput(logfile, ((loglevel > 1) ? apname : 0));
if (fLog) {
if (loglevel > 0)
fprintf(stderr,"%s: output redirected to %s\n", apname, logfile.Data());
} else {
fprintf(stderr,"%s: problems redirecting output\n", apname);
gSystem->Exit(1);
}
// Url to contact back
TString url = argv[1];
// Like in batch mode
gROOT->SetBatch();
// Enable autoloading
gInterpreter->EnableAutoLoading();
// Instantiate the TApplication object to be run
TPluginHandler *h = 0;
TApplication *theApp = 0;
if ((h = gROOT->GetPluginManager()->FindHandler("TApplication","server"))) {
if (h->LoadPlugin() == 0) {
theApp = (TApplication *) h->ExecPlugin(4, &argc, argv, fLog, logfile.Data());
} else {
fprintf(stderr, "%s: failed to load plugin for TApplicationServer\n", apname);
}
} else {
fprintf(stderr, "%s: failed to find plugin for TApplicationServer\n", apname);
}
// Run it
if (theApp) {
theApp->Run();
} else {
fprintf(stderr, "%s: failed to instantiate TApplicationServer\n", apname);
gSystem->Exit(1);
}
// Done
gSystem->Exit(0);
}
//______________________________________________________________________________
FILE *RedirectOutput(TString &logfile, const char *loc)
{
// Redirect stdout to 'logfile'. This log file will be flushed to the
// client or master after each command.
// On success return a pointer to the open log file. Return 0 on failure.
if (loc)
fprintf(stderr,"%s: RedirectOutput: enter\n", loc);
// Log file under $TEMP
logfile = Form("%s/roots-%d-%d.log", gSystem->TempDirectory(),
gSystem->GetUid(), gSystem->GetPid());
const char *lfn = logfile.Data();
if (loc)
fprintf(stderr,"%s: Path to log file: %s\n", loc, lfn);
if (loc)
fprintf(stderr,"%s: RedirectOutput: reopen %s\n", loc, lfn);
FILE *flog = freopen(lfn, "w", stdout);
if (!flog) {
fprintf(stderr,"%s: RedirectOutput: could not freopen stdout\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: dup2 ...\n", loc);
if ((dup2(fileno(stdout), fileno(stderr))) < 0) {
fprintf(stderr,"%s: RedirectOutput: could not redirect stderr\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: read open ...\n", loc);
FILE *fLog = fopen(lfn, "r");
if (!fLog) {
fprintf(stderr,"%s: RedirectOutput: could not open logfile %s\n", loc, lfn);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: done!\n", loc);
// We are done
return fLog;
}
//______________________________________________________________________________
Int_t MakeCleanupScript(Int_t loglevel)
{
// Create a script that can be executed to cleanup this process in case of
// problems. Return 0 on success, -1 in case of any problem.
// The file path
TString cleanup = Form("%s/roots-%d-%d.cleanup", gSystem->TempDirectory(),
gSystem->GetUid(), gSystem->GetPid());
// Open the file
FILE *fc = fopen(cleanup.Data(), "w");
if (fc) {
fprintf(fc,"#!/bin/sh\n");
fprintf(fc,"\n");
fprintf(fc,"# Cleanup script for roots process %d\n", gSystem->GetPid());
fprintf(fc,"# Usage:\n");
fprintf(fc,"# ssh %s@%s %s\n", gSystem->Getenv("USER"), gSystem->HostName(), cleanup.Data());
fprintf(fc,"#\n");
fprintf(fc,"kill -9 %d", gSystem->GetPid());
// Close file
fclose(fc);
if (chmod(cleanup.Data(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
fprintf(stderr,"%s: Error: cannot make script %s executable\n", apname, cleanup.Data());
unlink(cleanup.Data());
return -1;
} else {
if (loglevel > 1)
fprintf(stderr,"%s: Path to cleanup script %s\n", apname, cleanup.Data());
}
} else {
fprintf(stderr,"%s: Error: file %s could not be created\n", apname, cleanup.Data());
return -1;
}
// Done
return 0;
}
<commit_msg>From Gerri: - Fix coding conventions<commit_after>// @(#)root/main:$Name: $:$Id: roots.cxx,v 1.2 2007/05/10 16:25:13 rdm Exp $
// Author: G Ganis 10/5/2007
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Launching program for remote ROOT sessions //
// //
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "TInterpreter.h"
#include "TROOT.h"
#include "TApplication.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
static Int_t MakeCleanupScript(Int_t loglevel);
static FILE *RedirectOutput(TString &logfile, const char *loc);
static const char *gAppName = "roots";
//______________________________________________________________________________
int main(int argc, char **argv)
{
// The main program: start a TApplication which connects back to the client.
// Prepare the application
if (argc < 4) {
fprintf(stderr, "%s: insufficient input:"
" client URL must to be provided\n", gAppName);
gSystem->Exit(1);
}
// Parse the debug level
int loglevel = -1;
TString argdbg(argv[3]);
if (argdbg.BeginsWith("-d=")) {
argdbg.ReplaceAll("-d=","");
loglevel = argdbg.Atoi();
}
if (loglevel > 0) {
fprintf(stderr,"%s: Starting remote session on %s\n", gAppName, gSystem->HostName());
if (loglevel > 1) {
fprintf(stderr,"%s: argc: %d\n", gAppName, argc);
for (Int_t i = 0; i < argc; i++)
fprintf(stderr,"%s: argv[%d]: %s\n", gAppName, i, argv[i]);
}
}
// Cleanup script
if (MakeCleanupScript(loglevel) != 0)
fprintf(stderr,"%s: Error: failed to create cleanup script\n", gAppName);
// Redirect the output
TString logfile;
FILE *fLog = RedirectOutput(logfile, ((loglevel > 1) ? gAppName : 0));
if (fLog) {
if (loglevel > 0)
fprintf(stderr,"%s: output redirected to %s\n", gAppName, logfile.Data());
} else {
fprintf(stderr,"%s: problems redirecting output\n", gAppName);
gSystem->Exit(1);
}
// Url to contact back
TString url = argv[1];
// Like in batch mode
gROOT->SetBatch();
// Enable autoloading
gInterpreter->EnableAutoLoading();
// Instantiate the TApplication object to be run
TPluginHandler *h = 0;
TApplication *theApp = 0;
if ((h = gROOT->GetPluginManager()->FindHandler("TApplication","server"))) {
if (h->LoadPlugin() == 0) {
theApp = (TApplication *) h->ExecPlugin(4, &argc, argv, fLog, logfile.Data());
} else {
fprintf(stderr, "%s: failed to load plugin for TApplicationServer\n", gAppName);
}
} else {
fprintf(stderr, "%s: failed to find plugin for TApplicationServer\n", gAppName);
}
// Run it
if (theApp) {
theApp->Run();
} else {
fprintf(stderr, "%s: failed to instantiate TApplicationServer\n", gAppName);
gSystem->Exit(1);
}
// Done
gSystem->Exit(0);
}
//______________________________________________________________________________
FILE *RedirectOutput(TString &logfile, const char *loc)
{
// Redirect stdout to 'logfile'. This log file will be flushed to the
// client or master after each command.
// On success return a pointer to the open log file. Return 0 on failure.
if (loc)
fprintf(stderr,"%s: RedirectOutput: enter\n", loc);
// Log file under $TEMP
logfile = Form("%s/roots-%d-%d.log", gSystem->TempDirectory(),
gSystem->GetUid(), gSystem->GetPid());
const char *lfn = logfile.Data();
if (loc)
fprintf(stderr,"%s: Path to log file: %s\n", loc, lfn);
if (loc)
fprintf(stderr,"%s: RedirectOutput: reopen %s\n", loc, lfn);
FILE *flog = freopen(lfn, "w", stdout);
if (!flog) {
fprintf(stderr,"%s: RedirectOutput: could not freopen stdout\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: dup2 ...\n", loc);
if ((dup2(fileno(stdout), fileno(stderr))) < 0) {
fprintf(stderr,"%s: RedirectOutput: could not redirect stderr\n", loc);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: read open ...\n", loc);
FILE *fLog = fopen(lfn, "r");
if (!fLog) {
fprintf(stderr,"%s: RedirectOutput: could not open logfile %s\n", loc, lfn);
return 0;
}
if (loc)
fprintf(stderr,"%s: RedirectOutput: done!\n", loc);
// We are done
return fLog;
}
//______________________________________________________________________________
Int_t MakeCleanupScript(Int_t loglevel)
{
// Create a script that can be executed to cleanup this process in case of
// problems. Return 0 on success, -1 in case of any problem.
// The file path
TString cleanup = Form("%s/roots-%d-%d.cleanup", gSystem->TempDirectory(),
gSystem->GetUid(), gSystem->GetPid());
// Open the file
FILE *fc = fopen(cleanup.Data(), "w");
if (fc) {
fprintf(fc,"#!/bin/sh\n");
fprintf(fc,"\n");
fprintf(fc,"# Cleanup script for roots process %d\n", gSystem->GetPid());
fprintf(fc,"# Usage:\n");
fprintf(fc,"# ssh %s@%s %s\n", gSystem->Getenv("USER"), gSystem->HostName(), cleanup.Data());
fprintf(fc,"#\n");
fprintf(fc,"kill -9 %d", gSystem->GetPid());
// Close file
fclose(fc);
if (chmod(cleanup.Data(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
fprintf(stderr,"%s: Error: cannot make script %s executable\n", gAppName, cleanup.Data());
unlink(cleanup.Data());
return -1;
} else {
if (loglevel > 1)
fprintf(stderr,"%s: Path to cleanup script %s\n", gAppName, cleanup.Data());
}
} else {
fprintf(stderr,"%s: Error: file %s could not be created\n", gAppName, cleanup.Data());
return -1;
}
// Done
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/requestdialog.h"
#include "qt/pivx/forms/ui_requestdialog.h"
#include <QListView>
#include "qt/pivx/qtutils.h"
#include "guiutil.h"
#include "optionsmodel.h"
RequestDialog::RequestDialog(QWidget *parent) :
FocusedDialog(parent),
ui(new Ui::RequestDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
setCssProperty(ui->frame, "container-dialog");
// Text
setCssProperty(ui->labelTitle, "text-title-dialog");
setCssProperty(ui->labelMessage, "text-main-grey");
// Combo Coins
setCssProperty(ui->comboBoxCoin, "btn-combo-coins");
setCssProperty(ui->comboContainer, "container-purple");
// Label
setCssProperty(ui->labelSubtitleLabel, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditLabel, true);
// Amount
setCssProperty(ui->labelSubtitleAmount, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditAmount, true);
GUIUtil::setupAmountWidget(ui->lineEditAmount, this);
// Description
setCssProperty(ui->labelSubtitleDescription, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditDescription, true);
// Stack
ui->stack->setCurrentIndex(pos);
// Request QR Page
// Address
ui->labelAddress->setText(tr("Error"));
setCssProperty(ui->labelAddress, "text-main-grey-big");
// Buttons
setCssProperty(ui->btnEsc, "ic-close");
setCssProperty(ui->btnCancel, "btn-dialog-cancel");
setCssBtnPrimary(ui->btnSave);
setCssBtnPrimary(ui->btnCopyAddress);
setCssBtnPrimary(ui->btnCopyUrl);
connect(ui->btnCancel, &QPushButton::clicked, this, &RequestDialog::close);
connect(ui->btnEsc, &QPushButton::clicked, this, &RequestDialog::close);
connect(ui->btnSave, &QPushButton::clicked, this, &RequestDialog::accept);
// TODO: Change copy address for save image (the method is already implemented in other class called exportQr or something like that)
connect(ui->btnCopyAddress, &QPushButton::clicked, this, &RequestDialog::onCopyClicked);
connect(ui->btnCopyUrl, &QPushButton::clicked, this, &RequestDialog::onCopyUriClicked);
}
void RequestDialog::setWalletModel(WalletModel *model)
{
this->walletModel = model;
ui->comboBoxCoin->setText(BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()));
}
void RequestDialog::setPaymentRequest(bool isPaymentRequest)
{
this->isPaymentRequest = isPaymentRequest;
if (!this->isPaymentRequest) {
ui->labelMessage->setText(tr("Creates an address to receive coin delegations and be able to stake them."));
ui->labelTitle->setText(tr("New Cold Staking Address"));
ui->labelSubtitleAmount->setText(tr("Amount (optional)"));
}
}
void RequestDialog::accept()
{
if (walletModel) {
QString labelStr = ui->lineEditLabel->text();
if (!this->isPaymentRequest) {
// Add specific checks for cold staking address creation
if (labelStr.isEmpty()) {
inform(tr("Address label cannot be empty"));
return;
}
}
int displayUnit = walletModel->getOptionsModel()->getDisplayUnit();
auto value = ui->lineEditAmount->text().isEmpty() ? -1 :
GUIUtil::parseValue(ui->lineEditAmount->text(), displayUnit);
if (value <= 0) {
inform(tr("Invalid amount"));
return;
}
info = new SendCoinsRecipient();
info->label = labelStr;
info->amount = value;
info->message = ui->lineEditDescription->text();
// address
std::string label = info->label.isEmpty() ? "" : info->label.toStdString();
QString title;
CallResult<Destination> r;
if (this->isPaymentRequest) {
r = walletModel->getNewAddress(label);
title = tr("Request for ") + BitcoinUnits::format(displayUnit, info->amount, false, BitcoinUnits::separatorAlways) + " " + BitcoinUnits::name(displayUnit);
} else {
r = walletModel->getNewStakingAddress(label);
title = tr("Cold Staking Address Generated");
}
if (!r) {
// TODO: notify user about this error
close();
return;
}
info->address = QString::fromStdString(r.getObjResult()->ToString());
ui->labelTitle->setText(title);
updateQr(info->address);
ui->labelAddress->setText(info->address);
ui->buttonsStack->setVisible(false);
pos = 1;
ui->stack->setCurrentIndex(pos);
}
}
void RequestDialog::onCopyClicked()
{
if (info) {
GUIUtil::setClipboard(info->address);
res = 2;
QDialog::accept();
}
}
void RequestDialog::onCopyUriClicked()
{
if (info) {
GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(*info));
res = 1;
QDialog::accept();
}
}
void RequestDialog::showEvent(QShowEvent *event)
{
if (ui->lineEditAmount) ui->lineEditAmount->setFocus();
}
void RequestDialog::updateQr(const QString& str)
{
QString uri = GUIUtil::formatBitcoinURI(*info);
ui->labelQrImg->setText("");
QString error;
QPixmap pixmap = encodeToQr(uri, error);
if (!pixmap.isNull()) {
ui->labelQrImg->setPixmap(pixmap.scaled(ui->labelQrImg->width(), ui->labelQrImg->height()));
} else {
ui->labelQrImg->setText(!error.isEmpty() ? error : "Error encoding address");
}
}
void RequestDialog::inform(const QString& text)
{
if (!snackBar)
snackBar = new SnackBar(nullptr, this);
snackBar->setText(text);
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
}
RequestDialog::~RequestDialog()
{
delete ui;
}
<commit_msg>GUI: Allow for zero/empty value for new cold staking addresses<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/requestdialog.h"
#include "qt/pivx/forms/ui_requestdialog.h"
#include <QListView>
#include "qt/pivx/qtutils.h"
#include "guiutil.h"
#include "optionsmodel.h"
RequestDialog::RequestDialog(QWidget *parent) :
FocusedDialog(parent),
ui(new Ui::RequestDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
setCssProperty(ui->frame, "container-dialog");
// Text
setCssProperty(ui->labelTitle, "text-title-dialog");
setCssProperty(ui->labelMessage, "text-main-grey");
// Combo Coins
setCssProperty(ui->comboBoxCoin, "btn-combo-coins");
setCssProperty(ui->comboContainer, "container-purple");
// Label
setCssProperty(ui->labelSubtitleLabel, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditLabel, true);
// Amount
setCssProperty(ui->labelSubtitleAmount, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditAmount, true);
GUIUtil::setupAmountWidget(ui->lineEditAmount, this);
// Description
setCssProperty(ui->labelSubtitleDescription, "text-title2-dialog");
setCssEditLineDialog(ui->lineEditDescription, true);
// Stack
ui->stack->setCurrentIndex(pos);
// Request QR Page
// Address
ui->labelAddress->setText(tr("Error"));
setCssProperty(ui->labelAddress, "text-main-grey-big");
// Buttons
setCssProperty(ui->btnEsc, "ic-close");
setCssProperty(ui->btnCancel, "btn-dialog-cancel");
setCssBtnPrimary(ui->btnSave);
setCssBtnPrimary(ui->btnCopyAddress);
setCssBtnPrimary(ui->btnCopyUrl);
connect(ui->btnCancel, &QPushButton::clicked, this, &RequestDialog::close);
connect(ui->btnEsc, &QPushButton::clicked, this, &RequestDialog::close);
connect(ui->btnSave, &QPushButton::clicked, this, &RequestDialog::accept);
// TODO: Change copy address for save image (the method is already implemented in other class called exportQr or something like that)
connect(ui->btnCopyAddress, &QPushButton::clicked, this, &RequestDialog::onCopyClicked);
connect(ui->btnCopyUrl, &QPushButton::clicked, this, &RequestDialog::onCopyUriClicked);
}
void RequestDialog::setWalletModel(WalletModel *model)
{
this->walletModel = model;
ui->comboBoxCoin->setText(BitcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()));
}
void RequestDialog::setPaymentRequest(bool isPaymentRequest)
{
this->isPaymentRequest = isPaymentRequest;
if (!this->isPaymentRequest) {
ui->labelMessage->setText(tr("Creates an address to receive coin delegations and be able to stake them."));
ui->labelTitle->setText(tr("New Cold Staking Address"));
ui->labelSubtitleAmount->setText(tr("Amount (optional)"));
}
}
void RequestDialog::accept()
{
if (walletModel) {
QString labelStr = ui->lineEditLabel->text();
if (!this->isPaymentRequest) {
// Add specific checks for cold staking address creation
if (labelStr.isEmpty()) {
inform(tr("Address label cannot be empty"));
return;
}
}
int displayUnit = walletModel->getOptionsModel()->getDisplayUnit();
auto value = ui->lineEditAmount->text().isEmpty() ? 0 :
GUIUtil::parseValue(ui->lineEditAmount->text(), displayUnit);
if (value <= 0 && this->isPaymentRequest) {
inform(tr("Invalid amount"));
return;
}
info = new SendCoinsRecipient();
info->label = labelStr;
info->amount = value;
info->message = ui->lineEditDescription->text();
// address
std::string label = info->label.isEmpty() ? "" : info->label.toStdString();
QString title;
CallResult<Destination> r;
if (this->isPaymentRequest) {
r = walletModel->getNewAddress(label);
title = tr("Request for ") + BitcoinUnits::format(displayUnit, info->amount, false, BitcoinUnits::separatorAlways) + " " + BitcoinUnits::name(displayUnit);
} else {
r = walletModel->getNewStakingAddress(label);
title = tr("Cold Staking Address Generated");
}
if (!r) {
// TODO: notify user about this error
close();
return;
}
info->address = QString::fromStdString(r.getObjResult()->ToString());
ui->labelTitle->setText(title);
updateQr(info->address);
ui->labelAddress->setText(info->address);
ui->buttonsStack->setVisible(false);
pos = 1;
ui->stack->setCurrentIndex(pos);
}
}
void RequestDialog::onCopyClicked()
{
if (info) {
GUIUtil::setClipboard(info->address);
res = 2;
QDialog::accept();
}
}
void RequestDialog::onCopyUriClicked()
{
if (info) {
GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(*info));
res = 1;
QDialog::accept();
}
}
void RequestDialog::showEvent(QShowEvent *event)
{
if (ui->lineEditAmount) ui->lineEditAmount->setFocus();
}
void RequestDialog::updateQr(const QString& str)
{
QString uri = GUIUtil::formatBitcoinURI(*info);
ui->labelQrImg->setText("");
QString error;
QPixmap pixmap = encodeToQr(uri, error);
if (!pixmap.isNull()) {
ui->labelQrImg->setPixmap(pixmap.scaled(ui->labelQrImg->width(), ui->labelQrImg->height()));
} else {
ui->labelQrImg->setText(!error.isEmpty() ? error : "Error encoding address");
}
}
void RequestDialog::inform(const QString& text)
{
if (!snackBar)
snackBar = new SnackBar(nullptr, this);
snackBar->setText(text);
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
}
RequestDialog::~RequestDialog()
{
delete ui;
}
<|endoftext|> |
<commit_before>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007, Niklas Sorensson
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 "System.h"
#if defined(__linux__)
#include <cstdio>
#include <cstdlib>
using namespace Minisat;
static inline int memReadStat(int field)
{
char name[256];
pid_t pid = getpid();
int value;
sprintf(name, "/proc/%d/statm", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
for (; field >= 0; field--)
if (fscanf(in, "%d", &value) != 1)
printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
fclose(in);
return value;
}
static inline int memReadPeak(void)
{
char name[256];
pid_t pid = getpid();
sprintf(name, "/proc/%d/status", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
// Find the correct line, beginning with "VmHWM:":
uint32_t peak_kb = 0;
while (!feof(in) && fscanf(in, "VmHWM: %d kB", &peak_kb) != 1)
while (!feof(in) && fgetc(in) != '\n')
;
fclose(in);
return peak_kb;
}
#if 0
double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
#else
double Minisat::memUsed() { return (double)memReadPeak() / 1024; }
#endif
#elif defined(__FreeBSD__)
double Minisat::memUsed(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_maxrss / 1024; }
#elif defined(__APPLE__)
#include <malloc/malloc.h>
double Minisat::memUsed(void) {
malloc_statistics_t t;
malloc_zone_statistics(NULL, &t);
return (double)t.max_size_in_use / (1024*1024); }
#else
double Minisat::memUsed() {
return 0; }
#endif
<commit_msg>Added a TODO on splitting the memory usage functions into virtual and RSS.<commit_after>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007, Niklas Sorensson
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 "System.h"
#if defined(__linux__)
#include <cstdio>
#include <cstdlib>
using namespace Minisat;
// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and
// one for reading the current virtual memory size.
static inline int memReadStat(int field)
{
char name[256];
pid_t pid = getpid();
int value;
sprintf(name, "/proc/%d/statm", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
for (; field >= 0; field--)
if (fscanf(in, "%d", &value) != 1)
printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
fclose(in);
return value;
}
static inline int memReadPeak(void)
{
char name[256];
pid_t pid = getpid();
sprintf(name, "/proc/%d/status", pid);
FILE* in = fopen(name, "rb");
if (in == NULL) return 0;
// Find the correct line, beginning with "VmHWM:":
uint32_t peak_kb = 0;
while (!feof(in) && fscanf(in, "VmHWM: %d kB", &peak_kb) != 1)
while (!feof(in) && fgetc(in) != '\n')
;
fclose(in);
return peak_kb;
}
#if 0
double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
#else
double Minisat::memUsed() { return (double)memReadPeak() / 1024; }
#endif
#elif defined(__FreeBSD__)
double Minisat::memUsed(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_maxrss / 1024; }
#elif defined(__APPLE__)
#include <malloc/malloc.h>
double Minisat::memUsed(void) {
malloc_statistics_t t;
malloc_zone_statistics(NULL, &t);
return (double)t.max_size_in_use / (1024*1024); }
#else
double Minisat::memUsed() {
return 0; }
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "utils/loading_shared_values.hh"
#include "utils/loading_cache.hh"
#include <seastar/core/aligned_buffer.hh>
#include <seastar/core/file.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/sleep.hh>
#include <seastar/util/defer.hh>
#include "seastarx.hh"
#include "tests/test-utils.hh"
#include "tmpdir.hh"
#include "log.hh"
#include <vector>
#include <numeric>
#include <random>
/// Get a random integer in the [0, max) range.
/// \param upper bound of the random value range
/// \return The uniformly distributed random integer from the [0, \ref max) range.
static int rand_int(int max) {
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(0, max - 1); // guaranteed unbiased
return uni(rng);
}
static const sstring test_file_name = "loading_cache_test.txt";
static const sstring test_string = "1";
static bool file_prepared = false;
static constexpr int num_loaders = 1000;
static logging::logger test_logger("loading_cache_test");
static thread_local int load_count;
static const tmpdir& get_tmpdir() {
static thread_local tmpdir tmp;
return tmp;
}
static future<> prepare() {
if (file_prepared) {
return make_ready_future<>();
}
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::create | open_flags::wo).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
auto size = test_string.size() + 1;
auto aligned_size = align_up(size, f.disk_write_dma_alignment());
auto buf = allocate_aligned_buffer<char>(aligned_size, f.disk_write_dma_alignment());
auto wbuf = buf.get();
std::copy_n(test_string.c_str(), size, wbuf);
return f.dma_write(0, wbuf, aligned_size).then([aligned_size, buf = std::move(buf)] (size_t s) {
BOOST_REQUIRE_EQUAL(s, aligned_size);
file_prepared = true;
}).finally([&f] () mutable {
return f.close();
});
});
});
}
static future<sstring> loader(const int& k) {
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::ro).then([] (file f) -> future<sstring> {
return do_with(std::move(f), [] (file& f) -> future<sstring> {
auto size = align_up(test_string.size() + 1, f.disk_read_dma_alignment());
return f.dma_read_exactly<char>(0, size).then([] (auto buf) {
sstring str(buf.get());
BOOST_REQUIRE_EQUAL(str, test_string);
++load_count;
return make_ready_future<sstring>(std::move(str));
}).finally([&f] () mutable {
return f.close();
});
});
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_same_key) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(shared_values.size(), 1);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_different_keys) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called once for each key
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(shared_values.size(), num_loaders);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_rehash) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
// verify that load factor is always in the (0.25, 0.75) range
for (int k = 0; k < num_loaders; ++k) {
shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
}).get();
BOOST_REQUIRE_LE(shared_values.size(), 3 * shared_values.buckets_count() / 4);
}
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
// minimum buckets count (by default) is 16, so don't check for less than 4 elements
for (int k = 0; k < num_loaders - 4; ++k) {
anchors_list.pop_back();
shared_values.rehash();
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
}
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_explicit_eviction) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::vector<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_vec(num_loaders);
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_vec[k] = std::move(entry_ptr);
});
}).get();
int rand_key = rand_int(num_loaders);
BOOST_REQUIRE(shared_values.find(rand_key) != shared_values.end());
anchors_vec[rand_key] = nullptr;
BOOST_REQUIRE_MESSAGE(shared_values.find(rand_key) == shared_values.end(), format("explicit removal for key {} failed", rand_key));
anchors_vec.clear();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_same_key) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_different_keys) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), num_loaders);
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_expiry_eviction) {
return seastar::async([] {
using namespace std::chrono;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 20ms, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE(loading_cache.find(0) != loading_cache.end());
// timers get delayed sometimes (especially in a debug mode)
constexpr int max_retry = 10;
int i = 0;
do_until(
[&] { return i++ > max_retry || loading_cache.find(0) == loading_cache.end(); },
[] { return sleep(40ms); }
).get();
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_reloading) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(num_loaders, 100ms, 20ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
sleep(60ms).get();
BOOST_REQUIRE_MESSAGE(load_count >= 2, format("load_count is {}", load_count));
});
}
SEASTAR_TEST_CASE(test_loading_cache_max_size_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(1, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
for (int i = 0; i < num_loaders; ++i) {
loading_cache.get_ptr(i % 2, loader).discard_result().get();
}
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_TEST_CASE(test_loading_cache_reload_during_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(1, 100ms, 10ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
auto curr_time = lowres_clock::now();
int i = 0;
// this will cause reloading when values are being actively evicted due to the limited cache size
do_until(
[&] { return lowres_clock::now() - curr_time > 1s; },
[&] { return loading_cache.get_ptr(i++ % 2).discard_result(); }
).get();
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
<commit_msg>tests: loading_cache_test: add a tests for a loading_cache::remove(key)/remove(iterator)<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "utils/loading_shared_values.hh"
#include "utils/loading_cache.hh"
#include <seastar/core/aligned_buffer.hh>
#include <seastar/core/file.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/sleep.hh>
#include <seastar/util/defer.hh>
#include "seastarx.hh"
#include "tests/test-utils.hh"
#include "tmpdir.hh"
#include "log.hh"
#include <vector>
#include <numeric>
#include <random>
/// Get a random integer in the [0, max) range.
/// \param upper bound of the random value range
/// \return The uniformly distributed random integer from the [0, \ref max) range.
static int rand_int(int max) {
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(0, max - 1); // guaranteed unbiased
return uni(rng);
}
static const sstring test_file_name = "loading_cache_test.txt";
static const sstring test_string = "1";
static bool file_prepared = false;
static constexpr int num_loaders = 1000;
static logging::logger test_logger("loading_cache_test");
static thread_local int load_count;
static const tmpdir& get_tmpdir() {
static thread_local tmpdir tmp;
return tmp;
}
static future<> prepare() {
if (file_prepared) {
return make_ready_future<>();
}
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::create | open_flags::wo).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
auto size = test_string.size() + 1;
auto aligned_size = align_up(size, f.disk_write_dma_alignment());
auto buf = allocate_aligned_buffer<char>(aligned_size, f.disk_write_dma_alignment());
auto wbuf = buf.get();
std::copy_n(test_string.c_str(), size, wbuf);
return f.dma_write(0, wbuf, aligned_size).then([aligned_size, buf = std::move(buf)] (size_t s) {
BOOST_REQUIRE_EQUAL(s, aligned_size);
file_prepared = true;
}).finally([&f] () mutable {
return f.close();
});
});
});
}
static future<sstring> loader(const int& k) {
return open_file_dma((boost::filesystem::path(get_tmpdir().path) / test_file_name.c_str()).c_str(), open_flags::ro).then([] (file f) -> future<sstring> {
return do_with(std::move(f), [] (file& f) -> future<sstring> {
auto size = align_up(test_string.size() + 1, f.disk_read_dma_alignment());
return f.dma_read_exactly<char>(0, size).then([] (auto buf) {
sstring str(buf.get());
BOOST_REQUIRE_EQUAL(str, test_string);
++load_count;
return make_ready_future<sstring>(std::move(str));
}).finally([&f] () mutable {
return f.close();
});
});
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_same_key) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(shared_values.size(), 1);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_different_keys) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
});
}).get();
// "loader" must be called once for each key
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(shared_values.size(), num_loaders);
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_rehash) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::list<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_list;
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
// verify that load factor is always in the (0.25, 0.75) range
for (int k = 0; k < num_loaders; ++k) {
shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_list.emplace_back(std::move(entry_ptr));
}).get();
BOOST_REQUIRE_LE(shared_values.size(), 3 * shared_values.buckets_count() / 4);
}
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
// minimum buckets count (by default) is 16, so don't check for less than 4 elements
for (int k = 0; k < num_loaders - 4; ++k) {
anchors_list.pop_back();
shared_values.rehash();
BOOST_REQUIRE_GE(shared_values.size(), shared_values.buckets_count() / 4);
}
anchors_list.clear();
});
}
SEASTAR_TEST_CASE(test_loading_shared_values_parallel_loading_explicit_eviction) {
return seastar::async([] {
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_shared_values<int, sstring> shared_values;
std::vector<typename utils::loading_shared_values<int, sstring>::entry_ptr> anchors_vec(num_loaders);
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return shared_values.get_or_load(k, loader).then([&] (auto entry_ptr) {
anchors_vec[k] = std::move(entry_ptr);
});
}).get();
int rand_key = rand_int(num_loaders);
BOOST_REQUIRE(shared_values.find(rand_key) != shared_values.end());
anchors_vec[rand_key] = nullptr;
BOOST_REQUIRE_MESSAGE(shared_values.find(rand_key) == shared_values.end(), format("explicit removal for key {} failed", rand_key));
anchors_vec.clear();
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_same_key) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::fill(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
// "loader" must be called exactly once
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_THREAD_TEST_CASE(test_loading_cache_removing_key) {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 100s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE_EQUAL(load_count, 1);
BOOST_REQUIRE(loading_cache.find(0) != loading_cache.end());
loading_cache.remove(0);
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
}
SEASTAR_THREAD_TEST_CASE(test_loading_cache_removing_iterator) {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 100s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE_EQUAL(load_count, 1);
auto it = loading_cache.find(0);
BOOST_REQUIRE(it != loading_cache.end());
loading_cache.remove(it);
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
}
SEASTAR_TEST_CASE(test_loading_cache_loading_different_keys) {
return seastar::async([] {
using namespace std::chrono;
std::vector<int> ivec(num_loaders);
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
std::iota(ivec.begin(), ivec.end(), 0);
parallel_for_each(ivec, [&] (int& k) {
return loading_cache.get_ptr(k, loader).discard_result();
}).get();
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), num_loaders);
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_expiry_eviction) {
return seastar::async([] {
using namespace std::chrono;
utils::loading_cache<int, sstring> loading_cache(num_loaders, 20ms, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
BOOST_REQUIRE(loading_cache.find(0) != loading_cache.end());
// timers get delayed sometimes (especially in a debug mode)
constexpr int max_retry = 10;
int i = 0;
do_until(
[&] { return i++ > max_retry || loading_cache.find(0) == loading_cache.end(); },
[] { return sleep(40ms); }
).get();
BOOST_REQUIRE(loading_cache.find(0) == loading_cache.end());
});
}
SEASTAR_TEST_CASE(test_loading_cache_loading_reloading) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(num_loaders, 100ms, 20ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
loading_cache.get_ptr(0, loader).discard_result().get();
sleep(60ms).get();
BOOST_REQUIRE_MESSAGE(load_count >= 2, format("load_count is {}", load_count));
});
}
SEASTAR_TEST_CASE(test_loading_cache_max_size_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring> loading_cache(1, 1s, test_logger);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
for (int i = 0; i < num_loaders; ++i) {
loading_cache.get_ptr(i % 2, loader).discard_result().get();
}
BOOST_REQUIRE_EQUAL(load_count, num_loaders);
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
SEASTAR_TEST_CASE(test_loading_cache_reload_during_eviction) {
return seastar::async([] {
using namespace std::chrono;
load_count = 0;
utils::loading_cache<int, sstring, utils::loading_cache_reload_enabled::yes> loading_cache(1, 100ms, 10ms, test_logger, loader);
auto stop_cache_reload = seastar::defer([&loading_cache] { loading_cache.stop().get(); });
prepare().get();
auto curr_time = lowres_clock::now();
int i = 0;
// this will cause reloading when values are being actively evicted due to the limited cache size
do_until(
[&] { return lowres_clock::now() - curr_time > 1s; },
[&] { return loading_cache.get_ptr(i++ % 2).discard_result(); }
).get();
BOOST_REQUIRE_EQUAL(loading_cache.size(), 1);
});
}
<|endoftext|> |
<commit_before>#pragma once
#include "RawBuffer.hpp"
#include "depthai-shared/common/Point3f.hpp"
#include "depthai-shared/common/Timestamp.hpp"
namespace dai {
struct IMUReport {
enum class IMUReportAccuracy : std::uint8_t {
UNRELIABLE = 0,
LOW = 1,
MEDIUM = 2,
HIGH = 3,
};
/**
* The sequence number increments once for each report sent. Gaps
* in the sequence numbers indicate missing or dropped reports.
* Max value 255 after which resets to 0.
*/
int32_t sequence = 0;
/** Accuracy of sensor */
IMUReportAccuracy accuracy = IMUReportAccuracy::UNRELIABLE;
Timestamp timestamp = {};
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReport, sequence, accuracy, timestamp);
/**
* @brief Accelerometer
*
* Units are [m/s^2]
*/
struct IMUReportAccelerometer : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportAccelerometer, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Gyroscope
*
* Units are [rad/s]
*/
struct IMUReportGyroscope : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroscope, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Magnetic field
*
* Units are [uTesla]
*/
struct IMUReportMagneticField : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportMagneticField, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Rotation Vector with Accuracy
*
* Contains quaternion components: i,j,k,real
*/
struct IMUReportRotationVectorWAcc : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component, real */
float accuracy = 0; /**< @brief Accuracy estimate [radians], 0 means no estimate */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportRotationVectorWAcc, i, j, k, real, accuracy, sequence, accuracy, timestamp);
#if 0
/**
* @brief Uncalibrated gyroscope
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportGyroscopeUncalibrated : IMUReport {
/* Units are rad/s */
float x = 0; /**< @brief [rad/s] */
float y = 0; /**< @brief [rad/s] */
float z = 0; /**< @brief [rad/s] */
float biasX = 0; /**< @brief [rad/s] */
float biasY = 0; /**< @brief [rad/s] */
float biasZ = 0; /**< @brief [rad/s] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroscopeUncalibrated, x, y, z, biasX, biasY, biasZ, sequence, accuracy, timestamp);
/**
* @brief Uncalibrated magnetic field
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportMagneticFieldUncalibrated : IMUReport {
/* Units are uTesla */
float x = 0; /**< @brief [uTesla] */
float y = 0; /**< @brief [uTesla] */
float z = 0; /**< @brief [uTesla] */
float biasX = 0; /**< @brief [uTesla] */
float biasY = 0; /**< @brief [uTesla] */
float biasZ = 0; /**< @brief [uTesla] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportMagneticFieldUncalibrated, x, y, z, biasX, biasY, biasZ, sequence, accuracy, timestamp);
/**
* @brief Rotation Vector
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportRotationVector : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component real */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportRotationVector, i, j, k, real, sequence, accuracy, timestamp);
/**
* @brief Gyro integrated rotation vector
*
* See SH-2 Reference Manual for details.
*/
struct IMUReportGyroIntegratedRV : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component real */
float angVelX = 0; /**< @brief Angular velocity about x [rad/s] */
float angVelY = 0; /**< @brief Angular velocity about y [rad/s] */
float angVelZ = 0; /**< @brief Angular velocity about z [rad/s] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroIntegratedRV, i, j, k, real, angVelX, angVelY, angVelZ, sequence, accuracy, timestamp);
#endif
/**
* IMU output
*
* Contains combined output for all possible modes. Only the enabled outputs are populated.
*/
struct IMUPacket {
IMUReportAccelerometer acceleroMeter;
IMUReportGyroscope gyroscope;
IMUReportMagneticField magneticField;
IMUReportRotationVectorWAcc rotationVector;
#if 0
IMUReportAccelerometer rawAcceleroMeter;
IMUReportAccelerometer linearAcceleroMeter;
IMUReportAccelerometer gravity;
IMUReportGyroscope rawGyroscope;
IMUReportGyroscopeUncalibrated gyroscopeUncalibrated;
IMUReportMagneticField rawMagneticField;
IMUReportMagneticFieldUncalibrated magneticFieldUncalibrated;
IMUReportRotationVector gameRotationVector;
IMUReportRotationVectorWAcc geoMagRotationVector;
IMUReportRotationVectorWAcc arvrStabilizedRotationVector;
IMUReportRotationVector arvrStabilizedGameRotationVector;
IMUReportGyroIntegratedRV gyroIntegratedRotationVector;
#endif
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUPacket, acceleroMeter, gyroscope, magneticField, rotationVector);
struct RawIMUData : public RawBuffer {
std::vector<IMUPacket> packets;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::IMUData;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawIMUData, packets);
};
} // namespace dai
<commit_msg>Fix name clash for accuracy field in RotationVector structure<commit_after>#pragma once
#include "RawBuffer.hpp"
#include "depthai-shared/common/Point3f.hpp"
#include "depthai-shared/common/Timestamp.hpp"
namespace dai {
struct IMUReport {
enum class IMUReportAccuracy : std::uint8_t {
UNRELIABLE = 0,
LOW = 1,
MEDIUM = 2,
HIGH = 3,
};
/**
* The sequence number increments once for each report sent. Gaps
* in the sequence numbers indicate missing or dropped reports.
* Max value 255 after which resets to 0.
*/
int32_t sequence = 0;
/** Accuracy of sensor */
IMUReportAccuracy accuracy = IMUReportAccuracy::UNRELIABLE;
Timestamp timestamp = {};
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReport, sequence, accuracy, timestamp);
/**
* @brief Accelerometer
*
* Units are [m/s^2]
*/
struct IMUReportAccelerometer : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportAccelerometer, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Gyroscope
*
* Units are [rad/s]
*/
struct IMUReportGyroscope : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroscope, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Magnetic field
*
* Units are [uTesla]
*/
struct IMUReportMagneticField : IMUReport {
float x = 0;
float y = 0;
float z = 0;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportMagneticField, x, y, z, sequence, accuracy, timestamp);
/**
* @brief Rotation Vector with Accuracy
*
* Contains quaternion components: i,j,k,real
*/
struct IMUReportRotationVectorWAcc : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component, real */
float rotationVectorAccuracy = 0; /**< @brief Accuracy estimate [radians], 0 means no estimate */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportRotationVectorWAcc, i, j, k, real, rotationVectorAccuracy, sequence, accuracy, timestamp);
#if 0
/**
* @brief Uncalibrated gyroscope
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportGyroscopeUncalibrated : IMUReport {
/* Units are rad/s */
float x = 0; /**< @brief [rad/s] */
float y = 0; /**< @brief [rad/s] */
float z = 0; /**< @brief [rad/s] */
float biasX = 0; /**< @brief [rad/s] */
float biasY = 0; /**< @brief [rad/s] */
float biasZ = 0; /**< @brief [rad/s] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroscopeUncalibrated, x, y, z, biasX, biasY, biasZ, sequence, accuracy, timestamp);
/**
* @brief Uncalibrated magnetic field
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportMagneticFieldUncalibrated : IMUReport {
/* Units are uTesla */
float x = 0; /**< @brief [uTesla] */
float y = 0; /**< @brief [uTesla] */
float z = 0; /**< @brief [uTesla] */
float biasX = 0; /**< @brief [uTesla] */
float biasY = 0; /**< @brief [uTesla] */
float biasZ = 0; /**< @brief [uTesla] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportMagneticFieldUncalibrated, x, y, z, biasX, biasY, biasZ, sequence, accuracy, timestamp);
/**
* @brief Rotation Vector
*
* See the SH-2 Reference Manual for more detail.
*/
struct IMUReportRotationVector : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component real */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportRotationVector, i, j, k, real, sequence, accuracy, timestamp);
/**
* @brief Gyro integrated rotation vector
*
* See SH-2 Reference Manual for details.
*/
struct IMUReportGyroIntegratedRV : IMUReport {
float i = 0; /**< @brief Quaternion component i */
float j = 0; /**< @brief Quaternion component j */
float k = 0; /**< @brief Quaternion component k */
float real = 0; /**< @brief Quaternion component real */
float angVelX = 0; /**< @brief Angular velocity about x [rad/s] */
float angVelY = 0; /**< @brief Angular velocity about y [rad/s] */
float angVelZ = 0; /**< @brief Angular velocity about z [rad/s] */
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUReportGyroIntegratedRV, i, j, k, real, angVelX, angVelY, angVelZ, sequence, accuracy, timestamp);
#endif
/**
* IMU output
*
* Contains combined output for all possible modes. Only the enabled outputs are populated.
*/
struct IMUPacket {
IMUReportAccelerometer acceleroMeter;
IMUReportGyroscope gyroscope;
IMUReportMagneticField magneticField;
IMUReportRotationVectorWAcc rotationVector;
#if 0
IMUReportAccelerometer rawAcceleroMeter;
IMUReportAccelerometer linearAcceleroMeter;
IMUReportAccelerometer gravity;
IMUReportGyroscope rawGyroscope;
IMUReportGyroscopeUncalibrated gyroscopeUncalibrated;
IMUReportMagneticField rawMagneticField;
IMUReportMagneticFieldUncalibrated magneticFieldUncalibrated;
IMUReportRotationVector gameRotationVector;
IMUReportRotationVectorWAcc geoMagRotationVector;
IMUReportRotationVectorWAcc arvrStabilizedRotationVector;
IMUReportRotationVector arvrStabilizedGameRotationVector;
IMUReportGyroIntegratedRV gyroIntegratedRotationVector;
#endif
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(IMUPacket, acceleroMeter, gyroscope, magneticField, rotationVector);
struct RawIMUData : public RawBuffer {
std::vector<IMUPacket> packets;
void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override {
nlohmann::json j = *this;
metadata = nlohmann::json::to_msgpack(j);
datatype = DatatypeEnum::IMUData;
};
NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawIMUData, packets);
};
} // namespace dai
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>();
if (w.get() == _p)
w->addRating(1);
else
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto i: peerSessions())
i.first->cap<WhisperPeer>()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
<commit_msg>have not seen crash here. revert unrelated change.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>().get();
if (w == _p)
w->addRating(1);
else
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto i: peerSessions())
i.first->cap<WhisperPeer>()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>();
if (!!w && w.get() == _p)
w->addRating(1);
else if(!!w)
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto& i: peerSessions())
if (auto w = i.first->cap<WhisperPeer>())
if (!!w)
i.first->cap<WhisperPeer>()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
<commit_msg>Revert safeguards. Change peerSessions() use to same as EthereumHost. for(auto) instead of for(auto&).<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>();
if (w.get() == _p)
w->addRating(1);
else
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto i: peerSessions())
i.first->cap<WhisperPeer>()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
<|endoftext|> |
<commit_before>/*
* superviseddescent: A C++11 implementation of the supervised descent
* optimisation method
* File: superviseddescent/matserialisation.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef MATSERIALISATION_HPP_
#define MATSERIALISATION_HPP_
#include "opencv2/core/core.hpp"
#ifdef WIN32
#define BOOST_ALL_DYN_LINK // Link against the dynamic boost lib. Seems to be necessary because we use /MD, i.e. link to the dynamic CRT.
#define BOOST_ALL_NO_LIB // Don't use the automatic library linking by boost with VS2010 (#pragma ...). Instead, we specify everything in cmake.
#endif
#include "boost/serialization/serialization.hpp"
#include "boost/serialization/array.hpp"
/**
* Serialisation for the OpenCV cv::Mat class. Supports text and binary serialisation.
*
* Based on answer from: http://stackoverflow.com/questions/4170745/serializing-opencv-mat-vec3f
* Different method and tests: http://cheind.wordpress.com/2011/12/06/serialization-of-cvmat-objects-using-boost/
*
* Todos:
* - Add the unit tests from above blog.
*/
namespace boost {
namespace serialization {
/**
* Serialize a cv::Mat using boost::serialization.
*
* Supports all types of matrices as well as non-contiguous ones.
*
* @param[in] ar The archive to serialise to (or to serialise from).
* @param[in] mat The matrix to serialise (or deserialise).
* @param[in] version An optional version argument.
*/
template<class Archive>
void serialize(Archive& ar, cv::Mat& mat, const unsigned int /*version*/)
{
int rows, cols, type;
bool continuous;
if (Archive::is_saving::value) {
rows = mat.rows; cols = mat.cols; type = mat.type();
continuous = mat.isContinuous();
}
ar & rows & cols & type & continuous;
if (Archive::is_loading::value)
mat.create(rows, cols, type);
if (continuous) {
const unsigned int data_size = rows * cols * static_cast<int>(mat.elemSize());
ar & boost::serialization::make_array(mat.ptr(), data_size);
}
else {
const unsigned int row_size = cols * static_cast<int>(mat.elemSize());
for (int i = 0; i < rows; i++) {
ar & boost::serialization::make_array(mat.ptr(i), row_size);
}
}
};
} /* namespace serialization */
} /* namespace boost */
#endif /* MATSERIALISATION_HPP_ */
<commit_msg>Changed unsigned int to int in Mat serialisation<commit_after>/*
* superviseddescent: A C++11 implementation of the supervised descent
* optimisation method
* File: superviseddescent/matserialisation.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef MATSERIALISATION_HPP_
#define MATSERIALISATION_HPP_
#include "opencv2/core/core.hpp"
#ifdef WIN32
#define BOOST_ALL_DYN_LINK // Link against the dynamic boost lib. Seems to be necessary because we use /MD, i.e. link to the dynamic CRT.
#define BOOST_ALL_NO_LIB // Don't use the automatic library linking by boost with VS2010 (#pragma ...). Instead, we specify everything in cmake.
#endif
#include "boost/serialization/serialization.hpp"
#include "boost/serialization/array.hpp"
/**
* Serialisation for the OpenCV cv::Mat class. Supports text and binary serialisation.
*
* Based on answer from: http://stackoverflow.com/questions/4170745/serializing-opencv-mat-vec3f
* Different method and tests: http://cheind.wordpress.com/2011/12/06/serialization-of-cvmat-objects-using-boost/
*
* Todos:
* - Add the unit tests from above blog.
*/
namespace boost {
namespace serialization {
/**
* Serialize a cv::Mat using boost::serialization.
*
* Supports all types of matrices as well as non-contiguous ones.
*
* @param[in] ar The archive to serialise to (or to serialise from).
* @param[in] mat The matrix to serialise (or deserialise).
* @param[in] version An optional version argument.
*/
template<class Archive>
void serialize(Archive& ar, cv::Mat& mat, const unsigned int /*version*/)
{
int rows, cols, type;
bool continuous;
if (Archive::is_saving::value) {
rows = mat.rows; cols = mat.cols; type = mat.type();
continuous = mat.isContinuous();
}
ar & rows & cols & type & continuous;
if (Archive::is_loading::value)
mat.create(rows, cols, type);
if (continuous) {
const int data_size = rows * cols * static_cast<int>(mat.elemSize());
ar & boost::serialization::make_array(mat.ptr(), data_size);
}
else {
const int row_size = cols * static_cast<int>(mat.elemSize());
for (int i = 0; i < rows; i++) {
ar & boost::serialization::make_array(mat.ptr(i), row_size);
}
}
};
} /* namespace serialization */
} /* namespace boost */
#endif /* MATSERIALISATION_HPP_ */
<|endoftext|> |
<commit_before>#ifndef TWISTEDCPP_PROTOCOL_CORE
#define TWISTEDCPP_PROTOCOL_CORE
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>
namespace twisted {
template <typename ChildProtocol, typename BufferType>
class protocol_core : public std::enable_shared_from_this<ChildProtocol> {
public:
typedef boost::asio::ip::tcp::socket socket_type;
typedef boost::asio::steady_timer timer_type;
typedef boost::asio::io_service::strand strand_type;
typedef BufferType buffer_type;
typedef typename buffer_type::iterator buffer_iterator;
typedef typename buffer_type::const_iterator const_buffer_iterator;
void set_socket(socket_type socket) {
_socket.reset(new socket_type(std::move(socket)));
_strand = boost::in_place(boost::ref(_socket->get_io_service()));
_timer = boost::in_place(boost::ref(_socket->get_io_service()));
}
void run_protocol() {
auto self = this_protocol().shared_from_this();
boost::asio::spawn(*_strand,
[this, self](boost::asio::yield_context yield) {
_yield = boost::in_place(yield);
try {
for (; _socket->is_open();) {
auto bytes_read =
_socket->async_read_some(asio_buffer(), yield);
checked_on_message(buffer_begin(),
std::next(buffer_begin(), bytes_read));
}
}
catch (boost::system::system_error& connection_error) { // network
// errors
print_connection_error(connection_error);
this_protocol().on_disconnect();
}
catch (const std::exception& excep) { // errors from user protocols
print_exception_what(excep);
}
});
}
template <typename Iter>
void send_message(Iter begin, Iter end) {
boost::asio::async_write(
*_socket, boost::asio::buffer(&*begin, std::distance(begin, end)),
*_yield);
}
template <typename BuffersType>
void send_buffers(const BuffersType& buffers) {
boost::asio::async_write(*_socket, buffers, *_yield);
}
void on_disconnect() {}
void on_error(std::exception_ptr eptr) { std::rethrow_exception(eptr); }
void lose_connection() {
_socket->close();
std::cout << "Closing connection to client" << std::endl;
}
/*
* @brief CRTP wrapper for derived class access
*/
ChildProtocol& this_protocol() {
return *static_cast<ChildProtocol*>(this);
}
/*
* @brief CRTP wrapper for derived class access
*/
const ChildProtocol& this_protocol() const {
return *static_cast<ChildProtocol*>(this);
}
private:
void print_connection_error(
const boost::system::system_error& connection_error) const {
std::cerr << "Client disconnected with code " << connection_error.what()
<< std::endl;
}
void print_exception_what(const std::exception& excep) {
std::cerr << "Killing connection, exception in client handler: "
<< excep.what() << std::endl;
}
void checked_on_message(const_buffer_iterator begin,
const_buffer_iterator end) {
try {
this_protocol().on_message(begin, end);
}
catch (...) {
this_protocol().on_error(std::current_exception());
}
}
buffer_iterator buffer_begin() {
return this_protocol().read_buffer().begin();
}
buffer_iterator buffer_begin() const {
return this_protocol().read_buffer().begin();
}
buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }
buffer_iterator buffer_end() const {
return this_protocol().read_buffer().end();
}
boost::asio::mutable_buffers_1 asio_buffer() {
return boost::asio::buffer(&*buffer_begin(),
std::distance(buffer_begin(), buffer_end()));
}
private:
boost::optional<boost::asio::yield_context> _yield;
std::unique_ptr<socket_type> _socket; // unique_ptr as boost::optional has
// no move support
boost::optional<timer_type> _timer;
boost::optional<strand_type> _strand;
};
} // namespace twisted
#endif
<commit_msg>added move ctors to protocol_core; removed timer for now<commit_after>#ifndef TWISTEDCPP_PROTOCOL_CORE
#define TWISTEDCPP_PROTOCOL_CORE
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>
namespace twisted {
template <typename ChildProtocol, typename BufferType>
class protocol_core : public std::enable_shared_from_this<ChildProtocol> {
public:
typedef boost::asio::ip::tcp::socket socket_type;
typedef boost::asio::steady_timer timer_type;
typedef boost::asio::io_service::strand strand_type;
typedef BufferType buffer_type;
typedef typename buffer_type::iterator buffer_iterator;
typedef typename buffer_type::const_iterator const_buffer_iterator;
protocol_core() = default;
protocol_core(protocol_core&&) = default;
protocol_core& operator=(protocol_core&&) = default;
void set_socket(socket_type socket) {
_socket.reset(new socket_type(std::move(socket)));
_strand = boost::in_place(boost::ref(_socket->get_io_service()));
}
void run_protocol() {
auto self = this_protocol().shared_from_this();
boost::asio::spawn(*_strand,
[this, self](boost::asio::yield_context yield) {
_yield = boost::in_place(yield);
try {
for (; _socket->is_open();) {
auto bytes_read =
_socket->async_read_some(asio_buffer(), yield);
checked_on_message(buffer_begin(),
std::next(buffer_begin(), bytes_read));
}
}
catch (boost::system::system_error& connection_error) { // network
// errors
print_connection_error(connection_error);
this_protocol().on_disconnect();
}
catch (const std::exception& excep) { // errors from user protocols
print_exception_what(excep);
}
});
}
template <typename Iter>
void send_message(Iter begin, Iter end) {
boost::asio::async_write(
*_socket, boost::asio::buffer(&*begin, std::distance(begin, end)),
*_yield);
}
template <typename BuffersType>
void send_buffers(const BuffersType& buffers) {
boost::asio::async_write(*_socket, buffers, *_yield);
}
void on_disconnect() {}
void on_error(std::exception_ptr eptr) { std::rethrow_exception(eptr); }
void lose_connection() {
_socket->close();
std::cout << "Closing connection to client" << std::endl;
}
/*
* @brief CRTP wrapper for derived class access
*/
ChildProtocol& this_protocol() {
return *static_cast<ChildProtocol*>(this);
}
/*
* @brief CRTP wrapper for derived class access
*/
const ChildProtocol& this_protocol() const {
return *static_cast<ChildProtocol*>(this);
}
private:
void print_connection_error(
const boost::system::system_error& connection_error) const {
std::cerr << "Client disconnected with code " << connection_error.what()
<< std::endl;
}
void print_exception_what(const std::exception& excep) {
std::cerr << "Killing connection, exception in client handler: "
<< excep.what() << std::endl;
}
void checked_on_message(const_buffer_iterator begin,
const_buffer_iterator end) {
try {
this_protocol().on_message(begin, end);
}
catch (...) {
this_protocol().on_error(std::current_exception());
}
}
buffer_iterator buffer_begin() {
return this_protocol().read_buffer().begin();
}
buffer_iterator buffer_begin() const {
return this_protocol().read_buffer().begin();
}
buffer_iterator buffer_end() { return this_protocol().read_buffer().end(); }
buffer_iterator buffer_end() const {
return this_protocol().read_buffer().end();
}
boost::asio::mutable_buffers_1 asio_buffer() {
return boost::asio::buffer(&*buffer_begin(),
std::distance(buffer_begin(), buffer_end()));
}
private:
boost::optional<boost::asio::yield_context> _yield;
std::unique_ptr<socket_type> _socket; // unique_ptr as boost::optional has
// no move support
boost::optional<strand_type> _strand;
};
} // namespace twisted
#endif
<|endoftext|> |
<commit_before>#include "dialog.h"
#include "ui_dialog.h"
#include "Serial.hpp"
#include <string>
/**
* @brief Ctor
*/
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
//conn("/dev/ttyUSB0",9600)
{
ui->setupUi(this);
}
/**
* @brief Dtor
*/
Dialog::~Dialog()
{
delete ui;
}
/**
* @slot startClicked
*/
void Dialog::startClicked()
{
std::string data(4,0);
data[0] = (ui->cw ->isChecked() << 4) +
(ui->mic->isChecked() << 3) +
(ui->hlf->isChecked() << 2) +
(ui->ful->isChecked() << 1) +
(ui->wav->isChecked() << 0) ;
data[1] = (ui->slider_speed->value() < 75)?
(ui->slider_speed->value()) : 75 ;
data[3] = ui->slider_steps->value();
//conn.writeString(data);
ui->progressBar->setValue(100);
}
/**
* @slot speedChanged
* @param speed
*/
void Dialog::speedChanged(int speed)
{
ui->label_speed->setText(QString::number(speed) + "%");
}
/**
* @slot stepsChanged
* @param steps
*/
void Dialog::stepsChanged(int steps)
{
ui->label_steps->setText(QString::number(steps * 10) + " steps");
}
/**
* @slot tested
*/
void Dialog::tested()
{
ui->progressBar->setValue(100);
}
<commit_msg>Update dialog.cpp<commit_after>#include "dialog.h"
#include "ui_dialog.h"
#include "Serial.hpp"
#include <string>
/**
* @brief Ctor
*/
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
/**
* @brief Dtor
*/
Dialog::~Dialog()
{
delete ui;
}
/**
* @slot startClicked
*/
void Dialog::startClicked()
{
std::string data(4,0);
data[0] = (ui->cw ->isChecked() << 4) +
(ui->mic->isChecked() << 3) +
(ui->hlf->isChecked() << 2) +
(ui->ful->isChecked() << 1) +
(ui->wav->isChecked() << 0) ;
data[1] = (ui->slider_speed->value() < 75) ? (ui->slider_speed->value()) : 75;
data[3] = ui->slider_steps->value();
ui->progressBar->setValue(100);
}
/**
* @slot speedChanged
* @param speed
*/
void Dialog::speedChanged(int speed)
{
ui->label_speed->setText(QString::number(speed) + "%");
}
/**
* @slot stepsChanged
* @param steps
*/
void Dialog::stepsChanged(int steps)
{
ui->label_steps->setText(QString::number(steps * 10) + " steps");
}
/**
* @slot tested
*/
void Dialog::tested()
{
ui->progressBar->setValue(100);
}
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* Copyright (C) 2001 Philip Philonenko <philonenko@orgacom.ru>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Berlin/Logger.hh>
#include "SDLGL.hh"
// ---------------------------------------------------------------
// class SDL::GLExposeHandler (implementation)
// ---------------------------------------------------------------
void SDL::GLExposeHandler::refresh_screen()
{
Prague::Trace trace("SDL::GLExposeHandler::refresh_screen()");
/*
::Console::Drawable * drawable = ::Console::instance()->drawable();
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_BACK);
glDrawBuffer(GL_FRONT);
glRasterPos2i(0, 0);
glCopyPixels(0, drawable->height(), drawable->width(), drawable->height(),
GL_COLOR);
glFlush();
SDL_UpdateRect(static_cast<SDL::Drawable *>(drawable)->surface(), 0, 0, 0, 0);
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glEnable(GL_SCISSOR_TEST);
glDrawBuffer(GL_BACK);
_glcontext->flush();
*/
}
// ---------------------------------------------------------------
// class SDL::GLContext (implementation)
// ---------------------------------------------------------------
SDL::GLContext::GLContext()
{
Prague::Trace trace("SDL::GLContext::GLContext()");
_drawable =
dynamic_cast<SDL::Drawable *>(::Console::instance()->drawable());
Fresco::PixelCoord w(_drawable->width());
Fresco::PixelCoord h(_drawable->height());
Logger::log(Logger::loader) << "setting video mode GL " << " w="
<< w << " h= " << h << std::endl;
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_Surface * surface = SDL_SetVideoMode(w, h, 0,
SDL_HWSURFACE | SDL_HWPALETTE |
SDL_OPENGL |
SDL_DOUBLEBUF |
SDL_HWACCEL);
SDL_WM_SetCaption("Berlin on SDL (OpenGL)", NULL);
SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &_isDoubleBuffered);
if (!_isDoubleBuffered) {
std::cout << "SDL_Error: " << SDL_GetError() << std::endl;
throw;
}
// HACK: Replace the 'real' drawable with its OpenGL-replacement.
_drawable->_surface = surface;
_drawable->_width = w;
_drawable->_height = h;
int bits;
glGetIntegerv(GL_DEPTH_BITS, &bits);
switch (bits)
{
case 0: _drawable->_depth = 0; break;
case 8: _drawable->_depth = 1; break;
case 16: _drawable->_depth = 2; break;
case 24: _drawable->_depth = 3; break;
case 32: _drawable->_depth = 4; break;
default:
_drawable->_depth = 0;
}
glDrawBuffer(GL_BACK);
// setup PointerManager:
dynamic_cast<SDL::Console *>(::Console::instance())->
set_PointerManager(new SDL::PointerManagerT<GLPointer>);
// setup ExposeHandler:
dynamic_cast<SDL::Console *>(::Console::instance())->
set_ExposeHandler(new SDL::GLExposeHandler(this));
}
SDL::GLContext::~GLContext()
{
Prague::Trace trace("SDL::GLContext::~SDLGLContext()");
}
void SDL::GLContext::flush() {
Prague::Trace trace("SDL::GLContext::flush()");
if (_isDoubleBuffered) {
glFlush();
SDL_GL_SwapBuffers();
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_FRONT);
glDrawBuffer(GL_BACK);
glRasterPos2i(0, 0);
glCopyPixels(0, _drawable->height(), _drawable->width(), _drawable->height(),
GL_COLOR);
glCopyPixels(0, 0, _drawable->width(), _drawable->height(),
GL_COLOR);
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glEnable(GL_SCISSOR_TEST);
} else {
// FIXME: TODO
}
}
// ---------------------------------------------------------------
// class SDL::GLPointer (implementation)
// ---------------------------------------------------------------
SDL::GLPointer::GLPointer(Drawable * drawable, Fresco::Raster_ptr raster)
{
Prague::Trace trace("SDL::GLPointer::GLPointer(...)");
// copy over the Raster:
_raster = Fresco::Raster::_duplicate(raster);
// get screensizes:
_max_y_size = drawable->height();
// copy over the Raster:
_raster = Fresco::Raster::_duplicate(raster);
// Disable SDL default mousecursor
SDL_ShowCursor(0);
// Copy the raster over into the Drawable:
Fresco::Raster::Info info = raster->header();
Fresco::Raster::ColorSeq_var pixels;
Fresco::Raster::Index lower, upper;
lower.x = lower.y = 0;
upper.x = info.width, upper.y = info.height;
raster->store_pixels(lower, upper, pixels);
_origin[0] = _origin[1] = 0;
_size[0] = info.width;
_size[1] = info.height;
_scale[0] = 1.0/drawable->resolution(Fresco::xaxis);
_scale[1] = 1.0/drawable->resolution(Fresco::yaxis);
_cursor = new Uint8[_size[0] * _size[1] * 4]; // RGBA
_saved_area = new Uint8[_size[0] * _size[1] * 3]; //RGB
unsigned pos = 0;
Fresco::Color c;
for (unsigned short y = 0; y != _size[1]; ++y)
for (unsigned short x = 0; x != _size[0]; ++x)
{
c = (*(pixels->get_buffer() + y * info.width + x));
pos = (((_size[1] - 1 - y) * _size[0] + x) << 2);
_cursor[pos + 0] = Uint8(c.red * 0xFF);
_cursor[pos + 1] = Uint8(c.green * 0xFF);
_cursor[pos + 2] = Uint8(c.blue * 0xFF);
_cursor[pos + 3] = Uint8(c.alpha * 0xFF);
}
// set position
_position[0] = _position[1] = 8;
}
SDL::GLPointer::~GLPointer()
{
restore();
delete[] _cursor;
delete[] _saved_area;
}
void SDL::GLPointer::save()
{
Prague::Trace trace("SDL::GLPointer::save()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _max_y_size - _position[1] - _size[1] + _origin[1];
glDisable(GL_BLEND);
glDisable(GL_ALPHA);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_FRONT);
glReadPixels(x, y,
_size[0], _size[1],
GL_RGB, GL_UNSIGNED_BYTE,
_saved_area);
glEnable(GL_BLEND);
glEnable(GL_ALPHA);
glEnable(GL_SCISSOR_TEST);
}
void SDL::GLPointer::restore()
{
Prague::Trace trace("SDL::GLPointer::restore()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _position[1] + _size[1] - _origin[1];
glDisable(GL_BLEND);
glDisable(GL_ALPHA);
glDisable(GL_SCISSOR_TEST);
glRasterPos2i((int)(x * _scale[0]), (int)(y * _scale[1]));
glDrawBuffer(GL_FRONT);
glDrawPixels(_size[0], _size[1], GL_RGB, GL_UNSIGNED_BYTE, _saved_area);
glEnable(GL_BLEND);
glEnable(GL_ALPHA);
glEnable(GL_SCISSOR_TEST);
glDrawBuffer(GL_BACK);
}
void SDL::GLPointer::draw()
{
Prague::Trace trace("SDL::GLPointer::draw()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _position[1] + _size[1] - _origin[1];
glDisable(GL_SCISSOR_TEST);
glDrawBuffer(GL_FRONT);
glRasterPos2i((int)(x * _scale[0]), (int)(y * _scale[1]));
glDrawPixels(_size[0], _size[1], GL_RGBA, GL_UNSIGNED_BYTE, _cursor);
glEnable(GL_SCISSOR_TEST);
glFlush();
glDrawBuffer(GL_BACK);
}
// ---------------------------------------------------------------
// externs
// ---------------------------------------------------------------
extern "C" Console::Extension *load() { return new SDL::GLContext();}
<commit_msg>Updated SDL-GLExposeHandler. Fixes bug93.<commit_after>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* Copyright (C) 2001 Philip Philonenko <philonenko@orgacom.ru>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Berlin/Logger.hh>
#include "SDLGL.hh"
// ---------------------------------------------------------------
// class SDL::GLExposeHandler (implementation)
// ---------------------------------------------------------------
void SDL::GLExposeHandler::refresh_screen()
{
Prague::Trace trace("SDL::GLExposeHandler::refresh_screen()");
::Console::Drawable * drawable =
dynamic_cast<SDL::Drawable *>(::Console::instance()->drawable());
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_BACK);
glDrawBuffer(GL_FRONT);
glRasterPos2i(0, 0);
glCopyPixels(0, 0, drawable->width(), drawable->height(), GL_COLOR);
glFlush();
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glEnable(GL_SCISSOR_TEST);
glDrawBuffer(GL_BACK);
_glcontext->flush();
}
// ---------------------------------------------------------------
// class SDL::GLContext (implementation)
// ---------------------------------------------------------------
SDL::GLContext::GLContext()
{
Prague::Trace trace("SDL::GLContext::GLContext()");
_drawable =
dynamic_cast<SDL::Drawable *>(::Console::instance()->drawable());
Fresco::PixelCoord w(_drawable->width());
Fresco::PixelCoord h(_drawable->height());
Logger::log(Logger::loader) << "setting video mode GL " << " w="
<< w << " h= " << h << std::endl;
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_Surface * surface = SDL_SetVideoMode(w, h, 0,
SDL_HWSURFACE | SDL_HWPALETTE |
SDL_OPENGL |
SDL_DOUBLEBUF |
SDL_HWACCEL);
SDL_WM_SetCaption("Berlin on SDL (OpenGL)", NULL);
SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &_isDoubleBuffered);
if (!_isDoubleBuffered) {
std::cout << "SDL_Error: " << SDL_GetError() << std::endl;
throw;
}
// HACK: Replace the 'real' drawable with its OpenGL-replacement.
_drawable->_surface = surface;
_drawable->_width = w;
_drawable->_height = h;
int bits;
glGetIntegerv(GL_DEPTH_BITS, &bits);
switch (bits)
{
case 0: _drawable->_depth = 0; break;
case 8: _drawable->_depth = 1; break;
case 16: _drawable->_depth = 2; break;
case 24: _drawable->_depth = 3; break;
case 32: _drawable->_depth = 4; break;
default:
_drawable->_depth = 0;
}
glDrawBuffer(GL_BACK);
// setup PointerManager:
dynamic_cast<SDL::Console *>(::Console::instance())->
set_PointerManager(new SDL::PointerManagerT<GLPointer>);
// setup ExposeHandler:
dynamic_cast<SDL::Console *>(::Console::instance())->
set_ExposeHandler(new SDL::GLExposeHandler(this));
}
SDL::GLContext::~GLContext()
{
Prague::Trace trace("SDL::GLContext::~SDLGLContext()");
}
void SDL::GLContext::flush() {
Prague::Trace trace("SDL::GLContext::flush()");
if (_isDoubleBuffered) {
glFlush();
SDL_GL_SwapBuffers();
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_FRONT);
glDrawBuffer(GL_BACK);
glRasterPos2i(0, 0);
glCopyPixels(0, 0, _drawable->width(), _drawable->height(), GL_COLOR);
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
glEnable(GL_SCISSOR_TEST);
} else {
// FIXME: TODO
}
}
// ---------------------------------------------------------------
// class SDL::GLPointer (implementation)
// ---------------------------------------------------------------
SDL::GLPointer::GLPointer(Drawable * drawable, Fresco::Raster_ptr raster)
{
Prague::Trace trace("SDL::GLPointer::GLPointer(...)");
// copy over the Raster:
_raster = Fresco::Raster::_duplicate(raster);
// get screensizes:
_max_y_size = drawable->height();
// copy over the Raster:
_raster = Fresco::Raster::_duplicate(raster);
// Disable SDL default mousecursor
SDL_ShowCursor(0);
// Copy the raster over into the Drawable:
Fresco::Raster::Info info = raster->header();
Fresco::Raster::ColorSeq_var pixels;
Fresco::Raster::Index lower, upper;
lower.x = lower.y = 0;
upper.x = info.width, upper.y = info.height;
raster->store_pixels(lower, upper, pixels);
_origin[0] = _origin[1] = 0;
_size[0] = info.width;
_size[1] = info.height;
_scale[0] = 1.0/drawable->resolution(Fresco::xaxis);
_scale[1] = 1.0/drawable->resolution(Fresco::yaxis);
_cursor = new Uint8[_size[0] * _size[1] * 4]; // RGBA
_saved_area = new Uint8[_size[0] * _size[1] * 3]; //RGB
unsigned pos = 0;
Fresco::Color c;
for (unsigned short y = 0; y != _size[1]; ++y)
for (unsigned short x = 0; x != _size[0]; ++x)
{
c = (*(pixels->get_buffer() + y * info.width + x));
pos = (((_size[1] - 1 - y) * _size[0] + x) << 2);
_cursor[pos + 0] = Uint8(c.red * 0xFF);
_cursor[pos + 1] = Uint8(c.green * 0xFF);
_cursor[pos + 2] = Uint8(c.blue * 0xFF);
_cursor[pos + 3] = Uint8(c.alpha * 0xFF);
}
// set position
_position[0] = _position[1] = 8;
}
SDL::GLPointer::~GLPointer()
{
restore();
delete[] _cursor;
delete[] _saved_area;
}
void SDL::GLPointer::save()
{
Prague::Trace trace("SDL::GLPointer::save()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _max_y_size - _position[1] - _size[1] + _origin[1];
glDisable(GL_BLEND);
glDisable(GL_ALPHA);
glDisable(GL_SCISSOR_TEST);
glReadBuffer(GL_FRONT);
glReadPixels(x, y,
_size[0], _size[1],
GL_RGB, GL_UNSIGNED_BYTE,
_saved_area);
glEnable(GL_BLEND);
glEnable(GL_ALPHA);
glEnable(GL_SCISSOR_TEST);
}
void SDL::GLPointer::restore()
{
Prague::Trace trace("SDL::GLPointer::restore()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _position[1] + _size[1] - _origin[1];
glDisable(GL_BLEND);
glDisable(GL_ALPHA);
glDisable(GL_SCISSOR_TEST);
glRasterPos2i((int)(x * _scale[0]), (int)(y * _scale[1]));
glDrawBuffer(GL_FRONT);
glDrawPixels(_size[0], _size[1], GL_RGB, GL_UNSIGNED_BYTE, _saved_area);
glEnable(GL_BLEND);
glEnable(GL_ALPHA);
glEnable(GL_SCISSOR_TEST);
glDrawBuffer(GL_BACK);
}
void SDL::GLPointer::draw()
{
Prague::Trace trace("SDL::GLPointer::draw()");
Fresco::PixelCoord x = _position[0] - _origin[0];
Fresco::PixelCoord y = _position[1] + _size[1] - _origin[1];
glDisable(GL_SCISSOR_TEST);
glDrawBuffer(GL_FRONT);
glRasterPos2i((int)(x * _scale[0]), (int)(y * _scale[1]));
glDrawPixels(_size[0], _size[1], GL_RGBA, GL_UNSIGNED_BYTE, _cursor);
glEnable(GL_SCISSOR_TEST);
glFlush();
glDrawBuffer(GL_BACK);
}
// ---------------------------------------------------------------
// externs
// ---------------------------------------------------------------
extern "C" Console::Extension *load() { return new SDL::GLContext();}
<|endoftext|> |
<commit_before>
#include "log4cplus/logger.h"
#include "log4cplus/consoleappender.h"
#include "log4cplus/loglevel.h"
#include <log4cplus/loggingmacros.h>
#include <iomanip>
using namespace std;
using namespace log4cplus;
int
main()
{
SharedAppenderPtr append_1(new ConsoleAppender());
append_1->setName(LOG4CPLUS_TEXT("First"));
Logger::getRoot().addAppender(append_1);
Logger root = Logger::getRoot();
Logger test = Logger::getInstance(LOG4CPLUS_TEXT("test"));
LOG4CPLUS_DEBUG(root,
"This is"
<< " a reall"
<< "y long message." << endl
<< "Just testing it out" << endl
<< "What do you think?");
test.setLogLevel(NOT_SET_LOG_LEVEL);
LOG4CPLUS_DEBUG(test, "This is a bool: " << true);
LOG4CPLUS_INFO(test, "This is a char: " << 'x');
LOG4CPLUS_INFO(test, "This is a short: " << (short)-100);
LOG4CPLUS_INFO(test, "This is a unsigned short: " << (unsigned short)100);
LOG4CPLUS_INFO(test, "This is a int: " << (int)1000);
LOG4CPLUS_INFO(test, "This is a unsigned int: " << (unsigned int)1000);
LOG4CPLUS_INFO(test, "This is a long(hex): " << hex << (long)100000000);
LOG4CPLUS_INFO(test, "This is a unsigned long: " << (unsigned long)100000000);
LOG4CPLUS_WARN(test, "This is a float: " << (float)1.2345);
LOG4CPLUS_ERROR(test,
"This is a double: "
<< setprecision(15)
<< (double)1.2345234234);
LOG4CPLUS_FATAL(test,
"This is a long double: "
<< setprecision(15)
<< (long double)123452342342.342);
LOG4CPLUS_WARN(test, "The following message is empty:");
LOG4CPLUS_WARN(test, "");
return 0;
}
<commit_msg>tests/ostream_test/main.cxx: Fix old style cast warnings.<commit_after>
#include "log4cplus/logger.h"
#include "log4cplus/consoleappender.h"
#include "log4cplus/loglevel.h"
#include <log4cplus/loggingmacros.h>
#include <iomanip>
using namespace std;
using namespace log4cplus;
int
main()
{
SharedAppenderPtr append_1(new ConsoleAppender());
append_1->setName(LOG4CPLUS_TEXT("First"));
Logger::getRoot().addAppender(append_1);
Logger root = Logger::getRoot();
Logger test = Logger::getInstance(LOG4CPLUS_TEXT("test"));
LOG4CPLUS_DEBUG(root,
"This is"
<< " a reall"
<< "y long message." << endl
<< "Just testing it out" << endl
<< "What do you think?");
test.setLogLevel(NOT_SET_LOG_LEVEL);
LOG4CPLUS_DEBUG(test, "This is a bool: " << true);
LOG4CPLUS_INFO(test, "This is a char: " << 'x');
LOG4CPLUS_INFO(test, "This is a short: " << static_cast<short>(-100));
LOG4CPLUS_INFO(test, "This is a unsigned short: "
<< static_cast<unsigned short>(100));
LOG4CPLUS_INFO(test, "This is a int: " << 1000);
LOG4CPLUS_INFO(test, "This is a unsigned int: " << 1000u);
LOG4CPLUS_INFO(test, "This is a long(hex): " << hex << 100000000l);
LOG4CPLUS_INFO(test, "This is a unsigned long: " << 100000000ul);
LOG4CPLUS_WARN(test, "This is a float: " << 1.2345f);
LOG4CPLUS_ERROR(test,
"This is a double: "
<< setprecision(15)
<< 1.2345234234);
LOG4CPLUS_FATAL(test,
"This is a long double: "
<< setprecision(15)
<< 123452342342.342L);
LOG4CPLUS_WARN(test, "The following message is empty:");
LOG4CPLUS_WARN(test, "");
return 0;
}
<|endoftext|> |
<commit_before>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <assert.h>
#define UINT unsigned int
using std::vector; using std::pair;
using std::make_pair;
extern vector<unsigned int> _logTable;
extern vector<unsigned int> _expTable;
int _tmain(int argc, _TCHAR* argv[])
{
GF256init();
assert(GF256elm(3) + GF256elm(4) == GF256elm(7));
assert(GF256elm(500) == GF256elm(244));
assert(GF256elm(255) == GF256elm(-1));
assert(GF256elm(3) * GF256elm(4) == GF256elm(12));
GF256elm xd = GF256elm(7) * GF256elm(77);
assert((GF256elm(4) / GF256elm(1)) == GF256elm(4));
assert((GF256elm(32) / GF256elm(16)) == GF256elm(2));
assert((GF256elm(15) / GF256elm(5)) == GF256elm(3));
assert((GF256elm(88) / GF256elm(8)) == GF256elm(11));
assert((GF256elm(7) * GF256elm(11)) == GF256elm(77));
assert((GF256elm(77) / GF256elm(11)) == GF256elm(7));
assert((GF256elm(77) / GF256elm(7)) == GF256elm(11));
PGF256 hi = generateRandomPolynomial(5, 0x08);
vector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);
vector<pair<UINT, UINT>> lol2;
lol2.push_back(make_pair(225, 113));
lol2.push_back(make_pair(32, 247));
lol2.push_back(make_pair(249, 248));
UINT result = decodeByte(lol2);
return 0;
}
<commit_msg>check whether generated table is correct #1<commit_after>// SSSSCpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "GF256.h"
#include "SSSSCpp.h"
#include <vector>
#include <stdio.h>
#include <iostream>
#include <assert.h>
#define UINT unsigned int
using std::vector; using std::pair;
using std::make_pair;
extern vector<unsigned int> _logTable;
extern vector<unsigned int> _expTable;
static const UINT mexp[256] = {
0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35,
0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa,
0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0xab, 0xe6, 0x31,
0x53, 0xf5, 0x04, 0x0c, 0x14, 0x3c, 0x44, 0xcc, 0x4f, 0xd1, 0x68, 0xb8, 0xd3, 0x6e, 0xb2, 0xcd,
0x4c, 0xd4, 0x67, 0xa9, 0xe0, 0x3b, 0x4d, 0xd7, 0x62, 0xa6, 0xf1, 0x08, 0x18, 0x28, 0x78, 0x88,
0x83, 0x9e, 0xb9, 0xd0, 0x6b, 0xbd, 0xdc, 0x7f, 0x81, 0x98, 0xb3, 0xce, 0x49, 0xdb, 0x76, 0x9a,
0xb5, 0xc4, 0x57, 0xf9, 0x10, 0x30, 0x50, 0xf0, 0x0b, 0x1d, 0x27, 0x69, 0xbb, 0xd6, 0x61, 0xa3,
0xfe, 0x19, 0x2b, 0x7d, 0x87, 0x92, 0xad, 0xec, 0x2f, 0x71, 0x93, 0xae, 0xe9, 0x20, 0x60, 0xa0,
0xfb, 0x16, 0x3a, 0x4e, 0xd2, 0x6d, 0xb7, 0xc2, 0x5d, 0xe7, 0x32, 0x56, 0xfa, 0x15, 0x3f, 0x41,
0xc3, 0x5e, 0xe2, 0x3d, 0x47, 0xc9, 0x40, 0xc0, 0x5b, 0xed, 0x2c, 0x74, 0x9c, 0xbf, 0xda, 0x75,
0x9f, 0xba, 0xd5, 0x64, 0xac, 0xef, 0x2a, 0x7e, 0x82, 0x9d, 0xbc, 0xdf, 0x7a, 0x8e, 0x89, 0x80,
0x9b, 0xb6, 0xc1, 0x58, 0xe8, 0x23, 0x65, 0xaf, 0xea, 0x25, 0x6f, 0xb1, 0xc8, 0x43, 0xc5, 0x54,
0xfc, 0x1f, 0x21, 0x63, 0xa5, 0xf4, 0x07, 0x09, 0x1b, 0x2d, 0x77, 0x99, 0xb0, 0xcb, 0x46, 0xca,
0x45, 0xcf, 0x4a, 0xde, 0x79, 0x8b, 0x86, 0x91, 0xa8, 0xe3, 0x3e, 0x42, 0xc6, 0x51, 0xf3, 0x0e,
0x12, 0x36, 0x5a, 0xee, 0x29, 0x7b, 0x8d, 0x8c, 0x8f, 0x8a, 0x85, 0x94, 0xa7, 0xf2, 0x0d, 0x17,
0x39, 0x4b, 0xdd, 0x7c, 0x84, 0x97, 0xa2, 0xfd, 0x1c, 0x24, 0x6c, 0xb4, 0xc7, 0x52, 0xf6, 0x01};
static const UINT mlog[256] = {
0x00, // log(0) is not defined
0xff, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03, 0x64,
0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1, 0x7d,
0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78, 0x65,
0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e, 0x96,
0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38, 0x66,
0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10, 0x7e,
0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, 0x2b,
0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, 0xaf,
0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c,
0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f,
0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc,
0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97,
0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53,
0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44,
0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67,
0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07};
int _tmain(int argc, _TCHAR* argv[])
{
GF256init();
//verifying
for (int i = 0; i < 256; i++) {
assert((mexp[i] == _expTable[i]));
assert(mlog[i] == _logTable[i]);
if ((mexp[i] == _expTable[i]) && (mlog[i] == _logTable[i])) {
continue;
}
else {
std::cout << i << "\tmexp: " << mexp[i] << "\tmy: " << _expTable[i] << std::endl;
std::cout << i << "\tmlog: " << mlog[i] << "\tmy: " << _logTable[i] << std::endl;
}
}
assert(GF256elm(3) + GF256elm(4) == GF256elm(7));
assert(GF256elm(500) == GF256elm(244));
assert(GF256elm(255) == GF256elm(-1));
assert(GF256elm(3) * GF256elm(4) == GF256elm(12));
GF256elm xd = GF256elm(7) * GF256elm(77);
assert((GF256elm(4) / GF256elm(1)) == GF256elm(4));
assert((GF256elm(32) / GF256elm(16)) == GF256elm(2));
assert((GF256elm(15) / GF256elm(5)) == GF256elm(3));
assert((GF256elm(88) / GF256elm(8)) == GF256elm(11));
assert((GF256elm(7) * GF256elm(11)) == GF256elm(77));
assert((GF256elm(77) / GF256elm(11)) == GF256elm(7));
assert((GF256elm(77) / GF256elm(7)) == GF256elm(11));
PGF256 hi = generateRandomPolynomial(5, 0x08);
vector<pair<UINT, UINT>> lol = encodeByte(15, 5, 3);
vector<pair<UINT, UINT>> lol2;
lol2.push_back(make_pair(225, 113));
lol2.push_back(make_pair(32, 247));
lol2.push_back(make_pair(249, 248));
UINT result = decodeByte(lol2);
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Class to encapsulate the ALICE updates to TDatabasePDG.h
// Can be used by TGeant3 and TGeant4
// It contains also the constants for the PDG particle IDs.
// Should evolve towards dynamical loading from external data base.
// Comments to: andreas.morsch@cern.ch
#include "AliPDG.h"
#include "TDatabasePDG.h"
ClassImp(AliPDG)
void AliPDG::AddParticlesToPdgDataBase()
{
//
// Add particles to the PDG data base
TDatabasePDG *pdgDB = TDatabasePDG::Instance();
const Int_t kspe=50000000;
/*
const Int_t kion=10000000;
const Double_t kAu2Gev=0.9314943228;
const Double_t khSlash = 1.0545726663e-27;
const Double_t kErg2Gev = 1/1.6021773349e-3;
const Double_t khShGev = khSlash*kErg2Gev;
const Double_t kYear2Sec = 3600*24*365.25;
*/
//
// Bottom mesons
// mass and life-time from PDG
//
pdgDB->AddParticle("Upsilon(3S)","Upsilon(3S)",10.3552,kTRUE,
0,1,"Bottonium",200553);
// QCD diffractive states
pdgDB->AddParticle("rho_diff0","rho_diff0",0,kTRUE,
0,0,"QCD diffr. state",9900110);
pdgDB->AddParticle("pi_diffr+","pi_diffr+",0,kTRUE,
0,1,"QCD diffr. state",9900210);
pdgDB->AddParticle("omega_di","omega_di",0,kTRUE,
0,0,"QCD diffr. state",9900220);
pdgDB->AddParticle("phi_diff","phi_diff",0,kTRUE,
0,0,"QCD diffr. state",9900330);
pdgDB->AddParticle("J/psi_di","J/psi_di",0,kTRUE,
0,0,"QCD diffr. state",9900440);
pdgDB->AddParticle("n_diffr0","n_diffr0",0,kTRUE,
0,0,"QCD diffr. state",9902110);
pdgDB->AddParticle("p_diffr+","p_diffr+",0,kTRUE,
0,1,"QCD diffr. state",9902210);
// Done by default now from Pythia6 table!
//
//
// Ions
//
/*
pdgDB->AddParticle("Deuteron","Deuteron",2*kAu2Gev+8.071e-3,kTRUE,
0,1,"Ion",kion+10020);
pdgDB->AddParticle("Triton","Triton",3*kAu2Gev+14.931e-3,kFALSE,
khShGev/(12.33*kYear2Sec),1,"Ion",kion+10030);
pdgDB->AddParticle("Alpha","Alpha",4*kAu2Gev+2.424e-3,kTRUE,
khShGev/(12.33*kYear2Sec),2,"Ion",kion+20040);
pdgDB->AddParticle("HE3","HE3",3*kAu2Gev+14.931e-3,kFALSE,
0,2,"Ion",kion+20030);
*/
// Special particles
//
pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE,
0,0,"Special",kspe+50);
pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE,
0,0,"Special",kspe+51);
pdgDB->AddParticle("Lambda1520","Lambda1520",1.5195,kFALSE,
0.0156,0,"Resonance",3124);
pdgDB->AddAntiParticle("Lambda1520bar",-3124);
}
<commit_msg>Some particles produced by HERWIG added.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Class to encapsulate the ALICE updates to TDatabasePDG.h
// Can be used by TGeant3 and TGeant4
// It contains also the constants for the PDG particle IDs.
// Should evolve towards dynamical loading from external data base.
// Comments to: andreas.morsch@cern.ch
#include "AliPDG.h"
#include "TDatabasePDG.h"
ClassImp(AliPDG)
void AliPDG::AddParticlesToPdgDataBase()
{
//
// Add particles to the PDG data base
TDatabasePDG *pdgDB = TDatabasePDG::Instance();
const Int_t kspe=50000000;
/*
const Int_t kion=10000000;
const Double_t kAu2Gev=0.9314943228;
const Double_t khSlash = 1.0545726663e-27;
const Double_t kErg2Gev = 1/1.6021773349e-3;
const Double_t khShGev = khSlash*kErg2Gev;
const Double_t kYear2Sec = 3600*24*365.25;
*/
//
// Bottom mesons
// mass and life-time from PDG
//
pdgDB->AddParticle("Upsilon(3S)","Upsilon(3S)",10.3552,kTRUE,
0,1,"Bottonium",200553);
// QCD diffractive states
pdgDB->AddParticle("rho_diff0","rho_diff0",0,kTRUE,
0,0,"QCD diffr. state",9900110);
pdgDB->AddParticle("pi_diffr+","pi_diffr+",0,kTRUE,
0,1,"QCD diffr. state",9900210);
pdgDB->AddParticle("omega_di","omega_di",0,kTRUE,
0,0,"QCD diffr. state",9900220);
pdgDB->AddParticle("phi_diff","phi_diff",0,kTRUE,
0,0,"QCD diffr. state",9900330);
pdgDB->AddParticle("J/psi_di","J/psi_di",0,kTRUE,
0,0,"QCD diffr. state",9900440);
pdgDB->AddParticle("n_diffr0","n_diffr0",0,kTRUE,
0,0,"QCD diffr. state",9902110);
pdgDB->AddParticle("p_diffr+","p_diffr+",0,kTRUE,
0,1,"QCD diffr. state",9902210);
// Some particles produced by HERWIG
pdgDB->AddParticle("rho3(1690)0","rho(1690)0", 1.69, kTRUE,
0, 0,"rho", 117);
pdgDB->AddParticle("pion2(1670)0","pion2(1670)0", 1.67, kTRUE,
0, 0,"pion", 10115);
pdgDB->AddParticle("omega(1650)","omega(1650)", 1.65, kTRUE,
0, 0,"pion", 30223);
// Done by default now from Pythia6 table!
//
//
// Ions
//
/*
pdgDB->AddParticle("Deuteron","Deuteron",2*kAu2Gev+8.071e-3,kTRUE,
0,1,"Ion",kion+10020);
pdgDB->AddParticle("Triton","Triton",3*kAu2Gev+14.931e-3,kFALSE,
khShGev/(12.33*kYear2Sec),1,"Ion",kion+10030);
pdgDB->AddParticle("Alpha","Alpha",4*kAu2Gev+2.424e-3,kTRUE,
khShGev/(12.33*kYear2Sec),2,"Ion",kion+20040);
pdgDB->AddParticle("HE3","HE3",3*kAu2Gev+14.931e-3,kFALSE,
0,2,"Ion",kion+20030);
*/
// Special particles
//
pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE,
0,0,"Special",kspe+50);
pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE,
0,0,"Special",kspe+51);
pdgDB->AddParticle("Lambda1520","Lambda1520",1.5195,kFALSE,
0.0156,0,"Resonance",3124);
pdgDB->AddAntiParticle("Lambda1520bar",-3124);
}
<|endoftext|> |
<commit_before>//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// llvm-link a.bc b.bc c.bc -o x.bc
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include <memory>
using namespace llvm;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input bitcode files>"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
static cl::opt<bool>
Verbose("v", cl::desc("Print information about actions taken"));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
// LoadFile - Read the specified bitcode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
static inline std::auto_ptr<Module> LoadFile(const char *argv0,
const std::string &FN,
LLVMContext& Context) {
sys::Path Filename;
if (!Filename.set(FN)) {
errs() << "Invalid file name: '" << FN << "'\n";
return std::auto_ptr<Module>();
}
SMDiagnostic Err;
if (Verbose) errs() << "Loading '" << Filename.c_str() << "'\n";
Module* Result = 0;
const std::string &FNStr = Filename.str();
Result = ParseIRFile(FNStr, Err, Context);
if (Result) return std::auto_ptr<Module>(Result); // Load successful!
Err.print(argv0, errs());
return std::auto_ptr<Module>();
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
unsigned BaseArg = 0;
std::string ErrorMessage;
std::auto_ptr<Module> Composite(LoadFile(argv[0],
InputFilenames[BaseArg], Context));
if (Composite.get() == 0) {
errs() << argv[0] << ": error loading file '"
<< InputFilenames[BaseArg] << "'\n";
return 1;
}
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(argv[0],
InputFilenames[i], Context));
if (M.get() == 0) {
errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
return 1;
}
if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n";
if (Linker::LinkModules(Composite.get(), M.get(), Linker::DestroySource,
&ErrorMessage)) {
errs() << argv[0] << ": link error in '" << InputFilenames[i]
<< "': " << ErrorMessage << "\n";
return 1;
}
}
// TODO: Iterate over the -l list and link in any modules containing
// global symbols that have not been resolved so far.
if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
std::string ErrorInfo;
tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
if (verifyModule(*Composite)) {
errs() << argv[0] << ": linked module is broken!\n";
return 1;
}
if (Verbose) errs() << "Writing bitcode...\n";
if (OutputAssembly) {
Out.os() << *Composite;
} else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
WriteBitcodeToFile(Composite.get(), Out.os());
// Declare success.
Out.keep();
return 0;
}
<commit_msg>Remove stale comment<commit_after>//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// llvm-link a.bc b.bc c.bc -o x.bc
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include <memory>
using namespace llvm;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input bitcode files>"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
static cl::opt<bool>
Verbose("v", cl::desc("Print information about actions taken"));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
// LoadFile - Read the specified bitcode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
static inline std::auto_ptr<Module> LoadFile(const char *argv0,
const std::string &FN,
LLVMContext& Context) {
sys::Path Filename;
if (!Filename.set(FN)) {
errs() << "Invalid file name: '" << FN << "'\n";
return std::auto_ptr<Module>();
}
SMDiagnostic Err;
if (Verbose) errs() << "Loading '" << Filename.c_str() << "'\n";
Module* Result = 0;
const std::string &FNStr = Filename.str();
Result = ParseIRFile(FNStr, Err, Context);
if (Result) return std::auto_ptr<Module>(Result); // Load successful!
Err.print(argv0, errs());
return std::auto_ptr<Module>();
}
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
unsigned BaseArg = 0;
std::string ErrorMessage;
std::auto_ptr<Module> Composite(LoadFile(argv[0],
InputFilenames[BaseArg], Context));
if (Composite.get() == 0) {
errs() << argv[0] << ": error loading file '"
<< InputFilenames[BaseArg] << "'\n";
return 1;
}
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(argv[0],
InputFilenames[i], Context));
if (M.get() == 0) {
errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n";
return 1;
}
if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n";
if (Linker::LinkModules(Composite.get(), M.get(), Linker::DestroySource,
&ErrorMessage)) {
errs() << argv[0] << ": link error in '" << InputFilenames[i]
<< "': " << ErrorMessage << "\n";
return 1;
}
}
if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
std::string ErrorInfo;
tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
if (verifyModule(*Composite)) {
errs() << argv[0] << ": linked module is broken!\n";
return 1;
}
if (Verbose) errs() << "Writing bitcode...\n";
if (OutputAssembly) {
Out.os() << *Composite;
} else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
WriteBitcodeToFile(Composite.get(), Out.os());
// Declare success.
Out.keep();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/api/atom_api_protocol.h"
#include "base/stl_util.h"
#include "browser/atom_browser_context.h"
#include "browser/net/adapter_request_job.h"
#include "browser/net/atom_url_request_context_getter.h"
#include "browser/net/atom_url_request_job_factory.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_context.h"
#include "common/v8/node_common.h"
namespace atom {
namespace api {
typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
namespace {
// The protocol module object.
ScopedPersistent<v8::Object> g_protocol_object;
// Registered protocol handlers.
typedef std::map<std::string, RefCountedV8Function> HandlersMap;
static HandlersMap g_handlers;
static const char* kEarlyUseProtocolError = "This method can only be used"
"after the application has finished launching.";
// Emit an event for the protocol module.
void EmitEventInUI(const std::string& event, const std::string& parameter) {
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> argv[] = {
ToV8Value(event),
ToV8Value(parameter),
};
node::MakeCallback(g_protocol_object.NewHandle(node_isolate),
"emit", 2, argv);
}
// Convert the URLRequest object to V8 object.
v8::Handle<v8::Object> ConvertURLRequestToV8Object(
const net::URLRequest* request) {
v8::Local<v8::Object> obj = v8::Object::New();
obj->Set(ToV8Value("method"), ToV8Value(request->method()));
obj->Set(ToV8Value("url"), ToV8Value(request->url().spec()));
obj->Set(ToV8Value("referrer"), ToV8Value(request->referrer()));
return obj;
}
// Get the job factory.
AtomURLRequestJobFactory* GetRequestJobFactory() {
return AtomBrowserContext::Get()->url_request_context_getter()->job_factory();
}
class CustomProtocolRequestJob : public AdapterRequestJob {
public:
CustomProtocolRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: AdapterRequestJob(protocol_handler, request, network_delegate) {
}
// AdapterRequestJob:
virtual void GetJobTypeInUI() OVERRIDE {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
v8::HandleScope handle_scope(node_isolate);
// Call the JS handler.
v8::Handle<v8::Value> argv[] = {
ConvertURLRequestToV8Object(request()),
};
RefCountedV8Function callback = g_handlers[request()->url().scheme()];
v8::Handle<v8::Value> result = callback->NewHandle(node_isolate)->Call(
v8::Context::GetCurrent()->Global(), 1, argv);
// Determine the type of the job we are going to create.
if (result->IsString()) {
std::string data = FromV8Value(result);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
"text/plain",
"UTF-8",
data));
return;
} else if (result->IsObject()) {
v8::Handle<v8::Object> obj = result->ToObject();
std::string name = FromV8Value(obj->GetConstructorName());
if (name == "RequestStringJob") {
std::string mime_type = FromV8Value(obj->Get(
v8::String::New("mimeType")));
std::string charset = FromV8Value(obj->Get(v8::String::New("charset")));
std::string data = FromV8Value(obj->Get(v8::String::New("data")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
mime_type,
charset,
data));
return;
} else if (name == "RequestFileJob") {
base::FilePath path = FromV8Value(obj->Get(v8::String::New("path")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateFileJobAndStart,
GetWeakPtr(),
path));
return;
}
}
// Try the default protocol handler if we have.
if (default_protocol_handler()) {
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateJobFromProtocolHandlerAndStart,
GetWeakPtr()));
return;
}
// Fallback to the not implemented error.
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateErrorJobAndStart,
GetWeakPtr(),
net::ERR_NOT_IMPLEMENTED));
}
};
// Always return the same CustomProtocolRequestJob for all requests, because
// the content API needs the ProtocolHandler to return a job immediately, and
// getting the real job from the JS requires asynchronous calls, so we have
// to create an adapter job first.
// Users can also pass an extra ProtocolHandler as the fallback one when
// registered handler doesn't want to deal with the request.
class CustomProtocolHandler : public ProtocolHandler {
public:
explicit CustomProtocolHandler(ProtocolHandler* protocol_handler = NULL)
: protocol_handler_(protocol_handler) {
}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE {
return new CustomProtocolRequestJob(protocol_handler_.get(),
request,
network_delegate);
}
ProtocolHandler* ReleaseDefaultProtocolHandler() {
return protocol_handler_.release();
}
ProtocolHandler* original_handler() { return protocol_handler_.get(); }
private:
scoped_ptr<ProtocolHandler> protocol_handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
};
} // namespace
// static
void Protocol::RegisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument");
if (g_handlers.find(scheme) != g_handlers.end() ||
net::URLRequest::IsHandledProtocol(scheme))
return node::ThrowError("The scheme is already registered");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&RegisterProtocolInIO, scheme));
}
// static
void Protocol::UnregisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UnregisterProtocolInIO, scheme));
}
// static
void Protocol::IsHandledProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme = FromV8Value(args[0]);
args.GetReturnValue().Set(net::URLRequest::IsHandledProtocol(scheme));
}
// static
void Protocol::InterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument");
if (!GetRequestJobFactory()->HasProtocolHandler(scheme))
return node::ThrowError("Cannot intercept procotol");
if (ContainsKey(g_handlers, scheme))
return node::ThrowError("Cannot intercept custom procotols");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&InterceptProtocolInIO, scheme));
}
// static
void Protocol::UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UninterceptProtocolInIO,
scheme));
}
// static
void Protocol::RegisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, new CustomProtocolHandler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"registered",
scheme));
}
// static
void Protocol::UnregisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, NULL);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unregistered",
scheme));
}
// static
void Protocol::InterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
ProtocolHandler* original_handler = job_factory->GetProtocolHandler(scheme);
if (original_handler == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"There is no protocol handler to intercpet"));
return;
}
job_factory->ReplaceProtocol(scheme,
new CustomProtocolHandler(original_handler));
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"intercepted",
scheme));
}
// static
void Protocol::UninterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
// Check if the protocol handler is intercepted.
CustomProtocolHandler* handler = static_cast<CustomProtocolHandler*>(
job_factory->GetProtocolHandler(scheme));
if (handler->original_handler() == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"The protocol is not intercpeted"));
return;
}
// Reset the protocol handler to the orignal one and delete current
// protocol handler.
ProtocolHandler* original_handler = handler->ReleaseDefaultProtocolHandler();
delete job_factory->ReplaceProtocol(scheme, original_handler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unintercepted",
scheme));
}
// static
void Protocol::Initialize(v8::Handle<v8::Object> target) {
// Remember the protocol object, used for emitting event later.
g_protocol_object.reset(v8::Object::New());
NODE_SET_METHOD(target, "registerProtocol", RegisterProtocol);
NODE_SET_METHOD(target, "unregisterProtocol", UnregisterProtocol);
NODE_SET_METHOD(target, "isHandledProtocol", IsHandledProtocol);
NODE_SET_METHOD(target, "interceptProtocol", InterceptProtocol);
NODE_SET_METHOD(target, "uninterceptProtocol", UninterceptProtocol);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_protocol, atom::api::Protocol::Initialize)
<commit_msg>Fix protocol module specs.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/api/atom_api_protocol.h"
#include "base/stl_util.h"
#include "browser/atom_browser_context.h"
#include "browser/net/adapter_request_job.h"
#include "browser/net/atom_url_request_context_getter.h"
#include "browser/net/atom_url_request_job_factory.h"
#include "common/v8/native_type_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "net/url_request/url_request_context.h"
#include "common/v8/node_common.h"
namespace atom {
namespace api {
typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
namespace {
// The protocol module object.
ScopedPersistent<v8::Object> g_protocol_object;
// Registered protocol handlers.
typedef std::map<std::string, RefCountedV8Function> HandlersMap;
static HandlersMap g_handlers;
static const char* kEarlyUseProtocolError = "This method can only be used"
"after the application has finished launching.";
// Emit an event for the protocol module.
void EmitEventInUI(const std::string& event, const std::string& parameter) {
v8::HandleScope handle_scope(node_isolate);
v8::Handle<v8::Value> argv[] = {
ToV8Value(event),
ToV8Value(parameter),
};
node::MakeCallback(g_protocol_object.NewHandle(node_isolate),
"emit", 2, argv);
}
// Convert the URLRequest object to V8 object.
v8::Handle<v8::Object> ConvertURLRequestToV8Object(
const net::URLRequest* request) {
v8::Local<v8::Object> obj = v8::Object::New();
obj->Set(ToV8Value("method"), ToV8Value(request->method()));
obj->Set(ToV8Value("url"), ToV8Value(request->url().spec()));
obj->Set(ToV8Value("referrer"), ToV8Value(request->referrer()));
return obj;
}
// Get the job factory.
AtomURLRequestJobFactory* GetRequestJobFactory() {
return AtomBrowserContext::Get()->url_request_context_getter()->job_factory();
}
class CustomProtocolRequestJob : public AdapterRequestJob {
public:
CustomProtocolRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: AdapterRequestJob(protocol_handler, request, network_delegate) {
}
// AdapterRequestJob:
virtual void GetJobTypeInUI() OVERRIDE {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
v8::HandleScope handle_scope(node_isolate);
// Call the JS handler.
v8::Handle<v8::Value> argv[] = {
ConvertURLRequestToV8Object(request()),
};
RefCountedV8Function callback = g_handlers[request()->url().scheme()];
v8::Handle<v8::Value> result = callback->NewHandle(node_isolate)->Call(
v8::Context::GetCurrent()->Global(), 1, argv);
// Determine the type of the job we are going to create.
if (result->IsString()) {
std::string data = FromV8Value(result);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
"text/plain",
"UTF-8",
data));
return;
} else if (result->IsObject()) {
v8::Handle<v8::Object> obj = result->ToObject();
std::string name = FromV8Value(obj->GetConstructorName());
if (name == "RequestStringJob") {
std::string mime_type = FromV8Value(obj->Get(
v8::String::New("mimeType")));
std::string charset = FromV8Value(obj->Get(v8::String::New("charset")));
std::string data = FromV8Value(obj->Get(v8::String::New("data")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateStringJobAndStart,
GetWeakPtr(),
mime_type,
charset,
data));
return;
} else if (name == "RequestFileJob") {
base::FilePath path = FromV8Value(obj->Get(v8::String::New("path")));
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateFileJobAndStart,
GetWeakPtr(),
path));
return;
}
}
// Try the default protocol handler if we have.
if (default_protocol_handler()) {
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateJobFromProtocolHandlerAndStart,
GetWeakPtr()));
return;
}
// Fallback to the not implemented error.
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&AdapterRequestJob::CreateErrorJobAndStart,
GetWeakPtr(),
net::ERR_NOT_IMPLEMENTED));
}
};
// Always return the same CustomProtocolRequestJob for all requests, because
// the content API needs the ProtocolHandler to return a job immediately, and
// getting the real job from the JS requires asynchronous calls, so we have
// to create an adapter job first.
// Users can also pass an extra ProtocolHandler as the fallback one when
// registered handler doesn't want to deal with the request.
class CustomProtocolHandler : public ProtocolHandler {
public:
explicit CustomProtocolHandler(ProtocolHandler* protocol_handler = NULL)
: protocol_handler_(protocol_handler) {
}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE {
return new CustomProtocolRequestJob(protocol_handler_.get(),
request,
network_delegate);
}
ProtocolHandler* ReleaseDefaultProtocolHandler() {
return protocol_handler_.release();
}
ProtocolHandler* original_handler() { return protocol_handler_.get(); }
private:
scoped_ptr<ProtocolHandler> protocol_handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
};
} // namespace
// static
void Protocol::RegisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument");
if (g_handlers.find(scheme) != g_handlers.end() ||
GetRequestJobFactory()->IsHandledProtocol(scheme))
return node::ThrowError("The scheme is already registered");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&RegisterProtocolInIO, scheme));
}
// static
void Protocol::UnregisterProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UnregisterProtocolInIO, scheme));
}
// static
void Protocol::IsHandledProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
args.GetReturnValue().Set(GetRequestJobFactory()->IsHandledProtocol(scheme));
}
// static
void Protocol::InterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
RefCountedV8Function callback;
if (!FromV8Arguments(args, &scheme, &callback))
return node::ThrowTypeError("Bad argument");
if (!GetRequestJobFactory()->HasProtocolHandler(scheme))
return node::ThrowError("Cannot intercept procotol");
if (ContainsKey(g_handlers, scheme))
return node::ThrowError("Cannot intercept custom procotols");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Store the handler in a map.
g_handlers[scheme] = callback;
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&InterceptProtocolInIO, scheme));
}
// static
void Protocol::UninterceptProtocol(
const v8::FunctionCallbackInfo<v8::Value>& args) {
std::string scheme;
if (!FromV8Arguments(args, &scheme))
return node::ThrowTypeError("Bad argument");
if (AtomBrowserContext::Get()->url_request_context_getter() == NULL)
return node::ThrowError(kEarlyUseProtocolError);
// Erase the handler from map.
HandlersMap::iterator it(g_handlers.find(scheme));
if (it == g_handlers.end())
return node::ThrowError("The scheme has not been registered");
g_handlers.erase(it);
content::BrowserThread::PostTask(content::BrowserThread::IO,
FROM_HERE,
base::Bind(&UninterceptProtocolInIO,
scheme));
}
// static
void Protocol::RegisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, new CustomProtocolHandler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"registered",
scheme));
}
// static
void Protocol::UnregisterProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
job_factory->SetProtocolHandler(scheme, NULL);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unregistered",
scheme));
}
// static
void Protocol::InterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
ProtocolHandler* original_handler = job_factory->GetProtocolHandler(scheme);
if (original_handler == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"There is no protocol handler to intercpet"));
return;
}
job_factory->ReplaceProtocol(scheme,
new CustomProtocolHandler(original_handler));
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"intercepted",
scheme));
}
// static
void Protocol::UninterceptProtocolInIO(const std::string& scheme) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
AtomURLRequestJobFactory* job_factory(GetRequestJobFactory());
// Check if the protocol handler is intercepted.
CustomProtocolHandler* handler = static_cast<CustomProtocolHandler*>(
job_factory->GetProtocolHandler(scheme));
if (handler->original_handler() == NULL) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"error",
"The protocol is not intercpeted"));
return;
}
// Reset the protocol handler to the orignal one and delete current
// protocol handler.
ProtocolHandler* original_handler = handler->ReleaseDefaultProtocolHandler();
delete job_factory->ReplaceProtocol(scheme, original_handler);
content::BrowserThread::PostTask(content::BrowserThread::UI,
FROM_HERE,
base::Bind(&EmitEventInUI,
"unintercepted",
scheme));
}
// static
void Protocol::Initialize(v8::Handle<v8::Object> target) {
// Remember the protocol object, used for emitting event later.
g_protocol_object.reset(target);
NODE_SET_METHOD(target, "registerProtocol", RegisterProtocol);
NODE_SET_METHOD(target, "unregisterProtocol", UnregisterProtocol);
NODE_SET_METHOD(target, "isHandledProtocol", IsHandledProtocol);
NODE_SET_METHOD(target, "interceptProtocol", InterceptProtocol);
NODE_SET_METHOD(target, "uninterceptProtocol", UninterceptProtocol);
}
} // namespace api
} // namespace atom
NODE_MODULE(atom_browser_protocol, atom::api::Protocol::Initialize)
<|endoftext|> |
<commit_before>#include <Spark/Dse.hpp>
#include <Spark/Utils.hpp>
#include <boost/program_options.hpp>
#include <chrono>
#include <string>
using namespace spark::utils;
int main(int argc, char** argv) {
namespace po = boost::program_options;
std::string numPipes = "numPipes";
std::string cacheSize = "cacheSize";
std::string inputWidth = "inputWidth";
std::string gflopsOnly = "gflopsOnly";
std::string help = "help";
std::string help_m = "produce help message";
po::options_description desc("Allowed options");
desc.add_options()
(help.c_str(), help_m.c_str())
(numPipes.c_str(), po::value<std::string>(), "range for number of pipes: start,end,step")
(cacheSize.c_str(), po::value<std::string>(), "range for cache size")
(inputWidth.c_str(), po::value<std::string>(), "range for input width")
(gflopsOnly.c_str(), po::value<bool>(), "print only gflops")
("filePath", po::value<std::string>(), "path to matrix")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::string path;
if (vm.count("filePath")) {
path = vm["filePath"].as<std::string>();
} else {
std::cout << "Matrix path was not set.\n";
return 1;
}
Range numPipesRange{1, 4, 1}, inputWidthRange{8, 40, 8}, cacheSizeRange{1024, 1024 * 32, 1024};
if (vm.count(numPipes)) {
numPipesRange = Range(vm[numPipes].as<std::string>());
}
if (vm.count(inputWidth)) {
inputWidthRange = Range(vm[inputWidth].as<std::string>());
}
if (vm.count(cacheSize)) {
cacheSizeRange = Range(vm[cacheSize].as<std::string>());
}
bool gflopsOnlyV = false;
if (vm.count(gflopsOnly)) {
gflopsOnlyV = vm[gflopsOnly].as<bool>();
}
auto start = std::chrono::high_resolution_clock::now();
spark::dse::SparkDse dseTool;
dseTool.runDse();
spark::dse::DseParameters params;
params.numPipesRange = numPipesRange;
params.inputWidthRange = inputWidthRange;
params.cacheSizeRange = cacheSizeRange;
params.gflopsOnly = true;
int status = dseTool.run(path, params);
dfesnippets::timing::print_clock_diff("Test took: ", start);
if (status == 0)
std::cout << "All tests passed!" << std::endl;
else
std::cout << "Tests failed!" << std::endl;
return status;
}
<commit_msg>Fix test_architecture<commit_after>#include <Spark/Dse.hpp>
#include <Spark/Utils.hpp>
#include <boost/program_options.hpp>
#include <chrono>
#include <string>
using namespace spark::utils;
int main(int argc, char** argv) {
namespace po = boost::program_options;
std::string numPipes = "numPipes";
std::string cacheSize = "cacheSize";
std::string inputWidth = "inputWidth";
std::string gflopsOnly = "gflopsOnly";
std::string help = "help";
std::string help_m = "produce help message";
po::options_description desc("Allowed options");
desc.add_options()
(help.c_str(), help_m.c_str())
(numPipes.c_str(), po::value<std::string>(), "range for number of pipes: start,end,step")
(cacheSize.c_str(), po::value<std::string>(), "range for cache size")
(inputWidth.c_str(), po::value<std::string>(), "range for input width")
(gflopsOnly.c_str(), po::value<bool>(), "print only gflops")
("filePath", po::value<std::string>(), "path to matrix")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::string path;
if (vm.count("filePath")) {
path = vm["filePath"].as<std::string>();
} else {
std::cout << "Matrix path was not set.\n";
return 1;
}
Range numPipesRange{1, 4, 1}, inputWidthRange{8, 40, 8}, cacheSizeRange{1024, 1024 * 32, 1024};
if (vm.count(numPipes)) {
numPipesRange = Range(vm[numPipes].as<std::string>());
}
if (vm.count(inputWidth)) {
inputWidthRange = Range(vm[inputWidth].as<std::string>());
}
if (vm.count(cacheSize)) {
cacheSizeRange = Range(vm[cacheSize].as<std::string>());
}
bool gflopsOnlyV = false;
if (vm.count(gflopsOnly)) {
gflopsOnlyV = vm[gflopsOnly].as<bool>();
}
auto start = std::chrono::high_resolution_clock::now();
spark::dse::SparkDse dseTool;
spark::dse::DseParameters params;
params.numPipesRange = numPipesRange;
params.inputWidthRange = inputWidthRange;
params.cacheSizeRange = cacheSizeRange;
params.gflopsOnly = true;
spark::dse::Benchmark benchmark;
benchmark.add_matrix_path(path);
int status = dseTool.run(benchmark, params);
dfesnippets::timing::print_clock_diff("Test took: ", start);
if (status == 0)
std::cout << "All tests passed!" << std::endl;
else
std::cout << "Tests failed!" << std::endl;
return status;
}
<|endoftext|> |
<commit_before>#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/rmat_graph_generator.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/graph/graph_traits.hpp>
#include <iostream>
#include <ctime>
#include <stdio.h>
using namespace boost;
typedef adjacency_list<> Graph;
typedef rmat_iterator<minstd_rand, Graph> RMATGen;
typedef graph_traits<Graph>::vertex_iterator vertex_iter;
typedef property_map<Graph, vertex_index_t>::type IndexMap;
int main(int argc, char* argv[])
{
if (argc < 3) {
fprintf(stderr, "usage: make_graph #vertices, #numedges [output]\n");
return EXIT_FAILURE;
}
typedef boost::graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef boost::graph_traits<Graph>::edges_size_type edges_size_type;
vertices_size_type n = atol(argv[1]);
edges_size_type m = atol(argv[2]);
FILE *f = stdout;
std::string out_file;
if (argc >= 4) {
out_file = argv[3];
f = fopen(argv[3], "w");
assert(f);
}
fprintf(stderr, "Vertices = %ld\n", n);
fprintf(stderr, "Edges = %ld\n", m);
std::clock_t start;
start = std::clock();
minstd_rand gen;
RMATGen gen_it(gen, n, m, 0.57, 0.19, 0.19, 0.05, true);
RMATGen gen_end;
for (; gen_it != gen_end; ++gen_it) {
fprintf(f, "%ld %ld\n", gen_it->first, gen_it->second);
}
#if 0
// Create graph with 100 nodes and 400 edges
Graph g(RMATGen(gen, n, m, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), n);
IndexMap index = get(vertex_index, g);
// Get vertex set
#if 0
std::pair<vertex_iter, vertex_iter> vp;
for (vp = vertices(g); vp.first != vp.second; ++vp.first)
std::cout << index[*vp.first] << " ";
std::cout << std::endl;
#endif
// Get edge set
graph_traits<Graph>::edge_iterator ei, ei_end;
for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
std::cout << index[source(*ei, g)]<< " " << index[target(*ei, g)] << "\n";
#endif
if (f != stdout) {
printf("close %s\n", out_file.c_str());
fclose(f);
}
std::cerr << "The time to build the graph = " << (std::clock()-start)/(double)CLOCKS_PER_SEC << std::endl;
return 0;
}
<commit_msg>[Graph]: use a better rand generator in RMAT.<commit_after>#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/rmat_graph_generator.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/graph/graph_traits.hpp>
#include <iostream>
#include <ctime>
#include <stdio.h>
using namespace boost;
typedef adjacency_list<> Graph;
// The length of cycle of rand48 is 2^48-1, which is much longer than
// minstd_rand.
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_random/reference.html
typedef rand48 rand_gen_t;
typedef rmat_iterator<rand_gen_t, Graph> RMATGen;
typedef graph_traits<Graph>::vertex_iterator vertex_iter;
typedef property_map<Graph, vertex_index_t>::type IndexMap;
int main(int argc, char* argv[])
{
if (argc < 3) {
fprintf(stderr, "usage: make_graph #vertices, #numedges [output]\n");
return EXIT_FAILURE;
}
typedef boost::graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef boost::graph_traits<Graph>::edges_size_type edges_size_type;
vertices_size_type n = atol(argv[1]);
edges_size_type m = atol(argv[2]);
FILE *f = stdout;
std::string out_file;
if (argc >= 4) {
out_file = argv[3];
f = fopen(argv[3], "w");
assert(f);
}
fprintf(stderr, "Vertices = %ld\n", n);
fprintf(stderr, "Edges = %ld\n", m);
std::clock_t start;
start = std::clock();
rand_gen_t gen(time(NULL));
RMATGen gen_it(gen, n, m, 0.57, 0.19, 0.19, 0.05, true);
RMATGen gen_end;
for (; gen_it != gen_end; ++gen_it) {
fprintf(f, "%ld %ld\n", gen_it->first, gen_it->second);
}
#if 0
// Create graph with 100 nodes and 400 edges
Graph g(RMATGen(gen, n, m, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), n);
IndexMap index = get(vertex_index, g);
// Get vertex set
#if 0
std::pair<vertex_iter, vertex_iter> vp;
for (vp = vertices(g); vp.first != vp.second; ++vp.first)
std::cout << index[*vp.first] << " ";
std::cout << std::endl;
#endif
// Get edge set
graph_traits<Graph>::edge_iterator ei, ei_end;
for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
std::cout << index[source(*ei, g)]<< " " << index[target(*ei, g)] << "\n";
#endif
if (f != stdout) {
printf("close %s\n", out_file.c_str());
fclose(f);
}
std::cerr << "The time to build the graph = " << (std::clock()-start)/(double)CLOCKS_PER_SEC << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2002, 2003, 2004, 2005, 2006, 2009 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//----------------------------------------------------------------------
// test the umfpack sparse direct solver on a mass matrix that is
// slightly modified to make it nonsymmetric. same as umfpack_03, but
// for a BlockSparseMatrix<double> instead of SparseMatrix<double> matrix
#include "../tests.h"
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <dofs/dof_tools.h>
#include <lac/block_sparse_matrix.h>
#include <lac/block_sparsity_pattern.h>
#include <lac/vector.h>
#include <lac/sparse_direct.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
template <int dim>
void test ()
{
deallog << dim << 'd' << std::endl;
Triangulation<dim> tria;
GridGenerator::hyper_cube (tria,0,1);
tria.refine_global (1);
// destroy the uniformity of the matrix by
// refining one cell
tria.begin_active()->set_refine_flag ();
tria.execute_coarsening_and_refinement ();
tria.refine_global(8-2*dim);
FE_Q<dim> fe (1);
DoFHandler<dim> dof_handler (tria);
dof_handler.distribute_dofs (fe);
deallog << "Number of dofs = " << dof_handler.n_dofs() << std::endl;
BlockSparsityPattern sparsity_pattern;
sparsity_pattern.reinit (3, 3);
for (unsigned int i=0; i<3; ++i)
for (unsigned int j=0; j<3; ++j)
sparsity_pattern.block(i,j).reinit (i!=2 ?
dof_handler.n_dofs()/3 :
dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3),
j!=2 ?
dof_handler.n_dofs()/3 :
dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3),
dof_handler.max_couplings_between_dofs(),
false);
sparsity_pattern.collect_sizes();
DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);
sparsity_pattern.compress ();
BlockSparseMatrix<double> B;
B.reinit (sparsity_pattern);
{
// for some reason, we can't
// create block matrices directly
// in matrixtools...
SparsityPattern xsparsity_pattern;
xsparsity_pattern.reinit (dof_handler.n_dofs(),
dof_handler.n_dofs(),
dof_handler.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof_handler, xsparsity_pattern);
xsparsity_pattern.compress ();
SparseMatrix<double> xB;
xB.reinit (xsparsity_pattern);
QGauss<dim> qr (2);
MatrixTools::create_mass_matrix (dof_handler, qr, xB);
// scale lower left part of the matrix by
// 1/2 and upper right part by 2 to make
// matrix nonsymmetric
for (SparseMatrix<double>::iterator p=xB.begin();
p!=xB.end(); ++p)
if (p->column() < p->row())
p->value() = p->value()/2;
else if (p->column() > p->row())
p->value() = p->value() * 2;
// check that we've done it right
for (SparseMatrix<double>::iterator p=xB.begin();
p!=xB.end(); ++p)
if (p->column() != p->row())
Assert (xB(p->row(),p->column()) != xB(p->column(),p->row()),
ExcInternalError());
// now copy stuff over
for (SparseMatrix<double>::const_iterator i = xB.begin(); i != xB.end(); ++i)
B.set (i->row(), i->column(), i->value());
}
// for a number of different solution
// vectors, make up a matching rhs vector
// and check what the UMFPACK solver finds
for (unsigned int i=0; i<3; ++i)
{
BlockVector<double> solution (3);
solution.block(0).reinit(dof_handler.n_dofs()/3);
solution.block(1).reinit(dof_handler.n_dofs()/3);
solution.block(2).reinit(dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3));
solution.collect_sizes();
BlockVector<double> x;
x.reinit (solution);
BlockVector<double> b;
b.reinit (solution);
for (unsigned int j=0; j<dof_handler.n_dofs(); ++j)
solution(j) = j+j*(i+1)*(i+1);
B.vmult (b, solution);
x = b;
Vector<double> tmp (solution.size());
tmp = x;
SparseDirectUMFPACK().solve (B, tmp);
x = tmp;
x -= solution;
deallog << "relative norm distance = "
<< x.l2_norm() / solution.l2_norm()
<< std::endl;
deallog << "absolute norms = "
<< x.l2_norm() << ' ' << solution.l2_norm()
<< std::endl;
Assert (x.l2_norm() / solution.l2_norm() < 1e-8,
ExcInternalError());
}
}
int main ()
{
std::ofstream logfile("umfpack_09/output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-9);
test<1> ();
test<2> ();
test<3> ();
}
<commit_msg>Change threshold for zero.<commit_after>//----------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2002, 2003, 2004, 2005, 2006, 2009, 2010 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//----------------------------------------------------------------------
// test the umfpack sparse direct solver on a mass matrix that is
// slightly modified to make it nonsymmetric. same as umfpack_03, but
// for a BlockSparseMatrix<double> instead of SparseMatrix<double> matrix
#include "../tests.h"
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <dofs/dof_tools.h>
#include <lac/block_sparse_matrix.h>
#include <lac/block_sparsity_pattern.h>
#include <lac/vector.h>
#include <lac/sparse_direct.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
template <int dim>
void test ()
{
deallog << dim << 'd' << std::endl;
Triangulation<dim> tria;
GridGenerator::hyper_cube (tria,0,1);
tria.refine_global (1);
// destroy the uniformity of the matrix by
// refining one cell
tria.begin_active()->set_refine_flag ();
tria.execute_coarsening_and_refinement ();
tria.refine_global(8-2*dim);
FE_Q<dim> fe (1);
DoFHandler<dim> dof_handler (tria);
dof_handler.distribute_dofs (fe);
deallog << "Number of dofs = " << dof_handler.n_dofs() << std::endl;
BlockSparsityPattern sparsity_pattern;
sparsity_pattern.reinit (3, 3);
for (unsigned int i=0; i<3; ++i)
for (unsigned int j=0; j<3; ++j)
sparsity_pattern.block(i,j).reinit (i!=2 ?
dof_handler.n_dofs()/3 :
dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3),
j!=2 ?
dof_handler.n_dofs()/3 :
dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3),
dof_handler.max_couplings_between_dofs(),
false);
sparsity_pattern.collect_sizes();
DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);
sparsity_pattern.compress ();
BlockSparseMatrix<double> B;
B.reinit (sparsity_pattern);
{
// for some reason, we can't
// create block matrices directly
// in matrixtools...
SparsityPattern xsparsity_pattern;
xsparsity_pattern.reinit (dof_handler.n_dofs(),
dof_handler.n_dofs(),
dof_handler.max_couplings_between_dofs());
DoFTools::make_sparsity_pattern (dof_handler, xsparsity_pattern);
xsparsity_pattern.compress ();
SparseMatrix<double> xB;
xB.reinit (xsparsity_pattern);
QGauss<dim> qr (2);
MatrixTools::create_mass_matrix (dof_handler, qr, xB);
// scale lower left part of the matrix by
// 1/2 and upper right part by 2 to make
// matrix nonsymmetric
for (SparseMatrix<double>::iterator p=xB.begin();
p!=xB.end(); ++p)
if (p->column() < p->row())
p->value() = p->value()/2;
else if (p->column() > p->row())
p->value() = p->value() * 2;
// check that we've done it right
for (SparseMatrix<double>::iterator p=xB.begin();
p!=xB.end(); ++p)
if (p->column() != p->row())
Assert (xB(p->row(),p->column()) != xB(p->column(),p->row()),
ExcInternalError());
// now copy stuff over
for (SparseMatrix<double>::const_iterator i = xB.begin(); i != xB.end(); ++i)
B.set (i->row(), i->column(), i->value());
}
// for a number of different solution
// vectors, make up a matching rhs vector
// and check what the UMFPACK solver finds
for (unsigned int i=0; i<3; ++i)
{
BlockVector<double> solution (3);
solution.block(0).reinit(dof_handler.n_dofs()/3);
solution.block(1).reinit(dof_handler.n_dofs()/3);
solution.block(2).reinit(dof_handler.n_dofs()-2*(dof_handler.n_dofs()/3));
solution.collect_sizes();
BlockVector<double> x;
x.reinit (solution);
BlockVector<double> b;
b.reinit (solution);
for (unsigned int j=0; j<dof_handler.n_dofs(); ++j)
solution(j) = j+j*(i+1)*(i+1);
B.vmult (b, solution);
x = b;
Vector<double> tmp (solution.size());
tmp = x;
SparseDirectUMFPACK().solve (B, tmp);
x = tmp;
x -= solution;
deallog << "relative norm distance = "
<< x.l2_norm() / solution.l2_norm()
<< std::endl;
deallog << "absolute norms = "
<< x.l2_norm() << ' ' << solution.l2_norm()
<< std::endl;
Assert (x.l2_norm() / solution.l2_norm() < 1e-8,
ExcInternalError());
}
}
int main ()
{
std::ofstream logfile("umfpack_09/output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-8);
test<1> ();
test<2> ();
test<3> ();
}
<|endoftext|> |
<commit_before>#include <memory>
#include <utility>
#include <functional>
struct Vector
{
float x, y, z;
};
int main()
{
{
std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 1, 1, 1 },
[](Vector* p) { printf("custom deleter called\n"); });
}
return 0;
}
<commit_msg>* Add test for deleter with std::bind<commit_after>#include <memory>
#include <utility>
#include <functional>
struct Vector
{
float x, y, z;
};
struct Del
{
void del(Vector*)
{
printf("Call Del::del\n");
}
};
int main()
{
{
std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 1, 1, 1 },
[](Vector* p) { printf("custom deleter called\n"); });
}
{
Del d;
std::unique_ptr<Vector, std::function<void(Vector*)>> v(new Vector{ 2, 2, 2 },
std::bind(&Del::del, d, std::placeholders::_1));
}
return 0;
}
<|endoftext|> |
<commit_before>#include "autopilot_tester.h"
#include <iostream>
#include <future>
using namespace mavsdk;
using namespace mavsdk::geometry;
std::string connection_url {"udp://"};
void AutopilotTester::connect(const std::string uri)
{
ConnectionResult ret = _mavsdk.add_any_connection(uri);
REQUIRE(ret == ConnectionResult::SUCCESS);
std::cout << "Waiting for system connect" << std::endl;
REQUIRE(poll_condition_with_timeout(
[this]() { return _mavsdk.is_connected(); }, std::chrono::seconds(10)));
auto& system = _mavsdk.system();
_telemetry.reset(new Telemetry(system));
_action.reset(new Action(system));
_mission.reset(new Mission(system));
}
void AutopilotTester::wait_until_ready()
{
std::cout << "Waiting for system to be ready" << std::endl;
CHECK(poll_condition_with_timeout(
[this]() { return _telemetry->health_all_ok(); }, std::chrono::seconds(10)));
}
void AutopilotTester::set_takeoff_altitude(const float altitude_m)
{
CHECK(Action::Result::SUCCESS == _action->set_takeoff_altitude(altitude_m));
const auto result = _action->get_takeoff_altitude();
CHECK(result.first == Action::Result::SUCCESS);
CHECK(result.second == Approx(altitude_m));
}
void AutopilotTester::arm()
{
const auto result = _action->arm();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::takeoff()
{
const auto result = _action->takeoff();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::land()
{
const auto result = _action->land();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::wait_until_disarmed()
{
REQUIRE(poll_condition_with_timeout(
[this]() { return !_telemetry->armed(); }, std::chrono::seconds(10)));
}
void AutopilotTester::wait_until_hovering()
{
REQUIRE(poll_condition_with_timeout(
[this]() { return _telemetry->landed_state() == Telemetry::LandedState::IN_AIR; }, std::chrono::seconds(10)));
}
void AutopilotTester::prepare_square_mission(MissionOptions mission_options)
{
const auto ct = _get_coordinate_transformation();
std::vector<std::shared_ptr<MissionItem>> mission_items {};
mission_items.push_back(_create_mission_item({mission_options.leg_length_m, 0.}, mission_options, ct));
mission_items.push_back(_create_mission_item({mission_options.leg_length_m, mission_options.leg_length_m}, mission_options, ct));
mission_items.push_back(_create_mission_item({0., mission_options.leg_length_m}, mission_options, ct));
_mission->set_return_to_launch_after_mission(mission_options.rtl_at_end);
std::promise<void> prom;
auto fut = prom.get_future();
_mission->upload_mission_async(mission_items, [&prom](Mission::Result result) {
REQUIRE(Mission::Result::SUCCESS == result);
prom.set_value();
});
REQUIRE(fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready);
}
void AutopilotTester::execute_mission()
{
std::promise<void> prom;
auto fut = prom.get_future();
_mission->start_mission_async([&prom](Mission::Result result) {
REQUIRE(Mission::Result::SUCCESS == result);
prom.set_value();
});
// TODO: Adapt time limit based on mission size, flight speed, sim speed factor, etc.
REQUIRE(poll_condition_with_timeout(
[this]() { return _mission->mission_finished(); }, std::chrono::seconds(30)));
REQUIRE(fut.wait_for(std::chrono::seconds(1)) == std::future_status::ready);
}
CoordinateTransformation AutopilotTester::_get_coordinate_transformation()
{
const auto home = _telemetry->home_position();
REQUIRE(std::isfinite(home.latitude_deg));
REQUIRE(std::isfinite(home.longitude_deg));
REQUIRE(std::isfinite(home.longitude_deg));
return CoordinateTransformation({home.latitude_deg, home.longitude_deg});
}
std::shared_ptr<MissionItem> AutopilotTester::_create_mission_item(
const CoordinateTransformation::LocalCoordinate& local_coordinate,
const MissionOptions& mission_options,
const CoordinateTransformation& ct)
{
auto mission_item = std::make_shared<MissionItem>();
const auto pos_north = ct.global_from_local(local_coordinate);
mission_item->set_position(pos_north.latitude_deg, pos_north.longitude_deg);
mission_item->set_relative_altitude(mission_options.relative_altitude_m);
return mission_item;
}
void AutopilotTester::execute_rtl()
{
REQUIRE(Action::Result::SUCCESS == _action->return_to_launch());
}<commit_msg>mavsdk_tests: raise timeout for realtime sim speed<commit_after>#include "autopilot_tester.h"
#include <iostream>
#include <future>
using namespace mavsdk;
using namespace mavsdk::geometry;
std::string connection_url {"udp://"};
void AutopilotTester::connect(const std::string uri)
{
ConnectionResult ret = _mavsdk.add_any_connection(uri);
REQUIRE(ret == ConnectionResult::SUCCESS);
std::cout << "Waiting for system connect" << std::endl;
REQUIRE(poll_condition_with_timeout(
[this]() { return _mavsdk.is_connected(); }, std::chrono::seconds(10)));
auto& system = _mavsdk.system();
_telemetry.reset(new Telemetry(system));
_action.reset(new Action(system));
_mission.reset(new Mission(system));
}
void AutopilotTester::wait_until_ready()
{
std::cout << "Waiting for system to be ready" << std::endl;
CHECK(poll_condition_with_timeout(
[this]() { return _telemetry->health_all_ok(); }, std::chrono::seconds(20)));
}
void AutopilotTester::set_takeoff_altitude(const float altitude_m)
{
CHECK(Action::Result::SUCCESS == _action->set_takeoff_altitude(altitude_m));
const auto result = _action->get_takeoff_altitude();
CHECK(result.first == Action::Result::SUCCESS);
CHECK(result.second == Approx(altitude_m));
}
void AutopilotTester::arm()
{
const auto result = _action->arm();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::takeoff()
{
const auto result = _action->takeoff();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::land()
{
const auto result = _action->land();
REQUIRE(result == Action::Result::SUCCESS);
}
void AutopilotTester::wait_until_disarmed()
{
REQUIRE(poll_condition_with_timeout(
[this]() { return !_telemetry->armed(); }, std::chrono::seconds(60)));
}
void AutopilotTester::wait_until_hovering()
{
REQUIRE(poll_condition_with_timeout(
[this]() { return _telemetry->landed_state() == Telemetry::LandedState::IN_AIR; }, std::chrono::seconds(10)));
}
void AutopilotTester::prepare_square_mission(MissionOptions mission_options)
{
const auto ct = _get_coordinate_transformation();
std::vector<std::shared_ptr<MissionItem>> mission_items {};
mission_items.push_back(_create_mission_item({mission_options.leg_length_m, 0.}, mission_options, ct));
mission_items.push_back(_create_mission_item({mission_options.leg_length_m, mission_options.leg_length_m}, mission_options, ct));
mission_items.push_back(_create_mission_item({0., mission_options.leg_length_m}, mission_options, ct));
_mission->set_return_to_launch_after_mission(mission_options.rtl_at_end);
std::promise<void> prom;
auto fut = prom.get_future();
_mission->upload_mission_async(mission_items, [&prom](Mission::Result result) {
REQUIRE(Mission::Result::SUCCESS == result);
prom.set_value();
});
REQUIRE(fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready);
}
void AutopilotTester::execute_mission()
{
std::promise<void> prom;
auto fut = prom.get_future();
_mission->start_mission_async([&prom](Mission::Result result) {
REQUIRE(Mission::Result::SUCCESS == result);
prom.set_value();
});
// TODO: Adapt time limit based on mission size, flight speed, sim speed factor, etc.
REQUIRE(poll_condition_with_timeout(
[this]() { return _mission->mission_finished(); }, std::chrono::seconds(60)));
REQUIRE(fut.wait_for(std::chrono::seconds(1)) == std::future_status::ready);
}
CoordinateTransformation AutopilotTester::_get_coordinate_transformation()
{
const auto home = _telemetry->home_position();
REQUIRE(std::isfinite(home.latitude_deg));
REQUIRE(std::isfinite(home.longitude_deg));
REQUIRE(std::isfinite(home.longitude_deg));
return CoordinateTransformation({home.latitude_deg, home.longitude_deg});
}
std::shared_ptr<MissionItem> AutopilotTester::_create_mission_item(
const CoordinateTransformation::LocalCoordinate& local_coordinate,
const MissionOptions& mission_options,
const CoordinateTransformation& ct)
{
auto mission_item = std::make_shared<MissionItem>();
const auto pos_north = ct.global_from_local(local_coordinate);
mission_item->set_position(pos_north.latitude_deg, pos_north.longitude_deg);
mission_item->set_relative_altitude(mission_options.relative_altitude_m);
return mission_item;
}
void AutopilotTester::execute_rtl()
{
REQUIRE(Action::Result::SUCCESS == _action->return_to_launch());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "media/audio/linux/pulse_output.h"
#include "base/message_loop.h"
#include "media/audio/audio_parameters.h"
#include "media/audio/audio_util.h"
#include "media/audio/linux/audio_manager_linux.h"
#include "media/base/data_buffer.h"
#include "media/base/seekable_buffer.h"
static pa_sample_format_t BitsToFormat(int bits_per_sample) {
switch (bits_per_sample) {
// Unsupported sample formats shown for reference. I am assuming we want
// signed and little endian because that is what we gave to ALSA.
case 8:
return PA_SAMPLE_U8;
// Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
case 16:
return PA_SAMPLE_S16LE;
// Also 16-bits: PA_SAMPLE_S16BE (big endian).
case 24:
return PA_SAMPLE_S24LE;
// Also 24-bits: PA_SAMPLE_S24BE (big endian).
// Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),
// and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
case 32:
return PA_SAMPLE_S32LE;
// Also 32-bits: PA_SAMPLE_S32BE (big endian),
// PA_SAMPLE_FLOAT32LE (floating point little endian),
// and PA_SAMPLE_FLOAT32BE (floating point big endian).
default:
return PA_SAMPLE_INVALID;
}
}
static size_t MicrosecondsToBytes(
uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
return microseconds * sample_rate * bytes_per_frame /
base::Time::kMicrosecondsPerSecond;
}
void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
void* state_addr) {
pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);
*state = pa_context_get_state(context);
}
void PulseAudioOutputStream::WriteRequestCallback(
pa_stream* playback_handle, size_t length, void* stream_addr) {
PulseAudioOutputStream* stream =
static_cast<PulseAudioOutputStream*>(stream_addr);
DCHECK_EQ(stream->message_loop_, MessageLoop::current());
stream->write_callback_handled_ = true;
// Fulfill write request.
stream->FulfillWriteRequest(length);
}
PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
AudioManagerLinux* manager,
MessageLoop* message_loop)
: channel_layout_(params.channel_layout),
channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
sample_format_(BitsToFormat(params.bits_per_sample)),
sample_rate_(params.sample_rate),
bytes_per_frame_(params.channels * params.bits_per_sample / 8),
manager_(manager),
pa_context_(NULL),
pa_mainloop_(NULL),
playback_handle_(NULL),
packet_size_(params.GetPacketSize()),
frames_per_packet_(packet_size_ / bytes_per_frame_),
client_buffer_(NULL),
volume_(1.0f),
stream_stopped_(true),
write_callback_handled_(false),
message_loop_(message_loop),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
source_callback_(NULL) {
DCHECK_EQ(message_loop_, MessageLoop::current());
DCHECK(manager_);
// TODO(slock): Sanity check input values.
}
PulseAudioOutputStream::~PulseAudioOutputStream() {
// All internal structures should already have been freed in Close(),
// which calls AudioManagerLinux::Release which deletes this object.
DCHECK(!playback_handle_);
DCHECK(!pa_context_);
DCHECK(!pa_mainloop_);
}
bool PulseAudioOutputStream::Open() {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(slock): Possibly move most of this to an OpenPlaybackDevice function
// in a new class 'pulse_util', like alsa_util.
// Create a mainloop API and connect to the default server.
pa_mainloop_ = pa_mainloop_new();
pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);
pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED;
pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL);
// Wait until PulseAudio is ready.
pa_context_set_state_callback(pa_context_, &ContextStateCallback,
&pa_context_state);
while (pa_context_state != PA_CONTEXT_READY) {
pa_mainloop_iterate(pa_mainloop_, 1, NULL);
if (pa_context_state == PA_CONTEXT_FAILED ||
pa_context_state == PA_CONTEXT_TERMINATED) {
Reset();
return false;
}
}
// Set sample specifications and open playback stream.
pa_sample_spec pa_sample_specifications;
pa_sample_specifications.format = sample_format_;
pa_sample_specifications.rate = sample_rate_;
pa_sample_specifications.channels = channel_count_;
playback_handle_ = pa_stream_new(pa_context_, "Playback",
&pa_sample_specifications, NULL);
// Initialize client buffer.
uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;
client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));
// Set write callback.
pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
// Set server-side buffer attributes.
// (uint32_t)-1 is the default and recommended value from PulseAudio's
// documentation, found at:
// http://freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.html.
pa_buffer_attr pa_buffer_attributes;
pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);
pa_buffer_attributes.tlength = output_packet_size;
pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1);
pa_buffer_attributes.minreq = static_cast<uint32_t>(-1);
pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);
// Connect playback stream.
pa_stream_connect_playback(playback_handle_, NULL,
&pa_buffer_attributes,
(pa_stream_flags_t)
(PA_STREAM_INTERPOLATE_TIMING |
PA_STREAM_ADJUST_LATENCY |
PA_STREAM_AUTO_TIMING_UPDATE),
NULL, NULL);
if (!playback_handle_) {
Reset();
return false;
}
return true;
}
void PulseAudioOutputStream::Reset() {
stream_stopped_ = true;
// Close the stream.
if (playback_handle_) {
pa_stream_flush(playback_handle_, NULL, NULL);
pa_stream_disconnect(playback_handle_);
// Release PulseAudio structures.
pa_stream_unref(playback_handle_);
playback_handle_ = NULL;
}
if (pa_context_) {
pa_context_unref(pa_context_);
pa_context_ = NULL;
}
if (pa_mainloop_) {
pa_mainloop_free(pa_mainloop_);
pa_mainloop_ = NULL;
}
// Release internal buffer.
client_buffer_.reset();
}
void PulseAudioOutputStream::Close() {
DCHECK_EQ(message_loop_, MessageLoop::current());
Reset();
// Signal to the manager that we're closed and can be removed.
// This should be the last call in the function as it deletes "this".
manager_->ReleaseOutputStream(this);
}
void PulseAudioOutputStream::WaitForWriteRequest() {
DCHECK_EQ(message_loop_, MessageLoop::current());
if (stream_stopped_)
return;
// Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,
// post a task to iterate the mainloop again.
write_callback_handled_ = false;
pa_mainloop_iterate(pa_mainloop_, 1, NULL);
if (!write_callback_handled_) {
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
}
bool PulseAudioOutputStream::BufferPacketFromSource() {
uint32 buffer_delay = client_buffer_->forward_bytes();
pa_usec_t pa_latency_micros;
int negative;
pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
sample_rate_,
bytes_per_frame_);
// TODO(slock): Deal with negative latency (negative == 1). This has yet
// to happen in practice though.
scoped_refptr<media::DataBuffer> packet =
new media::DataBuffer(packet_size_);
size_t packet_size = RunDataCallback(packet->GetWritableData(),
packet->GetBufferSize(),
AudioBuffersState(buffer_delay,
hardware_delay));
if (packet_size == 0)
return false;
// TODO(slock): Swizzling and downmixing.
media::AdjustVolume(packet->GetWritableData(),
packet_size,
channel_count_,
bytes_per_frame_ / channel_count_,
volume_);
packet->SetDataSize(packet_size);
// Add the packet to the buffer.
client_buffer_->Append(packet);
return true;
}
void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
// If we have enough data to fulfill the request, we can finish the write.
if (stream_stopped_)
return;
// Request more data from the source until we can fulfill the request or
// fail to receive anymore data.
bool buffering_successful = true;
while (client_buffer_->forward_bytes() < requested_bytes &&
buffering_successful) {
buffering_successful = BufferPacketFromSource();
}
size_t bytes_written = 0;
if (client_buffer_->forward_bytes() > 0) {
// Try to fulfill the request by writing as many of the requested bytes to
// the stream as we can.
WriteToStream(requested_bytes, &bytes_written);
}
if (bytes_written < requested_bytes) {
// We weren't able to buffer enough data to fulfill the request. Try to
// fulfill the rest of the request later.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::FulfillWriteRequest,
requested_bytes - bytes_written));
} else {
// Continue playback.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
}
void PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,
size_t* bytes_written) {
*bytes_written = 0;
while (*bytes_written < bytes_to_write) {
const uint8* chunk;
size_t chunk_size;
// Stop writing if there is no more data available.
if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))
break;
// Write data to stream.
pa_stream_write(playback_handle_, chunk, chunk_size,
NULL, 0LL, PA_SEEK_RELATIVE);
client_buffer_->Seek(chunk_size);
*bytes_written += chunk_size;
}
}
void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK_EQ(message_loop_, MessageLoop::current());
CHECK(callback);
source_callback_ = callback;
// Clear buffer, it might still have data in it.
client_buffer_->Clear();
stream_stopped_ = false;
// Start playback.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
void PulseAudioOutputStream::Stop() {
DCHECK_EQ(message_loop_, MessageLoop::current());
stream_stopped_ = true;
}
void PulseAudioOutputStream::SetVolume(double volume) {
DCHECK_EQ(message_loop_, MessageLoop::current());
volume_ = static_cast<float>(volume);
}
void PulseAudioOutputStream::GetVolume(double* volume) {
DCHECK_EQ(message_loop_, MessageLoop::current());
*volume = volume_;
}
uint32 PulseAudioOutputStream::RunDataCallback(
uint8* dest, uint32 max_size, AudioBuffersState buffers_state) {
if (source_callback_)
return source_callback_->OnMoreData(this, dest, max_size, buffers_state);
return 0;
}
<commit_msg>Adds Surround Sound support using PulseAudio.<commit_after>// Copyright (c) 2011 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 "media/audio/linux/pulse_output.h"
#include "base/message_loop.h"
#include "media/audio/audio_parameters.h"
#include "media/audio/audio_util.h"
#include "media/audio/linux/audio_manager_linux.h"
#include "media/base/data_buffer.h"
#include "media/base/seekable_buffer.h"
static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {
switch (bits_per_sample) {
// Unsupported sample formats shown for reference. I am assuming we want
// signed and little endian because that is what we gave to ALSA.
case 8:
return PA_SAMPLE_U8;
// Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
case 16:
return PA_SAMPLE_S16LE;
// Also 16-bits: PA_SAMPLE_S16BE (big endian).
case 24:
return PA_SAMPLE_S24LE;
// Also 24-bits: PA_SAMPLE_S24BE (big endian).
// Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),
// and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
case 32:
return PA_SAMPLE_S32LE;
// Also 32-bits: PA_SAMPLE_S32BE (big endian),
// PA_SAMPLE_FLOAT32LE (floating point little endian),
// and PA_SAMPLE_FLOAT32BE (floating point big endian).
default:
return PA_SAMPLE_INVALID;
}
}
static pa_channel_position ChromiumToPAChannelPosition(Channels channel) {
switch (channel) {
// PulseAudio does not differentiate between left/right and
// stereo-left/stereo-right, both translate to front-left/front-right.
case LEFT:
case STEREO_LEFT:
return PA_CHANNEL_POSITION_FRONT_LEFT;
case RIGHT:
case STEREO_RIGHT:
return PA_CHANNEL_POSITION_FRONT_RIGHT;
case CENTER:
return PA_CHANNEL_POSITION_FRONT_CENTER;
case LFE:
return PA_CHANNEL_POSITION_LFE;
case BACK_LEFT:
return PA_CHANNEL_POSITION_REAR_LEFT;
case BACK_RIGHT:
return PA_CHANNEL_POSITION_REAR_RIGHT;
case LEFT_OF_CENTER:
return PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
case RIGHT_OF_CENTER:
return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
case BACK_CENTER:
return PA_CHANNEL_POSITION_REAR_CENTER;
case SIDE_LEFT:
return PA_CHANNEL_POSITION_SIDE_LEFT;
case SIDE_RIGHT:
return PA_CHANNEL_POSITION_SIDE_RIGHT;
case CHANNELS_MAX:
return PA_CHANNEL_POSITION_INVALID;
}
NOTREACHED();
}
static pa_channel_map ChannelLayoutToPAChannelMap(
ChannelLayout channel_layout) {
// Initialize channel map.
pa_channel_map channel_map;
pa_channel_map_init(&channel_map);
channel_map.channels = ChannelLayoutToChannelCount(channel_layout);
// All channel maps have the same size array of channel positions.
for (unsigned int channel = 0; channel != CHANNELS_MAX; ++channel) {
int channel_position = kChannelOrderings[channel_layout][channel];
if (channel_position > -1) {
channel_map.map[channel_position] = ChromiumToPAChannelPosition(
static_cast<Channels>(channel));
} else {
// PulseAudio expects unused channels in channel maps to be filled with
// PA_CHANNEL_POSITION_MONO.
channel_map.map[channel_position] = PA_CHANNEL_POSITION_MONO;
}
}
// Fill in the rest of the unused channels.
for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX;
++channel) {
channel_map.map[channel] = PA_CHANNEL_POSITION_MONO;
}
return channel_map;
}
static size_t MicrosecondsToBytes(
uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
return microseconds * sample_rate * bytes_per_frame /
base::Time::kMicrosecondsPerSecond;
}
void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
void* state_addr) {
pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);
*state = pa_context_get_state(context);
}
void PulseAudioOutputStream::WriteRequestCallback(
pa_stream* playback_handle, size_t length, void* stream_addr) {
PulseAudioOutputStream* stream =
static_cast<PulseAudioOutputStream*>(stream_addr);
DCHECK_EQ(stream->message_loop_, MessageLoop::current());
stream->write_callback_handled_ = true;
// Fulfill write request.
stream->FulfillWriteRequest(length);
}
PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
AudioManagerLinux* manager,
MessageLoop* message_loop)
: channel_layout_(params.channel_layout),
channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
sample_format_(BitsToPASampleFormat(params.bits_per_sample)),
sample_rate_(params.sample_rate),
bytes_per_frame_(params.channels * params.bits_per_sample / 8),
manager_(manager),
pa_context_(NULL),
pa_mainloop_(NULL),
playback_handle_(NULL),
packet_size_(params.GetPacketSize()),
frames_per_packet_(packet_size_ / bytes_per_frame_),
client_buffer_(NULL),
volume_(1.0f),
stream_stopped_(true),
write_callback_handled_(false),
message_loop_(message_loop),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
source_callback_(NULL) {
DCHECK_EQ(message_loop_, MessageLoop::current());
DCHECK(manager_);
// TODO(slock): Sanity check input values.
}
PulseAudioOutputStream::~PulseAudioOutputStream() {
// All internal structures should already have been freed in Close(),
// which calls AudioManagerLinux::Release which deletes this object.
DCHECK(!playback_handle_);
DCHECK(!pa_context_);
DCHECK(!pa_mainloop_);
}
bool PulseAudioOutputStream::Open() {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(slock): Possibly move most of this to an OpenPlaybackDevice function
// in a new class 'pulse_util', like alsa_util.
// Create a mainloop API and connect to the default server.
pa_mainloop_ = pa_mainloop_new();
pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);
pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED;
pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL);
// Wait until PulseAudio is ready.
pa_context_set_state_callback(pa_context_, &ContextStateCallback,
&pa_context_state);
while (pa_context_state != PA_CONTEXT_READY) {
pa_mainloop_iterate(pa_mainloop_, 1, NULL);
if (pa_context_state == PA_CONTEXT_FAILED ||
pa_context_state == PA_CONTEXT_TERMINATED) {
Reset();
return false;
}
}
// Set sample specifications.
pa_sample_spec pa_sample_specifications;
pa_sample_specifications.format = sample_format_;
pa_sample_specifications.rate = sample_rate_;
pa_sample_specifications.channels = channel_count_;
// Get channel mapping and open playback stream.
pa_channel_map* map = NULL;
pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap(
channel_layout_);
if (source_channel_map.channels != 0) {
// The source data uses a supported channel map so we will use it rather
// than the default channel map (NULL).
map = &source_channel_map;
}
playback_handle_ = pa_stream_new(pa_context_, "Playback",
&pa_sample_specifications, map);
// Initialize client buffer.
uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;
client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));
// Set write callback.
pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
// Set server-side buffer attributes.
// (uint32_t)-1 is the default and recommended value from PulseAudio's
// documentation, found at:
// http://freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.html.
pa_buffer_attr pa_buffer_attributes;
pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);
pa_buffer_attributes.tlength = output_packet_size;
pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1);
pa_buffer_attributes.minreq = static_cast<uint32_t>(-1);
pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);
// Connect playback stream.
pa_stream_connect_playback(playback_handle_, NULL,
&pa_buffer_attributes,
(pa_stream_flags_t)
(PA_STREAM_INTERPOLATE_TIMING |
PA_STREAM_ADJUST_LATENCY |
PA_STREAM_AUTO_TIMING_UPDATE),
NULL, NULL);
if (!playback_handle_) {
Reset();
return false;
}
return true;
}
void PulseAudioOutputStream::Reset() {
stream_stopped_ = true;
// Close the stream.
if (playback_handle_) {
pa_stream_flush(playback_handle_, NULL, NULL);
pa_stream_disconnect(playback_handle_);
// Release PulseAudio structures.
pa_stream_unref(playback_handle_);
playback_handle_ = NULL;
}
if (pa_context_) {
pa_context_unref(pa_context_);
pa_context_ = NULL;
}
if (pa_mainloop_) {
pa_mainloop_free(pa_mainloop_);
pa_mainloop_ = NULL;
}
// Release internal buffer.
client_buffer_.reset();
}
void PulseAudioOutputStream::Close() {
DCHECK_EQ(message_loop_, MessageLoop::current());
Reset();
// Signal to the manager that we're closed and can be removed.
// This should be the last call in the function as it deletes "this".
manager_->ReleaseOutputStream(this);
}
void PulseAudioOutputStream::WaitForWriteRequest() {
DCHECK_EQ(message_loop_, MessageLoop::current());
if (stream_stopped_)
return;
// Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,
// post a task to iterate the mainloop again.
write_callback_handled_ = false;
pa_mainloop_iterate(pa_mainloop_, 1, NULL);
if (!write_callback_handled_) {
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
}
bool PulseAudioOutputStream::BufferPacketFromSource() {
uint32 buffer_delay = client_buffer_->forward_bytes();
pa_usec_t pa_latency_micros;
int negative;
pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
sample_rate_,
bytes_per_frame_);
// TODO(slock): Deal with negative latency (negative == 1). This has yet
// to happen in practice though.
scoped_refptr<media::DataBuffer> packet =
new media::DataBuffer(packet_size_);
size_t packet_size = RunDataCallback(packet->GetWritableData(),
packet->GetBufferSize(),
AudioBuffersState(buffer_delay,
hardware_delay));
if (packet_size == 0)
return false;
media::AdjustVolume(packet->GetWritableData(),
packet_size,
channel_count_,
bytes_per_frame_ / channel_count_,
volume_);
packet->SetDataSize(packet_size);
// Add the packet to the buffer.
client_buffer_->Append(packet);
return true;
}
void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
// If we have enough data to fulfill the request, we can finish the write.
if (stream_stopped_)
return;
// Request more data from the source until we can fulfill the request or
// fail to receive anymore data.
bool buffering_successful = true;
while (client_buffer_->forward_bytes() < requested_bytes &&
buffering_successful) {
buffering_successful = BufferPacketFromSource();
}
size_t bytes_written = 0;
if (client_buffer_->forward_bytes() > 0) {
// Try to fulfill the request by writing as many of the requested bytes to
// the stream as we can.
WriteToStream(requested_bytes, &bytes_written);
}
if (bytes_written < requested_bytes) {
// We weren't able to buffer enough data to fulfill the request. Try to
// fulfill the rest of the request later.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::FulfillWriteRequest,
requested_bytes - bytes_written));
} else {
// Continue playback.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
}
void PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,
size_t* bytes_written) {
*bytes_written = 0;
while (*bytes_written < bytes_to_write) {
const uint8* chunk;
size_t chunk_size;
// Stop writing if there is no more data available.
if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))
break;
// Write data to stream.
pa_stream_write(playback_handle_, chunk, chunk_size,
NULL, 0LL, PA_SEEK_RELATIVE);
client_buffer_->Seek(chunk_size);
*bytes_written += chunk_size;
}
}
void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK_EQ(message_loop_, MessageLoop::current());
CHECK(callback);
source_callback_ = callback;
// Clear buffer, it might still have data in it.
client_buffer_->Clear();
stream_stopped_ = false;
// Start playback.
message_loop_->PostTask(
FROM_HERE,
method_factory_.NewRunnableMethod(
&PulseAudioOutputStream::WaitForWriteRequest));
}
void PulseAudioOutputStream::Stop() {
DCHECK_EQ(message_loop_, MessageLoop::current());
stream_stopped_ = true;
}
void PulseAudioOutputStream::SetVolume(double volume) {
DCHECK_EQ(message_loop_, MessageLoop::current());
volume_ = static_cast<float>(volume);
}
void PulseAudioOutputStream::GetVolume(double* volume) {
DCHECK_EQ(message_loop_, MessageLoop::current());
*volume = volume_;
}
uint32 PulseAudioOutputStream::RunDataCallback(
uint8* dest, uint32 max_size, AudioBuffersState buffers_state) {
if (source_callback_)
return source_callback_->OnMoreData(this, dest, max_size, buffers_state);
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************\
* Copyright 2005, 2006 Niels Lohmann, Christian Gierds, Dennis Reinert *
* *
* This file is part of BPEL2oWFN. *
* *
* BPEL2oWFN 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. *
* *
* BPEL2oWFN 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 BPEL2oWFN; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. *
\****************************************************************************/
/*!
* \file main.cc
*
* \brief The control component for BPEL2oWFN
*
* This file controls the behaviour of BPEL2oWFN and is the interface to the
* environment.
*
* \author
* - responsible: Christian Gierds <gierds@informatik.hu-berlin.de>
* - last changes of: \$Author: gierds $
*
* \date
* - created: 2005/10/18
* - last changed: \$Date: 2006/06/23 08:47:24 $
*
* \note This file is part of the tool BPEL2oWFN and was created during the
* project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
* http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
* for details.
*
* \version \$Revision: 1.84 $
* - 2005-11-15 (gierds) Moved command line evaluation to helpers.cc.
* Added option to created (abstracted) low level nets.
* Added option for LoLA output.
* - 2005-11-15 (nlohmann) Call Exception::info() to signal error.
* - 2005-11-16 (gierds) Use of error() and cleanup() as defined in
* helpers.cc
* - 2005-12-13 (gierds) Added variables in order to handle creation
* of oWFNs.
*
*/
#include "main.h"
#include "options.h"
#include "ast-printers.h"
/// The Petri Net
PetriNet *TheNet = new PetriNet();
/// The CFG
CFGBlock * TheCFG = NULL;
void cfg()
{
// create CFG
if (modus == M_CFG) // || modus == M_PETRINET
{
TheCFG = NULL;
trace(TRACE_INFORMATION, "-> Unparsing AST to CFG ...\n");
TheProcess->unparse(kc::pseudoPrinter, kc::cfg);
trace(TRACE_DEBUG, "[CFG] checking for DPE\n");
// do some business with CFG
list<kc::integer> kcl;
TheCFG->needsDPE(0, kcl);
TheCFG->resetProcessedFlag();
trace(TRACE_DEBUG, "[CFG] checking for cyclic links\n");
/// \todo (gierds) check for cyclic links, otherwise we will fail
TheCFG->checkForCyclicLinks();
TheCFG->resetProcessedFlag(true);
trace(TRACE_DEBUG, "[CFG] checking for uninitialized variables\n");
// test
TheCFG->checkForUninitializedVariables();
TheCFG->resetProcessedFlag();
/// end test
TheCFG->lastBlock->checkForConflictingReceive();
TheCFG->resetProcessedFlag(true, false);
}
if (modus == M_CFG)
{
if (formats[F_DOT])
{
if (output_filename != "")
{
output = openOutput(output_filename + ".cfg." + suffixes[F_DOT]);
}
trace(TRACE_INFORMATION, "-> Printing CFG in dot ...\n");
// output CFG;
cfgDot(TheCFG);
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
// delete CFG
if (modus == M_CFG || modus == M_PETRINET)
{
delete(TheCFG);
}
}
void petrinet_unparse()
{
// if(modus == M_PETRINET)
{
trace(TRACE_INFORMATION, "-> Unparsing AST to Petri net ...\n");
if (parameters[P_COMMUNICATIONONLY] == false)
TheProcess->unparse(kc::pseudoPrinter, kc::petrinet);
else
TheProcess->unparse(kc::pseudoPrinter, kc::petrinetsmall);
}
}
/**
* Entry point for BPEL2oWFN.
* Controls the behaviour of input and output.
*
* \param argc number of command line arguments
* \param argv array with command line arguments
*
* \returns Error code (0 if everything went well)
*/
int main( int argc, char *argv[])
{
try
{
/***
* Reading command line arguments and triggering appropriate behaviour.
* In case of false parameters call command line help function and exit.
*/
parse_command_line(argc, argv);
PetriNet * TheNet2 = new PetriNet();
list< std::string >::iterator file = inputfiles.begin();
do {
if (inputfiles.size() >= 1)
{
filename = *file;
if (!(yyin = fopen(filename.c_str(), "r")))
{
throw Exception(FILE_NOT_FOUND, "File '" + filename + "' not found.\n");
}
}
trace(TRACE_INFORMATION, "Parsing " + filename + " ...\n");
// invoke Bison parser
int error = yyparse();
if (!error)
{
trace(TRACE_INFORMATION, "Parsing complete.\n");
if ( filename != "<STDIN>" && yyin != NULL)
{
trace(TRACE_INFORMATION," + Closing input file: " + filename + "\n");
fclose(yyin);
}
cfg();
if (modus == M_PETRINET || modus == M_CONSISTENCY)
{
petrinet_unparse();
if (modus == M_CONSISTENCY)
{
unsigned int pos = file->rfind(".bpel", file->length());
unsigned int pos2 = file->rfind("/", file->length());
std::string prefix = "";
if (pos == (file->length() - 5))
{
prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_";
}
if ( parameters[P_SIMPLIFY] )
{
trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n");
TheNet->simplify();
}
TheNet->addPrefix(prefix);
TheNet2->connectNet(TheNet);
TheNet = new PetriNet();
TheProcess = NULL;
}
}
}
else
{
cleanup();
return error;
}
file++;
} while (modus == M_CONSISTENCY && file != inputfiles.end());
if (modus == M_CONSISTENCY)
{
TheNet = TheNet2;
}
if (modus == M_AST)
{
trace(TRACE_INFORMATION, "-> Printing AST ...\n");
TheProcess->print();
}
if (modus == M_PRETTY)
{
if (formats[F_XML])
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_XML]);
}
trace(TRACE_INFORMATION, "-> Printing \"pretty\" XML ...\n");
TheProcess->unparse(kc::printer, kc::xml);
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
if (modus == M_PETRINET || modus == M_CONSISTENCY)
{
// remove variables?
if ( parameters[P_NOVARIABLES] )
{
trace(TRACE_INFORMATION, "-> Remove variable places from Petri Net ...\n");
TheNet->removeVariables();
}
// simplify net ?
if ( parameters[P_SIMPLIFY] )
{
trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n");
TheNet->simplify();
}
// create oWFN output ?
if ( formats[F_OWFN] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_OWFN]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for oWFN ...\n");
TheNet->owfnOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create LoLA output ?
if ( formats[F_LOLA] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_LOLA]);
}
if (modus == M_CONSISTENCY)
{
TheNet->makeChannelsInternal();
}
trace(TRACE_INFORMATION, "-> Printing Petri net for LoLA ...\n");
TheNet->lolaOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
if (modus == M_CONSISTENCY)
{
if (output_filename != "")
{
output = openOutput(output_filename + ".task");
}
std::string comment = "{ AG EF (";
std::string formula = "FORMULA\n ALLPATH ALWAYS EXPATH EVENTUALLY (";
std::string andStr = "";
for (list< std::string >::iterator file = inputfiles.begin(); file != inputfiles.end(); file++)
{
unsigned int pos = file->rfind(".bpel", file->length());
unsigned int pos2 = file->rfind("/", file->length());
std::string prefix = "";
if (pos == (file->length() - 5))
{
prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_";
}
comment += andStr + prefix + "1.internal.final";
formula += andStr + TheNet->findPlace(prefix + "1.internal.final")->nodeShortName() + " > 0";
andStr = " AND ";
}
comment += ") }";
formula += ")";
(*output) << comment << endl << endl;
(*output) << formula << endl << endl;
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
// create PNML output ?
if ( formats[F_PNML] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_PNML]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for PNML ...\n");
TheNet->pnmlOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create PEP output ?
if ( formats[F_PEP] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_PEP]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for PEP ...\n");
TheNet->pepOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create APNN output ?
if ( formats[F_APNN] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_APNN]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for APNN ...\n");
TheNet->apnnOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create dot output ?
if ( formats[F_DOT] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_DOT]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for dot ...\n");
TheNet->dotOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
std::string systemcall = "dot -q -Tpng -o" + output_filename + ".png " + output_filename + "." + suffixes[F_DOT];
trace(TRACE_INFORMATION, "Invoking dot with the following options:\n");
trace(TRACE_INFORMATION, systemcall + "\n\n");
system(systemcall.c_str());
}
}
// create info file ?
if ( formats[F_INFO] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_INFO]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net information ...\n");
TheNet->printInformation();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// a hack for Turku: show that our tool exists
if (modus == M_PETRINET || modus == M_CONSISTENCY)
cerr << TheNet->information() << endl;
}
}
catch (Exception& e)
{
// output info file ?
if ( formats[F_INFO] )
{
output = log_output;
// just print to std::out
TheNet->printInformation();
output = NULL;
}
error(e);
}
return 0;
}
<commit_msg>* special Turku output now appears directly after the simplification<commit_after>/*****************************************************************************\
* Copyright 2005, 2006 Niels Lohmann, Christian Gierds, Dennis Reinert *
* *
* This file is part of BPEL2oWFN. *
* *
* BPEL2oWFN 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. *
* *
* BPEL2oWFN 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 BPEL2oWFN; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. *
\****************************************************************************/
/*!
* \file main.cc
*
* \brief The control component for BPEL2oWFN
*
* This file controls the behaviour of BPEL2oWFN and is the interface to the
* environment.
*
* \author
* - responsible: Christian Gierds <gierds@informatik.hu-berlin.de>
* - last changes of: \$Author: gierds $
*
* \date
* - created: 2005/10/18
* - last changed: \$Date: 2006/06/23 09:10:43 $
*
* \note This file is part of the tool BPEL2oWFN and was created during the
* project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
* http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
* for details.
*
* \version \$Revision: 1.85 $
* - 2005-11-15 (gierds) Moved command line evaluation to helpers.cc.
* Added option to created (abstracted) low level nets.
* Added option for LoLA output.
* - 2005-11-15 (nlohmann) Call Exception::info() to signal error.
* - 2005-11-16 (gierds) Use of error() and cleanup() as defined in
* helpers.cc
* - 2005-12-13 (gierds) Added variables in order to handle creation
* of oWFNs.
*
*/
#include "main.h"
#include "options.h"
#include "ast-printers.h"
/// The Petri Net
PetriNet *TheNet = new PetriNet();
/// The CFG
CFGBlock * TheCFG = NULL;
void cfg()
{
// create CFG
if (modus == M_CFG) // || modus == M_PETRINET
{
TheCFG = NULL;
trace(TRACE_INFORMATION, "-> Unparsing AST to CFG ...\n");
TheProcess->unparse(kc::pseudoPrinter, kc::cfg);
trace(TRACE_DEBUG, "[CFG] checking for DPE\n");
// do some business with CFG
list<kc::integer> kcl;
TheCFG->needsDPE(0, kcl);
TheCFG->resetProcessedFlag();
trace(TRACE_DEBUG, "[CFG] checking for cyclic links\n");
/// \todo (gierds) check for cyclic links, otherwise we will fail
TheCFG->checkForCyclicLinks();
TheCFG->resetProcessedFlag(true);
trace(TRACE_DEBUG, "[CFG] checking for uninitialized variables\n");
// test
TheCFG->checkForUninitializedVariables();
TheCFG->resetProcessedFlag();
/// end test
TheCFG->lastBlock->checkForConflictingReceive();
TheCFG->resetProcessedFlag(true, false);
}
if (modus == M_CFG)
{
if (formats[F_DOT])
{
if (output_filename != "")
{
output = openOutput(output_filename + ".cfg." + suffixes[F_DOT]);
}
trace(TRACE_INFORMATION, "-> Printing CFG in dot ...\n");
// output CFG;
cfgDot(TheCFG);
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
// delete CFG
if (modus == M_CFG || modus == M_PETRINET)
{
delete(TheCFG);
}
}
void petrinet_unparse()
{
// if(modus == M_PETRINET)
{
trace(TRACE_INFORMATION, "-> Unparsing AST to Petri net ...\n");
if (parameters[P_COMMUNICATIONONLY] == false)
TheProcess->unparse(kc::pseudoPrinter, kc::petrinet);
else
TheProcess->unparse(kc::pseudoPrinter, kc::petrinetsmall);
}
}
/**
* Entry point for BPEL2oWFN.
* Controls the behaviour of input and output.
*
* \param argc number of command line arguments
* \param argv array with command line arguments
*
* \returns Error code (0 if everything went well)
*/
int main( int argc, char *argv[])
{
try
{
/***
* Reading command line arguments and triggering appropriate behaviour.
* In case of false parameters call command line help function and exit.
*/
parse_command_line(argc, argv);
PetriNet * TheNet2 = new PetriNet();
list< std::string >::iterator file = inputfiles.begin();
do {
if (inputfiles.size() >= 1)
{
filename = *file;
if (!(yyin = fopen(filename.c_str(), "r")))
{
throw Exception(FILE_NOT_FOUND, "File '" + filename + "' not found.\n");
}
}
trace(TRACE_INFORMATION, "Parsing " + filename + " ...\n");
// invoke Bison parser
int error = yyparse();
if (!error)
{
trace(TRACE_INFORMATION, "Parsing complete.\n");
if ( filename != "<STDIN>" && yyin != NULL)
{
trace(TRACE_INFORMATION," + Closing input file: " + filename + "\n");
fclose(yyin);
}
cfg();
if (modus == M_PETRINET || modus == M_CONSISTENCY)
{
petrinet_unparse();
if (modus == M_CONSISTENCY)
{
unsigned int pos = file->rfind(".bpel", file->length());
unsigned int pos2 = file->rfind("/", file->length());
std::string prefix = "";
if (pos == (file->length() - 5))
{
prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_";
}
if ( parameters[P_SIMPLIFY] )
{
trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n");
TheNet->simplify();
}
TheNet->addPrefix(prefix);
TheNet2->connectNet(TheNet);
TheNet = new PetriNet();
TheProcess = NULL;
}
}
}
else
{
cleanup();
return error;
}
file++;
} while (modus == M_CONSISTENCY && file != inputfiles.end());
if (modus == M_CONSISTENCY)
{
TheNet = TheNet2;
}
if (modus == M_AST)
{
trace(TRACE_INFORMATION, "-> Printing AST ...\n");
TheProcess->print();
}
if (modus == M_PRETTY)
{
if (formats[F_XML])
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_XML]);
}
trace(TRACE_INFORMATION, "-> Printing \"pretty\" XML ...\n");
TheProcess->unparse(kc::printer, kc::xml);
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
if (modus == M_PETRINET || modus == M_CONSISTENCY)
{
// remove variables?
if ( parameters[P_NOVARIABLES] )
{
trace(TRACE_INFORMATION, "-> Remove variable places from Petri Net ...\n");
TheNet->removeVariables();
}
// simplify net ?
if ( parameters[P_SIMPLIFY] )
{
trace(TRACE_INFORMATION, "-> Structurally simplifying Petri Net ...\n");
TheNet->simplify();
}
// a hack for Turku: show that our tool exists
trace(TheNet->information() + "\n");
// create oWFN output ?
if ( formats[F_OWFN] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_OWFN]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for oWFN ...\n");
TheNet->owfnOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create LoLA output ?
if ( formats[F_LOLA] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_LOLA]);
}
if (modus == M_CONSISTENCY)
{
TheNet->makeChannelsInternal();
}
trace(TRACE_INFORMATION, "-> Printing Petri net for LoLA ...\n");
TheNet->lolaOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
if (modus == M_CONSISTENCY)
{
if (output_filename != "")
{
output = openOutput(output_filename + ".task");
}
std::string comment = "{ AG EF (";
std::string formula = "FORMULA\n ALLPATH ALWAYS EXPATH EVENTUALLY (";
std::string andStr = "";
for (list< std::string >::iterator file = inputfiles.begin(); file != inputfiles.end(); file++)
{
unsigned int pos = file->rfind(".bpel", file->length());
unsigned int pos2 = file->rfind("/", file->length());
std::string prefix = "";
if (pos == (file->length() - 5))
{
prefix = file->substr(pos2 + 1, pos - pos2 - 1) + "_";
}
comment += andStr + prefix + "1.internal.final";
formula += andStr + TheNet->findPlace(prefix + "1.internal.final")->nodeShortName() + " > 0";
andStr = " AND ";
}
comment += ") }";
formula += ")";
(*output) << comment << endl << endl;
(*output) << formula << endl << endl;
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
// create PNML output ?
if ( formats[F_PNML] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_PNML]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for PNML ...\n");
TheNet->pnmlOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create PEP output ?
if ( formats[F_PEP] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_PEP]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for PEP ...\n");
TheNet->pepOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create APNN output ?
if ( formats[F_APNN] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_APNN]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for APNN ...\n");
TheNet->apnnOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
// create dot output ?
if ( formats[F_DOT] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_DOT]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net for dot ...\n");
TheNet->dotOut();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
std::string systemcall = "dot -q -Tpng -o" + output_filename + ".png " + output_filename + "." + suffixes[F_DOT];
trace(TRACE_INFORMATION, "Invoking dot with the following options:\n");
trace(TRACE_INFORMATION, systemcall + "\n\n");
system(systemcall.c_str());
}
}
// create info file ?
if ( formats[F_INFO] )
{
if (output_filename != "")
{
output = openOutput(output_filename + "." + suffixes[F_INFO]);
}
trace(TRACE_INFORMATION, "-> Printing Petri net information ...\n");
TheNet->printInformation();
if (output_filename != "")
{
closeOutput(output);
output = NULL;
}
}
}
}
catch (Exception& e)
{
// output info file ?
if ( formats[F_INFO] )
{
output = log_output;
// just print to std::out
TheNet->printInformation();
output = NULL;
}
error(e);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "shaderc.h"
#if SHADERC_CONFIG_DIRECT3D9
#include <sal.h>
#define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
BX_PRAGMA_DIAGNOSTIC_PUSH();
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wundef");
#include <d3dx9.h>
BX_PRAGMA_DIAGNOSTIC_POP();
struct UniformRemapDx9
{
UniformType::Enum id;
D3DXPARAMETER_CLASS paramClass;
D3DXPARAMETER_TYPE paramType;
uint8_t columns;
uint8_t rows;
};
static const UniformRemapDx9 s_constRemapDx9[7] =
{
{ UniformType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 0, 0 },
{ UniformType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 3, 3 },
{ UniformType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 4, 4 },
};
UniformType::Enum findUniformTypeDx9(const D3DXCONSTANT_DESC& constDesc)
{
for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx9); ++ii)
{
const UniformRemapDx9& remap = s_constRemapDx9[ii];
if (remap.paramClass == constDesc.Class
&& remap.paramType == constDesc.Type)
{
if (D3DXPC_MATRIX_COLUMNS != constDesc.Class)
{
return remap.id;
}
if (remap.columns == constDesc.Columns
&& remap.rows == constDesc.Rows)
{
return remap.id;
}
}
}
return UniformType::Count;
}
static uint32_t s_optimizationLevelDx9[4] =
{
D3DXSHADER_OPTIMIZATION_LEVEL0,
D3DXSHADER_OPTIMIZATION_LEVEL1,
D3DXSHADER_OPTIMIZATION_LEVEL2,
D3DXSHADER_OPTIMIZATION_LEVEL3,
};
bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
{
BX_TRACE("DX9");
const char* profile = _cmdLine.findOption('p', "profile");
if (NULL == profile)
{
fprintf(stderr, "Shader profile must be specified.\n");
return false;
}
bool debug = _cmdLine.hasArg('\0', "debug");
uint32_t flags = 0;
flags |= debug ? D3DXSHADER_DEBUG : 0;
flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
bool werror = _cmdLine.hasArg('\0', "Werror");
uint32_t optimization = 3;
if (_cmdLine.hasArg(optimization, 'O') )
{
optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
flags |= s_optimizationLevelDx9[optimization];
}
else
{
flags |= D3DXSHADER_SKIPOPTIMIZATION;
}
BX_TRACE("Profile: %s", profile);
BX_TRACE("Flags: 0x%08x", flags);
LPD3DXBUFFER code;
LPD3DXBUFFER errorMsg;
LPD3DXCONSTANTTABLE constantTable;
HRESULT hr;
// Output preprocessed shader so that HLSL can be debugged via GPA
// or PIX. Compiling through memory won't embed preprocessed shader
// file path.
if (debug)
{
std::string hlslfp = _cmdLine.findOption('o');
hlslfp += ".hlsl";
writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
, NULL
, NULL
, "main"
, profile
, flags
, &code
, &errorMsg
, &constantTable
);
}
else
{
hr = D3DXCompileShader(_code.c_str()
, (uint32_t)_code.size()
, NULL
, NULL
, "main"
, profile
, flags
, &code
, &errorMsg
, &constantTable
);
}
if (FAILED(hr)
|| (werror && NULL != errorMsg) )
{
const char* log = (const char*)errorMsg->GetBufferPointer();
char source[1024];
int32_t line = 0;
int32_t column = 0;
int32_t start = 0;
int32_t end = INT32_MAX;
if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
&& 0 != line)
{
start = bx::uint32_imax(1, line-10);
end = start + 20;
}
printCode(_code.c_str(), line, start, end);
fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
errorMsg->Release();
return false;
}
UniformArray uniforms;
if (NULL != constantTable)
{
D3DXCONSTANTTABLE_DESC desc;
hr = constantTable->GetDesc(&desc);
if (FAILED(hr) )
{
fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
return false;
}
BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
BX_TRACE("Num constants: %d", desc.Constants);
BX_TRACE("# cl ty RxC S By Name");
for (uint32_t ii = 0; ii < desc.Constants; ++ii)
{
D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
D3DXCONSTANT_DESC constDesc;
uint32_t count;
constantTable->GetConstantDesc(handle, &constDesc, &count);
BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
, ii
, constDesc.Class
, constDesc.Type
, constDesc.Rows
, constDesc.Columns
, constDesc.StructMembers
, constDesc.Bytes
, constDesc.Name
, constDesc.Elements
, constDesc.RegisterIndex
, constDesc.RegisterCount
);
UniformType::Enum type = findUniformTypeDx9(constDesc);
if (UniformType::Count != type)
{
Uniform un;
un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
un.type = type;
un.num = constDesc.Elements;
un.regIndex = constDesc.RegisterIndex;
un.regCount = constDesc.RegisterCount;
uniforms.push_back(un);
}
}
}
uint16_t count = (uint16_t)uniforms.size();
bx::write(_writer, count);
uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
{
const Uniform& un = *it;
uint8_t nameSize = (uint8_t)un.name.size();
bx::write(_writer, nameSize);
bx::write(_writer, un.name.c_str(), nameSize);
uint8_t type = un.type|fragmentBit;
bx::write(_writer, type);
bx::write(_writer, un.num);
bx::write(_writer, un.regIndex);
bx::write(_writer, un.regCount);
BX_TRACE("%s, %s, %d, %d, %d"
, un.name.c_str()
, getUniformTypeName(un.type)
, un.num
, un.regIndex
, un.regCount
);
}
uint16_t shaderSize = (uint16_t)code->GetBufferSize();
bx::write(_writer, shaderSize);
bx::write(_writer, code->GetBufferPointer(), shaderSize);
uint8_t nul = 0;
bx::write(_writer, nul);
if (_cmdLine.hasArg('\0', "disasm") )
{
LPD3DXBUFFER disasm;
D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
, false
, NULL
, &disasm
);
if (NULL != disasm)
{
std::string disasmfp = _cmdLine.findOption('o');
disasmfp += ".disasm";
writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
disasm->Release();
}
}
if (NULL != code)
{
code->Release();
}
if (NULL != errorMsg)
{
errorMsg->Release();
}
if (NULL != constantTable)
{
constantTable->Release();
}
return true;
}
#else
bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
{
BX_UNUSED(_cmdLine, _code, _writer);
fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
return false;
}
#endif // SHADERC_CONFIG_DIRECT3D9
<commit_msg>D3DXDisassembleShader is not exposed in mingw libraries (nw)<commit_after>/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "shaderc.h"
#if SHADERC_CONFIG_DIRECT3D9
#include <sal.h>
#define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
BX_PRAGMA_DIAGNOSTIC_PUSH();
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wundef");
#include <d3dx9.h>
BX_PRAGMA_DIAGNOSTIC_POP();
struct UniformRemapDx9
{
UniformType::Enum id;
D3DXPARAMETER_CLASS paramClass;
D3DXPARAMETER_TYPE paramType;
uint8_t columns;
uint8_t rows;
};
static const UniformRemapDx9 s_constRemapDx9[7] =
{
{ UniformType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 0, 0 },
{ UniformType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
{ UniformType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 3, 3 },
{ UniformType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 4, 4 },
};
UniformType::Enum findUniformTypeDx9(const D3DXCONSTANT_DESC& constDesc)
{
for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx9); ++ii)
{
const UniformRemapDx9& remap = s_constRemapDx9[ii];
if (remap.paramClass == constDesc.Class
&& remap.paramType == constDesc.Type)
{
if (D3DXPC_MATRIX_COLUMNS != constDesc.Class)
{
return remap.id;
}
if (remap.columns == constDesc.Columns
&& remap.rows == constDesc.Rows)
{
return remap.id;
}
}
}
return UniformType::Count;
}
static uint32_t s_optimizationLevelDx9[4] =
{
D3DXSHADER_OPTIMIZATION_LEVEL0,
D3DXSHADER_OPTIMIZATION_LEVEL1,
D3DXSHADER_OPTIMIZATION_LEVEL2,
D3DXSHADER_OPTIMIZATION_LEVEL3,
};
bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
{
BX_TRACE("DX9");
const char* profile = _cmdLine.findOption('p', "profile");
if (NULL == profile)
{
fprintf(stderr, "Shader profile must be specified.\n");
return false;
}
bool debug = _cmdLine.hasArg('\0', "debug");
uint32_t flags = 0;
flags |= debug ? D3DXSHADER_DEBUG : 0;
flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
bool werror = _cmdLine.hasArg('\0', "Werror");
uint32_t optimization = 3;
if (_cmdLine.hasArg(optimization, 'O') )
{
optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
flags |= s_optimizationLevelDx9[optimization];
}
else
{
flags |= D3DXSHADER_SKIPOPTIMIZATION;
}
BX_TRACE("Profile: %s", profile);
BX_TRACE("Flags: 0x%08x", flags);
LPD3DXBUFFER code;
LPD3DXBUFFER errorMsg;
LPD3DXCONSTANTTABLE constantTable;
HRESULT hr;
// Output preprocessed shader so that HLSL can be debugged via GPA
// or PIX. Compiling through memory won't embed preprocessed shader
// file path.
if (debug)
{
std::string hlslfp = _cmdLine.findOption('o');
hlslfp += ".hlsl";
writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
, NULL
, NULL
, "main"
, profile
, flags
, &code
, &errorMsg
, &constantTable
);
}
else
{
hr = D3DXCompileShader(_code.c_str()
, (uint32_t)_code.size()
, NULL
, NULL
, "main"
, profile
, flags
, &code
, &errorMsg
, &constantTable
);
}
if (FAILED(hr)
|| (werror && NULL != errorMsg) )
{
const char* log = (const char*)errorMsg->GetBufferPointer();
char source[1024];
int32_t line = 0;
int32_t column = 0;
int32_t start = 0;
int32_t end = INT32_MAX;
if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
&& 0 != line)
{
start = bx::uint32_imax(1, line-10);
end = start + 20;
}
printCode(_code.c_str(), line, start, end);
fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
errorMsg->Release();
return false;
}
UniformArray uniforms;
if (NULL != constantTable)
{
D3DXCONSTANTTABLE_DESC desc;
hr = constantTable->GetDesc(&desc);
if (FAILED(hr) )
{
fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
return false;
}
BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
BX_TRACE("Num constants: %d", desc.Constants);
BX_TRACE("# cl ty RxC S By Name");
for (uint32_t ii = 0; ii < desc.Constants; ++ii)
{
D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
D3DXCONSTANT_DESC constDesc;
uint32_t count;
constantTable->GetConstantDesc(handle, &constDesc, &count);
BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
, ii
, constDesc.Class
, constDesc.Type
, constDesc.Rows
, constDesc.Columns
, constDesc.StructMembers
, constDesc.Bytes
, constDesc.Name
, constDesc.Elements
, constDesc.RegisterIndex
, constDesc.RegisterCount
);
UniformType::Enum type = findUniformTypeDx9(constDesc);
if (UniformType::Count != type)
{
Uniform un;
un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
un.type = type;
un.num = constDesc.Elements;
un.regIndex = constDesc.RegisterIndex;
un.regCount = constDesc.RegisterCount;
uniforms.push_back(un);
}
}
}
uint16_t count = (uint16_t)uniforms.size();
bx::write(_writer, count);
uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
{
const Uniform& un = *it;
uint8_t nameSize = (uint8_t)un.name.size();
bx::write(_writer, nameSize);
bx::write(_writer, un.name.c_str(), nameSize);
uint8_t type = un.type|fragmentBit;
bx::write(_writer, type);
bx::write(_writer, un.num);
bx::write(_writer, un.regIndex);
bx::write(_writer, un.regCount);
BX_TRACE("%s, %s, %d, %d, %d"
, un.name.c_str()
, getUniformTypeName(un.type)
, un.num
, un.regIndex
, un.regCount
);
}
uint16_t shaderSize = (uint16_t)code->GetBufferSize();
bx::write(_writer, shaderSize);
bx::write(_writer, code->GetBufferPointer(), shaderSize);
uint8_t nul = 0;
bx::write(_writer, nul);
#if !defined(__MINGW32__)
if (_cmdLine.hasArg('\0', "disasm") )
{
LPD3DXBUFFER disasm;
D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
, false
, NULL
, &disasm
);
if (NULL != disasm)
{
std::string disasmfp = _cmdLine.findOption('o');
disasmfp += ".disasm";
writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
disasm->Release();
}
}
#endif
if (NULL != code)
{
code->Release();
}
if (NULL != errorMsg)
{
errorMsg->Release();
}
if (NULL != constantTable)
{
constantTable->Release();
}
return true;
}
#else
bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
{
BX_UNUSED(_cmdLine, _code, _writer);
fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
return false;
}
#endif // SHADERC_CONFIG_DIRECT3D9
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// QT includes
#include <QChildEvent>
#include <QDebug>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QPushButton>
#include <QTreeView>
// CTK includes
#include "ctkFileDialog.h"
//------------------------------------------------------------------------------
class ctkFileDialogPrivate
{
Q_DECLARE_PUBLIC(ctkFileDialog);
protected:
ctkFileDialog* const q_ptr;
public:
ctkFileDialogPrivate(ctkFileDialog& object);
void init();
void observeAcceptButton();
QPushButton* acceptButton()const;
QListView* listView()const;
QTreeView* treeView()const;
bool AcceptButtonEnable;
bool AcceptButtonState;
bool IgnoreEvent;
bool UsingNativeDialog;
};
//------------------------------------------------------------------------------
ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object)
:q_ptr(&object)
{
this->IgnoreEvent = false;
this->AcceptButtonEnable = true;
this->AcceptButtonState = true;
this->UsingNativeDialog = true;
}
//------------------------------------------------------------------------------
void ctkFileDialogPrivate::init()
{
Q_Q(ctkFileDialog);
this->UsingNativeDialog = !(q->options() & QFileDialog::DontUseNativeDialog);
if (!this->UsingNativeDialog)
{
this->observeAcceptButton();
QObject::connect(this->listView()->selectionModel(),
SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
q, SLOT(onSelectionChanged()));
}
}
//------------------------------------------------------------------------------
QPushButton* ctkFileDialogPrivate::acceptButton()const
{
Q_Q(const ctkFileDialog);
if (this->UsingNativeDialog)
{
return NULL; // Native dialog does not supporting modifying or getting widget elements.
}
QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>();
Q_ASSERT(buttonBox);
QDialogButtonBox::StandardButton button =
(q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
return buttonBox->button(button);
}
//------------------------------------------------------------------------------
QListView* ctkFileDialogPrivate::listView()const
{
Q_Q(const ctkFileDialog);
QListView* listView= q->findChild<QListView*>("listView");
Q_ASSERT(listView);
return listView;
}
//------------------------------------------------------------------------------
QTreeView* ctkFileDialogPrivate::treeView()const
{
Q_Q(const ctkFileDialog);
QTreeView* treeView = q->findChild<QTreeView*>();
Q_ASSERT(treeView);
return treeView;
}
//------------------------------------------------------------------------------
void ctkFileDialogPrivate::observeAcceptButton()
{
Q_Q(ctkFileDialog);
QPushButton* button = this->acceptButton();
Q_ASSERT(button);
this->AcceptButtonState =
button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
// TODO: catching the event of the enable state is not enough, if the user
// double click on the file, the dialog will be accepted, that event should
// be intercepted as well
button->installEventFilter(q);
}
//------------------------------------------------------------------------------
ctkFileDialog::ctkFileDialog(QWidget *parentWidget,
const QString &caption,
const QString &directory,
const QString &filter)
:QFileDialog(parentWidget, caption, directory, filter)
, d_ptr(new ctkFileDialogPrivate(*this))
{
Q_D(ctkFileDialog);
d->init();
}
//------------------------------------------------------------------------------
ctkFileDialog::~ctkFileDialog()
{
}
//------------------------------------------------------------------------------
void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label)
{
Q_D(ctkFileDialog);
if (d->UsingNativeDialog)
{
return; // Native dialog does not supporting modifying or getting widget elements.
}
QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
QWidget* oldBottomWidget = this->bottomWidget();
// remove the old widget from the layout if any
if (oldBottomWidget)
{
if (oldBottomWidget == widget)
{
return;
}
gridLayout->removeWidget(oldBottomWidget);
delete oldBottomWidget;
}
if (widget == 0)
{
return;
}
if (!label.isEmpty())
{
gridLayout->addWidget(new QLabel(label), 4, 0);
gridLayout->addWidget(widget,4, 1,1, 1);
}
else
{
gridLayout->addWidget(widget,4, 0,1, 2);
}
// The dialog button box is no longer spanned on 2 rows but on 3 rows if
// there is a "bottom widget"
QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>();
Q_ASSERT(buttonBox);
gridLayout->removeWidget(buttonBox);
gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1);
}
//------------------------------------------------------------------------------
QWidget* ctkFileDialog::bottomWidget()const
{
QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
QLayoutItem* item = gridLayout ? gridLayout->itemAtPosition(4,1) : NULL;
return item ? item->widget() : 0;
}
//------------------------------------------------------------------------------
void ctkFileDialog::setSelectionMode(QAbstractItemView::SelectionMode mode)
{
Q_D(ctkFileDialog);
if (d->UsingNativeDialog)
{
return; // Native dialog does not support modifying or getting widget elements.
}
foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
<< d->listView()
<< d->treeView()
)
{
view->setSelectionMode(mode);
}
}
//------------------------------------------------------------------------------
QAbstractItemView::SelectionMode ctkFileDialog::selectionMode() const
{
Q_D(const ctkFileDialog);
return d->listView()->selectionMode();
}
//------------------------------------------------------------------------------
void ctkFileDialog::clearSelection()
{
Q_D(ctkFileDialog);
foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
<< d->listView()
<< d->treeView()
)
{
view->clearSelection();
}
}
//------------------------------------------------------------------------------
void ctkFileDialog::setAcceptButtonEnable(bool enable)
{
Q_D(ctkFileDialog);
d->AcceptButtonEnable = enable;
d->IgnoreEvent = true;
d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
d->IgnoreEvent = false;
}
//------------------------------------------------------------------------------
bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event)
{
Q_D(ctkFileDialog);
QPushButton* button = d->acceptButton();
QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj);
if (obj == button && event->type() == QEvent::EnabledChange &&
!d->IgnoreEvent)
{
d->IgnoreEvent = true;
d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
d->IgnoreEvent = false;
}
else if (obj == button && event->type() == QEvent::Destroy)
{
// The accept button is deleted probably because setAcceptMode() is being called.
// observe the parent to check when the accept button is added back
obj->parent()->installEventFilter(this);
}
else if (dialogButtonBox && event->type() == QEvent::ChildAdded)
{
dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this);
}
return QFileDialog::eventFilter(obj, event);
}
//------------------------------------------------------------------------------
void ctkFileDialog::onSelectionChanged()
{
emit this->fileSelectionChanged(this->selectedFiles());
}
//------------------------------------------------------------------------------
void ctkFileDialog::accept()
{
QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender());
if (fileNameEdit)
{
QFileInfo info(fileNameEdit->text());
if (info.isDir())
{
setDirectory(info.absoluteFilePath());
return;
}
}
// Don't accept read-only directories if we are in AcceptSave mode.
if ((this->fileMode() == Directory) &&
this->acceptMode() == AcceptSave)
{
QStringList files = this->selectedFiles();
QString fn = files.first();
QFileInfo info(fn);
if (info.isDir() && !info.isWritable())
{
this->setDirectory(info.absoluteFilePath());
return;
}
}
this->Superclass::accept();
}
<commit_msg>STYLE: Fix grammar in comment<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// QT includes
#include <QChildEvent>
#include <QDebug>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QPushButton>
#include <QTreeView>
// CTK includes
#include "ctkFileDialog.h"
//------------------------------------------------------------------------------
class ctkFileDialogPrivate
{
Q_DECLARE_PUBLIC(ctkFileDialog);
protected:
ctkFileDialog* const q_ptr;
public:
ctkFileDialogPrivate(ctkFileDialog& object);
void init();
void observeAcceptButton();
QPushButton* acceptButton()const;
QListView* listView()const;
QTreeView* treeView()const;
bool AcceptButtonEnable;
bool AcceptButtonState;
bool IgnoreEvent;
bool UsingNativeDialog;
};
//------------------------------------------------------------------------------
ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object)
:q_ptr(&object)
{
this->IgnoreEvent = false;
this->AcceptButtonEnable = true;
this->AcceptButtonState = true;
this->UsingNativeDialog = true;
}
//------------------------------------------------------------------------------
void ctkFileDialogPrivate::init()
{
Q_Q(ctkFileDialog);
this->UsingNativeDialog = !(q->options() & QFileDialog::DontUseNativeDialog);
if (!this->UsingNativeDialog)
{
this->observeAcceptButton();
QObject::connect(this->listView()->selectionModel(),
SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
q, SLOT(onSelectionChanged()));
}
}
//------------------------------------------------------------------------------
QPushButton* ctkFileDialogPrivate::acceptButton()const
{
Q_Q(const ctkFileDialog);
if (this->UsingNativeDialog)
{
return NULL; // Native dialog does not support modifying or getting widget elements.
}
QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>();
Q_ASSERT(buttonBox);
QDialogButtonBox::StandardButton button =
(q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
return buttonBox->button(button);
}
//------------------------------------------------------------------------------
QListView* ctkFileDialogPrivate::listView()const
{
Q_Q(const ctkFileDialog);
QListView* listView= q->findChild<QListView*>("listView");
Q_ASSERT(listView);
return listView;
}
//------------------------------------------------------------------------------
QTreeView* ctkFileDialogPrivate::treeView()const
{
Q_Q(const ctkFileDialog);
QTreeView* treeView = q->findChild<QTreeView*>();
Q_ASSERT(treeView);
return treeView;
}
//------------------------------------------------------------------------------
void ctkFileDialogPrivate::observeAcceptButton()
{
Q_Q(ctkFileDialog);
QPushButton* button = this->acceptButton();
Q_ASSERT(button);
this->AcceptButtonState =
button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
// TODO: catching the event of the enable state is not enough, if the user
// double click on the file, the dialog will be accepted, that event should
// be intercepted as well
button->installEventFilter(q);
}
//------------------------------------------------------------------------------
ctkFileDialog::ctkFileDialog(QWidget *parentWidget,
const QString &caption,
const QString &directory,
const QString &filter)
:QFileDialog(parentWidget, caption, directory, filter)
, d_ptr(new ctkFileDialogPrivate(*this))
{
Q_D(ctkFileDialog);
d->init();
}
//------------------------------------------------------------------------------
ctkFileDialog::~ctkFileDialog()
{
}
//------------------------------------------------------------------------------
void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label)
{
Q_D(ctkFileDialog);
if (d->UsingNativeDialog)
{
return; // Native dialog does not support modifying or getting widget elements.
}
QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
QWidget* oldBottomWidget = this->bottomWidget();
// remove the old widget from the layout if any
if (oldBottomWidget)
{
if (oldBottomWidget == widget)
{
return;
}
gridLayout->removeWidget(oldBottomWidget);
delete oldBottomWidget;
}
if (widget == 0)
{
return;
}
if (!label.isEmpty())
{
gridLayout->addWidget(new QLabel(label), 4, 0);
gridLayout->addWidget(widget,4, 1,1, 1);
}
else
{
gridLayout->addWidget(widget,4, 0,1, 2);
}
// The dialog button box is no longer spanned on 2 rows but on 3 rows if
// there is a "bottom widget"
QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>();
Q_ASSERT(buttonBox);
gridLayout->removeWidget(buttonBox);
gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1);
}
//------------------------------------------------------------------------------
QWidget* ctkFileDialog::bottomWidget()const
{
QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
QLayoutItem* item = gridLayout ? gridLayout->itemAtPosition(4,1) : NULL;
return item ? item->widget() : 0;
}
//------------------------------------------------------------------------------
void ctkFileDialog::setSelectionMode(QAbstractItemView::SelectionMode mode)
{
Q_D(ctkFileDialog);
if (d->UsingNativeDialog)
{
return; // Native dialog does not support modifying or getting widget elements.
}
foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
<< d->listView()
<< d->treeView()
)
{
view->setSelectionMode(mode);
}
}
//------------------------------------------------------------------------------
QAbstractItemView::SelectionMode ctkFileDialog::selectionMode() const
{
Q_D(const ctkFileDialog);
return d->listView()->selectionMode();
}
//------------------------------------------------------------------------------
void ctkFileDialog::clearSelection()
{
Q_D(ctkFileDialog);
foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
<< d->listView()
<< d->treeView()
)
{
view->clearSelection();
}
}
//------------------------------------------------------------------------------
void ctkFileDialog::setAcceptButtonEnable(bool enable)
{
Q_D(ctkFileDialog);
d->AcceptButtonEnable = enable;
d->IgnoreEvent = true;
d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
d->IgnoreEvent = false;
}
//------------------------------------------------------------------------------
bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event)
{
Q_D(ctkFileDialog);
QPushButton* button = d->acceptButton();
QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj);
if (obj == button && event->type() == QEvent::EnabledChange &&
!d->IgnoreEvent)
{
d->IgnoreEvent = true;
d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
d->IgnoreEvent = false;
}
else if (obj == button && event->type() == QEvent::Destroy)
{
// The accept button is deleted probably because setAcceptMode() is being called.
// observe the parent to check when the accept button is added back
obj->parent()->installEventFilter(this);
}
else if (dialogButtonBox && event->type() == QEvent::ChildAdded)
{
dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this);
}
return QFileDialog::eventFilter(obj, event);
}
//------------------------------------------------------------------------------
void ctkFileDialog::onSelectionChanged()
{
emit this->fileSelectionChanged(this->selectedFiles());
}
//------------------------------------------------------------------------------
void ctkFileDialog::accept()
{
QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender());
if (fileNameEdit)
{
QFileInfo info(fileNameEdit->text());
if (info.isDir())
{
setDirectory(info.absoluteFilePath());
return;
}
}
// Don't accept read-only directories if we are in AcceptSave mode.
if ((this->fileMode() == Directory) &&
this->acceptMode() == AcceptSave)
{
QStringList files = this->selectedFiles();
QString fn = files.first();
QFileInfo info(fn);
if (info.isDir() && !info.isWritable())
{
this->setDirectory(info.absoluteFilePath());
return;
}
}
this->Superclass::accept();
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include "AliMUONChamberTrigger.h"
#include "AliMUONResponseTrigger.h"
#include "AliMUONHit.h"
#include "AliMUONGeometrySegmentation.h"
#include "AliLog.h"
ClassImp(AliMUONChamberTrigger)
//-------------------------------------------
AliMUONChamberTrigger::AliMUONChamberTrigger()
: AliMUONChamber()
{
// Default constructor
}
AliMUONChamberTrigger::AliMUONChamberTrigger(Int_t id)
: AliMUONChamber(id)
{
// Constructor using chamber id
}
//-------------------------------------------
void AliMUONChamberTrigger::DisIntegration(AliMUONHit* hit,
Int_t& nnew,
Float_t newclust[6][500])
{
//
// Generates pad hits (simulated cluster)
// using the segmentation and the response model
Float_t tof = hit->Age();
Float_t xhit = hit->X();
Float_t yhit = hit->Y();
Float_t zhit = hit->Z();
Int_t id = hit->DetElemId();
Int_t twentyNano;
if (tof<75*TMath::Power(10,-9)) {
twentyNano=1;
} else {
twentyNano=100;
}
Float_t qp;
nnew=0;
for (Int_t i = 1; i <= 2; i++) {
AliMUONGeometrySegmentation * segmentation=
(AliMUONGeometrySegmentation*) (*fSegmentation2)[i-1];
// Find the module & strip Id. which has fired
Int_t ix,iy;
segmentation->GetPadI(id,xhit,yhit,0,ix,iy);
// treatment of GEANT hits w/o corresponding strip (due to the fact that
// geometry & segmentation are computed in a very slightly different way)
if (ix==100||iy==100) {
AliInfo(Form("AliMUONChamberTrigger hit w/o strip %i %f %f \n",id,xhit,yhit));
} else {
segmentation->SetPad(id,ix,iy);
if (xhit<0) ix = -ix;
// printf(" fId id fnsec xhit yhit zhit ix iy %i %i %i %f %f %f %i %i \n",fId,i,id,xhit,yhit,zhit,ix,iy);
// if (ix < 0 || ix > 10000) return;
// if (iy < 0 || iy > 10000) return;
// --- store signal information for this strip
newclust[0][nnew]=1.; // total charge
newclust[1][nnew]=ix; // ix-position of pad
newclust[2][nnew]=iy; // iy-position of pad
newclust[3][nnew]=twentyNano; // time of flight
newclust[4][nnew]=segmentation->ISector(); // sector id
newclust[5][nnew]=(Float_t) i; // counter
nnew++;
// cluster-size if AliMUONResponseTriggerV1, nothing if AliMUONResponseTrigger
if (((AliMUONResponseTrigger*) fResponse)->SetGenerCluster()) {
// set hits
segmentation->SetHit(id,xhit,yhit,zhit);
// get the list of nearest neighbours
Int_t nList, xList[10], yList[10];
segmentation->Neighbours(id,ix,iy,&nList,xList,yList);
qp = 0;
for (Int_t j=0; j<nList; j++){ // loop over neighbours
if (xList[j]!=0) { // existing neighbour
if (j==0||j==5||qp!=0) { // built-up cluster-size
// neighbour real coordinates (just for checks here)
Float_t x,y,z;
segmentation->GetPadC(id,xList[j],yList[j],x,y,z);
// set pad (fx fy & fix fiy are the current pad coord. & Id.)
segmentation->SetPad(id,xList[j],yList[j]);
// get the chamber (i.e. current strip) response
qp=fResponse->IntXY(id,segmentation);
if (qp > 0.5) {
// --- store signal information for neighbours
newclust[0][nnew]=qp; // total charge
newclust[1][nnew]=segmentation->Ix(); // ix-pos. of pad
newclust[2][nnew]=segmentation->Iy(); // iy-pos. of pad
newclust[3][nnew]=twentyNano; // time of flight
newclust[4][nnew]=segmentation->ISector(); // sector id
newclust[5][nnew]=(Float_t) i; // counter
nnew++;
} // qp > 0.5
} // built-up cluster-size
} // existing neighbour
} // loop over neighbours
} // endif hit w/o strip
} // loop over planes
} // if AliMUONResponseTriggerV1
}
<commit_msg>Changed the convention for invalid ix,iy (from 100,100 to <0,<0) and be a little more verbose in case of error. (Laurent)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include "AliMUONChamberTrigger.h"
#include "AliMUONResponseTrigger.h"
#include "AliMUONHit.h"
#include "AliMUONGeometrySegmentation.h"
#include "AliMUONGeometryModule.h"
#include "AliLog.h"
ClassImp(AliMUONChamberTrigger)
//-------------------------------------------
AliMUONChamberTrigger::AliMUONChamberTrigger()
: AliMUONChamber()
{
// Default constructor
}
AliMUONChamberTrigger::AliMUONChamberTrigger(Int_t id)
: AliMUONChamber(id)
{
// Constructor using chamber id
}
//-------------------------------------------
void AliMUONChamberTrigger::DisIntegration(AliMUONHit* hit,
Int_t& nnew,
Float_t newclust[6][500])
{
//
// Generates pad hits (simulated cluster)
// using the segmentation and the response model
Float_t tof = hit->Age();
Float_t xhit = hit->X();
Float_t yhit = hit->Y();
Float_t zhit = hit->Z();
Int_t id = hit->DetElemId();
Int_t twentyNano;
if (tof<75*TMath::Power(10,-9)) {
twentyNano=1;
} else {
twentyNano=100;
}
Float_t qp;
nnew=0;
for (Int_t i = 1; i <= 2; i++) {
AliMUONGeometrySegmentation * segmentation=
(AliMUONGeometrySegmentation*) (*fSegmentation2)[i-1];
// Find the module & strip Id. which has fired
Int_t ix(-1);
Int_t iy(-1);
segmentation->GetPadI(id,xhit,yhit,0,ix,iy);
// treatment of GEANT hits w/o corresponding strip (due to the fact that
// geometry & segmentation are computed in a very slightly different way)
if ( ix<0 || iy<0 )
{
Float_t lx,ly,lz;
GetGeometry()->Global2Local(id,xhit,yhit,0,lx,ly,lz);
AliWarning(Form("AliMUONChamberTrigger hit w/o strip %i-%d %e %e "
"local %e %e %e ix,iy=%d,%d\n",id,i-1,xhit,yhit,lx,ly,lz,ix,iy));
} else
{
segmentation->SetPad(id,ix,iy);
if (xhit<0) ix = -ix;
// printf(" fId id fnsec xhit yhit zhit ix iy %i %i %i %f %f %f %i %i \n",fId,i,id,xhit,yhit,zhit,ix,iy);
// if (ix < 0 || ix > 10000) return;
// if (iy < 0 || iy > 10000) return;
// --- store signal information for this strip
newclust[0][nnew]=1.; // total charge
newclust[1][nnew]=ix; // ix-position of pad
newclust[2][nnew]=iy; // iy-position of pad
newclust[3][nnew]=twentyNano; // time of flight
newclust[4][nnew]=segmentation->ISector(); // sector id
newclust[5][nnew]=(Float_t) i; // counter
nnew++;
// cluster-size if AliMUONResponseTriggerV1, nothing if AliMUONResponseTrigger
if (((AliMUONResponseTrigger*) fResponse)->SetGenerCluster()) {
// set hits
segmentation->SetHit(id,xhit,yhit,zhit);
// get the list of nearest neighbours
Int_t nList, xList[10], yList[10];
segmentation->Neighbours(id,ix,iy,&nList,xList,yList);
qp = 0;
for (Int_t j=0; j<nList; j++){ // loop over neighbours
if (xList[j]!=0) { // existing neighbour
if (j==0||j==5||qp!=0) { // built-up cluster-size
// neighbour real coordinates (just for checks here)
Float_t x,y,z;
segmentation->GetPadC(id,xList[j],yList[j],x,y,z);
// set pad (fx fy & fix fiy are the current pad coord. & Id.)
segmentation->SetPad(id,xList[j],yList[j]);
// get the chamber (i.e. current strip) response
qp=fResponse->IntXY(id,segmentation);
if (qp > 0.5) {
// --- store signal information for neighbours
newclust[0][nnew]=qp; // total charge
newclust[1][nnew]=segmentation->Ix(); // ix-pos. of pad
newclust[2][nnew]=segmentation->Iy(); // iy-pos. of pad
newclust[3][nnew]=twentyNano; // time of flight
newclust[4][nnew]=segmentation->ISector(); // sector id
newclust[5][nnew]=(Float_t) i; // counter
nnew++;
} // qp > 0.5
} // built-up cluster-size
} // existing neighbour
} // loop over neighbours
} // endif hit w/o strip
} // loop over planes
} // if AliMUONResponseTriggerV1
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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 partition.inl
* \brief Inline file for partition.h.
*/
#include <thrust/partition.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/dispatch/partition.h>
namespace thrust
{
namespace experimental
{
template<typename ForwardIterator,
typename OutputIterator,
typename Predicate>
OutputIterator stable_partition_copy(ForwardIterator begin,
ForwardIterator end,
OutputIterator result,
Predicate pred)
{
return detail::dispatch::stable_partition_copy(begin, end, result, pred,
typename thrust::iterator_traits<ForwardIterator>::iterator_category(),
typename thrust::iterator_traits<OutputIterator>::iterator_category());
} // end stable_partition_copy()
template<typename ForwardIterator,
typename OutputIterator,
typename Predicate>
OutputIterator partition_copy(ForwardIterator begin,
ForwardIterator end,
OutputIterator result,
Predicate pred)
{
return thrust::experimental::stable_partition_copy(begin,end,result,pred);
} // end partition_copy()
} // end namespace experimental
template<typename ForwardIterator,
typename Predicate>
ForwardIterator stable_partition(ForwardIterator begin,
ForwardIterator end,
Predicate pred)
{
return detail::dispatch::stable_partition(begin, end, pred,
typename thrust::iterator_traits<ForwardIterator>::iterator_category());
} // end stable_partition_copy()
template<typename ForwardIterator,
typename Predicate>
ForwardIterator partition(ForwardIterator begin,
ForwardIterator end,
Predicate pred)
{
return thrust::stable_partition(begin,end,pred);
} // end partition()
} // end thrust
<commit_msg>Help nvcc find the right namespace<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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 partition.inl
* \brief Inline file for partition.h.
*/
#include <thrust/partition.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/dispatch/partition.h>
namespace thrust
{
namespace experimental
{
template<typename ForwardIterator,
typename OutputIterator,
typename Predicate>
OutputIterator stable_partition_copy(ForwardIterator begin,
ForwardIterator end,
OutputIterator result,
Predicate pred)
{
return thrust::detail::dispatch::stable_partition_copy(begin, end, result, pred,
typename thrust::iterator_traits<ForwardIterator>::iterator_category(),
typename thrust::iterator_traits<OutputIterator>::iterator_category());
} // end stable_partition_copy()
template<typename ForwardIterator,
typename OutputIterator,
typename Predicate>
OutputIterator partition_copy(ForwardIterator begin,
ForwardIterator end,
OutputIterator result,
Predicate pred)
{
return thrust::experimental::stable_partition_copy(begin,end,result,pred);
} // end partition_copy()
} // end namespace experimental
template<typename ForwardIterator,
typename Predicate>
ForwardIterator stable_partition(ForwardIterator begin,
ForwardIterator end,
Predicate pred)
{
return detail::dispatch::stable_partition(begin, end, pred,
typename thrust::iterator_traits<ForwardIterator>::iterator_category());
} // end stable_partition_copy()
template<typename ForwardIterator,
typename Predicate>
ForwardIterator partition(ForwardIterator begin,
ForwardIterator end,
Predicate pred)
{
return thrust::stable_partition(begin,end,pred);
} // end partition()
} // end thrust
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "LoadDataReaction.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "EmdFormat.h"
#include "ModuleManager.h"
#include "RecentFilesMenu.h"
#include "Utilities.h"
#include "pqActiveObjects.h"
#include "pqLoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqProxyWidgetDialog.h"
#include "pqRenderView.h"
#include "pqSMAdaptor.h"
#include "pqView.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkNew.h"
#include "vtkPointData.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMStringVectorProperty.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include "vtkTrivialProducer.h"
#include <QDebug>
#include <QFileDialog>
#include <QFileInfo>
namespace tomviz {
LoadDataReaction::LoadDataReaction(QAction* parentObject)
: Superclass(parentObject)
{
}
LoadDataReaction::~LoadDataReaction()
{
}
void LoadDataReaction::onTriggered()
{
loadData();
}
QList<DataSource*> LoadDataReaction::loadData()
{
vtkNew<vtkSMParaViewPipelineController> controller;
QStringList filters;
filters
<< "Common file types (*.emd *.jpg *.jpeg *.png *.tiff *.tif *.raw"
" *.dat *.bin *.txt *.mhd *.mha *.vti *.mrc *.st *.rec *.ali *.xmf *.xdmf)"
<< "EMD (*.emd)"
<< "JPeg Image files (*.jpg *.jpeg)"
<< "PNG Image files (*.png)"
<< "TIFF Image files (*.tiff *.tif)"
<< "OME-TIFF Image files (*.ome.tif)"
<< "Raw data files (*.raw *.dat *.bin)"
<< "Meta Image files (*.mhd *.mha)"
<< "VTK ImageData Files (*.vti)"
<< "MRC files (*.mrc *.st *.rec *.ali)"
<< "XDMF files (*.xmf *.xdmf)"
<< "Text files (*.txt)"
<< "All files (*.*)";
QFileDialog dialog(nullptr);
dialog.setFileMode(QFileDialog::ExistingFiles);
dialog.setNameFilters(filters);
dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision?
QList<DataSource*> dataSources;
if (dialog.exec()) {
QStringList filenames = dialog.selectedFiles();
dataSources << loadData(filenames);
}
return dataSources;
}
DataSource* LoadDataReaction::loadData(const QString& fileName,
bool defaultModules, bool addToRecent,
bool child)
{
QStringList fileNames;
fileNames << fileName;
return loadData(fileNames, defaultModules, addToRecent, child);
}
DataSource* LoadDataReaction::loadData(const QStringList& fileNames,
bool defaultModules, bool addToRecent,
bool child)
{
DataSource* dataSource(nullptr);
QString fileName;
if (fileNames.size() > 0) {
fileName = fileNames[0];
}
QFileInfo info(fileName);
if (info.suffix().toLower() == "emd") {
// Load the file using our simple EMD class.
dataSource = createDataSourceLocal(fileName, defaultModules, child);
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, nullptr);
}
} else if (info.completeSuffix().endsWith("ome.tif")) {
auto pxm = tomviz::ActiveObjects::instance().proxyManager();
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "OMETIFFReader"));
QString pname = vtkSMCoreUtilities::GetFileNameProperty(source);
vtkSMStringVectorProperty* prop = vtkSMStringVectorProperty::SafeDownCast(
source->GetProperty(pname.toUtf8().data()));
pqSMAdaptor::setElementProperty(prop, fileName);
source->UpdateVTKObjects();
dataSource = createDataSource(source, defaultModules, child);
// The dataSource may be NULL if the user cancelled the action.
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, source);
}
} else {
// Use ParaView's file load infrastructure.
pqPipelineSource* reader = pqLoadDataReaction::loadData(fileNames);
if (!reader) {
return nullptr;
}
dataSource = createDataSource(reader->getProxy(), defaultModules, child);
// The dataSource may be NULL if the user cancelled the action.
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, reader->getProxy());
}
vtkNew<vtkSMParaViewPipelineController> controller;
controller->UnRegisterProxy(reader->getProxy());
}
return dataSource;
}
DataSource* LoadDataReaction::createDataSourceLocal(const QString& fileName,
bool defaultModules,
bool child)
{
QFileInfo info(fileName);
if (info.suffix().toLower() == "emd") {
// Load the file using our simple EMD class.
EmdFormat emdFile;
vtkNew<vtkImageData> imageData;
if (emdFile.read(fileName.toLatin1().data(), imageData.Get())) {
DataSource* dataSource = createDataSource(imageData.Get());
dataSource->originalDataSource()->SetAnnotation(
Attributes::FILENAME, fileName.toLatin1().data());
LoadDataReaction::dataSourceAdded(dataSource, defaultModules, child);
return dataSource;
}
}
return nullptr;
}
namespace {
bool hasData(vtkSMProxy* reader)
{
vtkSMSourceProxy* dataSource = vtkSMSourceProxy::SafeDownCast(reader);
if (!dataSource) {
return false;
}
dataSource->UpdatePipeline();
vtkAlgorithm* vtkalgorithm =
vtkAlgorithm::SafeDownCast(dataSource->GetClientSideObject());
if (!vtkalgorithm) {
return false;
}
// Create a clone and release the reader data.
vtkImageData* data =
vtkImageData::SafeDownCast(vtkalgorithm->GetOutputDataObject(0));
if (!data) {
return false;
}
int extent[6];
data->GetExtent(extent);
if (extent[0] > extent[1] || extent[2] > extent[3] || extent[4] > extent[5]) {
return false;
}
vtkPointData* pd = data->GetPointData();
if (!pd) {
return false;
}
vtkDataArray* scalars = pd->GetScalars();
if (!scalars || scalars->GetNumberOfTuples() == 0) {
return false;
}
return true;
}
}
DataSource* LoadDataReaction::createDataSource(vtkSMProxy* reader,
bool defaultModules, bool child)
{
// Prompt user for reader configuration, unless it is TIFF.
pqProxyWidgetDialog dialog(reader);
dialog.setObjectName("ConfigureReaderDialog");
dialog.setWindowTitle("Configure Reader Parameters");
if (QString(reader->GetXMLName()) == "TIFFSeriesReader" ||
dialog.hasVisibleWidgets() == false ||
dialog.exec() == QDialog::Accepted) {
DataSource* previousActiveDataSource =
ActiveObjects::instance().activeDataSource();
if (!hasData(reader)) {
qCritical() << "Error: failed to load file!";
return nullptr;
}
DataSource* dataSource =
new DataSource(vtkSMSourceProxy::SafeDownCast(reader));
// do whatever we need to do with a new data source.
LoadDataReaction::dataSourceAdded(dataSource, defaultModules, child);
if (!previousActiveDataSource) {
pqRenderView* renderView =
qobject_cast<pqRenderView*>(pqActiveObjects::instance().activeView());
if (renderView) {
tomviz::createCameraOrbit(dataSource->producer(),
renderView->getRenderViewProxy());
}
}
return dataSource;
}
return nullptr;
}
DataSource* LoadDataReaction::createDataSource(vtkImageData* imageData)
{
auto pxm = tomviz::ActiveObjects::instance().proxyManager();
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
auto tp = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
tp->SetOutput(imageData);
source->SetAnnotation("tomviz.Type", "DataSource");
auto dataSource = new DataSource(vtkSMSourceProxy::SafeDownCast(source));
return dataSource;
}
void LoadDataReaction::dataSourceAdded(DataSource* dataSource,
bool defaultModules, bool child)
{
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
if (child) {
ModuleManager::instance().addChildDataSource(dataSource);
} else {
ModuleManager::instance().addDataSource(dataSource);
}
// Work through pathological cases as necessary, prefer active view.
ActiveObjects::instance().createRenderViewIfNeeded();
auto view = ActiveObjects::instance().activeView();
if (!view || QString(view->GetXMLName()) != "RenderView") {
ActiveObjects::instance().setActiveViewToFirstRenderView();
view = ActiveObjects::instance().activeView();
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
if (defaultModules) {
addDefaultModules(dataSource);
}
}
void LoadDataReaction::addDefaultModules(DataSource* dataSource)
{
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
// Create an outline module for the source in the active view.
ModuleManager::instance().createAndAddModule("Outline", dataSource, view);
if (auto module = ModuleManager::instance().createAndAddModule(
"Orthogonal Slice", dataSource, view)) {
ActiveObjects::instance().setActiveModule(module);
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
auto pqview = tomviz::convert<pqView*>(view);
pqview->resetDisplay();
pqview->render();
}
} // end of namespace tomviz
<commit_msg>Remove assumption that Scalars are set by reader<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "LoadDataReaction.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "EmdFormat.h"
#include "ModuleManager.h"
#include "RecentFilesMenu.h"
#include "Utilities.h"
#include "pqActiveObjects.h"
#include "pqLoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqProxyWidgetDialog.h"
#include "pqRenderView.h"
#include "pqSMAdaptor.h"
#include "pqView.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkNew.h"
#include "vtkPointData.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMStringVectorProperty.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPointer.h"
#include "vtkTrivialProducer.h"
#include <QDebug>
#include <QFileDialog>
#include <QFileInfo>
namespace tomviz {
LoadDataReaction::LoadDataReaction(QAction* parentObject)
: Superclass(parentObject)
{
}
LoadDataReaction::~LoadDataReaction()
{
}
void LoadDataReaction::onTriggered()
{
loadData();
}
QList<DataSource*> LoadDataReaction::loadData()
{
vtkNew<vtkSMParaViewPipelineController> controller;
QStringList filters;
filters
<< "Common file types (*.emd *.jpg *.jpeg *.png *.tiff *.tif *.raw"
" *.dat *.bin *.txt *.mhd *.mha *.vti *.mrc *.st *.rec *.ali *.xmf *.xdmf)"
<< "EMD (*.emd)"
<< "JPeg Image files (*.jpg *.jpeg)"
<< "PNG Image files (*.png)"
<< "TIFF Image files (*.tiff *.tif)"
<< "OME-TIFF Image files (*.ome.tif)"
<< "Raw data files (*.raw *.dat *.bin)"
<< "Meta Image files (*.mhd *.mha)"
<< "VTK ImageData Files (*.vti)"
<< "MRC files (*.mrc *.st *.rec *.ali)"
<< "XDMF files (*.xmf *.xdmf)"
<< "Text files (*.txt)"
<< "All files (*.*)";
QFileDialog dialog(nullptr);
dialog.setFileMode(QFileDialog::ExistingFiles);
dialog.setNameFilters(filters);
dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision?
QList<DataSource*> dataSources;
if (dialog.exec()) {
QStringList filenames = dialog.selectedFiles();
dataSources << loadData(filenames);
}
return dataSources;
}
DataSource* LoadDataReaction::loadData(const QString& fileName,
bool defaultModules, bool addToRecent,
bool child)
{
QStringList fileNames;
fileNames << fileName;
return loadData(fileNames, defaultModules, addToRecent, child);
}
DataSource* LoadDataReaction::loadData(const QStringList& fileNames,
bool defaultModules, bool addToRecent,
bool child)
{
DataSource* dataSource(nullptr);
QString fileName;
if (fileNames.size() > 0) {
fileName = fileNames[0];
}
QFileInfo info(fileName);
if (info.suffix().toLower() == "emd") {
// Load the file using our simple EMD class.
dataSource = createDataSourceLocal(fileName, defaultModules, child);
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, nullptr);
}
} else if (info.completeSuffix().endsWith("ome.tif")) {
auto pxm = tomviz::ActiveObjects::instance().proxyManager();
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "OMETIFFReader"));
QString pname = vtkSMCoreUtilities::GetFileNameProperty(source);
vtkSMStringVectorProperty* prop = vtkSMStringVectorProperty::SafeDownCast(
source->GetProperty(pname.toUtf8().data()));
pqSMAdaptor::setElementProperty(prop, fileName);
source->UpdateVTKObjects();
dataSource = createDataSource(source, defaultModules, child);
// The dataSource may be NULL if the user cancelled the action.
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, source);
}
} else {
// Use ParaView's file load infrastructure.
pqPipelineSource* reader = pqLoadDataReaction::loadData(fileNames);
if (!reader) {
return nullptr;
}
dataSource = createDataSource(reader->getProxy(), defaultModules, child);
// The dataSource may be NULL if the user cancelled the action.
if (addToRecent && dataSource) {
RecentFilesMenu::pushDataReader(dataSource, reader->getProxy());
}
vtkNew<vtkSMParaViewPipelineController> controller;
controller->UnRegisterProxy(reader->getProxy());
}
return dataSource;
}
DataSource* LoadDataReaction::createDataSourceLocal(const QString& fileName,
bool defaultModules,
bool child)
{
QFileInfo info(fileName);
if (info.suffix().toLower() == "emd") {
// Load the file using our simple EMD class.
EmdFormat emdFile;
vtkNew<vtkImageData> imageData;
if (emdFile.read(fileName.toLatin1().data(), imageData.Get())) {
DataSource* dataSource = createDataSource(imageData.Get());
dataSource->originalDataSource()->SetAnnotation(
Attributes::FILENAME, fileName.toLatin1().data());
LoadDataReaction::dataSourceAdded(dataSource, defaultModules, child);
return dataSource;
}
}
return nullptr;
}
namespace {
bool hasData(vtkSMProxy* reader)
{
vtkSMSourceProxy* dataSource = vtkSMSourceProxy::SafeDownCast(reader);
if (!dataSource) {
return false;
}
dataSource->UpdatePipeline();
vtkAlgorithm* vtkalgorithm =
vtkAlgorithm::SafeDownCast(dataSource->GetClientSideObject());
if (!vtkalgorithm) {
return false;
}
// Create a clone and release the reader data.
vtkImageData* data =
vtkImageData::SafeDownCast(vtkalgorithm->GetOutputDataObject(0));
if (!data) {
return false;
}
int extent[6];
data->GetExtent(extent);
if (extent[0] > extent[1] || extent[2] > extent[3] || extent[4] > extent[5]) {
return false;
}
vtkPointData* pd = data->GetPointData();
if (!pd) {
return false;
}
if (pd->GetNumberOfArrays() < 1) {
return false;
}
return true;
}
}
DataSource* LoadDataReaction::createDataSource(vtkSMProxy* reader,
bool defaultModules, bool child)
{
// Prompt user for reader configuration, unless it is TIFF.
pqProxyWidgetDialog dialog(reader);
dialog.setObjectName("ConfigureReaderDialog");
dialog.setWindowTitle("Configure Reader Parameters");
if (QString(reader->GetXMLName()) == "TIFFSeriesReader" ||
dialog.hasVisibleWidgets() == false ||
dialog.exec() == QDialog::Accepted) {
DataSource* previousActiveDataSource =
ActiveObjects::instance().activeDataSource();
if (!hasData(reader)) {
qCritical() << "Error: failed to load file!";
return nullptr;
}
DataSource* dataSource =
new DataSource(vtkSMSourceProxy::SafeDownCast(reader));
// do whatever we need to do with a new data source.
LoadDataReaction::dataSourceAdded(dataSource, defaultModules, child);
if (!previousActiveDataSource) {
pqRenderView* renderView =
qobject_cast<pqRenderView*>(pqActiveObjects::instance().activeView());
if (renderView) {
tomviz::createCameraOrbit(dataSource->producer(),
renderView->getRenderViewProxy());
}
}
return dataSource;
}
return nullptr;
}
DataSource* LoadDataReaction::createDataSource(vtkImageData* imageData)
{
auto pxm = tomviz::ActiveObjects::instance().proxyManager();
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
auto tp = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
tp->SetOutput(imageData);
source->SetAnnotation("tomviz.Type", "DataSource");
auto dataSource = new DataSource(vtkSMSourceProxy::SafeDownCast(source));
return dataSource;
}
void LoadDataReaction::dataSourceAdded(DataSource* dataSource,
bool defaultModules, bool child)
{
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
if (child) {
ModuleManager::instance().addChildDataSource(dataSource);
} else {
ModuleManager::instance().addDataSource(dataSource);
}
// Work through pathological cases as necessary, prefer active view.
ActiveObjects::instance().createRenderViewIfNeeded();
auto view = ActiveObjects::instance().activeView();
if (!view || QString(view->GetXMLName()) != "RenderView") {
ActiveObjects::instance().setActiveViewToFirstRenderView();
view = ActiveObjects::instance().activeView();
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
if (defaultModules) {
addDefaultModules(dataSource);
}
}
void LoadDataReaction::addDefaultModules(DataSource* dataSource)
{
bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
ActiveObjects::instance().setMoveObjectsMode(false);
auto view = ActiveObjects::instance().activeView();
// Create an outline module for the source in the active view.
ModuleManager::instance().createAndAddModule("Outline", dataSource, view);
if (auto module = ModuleManager::instance().createAndAddModule(
"Orthogonal Slice", dataSource, view)) {
ActiveObjects::instance().setActiveModule(module);
}
ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
auto pqview = tomviz::convert<pqView*>(view);
pqview->resetDisplay();
pqview->render();
}
} // end of namespace tomviz
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "col_vec.h"
#include "vector.h"
#include "mem_worker_thread.h"
#include "generic_hashtable.h"
namespace fm
{
col_vec::ptr col_vec::create(detail::matrix_store::const_ptr store)
{
if (store->get_num_cols() > 1 && store->get_num_rows() > 1) {
BOOST_LOG_TRIVIAL(error)
<< "can't convert a matrix store with multiple cols&rows to a vector";
assert(0);
return ptr();
}
dense_matrix::ptr mat = dense_matrix::create(store);
if (mat->get_num_cols() > 1)
mat = mat->transpose();
if (mat->get_data().store_layout() == matrix_layout_t::L_ROW)
mat = mat->conv2(matrix_layout_t::L_COL);
return ptr(new col_vec(mat->get_raw_store()));
}
col_vec::ptr col_vec::create(dense_matrix::ptr mat)
{
if (mat->get_num_cols() > 1 && mat->get_num_rows() > 1) {
printf("the input matrix has %ld rows and %ld cols\n",
mat->get_num_rows(), mat->get_num_cols());
BOOST_LOG_TRIVIAL(error)
<< "can't convert a matrix with multiple cols&rows to a vector";
assert(0);
return ptr();
}
if (mat->get_num_cols() > 1)
mat = mat->transpose();
if (mat->get_data().store_layout() == matrix_layout_t::L_ROW)
mat = mat->conv2(matrix_layout_t::L_COL);
return ptr(new col_vec(mat->get_raw_store()));
}
col_vec::ptr col_vec::create(vector::const_ptr vec)
{
dense_matrix::ptr mat = vec->conv2mat(vec->get_length(), 1, false);
assert(mat->store_layout() == matrix_layout_t::L_COL);
if (mat == NULL)
return col_vec::ptr();
else
return col_vec::create(mat);
}
namespace
{
class agg_vec_portion_op: public detail::portion_mapply_op
{
agg_operate::const_ptr find_next;
agg_operate::const_ptr agg_op;
std::vector<generic_hashtable::ptr> tables;
std::vector<local_vec_store::ptr> lvec_bufs;
std::vector<local_vec_store::ptr> lkey_bufs;
std::vector<local_vec_store::ptr> lagg_bufs;
public:
agg_vec_portion_op(agg_operate::const_ptr agg_op): detail::portion_mapply_op(
0, 0, agg_op->get_output_type()) {
this->find_next = agg_op->get_input_type().get_agg_ops().get_find_next();
this->agg_op = agg_op;
size_t nthreads = detail::mem_thread_pool::get_global_num_threads();
tables.resize(nthreads);
lvec_bufs.resize(nthreads);
lkey_bufs.resize(nthreads);
lagg_bufs.resize(nthreads);
}
virtual detail::portion_mapply_op::const_ptr transpose() const {
return detail::portion_mapply_op::const_ptr();
}
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return "";
}
virtual void run(
const std::vector<detail::local_matrix_store::const_ptr> &ins) const;
generic_hashtable::ptr get_agg() const;
};
void agg_vec_portion_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins) const
{
int thread_id = detail::mem_thread_pool::get_curr_thread_id();
agg_vec_portion_op *mutable_this = const_cast<agg_vec_portion_op *>(this);
generic_hashtable::ptr ltable;
local_vec_store::ptr lvec;
local_vec_store::ptr lkeys;
local_vec_store::ptr laggs;
if (tables[thread_id] == NULL) {
mutable_this->tables[thread_id] = ins[0]->get_type().create_hashtable(
agg_op->get_output_type());
mutable_this->lvec_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
ins[0]->get_type(), -1));
mutable_this->lkey_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
ins[0]->get_type(), -1));
mutable_this->lagg_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
agg_op->get_output_type(), -1));
}
ltable = tables[thread_id];
lvec = lvec_bufs[thread_id];
lkeys = lkey_bufs[thread_id];
laggs = lagg_bufs[thread_id];
assert(ltable);
assert(lvec);
assert(lkeys);
assert(laggs);
size_t llength = ins[0]->get_num_rows();
assert(ins[0]->get_raw_arr());
assert(lvec->get_length() >= llength);
memcpy(lvec->get_raw_arr(), ins[0]->get_raw_arr(),
lvec->get_entry_size() * llength);
lvec->get_type().get_sorter().serial_sort(lvec->get_raw_arr(), llength,
false);
// Start to aggregate on the values.
const char *arr = lvec->get_raw_arr();
size_t key_idx = 0;
while (llength > 0) {
size_t num_same = 0;
find_next->runAgg(llength, arr, &num_same);
assert(num_same <= llength);
memcpy(lkeys->get(key_idx), arr, lvec->get_entry_size());
agg_op->runAgg(num_same, arr, laggs->get(key_idx));
key_idx++;
arr += num_same * lvec->get_entry_size();
llength -= num_same;
}
ltable->insert(key_idx, lkeys->get_raw_arr(), laggs->get_raw_arr(), *agg_op);
}
generic_hashtable::ptr agg_vec_portion_op::get_agg() const
{
generic_hashtable::ptr ret;
size_t i;
// Find a local table.
for (i = 0; i < tables.size(); i++) {
if (tables[i]) {
ret = tables[i];
break;
}
}
// We need to move to the next local table.
i++;
// Merge with other local tables if they exist.
for (; i < tables.size(); i++)
if (tables[i])
ret->merge(*tables[i], *agg_op);
return ret;
}
}
data_frame::ptr col_vec::groupby(agg_operate::const_ptr op, bool with_val,
bool sorted) const
{
std::vector<detail::matrix_store::const_ptr> stores(1);
stores[0] = get_raw_store();
agg_vec_portion_op *_portion_op = new agg_vec_portion_op(op);
detail::portion_mapply_op::const_ptr portion_op(_portion_op);
detail::__mapply_portion(stores, portion_op, matrix_layout_t::L_COL);
generic_hashtable::ptr agg_res = _portion_op->get_agg();
// The key-value pairs got from the hashtable aren't in any order.
// We need to sort them before returning them.
data_frame::ptr ret = data_frame::create();
data_frame::ptr df = agg_res->conv2df();
if (sorted) {
vector::ptr keys = vector::create(df->get_vec(0));
data_frame::ptr sorted_keys = keys->sort_with_index();
detail::smp_vec_store::const_ptr idx_store
= std::dynamic_pointer_cast<const detail::smp_vec_store>(
sorted_keys->get_vec("idx"));
detail::smp_vec_store::const_ptr agg_store
= std::dynamic_pointer_cast<const detail::smp_vec_store>(df->get_vec(1));
if (with_val)
ret->add_vec("val", sorted_keys->get_vec("val"));
ret->add_vec("agg", agg_store->get(*idx_store));
}
else {
if (with_val)
ret->add_vec("val", df->get_vec(0));
ret->add_vec("agg", df->get_vec(1));
}
return ret;
}
}
<commit_msg>[Matrix]: remove unnecessary assert.<commit_after>/*
* Copyright 2016 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 "col_vec.h"
#include "vector.h"
#include "mem_worker_thread.h"
#include "generic_hashtable.h"
namespace fm
{
col_vec::ptr col_vec::create(detail::matrix_store::const_ptr store)
{
if (store->get_num_cols() > 1 && store->get_num_rows() > 1) {
BOOST_LOG_TRIVIAL(error)
<< "can't convert a matrix store with multiple cols&rows to a vector";
assert(0);
return ptr();
}
dense_matrix::ptr mat = dense_matrix::create(store);
if (mat->get_num_cols() > 1)
mat = mat->transpose();
if (mat->get_data().store_layout() == matrix_layout_t::L_ROW)
mat = mat->conv2(matrix_layout_t::L_COL);
return ptr(new col_vec(mat->get_raw_store()));
}
col_vec::ptr col_vec::create(dense_matrix::ptr mat)
{
if (mat->get_num_cols() > 1 && mat->get_num_rows() > 1) {
BOOST_LOG_TRIVIAL(error)
<< "can't convert a matrix with multiple cols&rows to a vector";
return ptr();
}
if (mat->get_num_cols() > 1)
mat = mat->transpose();
if (mat->get_data().store_layout() == matrix_layout_t::L_ROW)
mat = mat->conv2(matrix_layout_t::L_COL);
return ptr(new col_vec(mat->get_raw_store()));
}
col_vec::ptr col_vec::create(vector::const_ptr vec)
{
dense_matrix::ptr mat = vec->conv2mat(vec->get_length(), 1, false);
assert(mat->store_layout() == matrix_layout_t::L_COL);
if (mat == NULL)
return col_vec::ptr();
else
return col_vec::create(mat);
}
namespace
{
class agg_vec_portion_op: public detail::portion_mapply_op
{
agg_operate::const_ptr find_next;
agg_operate::const_ptr agg_op;
std::vector<generic_hashtable::ptr> tables;
std::vector<local_vec_store::ptr> lvec_bufs;
std::vector<local_vec_store::ptr> lkey_bufs;
std::vector<local_vec_store::ptr> lagg_bufs;
public:
agg_vec_portion_op(agg_operate::const_ptr agg_op): detail::portion_mapply_op(
0, 0, agg_op->get_output_type()) {
this->find_next = agg_op->get_input_type().get_agg_ops().get_find_next();
this->agg_op = agg_op;
size_t nthreads = detail::mem_thread_pool::get_global_num_threads();
tables.resize(nthreads);
lvec_bufs.resize(nthreads);
lkey_bufs.resize(nthreads);
lagg_bufs.resize(nthreads);
}
virtual detail::portion_mapply_op::const_ptr transpose() const {
return detail::portion_mapply_op::const_ptr();
}
virtual std::string to_string(
const std::vector<detail::matrix_store::const_ptr> &mats) const {
return "";
}
virtual void run(
const std::vector<detail::local_matrix_store::const_ptr> &ins) const;
generic_hashtable::ptr get_agg() const;
};
void agg_vec_portion_op::run(
const std::vector<detail::local_matrix_store::const_ptr> &ins) const
{
int thread_id = detail::mem_thread_pool::get_curr_thread_id();
agg_vec_portion_op *mutable_this = const_cast<agg_vec_portion_op *>(this);
generic_hashtable::ptr ltable;
local_vec_store::ptr lvec;
local_vec_store::ptr lkeys;
local_vec_store::ptr laggs;
if (tables[thread_id] == NULL) {
mutable_this->tables[thread_id] = ins[0]->get_type().create_hashtable(
agg_op->get_output_type());
mutable_this->lvec_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
ins[0]->get_type(), -1));
mutable_this->lkey_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
ins[0]->get_type(), -1));
mutable_this->lagg_bufs[thread_id] = local_vec_store::ptr(
new local_buf_vec_store(0, ins[0]->get_num_rows(),
agg_op->get_output_type(), -1));
}
ltable = tables[thread_id];
lvec = lvec_bufs[thread_id];
lkeys = lkey_bufs[thread_id];
laggs = lagg_bufs[thread_id];
assert(ltable);
assert(lvec);
assert(lkeys);
assert(laggs);
size_t llength = ins[0]->get_num_rows();
assert(ins[0]->get_raw_arr());
assert(lvec->get_length() >= llength);
memcpy(lvec->get_raw_arr(), ins[0]->get_raw_arr(),
lvec->get_entry_size() * llength);
lvec->get_type().get_sorter().serial_sort(lvec->get_raw_arr(), llength,
false);
// Start to aggregate on the values.
const char *arr = lvec->get_raw_arr();
size_t key_idx = 0;
while (llength > 0) {
size_t num_same = 0;
find_next->runAgg(llength, arr, &num_same);
assert(num_same <= llength);
memcpy(lkeys->get(key_idx), arr, lvec->get_entry_size());
agg_op->runAgg(num_same, arr, laggs->get(key_idx));
key_idx++;
arr += num_same * lvec->get_entry_size();
llength -= num_same;
}
ltable->insert(key_idx, lkeys->get_raw_arr(), laggs->get_raw_arr(), *agg_op);
}
generic_hashtable::ptr agg_vec_portion_op::get_agg() const
{
generic_hashtable::ptr ret;
size_t i;
// Find a local table.
for (i = 0; i < tables.size(); i++) {
if (tables[i]) {
ret = tables[i];
break;
}
}
// We need to move to the next local table.
i++;
// Merge with other local tables if they exist.
for (; i < tables.size(); i++)
if (tables[i])
ret->merge(*tables[i], *agg_op);
return ret;
}
}
data_frame::ptr col_vec::groupby(agg_operate::const_ptr op, bool with_val,
bool sorted) const
{
std::vector<detail::matrix_store::const_ptr> stores(1);
stores[0] = get_raw_store();
agg_vec_portion_op *_portion_op = new agg_vec_portion_op(op);
detail::portion_mapply_op::const_ptr portion_op(_portion_op);
detail::__mapply_portion(stores, portion_op, matrix_layout_t::L_COL);
generic_hashtable::ptr agg_res = _portion_op->get_agg();
// The key-value pairs got from the hashtable aren't in any order.
// We need to sort them before returning them.
data_frame::ptr ret = data_frame::create();
data_frame::ptr df = agg_res->conv2df();
if (sorted) {
vector::ptr keys = vector::create(df->get_vec(0));
data_frame::ptr sorted_keys = keys->sort_with_index();
detail::smp_vec_store::const_ptr idx_store
= std::dynamic_pointer_cast<const detail::smp_vec_store>(
sorted_keys->get_vec("idx"));
detail::smp_vec_store::const_ptr agg_store
= std::dynamic_pointer_cast<const detail::smp_vec_store>(df->get_vec(1));
if (with_val)
ret->add_vec("val", sorted_keys->get_vec("val"));
ret->add_vec("agg", agg_store->get(*idx_store));
}
else {
if (with_val)
ret->add_vec("val", df->get_vec(0));
ret->add_vec("agg", df->get_vec(1));
}
return ret;
}
}
<|endoftext|> |
<commit_before>// Simulation of different particles sources penetrating thin silicon detectors.
// University of Bonn, Silab 2014, David-Leon Pohl
// based on the GEANT4 framework
#include "DetectorConstruction.hh"
#include "PixelROWorld.hh"
#include "ActionInitialization.hh"
#include "G4ParallelWorldPhysics.hh"
#ifdef G4MULTITHREADED
#include "G4MTRunManager.hh"
#else
#include "G4RunManager.hh"
#endif
#include "G4UImanager.hh"
#include "G4UIcommand.hh"
#include "FTFP_BERT.hh"
#include "LBE.hh"
#include "QGSP_BERT.hh"
#include "PhysicsList.hh"
#include "RadioactiveDecayPhysics.hh"
#include "Randomize.hh"
#include "G4ParallelWorldScoringProcess.hh"
#ifdef G4VIS_USE
#include "G4VisExecutive.hh"
#endif
#ifdef G4UI_USE
#include "G4UIExecutive.hh"
#endif
namespace {
void PrintUsage() {
G4cerr<<" Usage: "<<G4endl;
G4cerr<<" example [-m macro ] [-u UIsession] [-t nThreads]"<<G4endl;
G4cerr<<" note: -t option is available only for multi-threaded mode."<<G4endl;
}
}
int main(int argc,char** argv)
{
// Evaluate arguments
if ( argc > 7 ) {
PrintUsage();
return 1;
}
G4String macro;
G4String session;
#ifdef G4MULTITHREADED
G4int nThreads = 0;
#endif
for ( G4int i=1; i<argc; i=i+2 ) {
if ( G4String(argv[i]) == "-m" ) macro = argv[i+1];
else if ( G4String(argv[i]) == "-u" ) session = argv[i+1];
#ifdef G4MULTITHREADED
else if ( G4String(argv[i]) == "-t" ) {
nThreads = G4UIcommand::ConvertToInt(argv[i+1]);
}
#endif
else {
PrintUsage();
return 1;
}
}
// Choose the Random engine
G4Random::setTheEngine(new CLHEP::RanecuEngine);
// Construct the MT run manager
#ifdef G4MULTITHREADED
G4MTRunManager * runManager = new G4MTRunManager;
if ( nThreads > 0 ) {
runManager->SetNumberOfThreads(nThreads);
}
#else
G4RunManager * runManager = new G4RunManager;
#endif
// Get the pointer to the User Interface manager
G4UImanager* UImanager = G4UImanager::GetUIpointer();
// Set initialization classes
// Set material and parallel readout world
G4String parallelWorldName = "PixelReadoutWorld";
G4VUserDetectorConstruction* detector = new DetectorConstruction();
detector->RegisterParallelWorld(new PixelROWorld(parallelWorldName));
runManager->SetUserInitialization(detector);
// Set physics list for both worlds
PhysicsList* physicsList = new PhysicsList();
physicsList->RegisterPhysics(new G4ParallelWorldPhysics(parallelWorldName)); // parallel world physic has to be called FIRDT
physicsList->InitStdPhysics(); // material world physics set here (AFTER parallel world physics, otherwise wrong results... BAD framework implementation ...)
runManager->SetUserInitialization(physicsList);
// Set user actions (run action, event action, ...)
runManager->SetUserInitialization(new ActionInitialization());
G4VisManager* visManager = new G4VisExecutive;
visManager->Initialize();
if ( macro.size() ) { // macro mode, just execute macro without visuals and init script
G4String command = "/control/execute ";
UImanager->ApplyCommand(command+macro);
}
else { // std. mode initialize viewer
G4UIExecutive* ui = new G4UIExecutive(argc, argv, session);
UImanager->ApplyCommand("/control/execute init.mac"); // run init script
// BUG: the following can only be called from interface, was working in older GEANT versions...
// UImanager->ApplyCommand("/control/execute vis.mac"); // run vis script
// if (ui->IsGUI())
// UImanager->ApplyCommand("/control/execute gui.mac"); // run gui setup script
ui->SessionStart();
delete ui;
}
delete visManager;
delete runManager; // user actions, physics_list and detector_description are owned and deleted by the run manager
return 0;
}
<commit_msg>MAINT: tell RO world the detector<commit_after>// Simulation of different particles sources penetrating thin silicon detectors.
// University of Bonn, Silab 2014, David-Leon Pohl
// based on the GEANT4 framework
#include "DetectorConstruction.hh"
#include "PixelROWorld.hh"
#include "ActionInitialization.hh"
#include "G4ParallelWorldPhysics.hh"
#ifdef G4MULTITHREADED
#include "G4MTRunManager.hh"
#else
#include "G4RunManager.hh"
#endif
#include "G4UImanager.hh"
#include "G4UIcommand.hh"
#include "FTFP_BERT.hh"
#include "LBE.hh"
#include "QGSP_BERT.hh"
#include "PhysicsList.hh"
#include "RadioactiveDecayPhysics.hh"
#include "Randomize.hh"
#include "G4ParallelWorldScoringProcess.hh"
#ifdef G4VIS_USE
#include "G4VisExecutive.hh"
#endif
#ifdef G4UI_USE
#include "G4UIExecutive.hh"
#endif
namespace {
void PrintUsage() {
G4cerr<<" Usage: "<<G4endl;
G4cerr<<" example [-m macro ] [-u UIsession] [-t nThreads]"<<G4endl;
G4cerr<<" note: -t option is available only for multi-threaded mode."<<G4endl;
}
}
int main(int argc,char** argv)
{
// Evaluate arguments
if ( argc > 7 ) {
PrintUsage();
return 1;
}
G4String macro;
G4String session;
#ifdef G4MULTITHREADED
G4int nThreads = 0;
#endif
for ( G4int i=1; i<argc; i=i+2 ) {
if ( G4String(argv[i]) == "-m" ) macro = argv[i+1];
else if ( G4String(argv[i]) == "-u" ) session = argv[i+1];
#ifdef G4MULTITHREADED
else if ( G4String(argv[i]) == "-t" ) {
nThreads = G4UIcommand::ConvertToInt(argv[i+1]);
}
#endif
else {
PrintUsage();
return 1;
}
}
// Choose the Random engine
G4Random::setTheEngine(new CLHEP::RanecuEngine);
// Construct the MT run manager
#ifdef G4MULTITHREADED
G4MTRunManager * runManager = new G4MTRunManager;
if ( nThreads > 0 ) {
runManager->SetNumberOfThreads(nThreads);
}
#else
G4RunManager * runManager = new G4RunManager;
#endif
// Get the pointer to the User Interface manager
G4UImanager* UImanager = G4UImanager::GetUIpointer();
// Set initialization classes
// Set material and parallel readout world
G4String parallelWorldName = "PixelReadoutWorld";
DetectorConstruction* detector = new DetectorConstruction();
detector->RegisterParallelWorld(new PixelROWorld(parallelWorldName, detector));
runManager->SetUserInitialization(detector);
// Set physics list for both worlds
PhysicsList* physicsList = new PhysicsList();
physicsList->RegisterPhysics(new G4ParallelWorldPhysics(parallelWorldName)); // parallel world physic has to be called FIRDT
physicsList->InitStdPhysics(); // material world physics set here (AFTER parallel world physics, otherwise wrong results... BAD framework implementation ...)
runManager->SetUserInitialization(physicsList);
// Set user actions (run action, event action, ...)
runManager->SetUserInitialization(new ActionInitialization());
G4VisManager* visManager = new G4VisExecutive;
visManager->Initialize();
if ( macro.size() ) { // macro mode, just execute macro without visuals and init script
G4String command = "/control/execute ";
UImanager->ApplyCommand(command+macro);
}
else { // std. mode initialize viewer
G4UIExecutive* ui = new G4UIExecutive(argc, argv, session);
UImanager->ApplyCommand("/control/execute init.mac"); // run init script
// BUG: the following can only be called from interface, was working in older GEANT versions...
// UImanager->ApplyCommand("/control/execute vis.mac"); // run vis script
// if (ui->IsGUI())
// UImanager->ApplyCommand("/control/execute gui.mac"); // run gui setup script
ui->SessionStart();
delete ui;
}
delete visManager;
delete runManager; // user actions, physics_list and detector_description are owned and deleted by the run manager
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* Copyright (c) 2012, 2013 Linas Vepstas <linasvepstas@gmail.com> */
/* All rights reserved */
/* */
/* Use of the Viterbi parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/*************************************************************************/
#include "compile.h"
// XXX temporary hack until dynamic types are supported !?
namespace atombase {
using namespace link_grammar::viterbi;
// ============================================================
/// Remove optional connectors.
///
/// It doesn't make any sense at all to have an optional connector
/// in an AND-clause, so just remove it. (Well, OK, it "makes sense",
/// its just effectively a no-op, and so doesn't have any effect. So,
/// removing it here simplifies logic in other places.)
///
/// The cost of the optional is passed up to the dsjunct. The reason for
/// this is that the doctionary contains entries such as
/// <post-nominal-x>, whcih has (Xc+ or <costly-null>) & MX-
/// After being disjoined, we need to pass that cost up.
Atom* And::clean() const
{
TV tv = _tv;
OutList cl;
size_t sz = get_arity();
// Special case: it could be a and-clause containing a single,
// optional connector, in which case, we flatten the thing
// (returning the optional connector!)
if (1 == sz)
{
Atom* a = get_outgoing_atom(0);
a->_tv += _tv;
return a;
}
for (size_t i=0; i<sz; i++)
{
Connector* cn = dynamic_cast<Connector*>(get_outgoing_atom(i));
if (cn and cn->is_optional())
{
tv += cn->_tv;
continue;
}
cl.push_back(_oset[i]);
}
return new And(cl, tv);
}
// ============================================================
Atom* Atom::upcaster()
{
const Node* n = dynamic_cast<const Node*>(this);
const Link* l = dynamic_cast<const Link*>(this);
switch (get_type())
{
// Links
case AND:
if (dynamic_cast<And*>(this)) return this;
return new And(l->get_outgoing_set(), _tv);
case OR:
if (dynamic_cast<Or*>(this)) return this;
return new Or(l->get_outgoing_set(), _tv);
case SEQ:
if (dynamic_cast<Seq*>(this)) return this;
return new Seq(l->get_outgoing_set(), _tv);
case SET:
if (dynamic_cast<Set*>(this)) return this;
return new Set(l->get_outgoing_set(), _tv);
// Nodes
case CONNECTOR:
if (dynamic_cast<Connector*>(this)) return this;
return new Connector(n->get_name(), _tv);
case WORD:
if (dynamic_cast<Word*>(this)) return this;
return new Word(n->get_name(), _tv);
default:
assert(0, "Atom::upcaster(): implement me!");
}
}
// ============================================================
Link* Link::append(Atom* a) const
{
OutList ol = get_outgoing_set();
ol.push_back(a);
switch (get_type())
{
// Links
case AND:
return new And(ol, _tv);
case OR:
return new Or(ol, _tv);
case SEQ:
return new Seq(ol, _tv);
case SET:
return new Set(ol, _tv);
default:
assert(0, "append: implement me!");
}
}
} // namespace atombase
// ============================================================
namespace link_grammar {
namespace viterbi {
// Helper function for below.
static bool has_lefties(Atom* a)
{
Connector* c = dynamic_cast<Connector*>(a);
if (c)
{
if ('-' == c->get_direction())
return true;
return false;
}
// Verify we've got a valid disjunct
AtomType at = a->get_type();
assert ((at == OR) or (at == AND), "Disjunct, expecting OR or AND");
// Recurse down into disjunct
Link* l = dynamic_cast<Link*>(a);
size_t sz = l->get_arity();
for (size_t i=0; i<sz; i++)
{
if (has_lefties(l->get_outgoing_atom(i)))
return true;
}
return false;
}
/// Return true if any of the connectors in the cset point to the left.
bool WordCset::has_left_pointers() const
{
return has_lefties(get_cset());
}
/// Simplify any gratuituousnesting in the cset.
WordCset* WordCset::flatten()
{
// AND and OR inherit from Set
Set* s = dynamic_cast<Set*>(get_cset());
if (NULL == s)
return this;
Atom* flat = s->super_flatten();
// If there is nothing left after flattening, return NULL.
const Link* fl = dynamic_cast<const Link*>(flat);
if (fl && 0 == fl->get_arity())
return NULL;
return new WordCset(get_word(), flat);
}
} // namespace viterbi
} // namespace link-grammar
<commit_msg>backport from tracker<commit_after>/*************************************************************************/
/* Copyright (c) 2012, 2013 Linas Vepstas <linasvepstas@gmail.com> */
/* All rights reserved */
/* */
/* Use of the Viterbi parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software. */
/* This license allows free redistribution and use in source and binary */
/* forms, with or without modification, subject to certain conditions. */
/* */
/*************************************************************************/
#include "compile.h"
// XXX temporary hack until dynamic types are supported !?
namespace atombase {
using namespace link_grammar::viterbi;
// ============================================================
/// Remove optional connectors.
///
/// It doesn't make any sense at all to have an optional connector
/// in an AND-clause, so just remove it. (Well, OK, it "makes sense",
/// its just effectively a no-op, and so doesn't have any effect. So,
/// removing it here simplifies logic in other places.)
///
/// The cost of the optional is passed up to the dsjunct. The reason for
/// this is that the doctionary contains entries such as
/// <post-nominal-x>, whcih has (Xc+ or <costly-null>) & MX-
/// After being disjoined, we need to pass that cost up.
Atom* And::clean() const
{
TV tv = _tv;
OutList cl;
size_t sz = get_arity();
// Special case: it could be a and-clause containing a single,
// optional connector, in which case, we flatten the thing
// (returning the optional connector!)
if (1 == sz)
{
Atom* a = get_outgoing_atom(0);
a->_tv += _tv;
return a;
}
for (size_t i=0; i<sz; i++)
{
Connector* cn = dynamic_cast<Connector*>(get_outgoing_atom(i));
if (cn and cn->is_optional())
{
tv += cn->_tv;
continue;
}
cl.push_back(_oset[i]);
}
return new And(cl, tv);
}
// ============================================================
Atom* Atom::upcaster()
{
if (!this) return this;
const Node* n = dynamic_cast<const Node*>(this);
const Link* l = dynamic_cast<const Link*>(this);
switch (get_type())
{
// Links
case AND:
if (dynamic_cast<And*>(this)) return this;
return new And(l->get_outgoing_set(), _tv);
case OR:
if (dynamic_cast<Or*>(this)) return this;
return new Or(l->get_outgoing_set(), _tv);
case SEQ:
if (dynamic_cast<Seq*>(this)) return this;
return new Seq(l->get_outgoing_set(), _tv);
case SET:
if (dynamic_cast<Set*>(this)) return this;
return new Set(l->get_outgoing_set(), _tv);
// Nodes
case CONNECTOR:
if (dynamic_cast<Connector*>(this)) return this;
return new Connector(n->get_name(), _tv);
case WORD:
if (dynamic_cast<Word*>(this)) return this;
return new Word(n->get_name(), _tv);
default:
assert(0, "Atom::upcaster(): implement me!");
}
}
// ============================================================
Link* Link::append(Atom* a) const
{
OutList ol = get_outgoing_set();
ol.push_back(a);
switch (get_type())
{
// Links
case AND:
return new And(ol, _tv);
case OR:
return new Or(ol, _tv);
case SEQ:
return new Seq(ol, _tv);
case SET:
return new Set(ol, _tv);
default:
assert(0, "append: implement me!");
}
}
} // namespace atombase
// ============================================================
namespace link_grammar {
namespace viterbi {
// Helper function for below.
static bool has_lefties(Atom* a)
{
Connector* c = dynamic_cast<Connector*>(a);
if (c)
{
if ('-' == c->get_direction())
return true;
return false;
}
// Verify we've got a valid disjunct
AtomType at = a->get_type();
assert ((at == OR) or (at == AND), "Disjunct, expecting OR or AND");
// Recurse down into disjunct
Link* l = dynamic_cast<Link*>(a);
size_t sz = l->get_arity();
for (size_t i=0; i<sz; i++)
{
if (has_lefties(l->get_outgoing_atom(i)))
return true;
}
return false;
}
/// Return true if any of the connectors in the cset point to the left.
bool WordCset::has_left_pointers() const
{
return has_lefties(get_cset());
}
/// Simplify any gratuituousnesting in the cset.
WordCset* WordCset::flatten()
{
// AND and OR inherit from Set
Set* s = dynamic_cast<Set*>(get_cset());
if (NULL == s)
return this;
Atom* flat = s->super_flatten();
// If there is nothing left after flattening, return NULL.
const Link* fl = dynamic_cast<const Link*>(flat);
if (fl && 0 == fl->get_arity())
return NULL;
return new WordCset(get_word(), flat);
}
} // namespace viterbi
} // namespace link-grammar
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <array>
#include "utils.hpp"
#include "vm/interrupts.hpp"
namespace yagbe
{
class key_handler
{
uint8_t &P1;
public:
enum class key
{
A = 0,
B = 1,
Select = 2,
Start = 3,
Right = 4,
Left = 5,
Up = 6,
Down = 7,
};
key_handler(uint8_t &p1, interrupts &i) : P1(p1), _i(i)
{
P1 = 0;
}
void step()
{
//int offset = P1 & 0x20 ? 4 : P1 & 0x10 ? 0 : -1;
P1 = rows[1];
}
void set_key(key k, bool v)
{
int i = (int)k;
int r = i / 4;
i %= 4;
bit b(rows[r], i);
b = !v; //on bit = released, off - pressed
_i.joypad();
}
protected:
uint8_t rows[2] = { 0xF, 0xF };
interrupts &_i;
};
};<commit_msg>keypad should now work<commit_after>#pragma once
#include <cstdint>
#include <array>
#include "utils.hpp"
#include "vm/interrupts.hpp"
namespace yagbe
{
class key_handler
{
uint8_t &P1;
public:
enum class key
{
A = 0,
B = 1,
Select = 2,
Start = 3,
Right = 4,
Left = 5,
Up = 6,
Down = 7,
};
key_handler(uint8_t &p1, interrupts &i) : P1(p1), _i(i)
{
P1 = 0;
}
void step()
{
//int offset = P1 & 0x20 ? 4 : P1 & 0x10 ? 0 : -1;
auto c = P1 & 0x30;
if (c & 0x10)
_selected_column = 1;
else if (c & 0x10)
_selected_column = 0;
P1 = rows[_selected_column];
}
void set_key(key k, bool v)
{
int i = (int)k;
int r = i / 4;
i %= 4;
bit b(rows[r], i);
b = !v; //on bit = released, off - pressed
_i.joypad();
}
protected:
int _selected_column = 0;
uint8_t rows[2] = { 0xF, 0xF };
interrupts &_i;
};
};<|endoftext|> |
<commit_before>/* This program simulates a VRPN server to help support debugging and
testing without access to a tracking system.
This file is based heavily on a VRPN server tutorial written by
Sebastian Kuntz for VR Geeks (http://www.vrgeeks.org) in August
2011.
*/
#define OBJECT_NAME "Tracker0"
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <iostream>
#include "vrpn_Text.h"
#include "vrpn_Tracker.h"
#include "vrpn_Analog.h"
#include "vrpn_Button.h"
#include "vrpn_Connection.h"
#include "vecmat.h"
#include "kuhl-util.h"
using namespace std;
class myTracker : public vrpn_Tracker
{
public:
myTracker( vrpn_Connection *c = 0 );
virtual ~myTracker() {};
virtual void mainloop();
protected:
struct timeval _timestamp;
kuhl_fps_state fps_state;
};
myTracker::myTracker( vrpn_Connection *c ) :
vrpn_Tracker( OBJECT_NAME, c )
{
kuhl_getfps_init(&fps_state);
}
void myTracker::mainloop()
{
vrpn_gettimeofday(&_timestamp, NULL);
vrpn_Tracker::timestamp = _timestamp;
printf("\n");
printf("Records sent per second: %.1f\n", kuhl_getfps(&fps_state));
double angle = kuhl_milliseconds_start() / 1000.0;
// Position
pos[0] = sin( angle );
pos[1] = 1.55f; // approx normal eyeheight
pos[2] = 0.0f;
#if 0
double r[10]; // generate some random numbers to simulate imperfect tracking system.
for(int i=0; i<10; i++)
{
r[i] = 0;
r[i] = kuhl_gauss(); // generate some random numbers
}
// Add random noise to position
pos[0] += r[0] * .10;
pos[1] += r[1] * .01;
pos[2] += r[2] * .01;
#endif
printf("Pos = %f %f %f\n", pos[0], pos[1], pos[2]);
// Orientation
float rotMat[9];
// mat3f_rotateEuler_new(rotMat, 0, 0, 0, "XYZ"); // no rotation
mat3f_rotateEuler_new(rotMat, 0, angle*10, 0, "XYZ"); // yaw
//mat3f_rotateEuler_new(rotMat, r[3]*.05, angle*10 + r[4]*.05, r[5]*.05, "XYZ"); // yaw + noise
mat3f_print(rotMat);
// Convert rotation matrix into quaternion
float quat[4];
quatf_from_mat3f(quat, rotMat);
for(int i=0; i<4; i++)
d_quat[i] = quat[i];
char msgbuf[1000];
int len = vrpn_Tracker::encode_to(msgbuf);
if (d_connection->pack_message(len, _timestamp, position_m_id, d_sender_id, msgbuf,
vrpn_CONNECTION_LOW_LATENCY))
{
fprintf(stderr,"can't write message: tossing\n");
}
server_mainloop();
}
int main(int argc, char* argv[])
{
vrpn_Connection_IP* m_Connection = new vrpn_Connection_IP();
myTracker* serverTracker = new myTracker(m_Connection);
cout << "Starting VRPN server." << endl;
while(true)
{
serverTracker->mainloop();
m_Connection->mainloop();
kuhl_limitfps(100);
}
}
<commit_msg>Add timing info to fake vrpn server output<commit_after>/* This program simulates a VRPN server to help support debugging and
testing without access to a tracking system.
This file is based heavily on a VRPN server tutorial written by
Sebastian Kuntz for VR Geeks (http://www.vrgeeks.org) in August
2011.
*/
#define OBJECT_NAME "Tracker0"
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <iostream>
#include "vrpn_Text.h"
#include "vrpn_Tracker.h"
#include "vrpn_Analog.h"
#include "vrpn_Button.h"
#include "vrpn_Connection.h"
#include "vecmat.h"
#include "kuhl-util.h"
using namespace std;
class myTracker : public vrpn_Tracker
{
public:
myTracker( vrpn_Connection *c = 0 );
virtual ~myTracker() {};
virtual void mainloop();
protected:
struct timeval _timestamp;
kuhl_fps_state fps_state;
};
myTracker::myTracker( vrpn_Connection *c ) :
vrpn_Tracker( OBJECT_NAME, c )
{
kuhl_getfps_init(&fps_state);
}
long lastrecord = 0;
void myTracker::mainloop()
{
vrpn_gettimeofday(&_timestamp, NULL);
vrpn_Tracker::timestamp = _timestamp;
printf("\n");
printf("Records sent per second: %.1f\n", kuhl_getfps(&fps_state));
double angle = kuhl_milliseconds_start() / 1000.0;
// Position
pos[0] = sin( angle );
pos[1] = 1.55f; // approx normal eyeheight
pos[2] = 0.0f;
#if 0
double r[10]; // generate some random numbers to simulate imperfect tracking system.
for(int i=0; i<10; i++)
{
r[i] = 0;
r[i] = kuhl_gauss(); // generate some random numbers
}
// Add random noise to position
pos[0] += r[0] * .10;
pos[1] += r[1] * .01;
pos[2] += r[2] * .01;
#endif
printf("Pos = %f %f %f\n", pos[0], pos[1], pos[2]);
// Orientation
float rotMat[9];
// mat3f_rotateEuler_new(rotMat, 0, 0, 0, "XYZ"); // no rotation
mat3f_rotateEuler_new(rotMat, 0, angle*10, 0, "XYZ"); // yaw
//mat3f_rotateEuler_new(rotMat, r[3]*.05, angle*10 + r[4]*.05, r[5]*.05, "XYZ"); // yaw + noise
mat3f_print(rotMat);
// Convert rotation matrix into quaternion
float quat[4];
quatf_from_mat3f(quat, rotMat);
for(int i=0; i<4; i++)
d_quat[i] = quat[i];
char msgbuf[1000];
int len = vrpn_Tracker::encode_to(msgbuf);
printf("Microseconds since last record: %ld\n", kuhl_microseconds()-lastrecord);
lastrecord = kuhl_microseconds();
if (d_connection->pack_message(len, _timestamp, position_m_id, d_sender_id, msgbuf,
vrpn_CONNECTION_LOW_LATENCY))
{
fprintf(stderr,"can't write message: tossing\n");
}
server_mainloop();
}
int main(int argc, char* argv[])
{
vrpn_Connection_IP* m_Connection = new vrpn_Connection_IP();
myTracker* serverTracker = new myTracker(m_Connection);
cout << "Starting VRPN server." << endl;
while(true)
{
serverTracker->mainloop();
m_Connection->mainloop();
kuhl_limitfps(100);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: canvasfont.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: thb $ $Date: 2004-03-18 10:38:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CANVASFONT_HXX
#define _CANVASFONT_HXX
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XCANVASFONT_HPP_
#include <drafts/com/sun/star/rendering/XCanvasFont.hpp>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#include <canvas/vclwrapper.hxx>
#include "canvasbase.hxx"
#include "outdevprovider.hxx"
#include "impltools.hxx"
#define CANVASFONT_IMPLEMENTATION_NAME "VCLCanvas::CanvasFont"
/* Definition of CanvasFont class */
namespace vclcanvas
{
class SpriteCanvas;
class CanvasFont : public ::cppu::WeakImplHelper2< ::drafts::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo >
{
public:
CanvasFont( const ::drafts::com::sun::star::rendering::FontRequest& fontRequest,
const OutDevProvider::ImplRef& rCanvas );
// XCanvasFont
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XPolyPolygon2D > > SAL_CALL queryTextShapes( const ::drafts::com::sun::star::rendering::StringContext& text, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 direction ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::geometry::RealRectangle2D > SAL_CALL queryTightMeasures( const ::drafts::com::sun::star::rendering::StringContext& text, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 direction ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::geometry::RealRectangle2D > SAL_CALL queryTextMeasures( const ::drafts::com::sun::star::rendering::StringContext& text, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 direction ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL queryTextOffsets( const ::drafts::com::sun::star::rendering::StringContext& text, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 direction ) throw (::com::sun::star::uno::RuntimeException);
virtual ::drafts::com::sun::star::geometry::RealRectangle2D SAL_CALL queryTextBounds( const ::drafts::com::sun::star::rendering::StringContext& text, const ::drafts::com::sun::star::rendering::ViewState& viewState, const ::drafts::com::sun::star::rendering::RenderState& renderState, sal_Int8 direction ) throw (::com::sun::star::uno::RuntimeException);
virtual ::drafts::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::drafts::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XCanvas > SAL_CALL getAssociatedCanvas( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
protected:
~CanvasFont(); // we're a ref-counted UNO class. _We_ destroy ourselves.
private:
// default: disabled copy/assignment
CanvasFont(const CanvasFont&);
CanvasFont& operator=( const CanvasFont& );
::canvas::vcltools::VCLObject<Font> maFont;
::drafts::com::sun::star::rendering::FontRequest maFontRequest;
OutDevProvider::ImplRef mpCanvas;
};
}
#endif /* _CANVASFONT_HXX */
<commit_msg>INTEGRATION: CWS presentationengine01 (1.2.2); FILE MERGED 2004/11/17 17:00:29 thb 1.2.2.5: #118514# Canvas module reorg 2004/07/20 19:23:56 thb 1.2.2.4: #110496# Removed self-references to various interface implementations, along the lines, factored out common base implementation for all c++ canvases 2004/05/10 09:36:02 hdu 1.2.2.3: #116716# improve text handling for VCL canvas 2004/04/12 15:12:25 thb 1.2.2.2: #110496# Adaptions after canvas01 merge 2004/04/05 15:57:58 thb 1.2.2.1: Resync with canvas01 changes<commit_after>/*************************************************************************
*
* $RCSfile: canvasfont.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-11-26 17:11:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CANVASFONT_HXX
#define _CANVASFONT_HXX
#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XCANVASFONT_HPP_
#include <drafts/com/sun/star/rendering/XCanvasFont.hpp>
#endif
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#include <canvas/vclwrapper.hxx>
#include "canvashelper.hxx"
#include "impltools.hxx"
#define CANVASFONT_IMPLEMENTATION_NAME "VCLCanvas::CanvasFont"
/* Definition of CanvasFont class */
namespace vclcanvas
{
typedef ::cppu::WeakComponentImplHelper2< ::drafts::com::sun::star::rendering::XCanvasFont,
::com::sun::star::lang::XServiceInfo > CanvasFont_Base;
class CanvasFont : public ::comphelper::OBaseMutex, public CanvasFont_Base
{
public:
typedef ::comphelper::ImplementationReference<
CanvasFont,
::drafts::com::sun::star::rendering::XCanvasFont > ImplRef;
CanvasFont( const ::drafts::com::sun::star::rendering::FontRequest& fontRequest,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& extraFontProperties,
const ::drafts::com::sun::star::geometry::Matrix2D& rFontMatrix,
const OutDevProviderSharedPtr& rDevice );
/// Dispose all internal references
virtual void SAL_CALL disposing();
// XCanvasFont
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::drafts::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
virtual ::drafts::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::drafts::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties( ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );
::Font getVCLFont() const;
protected:
~CanvasFont(); // we're a ref-counted UNO class. _We_ destroy ourselves.
private:
// default: disabled copy/assignment
CanvasFont(const CanvasFont&);
CanvasFont& operator=( const CanvasFont& );
::canvas::vcltools::VCLObject<Font> maFont;
::drafts::com::sun::star::rendering::FontRequest maFontRequest;
OutDevProviderSharedPtr mpRefDevice;
};
}
#endif /* _CANVASFONT_HXX */
<|endoftext|> |
<commit_before>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dirent.h"
#include <sys/stat.h>
#include <errno.h>
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif
bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
rapidxml::file<> fdoc(strPlugin.c_str());
rapidxml::xml_document<> doc;
doc.parse<0>(fdoc.data());
rapidxml::xml_node<>* pRoot = doc.first_node();
for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
{
const char* strPluginName = pPluginNode->first_attribute("Name")->value();
const char* strMain = pPluginNode->first_attribute("Main")->value();
pluginList.push_back(std::string(strPluginName));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
if (!strAppID)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
if (!pPluginConfigPathNode)
{
//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
return false;
}
if (NULL == pPluginConfigPathNode->first_attribute("Name"))
{
//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
return false;
}
configPath = pPluginConfigPathNode->first_attribute("Name")->value();
return true;
}
int CopyFile(std::string& SourceFile, std::string& NewFile)
{
ifstream in;
ofstream out;
in.open(SourceFile.c_str(), ios::binary);//Դļ
if (in.fail())//Դļʧ
{
cout << "Error 1: Fail to open the source file." << endl;
in.close();
out.close();
return 0;
}
out.open(NewFile.c_str(), ios::binary);//Ŀļ
if (out.fail())//ļʧ
{
cout << "Error 2: Fail to create the new file." << endl;
out.close();
in.close();
return 0;
}
else//ļ
{
out << in.rdbuf();
out.close();
in.close();
return 1;
}
}
std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
_finddata_t FileInfo;
std::string strfind = folderPath + "\\*";
long long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
std::cerr << "can not match the folder path" << std::endl;
exit(-1);
}
do {
//жǷĿ¼
if (FileInfo.attrib & _A_SUBDIR)
{
//Ҫ
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
std::string newPath = folderPath + "\\" + FileInfo.name;
//dfsFolder(newPath, depth);
auto newResult = GetFileListInFolder(newPath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
}
else
{
std::string filename = (folderPath + "\\" + FileInfo.name);
result.push_back(filename);
}
} while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
DIR *pDir;
struct dirent *ent;
char childpath[512];
char absolutepath[512];
pDir = opendir(folderPath.c_str());
memset(childpath, 0, sizeof(childpath));
while ((ent = readdir(pDir)) != NULL)
{
if (ent->d_type & DT_DIR)
{
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
{
continue;
}
std::string childpath = folderPath + "/" + ent->d_name;
auto newResult = GetFileListInFolder(childpath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
else
{
sprintf(absolutepath, "%s/%s", folderPath.c_str(), ent->d_name);
result.push_back(absolutepath);
}
}
sort(result.begin(), result.end());//
#endif
return result;
}
void printResult(int result, std::string& strName)
{
if (result == 1)
{
printf("Copy file: %s success!\n", strName.c_str());
}
else
{
printf("Copy file: %s failed!\n", strName.c_str());
}
}
int main()
{
std::vector<std::string> fileList;
#ifdef NF_DEBUG_MODE
fileList = GetFileListInFolder("../../Debug", 10);
#else
fileList = GetFileListInFolder("../../Release", 10);
#endif
for (auto fileName : fileList)
{
if (fileName.find("Plugin.xml") != std::string::npos)
{
printf("Reading xml file: %s\n", fileName.c_str());
std::vector<std::string> pluginList;
std::string configPath = "";
GetPluginNameList(fileName, pluginList, configPath);
if (pluginList.size() > 0 && configPath != "")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
pluginList.push_back("libprotobuf");
pluginList.push_back("NFMessageDefine");
#else
pluginList.push_back("NFMessageDefine");
#endif
pluginList.push_back("NFPluginLoader");
configPath = "../" + configPath;
configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;
for (std::string name : pluginList)
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#else
#endif
int result = 0;
if (name == "NFPluginLoader")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
#else
std::string src = configPath + "Comm/Release/" + name;
#endif
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.exe";
auto strDes = des + "_d.exe";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
printResult(CopyFile(strSrc, strDes), strSrc);
printResult(CopyFile(strSrcPDB, strDesPDB), strSrcPDB);
#else
std::string src = configPath + "Comm/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d";
auto strDes = des + "_d";
printResult(CopyFile(strSrc, strDes), strSrc);
#endif
}
else
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
#else
std::string src = configPath + "Comm/Release/" + name;
#endif
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.dll";
auto strDes = des + "_d.dll";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
printResult(CopyFile(strSrc, strDes), strSrc);
printResult(CopyFile(strSrcPDB, strDesPDB), strSrcPDB);
#else
std::string src = configPath + "Comm/lib" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.so";
auto strDes = des + "_d.so";
printResult(CopyFile(strSrc, strDes), strSrc);
#endif
}
}
}
}
}
std::cin.ignore();
return 0;
}<commit_msg>update<commit_after>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif
bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
rapidxml::file<> fdoc(strPlugin.c_str());
rapidxml::xml_document<> doc;
doc.parse<0>(fdoc.data());
rapidxml::xml_node<>* pRoot = doc.first_node();
for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
{
const char* strPluginName = pPluginNode->first_attribute("Name")->value();
const char* strMain = pPluginNode->first_attribute("Main")->value();
pluginList.push_back(std::string(strPluginName));
}
rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
if (!pPluginAppNode)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
if (!strAppID)
{
//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
return false;
}
rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
if (!pPluginConfigPathNode)
{
//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
return false;
}
if (NULL == pPluginConfigPathNode->first_attribute("Name"))
{
//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
return false;
}
configPath = pPluginConfigPathNode->first_attribute("Name")->value();
return true;
}
int CopyFile(std::string& SourceFile, std::string& NewFile)
{
ifstream in;
ofstream out;
in.open(SourceFile.c_str(), ios::binary);//Դļ
if (in.fail())//Դļʧ
{
cout << "Error 1: Fail to open the source file." << endl;
in.close();
out.close();
return 0;
}
out.open(NewFile.c_str(), ios::binary);//Ŀļ
if (out.fail())//ļʧ
{
cout << "Error 2: Fail to create the new file." << endl;
out.close();
in.close();
return 0;
}
else//ļ
{
out << in.rdbuf();
out.close();
in.close();
return 1;
}
}
std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
_finddata_t FileInfo;
std::string strfind = folderPath + "\\*";
long long Handle = _findfirst(strfind.c_str(), &FileInfo);
if (Handle == -1L)
{
std::cerr << "can not match the folder path" << std::endl;
exit(-1);
}
do {
//жǷĿ¼
if (FileInfo.attrib & _A_SUBDIR)
{
//Ҫ
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
std::string newPath = folderPath + "\\" + FileInfo.name;
//dfsFolder(newPath, depth);
auto newResult = GetFileListInFolder(newPath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
}
else
{
std::string filename = (folderPath + "\\" + FileInfo.name);
result.push_back(filename);
}
} while (_findnext(Handle, &FileInfo) == 0);
_findclose(Handle);
#else
DIR *pDir;
struct dirent *ent;
char childpath[512];
char absolutepath[512];
pDir = opendir(folderPath.c_str());
memset(childpath, 0, sizeof(childpath));
while ((ent = readdir(pDir)) != NULL)
{
if (ent->d_type & DT_DIR)
{
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
{
continue;
}
std::string childpath = folderPath + "/" + ent->d_name;
auto newResult = GetFileListInFolder(childpath, depth);
result.insert(result.begin(), newResult.begin(), newResult.end());
}
else
{
sprintf(absolutepath, "%s/%s", folderPath.c_str(), ent->d_name);
result.push_back(absolutepath);
}
}
sort(result.begin(), result.end());//
#endif
return result;
}
void printResult(int result, std::string& strName)
{
if (result == 1)
{
printf("Copy file: %s success!\n", strName.c_str());
}
else
{
printf("Copy file: %s failed!\n", strName.c_str());
}
}
int main()
{
std::vector<std::string> fileList;
#ifdef NF_DEBUG_MODE
fileList = GetFileListInFolder("../../Debug", 10);
#else
fileList = GetFileListInFolder("../../Release", 10);
#endif
for (auto fileName : fileList)
{
if (fileName.find("Plugin.xml") != std::string::npos)
{
printf("Reading xml file: %s\n", fileName.c_str());
std::vector<std::string> pluginList;
std::string configPath = "";
GetPluginNameList(fileName, pluginList, configPath);
if (pluginList.size() > 0 && configPath != "")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
pluginList.push_back("libprotobuf");
pluginList.push_back("NFMessageDefine");
#else
pluginList.push_back("NFMessageDefine");
#endif
pluginList.push_back("NFPluginLoader");
configPath = "../" + configPath;
configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;
for (std::string name : pluginList)
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#else
#endif
int result = 0;
if (name == "NFPluginLoader")
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
#else
std::string src = configPath + "Comm/Release/" + name;
#endif
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.exe";
auto strDes = des + "_d.exe";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
printResult(CopyFile(strSrc, strDes), strSrc);
printResult(CopyFile(strSrcPDB, strDesPDB), strSrcPDB);
#else
std::string src = configPath + "Comm/" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d";
auto strDes = des + "_d";
printResult(CopyFile(strSrc, strDes), strSrc);
#endif
}
else
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DEBUG_MODE
std::string src = configPath + "Comm/Debug/" + name;
#else
std::string src = configPath + "Comm/Release/" + name;
#endif
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.dll";
auto strDes = des + "_d.dll";
auto strSrcPDB = src + "_d.pdb";
auto strDesPDB = des + "_d.pdb";
printResult(CopyFile(strSrc, strDes), strSrc);
printResult(CopyFile(strSrcPDB, strDesPDB), strSrcPDB);
#else
std::string src = configPath + "Comm/lib" + name;
std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
auto strSrc = src + "_d.so";
auto strDes = des + "_d.so";
printResult(CopyFile(strSrc, strDes), strSrc);
#endif
}
}
}
}
}
std::cin.ignore();
return 0;
}<|endoftext|> |
<commit_before>/*
Copyright (C) 2008-2016 The Communi Project
You may use this file under the terms of BSD license as follows:
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 copyright holder 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 HOLDERS 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 "messagehandler.h"
#include <IrcBufferModel>
#include <IrcConnection>
#include <IrcMessage>
#include <IrcChannel>
#include <IrcBuffer>
IRC_USE_NAMESPACE
MessageHandler::MessageHandler(QObject* parent) : QObject(parent)
{
setModel(qobject_cast<IrcBufferModel*>(parent));
}
MessageHandler::~MessageHandler()
{
}
IrcBufferModel* MessageHandler::model() const
{
return d.model;
}
void MessageHandler::setModel(IrcBufferModel* model)
{
if (d.model != model) {
if (d.model)
disconnect(d.model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(handleMessage(IrcMessage*)));
d.model = model;
if (model)
connect(model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(handleMessage(IrcMessage*)));
}
}
IrcBuffer* MessageHandler::defaultBuffer() const
{
return d.defaultBuffer;
}
void MessageHandler::setDefaultBuffer(IrcBuffer* buffer)
{
d.defaultBuffer = buffer;
}
IrcBuffer* MessageHandler::currentBuffer() const
{
return d.currentBuffer;
}
void MessageHandler::setCurrentBuffer(IrcBuffer* buffer)
{
d.currentBuffer = buffer;
}
void MessageHandler::handleMessage(IrcMessage* message)
{
switch (message->type()) {
case IrcMessage::Motd:
sendMessage(message, d.defaultBuffer);
break;
case IrcMessage::Numeric:
if (static_cast<IrcNumericMessage*>(message)->code() < 300)
sendMessage(message, d.defaultBuffer);
else
sendMessage(message, d.currentBuffer);
break;
default:
sendMessage(message, d.currentBuffer);
break;
}
}
void MessageHandler::sendMessage(IrcMessage* message, IrcBuffer* buffer)
{
if (!buffer)
buffer = d.defaultBuffer;
if (buffer)
buffer->receiveMessage(message);
}
void MessageHandler::sendMessage(IrcMessage* message, const QString& buffer)
{
sendMessage(message, d.model->find(buffer));
}
<commit_msg>MessageHandler: proper handing of ChanServ and RPL_CHANNEL_URL messages<commit_after>/*
Copyright (C) 2008-2016 The Communi Project
You may use this file under the terms of BSD license as follows:
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 copyright holder 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 HOLDERS 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 "messagehandler.h"
#include <IrcBufferModel>
#include <IrcConnection>
#include <IrcMessage>
#include <IrcChannel>
#include <IrcBuffer>
#include <Irc>
IRC_USE_NAMESPACE
MessageHandler::MessageHandler(QObject* parent) : QObject(parent)
{
setModel(qobject_cast<IrcBufferModel*>(parent));
}
MessageHandler::~MessageHandler()
{
}
IrcBufferModel* MessageHandler::model() const
{
return d.model;
}
void MessageHandler::setModel(IrcBufferModel* model)
{
if (d.model != model) {
if (d.model)
disconnect(d.model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(handleMessage(IrcMessage*)));
d.model = model;
if (model)
connect(model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(handleMessage(IrcMessage*)));
}
}
IrcBuffer* MessageHandler::defaultBuffer() const
{
return d.defaultBuffer;
}
void MessageHandler::setDefaultBuffer(IrcBuffer* buffer)
{
d.defaultBuffer = buffer;
}
IrcBuffer* MessageHandler::currentBuffer() const
{
return d.currentBuffer;
}
void MessageHandler::setCurrentBuffer(IrcBuffer* buffer)
{
d.currentBuffer = buffer;
}
void MessageHandler::handleMessage(IrcMessage* message)
{
switch (message->type()) {
case IrcMessage::Motd:
{
sendMessage(message, d.defaultBuffer);
break;
}
case IrcMessage::Numeric:
{
IrcNumericMessage *numMsg = static_cast<IrcNumericMessage*>(message);
if (numMsg->code() == Irc::RPL_CHANNEL_URL)
sendMessage(message, message->parameters().at(1));
else if (numMsg->code() < 300)
sendMessage(message, d.defaultBuffer);
else
sendMessage(message, d.currentBuffer);
break;
}
case IrcMessage::Notice:
{
if (message->prefix() == "ChanServ!ChanServ@services.") {
// Forward messages from ChanServ to the appropriate channel
QString content = static_cast<IrcNoticeMessage*>(message)->content();
if (content.startsWith("[")) {
int i = content.indexOf("]");
if (i != -1) {
QString title = content.mid(1, i - 1);
sendMessage(message, title);
}
}
}
break;
}
default:
{
sendMessage(message, d.currentBuffer);
break;
}
}
if (!message->property("handled").isValid() || !message->property("handled").toBool()) {
sendMessage(message, d.currentBuffer);
}
}
void MessageHandler::sendMessage(IrcMessage* message, IrcBuffer* buffer)
{
if (!buffer)
buffer = d.defaultBuffer;
if (buffer)
buffer->receiveMessage(message);
message->setProperty("handled", true);
}
void MessageHandler::sendMessage(IrcMessage* message, const QString& bufferName)
{
IrcBuffer *buffer = d.model->find(bufferName);
sendMessage(message, buffer);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Help.cpp : Help and About dialogs
****************************************************************************
* Copyright (C) 2007 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
*
* 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 "dialogs/about.hpp"
#include "dialogs/help.hpp"
#include "dialogs_provider.hpp"
#include "util/qvlcframe.hpp"
#include "qt4.hpp"
#include <QTextBrowser>
#include <QTabWidget>
#include <QFile>
#include <QLabel>
#include <QString>
HelpDialog *HelpDialog::instance = NULL;
HelpDialog::HelpDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf )
{
setWindowTitle( qtr( "Help" ) );
resize( 600, 500 );
QGridLayout *layout = new QGridLayout( this );
QTextBrowser *helpBrowser = new QTextBrowser( this );
helpBrowser->setOpenExternalLinks( true );
helpBrowser->setHtml( _("<html><h2>Welcome to VLC media player help</h2><h3>Documentation</h3><p>You can find VLC documentation on VideoLAN's <a href=\"http://wiki.videolan.org\">wiki</a> website.</p> <p>If you are a newcomer to VLC media player, please read the<br><a href=\"http://wiki.videolan.org/Documentation:VLC_for_dummies\"><em>Introduction to VLC media player</em></a>.</p><p>You will find some information on how to use the player in the <br>\"<a href=\"http://wiki.videolan.org/Documentation:Play_HowTo\">How to play files with VLC media player</a>\"document.</p> For all the saving, converting, transcoding, encoding, muxing and streaming tasks, you should find useful information in the <a href=\"http://wiki.videolan.org/Documentation:Streaming_HowTo\">Streaming Documentation</a>.</p><p>If you are unsure about terminology, please consult the <a href=\"http://wiki.videolan.org/Knowledge_Base\">knowledge base</a>.</p> <p>To understand the main keyboard shortcuts, read the <a href=\"http://wiki.videolan.org/Hotkeys\">shortcuts</a> page.</p><h3>Help</h3><p>Before asking any question, please refer yourself to the <a href=\"http://wiki.videolan.org/Frequently_Asked_Questions\">FAQ</a></p><p>You might then get (and give) help on the <a href=\"http://forum.videolan.org\">Forums</a>, the <a href=\"http://www.videolan.org/vlc/lists.html\">mailing-lists</a> or our IRC channel ( <a href=\"http://krishna.videolan.org/cgi-bin/irc/irc.cgi\"><em>#videolan</em></a> on irc.freenode.net ).</p><h3>Contribute to the project<h3><p>You can help the VideoLAN project giving some of your time to help the community, to design skins, to translate the documentation, to test and to code. You can also give funds and material to help us. And of course, you can <b>promote</b> VLC media player.<p> </html>") );
QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
closeButton->setDefault( true );
layout->addWidget( helpBrowser, 0, 0, 1, 0 );
layout->addWidget( closeButton, 1, 3 );
BUTTONACT( closeButton, close() );
}
HelpDialog::~HelpDialog()
{
}
void HelpDialog::close()
{
this->toggleVisible();
}
AboutDialog *AboutDialog::instance = NULL;
AboutDialog::AboutDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf )
{
setWindowTitle( qtr( "About" ) );
resize( 600, 500 );
QGridLayout *layout = new QGridLayout( this );
QTabWidget *tab = new QTabWidget( this );
QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
closeButton->setDefault( true );
QLabel *introduction = new QLabel(
qtr( "Information about VLC media player" ) );
layout->addWidget( introduction, 0, 0, 1, 4 );
layout->addWidget( tab, 1, 0, 1, 4 );
layout->addWidget( closeButton, 2, 3, 1, 1 );
/* GPL License */
QTextEdit *licenseEdit = new QTextEdit( this );
licenseEdit->setText( qfu( psz_licence ) );
licenseEdit->setReadOnly( true );
/* People who helped */
QTextEdit *thanksEdit = new QTextEdit( this );
thanksEdit->setText( qfu( psz_thanks ) );
thanksEdit->setReadOnly( true );
/* People who helped */
QTextEdit *authorsEdit = new QTextEdit( this );
authorsEdit->setText( qfu( psz_authors ) );
authorsEdit->setReadOnly( true );
/* add the tabs to the Tabwidget */
tab->addTab( NULL, qtr( "General Info" ) );
tab->addTab( authorsEdit, qtr( "Authors" ) );
tab->addTab( thanksEdit, qtr("Thanks") );
tab->addTab( licenseEdit, qtr("Distribution License") );
BUTTONACT( closeButton, close() );
}
AboutDialog::~AboutDialog()
{
}
void AboutDialog::close()
{
this->toggleVisible();
}
<commit_msg>Qt4 - Add a proper about section. This needs to be reviewed for i18n.<commit_after>/*****************************************************************************
* Help.cpp : Help and About dialogs
****************************************************************************
* Copyright (C) 2007 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
*
* 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 "dialogs/about.hpp"
#include "dialogs/help.hpp"
#include "dialogs_provider.hpp"
#include "util/qvlcframe.hpp"
#include "qt4.hpp"
#include <QTextBrowser>
#include <QTabWidget>
#include <QFile>
#include <QLabel>
#include <QString>
HelpDialog *HelpDialog::instance = NULL;
HelpDialog::HelpDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf )
{
setWindowTitle( qtr( "Help" ) );
resize( 600, 500 );
QGridLayout *layout = new QGridLayout( this );
QTextBrowser *helpBrowser = new QTextBrowser( this );
helpBrowser->setOpenExternalLinks( true );
helpBrowser->setHtml( _("<html><h2>Welcome to VLC media player help</h2><h3>Documentation</h3><p>You can find VLC documentation on VideoLAN's <a href=\"http://wiki.videolan.org\">wiki</a> website.</p> <p>If you are a newcomer to VLC media player, please read the<br><a href=\"http://wiki.videolan.org/Documentation:VLC_for_dummies\"><em>Introduction to VLC media player</em></a>.</p><p>You will find some information on how to use the player in the <br>\"<a href=\"http://wiki.videolan.org/Documentation:Play_HowTo\">How to play files with VLC media player</a>\"document.</p> For all the saving, converting, transcoding, encoding, muxing and streaming tasks, you should find useful information in the <a href=\"http://wiki.videolan.org/Documentation:Streaming_HowTo\">Streaming Documentation</a>.</p><p>If you are unsure about terminology, please consult the <a href=\"http://wiki.videolan.org/Knowledge_Base\">knowledge base</a>.</p> <p>To understand the main keyboard shortcuts, read the <a href=\"http://wiki.videolan.org/Hotkeys\">shortcuts</a> page.</p><h3>Help</h3><p>Before asking any question, please refer yourself to the <a href=\"http://wiki.videolan.org/Frequently_Asked_Questions\">FAQ</a></p><p>You might then get (and give) help on the <a href=\"http://forum.videolan.org\">Forums</a>, the <a href=\"http://www.videolan.org/vlc/lists.html\">mailing-lists</a> or our IRC channel ( <a href=\"http://krishna.videolan.org/cgi-bin/irc/irc.cgi\"><em>#videolan</em></a> on irc.freenode.net ).</p><h3>Contribute to the project<h3><p>You can help the VideoLAN project giving some of your time to help the community, to design skins, to translate the documentation, to test and to code. You can also give funds and material to help us. And of course, you can <b>promote</b> VLC media player.<p> </html>") );
QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
closeButton->setDefault( true );
layout->addWidget( helpBrowser, 0, 0, 1, 0 );
layout->addWidget( closeButton, 1, 3 );
BUTTONACT( closeButton, close() );
}
HelpDialog::~HelpDialog()
{
}
void HelpDialog::close()
{
this->toggleVisible();
}
AboutDialog *AboutDialog::instance = NULL;
AboutDialog::AboutDialog( intf_thread_t *_p_intf) : QVLCFrame( _p_intf )
{
setWindowTitle( qtr( "About" ) );
resize( 600, 500 );
QGridLayout *layout = new QGridLayout( this );
QTabWidget *tab = new QTabWidget( this );
QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
closeButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
closeButton->setDefault( true );
QLabel *introduction = new QLabel(
qtr( "Information about VLC media player." ) );
QLabel *iconVLC = new QLabel;
iconVLC->setPixmap( QPixmap( ":/vlc48.png" ) );
layout->addWidget( iconVLC, 0, 0, 1, 1 );
layout->addWidget( introduction, 0, 1, 1, 7 );
layout->addWidget( tab, 1, 0, 1, 8 );
layout->addWidget( closeButton, 2, 6, 1, 2 );
/* Main Introduction */
QWidget *infoWidget = new QWidget( this );
QHBoxLayout *infoLayout = new QHBoxLayout( infoWidget );
QLabel *infoLabel = new QLabel( "VLC media player " PACKAGE_VERSION "\n\n"
"(c) 1996-2006 - the VideoLAN Team\n\n" +
qtr( "VLC media player is a free media player, made by the "
"VideoLAN Team.\nIt is a standalone multimedia player, "
"encoder and streamer, that can read from many supports "
"(files, CDs, DVDs, networks, capture cards) and that works "
"on many platforms.\n\n" )
+ qtr( "You are using the new Qt4 Interface.\n" )
+ qtr( "Compiled by " ) + qfu( VLC_CompileBy() )+ "@"
+ qfu( VLC_CompileDomain() ) + ".\n"
+ "Compiler: " + qfu( VLC_Compiler() ) +".\n"
+ qtr( "Based on SVN revision: " ) + qfu( VLC_Changeset() )
+ ".\n\n"
+ qtr( "This program comes with NO WARRANTY, to the extent "
"permitted by the law; read the distribution tab.\n\n" )
+ "The VideoLAN team <videolan@videolan.org> \n"
"http://www.videolan.org/\n") ;
infoLabel->setWordWrap( infoLabel );
QLabel *iconVLC2 = new QLabel;
iconVLC2->setPixmap( QPixmap( ":/vlc128.png" ) );
infoLayout->addWidget( iconVLC2 );
infoLayout->addWidget( infoLabel );
/* GPL License */
QTextEdit *licenseEdit = new QTextEdit( this );
licenseEdit->setText( qfu( psz_licence ) );
licenseEdit->setReadOnly( true );
/* People who helped */
QWidget *thanksWidget = new QWidget( this );
QVBoxLayout *thanksLayout = new QVBoxLayout( thanksWidget );
QLabel *thanksLabel = new QLabel( qtr("We would like to thanks the whole "
"community, the testers, our users and the following people "
"(and the missing ones...) for their collaboration to "
"provide the best software." ) );
thanksLabel->setWordWrap( true );
thanksLayout->addWidget( thanksLabel );
QTextEdit *thanksEdit = new QTextEdit( this );
thanksEdit->setText( qfu( psz_thanks ) );
thanksEdit->setReadOnly( true );
thanksLayout->addWidget( thanksEdit );
/* People who wrote the software */
QTextEdit *authorsEdit = new QTextEdit( this );
authorsEdit->setText( qfu( psz_authors ) );
authorsEdit->setReadOnly( true );
/* add the tabs to the Tabwidget */
tab->addTab( infoWidget, qtr( "General Info" ) );
tab->addTab( authorsEdit, qtr( "Authors" ) );
tab->addTab( thanksWidget, qtr("Thanks") );
tab->addTab( licenseEdit, qtr("Distribution License") );
BUTTONACT( closeButton, close() );
}
AboutDialog::~AboutDialog()
{
}
void AboutDialog::close()
{
this->toggleVisible();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* open.cpp : Advanced open dialog
*****************************************************************************
* Copyright (C) 2006-2007 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* 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 "input_manager.hpp"
#include "dialogs/open.hpp"
#include "components/open.hpp"
#include <QTabWidget>
#include <QGridLayout>
#include <QFileDialog>
#include <QRegExp>
#include <QMenu>
OpenDialog *OpenDialog::instance = NULL;
OpenDialog::OpenDialog( QWidget *parent, intf_thread_t *_p_intf, bool modal,
int _action_flag ) : QVLCDialog( parent, _p_intf )
{
setModal( modal );
i_action_flag = _action_flag;
/* Basic Creation of the Window */
ui.setupUi( this );
setWindowTitle( qtr("Open" ) );
resize( 410, 300);
/* Tab definition and creation */
fileOpenPanel = new FileOpenPanel( ui.Tab, p_intf );
discOpenPanel = new DiscOpenPanel( ui.Tab, p_intf );
netOpenPanel = new NetOpenPanel( ui.Tab, p_intf );
captureOpenPanel = new CaptureOpenPanel( ui.Tab, p_intf );
/* Insert the tabs */
ui.Tab->insertTab( OPEN_FILE_TAB, fileOpenPanel, qtr( "&File" ) );
ui.Tab->insertTab( OPEN_DISC_TAB, discOpenPanel, qtr( "&Disc" ) );
ui.Tab->insertTab( OPEN_NETWORK_TAB, netOpenPanel, qtr( "&Network" ) );
ui.Tab->insertTab( OPEN_CAPTURE_TAB, captureOpenPanel,
qtr( "Capture &Device" ) );
/* Hide the advancedPanel */
if(! config_GetInt( p_intf, "qt-adv-options") )
{
ui.advancedFrame->hide();
}
else
{
ui.advancedCheckBox->setCheckState( Qt::Checked );
}
ui.slaveLabel->hide();
ui.slaveText->hide();
ui.slaveBrowseButton->hide();
/* Buttons Creation */
QSizePolicy buttonSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum );
buttonSizePolicy.setHorizontalStretch(0);
buttonSizePolicy.setVerticalStretch(0);
playButton = new QToolButton( this );
playButton->setText( qtr( "&Play" ) );
playButton->setSizePolicy( buttonSizePolicy );
playButton->setMinimumSize( QSize(90, 0) );
playButton->setPopupMode( QToolButton::MenuButtonPopup );
playButton->setToolButtonStyle( Qt::ToolButtonTextOnly );
cancelButton = new QPushButton();
cancelButton->setText( qtr( "&Cancel" ) );
cancelButton->setSizePolicy( buttonSizePolicy );
QMenu * openButtonMenu = new QMenu( "Open" );
openButtonMenu->addAction( qtr("&Enqueue"), this, SLOT( enqueue() ),
QKeySequence( "Alt+E") );
openButtonMenu->addAction( qtr("&Play"), this, SLOT( play() ),
QKeySequence( "Alt+P" ) );
openButtonMenu->addAction( qtr("&Stream"), this, SLOT( stream() ) ,
QKeySequence( "Alt+S" ) );
openButtonMenu->addAction( qtr("&Convert"), this, SLOT( transcode() ) ,
QKeySequence( "Alt+C" ) );
playButton->setMenu( openButtonMenu );
ui.buttonsBox->addButton( playButton, QDialogButtonBox::AcceptRole );
ui.buttonsBox->addButton( cancelButton, QDialogButtonBox::RejectRole );
/* Force MRL update on tab change */
CONNECT( ui.Tab, currentChanged(int), this, signalCurrent());
CONNECT( fileOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( netOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( discOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( captureOpenPanel, mrlUpdated( QString ), this,
updateMRL(QString) );
CONNECT( fileOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( netOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( discOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( captureOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
/* Advanced frame Connects */
CONNECT( ui.slaveText, textChanged(QString), this, updateMRL());
CONNECT( ui.cacheSpinBox, valueChanged(int), this, updateMRL());
CONNECT( ui.startTimeSpinBox, valueChanged(int), this, updateMRL());
BUTTONACT( ui.advancedCheckBox , toggleAdvancedPanel() );
/* Buttons action */
BUTTONACT( playButton, play());
BUTTONACT( cancelButton, cancel());
/* At creation time, modify the default buttons */
if ( i_action_flag ) setMenuAction();
/* Initialize caching */
storedMethod = "";
newMethod("file-caching");
mainHeight = advHeight = 0;
}
OpenDialog::~OpenDialog()
{
}
/* Finish the dialog and decide if you open another one after */
void OpenDialog::setMenuAction()
{
switch ( i_action_flag )
{
case OPEN_AND_STREAM:
playButton->setText( qtr("&Stream") );
BUTTONACT( playButton, stream() );
break;
case OPEN_AND_SAVE:
playButton->setText( qtr("&Convert / Save") );
BUTTONACT( playButton, transcode() );
break;
case OPEN_AND_ENQUEUE:
playButton->setText( qtr("&Enqueue") );
BUTTONACT( playButton, enqueue() );
break;
case OPEN_AND_PLAY:
default:
playButton->setText( qtr("&Play") );
BUTTONACT( playButton, play() );
}
}
void OpenDialog::showTab(int i_tab=0)
{
this->show();
ui.Tab->setCurrentIndex(i_tab);
}
void OpenDialog::signalCurrent() {
if (ui.Tab->currentWidget() != NULL) {
(dynamic_cast<OpenPanel*>(ui.Tab->currentWidget()))->updateMRL();
}
}
/***********
* Actions *
***********/
/* If Cancel is pressed or escaped */
void OpenDialog::cancel()
{
fileOpenPanel->clear();
this->toggleVisible();
if( isModal() )
reject();
}
/* If EnterKey is pressed */
void OpenDialog::close()
{
/* FIXME */
if ( !i_action_flag )
{
play();
}
else
{
stream();
}
}
/* Play button */
void OpenDialog::play()
{
finish( false );
}
void OpenDialog::enqueue()
{
finish( true );
}
void OpenDialog::transcode()
{
stream( true );
}
void OpenDialog::stream( bool b_transcode_only )
{
/* not finished FIXME */
/* Should go through the finish function */
THEDP->streamingDialog( mrl, b_transcode_only );
}
void OpenDialog::finish( bool b_enqueue = false )
{
this->toggleVisible();
mrl = ui.advancedLineInput->text();
if( !isModal() )
{
QStringList tempMRL = SeparateEntries( mrl );
for( size_t i = 0; i < tempMRL.size(); i++ )
{
bool b_start = !i && !b_enqueue;
input_item_t *p_input;
const char *psz_utf8 = qtu( tempMRL[i] );
p_input = input_ItemNew( p_intf, psz_utf8, NULL );
/* Insert options */
while( i + 1 < tempMRL.size() && tempMRL[i + 1].startsWith( ":" ) )
{
i++;
psz_utf8 = qtu( tempMRL[i] );
input_ItemAddOption( p_input, psz_utf8 );
}
if( b_start )
{
playlist_AddInput( THEPL, p_input,
PLAYLIST_APPEND | PLAYLIST_GO,
PLAYLIST_END, VLC_TRUE, VLC_FALSE );
}
else
{
playlist_AddInput( THEPL, p_input,
PLAYLIST_APPEND|PLAYLIST_PREPARSE,
PLAYLIST_END, VLC_TRUE, VLC_FALSE );
}
}
}
else
accept();
}
void OpenDialog::toggleAdvancedPanel()
{
//FIXME does not work under Windows
if( ui.advancedFrame->isVisible() ) {
ui.advancedFrame->hide();
#ifndef WIN32
setMinimumHeight(1);
resize( width(), mainHeight );
#endif
} else {
#ifndef WIN32
if( mainHeight == 0 )
mainHeight = height();
#endif
ui.advancedFrame->show();
#ifndef WIN32
if( advHeight == 0 ) {
advHeight = height() - mainHeight;
}
resize( width(), mainHeight + advHeight );
#endif
}
}
void OpenDialog::updateMRL() {
mrl = mainMRL;
if( ui.slaveCheckbox->isChecked() ) {
mrl += " :input-slave=" + ui.slaveText->text();
}
int i_cache = config_GetInt( p_intf, qta(storedMethod) );
if( i_cache != ui.cacheSpinBox->value() ) {
mrl += QString(" :%1=%2").arg(storedMethod).
arg(ui.cacheSpinBox->value());
}
if( ui.startTimeSpinBox->value()) {
mrl += " :start-time=" + QString("%1").
arg(ui.startTimeSpinBox->value());
}
ui.advancedLineInput->setText(mrl);
}
void OpenDialog::updateMRL(QString tempMRL)
{
mainMRL = tempMRL;
updateMRL();
}
void OpenDialog::newMethod(QString method)
{
if( method != storedMethod ) {
storedMethod = method;
int i_value = config_GetInt( p_intf, qta(storedMethod) );
ui.cacheSpinBox->setValue(i_value);
}
}
QStringList OpenDialog::SeparateEntries( QString entries )
{
bool b_quotes_mode = false;
QStringList entries_array;
QString entry;
int index = 0;
while( index < entries.size() )
{
int delim_pos = entries.indexOf( QRegExp( "\\s+|\"" ), index );
if( delim_pos < 0 ) delim_pos = entries.size() - 1;
entry += entries.mid( index, delim_pos - index + 1 );
index = delim_pos + 1;
if( entry.isEmpty() ) continue;
if( !b_quotes_mode && entry.endsWith( "\"" ) )
{
/* Enters quotes mode */
entry.truncate( entry.size() - 1 );
b_quotes_mode = true;
}
else if( b_quotes_mode && entry.endsWith( "\"" ) )
{
/* Finished the quotes mode */
entry.truncate( entry.size() - 1 );
b_quotes_mode = false;
}
else if( !b_quotes_mode && !entry.endsWith( "\"" ) )
{
/* we found a non-quoted standalone string */
if( index < entries.size() ||
entry.endsWith( " " ) || entry.endsWith( "\t" ) ||
entry.endsWith( "\r" ) || entry.endsWith( "\n" ) )
entry.truncate( entry.size() - 1 );
if( !entry.isEmpty() ) entries_array.append( entry );
entry.clear();
}
else
{;}
}
if( !entry.isEmpty() ) entries_array.append( entry );
return entries_array;
}
<commit_msg>Qt4 - Open Dialog: Code cosmetic.<commit_after>/*****************************************************************************
* open.cpp : Advanced open dialog
*****************************************************************************
* Copyright (C) 2006-2007 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* 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 "input_manager.hpp"
#include "dialogs/open.hpp"
#include "components/open.hpp"
#include <QTabWidget>
#include <QGridLayout>
#include <QFileDialog>
#include <QRegExp>
#include <QMenu>
OpenDialog *OpenDialog::instance = NULL;
OpenDialog::OpenDialog( QWidget *parent, intf_thread_t *_p_intf, bool modal,
int _action_flag ) : QVLCDialog( parent, _p_intf )
{
setModal( modal );
i_action_flag = _action_flag;
/* Basic Creation of the Window */
ui.setupUi( this );
setWindowTitle( qtr("Open" ) );
resize( 410, 300);
/* Tab definition and creation */
fileOpenPanel = new FileOpenPanel( ui.Tab, p_intf );
discOpenPanel = new DiscOpenPanel( ui.Tab, p_intf );
netOpenPanel = new NetOpenPanel( ui.Tab, p_intf );
captureOpenPanel = new CaptureOpenPanel( ui.Tab, p_intf );
/* Insert the tabs */
ui.Tab->insertTab( OPEN_FILE_TAB, fileOpenPanel, qtr( "&File" ) );
ui.Tab->insertTab( OPEN_DISC_TAB, discOpenPanel, qtr( "&Disc" ) );
ui.Tab->insertTab( OPEN_NETWORK_TAB, netOpenPanel, qtr( "&Network" ) );
ui.Tab->insertTab( OPEN_CAPTURE_TAB, captureOpenPanel,
qtr( "Capture &Device" ) );
/* Hide the Slave input widgets */
ui.slaveLabel->hide();
ui.slaveText->hide();
ui.slaveBrowseButton->hide();
/* Hide the advancedPanel */
if(! config_GetInt( p_intf, "qt-adv-options") )
ui.advancedFrame->hide();
else
ui.advancedCheckBox->setCheckState( Qt::Checked );
/* Buttons Creation */
QSizePolicy buttonSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum );
buttonSizePolicy.setHorizontalStretch(0);
buttonSizePolicy.setVerticalStretch(0);
/* Play Button */
playButton = new QToolButton( this );
playButton->setText( qtr( "&Play" ) );
playButton->setSizePolicy( buttonSizePolicy );
playButton->setMinimumSize( QSize(90, 0) );
playButton->setPopupMode( QToolButton::MenuButtonPopup );
playButton->setToolButtonStyle( Qt::ToolButtonTextOnly );
/* Cancel Button */
cancelButton = new QPushButton();
cancelButton->setText( qtr( "&Cancel" ) );
cancelButton->setSizePolicy( buttonSizePolicy );
/* Menu for the Play button */
QMenu * openButtonMenu = new QMenu( "Open" );
openButtonMenu->addAction( qtr("&Enqueue"), this, SLOT( enqueue() ),
QKeySequence( "Alt+E") );
openButtonMenu->addAction( qtr("&Play"), this, SLOT( play() ),
QKeySequence( "Alt+P" ) );
openButtonMenu->addAction( qtr("&Stream"), this, SLOT( stream() ) ,
QKeySequence( "Alt+S" ) );
openButtonMenu->addAction( qtr("&Convert"), this, SLOT( transcode() ) ,
QKeySequence( "Alt+C" ) );
playButton->setMenu( openButtonMenu );
ui.buttonsBox->addButton( playButton, QDialogButtonBox::AcceptRole );
ui.buttonsBox->addButton( cancelButton, QDialogButtonBox::RejectRole );
/* Force MRL update on tab change */
CONNECT( ui.Tab, currentChanged(int), this, signalCurrent());
CONNECT( fileOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( netOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( discOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( captureOpenPanel, mrlUpdated( QString ), this, updateMRL(QString) );
CONNECT( fileOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( netOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( discOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
CONNECT( captureOpenPanel, methodChanged( QString ),
this, newMethod(QString) );
/* Advanced frame Connects */
CONNECT( ui.slaveText, textChanged(QString), this, updateMRL());
CONNECT( ui.cacheSpinBox, valueChanged(int), this, updateMRL());
CONNECT( ui.startTimeSpinBox, valueChanged(int), this, updateMRL());
BUTTONACT( ui.advancedCheckBox , toggleAdvancedPanel() );
/* Buttons action */
BUTTONACT( playButton, play());
BUTTONACT( cancelButton, cancel());
/* At creation time, modify the default buttons */
if ( i_action_flag ) setMenuAction();
/* Initialize caching */
storedMethod = "";
newMethod("file-caching");
mainHeight = advHeight = 0;
}
OpenDialog::~OpenDialog()
{
}
/* Finish the dialog and decide if you open another one after */
void OpenDialog::setMenuAction()
{
switch ( i_action_flag )
{
case OPEN_AND_STREAM:
playButton->setText( qtr("&Stream") );
BUTTONACT( playButton, stream() );
break;
case OPEN_AND_SAVE:
playButton->setText( qtr("&Convert / Save") );
BUTTONACT( playButton, transcode() );
break;
case OPEN_AND_ENQUEUE:
playButton->setText( qtr("&Enqueue") );
BUTTONACT( playButton, enqueue() );
break;
case OPEN_AND_PLAY:
default:
playButton->setText( qtr("&Play") );
BUTTONACT( playButton, play() );
}
}
void OpenDialog::showTab( int i_tab=0 )
{
this->show();
ui.Tab->setCurrentIndex( i_tab );
}
void OpenDialog::signalCurrent() {
if (ui.Tab->currentWidget() != NULL)
(dynamic_cast<OpenPanel *>( ui.Tab->currentWidget() ))->updateMRL();
}
/***********
* Actions *
***********/
/* If Cancel is pressed or escaped */
void OpenDialog::cancel()
{
fileOpenPanel->clear();
this->toggleVisible();
if( isModal() ) reject();
}
/* If EnterKey is pressed */
void OpenDialog::close()
{
/* FIXME */
if ( !i_action_flag )
{
play();
}
else
{
stream();
}
}
/* Play button */
void OpenDialog::play()
{
finish( false );
}
void OpenDialog::enqueue()
{
finish( true );
}
void OpenDialog::transcode()
{
stream( true );
}
void OpenDialog::stream( bool b_transcode_only )
{
/* not finished FIXME */
/* Should go through the finish function */
THEDP->streamingDialog( mrl, b_transcode_only );
}
void OpenDialog::finish( bool b_enqueue = false )
{
this->toggleVisible();
mrl = ui.advancedLineInput->text();
if( !isModal() )
{
QStringList tempMRL = SeparateEntries( mrl );
for( size_t i = 0; i < tempMRL.size(); i++ )
{
bool b_start = !i && !b_enqueue;
input_item_t *p_input;
const char *psz_utf8 = qtu( tempMRL[i] );
p_input = input_ItemNew( p_intf, psz_utf8, NULL );
/* Insert options */
while( i + 1 < tempMRL.size() && tempMRL[i + 1].startsWith( ":" ) )
{
i++;
psz_utf8 = qtu( tempMRL[i] );
input_ItemAddOption( p_input, psz_utf8 );
}
if( b_start )
{
playlist_AddInput( THEPL, p_input,
PLAYLIST_APPEND | PLAYLIST_GO,
PLAYLIST_END, VLC_TRUE, VLC_FALSE );
}
else
{
playlist_AddInput( THEPL, p_input,
PLAYLIST_APPEND|PLAYLIST_PREPARSE,
PLAYLIST_END, VLC_TRUE, VLC_FALSE );
}
}
}
else
accept();
}
void OpenDialog::toggleAdvancedPanel()
{
//FIXME does not work under Windows
if( ui.advancedFrame->isVisible() ) {
ui.advancedFrame->hide();
#ifndef WIN32
setMinimumHeight(1);
resize( width(), mainHeight );
#endif
} else {
#ifndef WIN32
if( mainHeight == 0 )
mainHeight = height();
#endif
ui.advancedFrame->show();
#ifndef WIN32
if( advHeight == 0 ) {
advHeight = height() - mainHeight;
}
resize( width(), mainHeight + advHeight );
#endif
}
}
void OpenDialog::updateMRL() {
mrl = mainMRL;
if( ui.slaveCheckbox->isChecked() ) {
mrl += " :input-slave=" + ui.slaveText->text();
}
int i_cache = config_GetInt( p_intf, qta(storedMethod) );
if( i_cache != ui.cacheSpinBox->value() ) {
mrl += QString(" :%1=%2").arg(storedMethod).
arg(ui.cacheSpinBox->value());
}
if( ui.startTimeSpinBox->value()) {
mrl += " :start-time=" + QString("%1").
arg(ui.startTimeSpinBox->value());
}
ui.advancedLineInput->setText(mrl);
}
void OpenDialog::updateMRL(QString tempMRL)
{
mainMRL = tempMRL;
updateMRL();
}
void OpenDialog::newMethod(QString method)
{
if( method != storedMethod ) {
storedMethod = method;
int i_value = config_GetInt( p_intf, qta(storedMethod) );
ui.cacheSpinBox->setValue(i_value);
}
}
QStringList OpenDialog::SeparateEntries( QString entries )
{
bool b_quotes_mode = false;
QStringList entries_array;
QString entry;
int index = 0;
while( index < entries.size() )
{
int delim_pos = entries.indexOf( QRegExp( "\\s+|\"" ), index );
if( delim_pos < 0 ) delim_pos = entries.size() - 1;
entry += entries.mid( index, delim_pos - index + 1 );
index = delim_pos + 1;
if( entry.isEmpty() ) continue;
if( !b_quotes_mode && entry.endsWith( "\"" ) )
{
/* Enters quotes mode */
entry.truncate( entry.size() - 1 );
b_quotes_mode = true;
}
else if( b_quotes_mode && entry.endsWith( "\"" ) )
{
/* Finished the quotes mode */
entry.truncate( entry.size() - 1 );
b_quotes_mode = false;
}
else if( !b_quotes_mode && !entry.endsWith( "\"" ) )
{
/* we found a non-quoted standalone string */
if( index < entries.size() ||
entry.endsWith( " " ) || entry.endsWith( "\t" ) ||
entry.endsWith( "\r" ) || entry.endsWith( "\n" ) )
entry.truncate( entry.size() - 1 );
if( !entry.isEmpty() ) entries_array.append( entry );
entry.clear();
}
else
{;}
}
if( !entry.isEmpty() ) entries_array.append( entry );
return entries_array;
}
<|endoftext|> |
<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "method_ref.h"
#include "class.h"
#include "global_object.h"
#include "jni_test.h"
#include "local_object.h"
#include "local_string.h"
#include "method.h"
#include "method_selection.h"
#include "mock_jni_env.h"
#include "params.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "jni_dep.h"
#include "jni_helper/jni_helper.h"
#include "return.h"
namespace {
using jni::Class;
using jni::kDefaultClassLoader;
using jni::Method;
using jni::MethodSelection_t;
using jni::Overload;
using jni::Params;
using jni::Permutation;
using jni::PermutationRef;
using jni::test::JniTest;
using testing::_;
using testing::Eq;
using testing::InSequence;
using testing::StrEq;
template <const auto& class_loader_v, const auto& class_v, size_t I>
struct FirstOverloadFirstPermutation {
using IthMethodSelection =
MethodSelection_t<class_loader_v, class_v, false, I>;
using FirstOverload = Overload<IthMethodSelection, 0>;
using FirstPermutation = Permutation<IthMethodSelection, FirstOverload, 0>;
using type =
PermutationRef<IthMethodSelection, FirstOverload, FirstPermutation>;
};
template <const auto& class_loader_v, const auto& class_v, size_t I>
using MethodRefT_t =
typename FirstOverloadFirstPermutation<class_loader_v, class_v, I>::type;
TEST_F(JniTest, MethodRef_DoesntStaticCrossTalkWithTagUse) {
static constexpr Method m{"FooV", jni::Return<void>{}, Params{jint{}}};
static constexpr Class kSomeClass{"someClass", m};
const jclass clazz{reinterpret_cast<jclass>(0XAAAAA)};
const jobject object{reinterpret_cast<jobject>(0XBBBBBB)};
MethodRefT_t<kDefaultClassLoader, kSomeClass, 0>::Invoke(clazz, object, 123);
}
TEST_F(JniTest, MethodRef_CallsGetMethodCorrectlyForSingleMethod) {
static constexpr Method m1{"FooV", jni::Return<void>{}, Params<>{}};
static constexpr Class c{"SimpleClass", m1};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XABABA)};
const jobject object{reinterpret_cast<jobject>(0XAAAAAA)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XBBBBBB)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("FooV"), StrEq("()V")))
.WillOnce(testing::Return(fake_jmethod_1));
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object);
}
TEST_F(JniTest, MethodRef_ReturnWithNoParams) {
static constexpr Method m1{"FooV", jni::Return<void>{}, Params<>{}};
static constexpr Method m2{"BarI", jni::Return<jint>{}, Params<>{}};
static constexpr Method m3{"BazF", jni::Return<jfloat>{}, Params<>{}};
static constexpr Class c{"someClass", m1, m2, m3};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XABABA)};
const jobject object{reinterpret_cast<jobject>(0XAAAAAA)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XBBBBBB)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("FooV"), StrEq("()V")))
.WillOnce(testing::Return(fake_jmethod_1));
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
const jmethodID fake_jmethod_2{reinterpret_cast<jmethodID>(0XCCCCCC)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("BarI"), StrEq("()I")))
.WillOnce(testing::Return(fake_jmethod_2));
EXPECT_CALL(*env_, CallIntMethodV(object, fake_jmethod_2, _));
const jmethodID fake_jmethod_3{reinterpret_cast<jmethodID>(0XDDDDDD)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("BazF"), StrEq("()F")))
.WillOnce(testing::Return(fake_jmethod_3));
EXPECT_CALL(*env_, CallFloatMethodV(object, fake_jmethod_3, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object);
MethodRefT_t<kDefaultClassLoader, c, 1>::Invoke(clazz, object);
MethodRefT_t<kDefaultClassLoader, c, 2>::Invoke(clazz, object);
}
TEST_F(JniTest, MethodRef_SingleParam) {
constexpr Method m1{"SomeFunc1", jni::Return<void>{}, Params<jint>{}};
constexpr Method m2{"SomeFunc2", jni::Return<jint>{}, Params<jfloat>{}};
constexpr Method m3{"SomeFunc3", jni::Return<jfloat>{}, Params<jfloat>{}};
static constexpr Class c{"someClass", m1, m2, m3};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XAAAAAA)};
const jobject object{reinterpret_cast<jobject>(0XBBBBBB)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XCCCCCC)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc1"), StrEq("(I)V")))
.WillOnce(testing::Return(fake_jmethod_1));
// There is no clear way to test variable vaargs type arguments using Gmock,
// but at least we can test the correct method is called.
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
const jmethodID fake_jmethod_2{reinterpret_cast<jmethodID>(0XDDDDDD)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc2"), StrEq("(F)I")))
.WillOnce(testing::Return(fake_jmethod_2));
EXPECT_CALL(*env_, CallIntMethodV(object, fake_jmethod_2, _));
const jmethodID fake_jmethod_3{reinterpret_cast<jmethodID>(0XEEEEEE)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc3"), StrEq("(F)F")))
.WillOnce(testing::Return(fake_jmethod_3));
EXPECT_CALL(*env_, CallFloatMethodV(object, fake_jmethod_3, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object, 1);
MethodRefT_t<kDefaultClassLoader, c, 1>::Invoke(clazz, object, 1.234f);
MethodRefT_t<kDefaultClassLoader, c, 2>::Invoke(clazz, object, 5.6789f);
}
TEST_F(JniTest, MethodRef_ReturnsObjects) {
static constexpr Class c1{"Bazz"};
static constexpr Class kClass{
"com/google/ReturnsObjects",
Method{"Foo", jni::Return{c1}, Params<jint>{}},
};
const jobject local_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
// Note, class refs are not released, so Times() != 2.
EXPECT_CALL(*env_, NewObjectV).WillOnce(testing::Return(local_jobject));
jni::GlobalObject<kClass> global_object{};
jni::LocalObject<c1> new_obj{global_object("Foo", 5)};
}
TEST_F(JniTest, MethodRef_PassesObjects) {
static constexpr Class c1{"com/google/Bazz"};
static constexpr Class kClass{
"com/google/PassesObjects",
Method{"Foo", jni::Return<jint>{}, Params{c1}},
};
const jobject local_instance{reinterpret_cast<jobject>(0XAAAAAA)};
const jobject global_c1_instance{reinterpret_cast<jobject>(0XBBBBBB)};
jni::LocalObject<c1> local_object{local_instance};
jni::GlobalObject<kClass> global_object{global_c1_instance};
EXPECT_CALL(*env_,
GetMethodID(_, StrEq("Foo"), StrEq("(Lcom/google/Bazz;)I")));
global_object("Foo", local_object);
}
TEST_F(JniTest, MethodRef_PassesAndReturnsMultipleObjects) {
static constexpr Class c1{"Class1"};
static constexpr Class c2{"Class2"};
static constexpr Class c3{"Class3"};
static constexpr Class c4{"Class4"};
static constexpr Class class_under_test{
"com/google/PassesAndReturnsMultipleObjects",
Method{"Foo", jni::Return{c1}, Params{c1, c2, c3, c4}},
};
const jobject fake_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
jni::LocalObject<c1> obj1{fake_jobject};
jni::LocalObject<c2> obj2{fake_jobject};
jni::LocalObject<c3> obj3{fake_jobject};
jni::LocalObject<c4> obj4{fake_jobject};
jni::LocalObject<class_under_test> object_under_test{fake_jobject};
jni::LocalObject<c1> obj5{object_under_test("Foo", obj1, obj2, obj3, obj4)};
}
TEST_F(JniTest, MethodRef_SupportsStrings) {
static constexpr Class class_under_test{
"com/google/SupportsStrings",
Method{"Foo", jni::Return<void>{}, Params<jstring>{}},
Method{"Bar", jni::Return<void>{}, Params<jstring, jstring>{}},
Method{"Baz", jni::Return<jstring>{}, Params<>{}},
};
const jobject fake_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
jni::LocalObject<class_under_test> obj1{fake_jobject};
obj1("Foo", "This is a method.");
obj1("Bar", "This is a method.", "It takes strings");
obj1("Baz");
}
} // namespace
<commit_msg>Internal change<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "method_ref.h"
#include "class.h"
#include "global_object.h"
#include "jni_test.h"
#include "local_object.h"
#include "local_string.h"
#include "method.h"
#include "method_selection.h"
#include "mock_jni_env.h"
#include "params.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "jni_dep.h"
#include "jni_helper/jni_helper.h"
#include "return.h"
namespace {
using jni::Class;
using jni::kDefaultClassLoader;
using jni::Method;
using jni::MethodSelection_t;
using jni::Overload;
using jni::Params;
using jni::Permutation;
using jni::PermutationRef;
using jni::test::JniTest;
using testing::_;
using testing::Eq;
using testing::InSequence;
using testing::StrEq;
template <const auto& class_loader_v, const auto& class_v, size_t I>
struct FirstOverloadFirstPermutation {
using IthMethodSelection =
MethodSelection_t<class_loader_v, class_v, false, I>;
using FirstOverload = Overload<IthMethodSelection, 0>;
using FirstPermutation = Permutation<IthMethodSelection, FirstOverload, 0>;
using type =
PermutationRef<IthMethodSelection, FirstOverload, FirstPermutation>;
};
template <const auto& class_loader_v, const auto& class_v, size_t I>
using MethodRefT_t =
typename FirstOverloadFirstPermutation<class_loader_v, class_v, I>::type;
TEST_F(JniTest, MethodRef_DoesntStaticCrossTalkWithTagUse) {
static constexpr Method m{"FooV", jni::Return<void>{}, Params{jint{}}};
static constexpr Class kSomeClass{"someClass", m};
const jclass clazz{reinterpret_cast<jclass>(0XAAAAA)};
const jobject object{reinterpret_cast<jobject>(0XBBBBBB)};
MethodRefT_t<kDefaultClassLoader, kSomeClass, 0>::Invoke(clazz, object, 123);
}
TEST_F(JniTest, MethodRef_CallsGetMethodCorrectlyForSingleMethod) {
static constexpr Method m1{"FooV", jni::Return<void>{}, Params<>{}};
static constexpr Class c{"SimpleClass", m1};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XABABA)};
const jobject object{reinterpret_cast<jobject>(0XAAAAAA)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XBBBBBB)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("FooV"), StrEq("()V")))
.WillOnce(testing::Return(fake_jmethod_1));
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object);
}
TEST_F(JniTest, MethodRef_ReturnWithNoParams) {
static constexpr Method m1{"FooV", jni::Return<void>{}, Params<>{}};
static constexpr Method m2{"BarI", jni::Return<jint>{}, Params<>{}};
static constexpr Method m3{"BazF", jni::Return<jfloat>{}, Params<>{}};
static constexpr Class c{"someClass", m1, m2, m3};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XABABA)};
const jobject object{reinterpret_cast<jobject>(0XAAAAAA)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XBBBBBB)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("FooV"), StrEq("()V")))
.WillOnce(testing::Return(fake_jmethod_1));
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
const jmethodID fake_jmethod_2{reinterpret_cast<jmethodID>(0XCCCCCC)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("BarI"), StrEq("()I")))
.WillOnce(testing::Return(fake_jmethod_2));
EXPECT_CALL(*env_, CallIntMethodV(object, fake_jmethod_2, _));
const jmethodID fake_jmethod_3{reinterpret_cast<jmethodID>(0XDDDDDD)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("BazF"), StrEq("()F")))
.WillOnce(testing::Return(fake_jmethod_3));
EXPECT_CALL(*env_, CallFloatMethodV(object, fake_jmethod_3, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object);
MethodRefT_t<kDefaultClassLoader, c, 1>::Invoke(clazz, object);
MethodRefT_t<kDefaultClassLoader, c, 2>::Invoke(clazz, object);
}
TEST_F(JniTest, MethodRef_SingleParam) {
constexpr Method m1{"SomeFunc1", jni::Return<void>{}, Params<jint>{}};
constexpr Method m2{"SomeFunc2", jni::Return<jint>{}, Params<jfloat>{}};
constexpr Method m3{"SomeFunc3", jni::Return<jfloat>{}, Params<jfloat>{}};
static constexpr Class c{"someClass", m1, m2, m3};
InSequence seq;
const jclass clazz{reinterpret_cast<jclass>(0XAAAAAA)};
const jobject object{reinterpret_cast<jobject>(0XBBBBBB)};
const jmethodID fake_jmethod_1{reinterpret_cast<jmethodID>(0XCCCCCC)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc1"), StrEq("(I)V")))
.WillOnce(testing::Return(fake_jmethod_1));
// There is no clear way to test variable vaargs type arguments using Gmock,
// but at least we can test the correct method is called.
EXPECT_CALL(*env_, CallVoidMethodV(object, fake_jmethod_1, _));
const jmethodID fake_jmethod_2{reinterpret_cast<jmethodID>(0XDDDDDD)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc2"), StrEq("(F)I")))
.WillOnce(testing::Return(fake_jmethod_2));
EXPECT_CALL(*env_, CallIntMethodV(object, fake_jmethod_2, _));
const jmethodID fake_jmethod_3{reinterpret_cast<jmethodID>(0XEEEEEE)};
EXPECT_CALL(*env_, GetMethodID(Eq(clazz), StrEq("SomeFunc3"), StrEq("(F)F")))
.WillOnce(testing::Return(fake_jmethod_3));
EXPECT_CALL(*env_, CallFloatMethodV(object, fake_jmethod_3, _));
MethodRefT_t<kDefaultClassLoader, c, 0>::Invoke(clazz, object, 1);
MethodRefT_t<kDefaultClassLoader, c, 1>::Invoke(clazz, object, 1.234f);
MethodRefT_t<kDefaultClassLoader, c, 2>::Invoke(clazz, object, 5.6789f);
}
TEST_F(JniTest, MethodRef_ReturnsObjects) {
static constexpr Class c1{"Bazz"};
static constexpr Class kClass{
"com/google/ReturnsObjects",
Method{"Foo", jni::Return{c1}, Params<jint>{}},
};
const jobject local_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
// Note, class refs are not released, so Times() != 2.
EXPECT_CALL(*env_, NewObjectV).WillOnce(testing::Return(local_jobject));
jni::GlobalObject<kClass> global_object{};
jni::LocalObject<c1> new_obj{global_object("Foo", 5)};
}
TEST_F(JniTest, MethodRef_PassesObjects) {
static constexpr Class c1{"com/google/Bazz"};
static constexpr Class kClass{
"com/google/PassesObjects",
Method{"Foo", jni::Return<jint>{}, Params{c1}},
};
const jobject local_instance{reinterpret_cast<jobject>(0XAAAAAA)};
const jobject global_c1_instance{reinterpret_cast<jobject>(0XBBBBBB)};
jni::LocalObject<c1> local_object{local_instance};
jni::GlobalObject<kClass> global_object{global_c1_instance};
EXPECT_CALL(*env_,
GetMethodID(_, StrEq("Foo"), StrEq("(Lcom/google/Bazz;)I")));
global_object("Foo", local_object);
}
TEST_F(JniTest, MethodRef_PassesAndReturnsMultipleObjects) {
static constexpr Class c1{"Class1"};
static constexpr Class c2{"Class2"};
static constexpr Class c3{"Class3"};
static constexpr Class c4{"Class4"};
static constexpr Class class_under_test{
"com/google/PassesAndReturnsMultipleObjects",
Method{"Foo", jni::Return{c1}, Params{c1, c2, c3, c4}},
};
const jobject fake_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
jni::LocalObject<c1> obj1{fake_jobject};
jni::LocalObject<c2> obj2{fake_jobject};
jni::LocalObject<c3> obj3{fake_jobject};
jni::LocalObject<c4> obj4{fake_jobject};
jni::LocalObject<class_under_test> object_under_test{fake_jobject};
jni::LocalObject<c1> obj5{object_under_test("Foo", obj1, obj2, obj3, obj4)};
}
TEST_F(JniTest, MethodRef_SupportsForwardDefines) {
static constexpr Class kClass1{
"kClass1",
Method{"m1", jni::Return<void>{}, Params{Class{"kClass1"}}},
Method{"m2", jni::Return<void>{}, Params{Class{"kClass2"}}},
Method{"m3", jni::Return{Class{"kClass1"}}, Params{}},
Method{"m4", jni::Return{Class{"kClass2"}}, Params{}},
};
static constexpr Class kClass2{
"kClass2",
Method{"m1", jni::Return<void>{}, Params{Class{"kClass1"}}},
Method{"m2", jni::Return<void>{}, Params{Class{"kClass2"}}},
Method{"m3", jni::Return{Class{"kClass1"}}, Params{}},
Method{"m4", jni::Return{Class{"kClass2"}}, Params{}},
};
const jobject fake_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
jni::LocalObject<kClass1> c1_obj1{fake_jobject};
jni::LocalObject<kClass1> c1_obj2{fake_jobject};
jni::LocalObject<kClass2> c2_obj1{fake_jobject};
jni::LocalObject<kClass2> c2_obj2{fake_jobject};
c1_obj1("m1", c1_obj1);
c1_obj1("m2", c2_obj1);
c1_obj1("m1", c1_obj1("m3"));
c1_obj1("m2", c1_obj1("m4"));
c2_obj1("m1", c1_obj1);
c2_obj1("m2", c2_obj2);
c2_obj1("m2", std::move(std::move(c2_obj2)));
c1_obj1("m2", std::move(c2_obj1));
// c2_obj1("m1", c1_obj1); // illegal! triggers warnings (post move read).
// c2_obj1("m2", c2_obj2); // illegal! triggers warnings (post move read).
// c2_obj1("m2", std::move(c2_obj2)); // illegal! triggers warnings (post
// move read).
}
TEST_F(JniTest, MethodRef_SupportsStrings) {
static constexpr Class class_under_test{
"com/google/SupportsStrings",
Method{"Foo", jni::Return<void>{}, Params<jstring>{}},
Method{"Bar", jni::Return<void>{}, Params<jstring, jstring>{}},
Method{"Baz", jni::Return<jstring>{}, Params<>{}},
};
const jobject fake_jobject{reinterpret_cast<jobject>(0XAAAAAA)};
jni::LocalObject<class_under_test> obj1{fake_jobject};
obj1("Foo", "This is a method.");
obj1("Bar", "This is a method.", "It takes strings");
obj1("Baz");
}
} // namespace
<|endoftext|> |
<commit_before>// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "popup.h"
#include "TrayMenu.h"
#include "TrayMenuDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define UM_TRAYNOTIFY (WM_USER + 1)
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuDlg dialog
CTrayMenuDlg::CTrayMenuDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTrayMenuDlg::IDD, pParent)
{
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
// Initialize NOTIFYICONDATA
memset(&m_nid, 0 , sizeof(m_nid));
m_nid.cbSize = sizeof(m_nid);
m_nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
}
CTrayMenuDlg::~CTrayMenuDlg ()
{
m_nid.hIcon = NULL;
Shell_NotifyIcon (NIM_DELETE, &m_nid);
}
void CTrayMenuDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTrayMenuDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_APP_EXIT, OnAppExit)
ON_COMMAND(ID_APP_OPEN, OnAppOpen)
ON_COMMAND(ID_ITEM1, OnItem1)
ON_COMMAND(ID_ITEM2, OnItem2)
ON_COMMAND(ID_ITEM3, OnItem3)
ON_COMMAND(ID_ITEM4, OnItem4)
ON_UPDATE_COMMAND_UI(ID_ITEM4, OnUpdateItem4)
ON_MESSAGE(UM_TRAYNOTIFY, OnTrayNotify)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuDlg message handlers
BOOL CTrayMenuDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CString strMainToolbarTitle;
strMainToolbarTitle.LoadString (AFX_IDS_APP_TITLE);
::SetWindowText(m_hWnd, strMainToolbarTitle);
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bValidString;
CString strAboutMenu;
bValidString = strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Set tray notification window:
m_nid.hWnd = GetSafeHwnd ();
m_nid.uCallbackMessage = UM_TRAYNOTIFY;
// Set tray icon and tooltip:
m_nid.hIcon = m_hIcon;
CString strToolTip = _T("MFCTrayDemo");
_tcsncpy_s (m_nid.szTip, strToolTip, strToolTip.GetLength ());
Shell_NotifyIcon (NIM_ADD, &m_nid);
CMFCToolBar::AddToolBarForImageCollection (IDR_MENUIMAGES);
return TRUE; // return TRUE unless you set the focus to a control
}
void CTrayMenuDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTrayMenuDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTrayMenuDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
LRESULT CTrayMenuDlg::OnTrayNotify(WPARAM /*wp*/, LPARAM lp)
{
UINT uiMsg = (UINT) lp;
switch (uiMsg)
{
case WM_RBUTTONUP:
OnTrayContextMenu ();
return 1;
case WM_LBUTTONDBLCLK:
ShowWindow (SW_SHOWNORMAL);
return 1;
}
return 0;
}
void CTrayMenuDlg::OnTrayContextMenu ()
{
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu enter\n"));
CPoint point;
point.x = point.y = 0;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu GetCursorPos\n"));
BOOL res = ::GetCursorPos (&point);
if ( !res )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu build menu\n"));
CMenu menu;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu load menu\n"));
res = menu.LoadMenu (IDR_MENU1);
if ( !res )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu SetForceShadow\n"));
CMFCPopupMenu::SetForceShadow (TRUE);
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu GetSubMenu\n"));
CMenu *tmpMenu = menu.GetSubMenu (0);
if ( tmpMenu == NULL )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu Detach\n"));
HMENU hMenu = tmpMenu->Detach ();
if ( hMenu == NULL )
return;
CMFCPopupMenu* pMenu = theApp.GetContextMenuManager()->ShowPopupMenu(hMenu, point.x, point.y, this, TRUE);
if ( pMenu == NULL )
return;
pMenu->SetForegroundWindow ();
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu exit\n"));
}
void CTrayMenuDlg::OnAppAbout()
{
CRect rectPopup(GetSystemMetrics(SM_CXSCREEN)-200,
GetSystemMetrics(SM_CYSCREEN)-150,
GetSystemMetrics(SM_CXSCREEN)-50,
GetSystemMetrics(SM_CYSCREEN)-50);
CPopupWnd* pPopup = new CPopupWnd();
pPopup->Create(rectPopup);
}
void CTrayMenuDlg::OnAppExit()
{
PostMessage (WM_CLOSE);
}
void CTrayMenuDlg::OnAppOpen()
{
ShowWindow (SW_SHOWNORMAL);
}
void CTrayMenuDlg::OnItem1()
{
::MessageBox (NULL, _T("Item 1"), _T("TrayMenu"), MB_OK);
}
void CTrayMenuDlg::OnItem2()
{
::MessageBox (NULL, _T("Item 2"), _T("TrayMenu"), MB_OK);
}
void CTrayMenuDlg::OnItem3()
{
::MessageBox (NULL, _T("Item 3"), _T("TrayMenu"), MB_OK);
}
static BOOL bIsItem4Checked = TRUE;
void CTrayMenuDlg::OnItem4()
{
bIsItem4Checked = !bIsItem4Checked;
}
void CTrayMenuDlg::OnUpdateItem4(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck (bIsItem4Checked);
}
<commit_msg>TrayMenu: additional fixes for icon menu<commit_after>// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "popup.h"
#include "TrayMenu.h"
#include "TrayMenuDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define UM_TRAYNOTIFY (WM_USER + 1)
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuDlg dialog
CTrayMenuDlg::CTrayMenuDlg(CWnd* pParent /*=NULL*/)
: CDialog(CTrayMenuDlg::IDD, pParent)
{
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
// Initialize NOTIFYICONDATA
memset(&m_nid, 0 , sizeof(m_nid));
m_nid.cbSize = sizeof(m_nid);
m_nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
}
CTrayMenuDlg::~CTrayMenuDlg ()
{
m_nid.hIcon = NULL;
Shell_NotifyIcon (NIM_DELETE, &m_nid);
}
void CTrayMenuDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTrayMenuDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_APP_EXIT, OnAppExit)
ON_COMMAND(ID_APP_OPEN, OnAppOpen)
ON_COMMAND(ID_ITEM1, OnItem1)
ON_COMMAND(ID_ITEM2, OnItem2)
ON_COMMAND(ID_ITEM3, OnItem3)
ON_COMMAND(ID_ITEM4, OnItem4)
ON_UPDATE_COMMAND_UI(ID_ITEM4, OnUpdateItem4)
ON_MESSAGE(UM_TRAYNOTIFY, OnTrayNotify)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuDlg message handlers
BOOL CTrayMenuDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CString strMainToolbarTitle;
strMainToolbarTitle.LoadString (AFX_IDS_APP_TITLE);
::SetWindowText(m_hWnd, strMainToolbarTitle);
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bValidString;
CString strAboutMenu;
bValidString = strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Set tray notification window:
m_nid.hWnd = GetSafeHwnd ();
m_nid.uCallbackMessage = UM_TRAYNOTIFY;
// Set tray icon and tooltip:
m_nid.hIcon = m_hIcon;
CString strToolTip = _T("MFCTrayDemo");
_tcsncpy_s (m_nid.szTip, strToolTip, strToolTip.GetLength ());
Shell_NotifyIcon (NIM_ADD, &m_nid);
CMFCToolBar::AddToolBarForImageCollection (IDR_MENUIMAGES);
return TRUE; // return TRUE unless you set the focus to a control
}
void CTrayMenuDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTrayMenuDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTrayMenuDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
LRESULT CTrayMenuDlg::OnTrayNotify(WPARAM /*wp*/, LPARAM lp)
{
UINT uiMsg = (UINT) lp;
switch (uiMsg)
{
case WM_RBUTTONUP:
OnTrayContextMenu ();
return 1;
case WM_LBUTTONDBLCLK:
ShowWindow (SW_SHOWNORMAL);
return 1;
}
return 0;
}
void CTrayMenuDlg::OnTrayContextMenu ()
{
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu enter\n"));
CPoint point;
point.x = point.y = 0;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu GetCursorPos\n"));
BOOL res = ::GetCursorPos (&point);
if ( !res )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu build menu\n"));
CMenu menu;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu load menu\n"));
res = menu.LoadMenu (IDR_MENU1);
if ( !res )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu SetForceShadow\n"));
CMFCPopupMenu::SetForceShadow (TRUE);
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu GetSubMenu\n"));
CMenu *tmpMenu = menu.GetSubMenu (0);
if ( tmpMenu == NULL )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu Detach\n"));
HMENU hMenu = tmpMenu->Detach ();
if ( hMenu == NULL )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu GetContextMenuManager\n"));
auto ctxMgr = theApp.GetContextMenuManager();
if ( ctxMgr == NULL )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu ShowPopupMenu\n"));
CMFCPopupMenu* pMenu = ctxMgr->ShowPopupMenu(hMenu, point.x, point.y, this, TRUE);
if ( pMenu == NULL )
return;
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu SetForegroundWindow\n"));
pMenu->SetForegroundWindow ();
OutputDebugStringW(_T("CTrayMenuDlg::OnTrayContextMenu exit\n"));
}
void CTrayMenuDlg::OnAppAbout()
{
CRect rectPopup(GetSystemMetrics(SM_CXSCREEN)-200,
GetSystemMetrics(SM_CYSCREEN)-150,
GetSystemMetrics(SM_CXSCREEN)-50,
GetSystemMetrics(SM_CYSCREEN)-50);
CPopupWnd* pPopup = new CPopupWnd();
pPopup->Create(rectPopup);
}
void CTrayMenuDlg::OnAppExit()
{
PostMessage (WM_CLOSE);
}
void CTrayMenuDlg::OnAppOpen()
{
ShowWindow (SW_SHOWNORMAL);
}
void CTrayMenuDlg::OnItem1()
{
::MessageBox (NULL, _T("Item 1"), _T("TrayMenu"), MB_OK);
}
void CTrayMenuDlg::OnItem2()
{
::MessageBox (NULL, _T("Item 2"), _T("TrayMenu"), MB_OK);
}
void CTrayMenuDlg::OnItem3()
{
::MessageBox (NULL, _T("Item 3"), _T("TrayMenu"), MB_OK);
}
static BOOL bIsItem4Checked = TRUE;
void CTrayMenuDlg::OnItem4()
{
bIsItem4Checked = !bIsItem4Checked;
}
void CTrayMenuDlg::OnUpdateItem4(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck (bIsItem4Checked);
}
<|endoftext|> |
<commit_before>#include "engine.h"
Log logger;
Engine::Engine()
{
rooms_mgr = new RoomsManager();
events_mgr = new EventsManager();
gui_mgr = new GuiManager();
setState(INITIALIZING);
inventory = new GuiScrolledBar("inventory", "", "", GuiRect(0.08, 0, 0.84, 0.107),
GuiRect(0.08, 0, 0.08, 0.107), GuiRect(0, 0, 0.08, 0.107),
"./data/right_btn.png", "./data/left_btn.png", GuiList::H_GUILIST);
dialog_list = new GuiScrolledBar("dialog", "", "", GuiRect(0.08, 0.89, 0.84, 0.107),
GuiRect(0.08, 0.89, 0.65, 0.05), GuiRect(0, 0, 0.08, 0.107),
"./data/right_btn.png", "./data/left_btn.png", GuiList::V_GUILIST);
gui_mgr->addGuiObj(inventory);
gui_mgr->addGuiObj(dialog_list);
dialog_list->visible = false;
// Python stuff
apiInit(this);
EngineMod eng_mod;
RoomMod room_mod;
vm.import(eng_mod);
vm.import(room_mod);
}
Engine::~Engine()
{
logger.write("QUITTING ENGINE", Log::ERROR);
for (std::map<string, Dialog *>::iterator i = dialogs.begin();
i != dialogs.end(); ++i)
{
logger.write("Garbage collector: " + i->second->id, Log::NOTE);
delete i->second;
}
dialogs.clear();
delete rooms_mgr;
delete events_mgr;
delete gui_mgr;
}
Log *Engine::getLogger()
{
return &logger;
}
std::pair<float, float> Engine::absToRelCoord(const int x, const int y)
{
return std::make_pair(static_cast<float> (x) / rooms_mgr->width(), static_cast<float> (y) / rooms_mgr->height());
}
std::pair<int, int> Engine::relToAbsCoord(const float x, const float y)
{
return std::make_pair(x * rooms_mgr->width(), y * rooms_mgr->height());
}
void Engine::relToAbsRect(GuiRect &rect)
{
rect.x *= rooms_mgr->width();
rect.w *= rooms_mgr->width();
rect.y *= rooms_mgr->height();
rect.h *= rooms_mgr->height();
}
void Engine::click(const float x, const float y)
{
switch (state())
{
case GAME:
{
if (gui_mgr->click(x, y) == "")
clickArea(x, y);
break;
}
case DIALOG:
{
string choice = gui_mgr->click(x, y);
if (choice != "")
{
clickDialog(choice);
updateDialog();
}
break;
}
default:
gui_mgr->click(x, y);
}
}
void Engine::clickArea(const float x, const float y)
{
logger.write("Mouse click received", Log::NOTE);
Event *event = events_mgr->event(rooms_mgr->eventAt(x, y));
if (event == 0)
return;
logger.write("Event: " + event->id, Log::NOTE);
if (rooms_mgr->checkItemPlace(event->itemReqs()) &&
events_mgr->checkVarReqs(event->varReqs()))
execActions(events_mgr->actionsForEvent(event->id));
else
logger.write("Requirements are not satisfied", Log::NOTE);
}
void Engine::clickDialog(const string link)
{
logger.write("Dialog choice received: " + link, Log::NOTE);
std::map<string, string> choices = getDialogChoices();
string id_step = choices[link];
if (id_step == "-1")
{
setState(GAME);
return;
}
execActions(dialog->jump(id_step));
}
Engine::State Engine::state() const
{
return _state;
}
void Engine::setState(const Engine::State state_name)
{
_state = state_name;
}
void Engine::saveGame(const string filename)
{
logger.write("Saving to file: " + filename, Log::NOTE);
RoomsReader reader;
reader.loadEmptyDoc();
RRNode *node = reader.getCrawler();
node->gotoElement("world");
node->setAttr("version", floatToStr(RoomsReader::VERSION));
node->setAttr("current_room", rooms_mgr->currentRoom()->id);
node->appendElement("vars");
std::map<string, int> vars = events_mgr->getVars();
for (std::map<string, int>::iterator i = vars.begin();
i != vars.end(); ++i)
{
node->appendElement("var");
node->setAttr("id", i->first);
node->setAttr("value", floatToStr(i->second));
node->gotoParent();
}
node->gotoElement("world");
node->appendElement("items");
std::map<string, Item *> items = rooms_mgr->getItems();
for (std::map<string, Item *>::iterator i = items.begin();
i != items.end(); ++i)
{
node->appendElement("item");
node->setAttr("id", i->first);
node->setAttr("room", i->second->parent());
node->gotoParent();
}
reader.saveDoc(filename);
}
void Engine::loadGame(const string filename)
{
logger.write("Loading file: " + filename, Log::NOTE);
RoomsReader reader;
reader.loadFromFile(filename);
RRNode *node = reader.getCrawler();
for (node->gotoElement("items")->gotoChild("item"); !node->isNull(); node->gotoNext())
rooms_mgr->moveItem(node->attrStr("id"), node->attrStr("room"));
node->gotoRoot();
for (node->gotoElement("vars")->gotoChild("var"); !node->isNull(); node->gotoNext())
events_mgr->setVar(node->attrStr("id"), node->attrInt("value"));
node->gotoRoot();
apiRoomGoto(node->gotoElement("world")->attrStr("current_room"));
}
bool Engine::loadWorldFromFile(const string filename)
{
logger.write("Loading world from: " + filename, Log::NOTE);
std::ifstream xml(filename.c_str(), std::ios::binary);
if (!xml.good()) return false;
xml.seekg(0, std::ios::end);
long length = xml.tellg();
if (length == 0) return false;
char *buffer = new char [length];
xml.seekg(0, std::ios::beg);
xml.read(buffer, length);
bool res = loadWorldFromStr(buffer);
xml.close();
delete [] buffer;
return res;
}
bool Engine::loadWorldFromStr(const string content)
{
RoomsReader reader;
if (!reader.loadFromStr(content) || !reader.parse())
{
logger.write("ERROR: wrong xml document!", Log::ERROR);
return false;
}
RRNode *node = reader.getCrawler();
node->gotoElement("world");
string start_room = node->attrStr("start");
//Load World attributes
logger.write(node->attrStr("name"), Log::NOTE);
rooms_mgr->setRoomSize(node->attrInt("width"), node->attrInt("height"));
rooms_mgr->setWorldName(node->attrStr("name"));
//Loading from xml
for (node->gotoElement("images")->gotoChild("img"); !node->isNull(); node->gotoNext())
images.push_back(node->attrStr("file"));
node->gotoRoot();
for (node->gotoElement("events")->gotoChild("event"); !node->isNull(); node->gotoNext())
events_mgr->addEvent(node->fetchEvent());
node->gotoRoot();
for (node->gotoElement("rooms")->gotoChild("room"); !node->isNull(); node->gotoNext())
rooms_mgr->addRoom(node->fetchRoom());
node->gotoRoot();
for (node->gotoElement("items")->gotoChild("item"); !node->isNull(); node->gotoNext())
rooms_mgr->addItem(node->fetchItem());
node->isNull();
node->gotoRoot();
for (node->gotoElement("vars")->gotoChild("var"); !node->isNull(); node->gotoNext())
events_mgr->setVar(node->attrStr("id"), node->attrInt("value"));
node->gotoRoot();
for (node->gotoElement("dialogs")->gotoChild("dialog"); !node->isNull(); node->gotoNext())
dialogs[node->attrStr("id")] = node->fetchDialog();
node->gotoRoot();
apiRoomGoto(start_room);
setState(GAME);
return true;
}
std::vector<string> Engine::getImgNames() const
{
return images;
}
std::vector<Item *> Engine::getInventory() const
{
return rooms_mgr->room(ROOM_INV)->items();
}
RoomsManager *Engine::getRoomsManager() const
{
return rooms_mgr;
}
EventsManager *Engine::getEventsManager() const
{
return events_mgr;
}
GuiManager *Engine::getGuiManager() const
{
return gui_mgr;
}
string Engine::getDialogText()
{
return dialog->text();
}
std::map<string, string> Engine::getDialogChoices()
{
std::map<string, string> choices;
std::vector< std::pair<string, string> > links = dialog->links();
for (std::vector< std::pair<string, string> >::iterator i = links.begin();
i != links.end(); ++i)
{
DialogStep *step = dialog->step(i->first);
if (step == 0) //its an end-of-dialog link
choices[i->second] = i->first;
else if (rooms_mgr->checkItemPlace(step->event->itemReqs()) &&
events_mgr->checkVarReqs(step->event->varReqs()))
choices[i->second] = i->first;
}
return choices;
}
std::vector<string> Engine::getSFX()
{
std::vector<string> sfx_ = sfx;
sfx.clear();
return sfx_;
}
void Engine::execActions(std::vector <Action *> actions)
{
std::vector <Action *>::iterator i;
for (i = actions.begin(); i != actions.end(); ++i)
{
//TODO: think about improving this loop
Action act = *(*i);
logger.write("Exec action: " + act.id, Log::NOTE);
if (act.id == "ROOM_GOTO")
{
apiRoomGoto(act.popStrParam());
}
else if (act.id == "VAR_SET")
{
int var_value = act.popIntParam();
string var_name = act.popStrParam();
apiVarSet(var_name, var_value);
}
else if (act.id == "ITEM_MOVE")
{
string item_dest = act.popStrParam();
string item_id = act.popStrParam();
apiItemMove(item_id, item_dest);
}
else if (act.id == "DIALOG_START")
{
string diag_id = act.popStrParam();
apiDialogStart(diag_id);
}
else if (act.id == "SFX_PLAY")
{
string sfx_id = act.popStrParam();
apiSFXPlay(sfx_id);
}
else if (act.id == "SCRIPT")
{
string sfx_id = act.popStrParam();
apiExecScript(sfx_id);
}
}
}
void Engine::updateDialog()
{
dialog_list->visible = false;
dialog_list->clear();
if (state() == DIALOG)
{
dialog_list->setCaption(getDialogText());
std::map<string, string> choices = getDialogChoices();
for (std::map<string, string>::iterator i = choices.begin();
i != choices.end(); ++i)
{
dialog_list->addButton(i->first, i->first, "");
logger.write(i->first, Log::NOTE);
}
dialog_list->visible = true;
}
}
bool Engine::update()
{
if (state() == TRANSITION)
{
if (!transition.update())
setState(GAME);
return true;
}
return false;
}
GuiDataVect Engine::flash(Room *room, int alpha)
{
// Background visible data
GuiDataVect visible_data;
GuiData bg;
bg.alpha = alpha;
bg.image = room->bg();
bg.text = "";
bg.rect = GuiRect(0, 0, 1.0, 1.0);
visible_data.push_back(bg);
// Items visible data
std::vector <Item *> items = room->items();
for (std::vector<Item *>::iterator i = items.begin();
i != items.end(); ++i)
{
GuiData item;
item.alpha = alpha;
item.text = "";
item.image = (*i)->image();
item.rect = GuiRect((*i)->x(), (*i)->y(), (*i)->w(), (*i)->h());
visible_data.push_back(item);
}
return visible_data;
}
GuiDataVect Engine::getVisibleData()
{
GuiDataVect visible_data;
GuiDataVect gui_data = gui_mgr->getVisibleData();
// Background visible data with transition stuff
if (state() != TRANSITION)
{
GuiDataVect room_data = flash(rooms_mgr->currentRoom());
visible_data.insert(visible_data.end(), room_data.begin(), room_data.end());
}
else
{
GuiDataVect room_data1 = flash(transition.start, transition.alpha_room_start);
GuiDataVect room_data2 = flash(transition.end, transition.alpha_room_end);
visible_data.insert(visible_data.end(), room_data1.begin(), room_data1.end());
visible_data.insert(visible_data.end(), room_data2.begin(), room_data2.end());
}
// Gui visible data
visible_data.insert(visible_data.end(), gui_data.begin(), gui_data.end());
return visible_data;
}
void Engine::apiRoomGoto(const string id)
{
logger.write("ROOM_GOTO: " + id, Log::NOTE);
transition.index = 0;
transition.steps = 25;
transition.start = rooms_mgr->currentRoom();
transition.end = rooms_mgr->room(id);
transition.update();
rooms_mgr->setCurrentRoom(id);
setState(TRANSITION);
}
void Engine::apiVarSet(const string id, const int value)
{
logger.write("VAR_SET: " + id, Log::NOTE);
events_mgr->setVar(id, value);
}
void Engine::apiItemMove(const string id, const string dest)
{
logger.write("ITEM_MOVE: " + id + ", dest: " + dest, Log::NOTE);
Item * item = rooms_mgr->item(id);
string source = item->parent();
rooms_mgr->moveItem(id, dest);
if (source == "!INVENTORY")
inventory->remButton(id);
if (dest == "!INVENTORY")
inventory->addButton(id, "", item->image());
}
void Engine::apiDialogStart(const string id)
{
logger.write("DIALOG_START: " + id, Log::NOTE);
dialog = dialogs[id];
dialog->reset();
setState(DIALOG);
updateDialog();
execActions(dialog->actions());
}
void Engine::apiSFXPlay(const string id)
{
sfx.push_back(id);
}
void Engine::apiExecScript(const string id)
{
vm.execute(id);
}
<commit_msg>Shorten transition time<commit_after>#include "engine.h"
Log logger;
Engine::Engine()
{
rooms_mgr = new RoomsManager();
events_mgr = new EventsManager();
gui_mgr = new GuiManager();
setState(INITIALIZING);
inventory = new GuiScrolledBar("inventory", "", "", GuiRect(0.08, 0, 0.84, 0.107),
GuiRect(0.08, 0, 0.08, 0.107), GuiRect(0, 0, 0.08, 0.107),
"./data/right_btn.png", "./data/left_btn.png", GuiList::H_GUILIST);
dialog_list = new GuiScrolledBar("dialog", "", "", GuiRect(0.08, 0.89, 0.84, 0.107),
GuiRect(0.08, 0.89, 0.65, 0.05), GuiRect(0, 0, 0.08, 0.107),
"./data/right_btn.png", "./data/left_btn.png", GuiList::V_GUILIST);
gui_mgr->addGuiObj(inventory);
gui_mgr->addGuiObj(dialog_list);
dialog_list->visible = false;
// Python stuff
apiInit(this);
EngineMod eng_mod;
RoomMod room_mod;
vm.import(eng_mod);
vm.import(room_mod);
}
Engine::~Engine()
{
logger.write("QUITTING ENGINE", Log::ERROR);
for (std::map<string, Dialog *>::iterator i = dialogs.begin();
i != dialogs.end(); ++i)
{
logger.write("Garbage collector: " + i->second->id, Log::NOTE);
delete i->second;
}
dialogs.clear();
delete rooms_mgr;
delete events_mgr;
delete gui_mgr;
}
Log *Engine::getLogger()
{
return &logger;
}
std::pair<float, float> Engine::absToRelCoord(const int x, const int y)
{
return std::make_pair(static_cast<float> (x) / rooms_mgr->width(), static_cast<float> (y) / rooms_mgr->height());
}
std::pair<int, int> Engine::relToAbsCoord(const float x, const float y)
{
return std::make_pair(x * rooms_mgr->width(), y * rooms_mgr->height());
}
void Engine::relToAbsRect(GuiRect &rect)
{
rect.x *= rooms_mgr->width();
rect.w *= rooms_mgr->width();
rect.y *= rooms_mgr->height();
rect.h *= rooms_mgr->height();
}
void Engine::click(const float x, const float y)
{
switch (state())
{
case GAME:
{
if (gui_mgr->click(x, y) == "")
clickArea(x, y);
break;
}
case DIALOG:
{
string choice = gui_mgr->click(x, y);
if (choice != "")
{
clickDialog(choice);
updateDialog();
}
break;
}
default:
gui_mgr->click(x, y);
}
}
void Engine::clickArea(const float x, const float y)
{
logger.write("Mouse click received", Log::NOTE);
Event *event = events_mgr->event(rooms_mgr->eventAt(x, y));
if (event == 0)
return;
logger.write("Event: " + event->id, Log::NOTE);
if (rooms_mgr->checkItemPlace(event->itemReqs()) &&
events_mgr->checkVarReqs(event->varReqs()))
execActions(events_mgr->actionsForEvent(event->id));
else
logger.write("Requirements are not satisfied", Log::NOTE);
}
void Engine::clickDialog(const string link)
{
logger.write("Dialog choice received: " + link, Log::NOTE);
std::map<string, string> choices = getDialogChoices();
string id_step = choices[link];
if (id_step == "-1")
{
setState(GAME);
return;
}
execActions(dialog->jump(id_step));
}
Engine::State Engine::state() const
{
return _state;
}
void Engine::setState(const Engine::State state_name)
{
_state = state_name;
}
void Engine::saveGame(const string filename)
{
logger.write("Saving to file: " + filename, Log::NOTE);
RoomsReader reader;
reader.loadEmptyDoc();
RRNode *node = reader.getCrawler();
node->gotoElement("world");
node->setAttr("version", floatToStr(RoomsReader::VERSION));
node->setAttr("current_room", rooms_mgr->currentRoom()->id);
node->appendElement("vars");
std::map<string, int> vars = events_mgr->getVars();
for (std::map<string, int>::iterator i = vars.begin();
i != vars.end(); ++i)
{
node->appendElement("var");
node->setAttr("id", i->first);
node->setAttr("value", floatToStr(i->second));
node->gotoParent();
}
node->gotoElement("world");
node->appendElement("items");
std::map<string, Item *> items = rooms_mgr->getItems();
for (std::map<string, Item *>::iterator i = items.begin();
i != items.end(); ++i)
{
node->appendElement("item");
node->setAttr("id", i->first);
node->setAttr("room", i->second->parent());
node->gotoParent();
}
reader.saveDoc(filename);
}
void Engine::loadGame(const string filename)
{
logger.write("Loading file: " + filename, Log::NOTE);
RoomsReader reader;
reader.loadFromFile(filename);
RRNode *node = reader.getCrawler();
for (node->gotoElement("items")->gotoChild("item"); !node->isNull(); node->gotoNext())
rooms_mgr->moveItem(node->attrStr("id"), node->attrStr("room"));
node->gotoRoot();
for (node->gotoElement("vars")->gotoChild("var"); !node->isNull(); node->gotoNext())
events_mgr->setVar(node->attrStr("id"), node->attrInt("value"));
node->gotoRoot();
apiRoomGoto(node->gotoElement("world")->attrStr("current_room"));
}
bool Engine::loadWorldFromFile(const string filename)
{
logger.write("Loading world from: " + filename, Log::NOTE);
std::ifstream xml(filename.c_str(), std::ios::binary);
if (!xml.good()) return false;
xml.seekg(0, std::ios::end);
long length = xml.tellg();
if (length == 0) return false;
char *buffer = new char [length];
xml.seekg(0, std::ios::beg);
xml.read(buffer, length);
bool res = loadWorldFromStr(buffer);
xml.close();
delete [] buffer;
return res;
}
bool Engine::loadWorldFromStr(const string content)
{
RoomsReader reader;
if (!reader.loadFromStr(content) || !reader.parse())
{
logger.write("ERROR: wrong xml document!", Log::ERROR);
return false;
}
RRNode *node = reader.getCrawler();
node->gotoElement("world");
string start_room = node->attrStr("start");
//Load World attributes
logger.write(node->attrStr("name"), Log::NOTE);
rooms_mgr->setRoomSize(node->attrInt("width"), node->attrInt("height"));
rooms_mgr->setWorldName(node->attrStr("name"));
//Loading from xml
for (node->gotoElement("images")->gotoChild("img"); !node->isNull(); node->gotoNext())
images.push_back(node->attrStr("file"));
node->gotoRoot();
for (node->gotoElement("events")->gotoChild("event"); !node->isNull(); node->gotoNext())
events_mgr->addEvent(node->fetchEvent());
node->gotoRoot();
for (node->gotoElement("rooms")->gotoChild("room"); !node->isNull(); node->gotoNext())
rooms_mgr->addRoom(node->fetchRoom());
node->gotoRoot();
for (node->gotoElement("items")->gotoChild("item"); !node->isNull(); node->gotoNext())
rooms_mgr->addItem(node->fetchItem());
node->isNull();
node->gotoRoot();
for (node->gotoElement("vars")->gotoChild("var"); !node->isNull(); node->gotoNext())
events_mgr->setVar(node->attrStr("id"), node->attrInt("value"));
node->gotoRoot();
for (node->gotoElement("dialogs")->gotoChild("dialog"); !node->isNull(); node->gotoNext())
dialogs[node->attrStr("id")] = node->fetchDialog();
node->gotoRoot();
apiRoomGoto(start_room);
setState(GAME);
return true;
}
std::vector<string> Engine::getImgNames() const
{
return images;
}
std::vector<Item *> Engine::getInventory() const
{
return rooms_mgr->room(ROOM_INV)->items();
}
RoomsManager *Engine::getRoomsManager() const
{
return rooms_mgr;
}
EventsManager *Engine::getEventsManager() const
{
return events_mgr;
}
GuiManager *Engine::getGuiManager() const
{
return gui_mgr;
}
string Engine::getDialogText()
{
return dialog->text();
}
std::map<string, string> Engine::getDialogChoices()
{
std::map<string, string> choices;
std::vector< std::pair<string, string> > links = dialog->links();
for (std::vector< std::pair<string, string> >::iterator i = links.begin();
i != links.end(); ++i)
{
DialogStep *step = dialog->step(i->first);
if (step == 0) //its an end-of-dialog link
choices[i->second] = i->first;
else if (rooms_mgr->checkItemPlace(step->event->itemReqs()) &&
events_mgr->checkVarReqs(step->event->varReqs()))
choices[i->second] = i->first;
}
return choices;
}
std::vector<string> Engine::getSFX()
{
std::vector<string> sfx_ = sfx;
sfx.clear();
return sfx_;
}
void Engine::execActions(std::vector <Action *> actions)
{
std::vector <Action *>::iterator i;
for (i = actions.begin(); i != actions.end(); ++i)
{
//TODO: think about improving this loop
Action act = *(*i);
logger.write("Exec action: " + act.id, Log::NOTE);
if (act.id == "ROOM_GOTO")
{
apiRoomGoto(act.popStrParam());
}
else if (act.id == "VAR_SET")
{
int var_value = act.popIntParam();
string var_name = act.popStrParam();
apiVarSet(var_name, var_value);
}
else if (act.id == "ITEM_MOVE")
{
string item_dest = act.popStrParam();
string item_id = act.popStrParam();
apiItemMove(item_id, item_dest);
}
else if (act.id == "DIALOG_START")
{
string diag_id = act.popStrParam();
apiDialogStart(diag_id);
}
else if (act.id == "SFX_PLAY")
{
string sfx_id = act.popStrParam();
apiSFXPlay(sfx_id);
}
else if (act.id == "SCRIPT")
{
string sfx_id = act.popStrParam();
apiExecScript(sfx_id);
}
}
}
void Engine::updateDialog()
{
dialog_list->visible = false;
dialog_list->clear();
if (state() == DIALOG)
{
dialog_list->setCaption(getDialogText());
std::map<string, string> choices = getDialogChoices();
for (std::map<string, string>::iterator i = choices.begin();
i != choices.end(); ++i)
{
dialog_list->addButton(i->first, i->first, "");
logger.write(i->first, Log::NOTE);
}
dialog_list->visible = true;
}
}
bool Engine::update()
{
if (state() == TRANSITION)
{
if (!transition.update())
setState(GAME);
return true;
}
return false;
}
GuiDataVect Engine::flash(Room *room, int alpha)
{
// Background visible data
GuiDataVect visible_data;
GuiData bg;
bg.alpha = alpha;
bg.image = room->bg();
bg.text = "";
bg.rect = GuiRect(0, 0, 1.0, 1.0);
visible_data.push_back(bg);
// Items visible data
std::vector <Item *> items = room->items();
for (std::vector<Item *>::iterator i = items.begin();
i != items.end(); ++i)
{
GuiData item;
item.alpha = alpha;
item.text = "";
item.image = (*i)->image();
item.rect = GuiRect((*i)->x(), (*i)->y(), (*i)->w(), (*i)->h());
visible_data.push_back(item);
}
return visible_data;
}
GuiDataVect Engine::getVisibleData()
{
GuiDataVect visible_data;
GuiDataVect gui_data = gui_mgr->getVisibleData();
// Background visible data with transition stuff
if (state() != TRANSITION)
{
GuiDataVect room_data = flash(rooms_mgr->currentRoom());
visible_data.insert(visible_data.end(), room_data.begin(), room_data.end());
}
else
{
GuiDataVect room_data1 = flash(transition.start, transition.alpha_room_start);
GuiDataVect room_data2 = flash(transition.end, transition.alpha_room_end);
visible_data.insert(visible_data.end(), room_data1.begin(), room_data1.end());
visible_data.insert(visible_data.end(), room_data2.begin(), room_data2.end());
}
// Gui visible data
visible_data.insert(visible_data.end(), gui_data.begin(), gui_data.end());
return visible_data;
}
void Engine::apiRoomGoto(const string id)
{
logger.write("ROOM_GOTO: " + id, Log::NOTE);
transition.index = 0;
transition.steps = 5;
transition.start = rooms_mgr->currentRoom();
transition.end = rooms_mgr->room(id);
transition.update();
rooms_mgr->setCurrentRoom(id);
setState(TRANSITION);
}
void Engine::apiVarSet(const string id, const int value)
{
logger.write("VAR_SET: " + id, Log::NOTE);
events_mgr->setVar(id, value);
}
void Engine::apiItemMove(const string id, const string dest)
{
logger.write("ITEM_MOVE: " + id + ", dest: " + dest, Log::NOTE);
Item * item = rooms_mgr->item(id);
string source = item->parent();
rooms_mgr->moveItem(id, dest);
if (source == "!INVENTORY")
inventory->remButton(id);
if (dest == "!INVENTORY")
inventory->addButton(id, "", item->image());
}
void Engine::apiDialogStart(const string id)
{
logger.write("DIALOG_START: " + id, Log::NOTE);
dialog = dialogs[id];
dialog->reset();
setState(DIALOG);
updateDialog();
execActions(dialog->actions());
}
void Engine::apiSFXPlay(const string id)
{
sfx.push_back(id);
}
void Engine::apiExecScript(const string id)
{
vm.execute(id);
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP
/*
#include <srs_core.hpp>
*/
// current release version
#define VERSION_MAJOR 2
#define VERSION_MINOR 0
#define VERSION_REVISION 181
// server info.
#define RTMP_SIG_SRS_KEY "SRS"
#define RTMP_SIG_SRS_CODE "ZhouGuowen"
#define RTMP_SIG_SRS_ROLE "origin/edge server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)"
#define RTMP_SIG_SRS_URL_SHORT "github.com/simple-rtmp-server/srs"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_WEB "http://ossrs.net"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2015 SRS(simple-rtmp-server)"
#define RTMP_SIG_SRS_PRIMARY "SRS/"VERSION_STABLE_BRANCH
#define RTMP_SIG_SRS_AUTHROS "winlin,wenjie.zhao"
#define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt"
#define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")"
#define RTMP_SIG_SRS_RELEASE RTMP_SIG_SRS_URL"/tree/1.0release"
#define RTMP_SIG_SRS_ISSUES(id) RTMP_SIG_SRS_URL"/issues/"#id
#define RTMP_SIG_SRS_VERSION SRS_XSTR(VERSION_MAJOR)"."SRS_XSTR(VERSION_MINOR)"."SRS_XSTR(VERSION_REVISION)
#define RTMP_SIG_SRS_SERVER RTMP_SIG_SRS_KEY"/"RTMP_SIG_SRS_VERSION"("RTMP_SIG_SRS_CODE")"
// stable major version
#define VERSION_STABLE 1
#define VERSION_STABLE_BRANCH SRS_XSTR(VERSION_STABLE)".0release"
// internal macros, covert macro values to str,
// see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define SRS_XSTR(v) SRS_INTERNAL_STR(v)
#define SRS_INTERNAL_STR(v) #v
/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/
// for 32bit os, 2G big file limit for unistd io,
// ie. read/write/lseek to use 64bits size for huge file.
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
// for srs-librtmp, @see https://github.com/simple-rtmp-server/srs/issues/213
#ifndef _WIN32
#include <inttypes.h>
#endif
#include <assert.h>
#define srs_assert(expression) assert(expression)
#include <stddef.h>
#include <sys/types.h>
// generated by configure.
#include <srs_auto_headers.hpp>
// important performance options.
#include <srs_core_performance.hpp>
// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
if (p) { \
delete p; \
p = NULL; \
} \
(void)0
// sometimes, the freepa is useless,
// it's recomments to free each elem explicit.
// so we remove the srs_freepa utility.
/**
* disable copy constructor of class,
* to avoid the memory leak or corrupt by copy instance.
*/
#define disable_default_copy(className)\
private:\
/** \
* disable the copy constructor and operator=, donot allow directly copy. \
*/ \
className(const className&); \
className& operator= (const className&)
#endif
<commit_msg>refine the version<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP
/*
#include <srs_core.hpp>
*/
// current release version
#define VERSION_MAJOR 3
#define VERSION_MINOR 0
#define VERSION_REVISION 0
// server info.
#define RTMP_SIG_SRS_KEY "SRS"
#define RTMP_SIG_SRS_CODE "OuXuli"
#define RTMP_SIG_SRS_ROLE "origin/edge server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)"
#define RTMP_SIG_SRS_URL_SHORT "github.com/simple-rtmp-server/srs"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_WEB "http://ossrs.net"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2015 SRS(simple-rtmp-server)"
#define RTMP_SIG_SRS_PRIMARY "SRS/"VERSION_STABLE_BRANCH
#define RTMP_SIG_SRS_AUTHROS "winlin,wenjie.zhao"
#define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt"
#define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")"
#define RTMP_SIG_SRS_RELEASE RTMP_SIG_SRS_URL"/tree/1.0release"
#define RTMP_SIG_SRS_ISSUES(id) RTMP_SIG_SRS_URL"/issues/"#id
#define RTMP_SIG_SRS_VERSION SRS_XSTR(VERSION_MAJOR)"."SRS_XSTR(VERSION_MINOR)"."SRS_XSTR(VERSION_REVISION)
#define RTMP_SIG_SRS_SERVER RTMP_SIG_SRS_KEY"/"RTMP_SIG_SRS_VERSION"("RTMP_SIG_SRS_CODE")"
// stable major version
#define VERSION_STABLE 1
#define VERSION_STABLE_BRANCH SRS_XSTR(VERSION_STABLE)".0release"
// internal macros, covert macro values to str,
// see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define SRS_XSTR(v) SRS_INTERNAL_STR(v)
#define SRS_INTERNAL_STR(v) #v
/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/
// for 32bit os, 2G big file limit for unistd io,
// ie. read/write/lseek to use 64bits size for huge file.
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
// for srs-librtmp, @see https://github.com/simple-rtmp-server/srs/issues/213
#ifndef _WIN32
#include <inttypes.h>
#endif
#include <assert.h>
#define srs_assert(expression) assert(expression)
#include <stddef.h>
#include <sys/types.h>
// generated by configure.
#include <srs_auto_headers.hpp>
// important performance options.
#include <srs_core_performance.hpp>
// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
if (p) { \
delete p; \
p = NULL; \
} \
(void)0
// sometimes, the freepa is useless,
// it's recomments to free each elem explicit.
// so we remove the srs_freepa utility.
/**
* disable copy constructor of class,
* to avoid the memory leak or corrupt by copy instance.
*/
#define disable_default_copy(className)\
private:\
/** \
* disable the copy constructor and operator=, donot allow directly copy. \
*/ \
className(const className&); \
className& operator= (const className&)
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.