text
stringlengths 54
60.6k
|
|---|
<commit_before>55de8be6-5216-11e5-a549-6c40088e03e4<commit_msg>55e5a3cc-5216-11e5-9f9e-6c40088e03e4<commit_after>55e5a3cc-5216-11e5-9f9e-6c40088e03e4<|endoftext|>
|
<commit_before>c84ef4ba-35ca-11e5-aafa-6c40088e03e4<commit_msg>c8558b10-35ca-11e5-80fb-6c40088e03e4<commit_after>c8558b10-35ca-11e5-80fb-6c40088e03e4<|endoftext|>
|
<commit_before>d6c72c17-2e4e-11e5-bbc5-28cfe91dbc4b<commit_msg>d6cd737a-2e4e-11e5-be70-28cfe91dbc4b<commit_after>d6cd737a-2e4e-11e5-be70-28cfe91dbc4b<|endoftext|>
|
<commit_before>8b33254c-2d14-11e5-af21-0401358ea401<commit_msg>8b33254d-2d14-11e5-af21-0401358ea401<commit_after>8b33254d-2d14-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cstring>
using namespace std;
char ** get_command(string a)
{
char * copy = new char [a.length() + 1];
strcpy(copy, a.c_str());
//bool done = false;
char * begin = copy;
char * token = strtok(copy, " ;|&");
while (token != 0)
{
cout << token << endl;
if (token - begin + strlen(token) < a.size())
{
cout << a.at(token - begin + strlen(token)) << endl;
}
token = strtok(NULL, " ;|&");
}
return 0;
}
void display_prompt()
{
cout << "$ ";
}
int main()
{
display_prompt();
string command;
getline(cin, command);
cout << command << endl;
get_command(command);
return 0;
}
<commit_msg>Added conv_vec and get_command<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
//function to convert a vector of char * to a
//char * [] for use as an execvp argument
char ** conv_vec(vector<char*> v)
{
//create a char * [] of proper size
char ** t = new char* [v.size() + 1];
//counter to keep track of the position
//for entering char*
unsigned i = 0;
for (; i < v.size(); ++i)
{
//first make char[] entry of the right length
t[i] = new char[strlen(v.at(i))];
//then copy the entire string from the vector
//into the char *[]
strcpy(t[i], v.at(i));
}
//set the last position to a null character
t[i] = '\0';
return t;
}
char ** get_command(string& a, int flag)
{
//first make a copy of the command string
//so that we can check what delimiter strtok
//stopped at
char * copy = new char [a.length() + 1];
strcpy(copy, a.c_str());
//create a vector because we do not know
//how many tokens are in the command entered
vector<char *> temp;
//create an empty char * [] to return. It can
//either be empty if there is no input or
//filled later when we convert the vector
//into an array
char ** vec = NULL;
//bool done = false;
//set a starting position to reference when
//finding the position of the delimiter found
char * begin = copy;
//take the first token
char * token = strtok(copy, " ;|&");
while (token != 0)
{
// cout << token << endl;
//the position of the delimiter with respect
//to the beginning of the array
unsigned int pos = token - begin + strlen(token);
//put the token at the end of the vector
temp.push_back(token);
//to find out which delimiter was found
//if it was the end, it will not go through this
if (pos < a.size())
{
//store delimiter character found
char delim = a.at(pos);
// cout << delim << endl;
if (delim != ' ')
{
//if it was not ' ' then we have reached a
//delimiter that indicates the end of the
//command so we are done. Convert
//the vector into the proper char * []
vec = conv_vec(temp);
// for (unsigned i = 0; vec[i] != 0; ++i)
// {
// cout << i << endl;
// cout << vec[i] << endl;
// }
//remember to get rid of the dynamically allocated
delete copy;
if (delim == '|')
{
//set flag bit
flag = 1;
}
else if (delim == '&')
{
//set flag bit to 2
flag = 2;
}
else
{
//then it was ; so set flag bit to 0
flag = 0;
}
return vec;
}
}
token = strtok(NULL, " ;|&");
}
vec = conv_vec(temp);
delete copy;
flag = 0;
return vec;
return 0;
}
void display_prompt()
{
cout << "$ ";
}
int main()
{
int flag = 0;
//put loop here
display_prompt();
string command;
getline(cin, command);
char ** argv = get_command(command, flag);
for (int i = 0; argv[i] != 0; ++i)
{
cout << argv[i] << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>565ff01c-ad5b-11e7-b5b5-ac87a332f658<commit_msg>Stuff changed<commit_after>56d84075-ad5b-11e7-91a9-ac87a332f658<|endoftext|>
|
<commit_before>b2c12699-4b02-11e5-b622-28cfe9171a43<commit_msg>update testing<commit_after>b2cc6687-4b02-11e5-a4f2-28cfe9171a43<|endoftext|>
|
<commit_before>ec4ecdd4-313a-11e5-86f8-3c15c2e10482<commit_msg>ec550570-313a-11e5-b8a4-3c15c2e10482<commit_after>ec550570-313a-11e5-b8a4-3c15c2e10482<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <limits> /* numeric_limits */
#include <stdlib.h> /* exit, EXIT_SUCCESS */
using namespace std;
// Global variables
int randomInt, userMove;
char playAgain;
const string moves[] = {"rock", "paper", "scissors"};
// Empties the input stream
void clearStream()
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return;
}
void run(int playerWins = 0, int compWins = 0)
{
cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
cin >> userMove;
while(!(cin and userMove >= 1 and userMove <= 3))
{
cout << "Unknown command! Please try that again..." << endl;
clearStream();
cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
cin >> userMove;
}
// Create random integer in range [1,3] to simulate the computer selecting a move
randomInt = rand() % 3 + 1;
if(userMove == randomInt)
cout << "Tie game!\nBoth you and the computer chose " << moves[randomInt - 1] << endl;
else
{
if(userMove - randomInt == 1 or userMove - randomInt == -2)
{
cout << "Congratulations, you won!" << endl;
playerWins++;
} else
{
cout << "Sorry, better luck next time!" << endl;
compWins++;
}
cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[randomInt - 1] << endl;
}
cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << endl;
clearStream();
cout << "Play again? [y/n]: ";
cin >> playAgain;
while(!(cin and playAgain == 'y' or playAgain == 'n'))
{
cout << "Unknown command! Please try that again..." << endl;
clearStream();
cout << "Play again? [y/n]: ";
cin >> playAgain;
}
if(playAgain == 'y')
{
clearStream();
run(playerWins, compWins);
}
else
exit(EXIT_SUCCESS);
return;
}
int main()
{
// Initialize rng
srand(time(NULL));
cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors SHOOT!" << endl << "NOTE: Press CTRL+C at any time to terminate the game!";
clearStream(); // Pauses the program until the enter key is pressed and simultaneously clears the input stream if the user input anything before hitting enter
run();
return 0;
}
<commit_msg>Removal of recursive function<commit_after>#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <limits> /* numeric_limits */
#include <stdlib.h> /* exit, EXIT_SUCCESS */
int main()
{
bool playing = true;
std::string playAgain, line;
int playerWins = 0, compWins = 0, compMove, userMove;
const std::string moves[] = {"rock", "paper", "scissors"};
// Initialize rng
srand(time(NULL));
std::cout << "Welcome. Please press the enter key to begin playing Rock Paper Scissors!";
// Pauses the program
getline(std::cin, line);
while(playing)
{
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
while(!(std::cin and userMove >= 1 and userMove <= 3))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter 1 to play Rock, 2 to play Paper, and 3 to play Scissors!: ";
std::cin >> userMove;
}
// Create random integer in range [1,3] to simulate the computer selecting a move
compMove = rand() % 3 + 1;
if(userMove == compMove)
std::cout << "Tie game!\nBoth you and the computer chose " << moves[compMove - 1] << std::endl;
else
{
if(userMove - compMove == 1 or userMove - compMove == -2)
{
std::cout << "Congratulations, you won!" << std::endl;
playerWins++;
} else
{
std::cout << "Sorry, better luck next time!" << std::endl;
compWins++;
}
std::cout << "You chose " << moves[userMove - 1] << " and the computer chose " << moves[compMove - 1] << std::endl;
}
std::cout << "(Player: " << playerWins << " | Computer: " << compWins << ")" << std::endl;
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
while(!(std::cin and playAgain == "y" or playAgain == "n"))
{
std::cout << "Unknown command! Please try that again..." << std::endl;
std::cout << "Play again? [y/n]: ";
std::cin >> playAgain;
}
if(playAgain != "y")
playing = false;
}
return 0;
}
<|endoftext|>
|
<commit_before>d6ab603d-327f-11e5-9a3b-9cf387a8033e<commit_msg>d6b15c1e-327f-11e5-86c5-9cf387a8033e<commit_after>d6b15c1e-327f-11e5-86c5-9cf387a8033e<|endoftext|>
|
<commit_before>1540f9a6-2f67-11e5-a659-6c40088e03e4<commit_msg>1547ab18-2f67-11e5-9ea0-6c40088e03e4<commit_after>1547ab18-2f67-11e5-9ea0-6c40088e03e4<|endoftext|>
|
<commit_before>#include <iostream>
#include "include/CSVWriter.h"
using namespace std;
void test1(){
CSVWriter csv;
csv << "this" << "is" << "a" << "row";
cout << csv << endl;
}
void test2(){
CSVWriter csv;
csv.newRow() << "this" << "is" << "the" << "first" << "row";
csv.newRow() << "this" << "is" << "the" << "second" << "row";
cout << csv << endl;
}
void test3(){
CSVWriter csv;
csv.enableAutoNewRow(5);
csv << "this" << "is" << "the" << "first" << "row" << "this" << "is" << "the" << "second" << "row";
cout << csv << endl;
}
void test4(){
CSVWriter csv;
csv.newRow() << "this" << "is" << "the" << "first" << "row";
csv.newRow() << "this" << "is" << "the" << "second" << "row";
cout << csv.writeToFile("foobar.csv") << endl;
}
int main()
{
test1();
test2();
test3();
test4();
return 0;
}
<commit_msg>Added more tests<commit_after>#include <iostream>
#include "include/CSVWriter.h"
using namespace std;
void test1(){
CSVWriter csv(",");
csv << "this" << "is" << "a" << "row";
cout << csv << endl;
}
void test2(){
CSVWriter csv;
csv.newRow() << "this" << "is" << "the" << "first" << "row";
csv.newRow() << "this" << "is" << "the" << "second" << "row";
cout << csv << endl;
}
void test3(){
CSVWriter csv;
csv.enableAutoNewRow(5);
csv << "this" << "is" << "the" << "first" << "row" << "this" << "is" << "the" << "second" << "row";
cout << csv << endl;
}
void test4(){
CSVWriter csv;
csv.newRow() << "this" << "is" << "the" << "first" << "row";
csv.newRow() << "this" << "is" << "the" << "second" << "row";
cout << csv.writeToFile("foobar.csv") << endl;
}
void test5(){
CSVWriter csv;
csv << "append" << "this" << "row" << "please" << ":)";
cout << csv.writeToFile("foobar.csv",true) << endl;
}
void test6(){
CSVWriter csv_a;
CSVWriter csv_b;
csv_a << "this" << "comes" << "from" << "csv_a";
csv_b << "this" << "is" << "from" << "csv_b";
csv_b << csv_a;
cout << csv_b << endl;
}
int main()
{
test1();
test2();
test3();
test4();
test5();
test6();
return 0;
}
<|endoftext|>
|
<commit_before>438351f0-5216-11e5-9965-6c40088e03e4<commit_msg>438c7a7a-5216-11e5-8180-6c40088e03e4<commit_after>438c7a7a-5216-11e5-8180-6c40088e03e4<|endoftext|>
|
<commit_before>fdf03350-585a-11e5-972a-6c40088e03e4<commit_msg>fdfa8b46-585a-11e5-a7d9-6c40088e03e4<commit_after>fdfa8b46-585a-11e5-a7d9-6c40088e03e4<|endoftext|>
|
<commit_before>b03c6eb8-35ca-11e5-98d1-6c40088e03e4<commit_msg>b0434b66-35ca-11e5-be37-6c40088e03e4<commit_after>b0434b66-35ca-11e5-be37-6c40088e03e4<|endoftext|>
|
<commit_before>047da412-585b-11e5-b2d5-6c40088e03e4<commit_msg>0484e22e-585b-11e5-8047-6c40088e03e4<commit_after>0484e22e-585b-11e5-8047-6c40088e03e4<|endoftext|>
|
<commit_before>dc24fcf0-327f-11e5-bc1f-9cf387a8033e<commit_msg>dc2b38eb-327f-11e5-a0a1-9cf387a8033e<commit_after>dc2b38eb-327f-11e5-a0a1-9cf387a8033e<|endoftext|>
|
<commit_before>9babef59-2d3e-11e5-a113-c82a142b6f9b<commit_msg>9c0d0be3-2d3e-11e5-9ea3-c82a142b6f9b<commit_after>9c0d0be3-2d3e-11e5-9ea3-c82a142b6f9b<|endoftext|>
|
<commit_before>2ef6e48a-2f67-11e5-b127-6c40088e03e4<commit_msg>2efdbc76-2f67-11e5-b994-6c40088e03e4<commit_after>2efdbc76-2f67-11e5-b994-6c40088e03e4<|endoftext|>
|
<commit_before>78073bec-2d53-11e5-baeb-247703a38240<commit_msg>7807c166-2d53-11e5-baeb-247703a38240<commit_after>7807c166-2d53-11e5-baeb-247703a38240<|endoftext|>
|
<commit_before>1d6dfc0a-2f67-11e5-a635-6c40088e03e4<commit_msg>1d7557b6-2f67-11e5-9d92-6c40088e03e4<commit_after>1d7557b6-2f67-11e5-9d92-6c40088e03e4<|endoftext|>
|
<commit_before>#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>
#include "protocolparser.h"
#include "xmllinelocator.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ProtocolParser parser;
// The list of arguments
QStringList arguments = a.arguments();
if(arguments.size() <= 1)
{
std::cout << "Protocol generator usage:" << std::endl;
std::cout << "ProtoGen input.xml [outputpath] [-docs docspath] [-show-hidden-items] [-latex] [-latex-header-level level] [-no-doxygen] [-no-markdown] [-no-helper-files] [-no-unrecognized-warnings]" << std::endl;
return 2; // no input file
}
// We expect the input file here
QString filename;
// The output path
QString path;
// Skip the first argument "ProtoGen.exe"
for(int i = 1; i < arguments.size(); i++)
{
QString arg = arguments.at(i);
if(arg.contains("-no-doxygen", Qt::CaseInsensitive))
parser.disableDoxygen(true);
else if(arg.contains("-no-markdown", Qt::CaseInsensitive))
parser.disableMarkdown(true);
else if(arg.contains("-no-helper-files", Qt::CaseInsensitive))
parser.disableHelperFiles(true);
else if (arg.contains("-show-hidden-items", Qt::CaseInsensitive))
parser.showHiddenItems(true);
else if(arg.endsWith(".xml"))
filename = arg;
else if (arg.startsWith("-latex-header-level"))
{
// Is there an argument following this one?
if (arguments.size() > (i + 1))
{
// Read the header-level and parse the header level (and auto-increment the argument index)
QString lvl = arguments.at(++i);
bool ok = false;
int header_level = lvl.toInt(&ok);
if (!ok)
{
std::cerr << "warning: -latex-header-level argument '" << lvl.toStdString() << "' is invalid.";
}
else if (header_level > 0)
{
parser.setLaTeXLevel(header_level);
}
}
}
else if (arg.contains("-latex", Qt::CaseInsensitive))
parser.setLaTeXSupport(true);
else if (arg.contains("-no-unrecognized-warnings", Qt::CaseInsensitive))
parser.disableUnrecognizedWarnings(true);
else if(arg.endsWith(".css"))
{
QFile file(arg);
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
parser.setInlineCSS(file.readAll());
file.close();
}
else
std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(arg).toStdString() << ", using default css" << std::endl;
}
else if (arg.startsWith("-docs"))
{
// Is there an argument following this?
if (arguments.size() > (i + 1))
{
// The following argument is the directory path for documents
QString docs = ProtocolFile::sanitizePath(arguments.at(++i));
// If the directory already exists, or we can make it, then use it
if(QDir::current().mkpath(docs))
parser.setDocsPath(docs);
}
}
else if((path.isEmpty()) && (arg != filename))
path = arg;
}// for all input arguments
if(!filename.isEmpty())
{
if(parser.parse(filename, path))
return 0; // normal exit
else
return 1; // input file in error
}
else
{
std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
return 2; // no input file
}
}
<commit_msg>Improved command-line argument parsing<commit_after>#include <QCommandlineParser>
#include <QCoreApplication>
#include <QDomDocument>
#include <QStringList>
#include <QFile>
#include <QDir>
#include <iostream>
#include "protocolparser.h"
#include "xmllinelocator.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QCoreApplication::setApplicationName( "Protogen" );
QCoreApplication::setApplicationVersion(ProtocolParser::genVersion);
QCommandLineParser argParser;
argParser.setApplicationDescription("Protocol generation tool");
argParser.addHelpOption();
argParser.addVersionOption();
argParser.addPositionalArgument("input", "Protocol defintion file, .xml");
argParser.addPositionalArgument("outputpath", "Path for generated protocol files (default = current working directory)");
argParser.addOption({{"d", "docs"}, "Path for generated documentation files (default = outputpath)", "docpath"});
argParser.addOption({"show-hidden-items", "Show all items in documentation even if they are marked as 'hidden'"});
argParser.addOption({"latex", "Enable extra documentation output required for LaTeX integration"});
argParser.addOption({{"l", "latex-header-level"}, "LaTeX header level", "latexlevel"});
argParser.addOption({"no-doxygen", "Skip generation of developer-level documentation"});
argParser.addOption({"no-markdown", "Skip generation of user-level documentation"});
argParser.addOption({"no-helper-files", "Skip creation of helper files not directly specifed by protocol .xml file"});
argParser.addOption({{"s", "style"}, "Specify a css file to override the default style for HTML documentation", "cssfile"});
argParser.addOption({"no-unrecognized-warnings", "Suppress warnings for unrecognized xml tags"});
argParser.process(a);
ProtocolParser parser;
// Process the positional arguments
QStringList args = argParser.positionalArguments();
QString filename, path;
if (args.count() > 0 )
filename = args.at(0);
if (args.count() > 1)
path = args.at(1);
if (filename.isEmpty() || !filename.endsWith(".xml"))
{
std::cerr << "error: must provide a protocol (*.xml) file." << std::endl;
return 2; // no input file
}
// Documentation directory
QString docs = argParser.value("docs");
if (!docs.isEmpty() && !argParser.isSet("no-markdown"))
{
docs = ProtocolFile::sanitizePath(docs);
if (QDir::current().mkdir(docs))
{
parser.setDocsPath(docs);
}
}
// Process the optional arguments
parser.disableDoxygen(argParser.isSet("no-doxygen"));
parser.disableMarkdown(argParser.isSet("no-markdown"));
parser.disableHelperFiles(argParser.isSet("no-helper-files"));
parser.showHiddenItems(argParser.isSet("show-hidden-items"));
parser.disableUnrecognizedWarnings(argParser.isSet("no-unrecognized-warnings"));
parser.setLaTeXSupport(argParser.isSet("latex"));
QString latexLevel = argParser.value("latex-header-level");
if (!latexLevel.isEmpty())
{
bool ok = false;
int lvl = latexLevel.toInt(&ok);
if (ok)
{
parser.setLaTeXLevel(lvl);
}
else
{
std::cerr << "warning: -latex-header-level argument '" << latexLevel.toStdString() << "' is invalid.";
}
}
QString css = argParser.value("style");
if (!css.isEmpty() && css.endsWith(".css"))
{
// First attempt to open the file
QFile file(css);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
parser.setInlineCSS(file.readAll());
file.close();
}
else
{
std::cerr << "warning: Failed to open " << QDir::toNativeSeparators(css).toStdString() << ", using default css" << std::endl;
}
}
if (parser.parse(filename, path))
{
// Normal exit
return 0;
}
else
{
// Input file in error
return 1;
}
if(!filename.isEmpty())
{
if(parser.parse(filename, path))
return 0; // normal exit
else
return 1; // input file in error
}
else
{
}
}
<|endoftext|>
|
<commit_before>7a172287-4b02-11e5-a234-28cfe9171a43<commit_msg>more fixes<commit_after>7a231d99-4b02-11e5-9434-28cfe9171a43<|endoftext|>
|
<commit_before>939107c2-4b02-11e5-ad57-28cfe9171a43<commit_msg>I'm done<commit_after>93a093de-4b02-11e5-be58-28cfe9171a43<|endoftext|>
|
<commit_before>#include "test_engine.hpp"
#include <QTest>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDatabase>
#include <QRegularExpression>
#include <QFileSystemModel>
#include <QDebug>
#include <qtreports/engine.hpp>
Test_Engine::Test_Engine( QObject * parent ) :
QObject( parent ) {}
Test_Engine::~Test_Engine() {}
void Test_Engine::engine()
{
qtreports::Engine emptyEngine( "" );
QCOMPARE( emptyEngine.isOpened(), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
qtreports::Engine engine( reportPath );
QVERIFY2( engine.isOpened(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::open() {
qtreports::Engine engine;
QCOMPARE( engine.open( "" ), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QString erroredReportPath = QFINDTESTDATA( "../samples/reports/test/test.errored.qrxml" );
//qDebug() << endl << "Used report: " << erroredReportPath;
QCOMPARE( engine.open( erroredReportPath ), false );
}
void Test_Engine::close()
{
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
qtreports::Engine engine;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.isOpened(), true );
engine.close();
QCOMPARE( engine.isOpened(), false );
}
void Test_Engine::setParameters()
{
QMap < QString, QVariant > map;
map[ "title" ] = "Best Title in World";
//qDebug() << endl << "Used map: " << map;
qtreports::Engine engine;
QCOMPARE( engine.setParameters( map ), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/tests-images/test.full.qrxml" );
//qDebug() << endl << "Used report: " << reportPath;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setParameters( map ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setConnection() {
qtreports::Engine engine;
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
QCOMPARE( engine.setConnection( db ), false );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), ( "Can't open database. Error: " + db.lastError().text() ).toStdString().c_str() );
QCOMPARE( engine.setConnection( db ), false );
QString input = QFINDTESTDATA("../samples/reports/test/test.empty.qreport");
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.setConnection( db ), false );\
input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setDataSource()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QMap< QString, QVector< QVariant > > data;
QVector< QVariant > ids;
ids << 1 << 2 << 3;
data[ "group_id" ] = ids;
QVector< QVariant > group_names;
group_names << "first" << "second" << "three";
data[ "group_name" ] = group_names;
QVector< QVariant > dep_ids;
dep_ids << 11 << 12 << 13;
data[ "dep_id" ] = dep_ids;
QVector< QVariant > citys;
citys << "" << "" << "";
data[ "city" ] = citys;
QVector< QVariant > segments;
segments << "" << "" << "";
data[ "segment" ] = segments;
QVERIFY2( engine.setDataSource( data ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setQuery()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setQuery( "select * from groups_t" ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::addScript()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
// нет скрипта test, найти или поменять на другой
QVERIFY2( engine.addScript( "test" ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setDataModel()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setDataModel( QFileSystemModel() ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::createPDF()
{
qtreports::Engine engine;
QCOMPARE( engine.createPDF( "test.pdf" ), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QString outPath = "test.pdf";
QVERIFY2( engine.createPDF( outPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( QFile::exists( outPath ), true );
QFile file( outPath );
QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
QVERIFY( file.size() != 0 );
file.close();
QCOMPARE( QFile::remove( outPath ), true );
}
void Test_Engine::createHTML()
{
qtreports::Engine engine;
QString outPath = "test.html";
QCOMPARE( engine.createHTML( outPath ), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.html.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createHTML( outPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( QFile::exists( outPath ), true );
QFile file( outPath );
QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
QVERIFY( file.size() != 0 );
file.close();
QCOMPARE( QFile::remove( outPath ), true );
}
void Test_Engine::createWidget()
{
qtreports::Engine engine;
QCOMPARE( engine.createWidget(), qtreports::QWidgetPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createWidget() != qtreports::QWidgetPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::createLayout()
{
qtreports::Engine engine;
QCOMPARE( engine.createLayout(), qtreports::QWidgetPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createLayout() != qtreports::QWidgetPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::print()
{
qtreports::Engine engine;
QCOMPARE( engine.print(), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
//QTRY_VERIFY2_WITH_TIMEOUT( engine.print(), engine.getLastError().toStdString().c_str(), 5 );
}
void Test_Engine::isOpened()
{
qtreports::Engine engine;
QCOMPARE( engine.isOpened(), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.isOpened(), true );
}
void Test_Engine::getReport()
{
qtreports::Engine engine;
QCOMPARE( engine.getReport(), qtreports::detail::ReportPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.getReport() != qtreports::detail::ReportPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::getLastError()
{
qtreports::Engine engine;
QCOMPARE( engine.getLastError(), QString() );
}
<commit_msg>Update test_engine.cpp<commit_after>#include "test_engine.hpp"
#include <QTest>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDatabase>
#include <QRegularExpression>
#include <QFileSystemModel>
#include <QDebug>
#include <qtreports/engine.hpp>
Test_Engine::Test_Engine( QObject * parent ) :
QObject( parent ) {}
Test_Engine::~Test_Engine() {}
void Test_Engine::engine()
{
qtreports::Engine emptyEngine( "" );
QCOMPARE( emptyEngine.isOpened(), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
qtreports::Engine engine( reportPath );
QVERIFY2( engine.isOpened(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::open() {
qtreports::Engine engine;
QCOMPARE( engine.open( "" ), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QString erroredReportPath = QFINDTESTDATA( "../samples/reports/test/test.errored.qrxml" );
//qDebug() << endl << "Used report: " << erroredReportPath;
QCOMPARE( engine.open( erroredReportPath ), false );
}
void Test_Engine::close()
{
QString reportPath = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
//qDebug() << endl << "Used report: " << reportPath;
qtreports::Engine engine;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.isOpened(), true );
engine.close();
QCOMPARE( engine.isOpened(), false );
}
void Test_Engine::setParameters()
{
QMap < QString, QVariant > map;
map[ "title" ] = "Best Title in World";
//qDebug() << endl << "Used map: " << map;
qtreports::Engine engine;
QCOMPARE( engine.setParameters( map ), false );
QString reportPath = QFINDTESTDATA( "../samples/reports/tests-images/test.full.qrxml" );
//qDebug() << endl << "Used report: " << reportPath;
QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setParameters( map ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setConnection() {
qtreports::Engine engine;
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
QCOMPARE( engine.setConnection( db ), false );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), ( "Can't open database. Error: " + db.lastError().text() ).toStdString().c_str() );
QCOMPARE( engine.setConnection( db ), false );
QString input = QFINDTESTDATA("../samples/reports/test/test.empty.qreport");
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.setConnection( db ), false );\
input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setDataSource()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QMap< QString, QVector< QVariant > > data;
QVector< QVariant > ids;
ids << 1 << 2 << 3;
data[ "group_id" ] = ids;
QVector< QVariant > group_names;
group_names << "first" << "second" << "three";
data[ "group_name" ] = group_names;
QVector< QVariant > dep_ids;
dep_ids << 11 << 12 << 13;
data[ "dep_id" ] = dep_ids;
QVector< QVariant > citys;
citys << "" << "" << "";
data[ "city" ] = citys;
QVector< QVariant > segments;
segments << "" << "" << "";
data[ "segment" ] = segments;
QVERIFY2( engine.setDataSource( data ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setQuery()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setQuery( "select * from groups_t" ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::addScript()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
// нет скрипта test, найти или поменять на другой
QVERIFY2( engine.addScript( "test" ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::setDataModel()
{
qtreports::Engine engine;
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.setDataModel( QFileSystemModel() ), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::createPDF()
{
qtreports::Engine engine;
QCOMPARE( engine.createPDF( "test.pdf" ), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QString outPath = "test.pdf";
QVERIFY2( engine.createPDF( outPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( QFile::exists( outPath ), true );
QFile file( outPath );
QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
QVERIFY( file.size() != 0 );
file.close();
QCOMPARE( QFile::remove( outPath ), true );
}
void Test_Engine::createHTML()
{
qtreports::Engine engine;
QString outPath = "test.html";
QCOMPARE( engine.createHTML( outPath ), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.html.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createHTML( outPath ), engine.getLastError().toStdString().c_str() );
QCOMPARE( QFile::exists( outPath ), true );
QFile file( outPath );
QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
QVERIFY( file.size() != 0 );
file.close();
QCOMPARE( QFile::remove( outPath ), true );
}
void Test_Engine::createWidget()
{
qtreports::Engine engine;
QCOMPARE( engine.createWidget(), qtreports::QWidgetPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createWidget() != qtreports::QWidgetPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::createLayout()
{
qtreports::Engine engine;
QCOMPARE( engine.createLayout(), qtreports::QWidgetPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.createLayout() != qtreports::QWidgetPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::print()
{
qtreports::Engine engine;
QCOMPARE( engine.print(), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.print(), true );
//QTRY_VERIFY2_WITH_TIMEOUT( engine.print(), engine.getLastError().toStdString().c_str(), 5 );
}
void Test_Engine::isOpened()
{
qtreports::Engine engine;
QCOMPARE( engine.isOpened(), false );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QCOMPARE( engine.isOpened(), true );
}
void Test_Engine::getReport()
{
qtreports::Engine engine;
QCOMPARE( engine.getReport(), qtreports::detail::ReportPtr() );
QString input = QFINDTESTDATA( "../samples/reports/test/test.default.qreport" );
QVERIFY2( engine.open( input ), engine.getLastError().toStdString().c_str() );
QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName( "../samples/databases/test.db" );
QVERIFY2( db.open(), "Can't open test database 'testDB'" );
QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
QVERIFY2( engine.getReport() != qtreports::detail::ReportPtr(), engine.getLastError().toStdString().c_str() );
}
void Test_Engine::getLastError()
{
qtreports::Engine engine;
QCOMPARE( engine.getLastError(), QString() );
}
<|endoftext|>
|
<commit_before>#pragma once
#include <gtl/box3.hpp>
#include <gtl/gtl.hpp>
#include <gtl/ray.hpp>
#include <gtl/vec3.hpp>
namespace gtl {
/*!
\class sphere sphere.hpp geometry/sphere.hpp
\brief Represents a sphere in 3D.
\ingroup base
This class is used by many other classes.
\sa
*/
template <typename Type>
class sphere {
public:
//! The default constructor.
sphere()
: m_center(vec3<Type>(0.0, 0.0, 0.0))
, m_radius(1)
{
}
//! Constructs an instance with initial values from \a a_sphere.
sphere(const sphere<Type>& a_sphere)
: m_center(a_sphere.m_center)
, m_radius(a_sphere.m_radius)
{
}
//! Construct a sphere given center and radius
sphere(const vec3<Type>& a_center, Type a_radius)
: m_center(a_center)
, m_radius(a_radius)
{
}
//! Construct a sphere given the poles
sphere(const vec3<Type>& p1, const vec3<Type>& p2)
{
setPoles(p1, p2);
}
//! Compute a fast approximation of the bounding ball for the given point set.
sphere(const std::vector<vec3<Type>>& points)
{
//based on the algorithm given by [Jack Ritter, 1990]
if (points.empty())
return;
// find a large diameter to start with
// first get the bounding box
box3<Type> bbox;
for (size_t i = 0; i < points.size(); i++) {
bbox.extendBy(points[i]);
}
setPoles(bbox.getMin(), bbox.getMax());
m_radius /= (Type)2.0;
for (size_t i = 0; i < points.size(); i++) {
extendBy(points[i]);
}
}
//! Change the center and radius
void setValue(const vec3<Type>& c, Type r)
{
m_center = c;
m_radius = r;
}
//! Specify pair of antipodal points
void setPoles(const vec3<Type>& p1, const vec3<Type>& p2)
{
m_center = (Type)0.5 * (p1 + p2);
m_radius = (Type)0.5 * (p1 - p2).length();
}
//! Set the center
void setCenter(const vec3<Type>& c)
{
m_center = c;
}
//! Set the radius
void setRadius(Type r)
{
m_radius = r;
}
//! Return the center
const vec3<Type>& getCenter() const
{
return m_center;
}
//! Return the radius
Type getRadius() const
{
return m_radius;
}
//! Volume of the sphere
Type getVolume() const
{
return (Type)(M_PI * (4.0 / 3.0) * std::pow(m_radius, 3));
}
//! Surface of the sphere
Type getSurface() const
{
return (Type)(M_PI * 4.0 * std::pow(m_radius, 2));
}
//! Make the sphere containing a given box
void circumscribe(const box3<Type>& box)
{
m_center = box.getCenter();
m_radius = (box.getMax() - m_center).length();
}
//! Extend the boundaries of the sphere by the given point.
void extendBy(const vec3<Type>& a_point)
{
if (intersect(a_point))
return;
vec3<Type> dir = m_center - a_point;
dir.normalize();
const vec3<Type> p1 = m_center + m_radius * dir;
setPoles(p1, a_point);
}
//! Extend the boundaries of the sphere by the given sphere.
void extendBy(const sphere<Type>& sphere)
{
if (intersect(sphere))
return;
vec3<Type> dir = m_center - sphere.getCenter();
dir.normalize();
const vec3<Type> p1 = m_center + m_radius * dir;
const vec3<Type> p2 = sphere.getCenter() - sphere.getRadius() * dir;
setPoles(p1, p2);
}
//! Returns true if the given point p lies within the sphere.
bool intersect(const vec3<Type>& p) const
{
return (p - m_center).sqrLength() < m_radius * m_radius;
}
//! Intersect with a sphere, returning true if there is an intersection.
bool intersect(const sphere<Type>& s) const
{
const Type d1 = (s.getCenter() - m_center).sqrLength();
const Type d2 = m_radius + s.getRadius();
return (d1 < d2 * d2);
}
//! Intersect ray and sphere, returning true if there is an intersection.
bool intersect(const ray<Type>& r, Type& tmin, Type& tmax) const
{
const vec3<Type> r_to_s = r.getOrigin() - m_center;
//Compute A, B and C coefficients
const Type A = r.getDirection().sqrLength();
const Type B = 2.0f * r_to_s.dot(r.getDirection());
const Type C = r_to_s.sqrLength() - m_radius * m_radius;
//Find discriminant
Type disc = B * B - 4.0 * A * C;
// if discriminant is negative there are no real roots
if (disc < 0.0)
return false;
disc = (Type)std::sqrt((double)disc);
tmin = (-B + disc) / (2.0 * A);
tmax = (-B - disc) / (2.0 * A);
// check if we're inside it
if ((tmin < 0.0 && tmax > 0) || (tmin > 0 && tmax < 0))
return false;
if (tmin > tmax)
std::swap(tmin, tmax);
return (tmin > 0);
}
//! Intersect with an axis aligned box, returning true if there is an intersection.
bool intersect(const box3<Type>& b) const
{
// Arvo's algorithm.
Type d = 0;
//find the square of the distance from the sphere to the box
for (unsigned int i = 0; i < 3; i++) {
if (m_center[i] < b.getMin()[i]) {
Type s = m_center[i] - b.getMin()[i];
d += s * s;
} else if (m_center[i] > b.getMax()[i]) {
Type s = m_center[i] - b.getMax()[i];
d += s * s;
}
}
return d <= m_radius * m_radius;
}
//! Distribute N points on the sphere (uniform).
void getUniformSurfacePoints(std::vector<vec3<Type>>& points, size_t N)
{
// "generalized spiral set" [Saff and Kuijlaars, 1997]
points.resize(N);
Type theta = 0.0;
for (size_t k = 1; k <= N; k++) {
const Type cosphi = (Type)(-1.0 + 2.0 * (k - 1) / (Type)(N - 1));
const Type sinphi = (Type)std::sqrt(1.0 - cosphi * cosphi);
if (k == 1 || k == N)
theta = 0.0;
else
theta += (Type)3.6 / (sinphi * std::sqrt((Type)N));
points[k - 1] = vec3<Type>(m_radius * sinphi * std::cos(theta),
m_radius * sinphi * std::sin(theta),
m_radius * cosphi);
}
}
//! Check the two given sphere for equality.
friend bool operator==(const sphere<Type>& s1, const sphere<Type>& s2)
{
return (s1.m_center == s2.m_center && s1.m_radius == s2.m_radius);
}
//! Check the two given sphere for inequality.
friend bool operator!=(const sphere<Type>& s1, const sphere<Type>& s2)
{
return !(s1 == s2);
}
private:
vec3<Type> m_center; //!< sphere center
Type m_radius; //!< sphere radius
};
typedef sphere<int> spherei;
typedef sphere<float> spheref;
typedef sphere<double> sphered;
} // namespace gtl
<commit_msg>Simplify a little bit.<commit_after>#pragma once
#include <gtl/box3.hpp>
#include <gtl/gtl.hpp>
#include <gtl/ray.hpp>
#include <gtl/vec3.hpp>
namespace gtl {
/*!
\class sphere sphere.hpp geometry/sphere.hpp
\brief Represents a sphere in 3D.
\ingroup base
This class is used by many other classes.
\sa
*/
template <typename Type>
class sphere {
public:
//! The default constructor.
sphere()
: m_center(vec3<Type>(0.0, 0.0, 0.0))
, m_radius(1)
{
}
//! Constructs an instance with initial values from \a a_sphere.
sphere(const sphere<Type>& a_sphere)
: m_center(a_sphere.m_center)
, m_radius(a_sphere.m_radius)
{
}
//! Construct a sphere given center and radius
sphere(const vec3<Type>& a_center, Type a_radius)
: m_center(a_center)
, m_radius(a_radius)
{
}
//! Construct a sphere given the poles
sphere(const vec3<Type>& p1, const vec3<Type>& p2)
{
setPoles(p1, p2);
}
//! Compute a fast approximation of the bounding ball for the given point set.
sphere(const std::vector<vec3<Type>>& points)
{
//based on the algorithm given by [Jack Ritter, 1990]
if (points.empty())
return;
// find a large diameter to start with
// first get the bounding box
box3<Type> bbox;
for (size_t i = 0; i < points.size(); i++) {
bbox.extendBy(points[i]);
}
setPoles(bbox.getMin(), bbox.getMax());
m_radius /= (Type)2.0;
for (size_t i = 0; i < points.size(); i++) {
extendBy(points[i]);
}
}
//! Change the center and radius
void setValue(const vec3<Type>& c, Type r)
{
m_center = c;
m_radius = r;
}
//! Specify pair of antipodal points
void setPoles(const vec3<Type>& p1, const vec3<Type>& p2)
{
m_center = (Type)0.5 * (p1 + p2);
m_radius = (Type)0.5 * (p1 - p2).length();
}
//! Set the center
void setCenter(const vec3<Type>& c)
{
m_center = c;
}
//! Set the radius
void setRadius(Type r)
{
m_radius = r;
}
//! Return the center
const vec3<Type>& getCenter() const
{
return m_center;
}
//! Return the radius
Type getRadius() const
{
return m_radius;
}
//! Volume of the sphere
Type getVolume() const
{
return (Type)(M_PI * (4.0 / 3.0) * std::pow(m_radius, 3));
}
//! Surface of the sphere
Type getSurface() const
{
return (Type)(M_PI * 4.0 * std::pow(m_radius, 2));
}
//! Make the sphere containing a given box
void circumscribe(const box3<Type>& box)
{
m_center = box.getCenter();
m_radius = (box.getMax() - m_center).length();
}
//! Extend the boundaries of the sphere by the given point.
void extendBy(const vec3<Type>& a_point)
{
if (intersect(a_point))
return;
const vec3<Type> dir = (m_center - a_point).normalized();
const vec3<Type> p1 = m_center + m_radius * dir;
setPoles(p1, a_point);
}
//! Extend the boundaries of the sphere by the given sphere.
void extendBy(const sphere<Type>& sphere)
{
if (intersect(sphere))
return;
const vec3<Type> dir = (m_center - sphere.getCenter()).normalized();
const vec3<Type> p1 = m_center + m_radius * dir;
const vec3<Type> p2 = sphere.getCenter() - sphere.getRadius() * dir;
setPoles(p1, p2);
}
//! Returns true if the given point p lies within the sphere.
bool intersect(const vec3<Type>& p) const
{
return (p - m_center).sqrLength() < m_radius * m_radius;
}
//! Intersect with a sphere, returning true if there is an intersection.
bool intersect(const sphere<Type>& s) const
{
const Type d1 = (s.getCenter() - m_center).sqrLength();
const Type d2 = m_radius + s.getRadius();
return (d1 < d2 * d2);
}
//! Intersect ray and sphere, returning true if there is an intersection.
bool intersect(const ray<Type>& r, Type& tmin, Type& tmax) const
{
const vec3<Type> r_to_s = r.getOrigin() - m_center;
//Compute A, B and C coefficients
const Type A = r.getDirection().sqrLength();
const Type B = 2.0f * r_to_s.dot(r.getDirection());
const Type C = r_to_s.sqrLength() - m_radius * m_radius;
//Find discriminant
Type disc = B * B - 4.0 * A * C;
// if discriminant is negative there are no real roots
if (disc < 0.0)
return false;
disc = (Type)std::sqrt((double)disc);
tmin = (-B + disc) / (2.0 * A);
tmax = (-B - disc) / (2.0 * A);
// check if we're inside it
if ((tmin < 0.0 && tmax > 0) || (tmin > 0 && tmax < 0))
return false;
if (tmin > tmax)
std::swap(tmin, tmax);
return (tmin > 0);
}
//! Intersect with an axis aligned box, returning true if there is an intersection.
bool intersect(const box3<Type>& b) const
{
// Arvo's algorithm.
Type d = 0;
//find the square of the distance from the sphere to the box
for (unsigned int i = 0; i < 3; i++) {
if (m_center[i] < b.getMin()[i]) {
Type s = m_center[i] - b.getMin()[i];
d += s * s;
} else if (m_center[i] > b.getMax()[i]) {
Type s = m_center[i] - b.getMax()[i];
d += s * s;
}
}
return d <= m_radius * m_radius;
}
//! Distribute N points on the sphere (uniform).
void getUniformSurfacePoints(std::vector<vec3<Type>>& points, size_t N)
{
// "generalized spiral set" [Saff and Kuijlaars, 1997]
points.resize(N);
Type theta = 0.0;
for (size_t k = 1; k <= N; k++) {
const Type cosphi = (Type)(-1.0 + 2.0 * (k - 1) / (Type)(N - 1));
const Type sinphi = (Type)std::sqrt(1.0 - cosphi * cosphi);
if (k == 1 || k == N)
theta = 0.0;
else
theta += (Type)3.6 / (sinphi * std::sqrt((Type)N));
points[k - 1] = vec3<Type>(m_radius * sinphi * std::cos(theta),
m_radius * sinphi * std::sin(theta),
m_radius * cosphi);
}
}
//! Check the two given sphere for equality.
friend bool operator==(const sphere<Type>& s1, const sphere<Type>& s2)
{
return (s1.m_center == s2.m_center && s1.m_radius == s2.m_radius);
}
//! Check the two given sphere for inequality.
friend bool operator!=(const sphere<Type>& s1, const sphere<Type>& s2)
{
return !(s1 == s2);
}
private:
vec3<Type> m_center; //!< sphere center
Type m_radius; //!< sphere radius
};
typedef sphere<int> spherei;
typedef sphere<float> spheref;
typedef sphere<double> sphered;
} // namespace gtl
<|endoftext|>
|
<commit_before>#define _BSD_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include "ptbox.h"
pt_process *pt_alloc_process(pt_debugger *debugger) {
return new pt_process(debugger);
}
void pt_free_process(pt_process *process) {
delete process;
}
pt_process::pt_process(pt_debugger *debugger) :
pid(0), callback(NULL), context(NULL), debugger(debugger),
event_proc(NULL), event_context(NULL), _trace_syscalls(true),
_initialized(false)
{
memset(&exec_time, 0, sizeof exec_time);
memset(handler, 0, sizeof handler);
debugger->set_process(this);
}
void pt_process::set_callback(pt_handler_callback callback, void *context) {
this->callback = callback;
this->context = context;
}
void pt_process::set_event_proc(pt_event_callback callback, void *context) {
this->event_proc = callback;
this->event_context = context;
}
int pt_process::set_handler(int syscall, int handler) {
if (syscall >= MAX_SYSCALL || syscall < 0)
return 1;
this->handler[syscall] = handler;
return 0;
}
int pt_process::dispatch(int event, unsigned long param) {
if (event_proc != NULL)
return event_proc(event_context, event, param);
return -1;
}
int pt_process::spawn(pt_fork_handler child, void *context) {
pid_t pid = fork();
if (pid == -1)
return 1;
if (pid == 0) {
setpgid(0, 0);
_exit(child(context));
}
this->pid = pid;
debugger->new_process();
return 0;
}
int pt_process::protection_fault(int syscall) {
dispatch(PTBOX_EVENT_PROTECTION, syscall);
dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION);
kill(pid, SIGKILL);
#if PTBOX_FREEBSD
// FreeBSD SIGKILL doesn't under ptrace.
// ptrace(PT_KILL) doesn't work when not under signal-stop.
// Solution? Use both!
ptrace(PT_KILL, pid, (caddr_t) 1, 0);
#endif
return PTBOX_EXIT_PROTECTION;
}
int pt_process::monitor() {
bool in_syscall = false, first = true, spawned = false;
struct timespec start, end, delta;
int status, exit_reason = PTBOX_EXIT_NORMAL;
// Set pgid to -this->pid such that -pgid becomes pid, resulting
// in the initial wait be on the main thread. This allows it a chance
// of creating a new process group.
pid_t pid, pgid = -this->pid;
#if PTBOX_FREEBSD
struct ptrace_lwpinfo lwpi;
#endif
while (true) {
clock_gettime(CLOCK_MONOTONIC, &start);
pid = wait4(-pgid, &status, __WALL, &_rusage);
clock_gettime(CLOCK_MONOTONIC, &end);
timespec_sub(&end, &start, &delta);
timespec_add(&exec_time, &delta, &exec_time);
int signal = 0;
//printf("pid: %d (%d)\n", pid, this->pid);
if (WIFEXITED(status) || WIFSIGNALED(status)) {
if (first || pid == pgid)
break;
//else printf("Thread exit: %d\n", pid);
}
ptrace(PT_LWPINFO, pid, (caddr_t) &lwpi, sizeof lwpi);
if (first) {
dispatch(PTBOX_EVENT_ATTACH, 0);
#if PTBOX_FREEBSD
// PTRACE_O_TRACESYSGOOD can be replaced by struct ptrace_lwpinfo.pl_flags.
// No FreeBSD equivalent that I know of
// * TRACECLONE makes no sense since FreeBSD has no clone(2)
// * TRACEEXIT... I'm not sure about
#else
// This is right after SIGSTOP is received:
ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT | PTRACE_O_TRACECLONE);
#endif
// We now set the process group to the actual pgid.
pgid = pid;
}
if (WIFSTOPPED(status)) {
#if PTBOX_FREEBSD
if (WSTOPSIG(status) == SIGTRAP && lwpi.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)) {
debugger->update_syscall(&lwpi);
#else
if (WSTOPSIG(status) == (0x80 | SIGTRAP)) {
debugger->settid(pid);
#endif
int syscall = debugger->syscall();
#if PTBOX_FREEBSD
in_syscall = lwpi.pl_flags & PL_FLAG_SCE;
#else
in_syscall = debugger->is_enter();
#endif
//printf("%d: %s syscall %d\n", pid, in_syscall ? "Enter" : "Exit", syscall);
if (!spawned) {
// Does execve not return if the process hits an rlimit and gets SIGKILLed?
//
// It doesn't. See the strace below.
// $ ulimit -Sv50000
// $ strace ./a.out
// execve("./a.out", ["./a.out"], [/* 17 vars */] <unfinished ...>
// +++ killed by SIGKILL +++
// Killed
//
// From this we can see that execve doesn't return (<unfinished ...>) if the process fails to
// initialize, so we don't need to wait until the next non-execve syscall to set
// _initialized to true - if it exited execve, it's good to go.
if (!in_syscall && syscall == debugger->execve_syscall())
spawned = this->_initialized = true;
} else if (in_syscall) {
if (syscall < MAX_SYSCALL) {
switch (handler[syscall]) {
case PTBOX_HANDLER_ALLOW:
break;
case PTBOX_HANDLER_STDOUTERR: {
int arg0 = debugger->arg0();
if (arg0 != 1 && arg0 != 2)
exit_reason = protection_fault(syscall);
break;
}
case PTBOX_HANDLER_CALLBACK:
if (callback(context, syscall))
break;
//printf("Killed by callback: %d\n", syscall);
exit_reason = protection_fault(syscall);
continue;
default:
// Default is to kill, safety first.
//printf("Killed by DISALLOW or None: %d\n", syscall);
exit_reason = protection_fault(syscall);
continue;
}
}
} else if (debugger->on_return_callback) {
debugger->on_return_callback(debugger->on_return_context, syscall);
debugger->on_return_callback = NULL;
debugger->on_return_context = NULL;
}
} else {
#if PTBOX_FREEBSD
// No events aside from signal event on FreeBSD
// (TODO: maybe check for PL_SIGNAL instead of both PL_SIGNAL and PL_NONE?)
signal = WSTOPSIG(status);
#else
switch (WSTOPSIG(status)) {
case SIGTRAP:
switch (status >> 16) {
case PTRACE_EVENT_EXIT:
if (exit_reason != PTBOX_EXIT_NORMAL)
dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL);
case PTRACE_EVENT_CLONE: {
unsigned long tid;
ptrace(PTRACE_GETEVENTMSG, pid, NULL, &tid);
//printf("Created thread: %d\n", tid);
break;
}
}
break;
default:
signal = WSTOPSIG(status);
}
#endif
if (!first) // *** Don't set _signal to SIGSTOP if this is the /first/ SIGSTOP
dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status));
}
}
// Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our
// work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it.
// Doing this prevents a second SIGSTOP from being dispatched to our event handler above. ***
#if PTBOX_FREEBSD
ptrace(_trace_syscalls ? PT_SYSCALL : PT_CONTINUE, pid, (caddr_t) 1, first ? 0 : signal);
#else
ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal);
#endif
first = false;
}
dispatch(PTBOX_EVENT_EXITED, exit_reason);
return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status);
}
<commit_msg>Fixed Linux compilability; #192<commit_after>#define _BSD_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include "ptbox.h"
pt_process *pt_alloc_process(pt_debugger *debugger) {
return new pt_process(debugger);
}
void pt_free_process(pt_process *process) {
delete process;
}
pt_process::pt_process(pt_debugger *debugger) :
pid(0), callback(NULL), context(NULL), debugger(debugger),
event_proc(NULL), event_context(NULL), _trace_syscalls(true),
_initialized(false)
{
memset(&exec_time, 0, sizeof exec_time);
memset(handler, 0, sizeof handler);
debugger->set_process(this);
}
void pt_process::set_callback(pt_handler_callback callback, void *context) {
this->callback = callback;
this->context = context;
}
void pt_process::set_event_proc(pt_event_callback callback, void *context) {
this->event_proc = callback;
this->event_context = context;
}
int pt_process::set_handler(int syscall, int handler) {
if (syscall >= MAX_SYSCALL || syscall < 0)
return 1;
this->handler[syscall] = handler;
return 0;
}
int pt_process::dispatch(int event, unsigned long param) {
if (event_proc != NULL)
return event_proc(event_context, event, param);
return -1;
}
int pt_process::spawn(pt_fork_handler child, void *context) {
pid_t pid = fork();
if (pid == -1)
return 1;
if (pid == 0) {
setpgid(0, 0);
_exit(child(context));
}
this->pid = pid;
debugger->new_process();
return 0;
}
int pt_process::protection_fault(int syscall) {
dispatch(PTBOX_EVENT_PROTECTION, syscall);
dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION);
kill(pid, SIGKILL);
#if PTBOX_FREEBSD
// FreeBSD SIGKILL doesn't under ptrace.
// ptrace(PT_KILL) doesn't work when not under signal-stop.
// Solution? Use both!
ptrace(PT_KILL, pid, (caddr_t) 1, 0);
#endif
return PTBOX_EXIT_PROTECTION;
}
int pt_process::monitor() {
bool in_syscall = false, first = true, spawned = false;
struct timespec start, end, delta;
int status, exit_reason = PTBOX_EXIT_NORMAL;
// Set pgid to -this->pid such that -pgid becomes pid, resulting
// in the initial wait be on the main thread. This allows it a chance
// of creating a new process group.
pid_t pid, pgid = -this->pid;
#if PTBOX_FREEBSD
struct ptrace_lwpinfo lwpi;
#endif
while (true) {
clock_gettime(CLOCK_MONOTONIC, &start);
pid = wait4(-pgid, &status, __WALL, &_rusage);
clock_gettime(CLOCK_MONOTONIC, &end);
timespec_sub(&end, &start, &delta);
timespec_add(&exec_time, &delta, &exec_time);
int signal = 0;
//printf("pid: %d (%d)\n", pid, this->pid);
if (WIFEXITED(status) || WIFSIGNALED(status)) {
if (first || pid == pgid)
break;
//else printf("Thread exit: %d\n", pid);
}
#if PTBOX_FREEBSD
ptrace(PT_LWPINFO, pid, (caddr_t) &lwpi, sizeof lwpi);
#endif
if (first) {
dispatch(PTBOX_EVENT_ATTACH, 0);
#if PTBOX_FREEBSD
// PTRACE_O_TRACESYSGOOD can be replaced by struct ptrace_lwpinfo.pl_flags.
// No FreeBSD equivalent that I know of
// * TRACECLONE makes no sense since FreeBSD has no clone(2)
// * TRACEEXIT... I'm not sure about
#else
// This is right after SIGSTOP is received:
ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT | PTRACE_O_TRACECLONE);
#endif
// We now set the process group to the actual pgid.
pgid = pid;
}
if (WIFSTOPPED(status)) {
#if PTBOX_FREEBSD
if (WSTOPSIG(status) == SIGTRAP && lwpi.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)) {
debugger->update_syscall(&lwpi);
#else
if (WSTOPSIG(status) == (0x80 | SIGTRAP)) {
debugger->settid(pid);
#endif
int syscall = debugger->syscall();
#if PTBOX_FREEBSD
in_syscall = lwpi.pl_flags & PL_FLAG_SCE;
#else
in_syscall = debugger->is_enter();
#endif
//printf("%d: %s syscall %d\n", pid, in_syscall ? "Enter" : "Exit", syscall);
if (!spawned) {
// Does execve not return if the process hits an rlimit and gets SIGKILLed?
//
// It doesn't. See the strace below.
// $ ulimit -Sv50000
// $ strace ./a.out
// execve("./a.out", ["./a.out"], [/* 17 vars */] <unfinished ...>
// +++ killed by SIGKILL +++
// Killed
//
// From this we can see that execve doesn't return (<unfinished ...>) if the process fails to
// initialize, so we don't need to wait until the next non-execve syscall to set
// _initialized to true - if it exited execve, it's good to go.
if (!in_syscall && syscall == debugger->execve_syscall())
spawned = this->_initialized = true;
} else if (in_syscall) {
if (syscall < MAX_SYSCALL) {
switch (handler[syscall]) {
case PTBOX_HANDLER_ALLOW:
break;
case PTBOX_HANDLER_STDOUTERR: {
int arg0 = debugger->arg0();
if (arg0 != 1 && arg0 != 2)
exit_reason = protection_fault(syscall);
break;
}
case PTBOX_HANDLER_CALLBACK:
if (callback(context, syscall))
break;
//printf("Killed by callback: %d\n", syscall);
exit_reason = protection_fault(syscall);
continue;
default:
// Default is to kill, safety first.
//printf("Killed by DISALLOW or None: %d\n", syscall);
exit_reason = protection_fault(syscall);
continue;
}
}
} else if (debugger->on_return_callback) {
debugger->on_return_callback(debugger->on_return_context, syscall);
debugger->on_return_callback = NULL;
debugger->on_return_context = NULL;
}
} else {
#if PTBOX_FREEBSD
// No events aside from signal event on FreeBSD
// (TODO: maybe check for PL_SIGNAL instead of both PL_SIGNAL and PL_NONE?)
signal = WSTOPSIG(status);
#else
switch (WSTOPSIG(status)) {
case SIGTRAP:
switch (status >> 16) {
case PTRACE_EVENT_EXIT:
if (exit_reason != PTBOX_EXIT_NORMAL)
dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL);
case PTRACE_EVENT_CLONE: {
unsigned long tid;
ptrace(PTRACE_GETEVENTMSG, pid, NULL, &tid);
//printf("Created thread: %d\n", tid);
break;
}
}
break;
default:
signal = WSTOPSIG(status);
}
#endif
if (!first) // *** Don't set _signal to SIGSTOP if this is the /first/ SIGSTOP
dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status));
}
}
// Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our
// work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it.
// Doing this prevents a second SIGSTOP from being dispatched to our event handler above. ***
#if PTBOX_FREEBSD
ptrace(_trace_syscalls ? PT_SYSCALL : PT_CONTINUE, pid, (caddr_t) 1, first ? 0 : signal);
#else
ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal);
#endif
first = false;
}
dispatch(PTBOX_EVENT_EXITED, exit_reason);
return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImageRegistrationMethodTest_6.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
/**
* This program test one instantiation of the itk::ImageRegistrationMethod class
*
* Only typedef are tested in this file.
*/
int itkImageRegistrationMethodTest_6(int, char**)
{
bool pass = true;
const unsigned int dimension = 3;
// Fixed Image Type
typedef itk::Image<float,dimension> FixedImageType;
// Moving Image Type
typedef itk::Image<char,dimension> MovingImageType;
// Transform Type
typedef itk::AffineTransform< double, dimension > TransformType;
// Optimizer Type
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
// Metric Type
typedef itk::NormalizedCorrelationImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Interpolation technique
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Registration Method
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
TransformType::Pointer trasform = TransformType::New();
FixedImageType::Pointer fixedImage = FixedImageType::New();
MovingImageType::Pointer movingImage = MovingImageType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImage );
registration->SetInterpolator( interpolator );
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>FIX: Actual registration performed now. Parameters tunned.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImageRegistrationMethodTest_6.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkCommandIterationUpdate.h"
#include "itkImageRegistrationMethodImageSource.h"
/**
* This program tests one instantiation of the itk::ImageRegistrationMethod class
*
*
*/
int itkImageRegistrationMethodTest_6(int argc, char** argv)
{
bool pass = true;
const unsigned int dimension = 2;
// Fixed Image Type
typedef itk::Image<float,dimension> FixedImageType;
// Moving Image Type
typedef itk::Image<float,dimension> MovingImageType;
// Size Type
typedef MovingImageType::SizeType SizeType;
// ImageSource
typedef itk::testhelper::ImageRegistrationMethodImageSource<
FixedImageType::PixelType,
MovingImageType::PixelType,
dimension > ImageSourceType;
// Transform Type
typedef itk::AffineTransform< double, dimension > TransformType;
typedef TransformType::ParametersType ParametersType;
// Optimizer Type
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
// Metric Type
typedef itk::NormalizedCorrelationImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
// Interpolation technique
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
// Registration Method
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
typedef itk::CommandIterationUpdate<
OptimizerType > CommandIterationType;
MetricType::Pointer metric = MetricType::New();
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
TransformType::Pointer trasform = TransformType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
ImageSourceType::Pointer imageSource = ImageSourceType::New();
SizeType size;
size[0] = 100;
size[1] = 100;
imageSource->GenerateImages( size );
FixedImageType::ConstPointer fixedImage = imageSource->GetFixedImage();
MovingImageType::ConstPointer movingImage = imageSource->GetMovingImage();
//
// Connect all the components required for Registratio
//
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImage );
registration->SetInterpolator( interpolator );
// Select the Region of Interest over which the Metric will be computed
// Registration time will be proportional to the number of pixels in this region.
metric->SetFixedImageRegion( fixedImage->GetBufferedRegion() );
// Instantiate an Observer to report the progress of the Optimization
CommandIterationType::Pointer iterationCommand = CommandIterationType::New();
iterationCommand->SetOptimizer( optimizer.GetPointer() );
// Scale the translation components of the Transform in the Optimizer
OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );
scales.Fill( 1.0 );
unsigned long numberOfIterations = 30;
double translationScale = 1e-8;
double maximumStepLenght = 30.0; // no step will be larger than this
double minimumStepLenght = 0.01; // convergence criterion
double gradientTolerance = 0.01; // convergence criterion
if( argc > 1 )
{
numberOfIterations = atol( argv[1] );
std::cout << "numberOfIterations = " << numberOfIterations << std::endl;
}
if( argc > 2 )
{
translationScale = atof( argv[2] );
std::cout << "translationScale = " << translationScale << std::endl;
}
if( argc > 3 )
{
maximumStepLenght = atof( argv[3] );
std::cout << "maximumStepLenght = " << maximumStepLenght << std::endl;
}
if( argc > 4 )
{
minimumStepLenght = atof( argv[4] );
std::cout << "minimumStepLenght = " << minimumStepLenght << std::endl;
}
if( argc > 5 )
{
gradientTolerance = atof( argv[5] );
std::cout << "gradientTolerance = " << gradientTolerance << std::endl;
}
for( unsigned int i=0; i<dimension; i++)
{
scales[ i + dimension * dimension ] = translationScale;
}
optimizer->SetScales( scales );
optimizer->SetNumberOfIterations( numberOfIterations );
optimizer->SetMaximize(false);
optimizer->SetMinimumStepLength( minimumStepLenght );
optimizer->SetMaximumStepLength( maximumStepLenght );
optimizer->SetGradientMagnitudeTolerance( gradientTolerance );
// Start from an Identity transform (in a normal case, the user
// can probably provide a better guess than the identity...
transform->SetIdentity();
registration->SetInitialTransformParameters( transform->GetParameters() );
// Initialize the internal connections of the registration method.
// This can potentially throw an exception
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & e )
{
std::cerr << e << std::endl;
pass = false;
}
ParametersType actualParameters = imageSource->GetActualParameters();
ParametersType finalParameters = registration->GetLastTransformParameters();
const unsigned int numbeOfParameters = actualParameters.Size();
// We know that for the Affine transform the Translation parameters are at
// the end of the list of parameters.
const unsigned int offsetOrder = finalParameters.Size()-actualParameters.Size();
const double tolerance = 1.0; // equivalent to 1 pixel.
for(unsigned int i=0; i<numbeOfParameters; i++)
{
// the parameters are negated in order to get the inverse transformation.
// this only works for comparing translation parameters....
std::cout << finalParameters[i+offsetOrder] << " == " << -actualParameters[i] << std::endl;
if( fabs ( finalParameters[i+offsetOrder] - (-actualParameters[i]) ) > tolerance )
{
std::cout << "Tolerance exceeded at component " << i << std::endl;
pass = false;
}
}
if( !pass )
{
std::cout << "Test FAILED." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "blas.hpp"
#include "linalg.hpp"
#include "fast424_26_257.hpp"
#include <chrono>
#include <vector>
extern "C" {
void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info);
void sgetrf_(int *m, int *n, float *A, int *lda, int *ipiv, int *info);
}
void GetrfWrap(double *data, int m, int n, int lda, std::vector<int>& pivots) {
int info;
dgetrf_(&m, &n, data, &lda, &pivots[0], &info);
assert(info == 0);
}
void GetrfWrap(float *data, int m, int n, int lda, std::vector<int>& pivots) {
int info;
sgetrf_(&m, &n, data, &lda, &pivots[0], &info);
assert(info == 0);
}
template<typename Scalar>
void LU(Matrix<Scalar>& A, std::vector<int>& pivots) {
assert(A.m() > 0 && A.n() > 0);
int m = A.m();
int n = A.n();
pivots.resize(n);
int lda = A.stride();
Scalar *data = A.data();
GetrfWrap(data, m, n, lda, pivots);
// Convert back to C++ zero-indexing
for (int i = 0; i < pivots.size(); ++i) {
pivots[i] -= 1;
}
}
template<typename Scalar>
void Pivot(Matrix<Scalar>& A, std::vector<int>& pivots) {
Scalar *data = A.data();
int stride = A.stride();
for (int j = 0; j < A.n(); ++j) {
for (int i = 0; i < pivots.size(); ++i) {
// Swap rows i and pivots[i]
int pivot_row = pivots[i];
Scalar aij = data[i + j * stride];
data[i + j * stride] = data[pivot_row + j * stride];
data[pivot_row + j * stride] = aij;
}
}
}
template<typename Scalar>
void FastLU(Matrix<Scalar>& A, int blocksize) {
std::vector<int> all_pivots(A.m());
for (int i = 0; i < A.m() && A.m() - i >= blocksize; i += blocksize) {
Matrix<double> Panel = A.Submatrix(i, i, A.m() - i, blocksize);
std::vector<int> pivots;
LU(Panel, pivots);
Pivot(A, pivots);
Matrix<double> L21 = Panel.Submatrix(i, 0, A.m() - i - blocksize, blocksize);
Matrix<double> A22 = A.Submatrix(i, i, A.m() - i, A.n() - i);
Matrix<double> A12 = A.Submatrix(0, i, blocksize, A.n() - i);
// TODO: Need to update and multiply by negative one, not just overwrite
grey424_26_257::FastMatmul(L21, A12, A22, 1);
// Append pivots
for (int j = i; j < i + blocksize; ++j) {
all_pivots[j] = pivots[j - i];
}
}
// Now deal with the leftovers
int start_ind = (A.m() / blocksize) * blocksize;
int num_left = A.m() - start_ind;
assert(num_left >= A.m());
if (num_left == 0) {
return;
}
std::vector<int> pivots;
Matrix<double> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind);
LU(A_end, pivots);
for (int j = start_ind; j < A.m(); ++j) {
all_pivots[j] = pivots[j - start_ind];
}
}
int main(int argc, char **argv) {
int n = 10000;
Matrix<double> A = RandomMatrix<double>(n, n);
Matrix<double> B = A;
auto t1 = std::chrono::high_resolution_clock::now();
std::vector<int> pivots(A.m());
LU(A, pivots);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Classical LU took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
<< " milliseconds"
<< std::endl;
auto t3 = std::chrono::high_resolution_clock::now();
FastLU(B, 1600);
auto t4 = std::chrono::high_resolution_clock::now();
std::cout << "Fast LU took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
<< " milliseconds"
<< std::endl;
}
<commit_msg>Update blas calls<commit_after>#include "blas.hpp"
#include "linalg.hpp"
#include "mkl.h"
#include "fast424_26_257.hpp"
#include <chrono>
#include <vector>
void GetrfWrap(double *data, int m, int n, int lda, std::vector<int>& pivots) {
int info;
dgetrf_(&m, &n, data, &lda, &pivots[0], &info);
assert(info == 0);
}
void GetrfWrap(float *data, int m, int n, int lda, std::vector<int>& pivots) {
int info;
sgetrf_(&m, &n, data, &lda, &pivots[0], &info);
assert(info == 0);
}
template<typename Scalar>
void LU(Matrix<Scalar>& A, std::vector<int>& pivots) {
assert(A.m() > 0 && A.n() > 0);
int m = A.m();
int n = A.n();
pivots.resize(n);
int lda = A.stride();
Scalar *data = A.data();
GetrfWrap(data, m, n, lda, pivots);
// Convert back to C++ zero-indexing
for (int i = 0; i < pivots.size(); ++i) {
pivots[i] -= 1;
}
}
template<typename Scalar>
void Pivot(Matrix<Scalar>& A, std::vector<int>& pivots) {
Scalar *data = A.data();
int stride = A.stride();
for (int j = 0; j < A.n(); ++j) {
for (int i = 0; i < pivots.size(); ++i) {
// Swap rows i and pivots[i]
int pivot_row = pivots[i];
Scalar aij = data[i + j * stride];
data[i + j * stride] = data[pivot_row + j * stride];
data[pivot_row + j * stride] = aij;
}
}
}
template<typename Scalar>
void FastLU(Matrix<Scalar>& A, int blocksize) {
std::vector<int> all_pivots(A.m());
for (int i = 0; i < A.m() && A.m() - i >= blocksize; i += blocksize) {
Matrix<double> Panel = A.Submatrix(i, i, A.m() - i, blocksize);
std::vector<int> pivots;
LU(Panel, pivots);
Pivot(A, pivots);
Matrix<double> L21 = Panel.Submatrix(i, 0, A.m() - i - blocksize, blocksize);
Matrix<double> A22 = A.Submatrix(i, i, A.m() - i, A.n() - i);
Matrix<double> A12 = A.Submatrix(0, i, blocksize, A.n() - i);
// TODO: Need to update and multiply by negative one, not just overwrite
grey424_26_257::FastMatmul(L21, A12, A22, 1);
// Append pivots
for (int j = i; j < i + blocksize; ++j) {
all_pivots[j] = pivots[j - i];
}
}
// Now deal with the leftovers
int start_ind = (A.m() / blocksize) * blocksize;
int num_left = A.m() - start_ind;
assert(num_left >= A.m());
if (num_left == 0) {
return;
}
std::vector<int> pivots;
Matrix<double> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind);
LU(A_end, pivots);
for (int j = start_ind; j < A.m(); ++j) {
all_pivots[j] = pivots[j - start_ind];
}
}
int main(int argc, char **argv) {
int n = 10000;
Matrix<double> A = RandomMatrix<double>(n, n);
Matrix<double> B = A;
auto t1 = std::chrono::high_resolution_clock::now();
std::vector<int> pivots(A.m());
LU(A, pivots);
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Classical LU took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
<< " milliseconds"
<< std::endl;
auto t3 = std::chrono::high_resolution_clock::now();
FastLU(B, 1600);
auto t4 = std::chrono::high_resolution_clock::now();
std::cout << "Fast LU took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
<< " milliseconds"
<< std::endl;
}
<|endoftext|>
|
<commit_before>#include "Octree.h"
#include "ModuleRenderer3D.h"
OctreeNode::OctreeNode(AABB& box, OctreeNode* p)
{
if (p != nullptr) {
this->parent = p;
}
for (uint i = 0; i < 8; i++) {
children[i] = nullptr;
}
this->box = box;
box_size = this->box.Size();
}
OctreeNode::~OctreeNode()
{
for (uint i = 0; i < 8; i++) {
if(children[i]!=nullptr)
delete children[i];
}
}
void OctreeNode::Subdivide()
{
if (children[0]==nullptr) {
AABB new_box;
float3 new_lenght = box.HalfSize();
float3 center = this->box.CenterPoint();
int child_index = 0;
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
for (int z = 0; z < 2; z++)
{
float3 min_point(box.minPoint.x + z * new_lenght.x, box.minPoint.y + y * new_lenght.y, box.minPoint.z + x * new_lenght.z);
float3 max_point(min_point.x + new_lenght.x, min_point.y + new_lenght.y, min_point.z + new_lenght.z);
new_box.minPoint = min_point;
new_box.maxPoint = max_point;
children[child_index] = new OctreeNode(new_box,this);
children[child_index]->box_size = new_lenght;
LOG("New node created with size %f", new_lenght.x);
child_index++;
}
}
}
this->leaf = true;
LOG("Node subdivided");
}
else {
for (int i = 0; i < 8; i++) {
children[i]->Subdivide();
}
}
}
void OctreeNode::DebugDrawNode()
{
float3 corners[8];
this->box.GetCornerPoints(corners);
const int s = 24;
float3* lines = new float3[s];
float3* colors = new float3[s];
lines[0] = float3(corners[0].x, corners[0].y, corners[0].z);
lines[1] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[2] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[3] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[4] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[5] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[6] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[7] = float3(corners[0].x, corners[0].y, corners[0].z);
//
lines[8] = float3(corners[1].x, corners[1].y, corners[1].z);
lines[9] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[10] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[11] = float3(corners[7].x, corners[7].y, corners[7].z);
lines[12] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[13] = float3(corners[7].x, corners[7].y, corners[7].z);
lines[14] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[15] = float3(corners[1].x, corners[1].y, corners[1].z);
//
lines[16] = float3(corners[0].x, corners[0].y, corners[0].z);
lines[17] = float3(corners[1].x, corners[1].y, corners[1].z);
lines[18] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[19] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[20] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[21] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[22] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[23] = float3(corners[7].x, corners[7].y, corners[7].z);
for (int i = 0; i < s; i++)
{
colors[i] = float3(60, 60, 60);
}
// DrawLinesList(lines, s, 5, colors);
glLineWidth((float)5);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, (float*)lines->ptr());
if (colors != nullptr)
{
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(3, GL_FLOAT, 0, (float*)colors->ptr());
}
glDrawArrays(GL_LINES, 0, s);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glLineWidth(1);
delete[] lines;
delete[] colors;
}
void OctreeNode::DebugDraw()
{
DebugDrawNode();
if (this->children[0] != nullptr)
{
for (int i = 0; i < 8; i++)
{
children[i]->DebugDrawNode();
}
}
}
bool OctreeNode::IsALeaf()
{
return leaf;
}
Octree::Octree()
{
depth = 0;
}
Octree::~Octree()
{
if (root != nullptr) {
delete root;
}
}
void Octree::Create(float3 max_point, float3 min_point)
{
AABB box(min_point, max_point);
root = new OctreeNode(box);
}
void Octree::DebugDraw()
{
if(root!=nullptr)
root->DebugDraw();
}
void Octree::Divide()
{
if (!root->IsALeaf()) {
root->Subdivide();
}
else {
for (int i = 0; i < 8; i++) {
root->children[i]->Subdivide();
}
}
}
<commit_msg>Debug draw octree fixed<commit_after>#include "Octree.h"
#include "ModuleRenderer3D.h"
OctreeNode::OctreeNode(AABB& box, OctreeNode* p)
{
if (p != nullptr) {
this->parent = p;
}
for (uint i = 0; i < 8; i++) {
children[i] = nullptr;
}
this->box = box;
box_size = this->box.Size();
}
OctreeNode::~OctreeNode()
{
for (uint i = 0; i < 8; i++) {
if(children[i]!=nullptr)
delete children[i];
}
}
void OctreeNode::Subdivide()
{
if (children[0]==nullptr) {
AABB new_box;
float3 new_lenght = box.HalfSize();
float3 center = this->box.CenterPoint();
int child_index = 0;
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
for (int z = 0; z < 2; z++)
{
float3 min_point(box.minPoint.x + z * new_lenght.x, box.minPoint.y + y * new_lenght.y, box.minPoint.z + x * new_lenght.z);
float3 max_point(min_point.x + new_lenght.x, min_point.y + new_lenght.y, min_point.z + new_lenght.z);
new_box.minPoint = min_point;
new_box.maxPoint = max_point;
children[child_index] = new OctreeNode(new_box,this);
children[child_index]->box_size = new_lenght;
LOG("New node created with size %f", children[child_index]->box_size.x);
child_index++;
}
}
}
this->leaf = true;
LOG("Node subdivided");
}
else {
for (int i = 0; i < 8; i++) {
children[i]->Subdivide();
}
}
}
void OctreeNode::DebugDrawNode()
{
float3 corners[8];
this->box.GetCornerPoints(corners);
const int s = 24;
float3* lines = new float3[s];
float3* colors = new float3[s];
lines[0] = float3(corners[0].x, corners[0].y, corners[0].z);
lines[1] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[2] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[3] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[4] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[5] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[6] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[7] = float3(corners[0].x, corners[0].y, corners[0].z);
//
lines[8] = float3(corners[1].x, corners[1].y, corners[1].z);
lines[9] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[10] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[11] = float3(corners[7].x, corners[7].y, corners[7].z);
lines[12] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[13] = float3(corners[7].x, corners[7].y, corners[7].z);
lines[14] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[15] = float3(corners[1].x, corners[1].y, corners[1].z);
//
lines[16] = float3(corners[0].x, corners[0].y, corners[0].z);
lines[17] = float3(corners[1].x, corners[1].y, corners[1].z);
lines[18] = float3(corners[2].x, corners[2].y, corners[2].z);
lines[19] = float3(corners[3].x, corners[3].y, corners[3].z);
lines[20] = float3(corners[4].x, corners[4].y, corners[4].z);
lines[21] = float3(corners[5].x, corners[5].y, corners[5].z);
lines[22] = float3(corners[6].x, corners[6].y, corners[6].z);
lines[23] = float3(corners[7].x, corners[7].y, corners[7].z);
for (int i = 0; i < s; i++)
{
colors[i] = float3(60, 60, 60);
}
// DrawLinesList(lines, s, 5, colors);
glLineWidth((float)5);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, (float*)lines->ptr());
if (colors != nullptr)
{
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(3, GL_FLOAT, 0, (float*)colors->ptr());
}
glDrawArrays(GL_LINES, 0, s);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glLineWidth(1);
delete[] lines;
delete[] colors;
}
void OctreeNode::DebugDraw()
{
DebugDrawNode();
if (this->children[0] != nullptr)
{
for (int i = 0; i < 8; i++)
{
children[i]->DebugDraw();
}
}
}
bool OctreeNode::IsALeaf()
{
return leaf;
}
Octree::Octree()
{
depth = 0;
}
Octree::~Octree()
{
if (root != nullptr) {
delete root;
}
}
void Octree::Create(float3 max_point, float3 min_point)
{
AABB box(min_point, max_point);
root = new OctreeNode(box);
}
void Octree::DebugDraw()
{
if(root!=nullptr)
root->DebugDraw();
}
void Octree::Divide()
{
if (!root->IsALeaf()) {
root->Subdivide();
}
else {
for (int i = 0; i < 8; i++) {
root->children[i]->Subdivide();
}
}
}
<|endoftext|>
|
<commit_before>#include "calculator/cell/fission_source_norm.h"
#include <memory>
#include "data/cross_sections.h"
#include "domain/domain_types.h"
#include "domain/tests/finite_element_mock.h"
#include "material/tests/mock_material.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/dealii_test_domain.h"
namespace {
using namespace bart;
using ::testing::Return, ::testing::DoDefault, ::testing::NiceMock;
template <typename DimensionWrapper>
class CalcCellFissionSourceNormTest :
public ::testing::Test,
public bart::testing::DealiiTestDomain<DimensionWrapper::value> {
protected:
static constexpr int dim = DimensionWrapper::value;
using FiniteElementType = typename domain::FiniteElementMock<dim>;
using FissionSourceNormType = typename calculator::cell::FissionSourceNorm<dim>;
using SphericalHarmonicType = system::moments::SphericalHarmonicMock;
// Supporting objects and mocks
std::shared_ptr<NiceMock<FiniteElementType>> finite_element_ptr_;
std::shared_ptr<data::CrossSections> cross_sections_ptr_;
std::shared_ptr<SphericalHarmonicType > spherical_harmonic_ptr_;
NiceMock<btest::MockMaterial> mock_material_;
void SetUp() override;
};
template <typename DimensionWrapper>
void CalcCellFissionSourceNormTest<DimensionWrapper>::SetUp() {
std::unordered_map<int, bool> fissile_id_map{{0, true}, {1, false}};
std::unordered_map<int, std::vector<double>> nu_sigma_f = {
{0, {1.0, 2.0}},
{1, {3.0, 6.0}}
};
ON_CALL(mock_material_, GetFissileIDMap())
.WillByDefault(Return(fissile_id_map));
ON_CALL(mock_material_, GetNuSigF())
.WillByDefault(Return(nu_sigma_f));
finite_element_ptr_ = std::make_shared<NiceMock<FiniteElementType>>();
cross_sections_ptr_ = std::make_shared<data::CrossSections>(mock_material_);
spherical_harmonic_ptr_ = std::make_shared<SphericalHarmonicType>();
ON_CALL(*finite_element_ptr_, n_cell_quad_pts())
.WillByDefault(Return(4));
this->SetUpDealii();
}
TYPED_TEST_CASE(CalcCellFissionSourceNormTest, bart::testing::AllDimensions);
TYPED_TEST(CalcCellFissionSourceNormTest, Constructor) {
static constexpr int dim = this->dim;
EXPECT_CALL(*this->finite_element_ptr_, n_cell_quad_pts())
.WillOnce(DoDefault());
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
EXPECT_EQ(this->finite_element_ptr_.use_count(), 2);
EXPECT_EQ(this->cross_sections_ptr_.use_count(), 2);
}
TYPED_TEST(CalcCellFissionSourceNormTest, GetCellNormNonFissile) {
static constexpr int dim = this->dim;
for (auto cell : this->cells_) {
// Set to the non-fissile material
cell->set_material_id(1);
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
double fission_norm = test_calculator.GetCellNorm(cell,
this->spherical_harmonic_ptr_.get());
EXPECT_EQ(fission_norm, 0.0);
break;
}
}
TYPED_TEST(CalcCellFissionSourceNormTest, GetCellNorm) {
static constexpr int dim = this->dim;
auto& finite_element_mock = *(this->finite_element_ptr_);
for (auto cell : this->cells_) {
// Set to the non-fissile material
cell->set_material_id(0);
// Set expectations
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
double fission_norm = test_calculator.GetCellNorm(cell,
this->spherical_harmonic_ptr_.get());
EXPECT_EQ(fission_norm, 700.0);
break;
}
}
} // namespace<commit_msg>added expected calls to tests to FissionSourceNorm<commit_after>#include "calculator/cell/fission_source_norm.h"
#include <memory>
#include "data/cross_sections.h"
#include "domain/domain_types.h"
#include "domain/tests/finite_element_mock.h"
#include "material/tests/mock_material.h"
#include "system/moments/spherical_harmonic_types.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/dealii_test_domain.h"
namespace {
using namespace bart;
using ::testing::Return, ::testing::ReturnRef, ::testing::DoDefault, ::testing::NiceMock;
template <typename DimensionWrapper>
class CalcCellFissionSourceNormTest :
public ::testing::Test,
public bart::testing::DealiiTestDomain<DimensionWrapper::value> {
protected:
static constexpr int dim = DimensionWrapper::value;
using FiniteElementType = typename domain::FiniteElementMock<dim>;
using FissionSourceNormType = typename calculator::cell::FissionSourceNorm<dim>;
using SphericalHarmonicType = system::moments::SphericalHarmonicMock;
// Supporting objects and mocks
std::shared_ptr<NiceMock<FiniteElementType>> finite_element_ptr_;
std::shared_ptr<data::CrossSections> cross_sections_ptr_;
std::shared_ptr<SphericalHarmonicType > spherical_harmonic_ptr_;
NiceMock<btest::MockMaterial> mock_material_;
// test parameters
const int quadrature_points_ = 4;
void SetUp() override;
};
template <typename DimensionWrapper>
void CalcCellFissionSourceNormTest<DimensionWrapper>::SetUp() {
std::unordered_map<int, bool> fissile_id_map{{0, true}, {1, false}};
std::unordered_map<int, std::vector<double>> nu_sigma_f = {
{0, {1.0, 2.0}},
{1, {3.0, 6.0}}
};
ON_CALL(mock_material_, GetFissileIDMap())
.WillByDefault(Return(fissile_id_map));
ON_CALL(mock_material_, GetNuSigF())
.WillByDefault(Return(nu_sigma_f));
finite_element_ptr_ = std::make_shared<NiceMock<FiniteElementType>>();
cross_sections_ptr_ = std::make_shared<data::CrossSections>(mock_material_);
spherical_harmonic_ptr_ = std::make_shared<SphericalHarmonicType>();
ON_CALL(*finite_element_ptr_, n_cell_quad_pts())
.WillByDefault(Return(this->quadrature_points_));
this->SetUpDealii();
}
TYPED_TEST_CASE(CalcCellFissionSourceNormTest, bart::testing::AllDimensions);
TYPED_TEST(CalcCellFissionSourceNormTest, Constructor) {
static constexpr int dim = this->dim;
EXPECT_CALL(*this->finite_element_ptr_, n_cell_quad_pts())
.WillOnce(DoDefault());
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
EXPECT_EQ(this->finite_element_ptr_.use_count(), 2);
EXPECT_EQ(this->cross_sections_ptr_.use_count(), 2);
}
TYPED_TEST(CalcCellFissionSourceNormTest, GetCellNormNonFissile) {
static constexpr int dim = this->dim;
for (auto cell : this->cells_) {
// Set to the non-fissile material
cell->set_material_id(1);
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
double fission_norm = test_calculator.GetCellNorm(
cell,
this->spherical_harmonic_ptr_.get());
EXPECT_EQ(fission_norm, 0.0);
break;
}
}
TYPED_TEST(CalcCellFissionSourceNormTest, GetCellNorm) {
static constexpr int dim = this->dim;
auto& finite_element_mock = *(this->finite_element_ptr_);
auto& spherical_harmonic_mock = *(this->spherical_harmonic_ptr_);
for (auto cell : this->cells_) {
// Set to the non-fissile material
cell->set_material_id(0);
// EXPECTATIONS
// Jacobian should be called for each quadrature point
for (int q = 0; q < this->quadrature_points_; ++q) {
EXPECT_CALL(finite_element_mock, Jacobian(q))
.WillOnce(Return(10*(q+1)));
}
// Number of groups should be determined by Spherical Harmonics
EXPECT_CALL(spherical_harmonic_mock, total_groups())
.WillOnce(Return(2));
// Zeroth moments should be queried for each group
std::vector<double> group_0_flux{1, 2, 3, 4};
std::vector<double> group_1_flux{4, 3, 2, 1};
system::moments::MomentVector group_0_flux_vector(group_0_flux.begin(),
group_0_flux.end());
system::moments::MomentVector group_1_flux_vector(group_1_flux.begin(),
group_1_flux.end());
system::moments::MomentIndex group_0_index{0,0,0};
system::moments::MomentIndex group_1_index{1,0,0};
EXPECT_CALL(spherical_harmonic_mock, BracketOp(group_0_index))
.WillOnce(ReturnRef(group_0_flux_vector));
EXPECT_CALL(spherical_harmonic_mock, BracketOp(group_1_index))
.WillOnce(ReturnRef(group_1_flux_vector));
calculator::cell::FissionSourceNorm<dim> test_calculator(
this->finite_element_ptr_,
this->cross_sections_ptr_);
double fission_norm = test_calculator.GetCellNorm(
cell,
this->spherical_harmonic_ptr_.get());
EXPECT_EQ(fission_norm, 700.0);
break;
}
}
} // namespace<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#if defined (__GCC__)
#include <cxxabi.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <Dbghelp.h>
#endif
#include "Demangle.h"
using namespace Stroika::Foundation;
#if qPlatform_Windows
// otherwise modules linking with this code will tend to get link errors without explicitly linking
// to this module...
#pragma comment (lib, "Dbghelp.lib")
#endif
/*
********************************************************************************
************************ Debug::DropIntoDebuggerIfPresent **********************
********************************************************************************
*/
Characters::String Debug::Demangle (const Characters::String& originalName)
{
#if defined (__GCC__)
int status {};
char* realname = abi::__cxa_demangle (originalName.AsNarrowSDKString ().c_str (), 0, 0, &status);
auto&& cleanup = Execution::Finally ([&realname]() { if (realname != nullptr) { ::free (realname); } });
if (status == 0) {
return Characters::String::FromNarrowSDKString (realname);
}
#elif qPlatform_Windows
char resultBuf[1000];
if (::UnDecorateSymbolName (originalName.AsNarrowSDKString ().c_str (), resultBuf, sizeof (resultBuf), UNDNAME_COMPLETE) != 0) {
return Characters::String::FromNarrowSDKString (resultBuf);
}
#endif
return originalName;
}
<commit_msg>fixed missing include<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#if defined (__GCC__)
#include <cxxabi.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <Dbghelp.h>
#endif
#include "../Execution/Finally.h"
#include "Demangle.h"
using namespace Stroika::Foundation;
#if qPlatform_Windows
// otherwise modules linking with this code will tend to get link errors without explicitly linking
// to this module...
#pragma comment (lib, "Dbghelp.lib")
#endif
/*
********************************************************************************
************************ Debug::DropIntoDebuggerIfPresent **********************
********************************************************************************
*/
Characters::String Debug::Demangle (const Characters::String& originalName)
{
#if defined (__GCC__)
int status {};
char* realname = abi::__cxa_demangle (originalName.AsNarrowSDKString ().c_str (), 0, 0, &status);
auto&& cleanup = Execution::Finally ([&realname]() { if (realname != nullptr) { ::free (realname); } });
if (status == 0) {
return Characters::String::FromNarrowSDKString (realname);
}
#elif qPlatform_Windows
char resultBuf[1000];
if (::UnDecorateSymbolName (originalName.AsNarrowSDKString ().c_str (), resultBuf, sizeof (resultBuf), UNDNAME_COMPLETE) != 0) {
return Characters::String::FromNarrowSDKString (resultBuf);
}
#endif
return originalName;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <string>
#include <vector>
#include "errors.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include "http/http.hpp"
#include "clustering/administration/http/json_adapters.hpp"
#include "clustering/administration/http/semilattice_app.hpp"
#include "clustering/administration/suggester.hpp"
#include "stl_utils.hpp"
template <class metadata_t>
semilattice_http_app_t<metadata_t>::semilattice_http_app_t(
metadata_change_handler_t<metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
directory_metadata(_directory_metadata),
us(_us),
metadata_change_handler(_metadata_change_handler) {
// Do nothing
}
template <class metadata_t>
semilattice_http_app_t<metadata_t>::~semilattice_http_app_t() {
// Do nothing
}
template <class metadata_t>
void semilattice_http_app_t<metadata_t>::get_root(scoped_cJSON_t *json_out) {
// keep this in sync with handle's behavior for getting the root
metadata_t metadata = metadata_change_handler->get();
vclock_ctx_t json_ctx(us);
json_ctx_adapter_t<metadata_t, vclock_ctx_t> json_adapter(&metadata, json_ctx);
json_out->reset(json_adapter.render());
}
// Small helper to extract the changed namespace ids from a JSON change request
class collect_namespaces_exc_t {
public:
collect_namespaces_exc_t(const std::string &_msg) : msg(_msg) { }
std::string get_msg() const { return msg; }
private:
std::string msg;
};
std::vector<namespace_id_t> collect_affected_namespaces(const cJSON *change_request)
THROWS_ONLY(collect_namespaces_exc_t) {
if (change_request == NULL) {
throw collect_namespaces_exc_t("Missing change request");
}
if (change_request->type != cJSON_Object ) {
throw collect_namespaces_exc_t("Unhandled change_request type");
}
std::vector<namespace_id_t> result;
const cJSON *entry = change_request->next;
while (entry) {
if (entry->string == NULL) throw collect_namespaces_exc_t("Missing field name");
try {
const namespace_id_t ns_id = str_to_uuid(std::string(entry->string));
result.push_back(ns_id);
} catch (...) {
throw collect_namespaces_exc_t("Unable to decode UUID: "
+ std::string(entry->string));
}
entry = entry->next;
}
return result;
}
template <class metadata_t>
http_res_t semilattice_http_app_t<metadata_t>::handle(const http_req_t &req) {
try {
metadata_t metadata = metadata_change_handler->get();
//as we traverse the json sub directories this will keep track of where we are
vclock_ctx_t json_ctx(us);
boost::shared_ptr<json_adapter_if_t> json_adapter_head(new json_ctx_adapter_t<metadata_t, vclock_ctx_t>(&metadata, json_ctx));
http_req_t::resource_t::iterator it = req.resource.begin();
//Traverse through the subfields until we're done with the url
while (it != req.resource.end()) {
json_adapter_if_t::json_adapter_map_t subfields = json_adapter_head->get_subfields();
if (subfields.find(*it) == subfields.end()) {
return http_res_t(HTTP_NOT_FOUND); //someone tried to walk off the edge of the world
}
json_adapter_head = subfields[*it];
it++;
}
//json_adapter_head now points to the correct part of the metadata time to build a response and be on our way
switch (req.method) {
case GET:
{
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case POST:
{
// TODO: Get rid of this release mode wrapper, make Michael unhappy.
#ifdef NDEBUG
if (!verify_content_type(req, "application/json")) {
return http_res_t(HTTP_UNSUPPORTED_MEDIA_TYPE);
}
#endif
scoped_cJSON_t change(cJSON_Parse(req.body.c_str()));
if (!change.get()) { //A null value indicates that parsing failed
logINF("Json body failed to parse. Here's the data that failed: %s",
req.get_sanitized_body().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
// Determine for which namespaces we should prioritize distribution
// Default: none
defaulting_map_t<namespace_id_t, bool> prioritize_distr_for_ns(false);
const boost::optional<std::string> prefer_distribution_param =
req.find_query_param("prefer_distribution");
if (prefer_distribution_param) {
if (prefer_distribution_param.get() == "none") {
} else if (prefer_distribution_param.get() == "all") {
prioritize_distr_for_ns =
defaulting_map_t<namespace_id_t, bool>(true);
} else if (prefer_distribution_param.get() == "changed_only") {
try {
const std::vector<namespace_id_t> changed_ns =
collect_affected_namespaces(change.get());
for (auto jt = changed_ns.begin();
jt != changed_ns.end();
++jt) {
prioritize_distr_for_ns.set(*jt, true);
}
} catch (const collect_namespaces_exc_t &e) {
logINF("Unable to extract affected namespaces from request: %s",
e.get_msg().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
} else {
logINF("Invalid value for prefer_distribution argument: %s",
prefer_distribution_param.get().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
}
json_adapter_head->apply(change.get());
{
scoped_cJSON_t absolute_change(change.release());
std::vector<std::string> parts(req.resource.begin(), req.resource.end());
for (std::vector<std::string>::reverse_iterator jt = parts.rbegin(); jt != parts.rend(); ++jt) {
scoped_cJSON_t inner(absolute_change.release());
absolute_change.reset(cJSON_CreateObject());
absolute_change.AddItemToObject(jt->c_str(), inner.release());
}
logINF("Applying data %s", absolute_change.PrintUnformatted().c_str());
}
metadata_change_callback(&metadata, prioritize_distr_for_ns);
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case DELETE:
{
json_adapter_head->erase();
logINF("Deleting %s", req.resource.as_string().c_str());
metadata_change_callback(&metadata,
defaulting_map_t<namespace_id_t, bool>(false));
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case PUT:
{
// TODO: Get rid of this release mode wrapper, make Michael unhappy.
#ifdef NDEBUG
if (!verify_content_type(req, "application/json")) {
return http_res_t(HTTP_UNSUPPORTED_MEDIA_TYPE);
}
#endif
scoped_cJSON_t change(cJSON_Parse(req.body.c_str()));
if (!change.get()) { //A null value indicates that parsing failed
logINF("Json body failed to parse. Here's the data that failed: %s",
req.get_sanitized_body().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
{
scoped_cJSON_t absolute_change(change.release());
std::vector<std::string> parts(req.resource.begin(), req.resource.end());
for (std::vector<std::string>::reverse_iterator jt = parts.rbegin(); jt != parts.rend(); ++jt) {
scoped_cJSON_t inner(absolute_change.release());
absolute_change.reset(cJSON_CreateObject());
absolute_change.AddItemToObject(jt->c_str(), inner.release());
}
logINF("Applying data %s", absolute_change.PrintUnformatted().c_str());
}
json_adapter_head->reset();
json_adapter_head->apply(change.get());
metadata_change_callback(&metadata,
defaulting_map_t<namespace_id_t, bool>(false));
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case HEAD:
case TRACE:
case OPTIONS:
case CONNECT:
case PATCH:
default:
return http_res_t(HTTP_METHOD_NOT_ALLOWED);
break;
}
} catch (const schema_mismatch_exc_t &e) {
logINF("HTTP request throw a schema_mismatch_exc_t with what = %s", e.what());
return http_error_res(e.what());
} catch (const permission_denied_exc_t &e) {
logINF("HTTP request throw a permission_denied_exc_t with what = %s", e.what());
return http_error_res(e.what());
} catch (const cannot_satisfy_goals_exc_t &e) {
logINF("The server was given a set of goals for which it couldn't find a valid blueprint. %s", e.what());
return http_error_res(e.what(), HTTP_INTERNAL_SERVER_ERROR);
} catch (const gone_exc_t & e) {
logINF("HTTP request throw a gone_exc_t with what = %s", e.what());
return http_error_res(e.what(), HTTP_GONE);
}
unreachable();
}
template <class metadata_t>
bool semilattice_http_app_t<metadata_t>::verify_content_type(const http_req_t &req,
const std::string &expected_content_type) const {
boost::optional<std::string> content_type = req.find_header_line("Content-Type");
// Only compare the beginning of the content-type. Some browsers may add additional
// information, and e.g. send "application/json; charset=UTF-8" instead of "application/json"
if (!content_type || !boost::istarts_with(content_type.get(), expected_content_type)) {
std::string actual_content_type = (content_type ? content_type.get() : "<NONE>");
logINF("Bad request, Content-Type should be %s, but is %s.", expected_content_type.c_str(), actual_content_type.c_str());
return false;
}
return true;
}
cluster_semilattice_http_app_t::cluster_semilattice_http_app_t(
metadata_change_handler_t<cluster_semilattice_metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
semilattice_http_app_t<cluster_semilattice_metadata_t>(_metadata_change_handler, _directory_metadata, _us) {
// Do nothing
}
cluster_semilattice_http_app_t::~cluster_semilattice_http_app_t() {
// Do nothing
}
void cluster_semilattice_http_app_t::metadata_change_callback(cluster_semilattice_metadata_t *new_metadata,
const defaulting_map_t<namespace_id_t, bool> &prioritize_distr_for_ns) {
try {
fill_in_blueprints(new_metadata,
directory_metadata->get().get_inner(),
us,
prioritize_distr_for_ns);
} catch (const missing_machine_exc_t &e) { }
}
auth_semilattice_http_app_t::auth_semilattice_http_app_t(
metadata_change_handler_t<auth_semilattice_metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
semilattice_http_app_t<auth_semilattice_metadata_t>(_metadata_change_handler, _directory_metadata, _us) {
// Do nothing
}
auth_semilattice_http_app_t::~auth_semilattice_http_app_t() {
// Do nothing
}
void auth_semilattice_http_app_t::metadata_change_callback(auth_semilattice_metadata_t *,
const defaulting_map_t<namespace_id_t, bool> &) {
// Do nothing
}
template class semilattice_http_app_t<cluster_semilattice_metadata_t>;
template class semilattice_http_app_t<auth_semilattice_metadata_t>;
<commit_msg>Fix to previous commit: namespace ID now extracted from HTTP resource.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include <string>
#include <vector>
#include "errors.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include "http/http.hpp"
#include "clustering/administration/http/json_adapters.hpp"
#include "clustering/administration/http/semilattice_app.hpp"
#include "clustering/administration/suggester.hpp"
#include "stl_utils.hpp"
template <class metadata_t>
semilattice_http_app_t<metadata_t>::semilattice_http_app_t(
metadata_change_handler_t<metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
directory_metadata(_directory_metadata),
us(_us),
metadata_change_handler(_metadata_change_handler) {
// Do nothing
}
template <class metadata_t>
semilattice_http_app_t<metadata_t>::~semilattice_http_app_t() {
// Do nothing
}
template <class metadata_t>
void semilattice_http_app_t<metadata_t>::get_root(scoped_cJSON_t *json_out) {
// keep this in sync with handle's behavior for getting the root
metadata_t metadata = metadata_change_handler->get();
vclock_ctx_t json_ctx(us);
json_ctx_adapter_t<metadata_t, vclock_ctx_t> json_adapter(&metadata, json_ctx);
json_out->reset(json_adapter.render());
}
// Small helper to extract the changed namespace id from a resource_t
// TODO! Embed into a class
class collect_namespaces_exc_t {
public:
collect_namespaces_exc_t(const std::string &_msg) : msg(_msg) { }
const char *what() const { return msg.c_str(); }
private:
std::string msg;
};
namespace_id_t get_resource_namespace(const http_req_t::resource_t &resource)
THROWS_ONLY(collect_namespaces_exc_t) {
auto resource_it = resource.begin();
if (resource_it == resource.end()) {
throw collect_namespaces_exc_t("No namespace protocol defined");
}
const std::string protocol_ns(*resource_it);
if (protocol_ns != "rdb_namespaces" &&
protocol_ns != "dummy_namespaces" &&
protocol_ns != "memcached_namespaces") {
throw collect_namespaces_exc_t("Unhandled namespace protocol " + protocol_ns);
}
++resource_it;
if (resource_it == resource.end()) {
throw collect_namespaces_exc_t("No namespace defined");
}
const std::string ns(*resource_it);
try {
return str_to_uuid(ns);
} catch (...) {
throw collect_namespaces_exc_t("Unable to decode UUID " + ns);
}
}
template <class metadata_t>
http_res_t semilattice_http_app_t<metadata_t>::handle(const http_req_t &req) {
try {
metadata_t metadata = metadata_change_handler->get();
//as we traverse the json sub directories this will keep track of where we are
vclock_ctx_t json_ctx(us);
boost::shared_ptr<json_adapter_if_t> json_adapter_head(new json_ctx_adapter_t<metadata_t, vclock_ctx_t>(&metadata, json_ctx));
http_req_t::resource_t::iterator it = req.resource.begin();
//Traverse through the subfields until we're done with the url
while (it != req.resource.end()) {
json_adapter_if_t::json_adapter_map_t subfields = json_adapter_head->get_subfields();
if (subfields.find(*it) == subfields.end()) {
return http_res_t(HTTP_NOT_FOUND); //someone tried to walk off the edge of the world
}
json_adapter_head = subfields[*it];
it++;
}
//json_adapter_head now points to the correct part of the metadata time to build a response and be on our way
switch (req.method) {
case GET:
{
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case POST:
{
// TODO: Get rid of this release mode wrapper, make Michael unhappy.
#ifdef NDEBUG
if (!verify_content_type(req, "application/json")) {
return http_res_t(HTTP_UNSUPPORTED_MEDIA_TYPE);
}
#endif
scoped_cJSON_t change(cJSON_Parse(req.body.c_str()));
if (!change.get()) { //A null value indicates that parsing failed
logINF("Json body failed to parse. Here's the data that failed: %s",
req.get_sanitized_body().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
// Determine for which namespaces we should prioritize distribution
// Default: none
defaulting_map_t<namespace_id_t, bool> prioritize_distr_for_ns(false);
const boost::optional<std::string> prefer_distribution_param =
req.find_query_param("prefer_distribution");
if (prefer_distribution_param) {
if (prefer_distribution_param.get() == "none") {
} else if (prefer_distribution_param.get() == "all") {
prioritize_distr_for_ns =
defaulting_map_t<namespace_id_t, bool>(true);
} else if (prefer_distribution_param.get() == "changed_only") {
try {
const namespace_id_t changed_ns =
get_resource_namespace(req.resource);
prioritize_distr_for_ns.set(changed_ns, true);
} catch (const collect_namespaces_exc_t &e) {
logINF("Unable to extract affected namespace from request: %s",
e.what());
return http_res_t(HTTP_BAD_REQUEST);
}
} else {
logINF("Invalid value for prefer_distribution argument: %s",
prefer_distribution_param.get().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
}
json_adapter_head->apply(change.get());
{
scoped_cJSON_t absolute_change(change.release());
std::vector<std::string> parts(req.resource.begin(), req.resource.end());
for (std::vector<std::string>::reverse_iterator jt = parts.rbegin(); jt != parts.rend(); ++jt) {
scoped_cJSON_t inner(absolute_change.release());
absolute_change.reset(cJSON_CreateObject());
absolute_change.AddItemToObject(jt->c_str(), inner.release());
}
logINF("Applying data %s", absolute_change.PrintUnformatted().c_str());
}
metadata_change_callback(&metadata, prioritize_distr_for_ns);
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case DELETE:
{
json_adapter_head->erase();
logINF("Deleting %s", req.resource.as_string().c_str());
metadata_change_callback(&metadata,
defaulting_map_t<namespace_id_t, bool>(false));
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case PUT:
{
// TODO: Get rid of this release mode wrapper, make Michael unhappy.
#ifdef NDEBUG
if (!verify_content_type(req, "application/json")) {
return http_res_t(HTTP_UNSUPPORTED_MEDIA_TYPE);
}
#endif
scoped_cJSON_t change(cJSON_Parse(req.body.c_str()));
if (!change.get()) { //A null value indicates that parsing failed
logINF("Json body failed to parse. Here's the data that failed: %s",
req.get_sanitized_body().c_str());
return http_res_t(HTTP_BAD_REQUEST);
}
{
scoped_cJSON_t absolute_change(change.release());
std::vector<std::string> parts(req.resource.begin(), req.resource.end());
for (std::vector<std::string>::reverse_iterator jt = parts.rbegin(); jt != parts.rend(); ++jt) {
scoped_cJSON_t inner(absolute_change.release());
absolute_change.reset(cJSON_CreateObject());
absolute_change.AddItemToObject(jt->c_str(), inner.release());
}
logINF("Applying data %s", absolute_change.PrintUnformatted().c_str());
}
json_adapter_head->reset();
json_adapter_head->apply(change.get());
metadata_change_callback(&metadata,
defaulting_map_t<namespace_id_t, bool>(false));
metadata_change_handler->update(metadata);
scoped_cJSON_t json_repr(json_adapter_head->render());
return http_json_res(json_repr.get());
}
break;
case HEAD:
case TRACE:
case OPTIONS:
case CONNECT:
case PATCH:
default:
return http_res_t(HTTP_METHOD_NOT_ALLOWED);
break;
}
} catch (const schema_mismatch_exc_t &e) {
logINF("HTTP request throw a schema_mismatch_exc_t with what = %s", e.what());
return http_error_res(e.what());
} catch (const permission_denied_exc_t &e) {
logINF("HTTP request throw a permission_denied_exc_t with what = %s", e.what());
return http_error_res(e.what());
} catch (const cannot_satisfy_goals_exc_t &e) {
logINF("The server was given a set of goals for which it couldn't find a valid blueprint. %s", e.what());
return http_error_res(e.what(), HTTP_INTERNAL_SERVER_ERROR);
} catch (const gone_exc_t & e) {
logINF("HTTP request throw a gone_exc_t with what = %s", e.what());
return http_error_res(e.what(), HTTP_GONE);
}
unreachable();
}
template <class metadata_t>
bool semilattice_http_app_t<metadata_t>::verify_content_type(const http_req_t &req,
const std::string &expected_content_type) const {
boost::optional<std::string> content_type = req.find_header_line("Content-Type");
// Only compare the beginning of the content-type. Some browsers may add additional
// information, and e.g. send "application/json; charset=UTF-8" instead of "application/json"
if (!content_type || !boost::istarts_with(content_type.get(), expected_content_type)) {
std::string actual_content_type = (content_type ? content_type.get() : "<NONE>");
logINF("Bad request, Content-Type should be %s, but is %s.", expected_content_type.c_str(), actual_content_type.c_str());
return false;
}
return true;
}
cluster_semilattice_http_app_t::cluster_semilattice_http_app_t(
metadata_change_handler_t<cluster_semilattice_metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
semilattice_http_app_t<cluster_semilattice_metadata_t>(_metadata_change_handler, _directory_metadata, _us) {
// Do nothing
}
cluster_semilattice_http_app_t::~cluster_semilattice_http_app_t() {
// Do nothing
}
void cluster_semilattice_http_app_t::metadata_change_callback(cluster_semilattice_metadata_t *new_metadata,
const defaulting_map_t<namespace_id_t, bool> &prioritize_distr_for_ns) {
try {
fill_in_blueprints(new_metadata,
directory_metadata->get().get_inner(),
us,
prioritize_distr_for_ns);
} catch (const missing_machine_exc_t &e) { }
}
auth_semilattice_http_app_t::auth_semilattice_http_app_t(
metadata_change_handler_t<auth_semilattice_metadata_t> *_metadata_change_handler,
const clone_ptr_t<watchable_t<change_tracking_map_t<peer_id_t, cluster_directory_metadata_t> > > &_directory_metadata,
uuid_u _us) :
semilattice_http_app_t<auth_semilattice_metadata_t>(_metadata_change_handler, _directory_metadata, _us) {
// Do nothing
}
auth_semilattice_http_app_t::~auth_semilattice_http_app_t() {
// Do nothing
}
void auth_semilattice_http_app_t::metadata_change_callback(auth_semilattice_metadata_t *,
const defaulting_map_t<namespace_id_t, bool> &) {
// Do nothing
}
template class semilattice_http_app_t<cluster_semilattice_metadata_t>;
template class semilattice_http_app_t<auth_semilattice_metadata_t>;
<|endoftext|>
|
<commit_before>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#define CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#include <map>
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "containers/archive/order_token.hpp"
#include "containers/uuid.hpp"
template<class protocol_t>
class master_t {
public:
class ack_checker_t {
public:
virtual bool is_acceptable_ack_set(const std::set<peer_id_t> &acks) = 0;
ack_checker_t() { }
protected:
virtual ~ack_checker_t() { }
private:
DISABLE_COPYING(ack_checker_t);
};
master_t(
mailbox_manager_t *mm,
ack_checker_t *ac,
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *md,
mutex_assertion_t *mdl,
typename protocol_t::region_t region,
broadcaster_t<protocol_t> *b)
THROWS_ONLY(interrupted_exc_t) :
mailbox_manager(mm),
ack_checker(ac),
broadcaster(b),
read_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_read,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
write_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_write,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
registrar(mm, this),
master_directory(md), master_directory_lock(mdl),
uuid(generate_uuid()) {
rassert(ack_checker);
master_business_card_t<protocol_t> bcard(
region,
read_mailbox.get_address(), write_mailbox.get_address(),
registrar.get_business_card());
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.insert(std::make_pair(uuid, bcard));
master_directory->set_value(master_map);
}
~master_t() {
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.erase(uuid);
master_directory->set_value(master_map);
}
private:
struct parser_lifetime_t {
parser_lifetime_t(master_t *m, namespace_interface_business_card_t bc) : m_(m), namespace_interface_id_(bc.namespace_interface_id) {
m->sink_map.insert(std::pair<namespace_interface_id_t, parser_lifetime_t *>(bc.namespace_interface_id, this));
send(m->mailbox_manager, bc.ack_address);
}
~parser_lifetime_t() {
m_->sink_map.erase(namespace_interface_id_);
}
auto_drainer_t *drainer() { return &drainer_; }
fifo_enforcer_sink_t *sink() { return &sink_; }
private:
master_t *m_;
namespace_interface_id_t namespace_interface_id_;
fifo_enforcer_sink_t sink_;
auto_drainer_t drainer_;
DISABLE_COPYING(parser_lifetime_t);
};
void on_read(namespace_interface_id_t parser_id, typename protocol_t::read_t read, order_token_t otok, fifo_enforcer_read_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::read_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
try {
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::read_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can happen) could cause it to be wrong?
rassert(it != sink_map.end());
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_read_t exiter(it->second->sink(), token);
reply = broadcaster->read(read, &exiter, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
} catch (interrupted_exc_t) {
/* Bail out and don't even send a response. The reason an exception
was thrown is because the `master_t` is being destroyed, and the
client will find out some other way. */
}
}
void on_write(namespace_interface_id_t parser_id, typename protocol_t::write_t write, order_token_t otok, fifo_enforcer_write_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::write_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
try {
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::write_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can hoppen) could cause it to be wrong?
rassert(it != sink_map.end());
class ac_t : public broadcaster_t<protocol_t>::ack_callback_t {
public:
explicit ac_t(master_t *p) : parent(p) { }
bool on_ack(peer_id_t peer) {
ack_set.insert(peer);
return parent->ack_checker->is_acceptable_ack_set(ack_set);
}
master_t *parent;
std::set<peer_id_t> ack_set;
} ack_checker(this);
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_write_t exiter(it->second->sink(), token);
reply = broadcaster->write(write, &exiter, &ack_checker, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
} catch (interrupted_exc_t) {
/* See note in `on_read()` */
}
}
mailbox_manager_t *mailbox_manager;
ack_checker_t *ack_checker;
broadcaster_t<protocol_t> *broadcaster;
std::map<namespace_interface_id_t, parser_lifetime_t *> sink_map;
auto_drainer_t drainer;
typename master_business_card_t<protocol_t>::read_mailbox_t read_mailbox;
typename master_business_card_t<protocol_t>::write_mailbox_t write_mailbox;
registrar_t<namespace_interface_business_card_t, master_t *, parser_lifetime_t> registrar;
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *master_directory;
mutex_assertion_t *master_directory_lock;
master_id_t uuid;
DISABLE_COPYING(master_t);
};
#endif /* CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_ */
<commit_msg>Destroy master's mailboxes before registrar to avoid race conditions. Fixes #672. Also, tolerate reordering of deregistration messages and queries even though that wasn't causing the problem.<commit_after>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#define CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#include <map>
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "containers/archive/order_token.hpp"
#include "containers/uuid.hpp"
template<class protocol_t>
class master_t {
public:
class ack_checker_t {
public:
virtual bool is_acceptable_ack_set(const std::set<peer_id_t> &acks) = 0;
ack_checker_t() { }
protected:
virtual ~ack_checker_t() { }
private:
DISABLE_COPYING(ack_checker_t);
};
master_t(
mailbox_manager_t *mm,
ack_checker_t *ac,
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *md,
mutex_assertion_t *mdl,
typename protocol_t::region_t region,
broadcaster_t<protocol_t> *b)
THROWS_ONLY(interrupted_exc_t) :
mailbox_manager(mm),
ack_checker(ac),
broadcaster(b),
registrar(mm, this),
read_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_read,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
write_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_write,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
master_directory(md), master_directory_lock(mdl),
uuid(generate_uuid()) {
rassert(ack_checker);
master_business_card_t<protocol_t> bcard(
region,
read_mailbox.get_address(), write_mailbox.get_address(),
registrar.get_business_card());
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.insert(std::make_pair(uuid, bcard));
master_directory->set_value(master_map);
}
~master_t() {
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.erase(uuid);
master_directory->set_value(master_map);
}
private:
struct parser_lifetime_t {
parser_lifetime_t(master_t *m, namespace_interface_business_card_t bc) : m_(m), namespace_interface_id_(bc.namespace_interface_id) {
m->sink_map.insert(std::pair<namespace_interface_id_t, parser_lifetime_t *>(bc.namespace_interface_id, this));
send(m->mailbox_manager, bc.ack_address);
}
~parser_lifetime_t() {
m_->sink_map.erase(namespace_interface_id_);
}
auto_drainer_t *drainer() { return &drainer_; }
fifo_enforcer_sink_t *sink() { return &sink_; }
private:
master_t *m_;
namespace_interface_id_t namespace_interface_id_;
fifo_enforcer_sink_t sink_;
auto_drainer_t drainer_;
DISABLE_COPYING(parser_lifetime_t);
};
void on_read(namespace_interface_id_t parser_id, typename protocol_t::read_t read, order_token_t otok, fifo_enforcer_read_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::read_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
try {
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::read_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
if (it == sink_map.end()) {
/* We got a message from a parser that already deregistered
itself. This happened because the deregistration message
raced ahead of the query. Ignore it. */
return;
}
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_read_t exiter(it->second->sink(), token);
reply = broadcaster->read(read, &exiter, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
} catch (interrupted_exc_t) {
/* Bail out and don't even send a response. The reason an exception
was thrown is because the `master_t` is being destroyed, and the
client will find out some other way. */
}
}
void on_write(namespace_interface_id_t parser_id, typename protocol_t::write_t write, order_token_t otok, fifo_enforcer_write_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::write_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
try {
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::write_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
if (it == sink_map.end()) {
/* We got a message from a parser that already deregistered
itself. This happened because the deregistration message
raced ahead of the query. Ignore it. */
return;
}
class ac_t : public broadcaster_t<protocol_t>::ack_callback_t {
public:
explicit ac_t(master_t *p) : parent(p) { }
bool on_ack(peer_id_t peer) {
ack_set.insert(peer);
return parent->ack_checker->is_acceptable_ack_set(ack_set);
}
master_t *parent;
std::set<peer_id_t> ack_set;
} ack_checker(this);
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_write_t exiter(it->second->sink(), token);
reply = broadcaster->write(write, &exiter, &ack_checker, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
} catch (interrupted_exc_t) {
/* See note in `on_read()` */
}
}
mailbox_manager_t *mailbox_manager;
ack_checker_t *ack_checker;
broadcaster_t<protocol_t> *broadcaster;
std::map<namespace_interface_id_t, parser_lifetime_t *> sink_map;
auto_drainer_t drainer;
registrar_t<namespace_interface_business_card_t, master_t *, parser_lifetime_t> registrar;
typename master_business_card_t<protocol_t>::read_mailbox_t read_mailbox;
typename master_business_card_t<protocol_t>::write_mailbox_t write_mailbox;
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *master_directory;
mutex_assertion_t *master_directory_lock;
master_id_t uuid;
DISABLE_COPYING(master_t);
};
#endif /* CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_ */
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ClkPartPass : public Pass {
ClkPartPass() : Pass("clkpart", "partition design according to clock domain") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clkpart [options] [selection]\n");
log("\n");
log("Partition the contents of selected modules according to the clock (and optionally\n");
log("the enable) domains of its $_DFF* cells by extracting them into sub-modules,\n");
log("using the `submod` command.\n");
log("Sub-modules created by this command are marked with a 'clkpart' attribute.\n");
log("\n");
log(" -unpart\n");
log(" undo this operation within the selected modules, by flattening those with\n");
log(" a 'clkpart' attribute into those modules without this attribute.\n");
log("\n");
log(" -enable\n");
log(" also consider enable domains.\n");
log("\n");
}
bool unpart_mode, enable_mode;
void clear_flags() YS_OVERRIDE
{
unpart_mode = false;
enable_mode = false;
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing CLKPART pass (partition design according to clock domain).\n");
log_push();
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-unpart") {
unpart_mode = true;
continue;
}
if (args[argidx] == "-enable") {
enable_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (unpart_mode)
unpart(design);
else
part(design);
log_pop();
}
void part(RTLIL::Design *design)
{
CellTypes ct(design);
SigMap assign_map;
std::vector<std::string> new_submods;
log_header(design, "Summary of detected clock domains:\n");
for (auto mod : design->selected_modules())
{
if (mod->processes.size() > 0) {
log("Skipping module %s as it contains processes.\n", log_id(mod));
continue;
}
assign_map.set(mod);
std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
std::map<clkdomain_t, vector<Cell*>> assigned_cells;
std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
for (auto cell : all_cells)
{
clkdomain_t key;
for (auto &conn : cell->connections())
for (auto bit : conn.second) {
bit = assign_map(bit);
if (bit.wire != nullptr) {
cell_to_bit[cell].insert(bit);
bit_to_cell[bit].insert(cell);
if (ct.cell_input(cell->type, conn.first)) {
cell_to_bit_up[cell].insert(bit);
bit_to_cell_down[bit].insert(cell);
}
if (ct.cell_output(cell->type, conn.first)) {
cell_to_bit_down[cell].insert(bit);
bit_to_cell_up[bit].insert(cell);
}
}
}
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
{
key = clkdomain_t(cell->type == ID($_DFF_P_), assign_map(cell->getPort(ID(C))), true, RTLIL::SigSpec());
}
else
if (cell->type.in(ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
{
bool this_clk_pol = cell->type.in(ID($_DFFE_PN_), ID($_DFFE_PP_));
bool this_en_pol = !enable_mode || cell->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_));
key = clkdomain_t(this_clk_pol, assign_map(cell->getPort(ID(C))), this_en_pol, enable_mode ? assign_map(cell->getPort(ID(E))) : RTLIL::SigSpec());
}
else
continue;
unassigned_cells.erase(cell);
expand_queue.insert(cell);
expand_queue_up.insert(cell);
expand_queue_down.insert(cell);
assigned_cells[key].push_back(cell);
assigned_cells_reverse[cell] = key;
}
while (!expand_queue_up.empty() || !expand_queue_down.empty())
{
if (!expand_queue_up.empty())
{
RTLIL::Cell *cell = *expand_queue_up.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue_up.erase(cell);
for (auto bit : cell_to_bit_up[cell])
for (auto c : bit_to_cell_up[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue_up.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
expand_queue.insert(c);
}
}
if (!expand_queue_down.empty())
{
RTLIL::Cell *cell = *expand_queue_down.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue_down.erase(cell);
for (auto bit : cell_to_bit_down[cell])
for (auto c : bit_to_cell_down[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue_up.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
expand_queue.insert(c);
}
}
if (expand_queue_up.empty() && expand_queue_down.empty()) {
expand_queue_up.swap(next_expand_queue_up);
expand_queue_down.swap(next_expand_queue_down);
}
}
while (!expand_queue.empty())
{
RTLIL::Cell *cell = *expand_queue.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue.erase(cell);
for (auto bit : cell_to_bit.at(cell)) {
for (auto c : bit_to_cell[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
}
bit_to_cell[bit].clear();
}
if (expand_queue.empty())
expand_queue.swap(next_expand_queue);
}
clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
for (auto cell : unassigned_cells) {
assigned_cells[key].push_back(cell);
assigned_cells_reverse[cell] = key;
}
clkdomain_t largest_domain;
int largest_domain_size = 0;
log(" module %s\n", mod->name.c_str());
for (auto &it : assigned_cells) {
log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
if (GetSize(it.second) > largest_domain_size) {
largest_domain = it.first;
largest_domain_size = GetSize(it.second);
}
}
for (auto &it : assigned_cells) {
if (it.first == largest_domain)
continue;
std::string submod = stringf("\\%s%s.%s%s",
std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
for (auto c : it.second)
c->attributes[ID(submod)] = submod;
new_submods.push_back(stringf("%s_%s", mod->name.c_str(), submod.c_str()));
}
}
Pass::call(design, "submod");
for (auto m : new_submods)
design->module(m)->set_bool_attribute(ID(clkpart));
}
void unpart(RTLIL::Design *design)
{
vector<Module*> keeped;
for (auto mod : design->selected_modules()) {
if (mod->get_bool_attribute(ID(clkpart)))
continue;
if (mod->get_bool_attribute(ID(keep_hierarchy)))
continue;
keeped.push_back(mod);
mod->set_bool_attribute(ID(keep_hierarchy));
}
Pass::call(design, "flatten");
for (auto mod : keeped)
mod->set_bool_attribute(ID(keep_hierarchy), false);
}
} ClkPartPass;
PRIVATE_NAMESPACE_END
<commit_msg>Do not use log_signal() for empty SigSpec to prevent "{ }"<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ClkPartPass : public Pass {
ClkPartPass() : Pass("clkpart", "partition design according to clock domain") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clkpart [options] [selection]\n");
log("\n");
log("Partition the contents of selected modules according to the clock (and optionally\n");
log("the enable) domains of its $_DFF* cells by extracting them into sub-modules,\n");
log("using the `submod` command.\n");
log("Sub-modules created by this command are marked with a 'clkpart' attribute.\n");
log("\n");
log(" -unpart\n");
log(" undo this operation within the selected modules, by flattening those with\n");
log(" a 'clkpart' attribute into those modules without this attribute.\n");
log("\n");
log(" -enable\n");
log(" also consider enable domains.\n");
log("\n");
}
bool unpart_mode, enable_mode;
void clear_flags() YS_OVERRIDE
{
unpart_mode = false;
enable_mode = false;
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing CLKPART pass (partition design according to clock domain).\n");
log_push();
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-unpart") {
unpart_mode = true;
continue;
}
if (args[argidx] == "-enable") {
enable_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (unpart_mode)
unpart(design);
else
part(design);
log_pop();
}
void part(RTLIL::Design *design)
{
CellTypes ct(design);
SigMap assign_map;
std::vector<std::string> new_submods;
log_header(design, "Summary of detected clock domains:\n");
for (auto mod : design->selected_modules())
{
if (mod->processes.size() > 0) {
log("Skipping module %s as it contains processes.\n", log_id(mod));
continue;
}
assign_map.set(mod);
std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
std::map<clkdomain_t, vector<Cell*>> assigned_cells;
std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
for (auto cell : all_cells)
{
clkdomain_t key;
for (auto &conn : cell->connections())
for (auto bit : conn.second) {
bit = assign_map(bit);
if (bit.wire != nullptr) {
cell_to_bit[cell].insert(bit);
bit_to_cell[bit].insert(cell);
if (ct.cell_input(cell->type, conn.first)) {
cell_to_bit_up[cell].insert(bit);
bit_to_cell_down[bit].insert(cell);
}
if (ct.cell_output(cell->type, conn.first)) {
cell_to_bit_down[cell].insert(bit);
bit_to_cell_up[bit].insert(cell);
}
}
}
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
{
key = clkdomain_t(cell->type == ID($_DFF_P_), assign_map(cell->getPort(ID(C))), true, RTLIL::SigSpec());
}
else
if (cell->type.in(ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
{
bool this_clk_pol = cell->type.in(ID($_DFFE_PN_), ID($_DFFE_PP_));
bool this_en_pol = !enable_mode || cell->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_));
key = clkdomain_t(this_clk_pol, assign_map(cell->getPort(ID(C))), this_en_pol, enable_mode ? assign_map(cell->getPort(ID(E))) : RTLIL::SigSpec());
}
else
continue;
unassigned_cells.erase(cell);
expand_queue.insert(cell);
expand_queue_up.insert(cell);
expand_queue_down.insert(cell);
assigned_cells[key].push_back(cell);
assigned_cells_reverse[cell] = key;
}
while (!expand_queue_up.empty() || !expand_queue_down.empty())
{
if (!expand_queue_up.empty())
{
RTLIL::Cell *cell = *expand_queue_up.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue_up.erase(cell);
for (auto bit : cell_to_bit_up[cell])
for (auto c : bit_to_cell_up[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue_up.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
expand_queue.insert(c);
}
}
if (!expand_queue_down.empty())
{
RTLIL::Cell *cell = *expand_queue_down.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue_down.erase(cell);
for (auto bit : cell_to_bit_down[cell])
for (auto c : bit_to_cell_down[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue_up.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
expand_queue.insert(c);
}
}
if (expand_queue_up.empty() && expand_queue_down.empty()) {
expand_queue_up.swap(next_expand_queue_up);
expand_queue_down.swap(next_expand_queue_down);
}
}
while (!expand_queue.empty())
{
RTLIL::Cell *cell = *expand_queue.begin();
clkdomain_t key = assigned_cells_reverse.at(cell);
expand_queue.erase(cell);
for (auto bit : cell_to_bit.at(cell)) {
for (auto c : bit_to_cell[bit])
if (unassigned_cells.count(c)) {
unassigned_cells.erase(c);
next_expand_queue.insert(c);
assigned_cells[key].push_back(c);
assigned_cells_reverse[c] = key;
}
bit_to_cell[bit].clear();
}
if (expand_queue.empty())
expand_queue.swap(next_expand_queue);
}
clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
for (auto cell : unassigned_cells) {
assigned_cells[key].push_back(cell);
assigned_cells_reverse[cell] = key;
}
clkdomain_t largest_domain;
int largest_domain_size = 0;
log(" module %s\n", mod->name.c_str());
for (auto &it : assigned_cells) {
log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
if (GetSize(it.second) > largest_domain_size) {
largest_domain = it.first;
largest_domain_size = GetSize(it.second);
}
}
for (auto &it : assigned_cells) {
if (it.first == largest_domain)
continue;
auto clk = std::get<1>(it.first);
auto en = std::get<3>(it.first);
std::string submod = stringf("\\%s%s.%s%s",
std::get<0>(it.first) ? "" : "!", clk.empty() ? "" : log_signal(clk),
std::get<2>(it.first) ? "" : "!", en.empty() ? "" : log_signal(en));
for (auto c : it.second)
c->attributes[ID(submod)] = submod;
new_submods.push_back(stringf("%s_%s", mod->name.c_str(), submod.c_str()));
}
}
Pass::call(design, "submod");
for (auto m : new_submods)
design->module(m)->set_bool_attribute(ID(clkpart));
}
void unpart(RTLIL::Design *design)
{
vector<Module*> keeped;
for (auto mod : design->selected_modules()) {
if (mod->get_bool_attribute(ID(clkpart)))
continue;
if (mod->get_bool_attribute(ID(keep_hierarchy)))
continue;
keeped.push_back(mod);
mod->set_bool_attribute(ID(keep_hierarchy));
}
Pass::call(design, "flatten");
for (auto mod : keeped)
mod->set_bool_attribute(ID(keep_hierarchy), false);
}
} ClkPartPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include "SimTKsimbody.h"
using namespace SimTK;
using namespace std;
const Real TOL = 1e-5;
#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");}
template <class T>
void assertEqual(T val1, T val2) {
ASSERT(abs(val1-val2) < TOL || abs(val1-val2)/max(abs(val1), abs(val2)) < TOL);
}
template <int N>
void assertEqual(Vec<N> val1, Vec<N> val2) {
for (int i = 0; i < N; ++i)
assertEqual(val1[i], val2[i]);
}
void testForces() {
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
// Create a triangle mesh in the shape of a pyramid, with the
// square base having area 1 (split into two triangles).
vector<Vec3> vertices;
vertices.push_back(Vec3(0, 0, 0));
vertices.push_back(Vec3(1, 0, 0));
vertices.push_back(Vec3(1, 0, 1));
vertices.push_back(Vec3(0, 0, 1));
vertices.push_back(Vec3(0.5, 1, 0.5));
vector<int> faceIndices;
int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
{2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
// Create the mobilized bodies and configure the contact model.
Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
ContactSetIndex setIndex = contacts.createContactSet();
MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); // y < 0
ElasticFoundationForce ef(forces, contacts, setIndex);
Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
ASSERT(ef.getTransitionVelocity() == vt);
State state = system.realizeTopology();
// Position the pyramid at a variety of positions and check the normal
// force.
for (Real depth = -0.1; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
system.realize(state, Stage::Dynamics);
Real f = 0;
if (depth > 0)
f = stiffness*depth;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));
}
// Now do it with a vertical velocity and see if the dissipation force is correct.
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));
system.realize(state, Stage::Dynamics);
Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);
if (f < 0)
f = 0;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
}
}
// Do it with a horizontal velocity and see if the friction force is correct.
Vector_<SpatialVec> expectedForce(matter.getNumBodies());
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
Real fh = 0;
if (depth > 0)
fh = stiffness*depth;
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));
system.realize(state, Stage::Dynamics);
const Real vrel = std::abs(v/vt);
Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)/(1+vrel*vrel))+uv*std::fabs(v));
const Vec3 totalForce = Vec3(ff, fh, 0);
expectedForce = SpatialVec(Vec3(0), Vec3(0));
Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0/3.0, 0, 1.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);
Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0/3.0, 0, 2.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);
SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);
assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);
}
}
}
/**
* @brief This test compares the numerical result of a sphere
* in contact with a plane, using the elastic foundation
* model.
* The analytical solution of this problem is given by
* the product of the stiffness with the volume of
* the sphere in the plane, i.e the volume of a spherical
* cap.
* The volume of a spherical cap is:
* Vcap = Pi*h*h/3.0*(3.0*r-h)
* where
* r is the radis of the sphere
* h the height of the cap. In our case, the penetration
* depth
* @note If we want to go further, we can observe that doubling
* the penetration depth results in multiplying the normal
* effort by 4.
* This is different from Hertz theory, where doubling the
* penetration depth results in multiplying
* the normal effort by 2^(3/2)~2.68
*
*/
void testEffSphereOnPlaneOldFormulation(bool verbose = false);
void testEffSphereOnPlaneOldFormulation(bool verbose)
{
// Material properties for sphere
const Real stiffness = 1e9;
const Real dissipation = 0.0, us = 0.0, ud = 0.0, uv = 0.0, vt = 0.0;
// Sphere radius
const Real radius = 1.0;
// Define initial penetration
const Real initialPenetration = 0.002;
const int maxLevel = 6;
// Define some tolerances for each level in %
const Real tolerances[6]= {0.15, 0.07, 0.03, 0.02, 0.01, 0.02};
for (int i=0;i<maxLevel;++i)
{
// For each level, penetration is double
const Real penetration = initialPenetration * pow(2.0,(Real)i);
// Creation of the classical problem
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
const ContactSetIndex setIndex = contacts.createContactSet();
// Creation a sphere with 6 level of refinement
const PolygonalMesh sphereMesh(PolygonalMesh::createSphereMesh(radius, 6));
// Create the mobilized bodies and configure the contact model.
const Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
const MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(sphereMesh), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(),
Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0.0,penetration-radius,0.0))); // y < penetration-radius
ElasticFoundationForce ef(forces, contacts, setIndex);
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
const State state = system.realizeTopology();
system.realize(state, Stage::Dynamics);
const SpatialVec r = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
const Real volumeSphericalCap = Pi*penetration*penetration/3.0*(3.0*radius-penetration);
const Real theoreticalResult = stiffness*volumeSphericalCap;
const Real numericalResult = r[1][1];
const Real relativeDifference = abs((numericalResult/theoreticalResult)-1.0);
if (verbose) {
cout<<"Effort for penetration : "
<<penetration*1000.0<<" mm -> F = "<<numericalResult<<" N "
<<"(theoretical result : "<<theoreticalResult<< " N "
<<" relative difference : "<<100.0*relativeDifference<<" %)"<<endl;
}
ASSERT(abs((numericalResult/theoreticalResult)-1.0)<tolerances[i]);
}
}
int main() {
try {
testForces();
testEffSphereOnPlaneOldFormulation();
}
catch(const std::exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
<commit_msg>[master] Added testEffSphereOnPlaneNewFormulation test<commit_after>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include "SimTKsimbody.h"
using namespace SimTK;
using namespace std;
const Real TOL = 1e-5;
#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");}
template <class T>
void assertEqual(T val1, T val2) {
ASSERT(abs(val1-val2) < TOL || abs(val1-val2)/max(abs(val1), abs(val2)) < TOL);
}
template <int N>
void assertEqual(Vec<N> val1, Vec<N> val2) {
for (int i = 0; i < N; ++i)
assertEqual(val1[i], val2[i]);
}
void testForces() {
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
// Create a triangle mesh in the shape of a pyramid, with the
// square base having area 1 (split into two triangles).
vector<Vec3> vertices;
vertices.push_back(Vec3(0, 0, 0));
vertices.push_back(Vec3(1, 0, 0));
vertices.push_back(Vec3(1, 0, 1));
vertices.push_back(Vec3(0, 0, 1));
vertices.push_back(Vec3(0.5, 1, 0.5));
vector<int> faceIndices;
int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
{2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
// Create the mobilized bodies and configure the contact model.
Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
ContactSetIndex setIndex = contacts.createContactSet();
MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); // y < 0
ElasticFoundationForce ef(forces, contacts, setIndex);
Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
ASSERT(ef.getTransitionVelocity() == vt);
State state = system.realizeTopology();
// Position the pyramid at a variety of positions and check the normal
// force.
for (Real depth = -0.1; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
system.realize(state, Stage::Dynamics);
Real f = 0;
if (depth > 0)
f = stiffness*depth;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));
}
// Now do it with a vertical velocity and see if the dissipation force is correct.
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));
system.realize(state, Stage::Dynamics);
Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);
if (f < 0)
f = 0;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
}
}
// Do it with a horizontal velocity and see if the friction force is correct.
Vector_<SpatialVec> expectedForce(matter.getNumBodies());
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
Real fh = 0;
if (depth > 0)
fh = stiffness*depth;
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));
system.realize(state, Stage::Dynamics);
const Real vrel = std::abs(v/vt);
Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)/(1+vrel*vrel))+uv*std::fabs(v));
const Vec3 totalForce = Vec3(ff, fh, 0);
expectedForce = SpatialVec(Vec3(0), Vec3(0));
Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0/3.0, 0, 1.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);
Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0/3.0, 0, 2.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);
SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);
assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);
}
}
}
/**
* @brief This test compares the numerical result of a sphere
* in contact with a plane, using the elastic foundation
* model.
* The analytical solution of this problem is given by
* the product of the stiffness with the volume of
* the sphere in the plane, i.e the volume of a spherical
* cap.
* The volume of a spherical cap is:
* Vcap = Pi*h*h/3.0*(3.0*r-h)
* where
* r is the radis of the sphere
* h the height of the cap. In our case, the penetration
* depth
* @note If we want to go further, we can observe that doubling
* the penetration depth results in multiplying the normal
* effort by 4.
* This is different from Hertz theory, where doubling the
* penetration depth results in multiplying
* the normal effort by 2^(3/2)~2.68
*
*/
void testEffSphereOnPlaneOldFormulation(bool verbose = false);
void testEffSphereOnPlaneOldFormulation(bool verbose)
{
// Material properties for sphere
const Real stiffness = 1e9;
const Real dissipation = 0.0, us = 0.0, ud = 0.0, uv = 0.0, vt = 0.0;
// Sphere radius
const Real radius = 1.0;
// Define initial penetration
const Real initialPenetration = 0.002;
const int maxLevel = 6;
// Define some tolerances for each level in %
const Real tolerances[6]= {0.15, 0.07, 0.03, 0.02, 0.01, 0.02};
for (int i=0;i<maxLevel;++i)
{
// For each level, penetration is double
const Real penetration = initialPenetration * pow(2.0,(Real)i);
// Creation of the classical problem
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
const ContactSetIndex setIndex = contacts.createContactSet();
// Creation a sphere with 6 level of refinement
const PolygonalMesh sphereMesh(PolygonalMesh::createSphereMesh(radius, 6));
// Create the mobilized bodies and configure the contact model.
const Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
const MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(sphereMesh), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(),
Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0.0,penetration-radius,0.0))); // y < penetration-radius
ElasticFoundationForce ef(forces, contacts, setIndex);
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
const State state = system.realizeTopology();
system.realize(state, Stage::Dynamics);
const SpatialVec r = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
const Real volumeSphericalCap = Pi*penetration*penetration/3.0*(3.0*radius-penetration);
const Real theoreticalResult = stiffness*volumeSphericalCap;
const Real numericalResult = r[1][1];
const Real relativeDifference = abs((numericalResult/theoreticalResult)-1.0);
if (verbose) {
cout<<"Effort for penetration : "
<<penetration*1000.0<<" mm -> F = "<<numericalResult<<" N "
<<"(theoretical result : "<<theoreticalResult<< " N "
<<" relative difference : "<<100.0*relativeDifference<<" %)"<<endl;
}
ASSERT(abs((numericalResult/theoreticalResult)-1.0)<tolerances[i]);
}
}
void testEffSphereOnPlaneNewFormulation(bool verbose = false);
void testEffSphereOnPlaneNewFormulation(bool verbose)
{
// Material properties for sphere
// Global stiffness of the contact: each material will have
// twice this stiffness to obtain this global stiffness in the contact
// 1/kG = 1/k1 + 1/k2
const Real stiffness = 1e9;
const Real dissipation = 0.0, us = 0.0, ud = 0.0, uv = 0.0;
const Real vt = 1.0e-2;
// Sphere radius
const Real radius = 1.0;
// Define initial penetration
const Real initialPenetration = 0.002;
const int maxLevel = 6;
// Define some tolerances for each level in %
const Real tolerances[6]= {0.15, 0.07, 0.03, 0.02, 0.01, 0.02};
for (int i=0;i<maxLevel;++i)
{
// For each level, penetration is double
const Real penetration = initialPenetration * pow(2.0,(Real)i);
// Creation of the classical problem
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
ContactTrackerSubsystem tracker(system);
CompliantContactSubsystem contactForces(system, tracker);
contactForces.setTransitionVelocity(vt);
matter.Ground().updBody().addContactSurface(
Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0.0,penetration-radius,0.0)), // y < penetration-radius
ContactSurface(ContactGeometry::HalfSpace(),
ContactMaterial(2.0*stiffness, dissipation, us, ud, uv),
1.0));
Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
body.addContactSurface(Transform(),
ContactSurface(ContactGeometry::TriangleMesh(PolygonalMesh::createSphereMesh(radius, 6)),
ContactMaterial(2.0*stiffness, dissipation, us, ud, uv),
1.0));
const MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
const State state = system.realizeTopology();
system.realize(state, Stage::Dynamics);
if (verbose) {
cout << "Num contacts: " << contactForces.getNumContactForces(state) << endl;
}
ASSERT(contactForces.getNumContactForces(state)==1);
const ContactForce& force = contactForces.getContactForce(state,0);
const Vec3& frc = force.getForceOnSurface2()[1];
const Real numericalResult = frc[1];
const Real volumeSphericalCap = Pi*penetration*penetration/3.0*(3.0*radius-penetration);
const Real theoreticalResult = stiffness*volumeSphericalCap;
const Real relativeDifference = abs((numericalResult/theoreticalResult)-1.0);
if (verbose) {
cout<<force;
cout<<"Effort for penetration : "
<<penetration*1000.0<<" mm -> F = "<<numericalResult<<" N "
<<"(theoretical result : "<<theoreticalResult<< " N "
<<" relative difference : "<<100.0*relativeDifference<<" %)"<<endl;
}
ASSERT(abs((numericalResult/theoreticalResult)-1.0)<tolerances[i]);
}
}
int main() {
try {
testForces();
testEffSphereOnPlaneOldFormulation();
testEffSphereOnPlaneNewFormulation();
}
catch(const std::exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "wifi_utils.h"
WifiState wifiState = WIFI_DISCONNECTED;
const char * system_event_reasons1[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT" };
#define reason2str(r) ((r>176)?system_event_reasons1[r-176]:system_event_reasons1[r-1])
ServerCondition::ServerCondition(ServerError err){
error = err;
numberOfTimeouts = 0;
}
void ServerCondition::resetError(){
error = NO_ERROR;
numberOfTimeouts = 0;
}
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
uint8_t* reason;
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
LOGD(WIFI_U, "Wifi STA started.");
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_STOP:
LOGD(WIFI_U, "Wifi STA stopped.");
break;
case SYSTEM_EVENT_STA_CONNECTED:
LOGD(WIFI_U, "Wifi connected.");
break;
case SYSTEM_EVENT_STA_GOT_IP:
LOGI(WIFI_U, "Wifi got ip %s.",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
wifiState = WIFI_CONNECTED;
break;
case SYSTEM_EVENT_STA_LOST_IP:
LOGD(WIFI_U, "Wifi lost ip.");
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
LOGD(WIFI_U, "WiFi disconnected. ");
reason = &event->event_info.disconnected.reason;
LOGD(WIFI_U, " Reason %u: %s\n", *reason, reason2str(*reason));
wifi_stop_sta();
wifiState = WIFI_DISCONNECTED;
break;
default:
LOGW(WIFI_U, "Unhandled wifi event with ID %d\n", event->event_id);
break;
}
return ESP_OK;
}
bool wifi_init() {
LOGI(WIFI_U, "Init event loop...");
esp_err_t err = esp_event_loop_init(event_handler, NULL);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init event loop. Error: %s", esp_err_to_name(err));
return false;
}
LOGI(WIFI_U, "Init TCPIP...");
tcpip_adapter_init();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init wifi. Error: %s", esp_err_to_name(err));
return false;
}
err = esp_wifi_set_storage(WIFI_STORAGE_FLASH);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi storage. Error: %s", esp_err_to_name(err));
return false;
}
err = esp_wifi_set_mode(WIFI_MODE_STA);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi sta mode. Error: %s", esp_err_to_name(err));
return false;
}
return true;
}
bool wifi_start_sta(String ssid, String password,
IPAddress ip, IPAddress gateway, IPAddress subnet)
{
LOGI(WIFI_U, "Init Wifi...");
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_err_t err;
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init wifi. Error: %s", esp_err_to_name(err));
return false;
}
tcpip_adapter_ip_info_t info;
info.ip.addr = static_cast<uint32_t>(ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
LOGI(WIFI_U, "Configuring Wifi with SSID:%s...\n", ssid.c_str());
wifi_config_t sta_config = { };
strcpy((char*)sta_config.sta.ssid, ssid.c_str());
strcpy((char*)sta_config.sta.password, password.c_str());
sta_config.sta.bssid_set = false;
err = esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi config. Error: %s", esp_err_to_name(err));
return false;
}
LOGI(WIFI_U, "Starting Wifi...");
err = esp_wifi_start();
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot start wifi. Error: %s", esp_err_to_name(err));
return false;
}
err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
if (err != ESP_OK && err != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED){
LOGE(WIFI_U, "DHCP could not be stopped! Error: %s", esp_err_to_name(err));
return false;
}
err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info);
if (err != ESP_OK) {
LOGE(WIFI_U, "STA IP could not be configured! Error:%s", esp_err_to_name(err));
return false;
}
LOGI(WIFI_U, "End of wifi_start_sta.");
return true;
}
void wifi_disconnect() {
LOGI(WIFI_U, "Disconnecting Wifi...");
esp_err_t err = esp_wifi_disconnect();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem disconnecting from wifi. Error:%s", esp_err_to_name(err));
}
}
void wifi_stop_sta() {
LOGI(WIFI_U, "Stopping Wifi...");
esp_err_t err = esp_wifi_stop();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem stopping wifi. Error:%s", esp_err_to_name(err));
}
/*
LOGI(WIFI_U, "Deinitializing Wifi...");
err = esp_wifi_deinit();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem deinit wifi. Error:%s", esp_err_to_name(err));
} */
wifiState = WIFI_DISCONNECTED;
LOGI(WIFI_U, "End of wifi_stop_sta.");
}
String wiFiStateToString(){
switch(wifiState){
case WIFI_DISCONNECTED:
return String("UNCONFIGURED");
case WIFI_CONNECTED:
return String("WIFI_CONNECTED");
}
return String("UNKNOWN WiFi STATE");
}
String serverStateToString(ServerState state){
switch(state){
case UNCONFIGURED:
return String( "UNCONFIGURED");
case CONNECTED:
return String("CONNECTED");
case SERVER_LISTENING:
return String("SERVER_LISTENING");
case CLIENT_CONNECTED:
return String("CLIENT_CONNECTED");
case DATA_AVAILABLE:
return String("DATA_AVAILABLE");
default:
return String("UNKNOWN_STATE");
}
return String("UNKNOWN_STATE");
}
ServerState getNextServerStateUp(ServerState state) {
switch(state){
case UNCONFIGURED:
return CONNECTED;
case CONNECTED:
return SERVER_LISTENING;
case SERVER_LISTENING:
return CLIENT_CONNECTED;
case CLIENT_CONNECTED:
return DATA_AVAILABLE;
case DATA_AVAILABLE:
return DATA_AVAILABLE;
default:
return state;
}
}
ServerState getNextServerStateDown(ServerState state) {
switch(state){
case DATA_AVAILABLE:
return CLIENT_CONNECTED;
case CLIENT_CONNECTED:
return SERVER_LISTENING;
case SERVER_LISTENING:
return CONNECTED;
case CONNECTED:
return UNCONFIGURED;
case UNCONFIGURED:
return UNCONFIGURED;
default:
return state;
}
}
String Transition::toString(){
if (isEmptyTransition()) {
return String("No action");
}
else {
char buffer[40];
snprintf(buffer, 40, "%s --> %s",
serverStateToString(from).c_str(), serverStateToString(to).c_str());
return String(buffer);
}
}
<commit_msg>reduce logging level<commit_after>#include "wifi_utils.h"
WifiState wifiState = WIFI_DISCONNECTED;
const char * system_event_reasons1[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT" };
#define reason2str(r) ((r>176)?system_event_reasons1[r-176]:system_event_reasons1[r-1])
ServerCondition::ServerCondition(ServerError err){
error = err;
numberOfTimeouts = 0;
}
void ServerCondition::resetError(){
error = NO_ERROR;
numberOfTimeouts = 0;
}
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
uint8_t* reason;
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
LOGD(WIFI_U, "Wifi STA started.");
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_STOP:
LOGD(WIFI_U, "Wifi STA stopped.");
break;
case SYSTEM_EVENT_STA_CONNECTED:
LOGD(WIFI_U, "Wifi connected.");
break;
case SYSTEM_EVENT_STA_GOT_IP:
LOGI(WIFI_U, "Wifi got ip %s.",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
wifiState = WIFI_CONNECTED;
break;
case SYSTEM_EVENT_STA_LOST_IP:
LOGD(WIFI_U, "Wifi lost ip.");
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
LOGD(WIFI_U, "WiFi disconnected. ");
reason = &event->event_info.disconnected.reason;
LOGD(WIFI_U, " Reason %u: %s\n", *reason, reason2str(*reason));
wifi_stop_sta();
wifiState = WIFI_DISCONNECTED;
break;
default:
LOGW(WIFI_U, "Unhandled wifi event with ID %d\n", event->event_id);
break;
}
return ESP_OK;
}
bool wifi_init() {
LOGI(WIFI_U, "Init event loop...");
esp_err_t err = esp_event_loop_init(event_handler, NULL);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init event loop. Error: %s", esp_err_to_name(err));
return false;
}
LOGI(WIFI_U, "Init TCPIP...");
tcpip_adapter_init();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init wifi. Error: %s", esp_err_to_name(err));
return false;
}
err = esp_wifi_set_storage(WIFI_STORAGE_FLASH);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi storage. Error: %s", esp_err_to_name(err));
return false;
}
err = esp_wifi_set_mode(WIFI_MODE_STA);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi sta mode. Error: %s", esp_err_to_name(err));
return false;
}
return true;
}
bool wifi_start_sta(String ssid, String password,
IPAddress ip, IPAddress gateway, IPAddress subnet)
{
LOGI(WIFI_U, "Init Wifi...");
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_err_t err;
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot init wifi. Error: %s", esp_err_to_name(err));
return false;
}
tcpip_adapter_ip_info_t info;
info.ip.addr = static_cast<uint32_t>(ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
LOGI(WIFI_U, "Configuring Wifi with SSID:%s...\n", ssid.c_str());
wifi_config_t sta_config = { };
strcpy((char*)sta_config.sta.ssid, ssid.c_str());
strcpy((char*)sta_config.sta.password, password.c_str());
sta_config.sta.bssid_set = false;
err = esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config);
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot set wifi config. Error: %s", esp_err_to_name(err));
return false;
}
LOGI(WIFI_U, "Starting Wifi...");
err = esp_wifi_start();
if (err != ESP_OK) {
LOGE(WIFI_U, "Cannot start wifi. Error: %s", esp_err_to_name(err));
return false;
}
err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
if (err != ESP_OK && err != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED){
LOGE(WIFI_U, "DHCP could not be stopped! Error: %s", esp_err_to_name(err));
return false;
}
err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info);
if (err != ESP_OK) {
LOGE(WIFI_U, "STA IP could not be configured! Error:%s", esp_err_to_name(err));
return false;
}
LOGD(WIFI_U, "End of wifi_start_sta.");
return true;
}
void wifi_disconnect() {
LOGI(WIFI_U, "Disconnecting Wifi...");
esp_err_t err = esp_wifi_disconnect();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem disconnecting from wifi. Error:%s", esp_err_to_name(err));
}
}
void wifi_stop_sta() {
LOGI(WIFI_U, "Stopping Wifi...");
esp_err_t err = esp_wifi_stop();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem stopping wifi. Error:%s", esp_err_to_name(err));
}
/*
LOGI(WIFI_U, "Deinitializing Wifi...");
err = esp_wifi_deinit();
if (err != ESP_OK) {
LOGW(WIFI_U, "Problem deinit wifi. Error:%s", esp_err_to_name(err));
} */
wifiState = WIFI_DISCONNECTED;
LOGI(WIFI_U, "End of wifi_stop_sta.");
}
String wiFiStateToString(){
switch(wifiState){
case WIFI_DISCONNECTED:
return String("UNCONFIGURED");
case WIFI_CONNECTED:
return String("WIFI_CONNECTED");
}
return String("UNKNOWN WiFi STATE");
}
String serverStateToString(ServerState state){
switch(state){
case UNCONFIGURED:
return String( "UNCONFIGURED");
case CONNECTED:
return String("CONNECTED");
case SERVER_LISTENING:
return String("SERVER_LISTENING");
case CLIENT_CONNECTED:
return String("CLIENT_CONNECTED");
case DATA_AVAILABLE:
return String("DATA_AVAILABLE");
default:
return String("UNKNOWN_STATE");
}
return String("UNKNOWN_STATE");
}
ServerState getNextServerStateUp(ServerState state) {
switch(state){
case UNCONFIGURED:
return CONNECTED;
case CONNECTED:
return SERVER_LISTENING;
case SERVER_LISTENING:
return CLIENT_CONNECTED;
case CLIENT_CONNECTED:
return DATA_AVAILABLE;
case DATA_AVAILABLE:
return DATA_AVAILABLE;
default:
return state;
}
}
ServerState getNextServerStateDown(ServerState state) {
switch(state){
case DATA_AVAILABLE:
return CLIENT_CONNECTED;
case CLIENT_CONNECTED:
return SERVER_LISTENING;
case SERVER_LISTENING:
return CONNECTED;
case CONNECTED:
return UNCONFIGURED;
case UNCONFIGURED:
return UNCONFIGURED;
default:
return state;
}
}
String Transition::toString(){
if (isEmptyTransition()) {
return String("No action");
}
else {
char buffer[40];
snprintf(buffer, 40, "%s --> %s",
serverStateToString(from).c_str(), serverStateToString(to).c_str());
return String(buffer);
}
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/Fields/AlignMeshBoundingBoxes.h>
using namespace SCIRun;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Dataflow::Networks;
AlignMeshBoundingBoxes::AlignMeshBoundingBoxes() :
Module(ModuleLookupInfo("AlignMeshBoundingBoxes", "ChangeMesh", "SCIRun"), false)
{
}
void AlignMeshBoundingBoxes::execute()
{
FieldHandle ifield = getRequiredInput(InputField);
FieldHandle objfield = getRequiredInput(AlignmentField);
// inputs_changed_ || !oport_cached("Output") || !oport_cached("Transform")
if (needToExecute())
{
// Inform module that execution started
update_state(Executing);
// Core algorithm of the module
if(!(algo_.run(ifield,objfield,ofield,omatrix))) return;
// Send output to output ports
send_output_handle("Output", ofield);
send_output_handle("Transform", omatrix);
}
}
<commit_msg>Initialize ports<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/Fields/AlignMeshBoundingBoxes.h>
using namespace SCIRun;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Dataflow::Networks;
AlignMeshBoundingBoxes::AlignMeshBoundingBoxes() :
Module(ModuleLookupInfo("AlignMeshBoundingBoxes", "ChangeMesh", "SCIRun"), false)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(AlignmentField);
INITIALIZE_PORT(OutputField);
INITIALIZE_PORT(TransformMatrix);
}
void AlignMeshBoundingBoxes::execute()
{
FieldHandle ifield = getRequiredInput(InputField);
FieldHandle objfield = getRequiredInput(AlignmentField);
// inputs_changed_ || !oport_cached("Output") || !oport_cached("Transform")
if (needToExecute())
{
// Inform module that execution started
update_state(Executing);
// Core algorithm of the module
if(!(algo_.run(ifield,objfield,ofield,omatrix))) return;
// Send output to output ports
send_output_handle("Output", ofield);
send_output_handle("Transform", omatrix);
}
}
<|endoftext|>
|
<commit_before>//===----- R600Packetizer.cpp - VLIW packetizer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass implements instructions packetization for R600. It unsets isLast
/// bit of instructions inside a bundle and substitutes src register with
/// PreviousVector when applicable.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "packets"
#include "llvm/Support/Debug.h"
#include "AMDGPU.h"
#include "R600InstrInfo.h"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class R600Packetizer : public MachineFunctionPass {
public:
static char ID;
R600Packetizer(const TargetMachine &TM) : MachineFunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
const char *getPassName() const {
return "R600 Packetizer";
}
bool runOnMachineFunction(MachineFunction &Fn);
};
char R600Packetizer::ID = 0;
class R600PacketizerList : public VLIWPacketizerList {
private:
const R600InstrInfo *TII;
const R600RegisterInfo &TRI;
unsigned getSlot(const MachineInstr *MI) const {
return TRI.getHWRegChan(MI->getOperand(0).getReg());
}
/// \returns register to PV chan mapping for bundle/single instructions that
/// immediatly precedes I.
DenseMap<unsigned, unsigned> getPreviousVector(MachineBasicBlock::iterator I)
const {
DenseMap<unsigned, unsigned> Result;
I--;
if (!TII->isALUInstr(I->getOpcode()) && !I->isBundle())
return Result;
MachineBasicBlock::instr_iterator BI = I.getInstrIterator();
if (I->isBundle())
BI++;
do {
if (TII->isPredicated(BI))
continue;
if (TII->isTransOnly(BI))
continue;
int OperandIdx = TII->getOperandIdx(BI->getOpcode(), R600Operands::WRITE);
if (OperandIdx < 0)
continue;
if (BI->getOperand(OperandIdx).getImm() == 0)
continue;
unsigned Dst = BI->getOperand(0).getReg();
if (BI->getOpcode() == AMDGPU::DOT4_r600 ||
BI->getOpcode() == AMDGPU::DOT4_eg) {
Result[Dst] = AMDGPU::PV_X;
continue;
}
unsigned PVReg = 0;
switch (TRI.getHWRegChan(Dst)) {
case 0:
PVReg = AMDGPU::PV_X;
break;
case 1:
PVReg = AMDGPU::PV_Y;
break;
case 2:
PVReg = AMDGPU::PV_Z;
break;
case 3:
PVReg = AMDGPU::PV_W;
break;
default:
llvm_unreachable("Invalid Chan");
}
Result[Dst] = PVReg;
} while ((++BI)->isBundledWithPred());
return Result;
}
void substitutePV(MachineInstr *MI, const DenseMap<unsigned, unsigned> &PVs)
const {
R600Operands::Ops Ops[] = {
R600Operands::SRC0,
R600Operands::SRC1,
R600Operands::SRC2
};
for (unsigned i = 0; i < 3; i++) {
int OperandIdx = TII->getOperandIdx(MI->getOpcode(), Ops[i]);
if (OperandIdx < 0)
continue;
unsigned Src = MI->getOperand(OperandIdx).getReg();
const DenseMap<unsigned, unsigned>::const_iterator It = PVs.find(Src);
if (It != PVs.end())
MI->getOperand(OperandIdx).setReg(It->second);
}
}
public:
// Ctor.
R600PacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,
MachineDominatorTree &MDT)
: VLIWPacketizerList(MF, MLI, MDT, true),
TII (static_cast<const R600InstrInfo *>(MF.getTarget().getInstrInfo())),
TRI(TII->getRegisterInfo()) { }
// initPacketizerState - initialize some internal flags.
void initPacketizerState() { }
// ignorePseudoInstruction - Ignore bundling of pseudo instructions.
bool ignorePseudoInstruction(MachineInstr *MI, MachineBasicBlock *MBB) {
return false;
}
// isSoloInstruction - return true if instruction MI can not be packetized
// with any other instruction, which means that MI itself is a packet.
bool isSoloInstruction(MachineInstr *MI) {
if (TII->isVector(*MI))
return true;
if (!TII->isALUInstr(MI->getOpcode()))
return true;
if (TII->get(MI->getOpcode()).TSFlags & R600_InstFlag::TRANS_ONLY)
return true;
if (TII->isTransOnly(MI))
return true;
return false;
}
// isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
// together.
bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
MachineInstr *MII = SUI->getInstr(), *MIJ = SUJ->getInstr();
if (getSlot(MII) <= getSlot(MIJ))
return false;
// Does MII and MIJ share the same pred_sel ?
int OpI = TII->getOperandIdx(MII->getOpcode(), R600Operands::PRED_SEL),
OpJ = TII->getOperandIdx(MIJ->getOpcode(), R600Operands::PRED_SEL);
unsigned PredI = (OpI > -1)?MII->getOperand(OpI).getReg():0,
PredJ = (OpJ > -1)?MIJ->getOperand(OpJ).getReg():0;
if (PredI != PredJ)
return false;
if (SUJ->isSucc(SUI)) {
for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {
const SDep &Dep = SUJ->Succs[i];
if (Dep.getSUnit() != SUI)
continue;
if (Dep.getKind() == SDep::Anti)
continue;
if (Dep.getKind() == SDep::Output)
if (MII->getOperand(0).getReg() != MIJ->getOperand(0).getReg())
continue;
return false;
}
}
return true;
}
// isLegalToPruneDependencies - Is it legal to prune dependece between SUI
// and SUJ.
bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {return false;}
void setIsLastBit(MachineInstr *MI, unsigned Bit) const {
unsigned LastOp = TII->getOperandIdx(MI->getOpcode(), R600Operands::LAST);
MI->getOperand(LastOp).setImm(Bit);
}
MachineBasicBlock::iterator addToPacket(MachineInstr *MI) {
CurrentPacketMIs.push_back(MI);
bool FitsConstLimits = TII->canBundle(CurrentPacketMIs);
DEBUG(
if (!FitsConstLimits) {
dbgs() << "Couldn't pack :\n";
MI->dump();
dbgs() << "with the following packets :\n";
for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
CurrentPacketMIs[i]->dump();
dbgs() << "\n";
}
dbgs() << "because of Consts read limitations\n";
});
const DenseMap<unsigned, unsigned> &PV =
getPreviousVector(CurrentPacketMIs.front());
std::vector<R600InstrInfo::BankSwizzle> BS;
bool FitsReadPortLimits =
TII->fitsReadPortLimitations(CurrentPacketMIs, PV, BS);
DEBUG(
if (!FitsReadPortLimits) {
dbgs() << "Couldn't pack :\n";
MI->dump();
dbgs() << "with the following packets :\n";
for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
CurrentPacketMIs[i]->dump();
dbgs() << "\n";
}
dbgs() << "because of Read port limitations\n";
});
bool isBundlable = FitsConstLimits && FitsReadPortLimits;
if (isBundlable) {
for (unsigned i = 0, e = CurrentPacketMIs.size(); i < e; i++) {
MachineInstr *MI = CurrentPacketMIs[i];
unsigned Op = TII->getOperandIdx(MI->getOpcode(),
R600Operands::BANK_SWIZZLE);
MI->getOperand(Op).setImm(BS[i]);
}
}
CurrentPacketMIs.pop_back();
if (!isBundlable) {
endPacket(MI->getParent(), MI);
substitutePV(MI, getPreviousVector(MI));
return VLIWPacketizerList::addToPacket(MI);
}
if (!CurrentPacketMIs.empty())
setIsLastBit(CurrentPacketMIs.back(), 0);
substitutePV(MI, PV);
return VLIWPacketizerList::addToPacket(MI);
}
};
bool R600Packetizer::runOnMachineFunction(MachineFunction &Fn) {
const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
// Instantiate the packetizer.
R600PacketizerList Packetizer(Fn, MLI, MDT);
// DFA state table should not be empty.
assert(Packetizer.getResourceTracker() && "Empty DFA table!");
//
// Loop over all basic blocks and remove KILL pseudo-instructions
// These instructions confuse the dependence analysis. Consider:
// D0 = ... (Insn 0)
// R0 = KILL R0, D0 (Insn 1)
// R0 = ... (Insn 2)
// Here, Insn 1 will result in the dependence graph not emitting an output
// dependence between Insn 0 and Insn 2. This can lead to incorrect
// packetization
//
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
MachineBasicBlock::iterator End = MBB->end();
MachineBasicBlock::iterator MI = MBB->begin();
while (MI != End) {
if (MI->isKill()) {
MachineBasicBlock::iterator DeleteMI = MI;
++MI;
MBB->erase(DeleteMI);
End = MBB->end();
continue;
}
++MI;
}
}
// Loop over all of the basic blocks.
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
// Find scheduling regions and schedule / packetize each region.
unsigned RemainingCount = MBB->size();
for(MachineBasicBlock::iterator RegionEnd = MBB->end();
RegionEnd != MBB->begin();) {
// The next region starts above the previous region. Look backward in the
// instruction stream until we find the nearest boundary.
MachineBasicBlock::iterator I = RegionEnd;
for(;I != MBB->begin(); --I, --RemainingCount) {
if (TII->isSchedulingBoundary(llvm::prior(I), MBB, Fn))
break;
}
I = MBB->begin();
// Skip empty scheduling regions.
if (I == RegionEnd) {
RegionEnd = llvm::prior(RegionEnd);
--RemainingCount;
continue;
}
// Skip regions with one instruction.
if (I == llvm::prior(RegionEnd)) {
RegionEnd = llvm::prior(RegionEnd);
continue;
}
Packetizer.PacketizeMIs(MBB, I, RegionEnd);
RegionEnd = I;
}
}
return true;
}
} // end anonymous namespace
llvm::FunctionPass *llvm::createR600Packetizer(TargetMachine &tm) {
return new R600Packetizer(tm);
}
<commit_msg>R600: 3 op instructions have no write bit but the result are store in PV<commit_after>//===----- R600Packetizer.cpp - VLIW packetizer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass implements instructions packetization for R600. It unsets isLast
/// bit of instructions inside a bundle and substitutes src register with
/// PreviousVector when applicable.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "packets"
#include "llvm/Support/Debug.h"
#include "AMDGPU.h"
#include "R600InstrInfo.h"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class R600Packetizer : public MachineFunctionPass {
public:
static char ID;
R600Packetizer(const TargetMachine &TM) : MachineFunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
const char *getPassName() const {
return "R600 Packetizer";
}
bool runOnMachineFunction(MachineFunction &Fn);
};
char R600Packetizer::ID = 0;
class R600PacketizerList : public VLIWPacketizerList {
private:
const R600InstrInfo *TII;
const R600RegisterInfo &TRI;
unsigned getSlot(const MachineInstr *MI) const {
return TRI.getHWRegChan(MI->getOperand(0).getReg());
}
/// \returns register to PV chan mapping for bundle/single instructions that
/// immediatly precedes I.
DenseMap<unsigned, unsigned> getPreviousVector(MachineBasicBlock::iterator I)
const {
DenseMap<unsigned, unsigned> Result;
I--;
if (!TII->isALUInstr(I->getOpcode()) && !I->isBundle())
return Result;
MachineBasicBlock::instr_iterator BI = I.getInstrIterator();
if (I->isBundle())
BI++;
do {
if (TII->isPredicated(BI))
continue;
if (TII->isTransOnly(BI))
continue;
int OperandIdx = TII->getOperandIdx(BI->getOpcode(), R600Operands::WRITE);
if (OperandIdx > -1 && BI->getOperand(OperandIdx).getImm() == 0)
continue;
unsigned Dst = BI->getOperand(0).getReg();
if (BI->getOpcode() == AMDGPU::DOT4_r600 ||
BI->getOpcode() == AMDGPU::DOT4_eg) {
Result[Dst] = AMDGPU::PV_X;
continue;
}
unsigned PVReg = 0;
switch (TRI.getHWRegChan(Dst)) {
case 0:
PVReg = AMDGPU::PV_X;
break;
case 1:
PVReg = AMDGPU::PV_Y;
break;
case 2:
PVReg = AMDGPU::PV_Z;
break;
case 3:
PVReg = AMDGPU::PV_W;
break;
default:
llvm_unreachable("Invalid Chan");
}
Result[Dst] = PVReg;
} while ((++BI)->isBundledWithPred());
return Result;
}
void substitutePV(MachineInstr *MI, const DenseMap<unsigned, unsigned> &PVs)
const {
R600Operands::Ops Ops[] = {
R600Operands::SRC0,
R600Operands::SRC1,
R600Operands::SRC2
};
for (unsigned i = 0; i < 3; i++) {
int OperandIdx = TII->getOperandIdx(MI->getOpcode(), Ops[i]);
if (OperandIdx < 0)
continue;
unsigned Src = MI->getOperand(OperandIdx).getReg();
const DenseMap<unsigned, unsigned>::const_iterator It = PVs.find(Src);
if (It != PVs.end())
MI->getOperand(OperandIdx).setReg(It->second);
}
}
public:
// Ctor.
R600PacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,
MachineDominatorTree &MDT)
: VLIWPacketizerList(MF, MLI, MDT, true),
TII (static_cast<const R600InstrInfo *>(MF.getTarget().getInstrInfo())),
TRI(TII->getRegisterInfo()) { }
// initPacketizerState - initialize some internal flags.
void initPacketizerState() { }
// ignorePseudoInstruction - Ignore bundling of pseudo instructions.
bool ignorePseudoInstruction(MachineInstr *MI, MachineBasicBlock *MBB) {
return false;
}
// isSoloInstruction - return true if instruction MI can not be packetized
// with any other instruction, which means that MI itself is a packet.
bool isSoloInstruction(MachineInstr *MI) {
if (TII->isVector(*MI))
return true;
if (!TII->isALUInstr(MI->getOpcode()))
return true;
if (TII->get(MI->getOpcode()).TSFlags & R600_InstFlag::TRANS_ONLY)
return true;
if (TII->isTransOnly(MI))
return true;
return false;
}
// isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ
// together.
bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
MachineInstr *MII = SUI->getInstr(), *MIJ = SUJ->getInstr();
if (getSlot(MII) <= getSlot(MIJ))
return false;
// Does MII and MIJ share the same pred_sel ?
int OpI = TII->getOperandIdx(MII->getOpcode(), R600Operands::PRED_SEL),
OpJ = TII->getOperandIdx(MIJ->getOpcode(), R600Operands::PRED_SEL);
unsigned PredI = (OpI > -1)?MII->getOperand(OpI).getReg():0,
PredJ = (OpJ > -1)?MIJ->getOperand(OpJ).getReg():0;
if (PredI != PredJ)
return false;
if (SUJ->isSucc(SUI)) {
for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {
const SDep &Dep = SUJ->Succs[i];
if (Dep.getSUnit() != SUI)
continue;
if (Dep.getKind() == SDep::Anti)
continue;
if (Dep.getKind() == SDep::Output)
if (MII->getOperand(0).getReg() != MIJ->getOperand(0).getReg())
continue;
return false;
}
}
return true;
}
// isLegalToPruneDependencies - Is it legal to prune dependece between SUI
// and SUJ.
bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {return false;}
void setIsLastBit(MachineInstr *MI, unsigned Bit) const {
unsigned LastOp = TII->getOperandIdx(MI->getOpcode(), R600Operands::LAST);
MI->getOperand(LastOp).setImm(Bit);
}
MachineBasicBlock::iterator addToPacket(MachineInstr *MI) {
CurrentPacketMIs.push_back(MI);
bool FitsConstLimits = TII->canBundle(CurrentPacketMIs);
DEBUG(
if (!FitsConstLimits) {
dbgs() << "Couldn't pack :\n";
MI->dump();
dbgs() << "with the following packets :\n";
for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
CurrentPacketMIs[i]->dump();
dbgs() << "\n";
}
dbgs() << "because of Consts read limitations\n";
});
const DenseMap<unsigned, unsigned> &PV =
getPreviousVector(CurrentPacketMIs.front());
std::vector<R600InstrInfo::BankSwizzle> BS;
bool FitsReadPortLimits =
TII->fitsReadPortLimitations(CurrentPacketMIs, PV, BS);
DEBUG(
if (!FitsReadPortLimits) {
dbgs() << "Couldn't pack :\n";
MI->dump();
dbgs() << "with the following packets :\n";
for (unsigned i = 0, e = CurrentPacketMIs.size() - 1; i < e; i++) {
CurrentPacketMIs[i]->dump();
dbgs() << "\n";
}
dbgs() << "because of Read port limitations\n";
});
bool isBundlable = FitsConstLimits && FitsReadPortLimits;
if (isBundlable) {
for (unsigned i = 0, e = CurrentPacketMIs.size(); i < e; i++) {
MachineInstr *MI = CurrentPacketMIs[i];
unsigned Op = TII->getOperandIdx(MI->getOpcode(),
R600Operands::BANK_SWIZZLE);
MI->getOperand(Op).setImm(BS[i]);
}
}
CurrentPacketMIs.pop_back();
if (!isBundlable) {
endPacket(MI->getParent(), MI);
substitutePV(MI, getPreviousVector(MI));
return VLIWPacketizerList::addToPacket(MI);
}
if (!CurrentPacketMIs.empty())
setIsLastBit(CurrentPacketMIs.back(), 0);
substitutePV(MI, PV);
return VLIWPacketizerList::addToPacket(MI);
}
};
bool R600Packetizer::runOnMachineFunction(MachineFunction &Fn) {
const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
// Instantiate the packetizer.
R600PacketizerList Packetizer(Fn, MLI, MDT);
// DFA state table should not be empty.
assert(Packetizer.getResourceTracker() && "Empty DFA table!");
//
// Loop over all basic blocks and remove KILL pseudo-instructions
// These instructions confuse the dependence analysis. Consider:
// D0 = ... (Insn 0)
// R0 = KILL R0, D0 (Insn 1)
// R0 = ... (Insn 2)
// Here, Insn 1 will result in the dependence graph not emitting an output
// dependence between Insn 0 and Insn 2. This can lead to incorrect
// packetization
//
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
MachineBasicBlock::iterator End = MBB->end();
MachineBasicBlock::iterator MI = MBB->begin();
while (MI != End) {
if (MI->isKill()) {
MachineBasicBlock::iterator DeleteMI = MI;
++MI;
MBB->erase(DeleteMI);
End = MBB->end();
continue;
}
++MI;
}
}
// Loop over all of the basic blocks.
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
// Find scheduling regions and schedule / packetize each region.
unsigned RemainingCount = MBB->size();
for(MachineBasicBlock::iterator RegionEnd = MBB->end();
RegionEnd != MBB->begin();) {
// The next region starts above the previous region. Look backward in the
// instruction stream until we find the nearest boundary.
MachineBasicBlock::iterator I = RegionEnd;
for(;I != MBB->begin(); --I, --RemainingCount) {
if (TII->isSchedulingBoundary(llvm::prior(I), MBB, Fn))
break;
}
I = MBB->begin();
// Skip empty scheduling regions.
if (I == RegionEnd) {
RegionEnd = llvm::prior(RegionEnd);
--RemainingCount;
continue;
}
// Skip regions with one instruction.
if (I == llvm::prior(RegionEnd)) {
RegionEnd = llvm::prior(RegionEnd);
continue;
}
Packetizer.PacketizeMIs(MBB, I, RegionEnd);
RegionEnd = I;
}
}
return true;
}
} // end anonymous namespace
llvm::FunctionPass *llvm::createR600Packetizer(TargetMachine &tm) {
return new R600Packetizer(tm);
}
<|endoftext|>
|
<commit_before>//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines the pass that looks through the machine instructions
/// late in the compilation, and finds byte or word instructions that
/// can be profitably replaced with 32 bit instructions that give equivalent
/// results for the bits of the results that are used. There are two possible
/// reasons to do this.
///
/// One reason is to avoid false-dependences on the upper portions
/// of the registers. Only instructions that have a destination register
/// which is not in any of the source registers can be affected by this.
/// Any instruction where one of the source registers is also the destination
/// register is unaffected, because it has a true dependence on the source
/// register already. So, this consideration primarily affects load
/// instructions and register-to-register moves. It would
/// seem like cmov(s) would also be affected, but because of the way cmov is
/// really implemented by most machines as reading both the destination and
/// and source regsters, and then "merging" the two based on a condition,
/// it really already should be considered as having a true dependence on the
/// destination register as well.
///
/// The other reason to do this is for potential code size savings. Word
/// operations need an extra override byte compared to their 32 bit
/// versions. So this can convert many word operations to their larger
/// size, saving a byte in encoding. This could introduce partial register
/// dependences where none existed however. As an example take:
/// orw ax, $0x1000
/// addw ax, $3
/// now if this were to get transformed into
/// orw ax, $1000
/// addl eax, $3
/// because the addl encodes shorter than the addw, this would introduce
/// a use of a register that was only partially written earlier. On older
/// Intel processors this can be quite a performance penalty, so this should
/// probably only be done when it can be proven that a new partial dependence
/// wouldn't be created, or when your know a newer processor is being
/// targeted, or when optimizing for minimum code size.
///
//===----------------------------------------------------------------------===//
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
#define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
#define FIXUPBW_NAME "x86-fixup-bw-insts"
#define DEBUG_TYPE FIXUPBW_NAME
// Option to allow this optimization pass to have fine-grained control.
// This is turned off by default so as not to affect a large number of
// existing lit tests.
static cl::opt<bool>
FixupBWInsts("fixup-byte-word-insts",
cl::desc("Change byte and word instructions to larger sizes"),
cl::init(true), cl::Hidden);
namespace {
class FixupBWInstPass : public MachineFunctionPass {
/// Loop over all of the instructions in the basic block replacing applicable
/// byte or word instructions with better alternatives.
void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
/// This sets the \p SuperDestReg to the 32 bit super reg of the original
/// destination register of the MachineInstr passed in. It returns true if
/// that super register is dead just prior to \p OrigMI, and false if not.
bool getSuperRegDestIfDead(MachineInstr *OrigMI,
unsigned &SuperDestReg) const;
/// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
/// register if it is safe to do so. Return the replacement instruction if
/// OK, otherwise return nullptr.
MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
/// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is
/// safe to do so. Return the replacement instruction if OK, otherwise return
/// nullptr.
MachineInstr *tryReplaceCopy(MachineInstr *MI) const;
// Change the MachineInstr \p MI into an eqivalent 32 bit instruction if
// possible. Return the replacement instruction if OK, return nullptr
// otherwise. Set WasCandidate to true or false depending on whether the
// MI was a candidate for this sort of transformation.
MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB,
bool &WasCandidate) const;
public:
static char ID;
const char *getPassName() const override {
return FIXUPBW_DESC;
}
FixupBWInstPass() : MachineFunctionPass(ID) {
initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
// guide some heuristics.
MachineFunctionPass::getAnalysisUsage(AU);
}
/// Loop over all of the basic blocks, replacing byte and word instructions by
/// equivalent 32 bit instructions where performance or code size can be
/// improved.
bool runOnMachineFunction(MachineFunction &MF) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
private:
MachineFunction *MF;
/// Machine instruction info used throughout the class.
const X86InstrInfo *TII;
/// Local member for function's OptForSize attribute.
bool OptForSize;
/// Machine loop info used for guiding some heruistics.
MachineLoopInfo *MLI;
/// Register Liveness information after the current instruction.
LivePhysRegs LiveRegs;
};
char FixupBWInstPass::ID = 0;
}
INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
if (!FixupBWInsts || skipFunction(*MF.getFunction()))
return false;
this->MF = &MF;
TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
OptForSize = MF.getFunction()->optForSize();
MLI = &getAnalysis<MachineLoopInfo>();
LiveRegs.init(&TII->getRegisterInfo());
DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
// Process all basic blocks.
for (auto &MBB : MF)
processBasicBlock(MF, MBB);
DEBUG(dbgs() << "End X86FixupBWInsts\n";);
return true;
}
// TODO: This method of analysis can miss some legal cases, because the
// super-register could be live into the address expression for a memory
// reference for the instruction, and still be killed/last used by the
// instruction. However, the existing query interfaces don't seem to
// easily allow that to be checked.
//
// What we'd really like to know is whether after OrigMI, the
// only portion of SuperDestReg that is alive is the portion that
// was the destination register of OrigMI.
bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
unsigned &SuperDestReg) const {
auto *TRI = &TII->getRegisterInfo();
unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
// Make sure that the sub-register that this instruction has as its
// destination is the lowest order sub-register of the super-register.
// If it isn't, then the register isn't really dead even if the
// super-register is considered dead.
if (SubRegIdx == X86::sub_8bit_hi)
return false;
if (LiveRegs.contains(SuperDestReg))
return false;
if (SubRegIdx == X86::sub_8bit) {
// In the case of byte registers, we also have to check that the upper
// byte register is also dead. That is considered to be independent of
// whether the super-register is dead.
unsigned UpperByteReg =
getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true);
if (LiveRegs.contains(UpperByteReg))
return false;
}
return true;
}
MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
MachineInstr *MI) const {
unsigned NewDestReg;
// We are going to try to rewrite this load to a larger zero-extending
// load. This is safe if all portions of the 32 bit super-register
// of the original destination register, except for the original destination
// register are dead. getSuperRegDestIfDead checks that.
if (!getSuperRegDestIfDead(MI, NewDestReg))
return nullptr;
// Safe to change the instruction.
MachineInstrBuilder MIB =
BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
unsigned NumArgs = MI->getNumOperands();
for (unsigned i = 1; i < NumArgs; ++i)
MIB.addOperand(MI->getOperand(i));
MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
return MIB;
}
MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
assert(MI->getNumExplicitOperands() == 2);
auto &OldDest = MI->getOperand(0);
auto &OldSrc = MI->getOperand(1);
unsigned NewDestReg;
if (!getSuperRegDestIfDead(MI, NewDestReg))
return nullptr;
unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
// This is only correct if we access the same subregister index: otherwise,
// we could try to replace "movb %ah, %al" with "movl %eax, %eax".
auto *TRI = &TII->getRegisterInfo();
if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
return nullptr;
// Safe to change the instruction.
// Don't set src flags, as we don't know if we're also killing the superreg.
// However, the superregister might not be defined; make it explicit that
// we don't care about the higher bits by reading it as Undef, and adding
// an imp-use on the original subregister.
MachineInstrBuilder MIB =
BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg)
.addReg(NewSrcReg, RegState::Undef)
.addReg(OldSrc.getReg(), RegState::Implicit);
// Drop imp-defs/uses that would be redundant with the new def/use.
for (auto &Op : MI->implicit_operands())
if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
MIB.addOperand(Op);
return MIB;
}
MachineInstr *FixupBWInstPass::tryReplaceInstr(
MachineInstr *MI, MachineBasicBlock &MBB,
bool &WasCandidate) const {
MachineInstr *NewMI = nullptr;
WasCandidate = false;
// See if this is an instruction of the type we are currently looking for.
switch (MI->getOpcode()) {
case X86::MOV8rm:
// Only replace 8 bit loads with the zero extending versions if
// in an inner most loop and not optimizing for size. This takes
// an extra byte to encode, and provides limited performance upside.
if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
if (ML->begin() == ML->end() && !OptForSize) {
NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI);
WasCandidate = true;
}
}
break;
case X86::MOV16rm:
// Always try to replace 16 bit load with 32 bit zero extending.
// Code size is the same, and there is sometimes a perf advantage
// from eliminating a false dependence on the upper portion of
// the register.
NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI);
WasCandidate = true;
break;
case X86::MOV8rr:
case X86::MOV16rr:
// Always try to replace 8/16 bit copies with a 32 bit copy.
// Code size is either less (16) or equal (8), and there is sometimes a
// perf advantage from eliminating a false dependence on the upper portion
// of the register.
NewMI = tryReplaceCopy(MI);
WasCandidate = true;
break;
default:
// nothing to do here.
break;
}
return NewMI;
}
void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
MachineBasicBlock &MBB) {
// This algorithm doesn't delete the instructions it is replacing
// right away. By leaving the existing instructions in place, the
// register liveness information doesn't change, and this makes the
// analysis that goes on be better than if the replaced instructions
// were immediately removed.
//
// This algorithm always creates a replacement instruction
// and notes that and the original in a data structure, until the
// whole BB has been analyzed. This keeps the replacement instructions
// from making it seem as if the larger register might be live.
SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
// Start computing liveness for this block. We iterate from the end to be able
// to update this for each instruction.
LiveRegs.clear();
// We run after PEI, so we need to AddPristinesAndCSRs.
LiveRegs.addLiveOuts(MBB);
bool WasCandidate = false;
for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
MachineInstr *MI = &*I;
MachineInstr *NewMI = tryReplaceInstr(MI, MBB, WasCandidate);
// Add this to replacements if it was a candidate, even if NewMI is
// nullptr. We will revisit that in a bit.
if (WasCandidate) {
MIReplacements.push_back(std::make_pair(MI, NewMI));
}
// We're done with this instruction, update liveness for the next one.
LiveRegs.stepBackward(*MI);
}
while (!MIReplacements.empty()) {
MachineInstr *MI = MIReplacements.back().first;
MachineInstr *NewMI = MIReplacements.back().second;
MIReplacements.pop_back();
if (NewMI) {
MBB.insert(MI, NewMI);
MBB.erase(MI);
}
}
}
<commit_msg>[X86] Remove stale comment about FixupBWInsts pass being off by default. NFC<commit_after>//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines the pass that looks through the machine instructions
/// late in the compilation, and finds byte or word instructions that
/// can be profitably replaced with 32 bit instructions that give equivalent
/// results for the bits of the results that are used. There are two possible
/// reasons to do this.
///
/// One reason is to avoid false-dependences on the upper portions
/// of the registers. Only instructions that have a destination register
/// which is not in any of the source registers can be affected by this.
/// Any instruction where one of the source registers is also the destination
/// register is unaffected, because it has a true dependence on the source
/// register already. So, this consideration primarily affects load
/// instructions and register-to-register moves. It would
/// seem like cmov(s) would also be affected, but because of the way cmov is
/// really implemented by most machines as reading both the destination and
/// and source regsters, and then "merging" the two based on a condition,
/// it really already should be considered as having a true dependence on the
/// destination register as well.
///
/// The other reason to do this is for potential code size savings. Word
/// operations need an extra override byte compared to their 32 bit
/// versions. So this can convert many word operations to their larger
/// size, saving a byte in encoding. This could introduce partial register
/// dependences where none existed however. As an example take:
/// orw ax, $0x1000
/// addw ax, $3
/// now if this were to get transformed into
/// orw ax, $1000
/// addl eax, $3
/// because the addl encodes shorter than the addw, this would introduce
/// a use of a register that was only partially written earlier. On older
/// Intel processors this can be quite a performance penalty, so this should
/// probably only be done when it can be proven that a new partial dependence
/// wouldn't be created, or when your know a newer processor is being
/// targeted, or when optimizing for minimum code size.
///
//===----------------------------------------------------------------------===//
#include "X86.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
#define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
#define FIXUPBW_NAME "x86-fixup-bw-insts"
#define DEBUG_TYPE FIXUPBW_NAME
// Option to allow this optimization pass to have fine-grained control.
static cl::opt<bool>
FixupBWInsts("fixup-byte-word-insts",
cl::desc("Change byte and word instructions to larger sizes"),
cl::init(true), cl::Hidden);
namespace {
class FixupBWInstPass : public MachineFunctionPass {
/// Loop over all of the instructions in the basic block replacing applicable
/// byte or word instructions with better alternatives.
void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
/// This sets the \p SuperDestReg to the 32 bit super reg of the original
/// destination register of the MachineInstr passed in. It returns true if
/// that super register is dead just prior to \p OrigMI, and false if not.
bool getSuperRegDestIfDead(MachineInstr *OrigMI,
unsigned &SuperDestReg) const;
/// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
/// register if it is safe to do so. Return the replacement instruction if
/// OK, otherwise return nullptr.
MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
/// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is
/// safe to do so. Return the replacement instruction if OK, otherwise return
/// nullptr.
MachineInstr *tryReplaceCopy(MachineInstr *MI) const;
// Change the MachineInstr \p MI into an eqivalent 32 bit instruction if
// possible. Return the replacement instruction if OK, return nullptr
// otherwise. Set WasCandidate to true or false depending on whether the
// MI was a candidate for this sort of transformation.
MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB,
bool &WasCandidate) const;
public:
static char ID;
const char *getPassName() const override {
return FIXUPBW_DESC;
}
FixupBWInstPass() : MachineFunctionPass(ID) {
initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
// guide some heuristics.
MachineFunctionPass::getAnalysisUsage(AU);
}
/// Loop over all of the basic blocks, replacing byte and word instructions by
/// equivalent 32 bit instructions where performance or code size can be
/// improved.
bool runOnMachineFunction(MachineFunction &MF) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
private:
MachineFunction *MF;
/// Machine instruction info used throughout the class.
const X86InstrInfo *TII;
/// Local member for function's OptForSize attribute.
bool OptForSize;
/// Machine loop info used for guiding some heruistics.
MachineLoopInfo *MLI;
/// Register Liveness information after the current instruction.
LivePhysRegs LiveRegs;
};
char FixupBWInstPass::ID = 0;
}
INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
if (!FixupBWInsts || skipFunction(*MF.getFunction()))
return false;
this->MF = &MF;
TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
OptForSize = MF.getFunction()->optForSize();
MLI = &getAnalysis<MachineLoopInfo>();
LiveRegs.init(&TII->getRegisterInfo());
DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
// Process all basic blocks.
for (auto &MBB : MF)
processBasicBlock(MF, MBB);
DEBUG(dbgs() << "End X86FixupBWInsts\n";);
return true;
}
// TODO: This method of analysis can miss some legal cases, because the
// super-register could be live into the address expression for a memory
// reference for the instruction, and still be killed/last used by the
// instruction. However, the existing query interfaces don't seem to
// easily allow that to be checked.
//
// What we'd really like to know is whether after OrigMI, the
// only portion of SuperDestReg that is alive is the portion that
// was the destination register of OrigMI.
bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
unsigned &SuperDestReg) const {
auto *TRI = &TII->getRegisterInfo();
unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
// Make sure that the sub-register that this instruction has as its
// destination is the lowest order sub-register of the super-register.
// If it isn't, then the register isn't really dead even if the
// super-register is considered dead.
if (SubRegIdx == X86::sub_8bit_hi)
return false;
if (LiveRegs.contains(SuperDestReg))
return false;
if (SubRegIdx == X86::sub_8bit) {
// In the case of byte registers, we also have to check that the upper
// byte register is also dead. That is considered to be independent of
// whether the super-register is dead.
unsigned UpperByteReg =
getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true);
if (LiveRegs.contains(UpperByteReg))
return false;
}
return true;
}
MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
MachineInstr *MI) const {
unsigned NewDestReg;
// We are going to try to rewrite this load to a larger zero-extending
// load. This is safe if all portions of the 32 bit super-register
// of the original destination register, except for the original destination
// register are dead. getSuperRegDestIfDead checks that.
if (!getSuperRegDestIfDead(MI, NewDestReg))
return nullptr;
// Safe to change the instruction.
MachineInstrBuilder MIB =
BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
unsigned NumArgs = MI->getNumOperands();
for (unsigned i = 1; i < NumArgs; ++i)
MIB.addOperand(MI->getOperand(i));
MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
return MIB;
}
MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
assert(MI->getNumExplicitOperands() == 2);
auto &OldDest = MI->getOperand(0);
auto &OldSrc = MI->getOperand(1);
unsigned NewDestReg;
if (!getSuperRegDestIfDead(MI, NewDestReg))
return nullptr;
unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
// This is only correct if we access the same subregister index: otherwise,
// we could try to replace "movb %ah, %al" with "movl %eax, %eax".
auto *TRI = &TII->getRegisterInfo();
if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
return nullptr;
// Safe to change the instruction.
// Don't set src flags, as we don't know if we're also killing the superreg.
// However, the superregister might not be defined; make it explicit that
// we don't care about the higher bits by reading it as Undef, and adding
// an imp-use on the original subregister.
MachineInstrBuilder MIB =
BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg)
.addReg(NewSrcReg, RegState::Undef)
.addReg(OldSrc.getReg(), RegState::Implicit);
// Drop imp-defs/uses that would be redundant with the new def/use.
for (auto &Op : MI->implicit_operands())
if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
MIB.addOperand(Op);
return MIB;
}
MachineInstr *FixupBWInstPass::tryReplaceInstr(
MachineInstr *MI, MachineBasicBlock &MBB,
bool &WasCandidate) const {
MachineInstr *NewMI = nullptr;
WasCandidate = false;
// See if this is an instruction of the type we are currently looking for.
switch (MI->getOpcode()) {
case X86::MOV8rm:
// Only replace 8 bit loads with the zero extending versions if
// in an inner most loop and not optimizing for size. This takes
// an extra byte to encode, and provides limited performance upside.
if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
if (ML->begin() == ML->end() && !OptForSize) {
NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI);
WasCandidate = true;
}
}
break;
case X86::MOV16rm:
// Always try to replace 16 bit load with 32 bit zero extending.
// Code size is the same, and there is sometimes a perf advantage
// from eliminating a false dependence on the upper portion of
// the register.
NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI);
WasCandidate = true;
break;
case X86::MOV8rr:
case X86::MOV16rr:
// Always try to replace 8/16 bit copies with a 32 bit copy.
// Code size is either less (16) or equal (8), and there is sometimes a
// perf advantage from eliminating a false dependence on the upper portion
// of the register.
NewMI = tryReplaceCopy(MI);
WasCandidate = true;
break;
default:
// nothing to do here.
break;
}
return NewMI;
}
void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
MachineBasicBlock &MBB) {
// This algorithm doesn't delete the instructions it is replacing
// right away. By leaving the existing instructions in place, the
// register liveness information doesn't change, and this makes the
// analysis that goes on be better than if the replaced instructions
// were immediately removed.
//
// This algorithm always creates a replacement instruction
// and notes that and the original in a data structure, until the
// whole BB has been analyzed. This keeps the replacement instructions
// from making it seem as if the larger register might be live.
SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
// Start computing liveness for this block. We iterate from the end to be able
// to update this for each instruction.
LiveRegs.clear();
// We run after PEI, so we need to AddPristinesAndCSRs.
LiveRegs.addLiveOuts(MBB);
bool WasCandidate = false;
for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
MachineInstr *MI = &*I;
MachineInstr *NewMI = tryReplaceInstr(MI, MBB, WasCandidate);
// Add this to replacements if it was a candidate, even if NewMI is
// nullptr. We will revisit that in a bit.
if (WasCandidate) {
MIReplacements.push_back(std::make_pair(MI, NewMI));
}
// We're done with this instruction, update liveness for the next one.
LiveRegs.stepBackward(*MI);
}
while (!MIReplacements.empty()) {
MachineInstr *MI = MIReplacements.back().first;
MachineInstr *NewMI = MIReplacements.back().second;
MIReplacements.pop_back();
if (NewMI) {
MBB.insert(MI, NewMI);
MBB.erase(MI);
}
}
}
<|endoftext|>
|
<commit_before>#include <set>
#include <string>
#include <memory>
#include <cassert>
#include <iostream>
#include <stdexcept>
#include "config.h"
#include "parsers/cli.h"
#include "solvers/dpll.h"
#include "solvers/tseitin.h"
#include "structures/equality_atom.h"
#include "structures/extended_formula.h"
#include "solvers/equality_assistant.h"
#include "equality.y.hpp"
#define EF satsolver::ExtendedFormula
#define SPEF std::shared_ptr<EF>
#define EA theorysolver::EqualityAtom
#define SPEA std::shared_ptr<EA>
extern FILE *yyin;
extern int yyparse();
bool VERBOSE = false;
bool WITH_WL = false;
bool DISPLAY_SAT;
bool DISPLAY_ATOMS;
bool DISPLAY_FORMULA;
satsolver::Heuristic HEURISTIC = satsolver::DUMB ;
void parser_result(SPEF ext_formula, std::vector<SPEA> &literal_to_EA) {
/*********************
* Reduce
********************/
theorysolver::EqualityAssistant *assistant;
satsolver::Affectation *sat_solution;
std::vector<unsigned int> affected_literals;
std::shared_ptr<std::map<std::string, int>> name_to_variable;
std::map<int, std::string> variable_to_name;
std::shared_ptr<std::unordered_set<std::string>> literals = ext_formula->get_literals();
std::shared_ptr<satsolver::Formula> formula;
if (VERBOSE || DISPLAY_FORMULA)
std::cout << "Interpreted formula as: " << ext_formula->to_string() << std::endl;
if (VERBOSE || DISPLAY_ATOMS) {
std::cout << "Atoms:" << std::endl;
for (unsigned int i=0; i<literal_to_EA.size(); i++)
std::cout << "\t#" << i+1 << ": " << literal_to_EA[i]->to_string() << std::endl;
}
ext_formula = theorysolver::EqualityAssistant::canonize_formula(ext_formula, literal_to_EA);
if (VERBOSE || DISPLAY_FORMULA)
std::cout << "Canonized formula as: " << ext_formula->to_string() << std::endl;
if (VERBOSE || DISPLAY_ATOMS) {
std::cout << "Atoms:" << std::endl;
for (unsigned int i=0; i<literal_to_EA.size(); i++)
std::cout << "\t#" << i+1 << ": " << literal_to_EA[i]->to_string() << std::endl;
}
if (!tseitin_reduction(DISPLAY_SAT, ext_formula, name_to_variable, formula, &affected_literals)) {
// The formula is always false
if (DISPLAY_SAT)
std::cout << "c The formula is so obviously wrong it is not even needed to convert it to conjonctive form." << std::endl;
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
if (!name_to_variable) {
switch (ext_formula->get_type()) {
case EF::TRUE:
std::cout << "s SATISFIABLE (tautology)" << std::endl;
return;
case EF::FALSE:
std::cout << "s UNSATISFIABLE" << std::endl;
return;
default:
std::cout << "s SATISFIABLE" << std::endl;
return;
}
}
assistant = new theorysolver::EqualityAssistant(literal_to_EA, name_to_variable, formula);
for (auto it : affected_literals) {
if (!assistant->on_flip(it)) {
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
}
/*********************
* Solve
********************/
try {
sat_solution = satsolver::solve(formula, assistant);
}
catch (satsolver::Conflict) {
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
/*********************
* Display solution
********************/
assert(assistant->is_state_consistent());
if (VERBOSE) {
std::cout << "Solution to SAT problem: " << sat_solution->to_string() << std::endl;
/* std::cout << assistant->get_graph().to_string() << std::endl; */
}
for (auto literal : *literals) {
try {
std::cout << literal << " = " << (sat_solution->is_true(name_to_variable->at(literal)) ? "true" : "false") << std::endl;
}
catch (std::out_of_range) {
SPEF f = literal_to_EA[atoi(literal.c_str()+1)-1]->canonical;
std::cout << literal << " (inferred from " << f->to_string() << ")" << " = ";
try {
std::cout << (f->is_true(formula->get_aff(), name_to_variable) ? "true" : "false") << std::endl;
}
catch (std::out_of_range) {
std::cout << "can be true or false" << std::endl ;
}
}
}
delete assistant;
}
int main (int argc, char *argv[]) {
/*********************
* Get input
********************/
CommandLineParser cli_parser(argc, argv, std::unordered_set<std::string>({"-print-interpretation", "-print-sat", "-print-atoms"}), "[-print-interpretation] [-print-sat] [-print-atoms] [<filename>]");
if (cli_parser.get_nb_parsed_args() == -1)
return 1;
int nb_remaining_args = argc - cli_parser.get_nb_parsed_args();
if (nb_remaining_args == 0) {
// No other option
}
else if (nb_remaining_args == 1) {
// One option left; hopefully the file name
yyin = fopen(argv[argc-nb_remaining_args], "r");
}
else {
// Too many unknown options
cli_parser.print_syntax_error(argv[0]);
return 1;
}
DISPLAY_SAT = cli_parser.get_arg("-print-sat");
DISPLAY_ATOMS = cli_parser.get_arg("-print-atoms");
DISPLAY_FORMULA = cli_parser.get_arg("-print-interpretation");
return yyparse();
}
<commit_msg>Correct intialisation bug for equality theory.<commit_after>#include <set>
#include <string>
#include <memory>
#include <cassert>
#include <iostream>
#include <stdexcept>
#include "config.h"
#include "parsers/cli.h"
#include "solvers/dpll.h"
#include "solvers/tseitin.h"
#include "structures/equality_atom.h"
#include "structures/extended_formula.h"
#include "solvers/equality_assistant.h"
#include "equality.y.hpp"
#define EF satsolver::ExtendedFormula
#define SPEF std::shared_ptr<EF>
#define EA theorysolver::EqualityAtom
#define SPEA std::shared_ptr<EA>
extern FILE *yyin;
extern int yyparse();
bool VERBOSE = false;
bool WITH_WL = false;
bool DISPLAY_SAT;
bool DISPLAY_ATOMS;
bool DISPLAY_FORMULA;
satsolver::Heuristic HEURISTIC = satsolver::DUMB ;
void parser_result(SPEF ext_formula, std::vector<SPEA> &literal_to_EA) {
/*********************
* Reduce
********************/
theorysolver::EqualityAssistant *assistant;
satsolver::Affectation *sat_solution;
std::vector<unsigned int> affected_literals;
std::shared_ptr<std::map<std::string, int>> name_to_variable;
std::map<int, std::string> variable_to_name;
std::shared_ptr<std::unordered_set<std::string>> literals = ext_formula->get_literals();
std::shared_ptr<satsolver::Formula> formula;
if (VERBOSE || DISPLAY_FORMULA)
std::cout << "Interpreted formula as: " << ext_formula->to_string() << std::endl;
if (VERBOSE || DISPLAY_ATOMS) {
std::cout << "Atoms:" << std::endl;
for (unsigned int i=0; i<literal_to_EA.size(); i++)
std::cout << "\t#" << i+1 << ": " << literal_to_EA[i]->to_string() << std::endl;
}
ext_formula = theorysolver::EqualityAssistant::canonize_formula(ext_formula, literal_to_EA);
if (VERBOSE || DISPLAY_FORMULA)
std::cout << "Canonized formula as: " << ext_formula->to_string() << std::endl;
if (VERBOSE || DISPLAY_ATOMS) {
std::cout << "Atoms:" << std::endl;
for (unsigned int i=0; i<literal_to_EA.size(); i++)
std::cout << "\t#" << i+1 << ": " << literal_to_EA[i]->to_string() << std::endl;
}
if (!tseitin_reduction(DISPLAY_SAT, ext_formula, name_to_variable, formula, &affected_literals)) {
// The formula is always false
if (DISPLAY_SAT)
std::cout << "c The formula is so obviously wrong it is not even needed to convert it to conjonctive form." << std::endl;
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
if (!name_to_variable) {
switch (ext_formula->get_type()) {
case EF::TRUE:
std::cout << "s SATISFIABLE (tautology)" << std::endl;
return;
case EF::FALSE:
std::cout << "s UNSATISFIABLE" << std::endl;
return;
default:
std::cout << "s SATISFIABLE" << std::endl;
return;
}
}
assistant = new theorysolver::EqualityAssistant(literal_to_EA, name_to_variable, formula);
for (auto it : affected_literals) {
if (-1!=assistant->on_flip(it)) {
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
}
/*********************
* Solve
********************/
try {
sat_solution = satsolver::solve(formula, assistant);
}
catch (satsolver::Conflict) {
std::cout << "s UNSATISFIABLE" << std::endl;
return;
}
/*********************
* Display solution
********************/
assert(assistant->is_state_consistent());
if (VERBOSE) {
std::cout << "Solution to SAT problem: " << sat_solution->to_string() << std::endl;
/* std::cout << assistant->get_graph().to_string() << std::endl; */
}
for (auto literal : *literals) {
try {
std::cout << literal << " = " << (sat_solution->is_true(name_to_variable->at(literal)) ? "true" : "false") << std::endl;
}
catch (std::out_of_range) {
SPEF f = literal_to_EA[atoi(literal.c_str()+1)-1]->canonical;
std::cout << literal << " (inferred from " << f->to_string() << ")" << " = ";
try {
std::cout << (f->is_true(formula->get_aff(), name_to_variable) ? "true" : "false") << std::endl;
}
catch (std::out_of_range) {
std::cout << "can be true or false" << std::endl ;
}
}
}
delete assistant;
}
int main (int argc, char *argv[]) {
/*********************
* Get input
********************/
CommandLineParser cli_parser(argc, argv, std::unordered_set<std::string>({"-print-interpretation", "-print-sat", "-print-atoms"}), "[-print-interpretation] [-print-sat] [-print-atoms] [<filename>]");
if (cli_parser.get_nb_parsed_args() == -1)
return 1;
int nb_remaining_args = argc - cli_parser.get_nb_parsed_args();
if (nb_remaining_args == 0) {
// No other option
}
else if (nb_remaining_args == 1) {
// One option left; hopefully the file name
yyin = fopen(argv[argc-nb_remaining_args], "r");
}
else {
// Too many unknown options
cli_parser.print_syntax_error(argv[0]);
return 1;
}
DISPLAY_SAT = cli_parser.get_arg("-print-sat");
DISPLAY_ATOMS = cli_parser.get_arg("-print-atoms");
DISPLAY_FORMULA = cli_parser.get_arg("-print-interpretation");
return yyparse();
}
<|endoftext|>
|
<commit_before>//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements stripping symbols out of symbol tables.
//
// Specifically, this allows you to strip all of the symbols out of:
// * All functions in a module
// * All non-essential symbols in a module (all function symbols + all module
// scope symbols)
// * Debug information.
//
// Notice that:
// * This pass makes code much less readable, so it should only be used in
// situations where the 'strip' utility would be used (such as reducing
// code size, and making it harder to reverse engineer code).
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "llvm/Pass.h"
using namespace llvm;
namespace {
class StripSymbols : public ModulePass {
bool OnlyDebugInfo;
public:
StripSymbols(bool ODI = false) : OnlyDebugInfo(ODI) {}
virtual bool runOnModule(Module &M);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterOpt<StripSymbols> X("strip", "Strip all symbols from a module");
}
ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
return new StripSymbols(OnlyDebugInfo);
}
bool StripSymbols::runOnModule(Module &M) {
// If we're not just stripping debug info, strip all symbols from the
// functions and the names from any internal globals.
if (!OnlyDebugInfo) {
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
if (I->hasInternalLinkage())
I->setName(""); // Internal symbols can't participate in linkage
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (I->hasInternalLinkage())
I->setName(""); // Internal symbols can't participate in linkage
I->getSymbolTable().strip();
}
}
// FIXME: implement stripping of debug info.
return true;
}
<commit_msg>Implement stripping of debug symbols, making the --strip-debug options in gccas/gccld more than just a noop.<commit_after>//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements stripping symbols out of symbol tables.
//
// Specifically, this allows you to strip all of the symbols out of:
// * All functions in a module
// * All non-essential symbols in a module (all function symbols + all module
// scope symbols)
// * Debug information.
//
// Notice that:
// * This pass makes code much less readable, so it should only be used in
// situations where the 'strip' utility would be used (such as reducing
// code size, and making it harder to reverse engineer code).
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/SymbolTable.h"
using namespace llvm;
namespace {
class StripSymbols : public ModulePass {
bool OnlyDebugInfo;
public:
StripSymbols(bool ODI = false) : OnlyDebugInfo(ODI) {}
virtual bool runOnModule(Module &M);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterOpt<StripSymbols> X("strip", "Strip all symbols from a module");
}
ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
return new StripSymbols(OnlyDebugInfo);
}
static void RemoveDeadConstant(Constant *C) {
assert(C->use_empty() && "Constant is not dead!");
std::vector<Constant*> Operands;
for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
if (isa<DerivedType>(C->getOperand(i)->getType()) &&
C->getOperand(i)->hasOneUse())
Operands.push_back(C->getOperand(i));
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
if (!GV->hasInternalLinkage()) return; // Don't delete non static globals.
GV->eraseFromParent();
}
else if (!isa<Function>(C))
C->destroyConstant();
// If the constant referenced anything, see if we can delete it as well.
while (!Operands.empty()) {
RemoveDeadConstant(Operands.back());
Operands.pop_back();
}
}
bool StripSymbols::runOnModule(Module &M) {
// If we're not just stripping debug info, strip all symbols from the
// functions and the names from any internal globals.
if (!OnlyDebugInfo) {
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
if (I->hasInternalLinkage())
I->setName(""); // Internal symbols can't participate in linkage
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (I->hasInternalLinkage())
I->setName(""); // Internal symbols can't participate in linkage
I->getSymbolTable().strip();
}
}
// Strip debug info in the module if it exists. To do this, we remove
// llvm.dbg.func.start, llvm.dbg.stoppoint, and llvm.dbg.region.end calls, and
// any globals they point to if now dead.
Function *FuncStart = M.getNamedFunction("llvm.dbg.func.start");
Function *StopPoint = M.getNamedFunction("llvm.dbg.stoppoint");
Function *RegionEnd = M.getNamedFunction("llvm.dbg.region.end");
if (!FuncStart && !StopPoint && !RegionEnd)
return true;
std::vector<GlobalVariable*> DeadGlobals;
// Remove all of the calls to the debugger intrinsics, and remove them from
// the module.
if (FuncStart) {
Value *RV = UndefValue::get(StopPoint->getFunctionType()->getReturnType());
while (!FuncStart->use_empty()) {
CallInst *CI = cast<CallInst>(FuncStart->use_back());
Value *Arg = CI->getOperand(1);
CI->replaceAllUsesWith(RV);
CI->eraseFromParent();
if (Arg->use_empty())
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg))
DeadGlobals.push_back(GV);
}
FuncStart->eraseFromParent();
}
if (StopPoint) {
Value *RV = UndefValue::get(StopPoint->getFunctionType()->getReturnType());
while (!StopPoint->use_empty()) {
CallInst *CI = cast<CallInst>(StopPoint->use_back());
Value *Arg = CI->getOperand(4);
CI->replaceAllUsesWith(RV);
CI->eraseFromParent();
if (Arg->use_empty())
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg))
DeadGlobals.push_back(GV);
}
StopPoint->eraseFromParent();
}
if (RegionEnd) {
Value *RV = UndefValue::get(RegionEnd->getFunctionType()->getReturnType());
while (!RegionEnd->use_empty()) {
CallInst *CI = cast<CallInst>(RegionEnd->use_back());
CI->replaceAllUsesWith(RV);
CI->eraseFromParent();
}
RegionEnd->eraseFromParent();
}
// Finally, delete any internal globals that were only used by the debugger
// intrinsics.
while (!DeadGlobals.empty()) {
GlobalVariable *GV = DeadGlobals.back();
DeadGlobals.pop_back();
if (GV->hasInternalLinkage())
RemoveDeadConstant(GV);
}
return true;
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2016 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "UseAnalysisGroupings.h"
#include "ModelBase/src/nodes/Reference.h"
namespace CodeReview
{
bool const UseAnalysisGroupings::ONLY_CONSIDER_CHANGES = true;
UseAnalysisGroupings::DiffFrameInfo UseAnalysisGroupings::computeDiffFrameDependenciesAndPresentations
(VersionControlUI::DiffFrame* diffFrame)
{
auto oldNode = diffFrame->oldVersionNode();
auto newNode = diffFrame->newVersionNode();
if (!oldNode && !newNode)
return {};
QList<Model::Node*> stack;
if (oldNode)
stack << oldNode;
if (newNode)
stack << newNode;
DiffFrameInfo diffFrameInfo;
while (!stack.isEmpty())
{
auto top = stack.takeLast();
if (top)
{
if (auto referenceNode = DCast<Model::Reference>(top))
{
if (referenceNode->isResolved())
diffFrameInfo.refersTo_.insert(referenceNode->target());
}
else
{
stack.append(top->children());
diffFrameInfo.shows_.insert(top);
}
}
}
// remove ids which are shown by this DiffFrame from the dependencies
diffFrameInfo.refersTo_.subtract(diffFrameInfo.shows_);
return diffFrameInfo;
}
QList<QList<VersionControlUI::DiffFrame*>> UseAnalysisGroupings::useAnalysisGrouping(QList<VersionControlUI::DiffFrame*>
diffFrames)
{
QList<QList<VersionControlUI::DiffFrame*>> result;
QHash<VersionControlUI::DiffFrame*, DiffFrameInfo> diffPairsWithInfo;
QHash<VersionControlUI::DiffFrame*, QList<VersionControlUI::DiffFrame*>*> groupLists;
for (auto diffCompPair : diffFrame)
{
auto info = computeDiffFrameDependenciesAndPresentations(diffCompPair);
diffPairsWithInfo.insert(diffCompPair, info);
}
for (auto diffPair : diffPairsWithInfo.keys())
{
bool dependsOnOther = false;
for (auto otherDiffPair : diffPairsWithInfo.keys())
{
if (diffPair == otherDiffPair) continue;
if (dependsOn(diffPairsWithInfo.value(diffPair), otherDiffPair, diffPairsWithInfo.value(otherDiffPair)))
{
dependsOnOther = true;
auto iter = groupLists.find(otherDiffPair);
if (iter != groupLists.end())
{
(*iter)->append(diffPair);
groupLists.insert(diffPair, *iter);
} else
{
result.prepend({});
result.first().append(diffPair);
result.first().append(otherDiffPair);
groupLists.insert(diffPair, &result.first());
groupLists.insert(otherDiffPair, &result.first());
}
}
}
if (!dependsOnOther && !groupLists.contains(diffPair))
{
result.prepend({});
result.first().append(diffPair);
groupLists.insert(diffPair, &result.first());
}
}
return result;
}
bool UseAnalysisGroupings::dependsOn(DiffFrameInfo infoA,
VersionControlUI::DiffFrame* frameB, DiffFrameInfo infoB)
{
if (ONLY_CONSIDER_CHANGES)
{
for (auto referal : infoA.refersTo_)
{
for (auto changesOld : frameB->oldChangedNodes())
if (changesOld->isSameOrAncestorOf(referal))
return true;
for (auto changesNew : frameB->newChangedNodes())
if (changesNew->isSameOrAncestorOf(referal))
return true;
}
return false;
} else
{
auto refers = infoA.refersTo_;
auto shows = infoB.shows_;
return !refers.intersect(shows).isEmpty();
}
}
}
<commit_msg>Renaming of variables, iterating over list instead of qHash, bugfixing algorithm<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2016 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "UseAnalysisGroupings.h"
#include "ModelBase/src/nodes/Reference.h"
namespace CodeReview
{
bool const UseAnalysisGroupings::ONLY_CONSIDER_CHANGES = true;
UseAnalysisGroupings::DiffFrameInfo UseAnalysisGroupings::computeDiffFrameDependenciesAndPresentations
(VersionControlUI::DiffFrame* diffFrame)
{
auto oldNode = diffFrame->oldVersionNode();
auto newNode = diffFrame->newVersionNode();
if (!oldNode && !newNode)
return {};
QList<Model::Node*> stack;
if (oldNode)
stack << oldNode;
if (newNode)
stack << newNode;
DiffFrameInfo diffFrameInfo;
while (!stack.isEmpty())
{
auto top = stack.takeLast();
if (top)
{
if (auto referenceNode = DCast<Model::Reference>(top))
{
if (referenceNode->isResolved())
diffFrameInfo.refersTo_.insert(referenceNode->target());
}
else
{
stack.append(top->children());
diffFrameInfo.shows_.insert(top);
}
}
}
// remove ids which are shown by this DiffFrame from the dependencies
diffFrameInfo.refersTo_.subtract(diffFrameInfo.shows_);
return diffFrameInfo;
}
QList<QList<VersionControlUI::DiffFrame*>> UseAnalysisGroupings::useAnalysisGrouping(QList<VersionControlUI::DiffFrame*>
diffFrames)
{
QList<QList<VersionControlUI::DiffFrame*>> result;
QHash<VersionControlUI::DiffFrame*, DiffFrameInfo> diffFrameToInfo;
QHash<VersionControlUI::DiffFrame*, QList<VersionControlUI::DiffFrame*>*> groupLists;
for (auto diffFrame : diffFrames)
{
auto info = computeDiffFrameDependenciesAndPresentations(diffFrame);
diffFrameToInfo.insert(diffFrame, info);
}
for (auto diffFrame : diffFrames)
{
bool dependsOnOther = false;
for (auto otherDiffFrame : diffFrames)
{
if (diffFrame == otherDiffFrame) continue;
if (dependsOn(diffFrameToInfo.value(diffFrame), otherDiffFrame, diffFrameToInfo.value(otherDiffFrame)))
{
dependsOnOther = true;
auto iter = groupLists.find(otherDiffFrame);
if (iter != groupLists.end())
{
iter.value()->append(diffFrame);
groupLists.insert(diffFrame, iter.value());
} else
{
result.append(QList<VersionControlUI::DiffFrame*>{});
result.last().append(diffFrame);
result.last().append(otherDiffFrame);
groupLists.insert(diffFrame, &result.last());
groupLists.insert(otherDiffFrame, &result.last());
}
}
}
if (!dependsOnOther && !groupLists.contains(diffFrame))
{
result.append(QList<VersionControlUI::DiffFrame*>{});
result.last().append(diffFrame);
groupLists.insert(diffFrame, &result.last());
}
}
return result;
}
bool UseAnalysisGroupings::dependsOn(DiffFrameInfo infoA,
VersionControlUI::DiffFrame* frameB, DiffFrameInfo infoB)
{
if (ONLY_CONSIDER_CHANGES)
{
for (auto referal : infoA.refersTo_)
{
for (auto changesOld : frameB->oldChangedNodes())
if (changesOld->isSameOrAncestorOf(referal))
return true;
for (auto changesNew : frameB->newChangedNodes())
if (changesNew->isSameOrAncestorOf(referal))
return true;
}
return false;
} else
{
auto refers = infoA.refersTo_;
auto shows = infoB.shows_;
return !refers.intersect(shows).isEmpty();
}
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "AnimationManager.h"
#include <fstream>
#include <cassert>
#include "..\..\SGD Wrappers\SGD_Geometry.h"
#include"..\..\SGD Wrappers\SGD_GraphicsManager.h"
#include <iterator>
//***********************************************************************
// SINGLETON
// - instantiate the static member
AnimationManager* AnimationManager::s_pInstance = nullptr;
// GetInstance
// - allocate the singleton if necessary
// - return the singleton
AnimationManager* AnimationManager::GetInstance()
{
if( s_pInstance == nullptr )
{
s_pInstance = new AnimationManager;
}
return s_pInstance;
}
// DeleteInstance
// - deallocate the singleton
void AnimationManager::DeleteInstance()
{
//GetInstance()->Loaded.clear();
auto iter = GetInstance()->Loaded.begin();
for( ; iter != GetInstance()->Loaded.end(); ++iter )
{
// Do some stuff
delete GetInstance()->Loaded[ iter->first ];
}
delete s_pInstance;
s_pInstance = nullptr;
}
void AnimationManager::Render( AnimationTimeStamp ts , int posX , int posY )
{
//Draw the frame
Frame temp = Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() );
posX = posX - temp.GetAnchorPoint().x;
posY = posY - temp.GetAnchorPoint().y;
SGD::Rectangle rect = Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() ).GetDrawRect();
SGD::GraphicsManager::GetInstance()->DrawTextureSection(
Loaded[ ts.GetCurrentAnimation() ]->GetImage() ,
SGD::Point( posX , posY ) ,
rect);
}
void AnimationManager::Update( AnimationTimeStamp& ts , float dt )
{
if( ts.GetTimeOnFrame() + dt < Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() ).GetDuration() )
{
ts.SetTimeOnFrame( ts.GetTimeOnFrame() + dt );
}
else
{
//What is the last frame in the animation?
int lastFrame = Loaded[ ts.GetCurrentAnimation() ]->GetFrameVector().size()-1;
//if we are not on the last frame in the animation
if( ts.GetCurrentFrame() < lastFrame )
{
ts.SetCurrentFrame( ts.GetCurrentFrame() + 1 );
}
//else if we are on the last frame in the animation and the animation loops
else if( ts.GetCurrentFrame() == lastFrame && Loaded[ ts.GetCurrentAnimation() ]->GetLooping() == true )
{
ts.SetCurrentFrame( 0 );
}
//else if we are on the last frame in the animation and the animation does not loop
else
{
ts.SetCurrentFrame( lastFrame );
}
ts.SetTimeOnFrame( 0.0f );
}
}
void AnimationManager::Load( string fileName )
{
assert( fileName.c_str() != nullptr && fileName[ 0 ] != '\0' && "AnimationManager:Load - Invalid filename" );
SGD::GraphicsManager* pGraphics = SGD::GraphicsManager::GetInstance();
//create the TinyXML Document
TiXmlDocument doc;
//Attempt to load the file
// (will allocate & set the Entire tree)
if( doc.LoadFile( fileName.c_str() ) == false )
{
return;
}
//Access the root Element ("Root")
TiXmlElement* pRoot = doc.RootElement();
if( pRoot == nullptr )
{
return;
}
//Access the root's first "Root" Element
//TiXmlElement* pAnimation = pRoot->FirstChildElement( "Root" );
//Access the root's first "animation" Element
TiXmlElement* pAnimation = pRoot->FirstChildElement();
if( pAnimation == nullptr )
{
return;
}
while( pAnimation != nullptr )
{
//Access the root's first "animation_info" Element
TiXmlElement* pAnimationInfo = pAnimation->FirstChildElement();
//pAnimation = pAnimation->FirstChildElement();
if( pAnimationInfo == nullptr )
{
return;
}
//Get all the animations
while( pAnimationInfo != nullptr )
{
Animation* a = new Animation;
//Access the animation element's name
string szText = "";
szText = pAnimationInfo->Attribute( "name" );
if( szText != "" )
{
a->SetName( szText );
}
Loaded[ a->GetName() ] = a;
//Get the looping bool
bool bLoops;
int temp;
pAnimationInfo->Attribute( "looping" , &temp );
//bLoops = temp;
if( temp > 0 )
bLoops = true;
else
bLoops = false;
Loaded[ a->GetName() ]->SetLooping( bLoops );
//Get the filepath for the image
string path = "resource/graphics/";
string tName = "";
tName = pAnimationInfo->Attribute( "hTexture" );
path += tName;
SGD::HTexture m_hImage = SGD::INVALID_HANDLE;
m_hImage = pGraphics->LoadTexture( path.c_str() );
Loaded[ a->GetName() ]->SetImage( m_hImage );
//Clear the frames vector
Loaded[ a->GetName() ]->GetFrameVector().clear();
//Get the number of frames in the animation
int nFrames = 0;
pAnimationInfo->Attribute( "numFrames" , &nFrames );
//Access the animations's first "frame" Element
TiXmlElement* pFrame = pAnimationInfo->FirstChildElement();
//get each of the frames in the image
while( pFrame != nullptr )
{
Frame f;
/*<frame duration="0.5" damage="0" event="none" dLeft="4" dTop="520" dRight="47" dBottom="580" cLeft="4" cTop="520" cRight="47" cBottom="580" x="24" y="577"/>*/
//Get the frame's duration
double dur;
pFrame->Attribute( "duration" , &dur );
f.SetDuration( ( float ) dur );
//Get the frame's damage
int dam;
pFrame->Attribute( "damage" , &dam );
f.SetDamage( dam );
//Get the frame's event name
string eve = "";
eve = pFrame->Attribute( "event" );
f.SetEventName( eve );
//Get the drawRect
SGD::Rectangle dRect;
//Get the drawRect left
int dleft;
pFrame->Attribute( "dLeft" , &dleft );
//Get the drawRect top
int dtop;
pFrame->Attribute( "dTop" , &dtop );
//Get the drawRect right
int drig;
pFrame->Attribute( "dRight" , &drig );
//Get the drawRect bottom
int dbot;
pFrame->Attribute( "dBottom" , &dbot );
//set the drect left/top/bottom/right to the read in variables
dRect.left = ( float ) dleft;
dRect.top = ( float ) dtop;
dRect.right = ( float ) drig;
dRect.bottom = ( float ) dbot;
//set the frame's draw rect to the drect
f.SetDrawRect( dRect );
//Get the collisionRect
SGD::Rectangle cRect;
//Get the collisionRect left
int cleft;
pFrame->Attribute( "cLeft" , &cleft );
//Get the collisionRect top
int ctop;
pFrame->Attribute( "cTop" , &ctop );
//Get the collisionRect right
int crig;
pFrame->Attribute( "cRight" , &crig );
//Get the collisionRect bottom
int cbot;
pFrame->Attribute( "cBottom" , &cbot );
//set the crect left/top/bottom/right to the read in variables
cRect.left = ( float ) cleft;
cRect.top = ( float ) ctop;
cRect.right = ( float ) crig;
cRect.bottom = ( float ) cbot;
//add the crect to the frame collisionrects vector
f.AddCollisionRect( cRect );
//Get anchor point
SGD::Point aP;
//Get anchor point x
int aX;
pFrame->Attribute( "x" , &aX );
//Get anchor point y
int aY;
pFrame->Attribute( "y" , &aY );
aP.x = ( float ) aX;
aP.y = ( float ) aY;
f.SetAnchorPoint( aP );
//Add the new frame to a's frame vector
Loaded[ a->GetName() ]->AddFrame( f );
//Move to the next "frame" Sibling Element if there are more frames
pFrame = pFrame->NextSiblingElement();
}
pAnimationInfo = pAnimationInfo->NextSiblingElement();
}
pAnimation = pAnimation->NextSiblingElement();
}
}
void AnimationManager::AddToAnimationMap( Animation* animation )
{
if( animation != nullptr )
{
Loaded[ animation->GetName() ] = animation;
}
}
int AnimationManager::CheckSize()
{
return Loaded.size();
}<commit_msg>Fixed memory leaks from AnimationManager not releasing images in the DeleteInstance function<commit_after>#include "stdafx.h"
#include "AnimationManager.h"
#include <fstream>
#include <cassert>
#include "..\..\SGD Wrappers\SGD_Geometry.h"
#include"..\..\SGD Wrappers\SGD_GraphicsManager.h"
#include <iterator>
//***********************************************************************
// SINGLETON
// - instantiate the static member
AnimationManager* AnimationManager::s_pInstance = nullptr;
// GetInstance
// - allocate the singleton if necessary
// - return the singleton
AnimationManager* AnimationManager::GetInstance()
{
if( s_pInstance == nullptr )
{
s_pInstance = new AnimationManager;
}
return s_pInstance;
}
// DeleteInstance
// - deallocate the singleton
void AnimationManager::DeleteInstance()
{
//GetInstance()->Loaded.clear();
auto iter = GetInstance()->Loaded.begin();
for( ; iter != GetInstance()->Loaded.end(); ++iter )
{
SGD::GraphicsManager::GetInstance()->UnloadTexture( GetInstance()->Loaded[ iter->first ]->GetImage() );
// Do some stuff
delete GetInstance()->Loaded[ iter->first ];
}
delete s_pInstance;
s_pInstance = nullptr;
}
void AnimationManager::Render( AnimationTimeStamp ts , int posX , int posY )
{
//Draw the frame
Frame temp = Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() );
posX = posX - temp.GetAnchorPoint().x;
posY = posY - temp.GetAnchorPoint().y;
SGD::Rectangle rect = Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() ).GetDrawRect();
SGD::GraphicsManager::GetInstance()->DrawTextureSection(
Loaded[ ts.GetCurrentAnimation() ]->GetImage() ,
SGD::Point( posX , posY ) ,
rect);
}
void AnimationManager::Update( AnimationTimeStamp& ts , float dt )
{
if( ts.GetTimeOnFrame() + dt < Loaded[ ts.GetCurrentAnimation() ]->GetFrame( ts.GetCurrentFrame() ).GetDuration() )
{
ts.SetTimeOnFrame( ts.GetTimeOnFrame() + dt );
}
else
{
//What is the last frame in the animation?
int lastFrame = Loaded[ ts.GetCurrentAnimation() ]->GetFrameVector().size()-1;
//if we are not on the last frame in the animation
if( ts.GetCurrentFrame() < lastFrame )
{
ts.SetCurrentFrame( ts.GetCurrentFrame() + 1 );
}
//else if we are on the last frame in the animation and the animation loops
else if( ts.GetCurrentFrame() == lastFrame && Loaded[ ts.GetCurrentAnimation() ]->GetLooping() == true )
{
ts.SetCurrentFrame( 0 );
}
//else if we are on the last frame in the animation and the animation does not loop
else
{
ts.SetCurrentFrame( lastFrame );
}
ts.SetTimeOnFrame( 0.0f );
}
}
void AnimationManager::Load( string fileName )
{
assert( fileName.c_str() != nullptr && fileName[ 0 ] != '\0' && "AnimationManager:Load - Invalid filename" );
SGD::GraphicsManager* pGraphics = SGD::GraphicsManager::GetInstance();
//create the TinyXML Document
TiXmlDocument doc;
//Attempt to load the file
// (will allocate & set the Entire tree)
if( doc.LoadFile( fileName.c_str() ) == false )
{
return;
}
//Access the root Element ("Root")
TiXmlElement* pRoot = doc.RootElement();
if( pRoot == nullptr )
{
return;
}
//Access the root's first "Root" Element
//TiXmlElement* pAnimation = pRoot->FirstChildElement( "Root" );
//Access the root's first "animation" Element
TiXmlElement* pAnimation = pRoot->FirstChildElement();
if( pAnimation == nullptr )
{
return;
}
while( pAnimation != nullptr )
{
//Access the root's first "animation_info" Element
TiXmlElement* pAnimationInfo = pAnimation->FirstChildElement();
//pAnimation = pAnimation->FirstChildElement();
if( pAnimationInfo == nullptr )
{
return;
}
//Get all the animations
while( pAnimationInfo != nullptr )
{
Animation* a = new Animation;
//Access the animation element's name
string szText = "";
szText = pAnimationInfo->Attribute( "name" );
if( szText != "" )
{
a->SetName( szText );
}
Loaded[ a->GetName() ] = a;
//Get the looping bool
bool bLoops;
int temp;
pAnimationInfo->Attribute( "looping" , &temp );
//bLoops = temp;
if( temp > 0 )
bLoops = true;
else
bLoops = false;
Loaded[ a->GetName() ]->SetLooping( bLoops );
//Get the filepath for the image
string path = "resource/graphics/";
string tName = "";
tName = pAnimationInfo->Attribute( "hTexture" );
path += tName;
SGD::HTexture m_hImage = SGD::INVALID_HANDLE;
m_hImage = pGraphics->LoadTexture( path.c_str() );
Loaded[ a->GetName() ]->SetImage( m_hImage );
//Clear the frames vector
Loaded[ a->GetName() ]->GetFrameVector().clear();
//Get the number of frames in the animation
int nFrames = 0;
pAnimationInfo->Attribute( "numFrames" , &nFrames );
//Access the animations's first "frame" Element
TiXmlElement* pFrame = pAnimationInfo->FirstChildElement();
//get each of the frames in the image
while( pFrame != nullptr )
{
Frame f;
/*<frame duration="0.5" damage="0" event="none" dLeft="4" dTop="520" dRight="47" dBottom="580" cLeft="4" cTop="520" cRight="47" cBottom="580" x="24" y="577"/>*/
//Get the frame's duration
double dur;
pFrame->Attribute( "duration" , &dur );
f.SetDuration( ( float ) dur );
//Get the frame's damage
int dam;
pFrame->Attribute( "damage" , &dam );
f.SetDamage( dam );
//Get the frame's event name
string eve = "";
eve = pFrame->Attribute( "event" );
f.SetEventName( eve );
//Get the drawRect
SGD::Rectangle dRect;
//Get the drawRect left
int dleft;
pFrame->Attribute( "dLeft" , &dleft );
//Get the drawRect top
int dtop;
pFrame->Attribute( "dTop" , &dtop );
//Get the drawRect right
int drig;
pFrame->Attribute( "dRight" , &drig );
//Get the drawRect bottom
int dbot;
pFrame->Attribute( "dBottom" , &dbot );
//set the drect left/top/bottom/right to the read in variables
dRect.left = ( float ) dleft;
dRect.top = ( float ) dtop;
dRect.right = ( float ) drig;
dRect.bottom = ( float ) dbot;
//set the frame's draw rect to the drect
f.SetDrawRect( dRect );
//Get the collisionRect
SGD::Rectangle cRect;
//Get the collisionRect left
int cleft;
pFrame->Attribute( "cLeft" , &cleft );
//Get the collisionRect top
int ctop;
pFrame->Attribute( "cTop" , &ctop );
//Get the collisionRect right
int crig;
pFrame->Attribute( "cRight" , &crig );
//Get the collisionRect bottom
int cbot;
pFrame->Attribute( "cBottom" , &cbot );
//set the crect left/top/bottom/right to the read in variables
cRect.left = ( float ) cleft;
cRect.top = ( float ) ctop;
cRect.right = ( float ) crig;
cRect.bottom = ( float ) cbot;
//add the crect to the frame collisionrects vector
f.AddCollisionRect( cRect );
//Get anchor point
SGD::Point aP;
//Get anchor point x
int aX;
pFrame->Attribute( "x" , &aX );
//Get anchor point y
int aY;
pFrame->Attribute( "y" , &aY );
aP.x = ( float ) aX;
aP.y = ( float ) aY;
f.SetAnchorPoint( aP );
//Add the new frame to a's frame vector
Loaded[ a->GetName() ]->AddFrame( f );
//Move to the next "frame" Sibling Element if there are more frames
pFrame = pFrame->NextSiblingElement();
}
pAnimationInfo = pAnimationInfo->NextSiblingElement();
}
pAnimation = pAnimation->NextSiblingElement();
}
}
void AnimationManager::AddToAnimationMap( Animation* animation )
{
if( animation != nullptr )
{
Loaded[ animation->GetName() ] = animation;
}
}
int AnimationManager::CheckSize()
{
return Loaded.size();
}<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_obus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Obus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 1
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_obus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgObus(void* const iImagePtr, uint8_t*& oObusImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getObusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oObusImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oObusImgPtr, P9_XIP_SECTION_IOPPE_IOO_NV, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oObusImgPtr = ppeSection.iv_offset + (uint8_t*)(oObusImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getObusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_OBUS& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_obus_image_build(CONST_OBUS& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_obus_image_build.");
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000009011040ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pObusImg = NULL;
uint32_t imgSize = 0;
FAPI_TRY(extractPpeImgObus(iHwImagePtr, pObusImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pObusImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pObusImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pObusImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pObusImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pObusImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pObusImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pObusImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pObusImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
fapi_try_exit:
FAPI_IMP("Exit p9_io_obus_image_build.");
return fapi2::current_err;
}
<commit_msg>I/O Metadata Cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_obus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Obus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 3
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_obus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgObus(void* const iImagePtr, uint8_t*& oObusImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getObusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oObusImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oObusImgPtr, P9_XIP_SECTION_IOPPE_IOO_NV, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oObusImgPtr = ppeSection.iv_offset + (uint8_t*)(oObusImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getObusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_OBUS& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_obus_image_build(CONST_OBUS& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_obus_image_build.");
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000009011040ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pObusImg = NULL;
uint32_t imgSize = 0;
FAPI_TRY(extractPpeImgObus(iHwImagePtr, pObusImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pObusImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pObusImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pObusImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pObusImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pObusImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pObusImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pObusImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pObusImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
fapi_try_exit:
FAPI_IMP("Exit p9_io_obus_image_build.");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>#include <xzero/executor/NativeScheduler.h>
#include <xzero/RuntimeError.h>
#include <xzero/WallClock.h>
#include <xzero/sysconfig.h>
#include <algorithm>
#include <vector>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
namespace xzero {
#define PIPE_READ_END 0
#define PIPE_WRITE_END 1
/**
* XXX
* - registering a key should be *ONESHOT* and *Edge Triggered*
* - remove SelectionKey::change()
* - add SelectionKey::cancel()
* - do we need Selectable then (just use EndPoinit or `int fd`?)
* - endpoint: operator int() { return handle(); }
* - maybe inherit from Executor
* - add a way to add timed callbacks that can be cancelled
* - actual implementations inheriting from: Selector < Scheduler < Executor
* - select: SelectEventLoop (currently: NativeScheduler)
* - epoll: LinuxEventLoop
*
*/
NativeScheduler::NativeScheduler(
std::function<void(const std::exception&)> errorLogger,
WallClock* clock,
std::function<void()> preInvoke,
std::function<void()> postInvoke)
: Scheduler(std::move(errorLogger)),
clock_(clock ? clock : WallClock::system()),
lock_(),
wakeupPipe_(),
onPreInvokePending_(preInvoke),
onPostInvokePending_(postInvoke) {
if (pipe(wakeupPipe_) < 0) {
throw SYSTEM_ERROR(errno);
}
fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK);
fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK);
}
NativeScheduler::NativeScheduler(
std::function<void(const std::exception&)> errorLogger,
WallClock* clock)
: NativeScheduler(errorLogger, clock, nullptr, nullptr) {
}
NativeScheduler::NativeScheduler()
: NativeScheduler(nullptr, nullptr, nullptr, nullptr) {
}
NativeScheduler::~NativeScheduler() {
::close(wakeupPipe_[PIPE_READ_END]);
::close(wakeupPipe_[PIPE_WRITE_END]);
}
void NativeScheduler::execute(Task&& task) {
{
std::lock_guard<std::mutex> lk(lock_);
tasks_.push_back(task);
}
breakLoop();
}
std::string NativeScheduler::toString() const {
return "NativeScheduler";
}
Scheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) {
auto onCancel = [this](Handle* handle) {
removeFromTimersList(handle);
};
return insertIntoTimersList(clock_->get() + delay,
std::make_shared<Handle>(task, onCancel));
}
Scheduler::HandleRef NativeScheduler::executeAt(DateTime when, Task task) {
auto onCancel = [this](Handle* handle) {
removeFromTimersList(handle);
};
//return insertIntoTimersList(when, std::make_shared<Handle>(task, onCancel));
return insertIntoTimersList(when, std::make_shared<Handle>(task,
std::bind(&NativeScheduler::removeFromTimersList, this, std::placeholders::_1)));
}
Scheduler::HandleRef NativeScheduler::insertIntoTimersList(DateTime dt,
HandleRef handle) {
Timer t = { dt, handle };
std::lock_guard<std::mutex> lk(lock_);
auto i = timers_.end();
auto e = timers_.begin();
while (i != e) {
i--;
const Timer& current = *i;
if (current.when >= t.when) {
timers_.insert(i, t);
return handle;
}
}
if (i == e) {
timers_.push_front(t);
}
return handle;
}
void NativeScheduler::removeFromTimersList(Handle* handle) {
std::lock_guard<std::mutex> lk(lock_);
auto i = timers_.begin();
auto e = timers_.end();
while (i != e) {
if (i->handle.get() == handle) {
timers_.erase(i);
break;
}
i++;
}
}
void NativeScheduler::collectTimeouts() {
const DateTime now = clock_->get();
std::lock_guard<std::mutex> lk(lock_);
for (;;) {
if (timers_.empty())
break;
const Timer& job = timers_.front();
if (job.when > now)
break;
tasks_.push_back(job.handle->getAction());
timers_.pop_front();
}
}
inline Scheduler::HandleRef registerInterest(
std::mutex* registryLock,
std::list<std::pair<int, Scheduler::HandleRef>>* registry,
int fd,
Executor::Task task) {
auto onCancel = [=](Scheduler::Handle* h) {
std::lock_guard<std::mutex> lk(*registryLock);
for (auto i: *registry) {
if (i.second.get() == h) {
return registry->remove(i);
}
}
};
std::lock_guard<std::mutex> lk(*registryLock);
auto handle = std::make_shared<Scheduler::Handle>(task, onCancel);
registry->push_back(std::make_pair(fd, handle));
return handle;
}
Scheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) {
return registerInterest(&lock_, &readers_, fd, task);
}
Scheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) {
return registerInterest(&lock_, &writers_, fd, task);
}
inline void collectActiveHandles(
std::list<std::pair<int, Scheduler::HandleRef>>* interests,
fd_set* fdset,
std::vector<Scheduler::HandleRef>* result) {
auto i = interests->begin();
auto e = interests->end();
while (i != e) {
if (FD_ISSET(i->first, fdset)) {
result->push_back(i->second);
auto k = i;
++i;
interests->erase(k);
} else {
i++;
}
}
}
size_t NativeScheduler::timerCount() {
std::lock_guard<std::mutex> lk(lock_);
return timers_.size();
}
size_t NativeScheduler::readerCount() {
std::lock_guard<std::mutex> lk(lock_);
return readers_.size();
}
size_t NativeScheduler::writerCount() {
std::lock_guard<std::mutex> lk(lock_);
return writers_.size();
}
void NativeScheduler::runLoopOnce() {
fd_set input, output, error;
FD_ZERO(&input);
FD_ZERO(&output);
FD_ZERO(&error);
int wmark = 0;
timeval tv;
{
std::lock_guard<std::mutex> lk(lock_);
for (auto i: readers_) {
FD_SET(i.first, &input);
if (i.first > wmark) {
wmark = i.first;
}
}
for (auto i: writers_) {
FD_SET(i.first, &output);
if (i.first > wmark) {
wmark = i.first;
}
}
const TimeSpan nextTimeout = !tasks_.empty()
? TimeSpan::Zero
: !timers_.empty()
? timers_.front().when - clock_->get()
: TimeSpan::fromSeconds(4);
tv.tv_sec = static_cast<time_t>(nextTimeout.totalSeconds()),
tv.tv_usec = nextTimeout.microseconds();
}
FD_SET(wakeupPipe_[PIPE_READ_END], &input);
int rv = ::select(wmark + 1, &input, &output, &error, &tv);
if (rv < 0)
throw SYSTEM_ERROR(errno);
if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) {
bool consumeMore = true;
while (consumeMore) {
char buf[sizeof(int) * 128];
consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0;
}
}
collectTimeouts();
std::vector<HandleRef> activeHandles;
activeHandles.reserve(rv);
std::deque<Task> activeTasks;
{
std::lock_guard<std::mutex> lk(lock_);
collectActiveHandles(&readers_, &input, &activeHandles);
collectActiveHandles(&writers_, &output, &activeHandles);
activeTasks = std::move(tasks_);
}
safeCall(onPreInvokePending_);
safeCallEach(activeHandles);
safeCallEach(activeTasks);
safeCall(onPostInvokePending_);
}
void NativeScheduler::breakLoop() {
int dummy = 42;
::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy));
}
} // namespace xzero
<commit_msg>eliminate dead conditions. thx paul ;)<commit_after>#include <xzero/executor/NativeScheduler.h>
#include <xzero/RuntimeError.h>
#include <xzero/WallClock.h>
#include <xzero/sysconfig.h>
#include <algorithm>
#include <vector>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
namespace xzero {
#define PIPE_READ_END 0
#define PIPE_WRITE_END 1
/**
* XXX
* - registering a key should be *ONESHOT* and *Edge Triggered*
* - remove SelectionKey::change()
* - add SelectionKey::cancel()
* - do we need Selectable then (just use EndPoinit or `int fd`?)
* - endpoint: operator int() { return handle(); }
* - maybe inherit from Executor
* - add a way to add timed callbacks that can be cancelled
* - actual implementations inheriting from: Selector < Scheduler < Executor
* - select: SelectEventLoop (currently: NativeScheduler)
* - epoll: LinuxEventLoop
*
*/
NativeScheduler::NativeScheduler(
std::function<void(const std::exception&)> errorLogger,
WallClock* clock,
std::function<void()> preInvoke,
std::function<void()> postInvoke)
: Scheduler(std::move(errorLogger)),
clock_(clock ? clock : WallClock::system()),
lock_(),
wakeupPipe_(),
onPreInvokePending_(preInvoke),
onPostInvokePending_(postInvoke) {
if (pipe(wakeupPipe_) < 0) {
throw SYSTEM_ERROR(errno);
}
fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK);
fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK);
}
NativeScheduler::NativeScheduler(
std::function<void(const std::exception&)> errorLogger,
WallClock* clock)
: NativeScheduler(errorLogger, clock, nullptr, nullptr) {
}
NativeScheduler::NativeScheduler()
: NativeScheduler(nullptr, nullptr, nullptr, nullptr) {
}
NativeScheduler::~NativeScheduler() {
::close(wakeupPipe_[PIPE_READ_END]);
::close(wakeupPipe_[PIPE_WRITE_END]);
}
void NativeScheduler::execute(Task&& task) {
{
std::lock_guard<std::mutex> lk(lock_);
tasks_.push_back(task);
}
breakLoop();
}
std::string NativeScheduler::toString() const {
return "NativeScheduler";
}
Scheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) {
auto onCancel = [this](Handle* handle) {
removeFromTimersList(handle);
};
return insertIntoTimersList(clock_->get() + delay,
std::make_shared<Handle>(task, onCancel));
}
Scheduler::HandleRef NativeScheduler::executeAt(DateTime when, Task task) {
auto onCancel = [this](Handle* handle) {
removeFromTimersList(handle);
};
//return insertIntoTimersList(when, std::make_shared<Handle>(task, onCancel));
return insertIntoTimersList(when, std::make_shared<Handle>(task,
std::bind(&NativeScheduler::removeFromTimersList, this, std::placeholders::_1)));
}
Scheduler::HandleRef NativeScheduler::insertIntoTimersList(DateTime dt,
HandleRef handle) {
Timer t = { dt, handle };
std::lock_guard<std::mutex> lk(lock_);
auto i = timers_.end();
auto e = timers_.begin();
while (i != e) {
i--;
const Timer& current = *i;
if (current.when >= t.when) {
timers_.insert(i, t);
return handle;
}
}
timers_.push_front(t);
return handle;
}
void NativeScheduler::removeFromTimersList(Handle* handle) {
std::lock_guard<std::mutex> lk(lock_);
auto i = timers_.begin();
auto e = timers_.end();
while (i != e) {
if (i->handle.get() == handle) {
timers_.erase(i);
break;
}
i++;
}
}
void NativeScheduler::collectTimeouts() {
const DateTime now = clock_->get();
std::lock_guard<std::mutex> lk(lock_);
for (;;) {
if (timers_.empty())
break;
const Timer& job = timers_.front();
if (job.when > now)
break;
tasks_.push_back(job.handle->getAction());
timers_.pop_front();
}
}
inline Scheduler::HandleRef registerInterest(
std::mutex* registryLock,
std::list<std::pair<int, Scheduler::HandleRef>>* registry,
int fd,
Executor::Task task) {
auto onCancel = [=](Scheduler::Handle* h) {
std::lock_guard<std::mutex> lk(*registryLock);
for (auto i: *registry) {
if (i.second.get() == h) {
return registry->remove(i);
}
}
};
std::lock_guard<std::mutex> lk(*registryLock);
auto handle = std::make_shared<Scheduler::Handle>(task, onCancel);
registry->push_back(std::make_pair(fd, handle));
return handle;
}
Scheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) {
return registerInterest(&lock_, &readers_, fd, task);
}
Scheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) {
return registerInterest(&lock_, &writers_, fd, task);
}
inline void collectActiveHandles(
std::list<std::pair<int, Scheduler::HandleRef>>* interests,
fd_set* fdset,
std::vector<Scheduler::HandleRef>* result) {
auto i = interests->begin();
auto e = interests->end();
while (i != e) {
if (FD_ISSET(i->first, fdset)) {
result->push_back(i->second);
auto k = i;
++i;
interests->erase(k);
} else {
i++;
}
}
}
size_t NativeScheduler::timerCount() {
std::lock_guard<std::mutex> lk(lock_);
return timers_.size();
}
size_t NativeScheduler::readerCount() {
std::lock_guard<std::mutex> lk(lock_);
return readers_.size();
}
size_t NativeScheduler::writerCount() {
std::lock_guard<std::mutex> lk(lock_);
return writers_.size();
}
void NativeScheduler::runLoopOnce() {
fd_set input, output, error;
FD_ZERO(&input);
FD_ZERO(&output);
FD_ZERO(&error);
int wmark = 0;
timeval tv;
{
std::lock_guard<std::mutex> lk(lock_);
for (auto i: readers_) {
FD_SET(i.first, &input);
if (i.first > wmark) {
wmark = i.first;
}
}
for (auto i: writers_) {
FD_SET(i.first, &output);
if (i.first > wmark) {
wmark = i.first;
}
}
const TimeSpan nextTimeout = !tasks_.empty()
? TimeSpan::Zero
: !timers_.empty()
? timers_.front().when - clock_->get()
: TimeSpan::fromSeconds(4);
tv.tv_sec = static_cast<time_t>(nextTimeout.totalSeconds()),
tv.tv_usec = nextTimeout.microseconds();
}
FD_SET(wakeupPipe_[PIPE_READ_END], &input);
int rv = ::select(wmark + 1, &input, &output, &error, &tv);
if (rv < 0)
throw SYSTEM_ERROR(errno);
if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) {
bool consumeMore = true;
while (consumeMore) {
char buf[sizeof(int) * 128];
consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0;
}
}
collectTimeouts();
std::vector<HandleRef> activeHandles;
activeHandles.reserve(rv);
std::deque<Task> activeTasks;
{
std::lock_guard<std::mutex> lk(lock_);
collectActiveHandles(&readers_, &input, &activeHandles);
collectActiveHandles(&writers_, &output, &activeHandles);
activeTasks = std::move(tasks_);
}
safeCall(onPreInvokePending_);
safeCallEach(activeHandles);
safeCallEach(activeTasks);
safeCall(onPostInvokePending_);
}
void NativeScheduler::breakLoop() {
int dummy = 42;
::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy));
}
} // namespace xzero
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 2
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getXbusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getXbusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_xbus_image_build.");
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000006010840ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pPpeImg = NULL;
uint32_t imgSize = 0;
// Get vector of xbus units from the processor
auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();
// Make sure we have functional xbus units before we load the ppe
if(!xbusUnits.empty())
{
FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
}
else
{
FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
}
fapi_try_exit:
FAPI_IMP("Exit p9_io_xbus_image_build.");
return fapi2::current_err;
}
<commit_msg>I/O Metadata Cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 3
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getXbusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getXbusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_xbus_image_build.");
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000006010840ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pPpeImg = NULL;
uint32_t imgSize = 0;
// Get vector of xbus units from the processor
auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();
// Make sure we have functional xbus units before we load the ppe
if(!xbusUnits.empty())
{
FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
}
else
{
FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
}
fapi_try_exit:
FAPI_IMP("Exit p9_io_xbus_image_build.");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>
#include "game.hpp"
#ifdef GAME_NO_RENDER_WINDOW
#include <GL/glew.h>
#endif
// set packfile name/filepath if one is being used
#define PACKFILE_NAME ""
// set to true if a packfile is being used
#define IS_USING_PACKFILE false
// if not using cmake to build and using the ResourcePacker lib,
// define ResourcePacker_FOUND
#if defined(ResourcePacker_FOUND)
#else
# define IS_USING_PACKFILE false
#endif
#if IS_USING_PACKFILE == true
# define RESOURCE_MANAGER_MODE GameResources::PACKFILE
#else
# define RESOURCE_MANAGER_MODE GameResources::DEFAULT
#endif
Game::Game()
: window(sf::VideoMode(720,480), "SFML App"),
resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME),
mPlayer(),
sPlayer(),
stateStack(),
context(window, resourceManager, mPlayer, sPlayer, ecEngine, isQuitting, connection, clearColor),
isQuitting(false),
connection()
{
registerResources();
registerStates();
frameTime = sf::seconds(1.f / 60.f);
}
void Game::run()
{
sf::Clock clock;
sf::Time lastUpdateTime = sf::Time::Zero;
while (window.isOpen() && !isQuitting)
{
lastUpdateTime += clock.restart();
while (lastUpdateTime > frameTime)
{
lastUpdateTime -= frameTime;
processEvents();
update(frameTime);
}
draw();
}
if(window.isOpen())
window.close();
}
void Game::processEvents()
{
sf::Event event;
while (window.pollEvent(event))
{
stateStack.handleEvent(event, context);
if(event.type == sf::Event::Closed)
window.close();
}
}
void Game::update(sf::Time deltaTime)
{
stateStack.update(deltaTime, context);
if(connection)
{
connection->update(deltaTime);
}
}
void Game::draw()
{
#ifndef GAME_NO_RENDER_WINDOW
window.clear(clearColor);
#else
float r = (float) clearColor.r / 255.0f;
float g = (float) clearColor.g / 255.0f;
float b = (float) clearColor.b / 255.0f;
float a = (float) clearColor.a / 255.0f;
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT);
#endif
stateStack.draw(context);
window.display();
}
// register resources via resourceManager
// Resource IDs must be listed in resourceIdentifiers.hpp
void Game::registerResources()
{
}
// register states via stateStack
// State IDs must be listed in stateIdentifiers.hpp
void Game::registerStates()
{
}
<commit_msg>Changed defaults for OpenGL window<commit_after>
#include "game.hpp"
#ifdef GAME_NO_RENDER_WINDOW
#include <GL/glew.h>
#endif
#ifndef NDEBUG
#include <iostream>
#endif
// set packfile name/filepath if one is being used
#define PACKFILE_NAME ""
// set to true if a packfile is being used
#define IS_USING_PACKFILE false
// if not using cmake to build and using the ResourcePacker lib,
// define ResourcePacker_FOUND
#if defined(ResourcePacker_FOUND)
#else
# define IS_USING_PACKFILE false
#endif
#if IS_USING_PACKFILE == true
# define RESOURCE_MANAGER_MODE GameResources::PACKFILE
#else
# define RESOURCE_MANAGER_MODE GameResources::DEFAULT
#endif
Game::Game()
: window(sf::VideoMode(720,480), "SFML App"),
resourceManager(&stateStack, RESOURCE_MANAGER_MODE, PACKFILE_NAME),
mPlayer(),
sPlayer(),
stateStack(),
context(window, resourceManager, mPlayer, sPlayer, ecEngine, isQuitting, connection, clearColor),
isQuitting(false),
connection()
{
registerResources();
registerStates();
frameTime = sf::seconds(1.f / 60.f);
#ifdef GAME_NO_RENDER_WINDOW
sf::ContextSettings settings = window.getSettings();
settings.depthBits = 24;
settings.stencilBits = 8;
settings.majorVersion = 3;
settings.minorVersion = 2;
window.create(sf::VideoMode(720,480), "SFML App", sf::Style::Default, settings);
#ifndef NDEBUG
settings = window.getSettings();
std::cout << "depth bits:" << settings.depthBits << std::endl;
std::cout << "stencil bits:" << settings.stencilBits << std::endl;
std::cout << "antialiasing level:" << settings.antialiasingLevel << std::endl;
std::cout << "version:" << settings.majorVersion << "." << settings.minorVersion << std::endl;
#endif
#endif
}
void Game::run()
{
sf::Clock clock;
sf::Time lastUpdateTime = sf::Time::Zero;
while (window.isOpen() && !isQuitting)
{
lastUpdateTime += clock.restart();
while (lastUpdateTime > frameTime)
{
lastUpdateTime -= frameTime;
processEvents();
update(frameTime);
}
draw();
}
if(window.isOpen())
window.close();
}
void Game::processEvents()
{
sf::Event event;
while (window.pollEvent(event))
{
stateStack.handleEvent(event, context);
if(event.type == sf::Event::Closed)
window.close();
}
}
void Game::update(sf::Time deltaTime)
{
stateStack.update(deltaTime, context);
if(connection)
{
connection->update(deltaTime);
}
}
void Game::draw()
{
#ifndef GAME_NO_RENDER_WINDOW
window.clear(clearColor);
#else
float r = (float) clearColor.r / 255.0f;
float g = (float) clearColor.g / 255.0f;
float b = (float) clearColor.b / 255.0f;
float a = (float) clearColor.a / 255.0f;
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT);
#endif
stateStack.draw(context);
window.display();
}
// register resources via resourceManager
// Resource IDs must be listed in resourceIdentifiers.hpp
void Game::registerResources()
{
}
// register states via stateStack
// State IDs must be listed in stateIdentifiers.hpp
void Game::registerStates()
{
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <bench/data.h>
#include <rpc/blockchain.h>
#include <streams.h>
#include <validation.h>
#include <univalue.h>
static void BlockToJsonVerbose(benchmark::Bench& bench)
{
CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
CBlock block;
stream >> block;
CBlockIndex blockindex;
const uint256 blockHash = block.GetHash();
blockindex.phashBlock = &blockHash;
blockindex.nBits = 403014710;
bench.run([&] {
(void)blockToJSON(block, &blockindex, &blockindex, /*verbose*/ true);
});
}
BENCHMARK(BlockToJsonVerbose);
<commit_msg>Fix BlockToJsonVerbose benchmark<commit_after>// Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <bench/data.h>
#include <rpc/blockchain.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <validation.h>
#include <univalue.h>
static void BlockToJsonVerbose(benchmark::Bench& bench)
{
TestingSetup test_setup{};
CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
char a = '\0';
stream.write(&a, 1); // Prevent compaction
CBlock block;
stream >> block;
CBlockIndex blockindex;
const uint256 blockHash = block.GetHash();
blockindex.phashBlock = &blockHash;
blockindex.nBits = 403014710;
bench.run([&] {
(void)blockToJSON(block, &blockindex, &blockindex, /*verbose*/ true);
});
}
BENCHMARK(BlockToJsonVerbose);
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#define SEQAN_PROFILE
#ifndef RELEASE
//#define SEQAN_DEBUG
//#define SEQAN_TEST
#endif
#include <string>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/map.h>
#include <seqan/refinement.h>
#include <seqan/store.h>
#include <seqan/misc/misc_cmdparser.h>
#include "base.h"
#include "read_gff.h"
#include "read_gtf.h"
#include "create_gff.h"
#include "fusion.h"
#include "overlap_module.h"
using namespace seqan;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
////// main
///////////////////////////////////////////////////////////////////////////////
int main( int argc, const char *argv[] )
{
CharString nameSAM;
CharString nameGFF;
CharString outputPath;
unsigned nTuple;
unsigned offsetInterval;
unsigned thresholdGaps;
unsigned thresholdCount;
double thresholdRPKM = 0.0;
bool maxTuple = 0;
bool exact_nTuple = 0;
bool unknownO = 0;
bool fusion = 0;
bool gtf = 0;
CommandLineParser parser;
//////////////////////////////////////////////////////////////////////////////
// Define options
addTitleLine(parser, "**********************************************************************");
addTitleLine(parser, "*** INSEGT ***");
addTitleLine(parser, "*** INtersecting SEcond Generation sequencing daTa with annotation ***");
addTitleLine(parser, "**********************************************************************");
addSection(parser, "Main Options:");
addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM-file with aligned reads", (int)OptionType::String), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("g", "gff", "GFF_file with annotations", (int)OptionType::String), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("p", "outputPath", "path for output-files", (int)OptionType::String, ""), "<String>"));
addOption(parser, addArgumentText(CommandLineOption("n", "nTuple", "nTuple", (int)OptionType::Int, 2), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("o", "offsetInterval", "offset to short alignment-intervals for search", (int)OptionType::Int, 5), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("t", "thresholdGaps", "threshold for allowed gaps in alignment (not introns)", (int)OptionType::Int, 5), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("c", "thresholdCount", "threshold for min. count of tuple for output", (int)OptionType::Int, 1), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("r", "thresholdRPKM", "threshold for min. RPKM of tuple for output", (int)OptionType::Double, 0.0), "<Double>"));
addOption(parser, CommandLineOption("m", "maxTuple", "create only maxTuple", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("e", "exact_nTuple", "create only Tuple of exact length n", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("u", "unknown_orientation", "orientation of reads is unknown", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("f", "fusion_genes", "check for fusion genes and create separate output for matepair tuple", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("z", "gtf", "GTF-format as input (instead of GFF-format)", (int)OptionType::Boolean));
if (argc == 1)
{
shortHelp(parser, cerr); // print short help and exit
return 0;
}
if (!parse(parser, argc, argv, ::std::cerr)) return 1;
getOptionValueLong(parser, "sam", nameSAM);
getOptionValueLong(parser, "gff", nameGFF);
getOptionValueLong(parser, "outputPath", outputPath);
getOptionValueLong(parser, "nTuple", nTuple);
getOptionValueLong(parser, "offsetInterval", offsetInterval);
getOptionValueLong(parser, "thresholdGaps", thresholdGaps);
getOptionValueLong(parser, "thresholdCount", thresholdCount);
getOptionValueLong(parser, "thresholdRPKM", thresholdRPKM);
if (isSetLong(parser, "maxTuple")) maxTuple = 1;
if (isSetLong(parser, "exact_nTuple")) exact_nTuple = 1;
if (isSetLong(parser, "unknown_orientation")) unknownO = 1;
if (isSetLong(parser, "fusion_genes")) fusion = 1;
if (isSetLong(parser, "gtf")) gtf = 1;
if (maxTuple)
{
nTuple = 0; // sign for maxTuple
exact_nTuple = 0; // not both possible: maxTuple is prefered over exact_nTuple and n
}
ngsOverlapper(nameSAM, nameGFF, outputPath, nTuple, exact_nTuple, thresholdGaps, offsetInterval, thresholdCount, thresholdRPKM, unknownO, fusion, gtf);
return 0;
}
<commit_msg><commit_after>#include <fstream>
#include <iostream>
#include <sstream>
#define SEQAN_PROFILE
#ifndef RELEASE
//#define SEQAN_DEBUG
//#define SEQAN_TEST
#endif
#include <string>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/map.h>
#include <seqan/refinement.h>
#include <seqan/store.h>
#include <seqan/misc/misc_cmdparser.h>
#include "base.h"
#include "read_gff.h"
#include "read_gtf.h"
#include "create_gff.h"
#include "fusion.h"
#include "overlap_module.h"
using namespace seqan;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
////// main
///////////////////////////////////////////////////////////////////////////////
int main( int argc, const char *argv[] )
{
CharString nameSAM;
CharString nameGFF;
CharString outputPath;
unsigned nTuple;
unsigned offsetInterval;
unsigned thresholdGaps;
unsigned thresholdCount;
double thresholdRPKM = 0.0;
bool maxTuple = 0;
bool exact_nTuple = 0;
bool unknownO = 0;
bool fusion = 0;
bool gtf = 0;
CommandLineParser parser;
//////////////////////////////////////////////////////////////////////////////
// Define options
addTitleLine(parser, "**********************************************************************");
addTitleLine(parser, "*** INSEGT ***");
addTitleLine(parser, "*** INtersecting SEcond Generation sequencing daTa with annotation ***");
addTitleLine(parser, "**********************************************************************");
addSection(parser, "Main Options:");
addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM-file with aligned reads", (int)OptionType::String), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("g", "gff", "GFF_file with annotations", (int)OptionType::String), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("p", "outputPath", "path for output-files", (int)OptionType::String, ""), "<String>"));
addOption(parser, addArgumentText(CommandLineOption("n", "nTuple", "nTuple", (int)OptionType::Int, 2), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("o", "offsetInterval", "offset to short alignment-intervals for search", (int)OptionType::Int, 5), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("t", "thresholdGaps", "threshold for allowed gaps in alignment (not introns)", (int)OptionType::Int, 5), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("c", "thresholdCount", "threshold for min. count of tuple for output", (int)OptionType::Int, 1), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("r", "thresholdRPKM", "threshold for min. RPKM of tuple for output", (int)OptionType::Double, 0.0), "<Double>"));
addOption(parser, CommandLineOption("m", "maxTuple", "create only maxTuple", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("e", "exact_nTuple", "create only Tuple of exact length n", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("u", "unknown_orientation", "orientation of reads is unknown", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("f", "fusion_genes", "check for fusion genes and create separate output for matepair tuple", (int)OptionType::Boolean));
addOption(parser, CommandLineOption("z", "gtf", "GTF-format as input for annotation (instead of GFF-format)", (int)OptionType::Boolean));
if (argc == 1)
{
shortHelp(parser, cerr); // print short help and exit
return 0;
}
if (!parse(parser, argc, argv, ::std::cerr)) return 1;
getOptionValueLong(parser, "sam", nameSAM);
getOptionValueLong(parser, "gff", nameGFF);
getOptionValueLong(parser, "outputPath", outputPath);
getOptionValueLong(parser, "nTuple", nTuple);
getOptionValueLong(parser, "offsetInterval", offsetInterval);
getOptionValueLong(parser, "thresholdGaps", thresholdGaps);
getOptionValueLong(parser, "thresholdCount", thresholdCount);
getOptionValueLong(parser, "thresholdRPKM", thresholdRPKM);
if (isSetLong(parser, "maxTuple")) maxTuple = 1;
if (isSetLong(parser, "exact_nTuple")) exact_nTuple = 1;
if (isSetLong(parser, "unknown_orientation")) unknownO = 1;
if (isSetLong(parser, "fusion_genes")) fusion = 1;
if (isSetLong(parser, "gtf")) gtf = 1;
if (maxTuple)
{
nTuple = 0; // sign for maxTuple
exact_nTuple = 0; // not both possible: maxTuple is prefered over exact_nTuple and n
}
ngsOverlapper(nameSAM, nameGFF, outputPath, nTuple, exact_nTuple, thresholdGaps, offsetInterval, thresholdCount, thresholdRPKM, unknownO, fusion, gtf);
return 0;
}
<|endoftext|>
|
<commit_before>// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -shared -o %T/libignore_lib4.so
// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: echo "called_from_lib:libignore_lib4.so" > %t.supp
// RUN: %env_tsan_opts=suppressions='%t.supp' %run %t 2>&1 | FileCheck %s
// Longjmp assembly has not been implemented for mips64 yet
// XFAIL: mips64
// ppc64be bots failed with "FileCheck error: '-' is empty".
// UNSUPPORTED: powerpc64
// aarch64 bots failed with "called_from_lib suppression 'libignore_lib4.so'
// is matched against 2 libraries".
// UNSUPPORTED: aarch64
// Test longjmp in ignored lib.
// It used to crash since we jumped out of ScopedInterceptor scope.
#include "test.h"
#include <setjmp.h>
#include <string.h>
#include <errno.h>
#include <libgen.h>
#include <string>
#ifdef LIB
extern "C" void myfunc() {
for (int i = 0; i < (1 << 20); i++) {
jmp_buf env;
if (!setjmp(env))
longjmp(env, 1);
}
}
#else
int main(int argc, char **argv) {
std::string lib = std::string(dirname(argv[0])) + "/libignore_lib4.so";
void *h = dlopen(lib.c_str(), RTLD_GLOBAL | RTLD_NOW);
void (*func)() = (void(*)())dlsym(h, "myfunc");
func();
fprintf(stderr, "DONE\n");
return 0;
}
#endif
// CHECK: DONE
<commit_msg>[powerpc] reactivate ignore_lib4.cc on powerpc64le<commit_after>// RUN: %clangxx_tsan -O1 %s -DLIB -fPIC -shared -o %T/libignore_lib4.so
// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: echo "called_from_lib:libignore_lib4.so" > %t.supp
// RUN: %env_tsan_opts=suppressions='%t.supp' %run %t 2>&1 | FileCheck %s
// Longjmp assembly has not been implemented for mips64 yet
// XFAIL: mips64
// powerpc64 big endian bots failed with "FileCheck error: '-' is empty" due
// to a segmentation fault.
// UNSUPPORTED: powerpc64-unknown-linux-gnu
// aarch64 bots failed with "called_from_lib suppression 'libignore_lib4.so'
// is matched against 2 libraries".
// UNSUPPORTED: aarch64
// Test longjmp in ignored lib.
// It used to crash since we jumped out of ScopedInterceptor scope.
#include "test.h"
#include <setjmp.h>
#include <string.h>
#include <errno.h>
#include <libgen.h>
#include <string>
#ifdef LIB
extern "C" void myfunc() {
for (int i = 0; i < (1 << 20); i++) {
jmp_buf env;
if (!setjmp(env))
longjmp(env, 1);
}
}
#else
int main(int argc, char **argv) {
std::string lib = std::string(dirname(argv[0])) + "/libignore_lib4.so";
void *h = dlopen(lib.c_str(), RTLD_GLOBAL | RTLD_NOW);
void (*func)() = (void(*)())dlsym(h, "myfunc");
func();
fprintf(stderr, "DONE\n");
return 0;
}
#endif
// CHECK: DONE
<|endoftext|>
|
<commit_before>#pragma once
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/version.hpp>
#include "blackhole/error.hpp"
#include "blackhole/factory.hpp"
#include "blackhole/sink/files/rotation.hpp"
namespace blackhole {
namespace sink {
class boost_backend_t {
const boost::filesystem::path m_path;
boost::filesystem::ofstream m_file;
public:
boost_backend_t(const std::string& path) :
m_path(path)
{
}
bool opened() const {
return m_file.is_open();
}
bool exists(const std::string& filename) const {
return boost::filesystem::exists(m_path.parent_path() / filename);
}
std::vector<std::string> listdir() const {
//!@todo: Implement me!
return std::vector<std::string>();
}
std::time_t changed(const std::string&) const {
//!@todo: Implement me!
return std::time(nullptr);
}
bool open() {
//!@todo: Here the bug hides.
if (!create_directories(m_path.parent_path())) {
return false;
}
m_file.open(m_path, std::ios_base::out | std::ios_base::app);
return m_file.is_open();
}
void close() {
m_file.close();
}
void rename(const std::string& oldname, const std::string& newname) {
const boost::filesystem::path& path = m_path.parent_path();
boost::filesystem::rename(path / oldname, path / newname);
}
std::string filename() const {
#if BOOST_VERSION >= 104600
return m_path.filename().string();
#else
return m_path.filename();
#endif
}
std::string path() const {
return m_path.string();
}
void write(const std::string& message) {
m_file.write(message.data(), static_cast<std::streamsize>(message.size()));
m_file.put('\n');
}
void flush() {
m_file.flush();
}
private:
template<typename Path>
bool create_directories(const Path& path) {
try {
boost::filesystem::create_directories(path);
} catch (const boost::filesystem::filesystem_error&) {
return false;
}
return true;
}
};
namespace file {
template<class Rotator = NoRotation>
struct config_t {
std::string path;
bool autoflush;
config_t(const std::string& path = "/dev/stdout", bool autoflush = true) :
path(path),
autoflush(autoflush)
{}
};
template<class Backend, class Watcher, class Timer>
struct config_t<rotator_t<Backend, Watcher, Timer>> {
std::string path;
bool autoflush;
rotation::config_t<Watcher> rotation;
config_t(const std::string& path = "/dev/stdout",
bool autoflush = true,
const rotation::config_t<Watcher>& rotation = rotation::config_t<Watcher>()) :
path(path),
autoflush(autoflush),
rotation(rotation)
{}
};
} // namespace file
template<class Backend>
class writer_t {
Backend& backend;
public:
writer_t(Backend& backend) :
backend(backend)
{}
void write(const std::string& message) {
if (!backend.opened()) {
if (!backend.open()) {
throw error_t("failed to open file '%s' for writing", backend.path());
}
}
backend.write(message);
}
};
template<class Backend>
class flusher_t {
bool autoflush;
Backend& backend;
public:
flusher_t(bool autoflush, Backend& backend) :
autoflush(autoflush),
backend(backend)
{}
void flush() {
if (autoflush) {
backend.flush();
}
}
};
template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void>
class file_t;
template<class Backend>
class file_t<Backend, NoRotation, void> {
Backend m_backend;
writer_t<Backend> m_writer;
flusher_t<Backend> m_flusher;
public:
typedef file::config_t<NoRotation> config_type;
static const char* name() {
return "files";
}
file_t(const config_type& config) :
m_backend(config.path),
m_writer(m_backend),
m_flusher(config.autoflush, m_backend)
{}
void consume(const std::string& message) {
m_writer.write(message);
m_flusher.flush();
}
Backend& backend() {
return m_backend;
}
};
template<class Backend, class Rotator>
class file_t<
Backend,
Rotator,
typename std::enable_if<
!std::is_same<Rotator, NoRotation>::value
>::type>
{
Backend m_backend;
writer_t<Backend> m_writer;
flusher_t<Backend> m_flusher;
Rotator m_rotator;
public:
typedef file::config_t<Rotator> config_type;
static const char* name() {
return "files";
}
file_t(const config_type& config) :
m_backend(config.path),
m_writer(m_backend),
m_flusher(config.autoflush, m_backend),
m_rotator(config.rotation, m_backend)
{}
void consume(const std::string& message) {
m_writer.write(message);
m_flusher.flush();
if (m_rotator.necessary()) {
m_rotator.rotate();
}
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
namespace generator {
template<class Backend, class Watcher>
struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
static std::string extract(const boost::any& config) {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::file_t<Backend, rotator_type> sink_type;
std::map<std::string, boost::any> cfg;
aux::any_to(config, cfg);
if (cfg.find("rotation") != cfg.end()) {
return utils::format("%s/%s", sink_type::name(), rotator_type::name());
}
return sink_type::name();
}
};
} // namespace generator
template<class Backend>
struct config_traits<sink::file_t<Backend, sink::NoRotation>> {
static std::string name() {
return sink::file_t<Backend, sink::NoRotation>::name();
}
};
template<class Backend, class Rotator>
struct config_traits<sink::file_t<Backend, Rotator>> {
static std::string name() {
return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name());
}
};
template<class Backend>
struct factory_traits<sink::file_t<Backend>> {
typedef sink::file_t<Backend> sink_type;
typedef typename sink_type::config_type config_type;
static config_type map_config(const boost::any& config) {
config_type cfg;
aux::extractor<sink::file_t<Backend>> ex(config);
ex["path"].to(cfg.path);
ex["autoflush"].to(cfg.autoflush);
return cfg;
}
};
template<class Backend>
struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
typedef typename sink::file_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>> sink_type;
typedef typename sink_type::config_type config_type;
static config_type map_config(const boost::any& config) {
config_type cfg;
aux::extractor<sink_type> ex(config);
ex["path"].to(cfg.path);
ex["autoflush"].to(cfg.autoflush);
ex["rotation"]["pattern"].to(cfg.rotation.pattern);
ex["rotation"]["backups"].to(cfg.rotation.backups);
ex["rotation"]["size"].to(cfg.rotation.watcher.size);
return cfg;
}
};
} // namespace blackhole
<commit_msg>Disable auto creating directories for file sink, because it doesn’t work and is untested.<commit_after>#pragma once
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/version.hpp>
#include "blackhole/error.hpp"
#include "blackhole/factory.hpp"
#include "blackhole/sink/files/rotation.hpp"
namespace blackhole {
namespace sink {
class boost_backend_t {
const boost::filesystem::path m_path;
boost::filesystem::ofstream m_file;
public:
boost_backend_t(const std::string& path) :
m_path(path)
{
}
bool opened() const {
return m_file.is_open();
}
bool exists(const std::string& filename) const {
return boost::filesystem::exists(m_path.parent_path() / filename);
}
std::vector<std::string> listdir() const {
//!@todo: Implement me!
return std::vector<std::string>();
}
std::time_t changed(const std::string&) const {
//!@todo: Implement me!
return std::time(nullptr);
}
bool open() {
m_file.open(m_path, std::ios_base::out | std::ios_base::app);
return m_file.is_open();
}
void close() {
m_file.close();
}
void rename(const std::string& oldname, const std::string& newname) {
const boost::filesystem::path& path = m_path.parent_path();
boost::filesystem::rename(path / oldname, path / newname);
}
std::string filename() const {
#if BOOST_VERSION >= 104600
return m_path.filename().string();
#else
return m_path.filename();
#endif
}
std::string path() const {
return m_path.string();
}
void write(const std::string& message) {
m_file.write(message.data(), static_cast<std::streamsize>(message.size()));
m_file.put('\n');
}
void flush() {
m_file.flush();
}
};
namespace file {
template<class Rotator = NoRotation>
struct config_t {
std::string path;
bool autoflush;
config_t(const std::string& path = "/dev/stdout", bool autoflush = true) :
path(path),
autoflush(autoflush)
{}
};
template<class Backend, class Watcher, class Timer>
struct config_t<rotator_t<Backend, Watcher, Timer>> {
std::string path;
bool autoflush;
rotation::config_t<Watcher> rotation;
config_t(const std::string& path = "/dev/stdout",
bool autoflush = true,
const rotation::config_t<Watcher>& rotation = rotation::config_t<Watcher>()) :
path(path),
autoflush(autoflush),
rotation(rotation)
{}
};
} // namespace file
template<class Backend>
class writer_t {
Backend& backend;
public:
writer_t(Backend& backend) :
backend(backend)
{}
void write(const std::string& message) {
if (!backend.opened()) {
if (!backend.open()) {
throw error_t("failed to open file '%s' for writing", backend.path());
}
}
backend.write(message);
}
};
template<class Backend>
class flusher_t {
bool autoflush;
Backend& backend;
public:
flusher_t(bool autoflush, Backend& backend) :
autoflush(autoflush),
backend(backend)
{}
void flush() {
if (autoflush) {
backend.flush();
}
}
};
template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void>
class file_t;
template<class Backend>
class file_t<Backend, NoRotation, void> {
Backend m_backend;
writer_t<Backend> m_writer;
flusher_t<Backend> m_flusher;
public:
typedef file::config_t<NoRotation> config_type;
static const char* name() {
return "files";
}
file_t(const config_type& config) :
m_backend(config.path),
m_writer(m_backend),
m_flusher(config.autoflush, m_backend)
{}
void consume(const std::string& message) {
m_writer.write(message);
m_flusher.flush();
}
Backend& backend() {
return m_backend;
}
};
template<class Backend, class Rotator>
class file_t<
Backend,
Rotator,
typename std::enable_if<
!std::is_same<Rotator, NoRotation>::value
>::type>
{
Backend m_backend;
writer_t<Backend> m_writer;
flusher_t<Backend> m_flusher;
Rotator m_rotator;
public:
typedef file::config_t<Rotator> config_type;
static const char* name() {
return "files";
}
file_t(const config_type& config) :
m_backend(config.path),
m_writer(m_backend),
m_flusher(config.autoflush, m_backend),
m_rotator(config.rotation, m_backend)
{}
void consume(const std::string& message) {
m_writer.write(message);
m_flusher.flush();
if (m_rotator.necessary()) {
m_rotator.rotate();
}
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
namespace generator {
template<class Backend, class Watcher>
struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> {
static std::string extract(const boost::any& config) {
typedef sink::rotator_t<Backend, Watcher> rotator_type;
typedef sink::file_t<Backend, rotator_type> sink_type;
std::map<std::string, boost::any> cfg;
aux::any_to(config, cfg);
if (cfg.find("rotation") != cfg.end()) {
return utils::format("%s/%s", sink_type::name(), rotator_type::name());
}
return sink_type::name();
}
};
} // namespace generator
template<class Backend>
struct config_traits<sink::file_t<Backend, sink::NoRotation>> {
static std::string name() {
return sink::file_t<Backend, sink::NoRotation>::name();
}
};
template<class Backend, class Rotator>
struct config_traits<sink::file_t<Backend, Rotator>> {
static std::string name() {
return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name());
}
};
template<class Backend>
struct factory_traits<sink::file_t<Backend>> {
typedef sink::file_t<Backend> sink_type;
typedef typename sink_type::config_type config_type;
static config_type map_config(const boost::any& config) {
config_type cfg;
aux::extractor<sink::file_t<Backend>> ex(config);
ex["path"].to(cfg.path);
ex["autoflush"].to(cfg.autoflush);
return cfg;
}
};
template<class Backend>
struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
typedef typename sink::file_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>> sink_type;
typedef typename sink_type::config_type config_type;
static config_type map_config(const boost::any& config) {
config_type cfg;
aux::extractor<sink_type> ex(config);
ex["path"].to(cfg.path);
ex["autoflush"].to(cfg.autoflush);
ex["rotation"]["pattern"].to(cfg.rotation.pattern);
ex["rotation"]["backups"].to(cfg.rotation.backups);
ex["rotation"]["size"].to(cfg.rotation.watcher.size);
return cfg;
}
};
} // namespace blackhole
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2018 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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 "libmesh/hcurl_fe_transformation.h"
#include "libmesh/fe_interface.h"
namespace libMesh
{
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_phi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_dphi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_d2phi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
fe.get_fe_map().get_d2xidxyz2();
#endif
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::map_phi(const unsigned int dim,
const Elem * const elem,
const std::vector<Point> & qp,
const FEGenericBase<OutputShape> & fe,
std::vector<std::vector<OutputShape>> & phi) const
{
switch (dim)
{
case 0:
case 1:
libmesh_error_msg("These element transformations only make sense in 2D and 3D.");
case 2:
{
const std::vector<Real> & dxidx_map = fe.get_fe_map().get_dxidx();
const std::vector<Real> & dxidy_map = fe.get_fe_map().get_dxidy();
const std::vector<Real> & detadx_map = fe.get_fe_map().get_detadx();
const std::vector<Real> & detady_map = fe.get_fe_map().get_detady();
// FIXME: Need to update for 2D elements in 3D space
/* phi = (dx/dxi)^-T * \hat{phi}
In 2D:
(dx/dxi)^{-1} = [ dxi/dx dxi/dy
deta/dx deta/dy ]
so: dxi/dx^{-T} * \hat{phi} = [ dxi/dx deta/dx [ \hat{phi}_xi
dxi/dy deta/dy ] \hat{phi}_eta ]
or in indicial notation: phi_j = xi_{i,j}*\hat{phi}_i */
for (unsigned int i=0,
n_phi = cast_int<unsigned int>(phi.size());
i != n_phi; i++)
for (std::size_t p=0; p<phi[i].size(); p++)
{
// Need to temporarily cache reference shape functions
// TODO: PB: Might be worth trying to build phi_ref separately to see
// if we can get vectorization
OutputShape phi_ref;
FEInterface::shape<OutputShape>(2, fe.get_fe_type(), elem, i, qp[p], phi_ref);
phi[i][p](0) = dxidx_map[p]*phi_ref.slice(0) + detadx_map[p]*phi_ref.slice(1);
phi[i][p](1) = dxidy_map[p]*phi_ref.slice(0) + detady_map[p]*phi_ref.slice(1);
}
break;
}
case 3:
{
const std::vector<Real> & dxidx_map = fe.get_fe_map().get_dxidx();
const std::vector<Real> & dxidy_map = fe.get_fe_map().get_dxidy();
const std::vector<Real> & dxidz_map = fe.get_fe_map().get_dxidz();
const std::vector<Real> & detadx_map = fe.get_fe_map().get_detadx();
const std::vector<Real> & detady_map = fe.get_fe_map().get_detady();
const std::vector<Real> & detadz_map = fe.get_fe_map().get_detadz();
const std::vector<Real> & dzetadx_map = fe.get_fe_map().get_dzetadx();
const std::vector<Real> & dzetady_map = fe.get_fe_map().get_dzetady();
const std::vector<Real> & dzetadz_map = fe.get_fe_map().get_dzetadz();
/* phi = (dx/dxi)^-T * \hat{phi}
In 3D:
dx/dxi^-1 = [ dxi/dx dxi/dy dxi/dz
deta/dx deta/dy deta/dz
dzeta/dx dzeta/dy dzeta/dz]
so: dxi/dx^-T * \hat{phi} = [ dxi/dx deta/dx dzeta/dx [ \hat{phi}_xi
dxi/dy deta/dy dzeta/dy \hat{phi}_eta
dxi/dz deta/dz dzeta/dz ] \hat{phi}_zeta ]
or in indicial notation: phi_j = xi_{i,j}*\hat{phi}_i */
for (unsigned int i=0,
n_phi = cast_int<unsigned int>(phi.size());
i != n_phi; i++)
for (std::size_t p=0; p<phi[i].size(); p++)
{
// Need to temporarily cache reference shape functions
// TODO: PB: Might be worth trying to build phi_ref separately to see
// if we can get vectorization
OutputShape phi_ref;
FEInterface::shape<OutputShape>(3, fe.get_fe_type(), elem, i, qp[p], phi_ref);
phi[i][p].slice(0) = dxidx_map[p]*phi_ref.slice(0) + detadx_map[p]*phi_ref.slice(1)
+ dzetadx_map[p]*phi_ref.slice(2);
phi[i][p].slice(1) = dxidy_map[p]*phi_ref.slice(0) + detady_map[p]*phi_ref.slice(1)
+ dzetady_map[p]*phi_ref.slice(2);
phi[i][p].slice(2) = dxidz_map[p]*phi_ref.slice(0) + detadz_map[p]*phi_ref.slice(1)
+ dzetadz_map[p]*phi_ref.slice(2);
}
break;
}
default:
libmesh_error_msg("Invalid dim = " << dim);
} // switch(dim)
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::map_curl(const unsigned int dim,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<OutputShape> & fe,
std::vector<std::vector<OutputShape>> & curl_phi) const
{
switch (dim)
{
case 0:
case 1:
libmesh_error_msg("These element transformations only make sense in 2D and 3D.");
case 2:
{
const std::vector<std::vector<OutputShape>> & dphi_dxi = fe.get_dphidxi();
const std::vector<std::vector<OutputShape>> & dphi_deta = fe.get_dphideta();
const std::vector<Real> & J = fe.get_fe_map().get_jacobian();
// FIXME: I don't think this is valid for 2D elements in 3D space
/* In 2D: curl(phi) = J^{-1} * curl(\hat{phi}) */
for (std::size_t i=0; i<curl_phi.size(); i++)
for (std::size_t p=0; p<curl_phi[i].size(); p++)
{
curl_phi[i][p].slice(0) = curl_phi[i][p].slice(1) = 0.0;
curl_phi[i][p].slice(2) = ( dphi_dxi[i][p].slice(1) - dphi_deta[i][p].slice(0) )/J[p];
}
break;
}
case 3:
{
const std::vector<std::vector<OutputShape>> & dphi_dxi = fe.get_dphidxi();
const std::vector<std::vector<OutputShape>> & dphi_deta = fe.get_dphideta();
const std::vector<std::vector<OutputShape>> & dphi_dzeta = fe.get_dphidzeta();
const std::vector<RealGradient> & dxyz_dxi = fe.get_fe_map().get_dxyzdxi();
const std::vector<RealGradient> & dxyz_deta = fe.get_fe_map().get_dxyzdeta();
const std::vector<RealGradient> & dxyz_dzeta = fe.get_fe_map().get_dxyzdzeta();
const std::vector<Real> & J = fe.get_fe_map().get_jacobian();
for (std::size_t i=0; i<curl_phi.size(); i++)
for (std::size_t p=0; p<curl_phi[i].size(); p++)
{
Real dx_dxi = dxyz_dxi[p](0);
Real dx_deta = dxyz_deta[p](0);
Real dx_dzeta = dxyz_dzeta[p](0);
Real dy_dxi = dxyz_dxi[p](1);
Real dy_deta = dxyz_deta[p](1);
Real dy_dzeta = dxyz_dzeta[p](1);
Real dz_dxi = dxyz_dxi[p](2);
Real dz_deta = dxyz_deta[p](2);
Real dz_dzeta = dxyz_dzeta[p](2);
const Real inv_jac = 1.0/J[p];
/* In 3D: curl(phi) = J^{-1} dx/dxi * curl(\hat{phi})
dx/dxi = [ dx/dxi dx/deta dx/dzeta
dy/dxi dy/deta dy/dzeta
dz/dxi dz/deta dz/dzeta ]
curl(u) = [ du_z/deta - du_y/dzeta
du_x/dzeta - du_z/dxi
du_y/dxi - du_x/deta ]
*/
curl_phi[i][p].slice(0) = inv_jac*( dx_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dx_deta*( dphi_dzeta[i][p].slice(0) -
dphi_dxi[i][p].slice(2) ) +
dx_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
curl_phi[i][p].slice(1) = inv_jac*( dy_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dy_deta*( dphi_dzeta[i][p].slice(0)-
dphi_dxi[i][p].slice(2) ) +
dy_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
curl_phi[i][p].slice(2) = inv_jac*( dz_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dz_deta*( dphi_dzeta[i][p].slice(0) -
dphi_dxi[i][p].slice(2) ) +
dz_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
}
break;
}
default:
libmesh_error_msg("Invalid dim = " << dim);
} // switch(dim)
}
template class HCurlFETransformation<RealGradient>;
template<>
void HCurlFETransformation<Real>::init_map_phi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::init_map_dphi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::init_map_d2phi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::map_phi(const unsigned int,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<Real> &,
std::vector<std::vector<Real>> &) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::map_curl(const unsigned int,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<Real> &,
std::vector<std::vector<Real>> &) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
} // namespace libMesh
<commit_msg>Range-based for loops in hcurl_fe_transformation.C<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2018 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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 "libmesh/hcurl_fe_transformation.h"
#include "libmesh/fe_interface.h"
#include "libmesh/int_range.h"
namespace libMesh
{
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_phi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_dphi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::init_map_d2phi(const FEGenericBase<OutputShape> & fe) const
{
fe.get_fe_map().get_dxidx();
#ifdef LIBMESH_ENABLE_SECOND_DERIVATIVES
fe.get_fe_map().get_d2xidxyz2();
#endif
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::map_phi(const unsigned int dim,
const Elem * const elem,
const std::vector<Point> & qp,
const FEGenericBase<OutputShape> & fe,
std::vector<std::vector<OutputShape>> & phi) const
{
switch (dim)
{
case 0:
case 1:
libmesh_error_msg("These element transformations only make sense in 2D and 3D.");
case 2:
{
const std::vector<Real> & dxidx_map = fe.get_fe_map().get_dxidx();
const std::vector<Real> & dxidy_map = fe.get_fe_map().get_dxidy();
const std::vector<Real> & detadx_map = fe.get_fe_map().get_detadx();
const std::vector<Real> & detady_map = fe.get_fe_map().get_detady();
// FIXME: Need to update for 2D elements in 3D space
// phi = (dx/dxi)^-T * \hat{phi}
// In 2D:
// (dx/dxi)^{-1} = [ dxi/dx dxi/dy
// deta/dx deta/dy ]
//
// so: dxi/dx^{-T} * \hat{phi} = [ dxi/dx deta/dx [ \hat{phi}_xi
// dxi/dy deta/dy ] \hat{phi}_eta ]
//
// or in indicial notation: phi_j = xi_{i,j}*\hat{phi}_i
for (auto i : index_range(phi))
for (auto p : index_range(phi[i]))
{
// Need to temporarily cache reference shape functions
// TODO: PB: Might be worth trying to build phi_ref separately to see
// if we can get vectorization
OutputShape phi_ref;
FEInterface::shape<OutputShape>(2, fe.get_fe_type(), elem, i, qp[p], phi_ref);
phi[i][p](0) = dxidx_map[p]*phi_ref.slice(0) + detadx_map[p]*phi_ref.slice(1);
phi[i][p](1) = dxidy_map[p]*phi_ref.slice(0) + detady_map[p]*phi_ref.slice(1);
}
break;
}
case 3:
{
const std::vector<Real> & dxidx_map = fe.get_fe_map().get_dxidx();
const std::vector<Real> & dxidy_map = fe.get_fe_map().get_dxidy();
const std::vector<Real> & dxidz_map = fe.get_fe_map().get_dxidz();
const std::vector<Real> & detadx_map = fe.get_fe_map().get_detadx();
const std::vector<Real> & detady_map = fe.get_fe_map().get_detady();
const std::vector<Real> & detadz_map = fe.get_fe_map().get_detadz();
const std::vector<Real> & dzetadx_map = fe.get_fe_map().get_dzetadx();
const std::vector<Real> & dzetady_map = fe.get_fe_map().get_dzetady();
const std::vector<Real> & dzetadz_map = fe.get_fe_map().get_dzetadz();
// phi = (dx/dxi)^-T * \hat{phi}
// In 3D:
// dx/dxi^-1 = [ dxi/dx dxi/dy dxi/dz
// deta/dx deta/dy deta/dz
// dzeta/dx dzeta/dy dzeta/dz]
//
// so: dxi/dx^-T * \hat{phi} = [ dxi/dx deta/dx dzeta/dx [ \hat{phi}_xi
// dxi/dy deta/dy dzeta/dy \hat{phi}_eta
// dxi/dz deta/dz dzeta/dz ] \hat{phi}_zeta ]
//
// or in indicial notation: phi_j = xi_{i,j}*\hat{phi}_i
for (auto i : index_range(phi))
for (auto p : index_range(phi[i]))
{
// Need to temporarily cache reference shape functions
// TODO: PB: Might be worth trying to build phi_ref separately to see
// if we can get vectorization
OutputShape phi_ref;
FEInterface::shape<OutputShape>(3, fe.get_fe_type(), elem, i, qp[p], phi_ref);
phi[i][p].slice(0) = dxidx_map[p]*phi_ref.slice(0) + detadx_map[p]*phi_ref.slice(1)
+ dzetadx_map[p]*phi_ref.slice(2);
phi[i][p].slice(1) = dxidy_map[p]*phi_ref.slice(0) + detady_map[p]*phi_ref.slice(1)
+ dzetady_map[p]*phi_ref.slice(2);
phi[i][p].slice(2) = dxidz_map[p]*phi_ref.slice(0) + detadz_map[p]*phi_ref.slice(1)
+ dzetadz_map[p]*phi_ref.slice(2);
}
break;
}
default:
libmesh_error_msg("Invalid dim = " << dim);
} // switch(dim)
}
template<typename OutputShape>
void HCurlFETransformation<OutputShape>::map_curl(const unsigned int dim,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<OutputShape> & fe,
std::vector<std::vector<OutputShape>> & curl_phi) const
{
switch (dim)
{
case 0:
case 1:
libmesh_error_msg("These element transformations only make sense in 2D and 3D.");
case 2:
{
const std::vector<std::vector<OutputShape>> & dphi_dxi = fe.get_dphidxi();
const std::vector<std::vector<OutputShape>> & dphi_deta = fe.get_dphideta();
const std::vector<Real> & J = fe.get_fe_map().get_jacobian();
// FIXME: I don't think this is valid for 2D elements in 3D space
// In 2D: curl(phi) = J^{-1} * curl(\hat{phi})
for (auto i : index_range(curl_phi))
for (auto p : index_range(curl_phi[i]))
{
curl_phi[i][p].slice(0) = curl_phi[i][p].slice(1) = 0.0;
curl_phi[i][p].slice(2) = ( dphi_dxi[i][p].slice(1) - dphi_deta[i][p].slice(0) )/J[p];
}
break;
}
case 3:
{
const std::vector<std::vector<OutputShape>> & dphi_dxi = fe.get_dphidxi();
const std::vector<std::vector<OutputShape>> & dphi_deta = fe.get_dphideta();
const std::vector<std::vector<OutputShape>> & dphi_dzeta = fe.get_dphidzeta();
const std::vector<RealGradient> & dxyz_dxi = fe.get_fe_map().get_dxyzdxi();
const std::vector<RealGradient> & dxyz_deta = fe.get_fe_map().get_dxyzdeta();
const std::vector<RealGradient> & dxyz_dzeta = fe.get_fe_map().get_dxyzdzeta();
const std::vector<Real> & J = fe.get_fe_map().get_jacobian();
for (auto i : index_range(curl_phi))
for (auto p : index_range(curl_phi[i]))
{
Real dx_dxi = dxyz_dxi[p](0);
Real dx_deta = dxyz_deta[p](0);
Real dx_dzeta = dxyz_dzeta[p](0);
Real dy_dxi = dxyz_dxi[p](1);
Real dy_deta = dxyz_deta[p](1);
Real dy_dzeta = dxyz_dzeta[p](1);
Real dz_dxi = dxyz_dxi[p](2);
Real dz_deta = dxyz_deta[p](2);
Real dz_dzeta = dxyz_dzeta[p](2);
const Real inv_jac = 1.0/J[p];
/* In 3D: curl(phi) = J^{-1} dx/dxi * curl(\hat{phi})
dx/dxi = [ dx/dxi dx/deta dx/dzeta
dy/dxi dy/deta dy/dzeta
dz/dxi dz/deta dz/dzeta ]
curl(u) = [ du_z/deta - du_y/dzeta
du_x/dzeta - du_z/dxi
du_y/dxi - du_x/deta ]
*/
curl_phi[i][p].slice(0) = inv_jac*( dx_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dx_deta*( dphi_dzeta[i][p].slice(0) -
dphi_dxi[i][p].slice(2) ) +
dx_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
curl_phi[i][p].slice(1) = inv_jac*( dy_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dy_deta*( dphi_dzeta[i][p].slice(0)-
dphi_dxi[i][p].slice(2) ) +
dy_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
curl_phi[i][p].slice(2) = inv_jac*( dz_dxi*( dphi_deta[i][p].slice(2) -
dphi_dzeta[i][p].slice(1) ) +
dz_deta*( dphi_dzeta[i][p].slice(0) -
dphi_dxi[i][p].slice(2) ) +
dz_dzeta*( dphi_dxi[i][p].slice(1) -
dphi_deta[i][p].slice(0) ) );
}
break;
}
default:
libmesh_error_msg("Invalid dim = " << dim);
} // switch(dim)
}
template class HCurlFETransformation<RealGradient>;
template<>
void HCurlFETransformation<Real>::init_map_phi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::init_map_dphi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::init_map_d2phi(const FEGenericBase<Real> & ) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::map_phi(const unsigned int,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<Real> &,
std::vector<std::vector<Real>> &) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
template<>
void HCurlFETransformation<Real>::map_curl(const unsigned int,
const Elem * const,
const std::vector<Point> &,
const FEGenericBase<Real> &,
std::vector<std::vector<Real>> &) const
{
libmesh_error_msg("HCurl transformations only make sense for vector-valued elements.");
}
} // namespace libMesh
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// A menu system for PixelVFO.
//
// The idea is to define a menu definition with an associated hotspot
// definition. The code draws the menu and items on the screen, and uses the
// hotspot definition to handle screen touches and operation of the menu.
////////////////////////////////////////////////////////////////////////////////
#include <Arduino.h>
#include "PixelVFO.h"
#include "menu.h"
#include "events.h"
#include "hotspot.h"
extern int ts_width;
extern int ts_height;
// constants for the menu system
#define MENU_FG ILI9341_BLACK
#define MENU_BG ILI9341_GREEN
#define MENUITEM_HEIGHT 38
#define MAXMENUITEMROWS 5
#define MENU_SCROLL_WIDTH 20
#define SCROLL_FG ILI9341_WHITE
//#define SCROLL_BG ILI9341_BLACK
#define SCROLL_BG ILI9341_RED
#define SCROLL_HEIGHT 20
#define MENUBACK_WIDTH 80
#define MENUBACK_HEIGHT 35
#define MENUBACK_FG ILI9341_BLACK
#define MENUBACK_BG ILI9341_BLACK
#define MENUBACK_BG2 ILI9341_GREEN
#define MENUBACK_X (ts_width - MENUBACK_WIDTH - 1)
#define MENUBACK_Y ((DEPTH_FREQ_DISPLAY - MENUBACK_HEIGHT)/2)
#define MENU_ITEM_BG 0x0700
//----------------------------------------
// Handler if user clicks on "Back" button.
// hs address of HotSpot item clicked on (the "Back" button)
//
// Just returns 'true' - a signal that we should return from the menu.
//----------------------------------------
bool hs_menuback_handler(HotSpot *hs, void *ignore)
{
return true;
}
//----------------------------------------
// Handler if user clicks on a MenuItem hotspot.
// hs address of HotSpot MenuItem clicked on
// mi address of MenuItem to action
//----------------------------------------
bool hs_menuitem_handler(HotSpot *hs, void *mi)
{
MenuItem *mi_ptr = (MenuItem *) mi;
DEBUG3(">>>>> hs_menuitem_handler: entered, hs=\n%s\nmi=\n%s\n",
hs_display(hs), mi_display(mi_ptr));
if (mi_ptr->menu)
menu_show(mi_ptr->menu);
else
mi_ptr->action();
DEBUG3(">>>>> hs_menuitem_handler: returning false\n");
return false;
}
//----------------------------------------
// Handler if user clicks UP on a scrollbar widget.
// hs address of HotSpot item clicked on
// mptr address of Menu
//----------------------------------------
bool menu_scroll_up(HotSpot *hs, void *mptr)
{
Menu *menu = (Menu *) mptr;
int arg = hs->arg;
menu_dump("menu_scroll_up: menu", menu);
// add 'arg' to menu 'top' value and normalize
menu->top -= arg;
if (menu->top < 0)
menu->top = 0;
return false;
}
//----------------------------------------
// Handler if user clicks DOWN on a scrollbar widget.
// hs address of HotSpot item clicked on
// mi address of MenuItem to action
//----------------------------------------
bool menu_scroll_down(HotSpot *hs, void *mptr)
{
Menu *menu = (Menu *) mptr;
int arg = hs->arg;
menu_dump("menu_scroll_down: menu", menu);
// add 'arg' to menu 'top' value and normalize
menu->top += arg;
if (menu->top > menu->num_items - MAXMENUITEMROWS)
menu->top = menu->num_items - MAXMENUITEMROWS;
return false;
}
// Define the Hotspots the menu uses
static HotSpot hs_menu[] =
{
// menuitem hotspots
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*0, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 0},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*1, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 1},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*2, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 2},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*3, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 3},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*4, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 4},
};
// Define the Hotspots the menu uses
static HotSpot hs_other[] =
{
// the 'Back' button
{MENUBACK_X, 0, ts_width-MENUBACK_X, DEPTH_FREQ_DISPLAY, hs_menuback_handler, 0},
// the 'scroll' hotspots
{0, DEPTH_FREQ_DISPLAY, 50, 50, menu_scroll_up, 1},
{0, ts_height-50, 50, 50, menu_scroll_down, 1},
};
//----------------------------------------
// Format one HotSpotMenu struct into a display string.
// mi address of the Menuitem to dump
//
// Debug function.
//----------------------------------------
const char *mi_display(struct MenuItem *mi)
{
static char buffer[128];
sprintf(buffer, "mi: %p, title=%s, menu=%p, action=%p\n", mi, mi->title, mi->menu, mi->action);
return buffer;
}
//----------------------------------------
// Dump a Menu struct to the console.
// msg message to label dump with
// menu address of the Menu struct to dump
//
// Debug function.
//----------------------------------------
void menu_dump(char const *msg, Menu *menu)
{
DEBUG3("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
DEBUG3("Menu: %s\n", msg);
DEBUG3(" title=%s, top=%d, num items=%d\n", menu->title, menu->top, menu->num_items);
for (int i = 0; i < menu->num_items; ++i)
{
struct MenuItem *mi_ptr = menu->items[i];
DEBUG3(" mi %d: %s", i, mi_display(mi_ptr));
}
DEBUG3("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}
//----------------------------------------
// Draw the Menu "Back" button.
//----------------------------------------
void menuBackButton(void)
{
tft.fillRoundRect(MENUBACK_X, MENUBACK_Y, MENUBACK_WIDTH, MENUBACK_HEIGHT, BUTTON_RADIUS, MENUBACK_BG);
tft.fillRoundRect(MENUBACK_X+1, MENUBACK_Y+1, MENUBACK_WIDTH-2, MENUBACK_HEIGHT-2, BUTTON_RADIUS, MENUBACK_BG2);
tft.setFont(FONT_BUTTON);
tft.setTextColor(MENUBACK_FG);
tft.setCursor(MENUBACK_X + 8, MENUBACK_Y + 25);
tft.print("Back");
}
//----------------------------------------
// Draw a menu on the screen.
// menu pointer to a Menu structure
//----------------------------------------
static void menu_draw(struct Menu *menu)
{
DEBUG3(">>>>>>>>>>>>>>>>>>>> menu_draw: entered\n");
// clear screen and write menu title on upper row
tft.fillScreen(SCREEN_BG);
tft.setTextWrap(false);
// start drawing things that don't change
tft.fillRect(0, 0, ts_width, DEPTH_FREQ_DISPLAY, FREQ_BG);
tft.setCursor(TITLE_OFFSET_X, TITLE_OFFSET_Y);
tft.setTextColor(MENU_FG);
tft.setFont(FONT_MENU);
tft.print(menu->title);
menuBackButton();
DEBUG3("After menuBackButton\n");
// draw menuitems (at least, those that fit on screen
tft.setFont(FONT_MENUITEM);
int mi_y = DEPTH_FREQ_DISPLAY + MENUITEM_HEIGHT;
for (int i = menu->top; i < menu->top + MAXMENUITEMROWS; ++i)
{
if (i > menu->num_items)
{
break;
}
DEBUG3("Top of loop, i=%d, top=%d\n", i, menu->top);
int16_t x1;
int16_t y1;
uint16_t w;
uint16_t h;
tft.getTextBounds((char *) menu->items[i]->title, 1, 1, &x1, &y1, &w, &h);
// write indexed item on lower row, right-justified
DEBUG3("fillRect(%d, %d, %d, %d, MENU_BG)\n",
0, mi_y - MENUITEM_HEIGHT, ts_width, MENUITEM_HEIGHT);
tft.fillRect(0, mi_y - MENUITEM_HEIGHT, ts_width, MENUITEM_HEIGHT, MENU_BG);
tft.setCursor(ts_width - w - 5, mi_y - 10);
tft.print(menu->items[i]->title);
mi_y += MENUITEM_HEIGHT;
DEBUG3("End of loop, i=%d, top=%d\n", i, menu->top);
}
DEBUG3("After draw MenuItems\n");
// highlight the active menuitems
for (int i = 0; i < menu->num_items; ++i) // skip the "Back" button
{
if (i >= MAXMENUITEMROWS) // break out if max showable is reached
break;
Serial.printf(F("Drawing highlight %d of %d\n"), i, menu->num_items);
HotSpot *hs = &hs_menu[i];
//tft.drawFastHLine(0, hs->y+MENUITEM_HEIGHT, ts_width, MENU_ITEM_BG);
tft.drawRect(hs->x, hs->y, hs->w, hs->h, MENU_ITEM_BG);
}
DEBUG3("After draw highlights\n");
// draw the scroll widget if required
if (menu->num_items > MAXMENUITEMROWS)
{
tft.fillRect(0, DEPTH_FREQ_DISPLAY,
MENU_SCROLL_WIDTH, ts_height - DEPTH_FREQ_DISPLAY, SCROLL_BG);
tft.fillTriangle(0, DEPTH_FREQ_DISPLAY+SCROLL_HEIGHT,
MENU_SCROLL_WIDTH-1, DEPTH_FREQ_DISPLAY+SCROLL_HEIGHT,
MENU_SCROLL_WIDTH/2, DEPTH_FREQ_DISPLAY,
SCROLL_FG);
tft.fillTriangle(0, ts_height-1-SCROLL_HEIGHT,
MENU_SCROLL_WIDTH-1, ts_height-1-SCROLL_HEIGHT,
MENU_SCROLL_WIDTH/2, ts_height-1,
SCROLL_FG);
DEBUG3("After draw scroll\n");
}
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_draw: exit\n");
}
//----------------------------------------
// Handle a touch on a menu hotspot.
// x X coord of screen touch
// y Y coord of screen touch
// hs base address of array of HotSpots
// hslen length of 'hs_array'
// is_menu 'true' if this a MenuItem touch
// menu address of menu structure (NULL if no menu)
//
// If spot selected then call menu action routine if 'menu' not NULL,
// else call HotSpot action routine. Return value of either routine.
//
// Returns 'true' if menu is finished.
//----------------------------------------
bool menu_handletouch(int x, int y, HotSpot *hs, int hslen, bool is_menu, struct Menu *menu)
{
DEBUG3(">>>>>>>>>>>>>>>>>>>> menu_handletouch: entered, is_menu=%s\n", is_menu ? "true" : "false");
for (int i = 0; i < hslen; ++hs, ++i)
{
if ((x >= hs->x) && (x < hs->x + hs->w) &&
(y >= hs->y) && (y < hs->y + hs->h))
{
if (is_menu)
{ // we have a menu
struct MenuItem *mi = menu->items[i];
if (mi->menu)
{
struct MenuItem *mi = menu->items[i];
event_flush();
menu_show(mi->menu);
// menu_draw(menu); // redraw current menu
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: action, returning false\n");
return false;
}
// else call mi->action()
mi->action();
event_flush();
menu_draw(menu); // redraw current menu
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: action, returning false\n");
return false;
}
else
{ // just call action HotSpot routine
event_flush();
DEBUG3("menu_handletouch: calling HotSpot handler: %p\n", hs->handler);
event_dump_queue("menu_handletouch: event queue before HotSpot handler:");
return hs->handler(hs, (void *) menu);
}
}
}
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: end of items, returning 'false'\n");
return false;
}
//----------------------------------------
// Handle a menu.
// menu pointer to a Menu structure
//----------------------------------------
void menu_show(struct Menu *menu)
{
dump_mem("menu_show");
// draw the menu page
menu_draw(menu);
// get rid of any stray events to this point
event_flush();
while (true)
{
// get next event and handle it
VFOEvent *event = event_pop();
switch (event->event)
{
case event_Down:
if (menu_handletouch(event->x, event->y, hs_menu, ALEN(hs_menu), true, menu))
{
return;
}
if (menu_handletouch(event->x, event->y, hs_other, ALEN(hs_other), false, menu))
{
return;
}
menu_draw(menu);
break;
case event_None:
break;
default:
abort("Unrecognized event!?");
}
}
}
<commit_msg>Fixed issue #5, problem was looping too many times<commit_after>////////////////////////////////////////////////////////////////////////////////
// A menu system for PixelVFO.
//
// The idea is to define a menu definition with an associated hotspot
// definition. The code draws the menu and items on the screen, and uses the
// hotspot definition to handle screen touches and operation of the menu.
////////////////////////////////////////////////////////////////////////////////
#include <Arduino.h>
#include "PixelVFO.h"
#include "menu.h"
#include "events.h"
#include "hotspot.h"
extern int ts_width;
extern int ts_height;
// constants for the menu system
#define MENU_FG ILI9341_BLACK
#define MENU_BG ILI9341_GREEN
#define MENUITEM_HEIGHT 38
#define MAXMENUITEMROWS 5
#define MENU_SCROLL_WIDTH 20
#define MENU_SCROLL_OFFSET 0
#define SCROLL_HEIGHT 20
#define SCROLL_FG ILI9341_WHITE
#define SCROLL_BG ILI9341_RED
#define MENUBACK_WIDTH 80
#define MENUBACK_HEIGHT 35
#define MENUBACK_FG ILI9341_BLACK
#define MENUBACK_BG ILI9341_BLACK
#define MENUBACK_BG2 ILI9341_GREEN
#define MENUBACK_X (ts_width - MENUBACK_WIDTH - 1)
#define MENUBACK_Y ((DEPTH_FREQ_DISPLAY - MENUBACK_HEIGHT)/2)
#define MENU_ITEM_BG 0x0700
//----------------------------------------
// Handler if user clicks on "Back" button.
// hs address of HotSpot item clicked on (the "Back" button)
//
// Just returns 'true' - a signal that we should return from the menu.
//----------------------------------------
bool hs_menuback_handler(HotSpot *hs, void *ignore)
{
return true;
}
//----------------------------------------
// Handler if user clicks on a MenuItem hotspot.
// hs address of HotSpot MenuItem clicked on
// mi address of MenuItem to action
//----------------------------------------
bool hs_menuitem_handler(HotSpot *hs, void *mi)
{
MenuItem *mi_ptr = (MenuItem *) mi;
DEBUG3(">>>>> hs_menuitem_handler: entered, hs=\n%s\nmi=\n%s\n",
hs_display(hs), mi_display(mi_ptr));
if (mi_ptr->menu)
menu_show(mi_ptr->menu);
else
mi_ptr->action();
DEBUG3(">>>>> hs_menuitem_handler: returning false\n");
return false;
}
//----------------------------------------
// Handler if user clicks UP on a scrollbar widget.
// hs address of HotSpot item clicked on
// mptr address of Menu
//----------------------------------------
bool menu_scroll_up(HotSpot *hs, void *mptr)
{
Menu *menu = (Menu *) mptr;
int arg = hs->arg;
menu_dump("menu_scroll_up: menu", menu);
// add 'arg' to menu 'top' value and normalize
menu->top -= arg;
if (menu->top < 0)
menu->top = 0;
return false;
}
//----------------------------------------
// Handler if user clicks DOWN on a scrollbar widget.
// hs address of HotSpot item clicked on
// mi address of MenuItem to action
//----------------------------------------
bool menu_scroll_down(HotSpot *hs, void *mptr)
{
Menu *menu = (Menu *) mptr;
int arg = hs->arg;
menu_dump("menu_scroll_down: menu", menu);
// add 'arg' to menu 'top' value and normalize
menu->top += arg;
if (menu->top > menu->num_items - MAXMENUITEMROWS)
menu->top = menu->num_items - MAXMENUITEMROWS;
return false;
}
// Define the Hotspots the menu uses
static HotSpot hs_menu[] =
{
// menuitem hotspots
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*0, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 0},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*1, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 1},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*2, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 2},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*3, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 3},
{100, DEPTH_FREQ_DISPLAY+MENUITEM_HEIGHT*4, ts_width, MENUITEM_HEIGHT, hs_menuitem_handler, 4},
};
// Define the Hotspots the menu uses
static HotSpot hs_other[] =
{
// the 'Back' button
{MENUBACK_X, 0, ts_width-MENUBACK_X, DEPTH_FREQ_DISPLAY, hs_menuback_handler, 0},
// the 'scroll' hotspots
{0, DEPTH_FREQ_DISPLAY, 50, 50, menu_scroll_up, 1},
{0, ts_height-50, 50, 50, menu_scroll_down, 1},
};
//----------------------------------------
// Format one HotSpotMenu struct into a display string.
// mi address of the Menuitem to dump
//
// Debug function.
//----------------------------------------
const char *mi_display(struct MenuItem *mi)
{
static char buffer[128];
sprintf(buffer, "mi: %p, title=%s, menu=%p, action=%p\n", mi, mi->title, mi->menu, mi->action);
return buffer;
}
//----------------------------------------
// Dump a Menu struct to the console.
// msg message to label dump with
// menu address of the Menu struct to dump
//
// Debug function.
//----------------------------------------
void menu_dump(char const *msg, Menu *menu)
{
DEBUG3("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
DEBUG3("Menu: %s\n", msg);
DEBUG3(" title=%s, top=%d, num items=%d\n", menu->title, menu->top, menu->num_items);
for (int i = 0; i < menu->num_items; ++i)
{
struct MenuItem *mi_ptr = menu->items[i];
DEBUG3(" mi %d: %s", i, mi_display(mi_ptr));
}
DEBUG3("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}
//----------------------------------------
// Draw the Menu "Back" button.
//----------------------------------------
void menuBackButton(void)
{
tft.fillRoundRect(MENUBACK_X, MENUBACK_Y, MENUBACK_WIDTH, MENUBACK_HEIGHT, BUTTON_RADIUS, MENUBACK_BG);
tft.fillRoundRect(MENUBACK_X+1, MENUBACK_Y+1, MENUBACK_WIDTH-2, MENUBACK_HEIGHT-2, BUTTON_RADIUS, MENUBACK_BG2);
tft.setFont(FONT_BUTTON);
tft.setTextColor(MENUBACK_FG);
tft.setCursor(MENUBACK_X + 8, MENUBACK_Y + 25);
tft.print("Back");
}
//----------------------------------------
// Draw a menu on the screen.
// menu pointer to a Menu structure
//----------------------------------------
static void menu_draw(struct Menu *menu)
{
DEBUG3(">>>>>>>>>>>>>>>>>>>> menu_draw: entered\n");
DEBUG3("menu->num_items=%d, menu->top + MAXMENUITEMROWS=%d\n",
menu->num_items, menu->top + MAXMENUITEMROWS);
// clear screen and write menu title on upper row
tft.fillScreen(SCREEN_BG);
tft.setTextWrap(false);
// start drawing things that don't change
tft.fillRect(0, 0, ts_width, DEPTH_FREQ_DISPLAY, FREQ_BG);
tft.setCursor(TITLE_OFFSET_X, TITLE_OFFSET_Y);
tft.setTextColor(MENU_FG);
tft.setFont(FONT_MENU);
tft.print(menu->title);
menuBackButton();
DEBUG3("After menuBackButton\n");
// draw menuitems (at least, those that fit on screen
tft.setFont(FONT_MENUITEM);
int mi_y = DEPTH_FREQ_DISPLAY + MENUITEM_HEIGHT;
for (int i = menu->top; i < menu->top + MAXMENUITEMROWS; ++i)
{
DEBUG3("Top of loop, i=%d, top=%d, menu->num_items=%d\n", i, menu->top, menu->num_items);
if (i >= menu->num_items)
{
break;
}
DEBUG3("Top of loop, i=%d, top=%d\n", i, menu->top);
int16_t x1;
int16_t y1;
uint16_t w;
uint16_t h;
tft.getTextBounds((char *) menu->items[i]->title, 1, 1, &x1, &y1, &w, &h);
// write indexed item on lower row, right-justified
DEBUG3("fillRect(%d, %d, %d, %d, MENU_BG)\n",
0, mi_y - MENUITEM_HEIGHT, ts_width-1, MENUITEM_HEIGHT);
tft.fillRect(0, mi_y - MENUITEM_HEIGHT, ts_width-1, MENUITEM_HEIGHT, MENU_BG);
tft.setCursor(ts_width - w - 5, mi_y - 10);
tft.print(menu->items[i]->title);
mi_y += MENUITEM_HEIGHT;
DEBUG3("End of loop, i=%d, top=%d\n", i, menu->top);
}
DEBUG3("After draw MenuItems\n");
// highlight the active menuitems
for (int i = 0; i < menu->num_items; ++i) // skip the "Back" button
{
if (i >= MAXMENUITEMROWS) // break out if max showable is reached
break;
Serial.printf(F("Drawing highlight %d of %d\n"), i, menu->num_items);
HotSpot *hs = &hs_menu[i];
//tft.drawFastHLine(0, hs->y+MENUITEM_HEIGHT, ts_width, MENU_ITEM_BG);
tft.drawRect(hs->x, hs->y, hs->w, hs->h, MENU_ITEM_BG);
}
DEBUG3("After draw highlights\n");
// draw the scroll widget if required
if (menu->num_items > MAXMENUITEMROWS)
{
tft.fillRect(MENU_SCROLL_OFFSET, DEPTH_FREQ_DISPLAY,
MENU_SCROLL_WIDTH, ts_height - DEPTH_FREQ_DISPLAY, SCROLL_BG);
tft.fillTriangle(MENU_SCROLL_OFFSET, DEPTH_FREQ_DISPLAY+SCROLL_HEIGHT,
MENU_SCROLL_OFFSET + MENU_SCROLL_WIDTH-1, DEPTH_FREQ_DISPLAY+SCROLL_HEIGHT,
MENU_SCROLL_OFFSET + MENU_SCROLL_WIDTH/2, DEPTH_FREQ_DISPLAY,
SCROLL_FG);
tft.fillTriangle(MENU_SCROLL_OFFSET, ts_height-1-SCROLL_HEIGHT,
MENU_SCROLL_OFFSET + MENU_SCROLL_WIDTH-1, ts_height-1-SCROLL_HEIGHT,
MENU_SCROLL_OFFSET + MENU_SCROLL_WIDTH/2, ts_height-1,
SCROLL_FG);
DEBUG3("After draw scroll\n");
}
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_draw: exit\n");
}
//----------------------------------------
// Handle a touch on a menu hotspot.
// x X coord of screen touch
// y Y coord of screen touch
// hs base address of array of HotSpots
// hslen length of 'hs_array'
// is_menu 'true' if this a MenuItem touch
// menu address of menu structure (NULL if no menu)
//
// If spot selected then call menu action routine if 'menu' not NULL,
// else call HotSpot action routine. Return value of either routine.
//
// Returns 'true' if menu is finished.
//----------------------------------------
bool menu_handletouch(int x, int y, HotSpot *hs, int hslen, bool is_menu, struct Menu *menu)
{
DEBUG3(">>>>>>>>>>>>>>>>>>>> menu_handletouch: entered, is_menu=%s\n", is_menu ? "true" : "false");
for (int i = 0; i < hslen; ++hs, ++i)
{
if ((x >= hs->x) && (x < hs->x + hs->w) &&
(y >= hs->y) && (y < hs->y + hs->h))
{
if (is_menu)
{ // we have a menu
struct MenuItem *mi = menu->items[i];
if (mi->menu)
{
struct MenuItem *mi = menu->items[i];
event_flush();
menu_show(mi->menu);
// menu_draw(menu); // redraw current menu
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: action, returning false\n");
return false;
}
// else call mi->action()
mi->action();
event_flush();
menu_draw(menu); // redraw current menu
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: action, returning false\n");
return false;
}
else
{ // just call action HotSpot routine
event_flush();
DEBUG3("menu_handletouch: calling HotSpot handler: %p\n", hs->handler);
event_dump_queue("menu_handletouch: event queue before HotSpot handler:");
return hs->handler(hs, (void *) menu);
}
}
}
DEBUG3("<<<<<<<<<<<<<<<<<<<< menu_handletouch: end of items, returning 'false'\n");
return false;
}
//----------------------------------------
// Handle a menu.
// menu pointer to a Menu structure
//----------------------------------------
void menu_show(struct Menu *menu)
{
dump_mem("menu_show");
// draw the menu page
menu_draw(menu);
// get rid of any stray events to this point
event_flush();
while (true)
{
// get next event and handle it
VFOEvent *event = event_pop();
switch (event->event)
{
case event_Down:
if (menu_handletouch(event->x, event->y, hs_menu, ALEN(hs_menu), true, menu))
{
return;
}
if (menu_handletouch(event->x, event->y, hs_other, ALEN(hs_other), false, menu))
{
return;
}
menu_draw(menu);
break;
case event_None:
break;
default:
abort("Unrecognized event!?");
}
}
}
<|endoftext|>
|
<commit_before>// Copyright 2010 Google
// 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.
//
// N-queens problem
//
// unique solutions: http://www.research.att.com/~njas/sequences/A000170
// distinct solutions: http://www.research.att.com/~njas/sequences/A002562
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/map-util.h"
#include "constraint_solver/constraint_solveri.h"
DEFINE_bool(use_range, false, "If true, use AllDifferenceRange.");
DEFINE_bool(print, false, "If true, print one of the solution.");
DEFINE_bool(print_all, false, "If true, print all the solutions.");
DEFINE_int32(nb_loops, 1,
"Number of solving loops to perform, for performance timing.");
DEFINE_int32(size, 0,
"Size of the problem. If equal to 0, will test several increasing sizes.");
DEFINE_bool(use_symmetry, false, "Use Symmetry Breaking methods");
static const int kNumSolutions[] = {
1, 0, 0, 2, 10, 4, 40, 92, 352, 724,
2680, 14200, 73712, 365596, 2279184
};
static const int kKnownSolutions = 15;
static const int kNumUniqueSolutions[] = {
1, 0, 0, 1, 2, 1, 6, 12, 46, 92, 341, 1787, 9233, 45752,
285053, 1846955, 11977939, 83263591, 621012754
};
static const int kKnownUniqueSolutions = 19;
namespace operations_research {
class MyFirstSolutionCollector : public SolutionCollector {
public:
MyFirstSolutionCollector(Solver* const s, const Assignment* a);
virtual ~MyFirstSolutionCollector();
virtual void EnterSearch();
virtual bool RejectSolution();
virtual string DebugString() const;
private:
bool done_;
};
MyFirstSolutionCollector::MyFirstSolutionCollector(Solver* const s,
const Assignment* a)
: SolutionCollector(s, a), done_(false) {}
MyFirstSolutionCollector::~MyFirstSolutionCollector() {}
void MyFirstSolutionCollector::EnterSearch() {
SolutionCollector::EnterSearch();
done_ = false;
}
bool MyFirstSolutionCollector::RejectSolution() {
if (!done_) {
PushSolution();
done_ = true;
return false;
}
return true;
}
string MyFirstSolutionCollector::DebugString() const {
if (prototype_.get() == NULL) {
return "MyFirstSolutionCollector()";
} else {
return "MyFirstSolutionCollector(" + prototype_->DebugString() + ")";
}
}
class NQueenSymmetry : public SymmetryBreaker {
public:
NQueenSymmetry(Solver* const s, const vector<IntVar*>& vars)
: solver_(s), vars_(vars), size_(vars.size()) {
for (int i = 0; i < size_; ++i) {
indices_[vars[i]] = i;
}
}
virtual ~NQueenSymmetry() {}
int Index(IntVar* const var) const {
return FindWithDefault(indices_, var, -1);
}
IntVar* Var(int index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, size_);
return vars_[index];
}
int size() const { return size_; }
Solver* const solver() const { return solver_; }
private:
Solver* const solver_;
const vector<IntVar*> vars_;
map<IntVar*, int> indices_;
const int size_;
};
// Symmetry vertical axis.
class SX : public NQueenSymmetry {
public:
SX(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SX() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - index);
AddToClause(solver()->MakeIsEqualCstVar(other_var, value));
}
};
// Symmetry horizontal axis.
class SY : public NQueenSymmetry {
public:
SY(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SY() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
AddToClause(solver()->MakeIsEqualCstVar(var, size() - 1 - value));
}
};
// Symmetry 1 diagonal axis.
class SD1 : public NQueenSymmetry {
public:
SD1(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SD1() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, index));
}
};
// Symmetry second diagonal axis.
class SD2 : public NQueenSymmetry {
public:
SD2(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SD2() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - index));
}
};
// Rotate 1/4 turn.
class R90 : public NQueenSymmetry {
public:
R90(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~R90() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - index));
}
};
// Rotate 1/2 turn.
class R180 : public NQueenSymmetry {
public:
R180(Solver* const s, const vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
virtual ~R180() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - index);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - value));
}
};
// Rotate 3/4 turn.
class R270 : public NQueenSymmetry {
public:
R270(Solver* const s, const vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
virtual ~R270() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, index));
}
};
void NQueens(int size) {
CHECK_GE(size, 1);
scoped_ptr<Solver> s(new Solver("nqueens"));
// model
vector<IntVar*> queens;
for (int i = 0; i < size; ++i) {
queens.push_back(
s->MakeIntVar(0, size - 1, StringPrintf("queen%04d", i)));
}
s->AddConstraint(s->MakeAllDifferent(queens, FLAGS_use_range));
vector<IntVar*> vars;
vars.resize(size);
for (int i = 0; i < size; ++i) {
vars[i] = s->MakeSum(queens[i], i)->Var();
}
s->AddConstraint(s->MakeAllDifferent(vars, FLAGS_use_range));
for (int i = 0; i < size; ++i) {
vars[i] = s->MakeSum(queens[i], -i)->Var();
}
s->AddConstraint(s->MakeAllDifferent(vars, FLAGS_use_range));
SolutionCollector * const c1 = s->MakeAllSolutionCollector(NULL);
Assignment * a = new Assignment(s.get()); // store first solution
a->Add(queens);
SolutionCollector * const c2 =
s->RevAlloc(new MyFirstSolutionCollector(s.get(), a));
delete a;
vector<SearchMonitor*> monitors;
monitors.push_back(c1);
monitors.push_back(c2);
DecisionBuilder* const db = s->MakePhase(queens,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
if (FLAGS_use_symmetry) {
vector<SymmetryBreaker*> breakers;
NQueenSymmetry* sx = s->RevAlloc(new SX(s.get(), queens));
breakers.push_back(sx);
NQueenSymmetry* sy = s->RevAlloc(new SY(s.get(), queens));
breakers.push_back(sy);
NQueenSymmetry* sd1 = s->RevAlloc(new SD1(s.get(), queens));
breakers.push_back(sd1);
NQueenSymmetry* sd2 = s->RevAlloc(new SD2(s.get(), queens));
breakers.push_back(sd2);
NQueenSymmetry* r90 = s->RevAlloc(new R90(s.get(), queens));
breakers.push_back(r90);
NQueenSymmetry* r180 = s->RevAlloc(new R180(s.get(), queens));
breakers.push_back(r180);
NQueenSymmetry* r270 = s->RevAlloc(new R270(s.get(), queens));
breakers.push_back(r270);
SearchMonitor* symmetry_manager = s->MakeSymmetryManager(breakers);
monitors.push_back(symmetry_manager);
}
for (int loop = 0; loop < FLAGS_nb_loops; ++loop) {
s->Solve(db, monitors); // go!
}
const int num_solutions = c1->solution_count();
if (num_solutions > 0 && size < kKnownSolutions) {
int print_max = FLAGS_print_all ? num_solutions : FLAGS_print ? 1 : 0;
for (int n = 0; n < print_max; ++n) {
printf("--- solution #%d\n", n);
const Assignment * const b = c2->solution(n);
for (int i = 0; i < size; ++i) {
const int pos = static_cast<int>(b->Value(queens[i]));
for (int k = 0; k < pos; ++k) printf(" . ");
printf("%2d ", i);
for (int k = pos + 1; k < size; ++k) printf(" . ");
printf("\n");
}
}
}
printf("========= number of solutions:%d\n", num_solutions);
printf(" number of failures: %lld\n", s->failures());
if (FLAGS_use_symmetry) {
if (size - 1 < kKnownUniqueSolutions) {
CHECK_EQ(num_solutions, kNumUniqueSolutions[size - 1] * FLAGS_nb_loops);
} else {
CHECK_GT(num_solutions, 0);
}
} else {
if (size - 1 < kKnownSolutions) {
CHECK_EQ(num_solutions, kNumSolutions[size - 1] * FLAGS_nb_loops);
} else {
CHECK_GT(num_solutions, 0);
}
}
}
} // namespace operations_research
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_size != 0) {
operations_research::NQueens(FLAGS_size);
} else {
for (int n = 1; n < 12; ++n) {
operations_research::NQueens(n);
}
}
return 0;
}
<commit_msg>clean up nqueen example<commit_after>// Copyright 2010 Google
// 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.
//
// N-queens problem
//
// unique solutions: http://www.research.att.com/~njas/sequences/A000170
// distinct solutions: http://www.research.att.com/~njas/sequences/A002562
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/stringprintf.h"
#include "base/map-util.h"
#include "constraint_solver/constraint_solveri.h"
DEFINE_bool(use_range, false, "If true, use AllDifferenceRange.");
DEFINE_bool(print, false, "If true, print one of the solution.");
DEFINE_bool(print_all, false, "If true, print all the solutions.");
DEFINE_int32(nb_loops, 1,
"Number of solving loops to perform, for performance timing.");
DEFINE_int32(size, 0,
"Size of the problem. If equal to 0, will test several increasing sizes.");
DEFINE_bool(use_symmetry, false, "Use Symmetry Breaking methods");
static const int kNumSolutions[] = {
1, 0, 0, 2, 10, 4, 40, 92, 352, 724,
2680, 14200, 73712, 365596, 2279184
};
static const int kKnownSolutions = 15;
static const int kNumUniqueSolutions[] = {
1, 0, 0, 1, 2, 1, 6, 12, 46, 92, 341, 1787, 9233, 45752,
285053, 1846955, 11977939, 83263591, 621012754
};
static const int kKnownUniqueSolutions = 19;
namespace operations_research {
class MyFirstSolutionCollector : public SolutionCollector {
public:
MyFirstSolutionCollector(Solver* const s, const Assignment* a);
virtual ~MyFirstSolutionCollector();
virtual void EnterSearch();
virtual bool RejectSolution();
virtual string DebugString() const;
private:
bool done_;
};
MyFirstSolutionCollector::MyFirstSolutionCollector(Solver* const s,
const Assignment* a)
: SolutionCollector(s, a), done_(false) {}
MyFirstSolutionCollector::~MyFirstSolutionCollector() {}
void MyFirstSolutionCollector::EnterSearch() {
SolutionCollector::EnterSearch();
done_ = false;
}
bool MyFirstSolutionCollector::RejectSolution() {
if (!done_) {
PushSolution();
done_ = true;
return false;
}
return true;
}
string MyFirstSolutionCollector::DebugString() const {
if (prototype_.get() == NULL) {
return "MyFirstSolutionCollector()";
} else {
return "MyFirstSolutionCollector(" + prototype_->DebugString() + ")";
}
}
class NQueenSymmetry : public SymmetryBreaker {
public:
NQueenSymmetry(Solver* const s, const vector<IntVar*>& vars)
: solver_(s), vars_(vars), size_(vars.size()) {
for (int i = 0; i < size_; ++i) {
indices_[vars[i]] = i;
}
}
virtual ~NQueenSymmetry() {}
int Index(IntVar* const var) const {
return FindWithDefault(indices_, var, -1);
}
IntVar* Var(int index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, size_);
return vars_[index];
}
int size() const { return size_; }
Solver* const solver() const { return solver_; }
private:
Solver* const solver_;
const vector<IntVar*> vars_;
map<IntVar*, int> indices_;
const int size_;
};
// Symmetry vertical axis.
class SX : public NQueenSymmetry {
public:
SX(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SX() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - index);
AddToClause(solver()->MakeIsEqualCstVar(other_var, value));
}
};
// Symmetry horizontal axis.
class SY : public NQueenSymmetry {
public:
SY(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SY() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
AddToClause(solver()->MakeIsEqualCstVar(var, size() - 1 - value));
}
};
// Symmetry first diagonal axis.
class SD1 : public NQueenSymmetry {
public:
SD1(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SD1() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, index));
}
};
// Symmetry second diagonal axis.
class SD2 : public NQueenSymmetry {
public:
SD2(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~SD2() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - index));
}
};
// Rotate 1/4 turn.
class R90 : public NQueenSymmetry {
public:
R90(Solver* const s, const vector<IntVar*>& vars) : NQueenSymmetry(s, vars) {}
virtual ~R90() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - index));
}
};
// Rotate 1/2 turn.
class R180 : public NQueenSymmetry {
public:
R180(Solver* const s, const vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
virtual ~R180() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - index);
AddToClause(solver()->MakeIsEqualCstVar(other_var, size() - 1 - value));
}
};
// Rotate 3/4 turn.
class R270 : public NQueenSymmetry {
public:
R270(Solver* const s, const vector<IntVar*>& vars)
: NQueenSymmetry(s, vars) {}
virtual ~R270() {}
virtual void VisitSetVariableValue(IntVar* const var, int64 value) {
const int index = Index(var);
IntVar* const other_var = Var(size() - 1 - value);
AddToClause(solver()->MakeIsEqualCstVar(other_var, index));
}
};
void NQueens(int size) {
CHECK_GE(size, 1);
Solver s("nqueens");
// model
vector<IntVar*> queens;
for (int i = 0; i < size; ++i) {
queens.push_back(s.MakeIntVar(0, size - 1, StringPrintf("queen%04d", i)));
}
s.AddConstraint(s.MakeAllDifferent(queens, FLAGS_use_range));
vector<IntVar*> vars(size);
for (int i = 0; i < size; ++i) {
vars[i] = s.MakeSum(queens[i], i)->Var();
}
s.AddConstraint(s.MakeAllDifferent(vars, FLAGS_use_range));
for (int i = 0; i < size; ++i) {
vars[i] = s.MakeSum(queens[i], -i)->Var();
}
s.AddConstraint(s.MakeAllDifferent(vars, FLAGS_use_range));
SolutionCollector* const c1 = s.MakeAllSolutionCollector(NULL);
Assignment* const a = new Assignment(&s); // store first solution
a->Add(queens);
SolutionCollector* const c2 = s.RevAlloc(new MyFirstSolutionCollector(&s, a));
delete a;
vector<SearchMonitor*> monitors;
monitors.push_back(c1);
monitors.push_back(c2);
DecisionBuilder* const db = s.MakePhase(queens,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
if (FLAGS_use_symmetry) {
vector<SymmetryBreaker*> breakers;
NQueenSymmetry* sx = s.RevAlloc(new SX(&s, queens));
breakers.push_back(sx);
NQueenSymmetry* sy = s.RevAlloc(new SY(&s, queens));
breakers.push_back(sy);
NQueenSymmetry* sd1 = s.RevAlloc(new SD1(&s, queens));
breakers.push_back(sd1);
NQueenSymmetry* sd2 = s.RevAlloc(new SD2(&s, queens));
breakers.push_back(sd2);
NQueenSymmetry* r90 = s.RevAlloc(new R90(&s, queens));
breakers.push_back(r90);
NQueenSymmetry* r180 = s.RevAlloc(new R180(&s, queens));
breakers.push_back(r180);
NQueenSymmetry* r270 = s.RevAlloc(new R270(&s, queens));
breakers.push_back(r270);
SearchMonitor* symmetry_manager = s.MakeSymmetryManager(breakers);
monitors.push_back(symmetry_manager);
}
for (int loop = 0; loop < FLAGS_nb_loops; ++loop) {
s.Solve(db, monitors); // go!
}
const int num_solutions = c1->solution_count();
if (num_solutions > 0 && size < kKnownSolutions) {
int print_max = FLAGS_print_all ? num_solutions : FLAGS_print ? 1 : 0;
for (int n = 0; n < print_max; ++n) {
printf("--- solution #%d\n", n);
const Assignment * const b = c2->solution(n);
for (int i = 0; i < size; ++i) {
const int pos = static_cast<int>(b->Value(queens[i]));
for (int k = 0; k < pos; ++k) printf(" . ");
printf("%2d ", i);
for (int k = pos + 1; k < size; ++k) printf(" . ");
printf("\n");
}
}
}
printf("========= number of solutions:%d\n", num_solutions);
printf(" number of failures: %lld\n", s.failures());
if (FLAGS_use_symmetry) {
if (size - 1 < kKnownUniqueSolutions) {
CHECK_EQ(num_solutions, kNumUniqueSolutions[size - 1] * FLAGS_nb_loops);
} else {
CHECK_GT(num_solutions, 0);
}
} else {
if (size - 1 < kKnownSolutions) {
CHECK_EQ(num_solutions, kNumSolutions[size - 1] * FLAGS_nb_loops);
} else {
CHECK_GT(num_solutions, 0);
}
}
}
} // namespace operations_research
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_size != 0) {
operations_research::NQueens(FLAGS_size);
} else {
for (int n = 1; n < 12; ++n) {
operations_research::NQueens(n);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "SparsityBasedGluedContactConstraint.h"
#include "SystemBase.h"
#include "PenetrationLocator.h"
// libMesh includes
#include "libmesh/string_to_enum.h"
template<>
InputParameters validParams<SparsityBasedGluedContactConstraint>()
{
MooseEnum orders("CONSTANT, FIRST, SECOND, THIRD, FOURTH", "FIRST");
InputParameters params = validParams<NodeFaceConstraint>();
params.addRequiredParam<BoundaryName>("boundary", "The master boundary");
params.addRequiredParam<BoundaryName>("slave", "The slave boundary");
params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
params.addCoupledVar("disp_x", "The x displacement");
params.addCoupledVar("disp_y", "The y displacement");
params.addCoupledVar("disp_z", "The z displacement");
params.addRequiredCoupledVar("nodal_area", "The nodal area");
params.set<bool>("use_displaced_mesh") = true;
params.addParam<Real>("penalty", 1e8, "The penalty to apply. This can vary depending on the stiffness of your materials");
params.addParam<Real>("tangential_tolerance", "Tangential distance to extend edges of contact surfaces");
params.addParam<Real>("normal_smoothing_distance", "Distance from edge in parametric coordinates over which to smooth contact normal");
params.addParam<std::string>("normal_smoothing_method","Method to use to smooth normals (edge_based|nodal_normal_based)");
params.addParam<MooseEnum>("order", orders, "The finite element order");
return params;
}
SparsityBasedGluedContactConstraint::SparsityBasedGluedContactConstraint(const std::string & name, InputParameters parameters) :
NodeFaceConstraint(name, parameters),
_component(getParam<unsigned int>("component")),
_updateContactSet(true),
_time_last_called(-std::numeric_limits<Real>::max()),
_penalty(getParam<Real>("penalty")),
_residual_copy(_sys.residualGhosted()),
_x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999),
_y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999),
_z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999),
_vars(_x_var, _y_var, _z_var),
_nodal_area_var(getVar("nodal_area", 0)),
_aux_system( _nodal_area_var->sys() ),
_aux_solution( _aux_system.currentSolution() )
{
// _overwrite_slave_residual = false;
if (parameters.isParamValid("tangential_tolerance"))
{
_penetration_locator.setTangentialTolerance(getParam<Real>("tangential_tolerance"));
}
if (parameters.isParamValid("normal_smoothing_distance"))
{
_penetration_locator.setNormalSmoothingDistance(getParam<Real>("normal_smoothing_distance"));
}
if (parameters.isParamValid("normal_smoothing_method"))
{
_penetration_locator.setNormalSmoothingMethod(parameters.get<std::string>("normal_smoothing_method"));
}
_penetration_locator.setUpdate(false);
}
void
SparsityBasedGluedContactConstraint::timestepSetup()
{
if (_component == 0)
{
_penetration_locator._unlocked_this_step.clear();
_penetration_locator._locked_this_step.clear();
bool beginning_of_step = false;
if (_t > _time_last_called)
{
beginning_of_step = true;
_penetration_locator.saveContactStateVars();
}
updateContactSet(beginning_of_step);
_updateContactSet = false;
_time_last_called = _t;
}
}
void
SparsityBasedGluedContactConstraint::jacobianSetup()
{
if (_component == 0)
{
if (_updateContactSet)
{
updateContactSet();
}
_updateContactSet = true;
}
}
void
SparsityBasedGluedContactConstraint::updateContactSet(bool beginning_of_step)
{
std::set<unsigned int> & has_penetrated = _penetration_locator._has_penetrated;
std::map<unsigned int, unsigned> & unlocked_this_step = _penetration_locator._unlocked_this_step;
std::map<unsigned int, unsigned> & locked_this_step = _penetration_locator._locked_this_step;
std::map<unsigned int, Real> & lagrange_multiplier = _penetration_locator._lagrange_multiplier;
std::map<unsigned int, PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
std::map<unsigned int, PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();
for (; it!=end; ++it)
{
PenetrationInfo * pinfo = it->second;
if (!pinfo)
{
continue;
}
const unsigned int slave_node_num = it->first;
std::set<unsigned int>::iterator hpit = has_penetrated.find(slave_node_num);
if (beginning_of_step)
{
if (hpit != has_penetrated.end())
pinfo->_penetrated_at_beginning_of_step = true;
else
pinfo->_penetrated_at_beginning_of_step = false;
pinfo->_starting_elem = it->second->_elem;
pinfo->_starting_side_num = it->second->_side_num;
pinfo->_starting_closest_point_ref = it->second->_closest_point_ref;
}
if (pinfo->_distance >= 0)
if (hpit == has_penetrated.end())
has_penetrated.insert(slave_node_num);
}
}
bool
SparsityBasedGluedContactConstraint::shouldApply()
{
std::set<unsigned int>::iterator hpit = _penetration_locator._has_penetrated.find(_current_node->id());
return (hpit != _penetration_locator._has_penetrated.end());
}
Real
SparsityBasedGluedContactConstraint::computeQpSlaveValue()
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
return _u_slave[_qp];
}
Real
SparsityBasedGluedContactConstraint::computeQpResidual(Moose::ConstraintType type)
{
switch(type)
{
case Moose::Slave:
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
Real distance = (*_current_node)(_component) - pinfo->_closest_point(_component);
Real pen_force = _penalty * distance;
Real resid = pen_force;
pinfo->_contact_force(_component) = resid;
pinfo->_mech_status=PenetrationInfo::MS_STICKING;
return _test_slave[_i][_qp] * resid;
}
case Moose::Master:
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
long int dof_number = _current_node->dof_number(0, _vars(_component), 0);
Real resid = _residual_copy(dof_number);
pinfo->_contact_force(_component) = -resid;
pinfo->_mech_status=PenetrationInfo::MS_STICKING;
return _test_master[_i][_qp] * resid;
}
}
return 0;
}
Real
SparsityBasedGluedContactConstraint::computeQpJacobian(Moose::ConstraintJacobianType type)
{
switch(type)
{
case Moose::SlaveSlave:
{
return _penalty*_phi_slave[_j][_qp]*_test_slave[_i][_qp];
}
case Moose::SlaveMaster:
{
return _penalty*-_phi_master[_j][_qp]*_test_slave[_i][_qp];
}
case Moose::MasterSlave:
{
double slave_jac = (*_jacobian)(_current_node->dof_number(0, _vars(_component), 0), _connected_dof_indices[_j]);
return slave_jac*_test_master[_i][_qp];
}
case Moose::MasterMaster:
return 0;
}
return 0;
}
void
SparsityBasedGluedContactConstraint::computeJacobian()
{
_connected_dof_indices.clear();
#if defined(LIBMESH_HAVE_PETSC) && !PETSC_VERSION_LESS_THAN(3,3,0)
// An ugly hack: have to extract the row and look at it's sparsity structure, since otherwise I won't get the dofs connected to this row by virtue of intervariable coupling
// This is easier than sifting through all coupled variables, selecting those active on the current subdomain, dealing with the scalar variables, etc.
// Also, importantly, this will miss coupling to variables that might have introduced by prior constraints similar to this one!
PetscMatrix<Number>* petsc_jacobian = dynamic_cast<PetscMatrix<Number> *>(_jacobian);
mooseAssert(petsc_jacobian, "Expected a PETSc matrix");
Mat jac = petsc_jacobian->mat();
PetscErrorCode ierr;
PetscInt ncols;
const PetscInt *cols;
ierr = MatGetRow(jac,_var.nodalDofIndex(),&ncols,&cols,PETSC_NULL);CHKERRABORT(libMesh::COMM_WORLD, ierr);
bool debug = false;
if(debug) {
libMesh::out << "_connected_dof_indices: adding " << ncols << " dofs from Jacobian row[" << _var.nodalDofIndex() << "] = [";
}
for (PetscInt i = 0; i < ncols; ++i) {
if(debug) {
libMesh::out << cols[i] << " ";
}
_connected_dof_indices.push_back(cols[i]);
}
if (debug) {
libMesh::out << "]\n";
}
ierr = MatRestoreRow(jac,_var.nodalDofIndex(),&ncols,&cols,PETSC_NULL);CHKERRABORT(libMesh::COMM_WORLD, ierr);
#else
std::vector<unsigned int> & elems = _node_to_elem_map[_current_node->id()];
std::set<unsigned int> unique_dof_indices;
// Get the dof indices from each elem connected to the node
for(unsigned int el=0; el < elems.size(); ++el)
{
unsigned int cur_elem = elems[el];
std::vector<unsigned int> dof_indices;
_var.getDofIndices(_mesh.elem(cur_elem), dof_indices);
for(unsigned int di=0; di < dof_indices.size(); di++)
unique_dof_indices.insert(dof_indices[di]);
}
for(std::set<unsigned int>::iterator sit=unique_dof_indices.begin(); sit != unique_dof_indices.end(); ++sit)
_connected_dof_indices.push_back(*sit);
#endif
// DenseMatrix<Number> & Kee = _assembly.jacobianBlock(_var.number(), _var.number());
DenseMatrix<Number> & Ken = _assembly.jacobianBlockNeighbor(Moose::ElementNeighbor, _var.number(), _var.number());
// DenseMatrix<Number> & Kne = _assembly.jacobianBlockNeighbor(Moose::NeighborElement, _var.number(), _var.number());
DenseMatrix<Number> & Knn = _assembly.jacobianBlockNeighbor(Moose::NeighborNeighbor, _var.number(), _var.number());
_Kee.resize(_test_slave.size(), _connected_dof_indices.size());
_Kne.resize(_test_master.size(), _connected_dof_indices.size());
_phi_slave.resize(_connected_dof_indices.size());
_qp = 0;
// Fill up _phi_slave so that it is 1 when j corresponds to this dof and 0 for every other dof
// This corresponds to evaluating all of the connected shape functions at _this_ node
for(unsigned int j=0; j<_connected_dof_indices.size(); j++)
{
_phi_slave[j].resize(1);
if(_connected_dof_indices[j] == _var.nodalDofIndex())
_phi_slave[j][_qp] = 1.0;
else
_phi_slave[j][_qp] = 0.0;
}
for (_i = 0; _i < _test_slave.size(); _i++)
// Loop over the connected dof indices so we can get all the jacobian contributions
for (_j=0; _j<_connected_dof_indices.size(); _j++)
_Kee(_i,_j) += computeQpJacobian(Moose::SlaveSlave);
for (_i=0; _i<_test_slave.size(); _i++)
for (_j=0; _j<_phi_master.size(); _j++)
Ken(_i,_j) += computeQpJacobian(Moose::SlaveMaster);
for (_i=0; _i<_test_master.size(); _i++)
// Loop over the connected dof indices so we can get all the jacobian contributions
for (_j=0; _j<_connected_dof_indices.size(); _j++)
_Kne(_i,_j) += computeQpJacobian(Moose::MasterSlave);
for (_i=0; _i<_test_master.size(); _i++)
for (_j=0; _j<_phi_master.size(); _j++)
Knn(_i,_j) += computeQpJacobian(Moose::MasterMaster);
}
<commit_msg>Cannot use libMesh::COMM_WORLD, unless configuring libMesh appropriately (MOOSE doesn't).<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "SparsityBasedGluedContactConstraint.h"
#include "SystemBase.h"
#include "PenetrationLocator.h"
// libMesh includes
#include "libmesh/string_to_enum.h"
template<>
InputParameters validParams<SparsityBasedGluedContactConstraint>()
{
MooseEnum orders("CONSTANT, FIRST, SECOND, THIRD, FOURTH", "FIRST");
InputParameters params = validParams<NodeFaceConstraint>();
params.addRequiredParam<BoundaryName>("boundary", "The master boundary");
params.addRequiredParam<BoundaryName>("slave", "The slave boundary");
params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
params.addCoupledVar("disp_x", "The x displacement");
params.addCoupledVar("disp_y", "The y displacement");
params.addCoupledVar("disp_z", "The z displacement");
params.addRequiredCoupledVar("nodal_area", "The nodal area");
params.set<bool>("use_displaced_mesh") = true;
params.addParam<Real>("penalty", 1e8, "The penalty to apply. This can vary depending on the stiffness of your materials");
params.addParam<Real>("tangential_tolerance", "Tangential distance to extend edges of contact surfaces");
params.addParam<Real>("normal_smoothing_distance", "Distance from edge in parametric coordinates over which to smooth contact normal");
params.addParam<std::string>("normal_smoothing_method","Method to use to smooth normals (edge_based|nodal_normal_based)");
params.addParam<MooseEnum>("order", orders, "The finite element order");
return params;
}
SparsityBasedGluedContactConstraint::SparsityBasedGluedContactConstraint(const std::string & name, InputParameters parameters) :
NodeFaceConstraint(name, parameters),
_component(getParam<unsigned int>("component")),
_updateContactSet(true),
_time_last_called(-std::numeric_limits<Real>::max()),
_penalty(getParam<Real>("penalty")),
_residual_copy(_sys.residualGhosted()),
_x_var(isCoupled("disp_x") ? coupled("disp_x") : 99999),
_y_var(isCoupled("disp_y") ? coupled("disp_y") : 99999),
_z_var(isCoupled("disp_z") ? coupled("disp_z") : 99999),
_vars(_x_var, _y_var, _z_var),
_nodal_area_var(getVar("nodal_area", 0)),
_aux_system( _nodal_area_var->sys() ),
_aux_solution( _aux_system.currentSolution() )
{
// _overwrite_slave_residual = false;
if (parameters.isParamValid("tangential_tolerance"))
{
_penetration_locator.setTangentialTolerance(getParam<Real>("tangential_tolerance"));
}
if (parameters.isParamValid("normal_smoothing_distance"))
{
_penetration_locator.setNormalSmoothingDistance(getParam<Real>("normal_smoothing_distance"));
}
if (parameters.isParamValid("normal_smoothing_method"))
{
_penetration_locator.setNormalSmoothingMethod(parameters.get<std::string>("normal_smoothing_method"));
}
_penetration_locator.setUpdate(false);
}
void
SparsityBasedGluedContactConstraint::timestepSetup()
{
if (_component == 0)
{
_penetration_locator._unlocked_this_step.clear();
_penetration_locator._locked_this_step.clear();
bool beginning_of_step = false;
if (_t > _time_last_called)
{
beginning_of_step = true;
_penetration_locator.saveContactStateVars();
}
updateContactSet(beginning_of_step);
_updateContactSet = false;
_time_last_called = _t;
}
}
void
SparsityBasedGluedContactConstraint::jacobianSetup()
{
if (_component == 0)
{
if (_updateContactSet)
{
updateContactSet();
}
_updateContactSet = true;
}
}
void
SparsityBasedGluedContactConstraint::updateContactSet(bool beginning_of_step)
{
std::set<unsigned int> & has_penetrated = _penetration_locator._has_penetrated;
std::map<unsigned int, unsigned> & unlocked_this_step = _penetration_locator._unlocked_this_step;
std::map<unsigned int, unsigned> & locked_this_step = _penetration_locator._locked_this_step;
std::map<unsigned int, Real> & lagrange_multiplier = _penetration_locator._lagrange_multiplier;
std::map<unsigned int, PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
std::map<unsigned int, PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();
for (; it!=end; ++it)
{
PenetrationInfo * pinfo = it->second;
if (!pinfo)
{
continue;
}
const unsigned int slave_node_num = it->first;
std::set<unsigned int>::iterator hpit = has_penetrated.find(slave_node_num);
if (beginning_of_step)
{
if (hpit != has_penetrated.end())
pinfo->_penetrated_at_beginning_of_step = true;
else
pinfo->_penetrated_at_beginning_of_step = false;
pinfo->_starting_elem = it->second->_elem;
pinfo->_starting_side_num = it->second->_side_num;
pinfo->_starting_closest_point_ref = it->second->_closest_point_ref;
}
if (pinfo->_distance >= 0)
if (hpit == has_penetrated.end())
has_penetrated.insert(slave_node_num);
}
}
bool
SparsityBasedGluedContactConstraint::shouldApply()
{
std::set<unsigned int>::iterator hpit = _penetration_locator._has_penetrated.find(_current_node->id());
return (hpit != _penetration_locator._has_penetrated.end());
}
Real
SparsityBasedGluedContactConstraint::computeQpSlaveValue()
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
return _u_slave[_qp];
}
Real
SparsityBasedGluedContactConstraint::computeQpResidual(Moose::ConstraintType type)
{
switch(type)
{
case Moose::Slave:
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
Real distance = (*_current_node)(_component) - pinfo->_closest_point(_component);
Real pen_force = _penalty * distance;
Real resid = pen_force;
pinfo->_contact_force(_component) = resid;
pinfo->_mech_status=PenetrationInfo::MS_STICKING;
return _test_slave[_i][_qp] * resid;
}
case Moose::Master:
{
PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
long int dof_number = _current_node->dof_number(0, _vars(_component), 0);
Real resid = _residual_copy(dof_number);
pinfo->_contact_force(_component) = -resid;
pinfo->_mech_status=PenetrationInfo::MS_STICKING;
return _test_master[_i][_qp] * resid;
}
}
return 0;
}
Real
SparsityBasedGluedContactConstraint::computeQpJacobian(Moose::ConstraintJacobianType type)
{
switch(type)
{
case Moose::SlaveSlave:
{
return _penalty*_phi_slave[_j][_qp]*_test_slave[_i][_qp];
}
case Moose::SlaveMaster:
{
return _penalty*-_phi_master[_j][_qp]*_test_slave[_i][_qp];
}
case Moose::MasterSlave:
{
double slave_jac = (*_jacobian)(_current_node->dof_number(0, _vars(_component), 0), _connected_dof_indices[_j]);
return slave_jac*_test_master[_i][_qp];
}
case Moose::MasterMaster:
return 0;
}
return 0;
}
void
SparsityBasedGluedContactConstraint::computeJacobian()
{
_connected_dof_indices.clear();
#if defined(LIBMESH_HAVE_PETSC) && !PETSC_VERSION_LESS_THAN(3,3,0)
// An ugly hack: have to extract the row and look at it's sparsity structure, since otherwise I won't get the dofs connected to this row by virtue of intervariable coupling
// This is easier than sifting through all coupled variables, selecting those active on the current subdomain, dealing with the scalar variables, etc.
// Also, importantly, this will miss coupling to variables that might have introduced by prior constraints similar to this one!
PetscMatrix<Number>* petsc_jacobian = dynamic_cast<PetscMatrix<Number> *>(_jacobian);
mooseAssert(petsc_jacobian, "Expected a PETSc matrix");
Mat jac = petsc_jacobian->mat();
PetscErrorCode ierr;
PetscInt ncols;
const PetscInt *cols;
ierr = MatGetRow(jac,_var.nodalDofIndex(),&ncols,&cols,PETSC_NULL);CHKERRABORT(PetscObjectComm((PetscObject)jac), ierr);
bool debug = false;
if(debug) {
libMesh::out << "_connected_dof_indices: adding " << ncols << " dofs from Jacobian row[" << _var.nodalDofIndex() << "] = [";
}
for (PetscInt i = 0; i < ncols; ++i) {
if(debug) {
libMesh::out << cols[i] << " ";
}
_connected_dof_indices.push_back(cols[i]);
}
if (debug) {
libMesh::out << "]\n";
}
ierr = MatRestoreRow(jac,_var.nodalDofIndex(),&ncols,&cols,PETSC_NULL);CHKERRABORT(PetscObjectComm((PetscObject)jac), ierr);
#else
std::vector<unsigned int> & elems = _node_to_elem_map[_current_node->id()];
std::set<unsigned int> unique_dof_indices;
// Get the dof indices from each elem connected to the node
for(unsigned int el=0; el < elems.size(); ++el)
{
unsigned int cur_elem = elems[el];
std::vector<unsigned int> dof_indices;
_var.getDofIndices(_mesh.elem(cur_elem), dof_indices);
for(unsigned int di=0; di < dof_indices.size(); di++)
unique_dof_indices.insert(dof_indices[di]);
}
for(std::set<unsigned int>::iterator sit=unique_dof_indices.begin(); sit != unique_dof_indices.end(); ++sit)
_connected_dof_indices.push_back(*sit);
#endif
// DenseMatrix<Number> & Kee = _assembly.jacobianBlock(_var.number(), _var.number());
DenseMatrix<Number> & Ken = _assembly.jacobianBlockNeighbor(Moose::ElementNeighbor, _var.number(), _var.number());
// DenseMatrix<Number> & Kne = _assembly.jacobianBlockNeighbor(Moose::NeighborElement, _var.number(), _var.number());
DenseMatrix<Number> & Knn = _assembly.jacobianBlockNeighbor(Moose::NeighborNeighbor, _var.number(), _var.number());
_Kee.resize(_test_slave.size(), _connected_dof_indices.size());
_Kne.resize(_test_master.size(), _connected_dof_indices.size());
_phi_slave.resize(_connected_dof_indices.size());
_qp = 0;
// Fill up _phi_slave so that it is 1 when j corresponds to this dof and 0 for every other dof
// This corresponds to evaluating all of the connected shape functions at _this_ node
for(unsigned int j=0; j<_connected_dof_indices.size(); j++)
{
_phi_slave[j].resize(1);
if(_connected_dof_indices[j] == _var.nodalDofIndex())
_phi_slave[j][_qp] = 1.0;
else
_phi_slave[j][_qp] = 0.0;
}
for (_i = 0; _i < _test_slave.size(); _i++)
// Loop over the connected dof indices so we can get all the jacobian contributions
for (_j=0; _j<_connected_dof_indices.size(); _j++)
_Kee(_i,_j) += computeQpJacobian(Moose::SlaveSlave);
for (_i=0; _i<_test_slave.size(); _i++)
for (_j=0; _j<_phi_master.size(); _j++)
Ken(_i,_j) += computeQpJacobian(Moose::SlaveMaster);
for (_i=0; _i<_test_master.size(); _i++)
// Loop over the connected dof indices so we can get all the jacobian contributions
for (_j=0; _j<_connected_dof_indices.size(); _j++)
_Kne(_i,_j) += computeQpJacobian(Moose::MasterSlave);
for (_i=0; _i<_test_master.size(); _i++)
for (_j=0; _j<_phi_master.size(); _j++)
Knn(_i,_j) += computeQpJacobian(Moose::MasterMaster);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include "ChannelSelectTestRequestProxy.h"
#include "ChannelSelectTestIndicationWrapper.h"
#include "GeneratedTypes.h"
sem_t data_sem;
sem_t config_sem;
class ChannelSelectTestIndication : public ChannelSelectTestIndicationWrapper
{
public:
ChannelSelectTestIndication(unsigned int id) : ChannelSelectTestIndicationWrapper(id){}
virtual void ifreqData(unsigned dataRe, unsigned dataIm){
fprintf(stderr, "read %x %x\n", dataRe, dataIm);
}
virtual void setDataResp(){
fprintf(stderr, "setDataResp\n");
sem_post(&data_sem);
}
virtual void setConfigResp(){
fprintf(stderr, "setDataResp\n");
sem_post(&config_sem);
}
};
class DDSTestIndication : public DDSTestIndicationWrapper
{
public:
DDSTestIndication(unsigned int id) : DDSTestIndicationWrapper(id){}
virtual void ddsData(unsigned phase, unsigned dataRe, unsigned dataIm){
fprintf("data %d %X %x\n", phase, dataRe, dataIM);
sem_post(&data_sem);
}
};
int main(int argc, const char **argv)
{
ChannelSelectTestRequestProxy *ctdevice = 0;
ChannelSelectTestIndication *ctindication = 0;
DDSTestRequestProxy *ctdevice = 0;
DDSTestIndication *ctindication = 0;
sem_init(&data_sem, 0, 0);
sem_init(&config_sem, 0, 0);
fprintf(stderr, "Main::%s %s\n", __DATE__, __TIME__);
ctdevice = new ChannelSelectTestRequestProxy(IfcNames_ChannelSelectTestRequest);
ctindication = new ChannelSelectTestIndication(IfcNames_ChannelSelectTestIndication);
ddsdevice = new DDSTestRequestProxy(IfcNames_DDSTestRequest);
ddsindication = new DDSTestIndication(IfcNames_DDSTestIndication);
portalExec_start();
fprintf(stdout, "DDSTest\n");
ddsdevice.setPhaseAdvance(1, 0);
for (i = 0; i < 2048; i += 1)
ddsdevice.getData();
fprintf(stdout, "Main::starting\n");
device->setCoeff(0, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(1, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(2, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(3, 1<<21, 0);
sem_wait(&config_sem);
device->setPhaseAdvance(0, 1 << 21);
sem_wait(&config_sem);
int i;
for (i = 0; i < 128; i += 1) {
device->rfreqDataWrite(1<<16, 0); // should be re=1, im=0
sem_wait(&data_sem);
}
fprintf(stderr, "Main::stopping\n");
exit(0);
}
<commit_msg>add dds.setConfigResp<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include "ChannelSelectTestRequestProxy.h"
#include "ChannelSelectTestIndicationWrapper.h"
#include "GeneratedTypes.h"
sem_t data_sem;
sem_t config_sem;
class ChannelSelectTestIndication : public ChannelSelectTestIndicationWrapper
{
public:
ChannelSelectTestIndication(unsigned int id) : ChannelSelectTestIndicationWrapper(id){}
virtual void ifreqData(unsigned dataRe, unsigned dataIm){
fprintf(stderr, "read %x %x\n", dataRe, dataIm);
}
virtual void setDataResp(){
fprintf(stderr, "setDataResp\n");
sem_post(&data_sem);
}
virtual void setConfigResp(){
fprintf(stderr, "setDataResp\n");
sem_post(&config_sem);
}
};
class DDSTestIndication : public DDSTestIndicationWrapper
{
public:
DDSTestIndication(unsigned int id) : DDSTestIndicationWrapper(id){}
virtual void ddsData(unsigned phase, unsigned dataRe, unsigned dataIm){
fprintf("data %d %X %x\n", phase, dataRe, dataIM);
sem_post(&data_sem);
}
virtual void setConfigResp(){
fprintf(stderr, "dds.setDataResp\n");
sem_post(&config_sem);
}
};
int main(int argc, const char **argv)
{
ChannelSelectTestRequestProxy *ctdevice = 0;
ChannelSelectTestIndication *ctindication = 0;
DDSTestRequestProxy *ctdevice = 0;
DDSTestIndication *ctindication = 0;
sem_init(&data_sem, 0, 0);
sem_init(&config_sem, 0, 0);
fprintf(stderr, "Main::%s %s\n", __DATE__, __TIME__);
ctdevice = new ChannelSelectTestRequestProxy(IfcNames_ChannelSelectTestRequest);
ctindication = new ChannelSelectTestIndication(IfcNames_ChannelSelectTestIndication);
ddsdevice = new DDSTestRequestProxy(IfcNames_DDSTestRequest);
ddsindication = new DDSTestIndication(IfcNames_DDSTestIndication);
portalExec_start();
fprintf(stdout, "DDSTest\n");
ddsdevice.setPhaseAdvance(1, 0);
for (i = 0; i < 2048; i += 1)
ddsdevice.getData();
fprintf(stdout, "Main::starting\n");
device->setCoeff(0, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(1, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(2, 1<<21, 0);
sem_wait(&config_sem);
device->setCoeff(3, 1<<21, 0);
sem_wait(&config_sem);
device->setPhaseAdvance(0, 1 << 21);
sem_wait(&config_sem);
int i;
for (i = 0; i < 128; i += 1) {
device->rfreqDataWrite(1<<16, 0); // should be re=1, im=0
sem_wait(&data_sem);
}
fprintf(stderr, "Main::stopping\n");
exit(0);
}
<|endoftext|>
|
<commit_before>#include "../ris_lib/ris_generator.h"
#include "../ris_lib/ris_json_resources.h"
#include "../ris_lib/ris_bundle_compression.h"
#include "../ris_lib/ris_writing_files.h"
#include "../ris_lib/template.h"
#include "../ris_lib/ris_resource_loader.h"
#include "../ris_lib/ris_default_or_from_file.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <boost/filesystem.hpp>
void print_usage() {
std::cout
<< "USAGE:" << std::endl
<< " ris <path_to>/ris.json" << std::endl
;
}
void process(std::string const& path, std::string const& source_template) {
auto full_path = absolute(boost::filesystem::path(path));
full_path.make_preferred();
std::cout << "reading " << full_path.generic_string() << std::endl;
auto r = ris::json_resources(path);
std::cout << "read " << r.resources().resources.size() << " resources" << std::endl;
auto c = ris::bundle_compression();
auto t = ris::default_or_from_file<ris::Resource>(source_template);
auto g = ris::get_generator(r, c, t);
ris::write_to_temp_first_then_move header([&g](std::ostream& s) {
g.generate_header(s);
}, r.header());
header.start();
ris::write_to_temp_first_then_move source([&g](std::ostream& s) {
g.generate_source(s);
}, r.source());
source.start();
}
int main(int argc, char ** argv) {
std::string source_template;
switch (argc) {
case 3:
source_template = argv[2];
// fall through
case 2:
try {
process(argv[1], source_template);
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
break;
default:
print_usage();
}
}
<commit_msg>usage of template overrides<commit_after>#include "../ris_lib/ris_generator.h"
#include "../ris_lib/ris_json_resources.h"
#include "../ris_lib/ris_bundle_compression.h"
#include "../ris_lib/ris_writing_files.h"
#include "../ris_lib/template.h"
#include "../ris_lib/ris_resource_loader.h"
#include "../ris_lib/ris_default_or_from_file.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <boost/filesystem.hpp>
void print_usage() {
std::cout
<< "USAGE:" << std::endl
<< " ris <path_to>/<resources>.json [<template_overrides>.json]" << std::endl
;
}
void process(std::string const& path, std::string const& source_template) {
auto full_path = absolute(boost::filesystem::path(path));
full_path.make_preferred();
std::cout << "reading " << full_path.generic_string() << std::endl;
auto r = ris::json_resources(path);
std::cout << "read " << r.resources().resources.size() << " resources" << std::endl;
auto c = ris::bundle_compression();
auto t = ris::default_or_from_file<ris::Resource>(source_template);
auto g = ris::get_generator(r, c, t);
ris::write_to_temp_first_then_move header([&g](std::ostream& s) {
g.generate_header(s);
}, r.header());
header.start();
ris::write_to_temp_first_then_move source([&g](std::ostream& s) {
g.generate_source(s);
}, r.source());
source.start();
}
int main(int argc, char ** argv) {
std::string source_template;
switch (argc) {
case 3:
source_template = argv[2];
// fall through
case 2:
try {
process(argv[1], source_template);
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
break;
default:
print_usage();
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <pdal/FileUtils.hpp>
#include "Support.hpp"
#include <iostream>
#include <sstream>
#include <string>
BOOST_AUTO_TEST_SUITE(pcinfoTest)
static std::string appName()
{
const std::string app = Support::binpath(Support::exename("pcinfo"));
BOOST_CHECK(pdal::FileUtils::fileExists(app));
return app;
}
#ifdef PDAL_COMPILER_MSVC
BOOST_AUTO_TEST_CASE(pcinfoTest_no_input)
{
const std::string cmd = appName();
std::string output;
int stat = Support::run_command(cmd, output);
BOOST_CHECK_EQUAL(stat, 1);
const std::string expected = "Usage error: input file name required";
BOOST_CHECK_EQUAL(output.substr(0, expected.length()), expected);
return;
}
#endif
BOOST_AUTO_TEST_CASE(pcinfo_test_common_opts)
{
const std::string cmd = appName();
std::string output;
int stat = Support::run_command(cmd + " -h", output);
BOOST_CHECK_EQUAL(stat, 0);
stat = Support::run_command(cmd + " --version", output);
BOOST_CHECK_EQUAL(stat, 0);
return;
}
BOOST_AUTO_TEST_CASE(pcinfo_test_switches)
{
const std::string cmd = appName();
std::string inputLas = Support::datapath("apps/simple.las");
std::string inputLaz = Support::datapath("apps/simple.laz");
std::string output;
int stat = 0;
// does the default work?
stat = Support::run_command(cmd + " " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
// does --input work?
stat = Support::run_command(cmd + " --input=" + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
// does -i work?
stat = Support::run_command(cmd + " -i " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#ifdef PDAL_HAVE_LASZIP
// does it work for .laz?
stat = Support::run_command(cmd + " " + inputLaz, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#ifdef PDAL_HAVE_LIBLAS
// does --liblas work?
stat = Support::run_command(cmd + " --liblas " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#ifdef PDAL_HAVE_LIBLAS
#ifdef PDAL_HAVE_LASZIP
// does --liblas work for .laz too?
stat = Support::run_command(cmd + " --liblas " + inputLaz, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#endif
return;
}
BOOST_AUTO_TEST_CASE(pcinfo_test_dumps)
{
const std::string cmd = appName();
const std::string inputLas = Support::datapath("apps/simple.las");
const std::string inputLaz = Support::datapath("apps/simple.laz");
const std::string outputTxt = Support::temppath("pcinfo.txt");
std::string output;
int stat = 0;
// dump a single point to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --point=1 " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_point.txt")));
// dump summary of all points to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --stats " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_stats.txt")));
// dump schema to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --schema " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_schema.txt")));
// dump stage info to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --stage " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#ifdef PDAL_HAVE_GDAL
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_stage.txt")));
#else
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_stage_nosrs.txt")));
#endif
pdal::FileUtils::deleteFile(outputTxt);
return;
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>ingore messy path stuff in outputs<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <pdal/FileUtils.hpp>
#include "Support.hpp"
#include <iostream>
#include <sstream>
#include <string>
BOOST_AUTO_TEST_SUITE(pcinfoTest)
static std::string appName()
{
const std::string app = Support::binpath(Support::exename("pcinfo"));
BOOST_CHECK(pdal::FileUtils::fileExists(app));
return app;
}
#ifdef PDAL_COMPILER_MSVC
BOOST_AUTO_TEST_CASE(pcinfoTest_no_input)
{
const std::string cmd = appName();
std::string output;
int stat = Support::run_command(cmd, output);
BOOST_CHECK_EQUAL(stat, 1);
const std::string expected = "Usage error: input file name required";
BOOST_CHECK_EQUAL(output.substr(0, expected.length()), expected);
return;
}
#endif
BOOST_AUTO_TEST_CASE(pcinfo_test_common_opts)
{
const std::string cmd = appName();
std::string output;
int stat = Support::run_command(cmd + " -h", output);
BOOST_CHECK_EQUAL(stat, 0);
stat = Support::run_command(cmd + " --version", output);
BOOST_CHECK_EQUAL(stat, 0);
return;
}
BOOST_AUTO_TEST_CASE(pcinfo_test_switches)
{
const std::string cmd = appName();
std::string inputLas = Support::datapath("apps/simple.las");
std::string inputLaz = Support::datapath("apps/simple.laz");
std::string output;
int stat = 0;
// does the default work?
stat = Support::run_command(cmd + " " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
// does --input work?
stat = Support::run_command(cmd + " --input=" + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
// does -i work?
stat = Support::run_command(cmd + " -i " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#ifdef PDAL_HAVE_LASZIP
// does it work for .laz?
stat = Support::run_command(cmd + " " + inputLaz, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#ifdef PDAL_HAVE_LIBLAS
// does --liblas work?
stat = Support::run_command(cmd + " --liblas " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#ifdef PDAL_HAVE_LIBLAS
#ifdef PDAL_HAVE_LASZIP
// does --liblas work for .laz too?
stat = Support::run_command(cmd + " --liblas " + inputLaz, output);
BOOST_CHECK_EQUAL(stat, 0);
#endif
#endif
return;
}
BOOST_AUTO_TEST_CASE(pcinfo_test_dumps)
{
const std::string cmd = appName();
const std::string inputLas = Support::datapath("apps/simple.las");
const std::string inputLaz = Support::datapath("apps/simple.laz");
const std::string outputTxt = Support::temppath("pcinfo.txt");
std::string output;
int stat = 0;
// dump a single point to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --point=1 " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_point.txt")));
// dump summary of all points to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --stats " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_stats.txt")));
// dump schema to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --schema " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
BOOST_CHECK(Support::compare_text_files(outputTxt, Support::datapath("apps/pcinfo_schema.txt")));
// dump stage info to json
stat = Support::run_command(cmd + " --output=" + outputTxt + " --stage " + inputLas, output);
BOOST_CHECK_EQUAL(stat, 0);
#ifdef PDAL_HAVE_GDAL
BOOST_CHECK_EQUAL(Support::diff_text_files(outputTxt, Support::datapath("apps/pcinfo_stage.txt"), 15), 0u);
#else
BOOST_CHECK_EQUAL(Support::diff_text_files(outputTxt, Support::datapath("apps/pcinfo_stage_nosrs.txt"), 15), 0u);
#endif
pdal::FileUtils::deleteFile(outputTxt);
return;
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/*
* Escape or unescape HTML entities.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "escape_html.hxx"
#include "escape_class.h"
#include "strref.h"
#include "strutil.h"
#include <assert.h>
#include <string.h>
static const char *
html_unescape_find(const char *p, size_t length)
{
return (const char *)memchr(p, '&', length);
}
static const char *
find_semicolon(const char *p, const char *end)
{
while (p < end) {
if (*p == ';')
return p;
else if (!char_is_letter(*p))
break;
++p;
}
return nullptr;
}
static size_t
html_unescape(const char *p, size_t length, char *q)
{
const char *p_end = p + length, *q_start = q;
const char *amp;
while ((amp = (const char *)memchr(p, '&', p_end - p)) != nullptr) {
memmove(q, p, amp - p);
q += amp - p;
struct strref entity;
entity.data = amp + 1;
const char *semicolon = find_semicolon(entity.data, p_end);
if (semicolon == nullptr) {
*q++ = '&';
p = amp + 1;
continue;
}
entity.length = semicolon - entity.data;
if (strref_cmp_literal(&entity, "amp") == 0)
*q++ = '&';
else if (strref_cmp_literal(&entity, "quot") == 0)
*q++ = '"';
else if (strref_cmp_literal(&entity, "lt") == 0)
*q++ = '<';
else if (strref_cmp_literal(&entity, "gt") == 0)
*q++ = '>';
else if (strref_cmp_literal(&entity, "apos") == 0)
*q++ = '\'';
p = semicolon + 1;
}
memmove(q, p, p_end - p);
q += p_end - p;
return q - q_start;
}
static size_t
html_escape_size(const char *p, size_t length)
{
const char *end = p + length;
size_t size = 0;
while (p < end) {
switch (*p++) {
case '&':
size += 5;
break;
case '"':
case '\'':
size += 6;
break;
case '<':
case '>':
size += 4;
break;
default:
++size;
}
}
return size;
}
static const char *
html_escape_find(const char *p, size_t length)
{
const char *end = p + length;
while (p < end) {
switch (*p) {
case '&':
case '"':
case '\'':
case '<':
case '>':
return p;
default:
++p;
}
}
return nullptr;
}
static const char *
html_escape_char(char ch)
{
switch (ch) {
case '&':
return "&";
case '"':
return """;
case '\'':
return "'";
case '<':
return "<";
case '>':
return ">";
default:
assert(false);
return nullptr;
}
}
static size_t
html_escape(const char *p, size_t length, char *q)
{
const char *p_end = p + length, *q_start = q;
while (p < p_end) {
char ch = *p++;
switch (ch) {
case '&':
memmove(q, "&", 5);
q += 5;
break;
case '"':
memmove(q, """, 6);
q += 6;
break;
case '\'':
memmove(q, "'", 6);
q += 6;
break;
case '<':
memmove(q, "<", 4);
q += 4;
break;
case '>':
memmove(q, ">", 4);
q += 4;
break;
default:
*q++ = ch;
}
}
return q - q_start;
}
const struct escape_class html_escape_class = {
.unescape_find = html_unescape_find,
.unescape = html_unescape,
.escape_find = html_escape_find,
.escape_char = html_escape_char,
.escape_size = html_escape_size,
.escape = html_escape,
};
<commit_msg>escape_html: use mempcpy() instead of memmove()<commit_after>/*
* Escape or unescape HTML entities.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "escape_html.hxx"
#include "escape_class.h"
#include "strref.h"
#include "strutil.h"
#include <assert.h>
#include <string.h>
static const char *
html_unescape_find(const char *p, size_t length)
{
return (const char *)memchr(p, '&', length);
}
static const char *
find_semicolon(const char *p, const char *end)
{
while (p < end) {
if (*p == ';')
return p;
else if (!char_is_letter(*p))
break;
++p;
}
return nullptr;
}
static size_t
html_unescape(const char *p, size_t length, char *q)
{
const char *p_end = p + length, *q_start = q;
const char *amp;
while ((amp = (const char *)memchr(p, '&', p_end - p)) != nullptr) {
memmove(q, p, amp - p);
q += amp - p;
struct strref entity;
entity.data = amp + 1;
const char *semicolon = find_semicolon(entity.data, p_end);
if (semicolon == nullptr) {
*q++ = '&';
p = amp + 1;
continue;
}
entity.length = semicolon - entity.data;
if (strref_cmp_literal(&entity, "amp") == 0)
*q++ = '&';
else if (strref_cmp_literal(&entity, "quot") == 0)
*q++ = '"';
else if (strref_cmp_literal(&entity, "lt") == 0)
*q++ = '<';
else if (strref_cmp_literal(&entity, "gt") == 0)
*q++ = '>';
else if (strref_cmp_literal(&entity, "apos") == 0)
*q++ = '\'';
p = semicolon + 1;
}
memmove(q, p, p_end - p);
q += p_end - p;
return q - q_start;
}
static size_t
html_escape_size(const char *p, size_t length)
{
const char *end = p + length;
size_t size = 0;
while (p < end) {
switch (*p++) {
case '&':
size += 5;
break;
case '"':
case '\'':
size += 6;
break;
case '<':
case '>':
size += 4;
break;
default:
++size;
}
}
return size;
}
static const char *
html_escape_find(const char *p, size_t length)
{
const char *end = p + length;
while (p < end) {
switch (*p) {
case '&':
case '"':
case '\'':
case '<':
case '>':
return p;
default:
++p;
}
}
return nullptr;
}
static const char *
html_escape_char(char ch)
{
switch (ch) {
case '&':
return "&";
case '"':
return """;
case '\'':
return "'";
case '<':
return "<";
case '>':
return ">";
default:
assert(false);
return nullptr;
}
}
static size_t
html_escape(const char *p, size_t length, char *q)
{
const char *p_end = p + length, *q_start = q;
while (p < p_end) {
char ch = *p++;
switch (ch) {
case '&':
q = mempcpy(q, "&", 5);
break;
case '"':
q = mempcpy(q, """, 6);
break;
case '\'':
q = mempcpy(q, "'", 6);
break;
case '<':
q = mempcpy(q, "<", 4);
break;
case '>':
q = mempcpy(q, ">", 4);
break;
default:
*q++ = ch;
}
}
return q - q_start;
}
const struct escape_class html_escape_class = {
.unescape_find = html_unescape_find,
.unescape = html_unescape,
.escape_find = html_escape_find,
.escape_char = html_escape_char,
.escape_size = html_escape_size,
.escape = html_escape,
};
<|endoftext|>
|
<commit_before>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.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. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
#define KOPETE_VERSION "0.6.90cvs >= 20030326"
static const char *description =
I18N_NOOP("Kopete, the KDE Instant Messenger");
static KCmdLineOptions options[] =
{
{ "noplugins", I18N_NOOP("Do not load plugins"), 0 },
{ "noconnect" , I18N_NOOP("Disable auto-connection") , 0 },
// { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO
{ "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 },
{ "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
I18N_NOOP("(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" );
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" );
aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net");
aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" );
aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" );
aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") );
aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
//aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Old developer"), "ryan@kde.org" );
aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Old Developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Old Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Old Developer"), "dae@chez.com" );
aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Update the version string at least once a month :-D<commit_after>/*
Kopete , The KDE Instant Messenger
Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Viva Chile Mierda!
Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.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. *
* *
*************************************************************************
*/
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopete.h"
#include <dcopclient.h>
#include "kopeteiface.h"
#define KOPETE_VERSION "0.6.90cvs >= 20030426"
static const char *description =
I18N_NOOP("Kopete, the KDE Instant Messenger");
static KCmdLineOptions options[] =
{
{ "noplugins", I18N_NOOP("Do not load plugins"), 0 },
{ "noconnect" , I18N_NOOP("Disable auto-connection") , 0 },
// { "connect <account>" , I18N_NOOP("auto-connect specified account") , 0 }, //TODO
{ "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 },
{ "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
KOPETE_VERSION, description, KAboutData::License_GPL,
I18N_NOOP("(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002,2003, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");
aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" );
aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net");
aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer, MSN Plugin"), "ogoffart@tiscalinet.be");
aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" );
aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" );
aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" );
aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net");
aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Core developer"), "jason@keirstead.org", "http://www.keirstead.org");
aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" );
aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, Icons, Plugins"), "lists@stevello.free-online.co.uk" );
aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") );
aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") );
aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") );
aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
//aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );
aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Old developer"), "ryan@kde.org" );
aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Old Developer"), "remenic@linuxfromscratch.org");
aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Old Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Old Developer"), "dae@chez.com" );
aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
KUniqueApplication::addCmdLineOptions();
Kopete kopete;
kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec
kopete.exec();
}
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstring>
#include <chrono>
typedef long long ll;
static const int N = 1<<20;//10^5
static const int M = 500000 + 8;//5*10^5
static const int oo = 1000000000;
int a[N];
int n,m;
char in[1<<23];
char out[1<<23];
struct scanner
{
char const* o;
scanner(): o(in){
in[fread(in,1,sizeof(in)-4,stdin)] = 0;
}
int readInt()
{
unsigned u = 0, s= 0;
while(*o && *o <= 32)++o;
if (*o == '-')s = ~0,++o;else if (*o == '+')++o;
while(*o >='0' && *o <='9')u = (u << 3) + (u << 1) + (*o++ -'0');
return (u^s) + !!s;
}
};
struct writer
{
char * w;
writer() : w(out){}
~writer(){ flush(); }
void writeInt( ll u, char c)
{
if (u < 0){*w++ = '-'; u = -u;}
ll v = u;
int n = 0,m;
do ++n; while(v/=10);
m = n;
while(m-->0)w[m] = u%10 + '0',u/=10;
w+=n;
*w++=c;
}
void flush(){ if (w != out) fwrite(out, 1, w - out, stdout), w = out;}
};
struct auto_cpu_timer
{
typedef std::chrono::high_resolution_clock ct;
typedef ct::time_point tp;
tp s,e;
auto_cpu_timer(){ s = ct::now();}
~auto_cpu_timer(){ e = ct::now();
long int n = std::chrono::duration_cast< std::chrono::milliseconds > ( e - s).count();
fprintf(stderr,"\nelapsed time: %ld ms.\n", n);
}
};
int solve()
{
auto_cpu_timer cpu_timer;
scanner sc;
writer pw;
n = sc.readInt();
for(int i = 0; i < n; ++i)a[i] = sc.readInt();
//sort(a, a + n);
for(int i = 0; i < n; ++i)pw.writeInt(a[i], ' ');
return 0;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
solve();
return 0;
}
<commit_msg>Update test.cpp<commit_after>
// TEST my fast i/o implementation
// read and write 10^6 numbers took 120 milliseconds.
#include <cstdio>
#include <cstring>
#include <chrono>
#include <cstdlib>
static const int N = 1<<20;//10^6
int a[N];
int n;
char in[1<<23];
char out[1<<23];
struct scanner
{
char const* o;
scanner(): o(in){
in[fread(in,1,sizeof(in)-4,stdin)] = 0;
}
int readInt()
{
unsigned u = 0, s= 0;
while(*o && *o <= 32)++o;
if (*o == '-')s = ~0,++o;else if (*o == '+')++o;
while(*o >='0' && *o <='9')u = (u << 3) + (u << 1) + (*o++ -'0');
return (u^s) + !!s;
}
};
struct writer
{
char * w;
writer() : w(out){}
~writer(){ flush(); }
void writeInt( int u, char c)
{
if (u < 0){*w++ = '-'; u = -u;}
int v = u;
int n = 0,m;
do ++n; while(v/=10);
m = n;
while(m-->0)w[m] = u%10 + '0',u/=10;
w+=n;
*w++=c;
}
void flush(){ if (w != out) fwrite(out, 1, w - out, stdout), w = out;}
};
struct auto_cpu_timer
{
typedef std::chrono::high_resolution_clock ct;
typedef ct::time_point tp;
tp s,e;
auto_cpu_timer(){ s = ct::now();}
~auto_cpu_timer(){ e = ct::now();
long int n = std::chrono::duration_cast< std::chrono::milliseconds > ( e - s).count();
fprintf(stderr,"\nelapsed time: %ld ms.\n", n);
}
};
int test()
{
auto_cpu_timer cpu_timer;
scanner sc;
writer pw;
n = sc.readInt();
for(int i = 0; i < n; ++i)a[i] = sc.readInt();
//sort(a, a + n);
for(int i = 0; i < n; ++i)pw.writeInt(a[i], ' ');
return 0;
}
void writeMillionNumbers()
{
FILE * f = fopen("input.txt", "w");
if (f != NULL)
{
n = 1000*1000;
fprintf(f, "%d\n", n);
srand(time(NULL));
for(int i = 0; i < n; ++i)fprintf(f, "%d ", rand());
fclose(f);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// uncomment for write 10^6 numbers
writeMillionNumbers();
test();
return 0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2016 Sergey Alexandrov
*
* 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 <fstream>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <boost/format.hpp>
#include <boost/throw_exception.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <radical/mat_io.h>
#include <radical/exceptions.h>
#include <radical/radiometric_response.h>
/** Helper function for inverse look-up in a table (cv::Vec3f → Vec3b). */
inline cv::Vec3b inverseLUT(const std::vector<cv::Mat>& lut, const cv::Vec3f& in) {
cv::Vec3b out;
for (int c = 0; c < 3; ++c) {
auto begin = &lut[c].at<float>(0);
auto p = std::lower_bound(begin, &lut[c].at<float>(255), in[c]);
out[c] = std::distance(begin, p);
}
return out;
}
namespace radical {
RadiometricResponse::RadiometricResponse(cv::InputArray _response, ChannelOrder order) : order_(order) {
if (_response.total() != 256)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Radiometric response should have exactly 256 elements")
<< RadiometricResponseException::Size(_response.size()));
if (_response.type() != CV_32FC3)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Radiometric response values should be 3-channel float")
<< RadiometricResponseException::Type(_response.type()));
if (order_ == ChannelOrder::RGB)
cv::cvtColor(_response, response_, CV_BGR2RGB);
else
response_ = _response.getMat();
cv::log(response_, log_response_);
cv::split(response_, response_channels_);
}
RadiometricResponse::RadiometricResponse(const std::string& filename, ChannelOrder order)
: RadiometricResponse(readMat(filename), order) {}
RadiometricResponse::~RadiometricResponse() {}
void RadiometricResponse::save(const std::string& filename) const {
cv::Mat response;
if (order_ == ChannelOrder::RGB)
cv::cvtColor(response_, response, CV_RGB2BGR);
else
response = response_;
writeMat(filename, response);
}
cv::Vec3b RadiometricResponse::directMap(const cv::Vec3f& E) const {
return inverseLUT(response_channels_, E);
}
void RadiometricResponse::directMap(cv::InputArray _E, cv::OutputArray _I) const {
if (_E.empty()) {
_I.clear();
return;
}
auto E = _E.getMat();
_I.create(_E.size(), CV_8UC3);
auto I = _I.getMat();
#if CV_MAJOR_VERSION > 2
E.forEach<cv::Vec3f>(
[&I, this](cv::Vec3f& v, const int* p) { I.at<cv::Vec3b>(p[0], p[1]) = inverseLUT(response_channels_, v); });
#else
for (int i = 0; i < E.rows; i++)
for (int j = 0; j < E.cols; j++)
I.at<cv::Vec3b>(i, j) = inverseLUT(response_channels_, E.at<cv::Vec3f>(i, j));
#endif
}
cv::Vec3f RadiometricResponse::inverseMap(const cv::Vec3b& _I) const {
cv::Mat I(1, 1, CV_8UC3);
I.at<cv::Vec3b>(0, 0) = _I;
cv::Mat E;
cv::LUT(I, response_, E);
return E.at<cv::Vec3f>(0, 0);
}
void RadiometricResponse::inverseMap(cv::InputArray _I, cv::OutputArray _E) const {
if (_I.empty())
BOOST_THROW_EXCEPTION(RadiometricResponseException("Brightness image should not be empty"));
if (_I.depth() != CV_8U && _I.depth() != CV_8S)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Brightness image should have 8U or 8S depth"));
cv::LUT(_I, response_, _E);
}
} // namespace radical
<commit_msg>Remove unused includes in radiometric_response.cpp<commit_after>/******************************************************************************
* Copyright (c) 2016 Sergey Alexandrov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#include <algorithm>
#include <boost/throw_exception.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <radical/mat_io.h>
#include <radical/exceptions.h>
#include <radical/radiometric_response.h>
/** Helper function for inverse look-up in a table (cv::Vec3f → Vec3b). */
inline cv::Vec3b inverseLUT(const std::vector<cv::Mat>& lut, const cv::Vec3f& in) {
cv::Vec3b out;
for (int c = 0; c < 3; ++c) {
auto begin = &lut[c].at<float>(0);
auto p = std::lower_bound(begin, &lut[c].at<float>(255), in[c]);
out[c] = std::distance(begin, p);
}
return out;
}
namespace radical {
RadiometricResponse::RadiometricResponse(cv::InputArray _response, ChannelOrder order) : order_(order) {
if (_response.total() != 256)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Radiometric response should have exactly 256 elements")
<< RadiometricResponseException::Size(_response.size()));
if (_response.type() != CV_32FC3)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Radiometric response values should be 3-channel float")
<< RadiometricResponseException::Type(_response.type()));
if (order_ == ChannelOrder::RGB)
cv::cvtColor(_response, response_, CV_BGR2RGB);
else
response_ = _response.getMat();
cv::log(response_, log_response_);
cv::split(response_, response_channels_);
}
RadiometricResponse::RadiometricResponse(const std::string& filename, ChannelOrder order)
: RadiometricResponse(readMat(filename), order) {}
RadiometricResponse::~RadiometricResponse() {}
void RadiometricResponse::save(const std::string& filename) const {
cv::Mat response;
if (order_ == ChannelOrder::RGB)
cv::cvtColor(response_, response, CV_RGB2BGR);
else
response = response_;
writeMat(filename, response);
}
cv::Vec3b RadiometricResponse::directMap(const cv::Vec3f& E) const {
return inverseLUT(response_channels_, E);
}
void RadiometricResponse::directMap(cv::InputArray _E, cv::OutputArray _I) const {
if (_E.empty()) {
_I.clear();
return;
}
auto E = _E.getMat();
_I.create(_E.size(), CV_8UC3);
auto I = _I.getMat();
#if CV_MAJOR_VERSION > 2
E.forEach<cv::Vec3f>(
[&I, this](cv::Vec3f& v, const int* p) { I.at<cv::Vec3b>(p[0], p[1]) = inverseLUT(response_channels_, v); });
#else
for (int i = 0; i < E.rows; i++)
for (int j = 0; j < E.cols; j++)
I.at<cv::Vec3b>(i, j) = inverseLUT(response_channels_, E.at<cv::Vec3f>(i, j));
#endif
}
cv::Vec3f RadiometricResponse::inverseMap(const cv::Vec3b& _I) const {
cv::Mat I(1, 1, CV_8UC3);
I.at<cv::Vec3b>(0, 0) = _I;
cv::Mat E;
cv::LUT(I, response_, E);
return E.at<cv::Vec3f>(0, 0);
}
void RadiometricResponse::inverseMap(cv::InputArray _I, cv::OutputArray _E) const {
if (_I.empty())
BOOST_THROW_EXCEPTION(RadiometricResponseException("Brightness image should not be empty"));
if (_I.depth() != CV_8U && _I.depth() != CV_8S)
BOOST_THROW_EXCEPTION(RadiometricResponseException("Brightness image should have 8U or 8S depth"));
cv::LUT(_I, response_, _E);
}
} // namespace radical
<|endoftext|>
|
<commit_before>#include "dispatcher_utility.hpp"
#include "grabbable_state_manager/manager.hpp"
#include "iokit_utility.hpp"
#include <csignal>
#include <pqrs/osx/iokit_hid_manager.hpp>
#include <pqrs/osx/iokit_hid_queue_value_monitor.hpp>
namespace {
class grabbable_state_manager_demo final : public pqrs::dispatcher::extra::dispatcher_client {
public:
grabbable_state_manager_demo(const grabbable_state_manager_demo&) = delete;
grabbable_state_manager_demo(void) : dispatcher_client() {
grabbable_state_manager_ = std::make_unique<krbn::grabbable_state_manager::manager>();
grabbable_state_manager_->grabbable_state_changed.connect([](auto&& grabbable_state) {
std::cout << "grabbable_state_changed "
<< grabbable_state.get_device_id()
<< " "
<< grabbable_state.get_state()
<< std::endl;
});
std::vector<pqrs::cf_ptr<CFDictionaryRef>> matching_dictionaries{
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_mouse),
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
};
hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_,
matching_dictionaries);
hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) {
if (device_ptr) {
auto device_id = krbn::make_device_id(registry_entry_id);
std::cout << krbn::iokit_utility::make_device_name_for_log(device_id,
*device_ptr)
<< "is matched." << std::endl;
auto hid_queue_value_monitor = std::make_shared<pqrs::osx::iokit_hid_queue_value_monitor>(weak_dispatcher_,
*device_ptr);
hid_queue_value_monitors_[device_id] = hid_queue_value_monitor;
hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
if (grabbable_state_manager_) {
auto event_queue = krbn::iokit_utility::make_event_queue(device_id, values_ptr);
grabbable_state_manager_->update(*event_queue);
}
});
hid_queue_value_monitor->async_start(kIOHIDOptionsTypeNone,
std::chrono::milliseconds(3000));
}
});
hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) {
krbn::logger::get_logger().info("registry_entry_id:{0} is terminated.", type_safe::get(registry_entry_id));
auto device_id = krbn::make_device_id(registry_entry_id);
hid_queue_value_monitors_.erase(device_id);
});
hid_manager_->async_start();
}
virtual ~grabbable_state_manager_demo(void) {
detach_from_dispatcher([this] {
hid_manager_ = nullptr;
hid_queue_value_monitors_.clear();
});
}
private:
std::unique_ptr<krbn::grabbable_state_manager::manager> grabbable_state_manager_;
std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_;
std::unordered_map<krbn::device_id, std::shared_ptr<pqrs::osx::iokit_hid_queue_value_monitor>> hid_queue_value_monitors_;
};
auto global_wait = pqrs::make_thread_wait();
} // namespace
int main(int argc, const char* argv[]) {
krbn::dispatcher_utility::initialize_dispatchers();
std::signal(SIGINT, [](int) {
global_wait->notify();
});
auto d = std::make_unique<grabbable_state_manager_demo>();
// ------------------------------------------------------------
global_wait->wait_notice();
// ------------------------------------------------------------
d = nullptr;
krbn::dispatcher_utility::terminate_dispatchers();
std::cout << "finished" << std::endl;
return 0;
}
<commit_msg>fix appendix/grabbable_state_manager<commit_after>#include "dispatcher_utility.hpp"
#include "grabbable_state_manager/manager.hpp"
#include "iokit_utility.hpp"
#include <csignal>
#include <pqrs/osx/iokit_hid_manager.hpp>
#include <pqrs/osx/iokit_hid_queue_value_monitor.hpp>
namespace {
class grabbable_state_manager_demo final : public pqrs::dispatcher::extra::dispatcher_client {
public:
grabbable_state_manager_demo(const grabbable_state_manager_demo&) = delete;
grabbable_state_manager_demo(void) : dispatcher_client() {
grabbable_state_manager_ = std::make_unique<krbn::grabbable_state_manager::manager>();
grabbable_state_manager_->grabbable_state_changed.connect([](auto&& grabbable_state) {
std::cout << "grabbable_state_changed "
<< grabbable_state.get_device_id()
<< " "
<< grabbable_state.get_state()
<< std::endl;
});
std::vector<pqrs::cf_ptr<CFDictionaryRef>> matching_dictionaries{
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_keyboard),
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_mouse),
pqrs::osx::iokit_hid_manager::make_matching_dictionary(
pqrs::osx::iokit_hid_usage_page_generic_desktop,
pqrs::osx::iokit_hid_usage_generic_desktop_pointer),
};
hid_manager_ = std::make_unique<pqrs::osx::iokit_hid_manager>(weak_dispatcher_,
matching_dictionaries);
hid_manager_->device_matched.connect([this](auto&& registry_entry_id, auto&& device_ptr) {
if (device_ptr) {
auto device_id = krbn::make_device_id(registry_entry_id);
std::cout << krbn::iokit_utility::make_device_name_for_log(device_id,
*device_ptr)
<< "is matched." << std::endl;
auto hid_queue_value_monitor = std::make_shared<pqrs::osx::iokit_hid_queue_value_monitor>(weak_dispatcher_,
*device_ptr);
hid_queue_value_monitors_[device_id] = hid_queue_value_monitor;
hid_queue_value_monitor->values_arrived.connect([this, device_id](auto&& values_ptr) {
if (grabbable_state_manager_) {
auto event_queue = krbn::event_queue::utility::make_queue(device_id,
krbn::iokit_utility::make_hid_values(values_ptr));
grabbable_state_manager_->update(*event_queue);
}
});
hid_queue_value_monitor->async_start(kIOHIDOptionsTypeNone,
std::chrono::milliseconds(3000));
}
});
hid_manager_->device_terminated.connect([this](auto&& registry_entry_id) {
krbn::logger::get_logger().info("registry_entry_id:{0} is terminated.", type_safe::get(registry_entry_id));
auto device_id = krbn::make_device_id(registry_entry_id);
hid_queue_value_monitors_.erase(device_id);
});
hid_manager_->async_start();
}
virtual ~grabbable_state_manager_demo(void) {
detach_from_dispatcher([this] {
hid_manager_ = nullptr;
hid_queue_value_monitors_.clear();
});
}
private:
std::unique_ptr<krbn::grabbable_state_manager::manager> grabbable_state_manager_;
std::unique_ptr<pqrs::osx::iokit_hid_manager> hid_manager_;
std::unordered_map<krbn::device_id, std::shared_ptr<pqrs::osx::iokit_hid_queue_value_monitor>> hid_queue_value_monitors_;
};
auto global_wait = pqrs::make_thread_wait();
} // namespace
int main(int argc, const char* argv[]) {
krbn::dispatcher_utility::initialize_dispatchers();
std::signal(SIGINT, [](int) {
global_wait->notify();
});
auto d = std::make_unique<grabbable_state_manager_demo>();
// ------------------------------------------------------------
global_wait->wait_notice();
// ------------------------------------------------------------
d = nullptr;
krbn::dispatcher_utility::terminate_dispatchers();
std::cout << "finished" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_
#include <map>
#include <vector>
#include <utility>
#include "errors.hpp"
#include <boost/ptr_container/ptr_map.hpp>
#include "buffer_cache/alt/page_cache.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
class serializer_t;
class buf_lock_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;
class perfmon_collection_t;
class cache_balancer_t;
class alt_txn_throttler_t {
public:
explicit alt_txn_throttler_t(int64_t minimum_unwritten_changes_limit);
~alt_txn_throttler_t();
alt::throttler_acq_t begin_txn_or_throttle(int64_t expected_change_count);
void end_txn(alt::throttler_acq_t acq);
void inform_memory_limit_change(uint64_t memory_limit,
block_size_t max_block_size);
private:
const int64_t minimum_unwritten_changes_limit_;
new_semaphore_t unwritten_changes_semaphore_;
DISABLE_COPYING(alt_txn_throttler_t);
};
class cache_t : public home_thread_mixin_t {
public:
explicit cache_t(serializer_t *serializer,
cache_balancer_t *balancer,
perfmon_collection_t *perfmon_collection);
~cache_t();
block_size_t max_block_size() const { return page_cache_.max_block_size(); }
// RSI: Remove this.
block_size_t get_block_size() const { return max_block_size(); }
// These todos come from the mirrored cache. The real problem is that whole
// cache account / priority thing is just one ghetto hack amidst a dozen other
// throttling systems. TODO: Come up with a consistent priority scheme,
// i.e. define a "default" priority etc. TODO: As soon as we can support it, we
// might consider supporting a mem_cap paremeter.
cache_account_t create_cache_account(int priority);
private:
friend class txn_t;
friend class buf_read_t;
friend class buf_write_t;
friend class buf_lock_t;
alt_snapshot_node_t *matching_snapshot_node_or_null(
block_id_t block_id,
alt::block_version_t block_version);
void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
scoped_ptr_t<alt_cache_stats_t> stats_;
// throttler_ can cause the txn_t constructor to block
alt_txn_throttler_t throttler_;
alt::page_cache_t page_cache_;
boost::ptr_map<block_id_t, intrusive_list_t<alt_snapshot_node_t> >
snapshot_nodes_by_block_id_;
DISABLE_COPYING(cache_t);
};
class txn_t {
public:
// Constructor for read-only transactions.
txn_t(cache_conn_t *cache_conn, read_access_t read_access);
// KSI: Remove default parameter for expected_change_count.
txn_t(cache_conn_t *cache_conn,
write_durability_t durability,
repli_timestamp_t txn_timestamp,
int64_t expected_change_count = 2);
~txn_t();
cache_t *cache() { return cache_; }
alt::page_txn_t *page_txn() { return page_txn_.get(); }
access_t access() const { return access_; }
void set_account(cache_account_t *cache_account);
cache_account_t *account() { return cache_account_; }
private:
// Resets the *throttler_acq parameter.
static void inform_tracker(cache_t *cache,
alt::throttler_acq_t *throttler_acq);
// Resets the *throttler_acq parameter.
static void pulse_and_inform_tracker(cache_t *cache,
alt::throttler_acq_t *throttler_acq,
cond_t *pulsee);
void help_construct(repli_timestamp_t txn_timestamp,
int64_t expected_change_count,
cache_conn_t *cache_conn);
cache_t *const cache_;
// Initialized to cache()->page_cache_.default_cache_account(), and modified by
// set_account().
cache_account_t *cache_account_;
const access_t access_;
// Only applicable if access_ == write.
const write_durability_t durability_;
scoped_ptr_t<alt::page_txn_t> page_txn_;
DISABLE_COPYING(txn_t);
};
class buf_parent_t;
class buf_lock_t {
public:
buf_lock_t();
// buf_parent_t is a type that either points at a buf_lock_t (its parent) or
// merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
// If acquiring the child for read, the constructor will wait for the parent to
// be acquired for read. Similarly, if acquiring the child for write, the
// constructor will wait for the parent to be acquired for write. Once the
// constructor returns, you are "in line" for the block, meaning you'll acquire
// it in the same order relative other agents as you did when acquiring the same
// parent. (Of course, readers can intermingle.)
// These constructors will _not_ yield the coroutine _if_ the parent is already
// {access}-acquired.
// Acquires an existing block for read or write access.
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
access_t access);
// Creates a new block with a specified block id, one that doesn't have a parent.
buf_lock_t(txn_t *txn,
block_id_t block_id,
alt_create_t create);
// Creates a new block with a specified block id as the child of a parent (if it's
// not just a txn_t *).
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
alt_create_t create);
// Acquires an existing block given the parent.
buf_lock_t(buf_lock_t *parent,
block_id_t block_id,
access_t access);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_parent_t parent,
alt_create_t create);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_lock_t *parent,
alt_create_t create);
~buf_lock_t();
buf_lock_t(buf_lock_t &&movee);
buf_lock_t &operator=(buf_lock_t &&movee);
void swap(buf_lock_t &other);
void reset_buf_lock();
bool empty() const {
return txn_ == NULL;
}
void snapshot_subdag();
void detach_child(block_id_t child_id);
block_id_t block_id() const {
guarantee(txn_ != NULL);
return current_page_acq()->block_id();
}
repli_timestamp_t get_recency() const;
// Usually unnecessary -- the txn has a recency value that touches the recency.
// This is used when your tree transformations (leveling, merging, adding a new
// root, etc) potentially gives yourself new subtrees with greater recency values
// than your txn's.
void manually_touch_recency(repli_timestamp_t superceding_recency);
access_t access() const {
guarantee(!empty());
return current_page_acq()->access();
}
signal_t *read_acq_signal() {
guarantee(!empty());
return current_page_acq()->read_acq_signal();
}
signal_t *write_acq_signal() {
guarantee(!empty());
return current_page_acq()->write_acq_signal();
}
void mark_deleted();
txn_t *txn() const { return txn_; }
cache_t *cache() const { return txn_->cache(); }
private:
void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
void help_construct(buf_parent_t parent, alt_create_t create);
void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);
static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id);
static void wait_for_parent(buf_parent_t parent, access_t access);
static alt_snapshot_node_t *
get_or_create_child_snapshot_node(cache_t *cache,
alt_snapshot_node_t *parent,
block_id_t child_id);
static void create_empty_child_snapshot_attachments(
cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
static void create_child_snapshot_attachments(cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
alt::current_page_acq_t *current_page_acq() const;
friend class buf_read_t; // for get_held_page_for_read, access_ref_count_.
friend class buf_write_t; // for get_held_page_for_write, access_ref_count_.
alt::page_t *get_held_page_for_read();
alt::page_t *get_held_page_for_write();
txn_t *txn_;
scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;
alt_snapshot_node_t *snapshot_node_;
// Keeps track of how many alt_buf_{read|write}_t have been created for
// this lock, for assertion/guarantee purposes.
intptr_t access_ref_count_;
DISABLE_COPYING(buf_lock_t);
};
class buf_parent_t {
public:
buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }
explicit buf_parent_t(buf_lock_t *lock)
: txn_(lock->txn()), lock_or_null_(lock) {
guarantee(lock != NULL);
guarantee(!lock->empty());
}
explicit buf_parent_t(txn_t *txn)
: txn_(txn), lock_or_null_(NULL) {
rassert(txn != NULL);
}
void detach_child(block_id_t child_id) {
if (lock_or_null_ != NULL) {
lock_or_null_->detach_child(child_id);
}
}
bool empty() const {
return txn_ == NULL;
}
txn_t *txn() const {
guarantee(!empty());
return txn_;
}
cache_t *cache() const {
guarantee(!empty());
return txn_->cache();
}
private:
friend class buf_lock_t;
txn_t *txn_;
buf_lock_t *lock_or_null_;
};
class buf_read_t {
public:
explicit buf_read_t(buf_lock_t *lock);
~buf_read_t();
const void *get_data_read(uint32_t *block_size_out);
const void *get_data_read() {
uint32_t block_size;
const void *data = get_data_read(&block_size);
guarantee(block_size == lock_->cache()->max_block_size().value());
return data;
}
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_read_t);
};
class buf_write_t {
public:
explicit buf_write_t(buf_lock_t *lock);
~buf_write_t();
void *get_data_write(uint32_t block_size);
// Equivalent to passing the max_block_size.
void *get_data_write();
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_write_t);
};
#endif // BUFFER_CACHE_ALT_ALT_HPP_
<commit_msg>Added RSI about removing block-size-less get_data_read.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_
#include <map>
#include <vector>
#include <utility>
#include "errors.hpp"
#include <boost/ptr_container/ptr_map.hpp>
#include "buffer_cache/alt/page_cache.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
class serializer_t;
class buf_lock_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;
class perfmon_collection_t;
class cache_balancer_t;
class alt_txn_throttler_t {
public:
explicit alt_txn_throttler_t(int64_t minimum_unwritten_changes_limit);
~alt_txn_throttler_t();
alt::throttler_acq_t begin_txn_or_throttle(int64_t expected_change_count);
void end_txn(alt::throttler_acq_t acq);
void inform_memory_limit_change(uint64_t memory_limit,
block_size_t max_block_size);
private:
const int64_t minimum_unwritten_changes_limit_;
new_semaphore_t unwritten_changes_semaphore_;
DISABLE_COPYING(alt_txn_throttler_t);
};
class cache_t : public home_thread_mixin_t {
public:
explicit cache_t(serializer_t *serializer,
cache_balancer_t *balancer,
perfmon_collection_t *perfmon_collection);
~cache_t();
block_size_t max_block_size() const { return page_cache_.max_block_size(); }
// RSI: Remove this.
block_size_t get_block_size() const { return max_block_size(); }
// These todos come from the mirrored cache. The real problem is that whole
// cache account / priority thing is just one ghetto hack amidst a dozen other
// throttling systems. TODO: Come up with a consistent priority scheme,
// i.e. define a "default" priority etc. TODO: As soon as we can support it, we
// might consider supporting a mem_cap paremeter.
cache_account_t create_cache_account(int priority);
private:
friend class txn_t;
friend class buf_read_t;
friend class buf_write_t;
friend class buf_lock_t;
alt_snapshot_node_t *matching_snapshot_node_or_null(
block_id_t block_id,
alt::block_version_t block_version);
void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
scoped_ptr_t<alt_cache_stats_t> stats_;
// throttler_ can cause the txn_t constructor to block
alt_txn_throttler_t throttler_;
alt::page_cache_t page_cache_;
boost::ptr_map<block_id_t, intrusive_list_t<alt_snapshot_node_t> >
snapshot_nodes_by_block_id_;
DISABLE_COPYING(cache_t);
};
class txn_t {
public:
// Constructor for read-only transactions.
txn_t(cache_conn_t *cache_conn, read_access_t read_access);
// KSI: Remove default parameter for expected_change_count.
txn_t(cache_conn_t *cache_conn,
write_durability_t durability,
repli_timestamp_t txn_timestamp,
int64_t expected_change_count = 2);
~txn_t();
cache_t *cache() { return cache_; }
alt::page_txn_t *page_txn() { return page_txn_.get(); }
access_t access() const { return access_; }
void set_account(cache_account_t *cache_account);
cache_account_t *account() { return cache_account_; }
private:
// Resets the *throttler_acq parameter.
static void inform_tracker(cache_t *cache,
alt::throttler_acq_t *throttler_acq);
// Resets the *throttler_acq parameter.
static void pulse_and_inform_tracker(cache_t *cache,
alt::throttler_acq_t *throttler_acq,
cond_t *pulsee);
void help_construct(repli_timestamp_t txn_timestamp,
int64_t expected_change_count,
cache_conn_t *cache_conn);
cache_t *const cache_;
// Initialized to cache()->page_cache_.default_cache_account(), and modified by
// set_account().
cache_account_t *cache_account_;
const access_t access_;
// Only applicable if access_ == write.
const write_durability_t durability_;
scoped_ptr_t<alt::page_txn_t> page_txn_;
DISABLE_COPYING(txn_t);
};
class buf_parent_t;
class buf_lock_t {
public:
buf_lock_t();
// buf_parent_t is a type that either points at a buf_lock_t (its parent) or
// merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
// If acquiring the child for read, the constructor will wait for the parent to
// be acquired for read. Similarly, if acquiring the child for write, the
// constructor will wait for the parent to be acquired for write. Once the
// constructor returns, you are "in line" for the block, meaning you'll acquire
// it in the same order relative other agents as you did when acquiring the same
// parent. (Of course, readers can intermingle.)
// These constructors will _not_ yield the coroutine _if_ the parent is already
// {access}-acquired.
// Acquires an existing block for read or write access.
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
access_t access);
// Creates a new block with a specified block id, one that doesn't have a parent.
buf_lock_t(txn_t *txn,
block_id_t block_id,
alt_create_t create);
// Creates a new block with a specified block id as the child of a parent (if it's
// not just a txn_t *).
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
alt_create_t create);
// Acquires an existing block given the parent.
buf_lock_t(buf_lock_t *parent,
block_id_t block_id,
access_t access);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_parent_t parent,
alt_create_t create);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_lock_t *parent,
alt_create_t create);
~buf_lock_t();
buf_lock_t(buf_lock_t &&movee);
buf_lock_t &operator=(buf_lock_t &&movee);
void swap(buf_lock_t &other);
void reset_buf_lock();
bool empty() const {
return txn_ == NULL;
}
void snapshot_subdag();
void detach_child(block_id_t child_id);
block_id_t block_id() const {
guarantee(txn_ != NULL);
return current_page_acq()->block_id();
}
repli_timestamp_t get_recency() const;
// Usually unnecessary -- the txn has a recency value that touches the recency.
// This is used when your tree transformations (leveling, merging, adding a new
// root, etc) potentially gives yourself new subtrees with greater recency values
// than your txn's.
void manually_touch_recency(repli_timestamp_t superceding_recency);
access_t access() const {
guarantee(!empty());
return current_page_acq()->access();
}
signal_t *read_acq_signal() {
guarantee(!empty());
return current_page_acq()->read_acq_signal();
}
signal_t *write_acq_signal() {
guarantee(!empty());
return current_page_acq()->write_acq_signal();
}
void mark_deleted();
txn_t *txn() const { return txn_; }
cache_t *cache() const { return txn_->cache(); }
private:
void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
void help_construct(buf_parent_t parent, alt_create_t create);
void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);
static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id);
static void wait_for_parent(buf_parent_t parent, access_t access);
static alt_snapshot_node_t *
get_or_create_child_snapshot_node(cache_t *cache,
alt_snapshot_node_t *parent,
block_id_t child_id);
static void create_empty_child_snapshot_attachments(
cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
static void create_child_snapshot_attachments(cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
alt::current_page_acq_t *current_page_acq() const;
friend class buf_read_t; // for get_held_page_for_read, access_ref_count_.
friend class buf_write_t; // for get_held_page_for_write, access_ref_count_.
alt::page_t *get_held_page_for_read();
alt::page_t *get_held_page_for_write();
txn_t *txn_;
scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;
alt_snapshot_node_t *snapshot_node_;
// Keeps track of how many alt_buf_{read|write}_t have been created for
// this lock, for assertion/guarantee purposes.
intptr_t access_ref_count_;
DISABLE_COPYING(buf_lock_t);
};
class buf_parent_t {
public:
buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }
explicit buf_parent_t(buf_lock_t *lock)
: txn_(lock->txn()), lock_or_null_(lock) {
guarantee(lock != NULL);
guarantee(!lock->empty());
}
explicit buf_parent_t(txn_t *txn)
: txn_(txn), lock_or_null_(NULL) {
rassert(txn != NULL);
}
void detach_child(block_id_t child_id) {
if (lock_or_null_ != NULL) {
lock_or_null_->detach_child(child_id);
}
}
bool empty() const {
return txn_ == NULL;
}
txn_t *txn() const {
guarantee(!empty());
return txn_;
}
cache_t *cache() const {
guarantee(!empty());
return txn_->cache();
}
private:
friend class buf_lock_t;
txn_t *txn_;
buf_lock_t *lock_or_null_;
};
class buf_read_t {
public:
explicit buf_read_t(buf_lock_t *lock);
~buf_read_t();
const void *get_data_read(uint32_t *block_size_out);
// RSI: Remove this?
const void *get_data_read() {
uint32_t block_size;
const void *data = get_data_read(&block_size);
guarantee(block_size == lock_->cache()->max_block_size().value());
return data;
}
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_read_t);
};
class buf_write_t {
public:
explicit buf_write_t(buf_lock_t *lock);
~buf_write_t();
void *get_data_write(uint32_t block_size);
// Equivalent to passing the max_block_size.
void *get_data_write();
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_write_t);
};
#endif // BUFFER_CACHE_ALT_ALT_HPP_
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 gameld
* Write: huangtao117@gmail.com
* 注意:
* JNI规定每个JNIEnv对于线程都是本地的
* 一个线程使用另一个线程的JNIEnv将引起BUG和崩溃
* 对于c++创建的线程如果需要调用JNI则必须创建JNIEnv
* 对于CallStaticObjectMethod这类调用来说,异常检测是必须的。
*/
#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <android/log.h>
#include "com_gameld_core_libqp.h"
#include "qipai.h"
/* comment this line to release */
#define TAO_DEBUG 1
const int CORE_PARAM_LOG = 1;
/*
* c++ thread cann't FindClass
* because c++ thread != jvm thread
* so must cached jobject
*/
static JavaVM* g_jvm = NULL;
static JNIEnv* g_envJava = NULL;
static JNIEnv* g_envRead = NULL;
static JNIEnv* g_envWrite = NULL;
static jclass g_myjni = NULL;
static gp_t g_gp;
int Java_com_gameld_core_libqp_gpInit(JNIEnv *, jclass, jint type)
{
gp_init(&g_gp, type, GP_MODE_CLIENT, 2);
return 1;
}
void Java_com_gameld_core_libqp_gpClear(JNIEnv *, jclass)
{
}
int Java_com_gameld_core_libqp_gpGetState(JNIEnv *, jclass)
{
return g_gp.game_state;
}
void Java_com_gameld_core_libqp_gpSetState(JNIEnv *, jclass, jint state)
{
g_gp.game_state = state;
}
void Java_com_gameld_core_libqp_gpStart(JNIEnv *env, jclass,
jbyteArray jarray0, jbyteArray jarray1, jint fno, jint pno, jbyteArray jarr_played)
{
card_t* card;
g_gp.player_num = 2;
gp_start(&g_gp);
g_gp.curr_player_no = fno;
g_gp.first_player_no = fno;
jbyte* p = env->GetByteArrayElements(jarray0, NULL);
jsize size = env->GetArrayLength(jarray0);
card = g_gp.players[0].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray0, p, 0);
gp_sort(g_gp.players[0].cards, GP_MAX_CARDS);
p = env->GetByteArrayElements(jarray1, NULL);
size = env->GetArrayLength(jarray1);
card = g_gp.players[1].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray1, p, 0);
gp_sort(g_gp.players[1].cards, GP_MAX_CARDS);
if (pno >= 0 && pno < g_gp.player_num) {
p = env->GetByteArrayElements(jarr_played, NULL);
size = env->GetArrayLength(jarr_played);
card = g_gp.players[pno].cards_played;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarr_played, p, 0);
if (size > 0) {
memcpy(g_gp.last_hand, g_gp.players[pno].cards_played,
sizeof(card_t) * GP_MAX_CARDS);
gp_handtype(&g_gp, g_gp.players[pno].cards_played, GP_MAX_CARDS,
&g_gp.last_hand_type);
g_gp.largest_player_no = pno;
}
}
#ifdef TAO_DEBUG
__android_log_print(ANDROID_LOG_INFO, "qipai", "cards0:%d,cards1:%d",
cards_num(g_gp.players[0].cards, GP_MAX_CARDS),
cards_num(g_gp.players[1].cards, GP_MAX_CARDS));
//cards_to_string(g_gp.players[my_seat].cards, GP_MAX_CARDS));
#endif
}
void Java_com_gameld_core_libqp_gpSetCards(JNIEnv *env, jclass,
jint no, jbyteArray jarray)
{
card_t* card;
if (no >= g_gp.player_num)
return;
memset(g_gp.players[no].cards, 0, sizeof(card_t) * GP_MAX_PLAYER);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
card = g_gp.players[no].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
gp_sort(g_gp.players[no].cards, GP_MAX_CARDS);
#ifdef TAO_DEBUG
__android_log_print(ANDROID_LOG_INFO, "qipai", "gpSetCards:%s",
cards_to_string(g_gp.players[no].cards, GP_MAX_CARDS));
#endif
}
void Java_com_gameld_core_libqp_gpSetPlayedCards(JNIEnv *env, jclass,
jint no, jbyteArray jarray)
{
card_t* card;
if (no >= g_gp.player_num)
return;
memset(g_gp.last_hand, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
card = g_gp.players[no].cards_played;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
if (size > 0) {
memcpy(g_gp.last_hand, g_gp.players[no].cards_played,
sizeof(card_t) * GP_MAX_CARDS);
gp_handtype(&g_gp, g_gp.players[no].cards_played, GP_MAX_CARDS,
&g_gp.last_hand_type);
g_gp.largest_player_no = no;
}
}
int Java_com_gameld_core_libqp_gpCanPlay(JNIEnv *env, jclass,jbyteArray jarray)
{
int ret,n;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
ret = gp_canplay(&g_gp, cards, GP_MAX_CARDS);
#ifdef TAO_DEBUG
char dbg_str[512];
strcpy(dbg_str, cards_to_string(cards, GP_MAX_CARDS));
__android_log_print(ANDROID_LOG_INFO, "qipai", "play cards:%s", dbg_str);
__android_log_print(ANDROID_LOG_INFO, "qipai", "last type:%d,num=%d",
g_gp.last_hand_type.type, g_gp.last_hand_type.num);
#endif
return ret;
}
void Java_com_gameld_core_libqp_gpPlay(JNIEnv *env, jclass,jbyteArray jarray)
{
int n;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
gp_play(&g_gp, g_gp.curr_player_no, cards, GP_MAX_CARDS);
}
void Java_com_gameld_core_libqp_gpPass(JNIEnv *env, jclass)
{
gp_pass(&g_gp, g_gp.curr_player_no);
}
jbyteArray Java_com_gameld_core_libqp_gpHint(JNIEnv *env, jclass, jint flag)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
card_t cards[GP_MAX_CARDS];
n = gp_hint(&g_gp, cards, GP_MAX_CARDS, flag);
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = cards[i].id;
}
}
jbyteArray array = env->NewByteArray(GP_MAX_CARDS);
env->SetByteArrayRegion(array, 0, GP_MAX_CARDS, (jbyte*)data);
return array;
}
int Java_com_gameld_core_libqp_gpGetCurrentNo(JNIEnv *, jclass)
{
return g_gp.curr_player_no;
}
int Java_com_gameld_core_libqp_gpGetHandType(JNIEnv *env, jclass, jbyteArray jarray)
{
int n;
hand_type htype;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
gp_handtype(&g_gp, cards, GP_MAX_CARDS, &htype);
return htype.type;
}
int Java_com_gameld_core_libqp_gpCardNum(JNIEnv *env, jclass, int no)
{
if (no >= g_gp.player_num) {
return 0;
}
return cards_num(g_gp.players[no].cards, GP_MAX_CARDS);
}
int Java_com_gameld_core_libqp_gpGetCard(JNIEnv *env, jclass, int no, int index)
{
if (no >= g_gp.player_num) {
return 0;
}
if (index >= GP_MAX_CARDS) {
return 0;
}
return card_to_n55(g_gp.players[no].cards + index);
}
int Java_com_gameld_core_libqp_gpCardPlayedNum(JNIEnv *env, jclass, int no)
{
if (no >= g_gp.player_num) {
return 0;
}
return cards_num(g_gp.players[no].cards_played, GP_MAX_CARDS);
}
int Java_com_gameld_core_libqp_gpGetCardPlayed(JNIEnv *env, jclass, int no, int index)
{
if (no >= g_gp.player_num) {
return 0;
}
if (index >= GP_MAX_CARDS) {
return 0;
}
return card_to_n55(g_gp.players[no].cards_played + index);
}
jbyteArray Java_com_gameld_core_libqp_gpGetCards(JNIEnv *env, jclass, int no)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
if (no >= g_gp.player_num) {
n = 0;
} else {
n = cards_num(g_gp.players[no].cards, GP_MAX_CARDS);
}
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = card_to_n55(g_gp.players[no].cards + i);
}
}
jbyteArray array = env->NewByteArray(n);
if (n > 0)
env->SetByteArrayRegion(array, 0, n, (jbyte*)data);
return array;
}
jbyteArray Java_com_gameld_core_libqp_gpGetCardsPlayed(JNIEnv *env, jclass, int no)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
if (no >= g_gp.player_num) {
n = 0;
} else {
n = cards_num(g_gp.players[no].cards_played, GP_MAX_CARDS);
}
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = card_to_n55(g_gp.players[no].cards_played + i);
}
}
jbyteArray array = env->NewByteArray(n);
if (n > 0)
env->SetByteArrayRegion(array, 0, n, (jbyte*)data);
return array;
}
<commit_msg>fixed bug<commit_after>/*
* Copyright (C) 2014 gameld
* Write: huangtao117@gmail.com
* 注意:
* JNI规定每个JNIEnv对于线程都是本地的
* 一个线程使用另一个线程的JNIEnv将引起BUG和崩溃
* 对于c++创建的线程如果需要调用JNI则必须创建JNIEnv
* 对于CallStaticObjectMethod这类调用来说,异常检测是必须的。
*/
#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <android/log.h>
#include "com_gameld_core_libqp.h"
#include "qipai.h"
/* comment this line to release */
#define TAO_DEBUG 1
const int CORE_PARAM_LOG = 1;
/*
* c++ thread cann't FindClass
* because c++ thread != jvm thread
* so must cached jobject
*/
static JavaVM* g_jvm = NULL;
static JNIEnv* g_envJava = NULL;
static JNIEnv* g_envRead = NULL;
static JNIEnv* g_envWrite = NULL;
static jclass g_myjni = NULL;
static gp_t g_gp;
int Java_com_gameld_core_libqp_gpInit(JNIEnv *, jclass, jint type)
{
gp_init(&g_gp, type, GP_MODE_CLIENT, 2);
return 1;
}
void Java_com_gameld_core_libqp_gpClear(JNIEnv *, jclass)
{
}
int Java_com_gameld_core_libqp_gpGetState(JNIEnv *, jclass)
{
return g_gp.game_state;
}
void Java_com_gameld_core_libqp_gpSetState(JNIEnv *, jclass, jint state)
{
g_gp.game_state = state;
}
void Java_com_gameld_core_libqp_gpStart(JNIEnv *env, jclass,
jbyteArray jarray0, jbyteArray jarray1, jint fno, jint pno, jbyteArray jarr_played)
{
card_t* card;
g_gp.player_num = 2;
gp_start(&g_gp);
g_gp.curr_player_no = fno;
g_gp.first_player_no = fno;
jbyte* p = env->GetByteArrayElements(jarray0, NULL);
jsize size = env->GetArrayLength(jarray0);
card = g_gp.players[0].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray0, p, 0);
gp_sort(g_gp.players[0].cards, GP_MAX_CARDS);
p = env->GetByteArrayElements(jarray1, NULL);
size = env->GetArrayLength(jarray1);
card = g_gp.players[1].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray1, p, 0);
gp_sort(g_gp.players[1].cards, GP_MAX_CARDS);
if (pno >= 0 && pno < g_gp.player_num) {
p = env->GetByteArrayElements(jarr_played, NULL);
size = env->GetArrayLength(jarr_played);
card = g_gp.players[pno].cards_played;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarr_played, p, 0);
if (size > 0) {
memcpy(g_gp.last_hand, g_gp.players[pno].cards_played,
sizeof(card_t) * GP_MAX_CARDS);
gp_handtype(&g_gp, g_gp.players[pno].cards_played, GP_MAX_CARDS,
&g_gp.last_hand_type);
g_gp.largest_player_no = pno;
}
}
#ifdef TAO_DEBUG
__android_log_print(ANDROID_LOG_INFO, "qipai", "cards0:%d,cards1:%d",
cards_num(g_gp.players[0].cards, GP_MAX_CARDS),
cards_num(g_gp.players[1].cards, GP_MAX_CARDS));
//cards_to_string(g_gp.players[my_seat].cards, GP_MAX_CARDS));
#endif
}
void Java_com_gameld_core_libqp_gpSetCards(JNIEnv *env, jclass,
jint no, jbyteArray jarray)
{
card_t* card;
if (no >= g_gp.player_num)
return;
memset(g_gp.players[no].cards, 0, sizeof(card_t) * GP_MAX_PLAYER);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
card = g_gp.players[no].cards;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
gp_sort(g_gp.players[no].cards, GP_MAX_CARDS);
#ifdef TAO_DEBUG
__android_log_print(ANDROID_LOG_INFO, "qipai", "gpSetCards:%s",
cards_to_string(g_gp.players[no].cards, GP_MAX_CARDS));
#endif
}
void Java_com_gameld_core_libqp_gpSetPlayedCards(JNIEnv *env, jclass,
jint no, jbyteArray jarray)
{
card_t* card;
if (no >= g_gp.player_num)
return;
memset(g_gp.last_hand, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
card = g_gp.players[no].cards_played;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], card);
card++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
if (size > 0) {
memcpy(g_gp.last_hand, g_gp.players[no].cards_played,
sizeof(card_t) * GP_MAX_CARDS);
gp_handtype(&g_gp, g_gp.players[no].cards_played, GP_MAX_CARDS,
&g_gp.last_hand_type);
g_gp.largest_player_no = no;
}
}
int Java_com_gameld_core_libqp_gpCanPlay(JNIEnv *env, jclass,jbyteArray jarray)
{
int ret,n;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
ret = gp_canplay(&g_gp, cards, GP_MAX_CARDS);
#ifdef TAO_DEBUG
char dbg_str[512];
strcpy(dbg_str, cards_to_string(cards, GP_MAX_CARDS));
__android_log_print(ANDROID_LOG_INFO, "qipai", "play cards:%s", dbg_str);
__android_log_print(ANDROID_LOG_INFO, "qipai", "last type:%d,num=%d",
g_gp.last_hand_type.type, g_gp.last_hand_type.num);
#endif
return ret;
}
void Java_com_gameld_core_libqp_gpPlay(JNIEnv *env, jclass,jbyteArray jarray)
{
int n;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
n = gp_play(&g_gp, g_gp.curr_player_no, cards, GP_MAX_CARDS);
#ifdef TAO_DEBUG
char dbg_str[512];
strcpy(dbg_str, cards_to_string(cards, GP_MAX_CARDS));
__android_log_print(ANDROID_LOG_INFO, "qipai", "play cards:%s", dbg_str);
__android_log_print(ANDROID_LOG_INFO, "qipai", "gp_play return %d",
n);
#endif
}
void Java_com_gameld_core_libqp_gpPass(JNIEnv *env, jclass)
{
gp_pass(&g_gp, g_gp.curr_player_no);
}
jbyteArray Java_com_gameld_core_libqp_gpHint(JNIEnv *env, jclass, jint flag)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
card_t cards[GP_MAX_CARDS];
n = gp_hint(&g_gp, cards, GP_MAX_CARDS, flag);
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = cards[i].id;
}
}
jbyteArray array = env->NewByteArray(GP_MAX_CARDS);
env->SetByteArrayRegion(array, 0, GP_MAX_CARDS, (jbyte*)data);
return array;
}
int Java_com_gameld_core_libqp_gpGetCurrentNo(JNIEnv *, jclass)
{
return g_gp.curr_player_no;
}
int Java_com_gameld_core_libqp_gpGetHandType(JNIEnv *env, jclass, jbyteArray jarray)
{
int n;
hand_type htype;
card_t cards[GP_MAX_CARDS];
memset(cards, 0, sizeof(card_t) * GP_MAX_CARDS);
jbyte* p = env->GetByteArrayElements(jarray, NULL);
jsize size = env->GetArrayLength(jarray);
n = 0;
for (int i = 0; i < size && i < GP_MAX_CARDS; i++) {
if (p[i] > 0) {
n55_to_card(p[i], cards + n);
n++;
}
}
env->ReleaseByteArrayElements(jarray, p, 0);
gp_handtype(&g_gp, cards, GP_MAX_CARDS, &htype);
return htype.type;
}
int Java_com_gameld_core_libqp_gpCardNum(JNIEnv *env, jclass, int no)
{
if (no >= g_gp.player_num) {
return 0;
}
return cards_num(g_gp.players[no].cards, GP_MAX_CARDS);
}
int Java_com_gameld_core_libqp_gpGetCard(JNIEnv *env, jclass, int no, int index)
{
if (no >= g_gp.player_num) {
return 0;
}
if (index >= GP_MAX_CARDS) {
return 0;
}
return card_to_n55(g_gp.players[no].cards + index);
}
int Java_com_gameld_core_libqp_gpCardPlayedNum(JNIEnv *env, jclass, int no)
{
if (no >= g_gp.player_num) {
return 0;
}
return cards_num(g_gp.players[no].cards_played, GP_MAX_CARDS);
}
int Java_com_gameld_core_libqp_gpGetCardPlayed(JNIEnv *env, jclass, int no, int index)
{
if (no >= g_gp.player_num) {
return 0;
}
if (index >= GP_MAX_CARDS) {
return 0;
}
return card_to_n55(g_gp.players[no].cards_played + index);
}
jbyteArray Java_com_gameld_core_libqp_gpGetCards(JNIEnv *env, jclass, int no)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
if (no >= g_gp.player_num) {
n = 0;
} else {
n = cards_num(g_gp.players[no].cards, GP_MAX_CARDS);
}
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = card_to_n55(g_gp.players[no].cards + i);
}
}
jbyteArray array = env->NewByteArray(n);
if (n > 0)
env->SetByteArrayRegion(array, 0, n, (jbyte*)data);
return array;
}
jbyteArray Java_com_gameld_core_libqp_gpGetCardsPlayed(JNIEnv *env, jclass, int no)
{
int i,n;
unsigned char data[GP_MAX_CARDS];
if (no >= g_gp.player_num) {
n = 0;
} else {
n = cards_num(g_gp.players[no].cards_played, GP_MAX_CARDS);
}
memset(data, 0, GP_MAX_CARDS);
if (n > 0) {
for (i = 0; i < n; ++i) {
data[i] = card_to_n55(g_gp.players[no].cards_played + i);
}
}
jbyteArray array = env->NewByteArray(n);
if (n > 0)
env->SetByteArrayRegion(array, 0, n, (jbyte*)data);
return array;
}
<|endoftext|>
|
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include "TFile.h"
#include "TTree.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODCluster.h"
#endif
void ReadAOD(const char *fileName = "AliAOD.root") {
// open input file and get the TTree
TFile inFile(fileName, "READ");
TTree *aodTree = (TTree*)inFile.Get("AOD");
AliAODEvent *aod = (AliAODEvent*)aodTree->GetUserInfo()->FindObject("AliAODEvent");
TIter next(aod->GetList());
TObject *el;
while((el=(TNamed*)next()))
aodTree->SetBranchAddress(el->GetName(),aod->GetList()->GetObjectRef(el));
// loop over events
Int_t nEvents = aodTree->GetEntries();
for (Int_t nEv = 0; nEv < nEvents; nEv++) {
cout << "Event: " << nEv+1 << "/" << nEvents << endl;
// read events
aodTree->GetEvent(nEv);
// set pointers
aod->GetStdContent();
//print event info
aod->GetHeader()->Print();
// loop over tracks
Int_t nTracks = aod->GetNTracks();
for (Int_t nTr = 0; nTr < nTracks; nTr++) {
AliAODTrack *tr = aod->GetTrack(nTr);
// print track info
cout << nTr+1 << "/" << nTracks << ": track pt: " << tr->Pt();
if (tr->GetProdVertex()) {
cout << ", vertex z of this track: " << tr->GetProdVertex()->GetZ();
}
cout << endl;
}
// loop over vertices
Int_t nVtxs = aod->GetNVertices();
for (Int_t nVtx = 0; nVtx < nVtxs; nVtx++) {
// print track info
cout << nVtx+1 << "/" << nVtxs << ": vertex z position: " << aod->GetVertex(nVtx)->GetZ() << endl;
}
}
return;
}
<commit_msg>Read AOD according to new functionality (Markus)<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include "TFile.h"
#include "TTree.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODCluster.h"
#endif
void ReadAOD(const char *fileName = "AliAOD.root") {
// open input file and get the TTree
TFile inFile(fileName, "READ");
TTree *aodTree = (TTree*)inFile.Get("aodTree");
AliAODEvent *ev = new AliAODEvent();
ev->ReadFromTree(aodTree);
// loop over events
Int_t nEvents = aodTree->GetEntries();
for (Int_t nEv = 0; nEv < nEvents; nEv++) {
cout << "Event: " << nEv+1 << "/" << nEvents << endl;
// read events
aodTree->GetEvent(nEv);
//print event info
ev->GetHeader()->Print();
// loop over tracks
Int_t nTracks = ev->GetNTracks();
for (Int_t nTr = 0; nTr < nTracks; nTr++) {
AliAODTrack *tr = ev->GetTrack(nTr);
// print track info
cout << nTr+1 << "/" << nTracks << ": track pt: " << tr->Pt();
if (tr->GetProdVertex()) {
cout << ", vertex z of this track: " << tr->GetProdVertex()->GetZ();
}
cout << endl;
}
// loop over vertices
Int_t nVtxs = ev->GetNVertices();
for (Int_t nVtx = 0; nVtx < nVtxs; nVtx++) {
// print track info
cout << nVtx+1 << "/" << nVtxs << ": vertex z position: " << ev->GetVertex(nVtx)->GetZ() << endl;
}
}
return;
}
<|endoftext|>
|
<commit_before>// infoware - C++ System information Library
//
// Written in 2016-2019 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#ifdef _WIN32
#include "infoware/cpu.hpp"
#include <bitset>
#include <vector>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> cpuinfo_buffer() {
std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> buffer;
DWORD byte_count = 0;
GetLogicalProcessorInformation(nullptr, &byte_count);
buffer.resize(byte_count / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
GetLogicalProcessorInformation(buffer.data(), &byte_count);
return buffer;
}
// C++ified http://stackoverflow.com/a/28894219/2851815
iware::cpu::quantities_t iware::cpu::quantities() {
iware::cpu::quantities_t ret{};
for(auto&& info : cpuinfo_buffer())
switch(info.Relationship) {
case RelationProcessorCore:
++ret.physical;
// A hyperthreaded core supplies more than one logical processor.
ret.logical += static_cast<std::uint32_t>(std::bitset<sizeof(ULONG_PTR) * 8>(info.ProcessorMask).count());
break;
case RelationProcessorPackage:
// Logical processors share a physical package.
++ret.packages;
break;
default:
break;
}
return ret;
}
iware::cpu::cache_t iware::cpu::cache(unsigned int level) {
for(auto&& info : cpuinfo_buffer())
if(info.Relationship == RelationCache)
// Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache.
if(info.Cache.Level == level) {
iware::cpu::cache_type_t type{};
switch(info.Cache.Type) {
case CacheUnified:
type = iware::cpu::cache_type_t::unified;
break;
case CacheInstruction:
type = iware::cpu::cache_type_t::instruction;
break;
case CacheData:
type = iware::cpu::cache_type_t::data;
break;
case CacheTrace:
type = iware::cpu::cache_type_t::trace;
break;
}
return {info.Cache.Size, info.Cache.LineSize, info.Cache.Associativity, type};
}
return {};
}
#endif
<commit_msg>Fix bitset constructor used in cpu::quantities() on Windows<commit_after>// infoware - C++ System information Library
//
// Written in 2016-2019 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#ifdef _WIN32
#include "infoware/cpu.hpp"
#include <bitset>
#include <vector>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> cpuinfo_buffer() {
std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> buffer;
DWORD byte_count = 0;
GetLogicalProcessorInformation(nullptr, &byte_count);
buffer.resize(byte_count / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
GetLogicalProcessorInformation(buffer.data(), &byte_count);
return buffer;
}
// C++ified http://stackoverflow.com/a/28894219/2851815
iware::cpu::quantities_t iware::cpu::quantities() {
static_assert(sizeof(ULONG_PTR) == sizeof(std::size_t), "size_t must be as wide as a pointer");
iware::cpu::quantities_t ret{};
for(auto&& info : cpuinfo_buffer())
switch(info.Relationship) {
case RelationProcessorCore:
++ret.physical;
// A hyperthreaded core supplies more than one logical processor.
ret.logical += static_cast<std::uint32_t>(std::bitset<sizeof(ULONG_PTR) * 8>(reinterpret_cast<std::size_t>(info.ProcessorMask)).count());
break;
case RelationProcessorPackage:
// Logical processors share a physical package.
++ret.packages;
break;
default:
break;
}
return ret;
}
iware::cpu::cache_t iware::cpu::cache(unsigned int level) {
for(auto&& info : cpuinfo_buffer())
if(info.Relationship == RelationCache)
// Cache data is in ptr->Cache, one CACHE_DESCRIPTOR structure for each cache.
if(info.Cache.Level == level) {
iware::cpu::cache_type_t type{};
switch(info.Cache.Type) {
case CacheUnified:
type = iware::cpu::cache_type_t::unified;
break;
case CacheInstruction:
type = iware::cpu::cache_type_t::instruction;
break;
case CacheData:
type = iware::cpu::cache_type_t::data;
break;
case CacheTrace:
type = iware::cpu::cache_type_t::trace;
break;
}
return {info.Cache.Size, info.Cache.LineSize, info.Cache.Associativity, type};
}
return {};
}
#endif
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Geometry.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/RigidTransform.h"
using SurgSim::DataStructures::TriangleMesh;
using SurgSim::DataStructures::TriangleMeshBase;
using SurgSim::Math::MeshShape;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Collision
{
TriangleMeshTriangleMeshDcdContact::TriangleMeshTriangleMeshDcdContact()
{
}
std::pair<int,int> TriangleMeshTriangleMeshDcdContact::getShapeTypes()
{
return std::pair<int,int>(SurgSim::Math::SHAPE_TYPE_MESH, SurgSim::Math::SHAPE_TYPE_MESH);
}
static void assertIsCoplanar(const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2,
const Vector3d& point)
{
SURGSIM_ASSERT(abs((triangle2 - triangle0).dot((triangle1 - triangle0).cross(point - triangle2)))
< SurgSim::Math::Geometry::ScalarEpsilon)
<< "Coplanarity failed with: "
<< "t0 " << triangle0 << ", t1 " << triangle1 << ", t2 " << triangle2 << ", pt " << point;
}
static void assertIsConstrained(const Vector3d& point,
const Vector3d& triangle0,
const Vector3d& triangle1,
const Vector3d& triangle2,
const Vector3d& normal)
{
Vector3d barycentricCoordinate;
SurgSim::Math::barycentricCoordinates(point, triangle0, triangle1, triangle2, normal, &barycentricCoordinate);
SURGSIM_ASSERT(barycentricCoordinate.x() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.x() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0 << ", t1 " << triangle1 << ", t2 " << triangle2 << ", n " << normal << ", pt " << point;
SURGSIM_ASSERT(barycentricCoordinate.y() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.y() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0 << ", t1 " << triangle1 << ", t2 " << triangle2 << ", n " << normal << ", pt " << point;
SURGSIM_ASSERT(barycentricCoordinate.z() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.z() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0 << ", t1 " << triangle1 << ", t2 " << triangle2 << ", n " << normal << ", pt " << point;
}
static void assertIsCorrectNormalAndDepth(const Vector3d& normal,
double penetrationDepth,
Vector3d triangleA0,
Vector3d triangleA1,
Vector3d triangleA2,
Vector3d triangleB0,
Vector3d triangleB1,
Vector3d triangleB2)
{
Vector3d correction = normal * (0.5 * (penetrationDepth + 2.0 * SurgSim::Math::Geometry::DistanceEpsilon));
triangleA0 += correction;
triangleA1 += correction;
triangleA2 += correction;
triangleB0 += correction;
triangleB1 += correction;
triangleB2 += correction;
Vector3d temp1, temp2;
double expectedDistance = SurgSim::Math::distanceTriangleTriangle(triangleA0, triangleA1, triangleA2,
triangleB0, triangleB1, triangleB2,
&temp1, &temp2);
SURGSIM_ASSERT(expectedDistance >= 0.0)
<< "Normal and depth failed with: "
<< "n " << normal << ", d " << penetrationDepth
<< ", a0 " << triangleA0 << ", a1 " << triangleA1 << ", a2 " << triangleA2
<< ", b0 " << triangleB0 << ", b1 " << triangleB1 << ", b2 " << triangleB2;
SURGSIM_ASSERT(expectedDistance <= 2.1 * SurgSim::Math::Geometry::DistanceEpsilon)
<< "Normal and depth failed with: "
<< "n " << normal << ", d " << penetrationDepth
<< ", a0 " << triangleA0 << ", a1 " << triangleA1 << ", a2 " << triangleA2
<< ", b0 " << triangleB0 << ", b1 " << triangleB1 << ", b2 " << triangleB2;
}
void TriangleMeshTriangleMeshDcdContact::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
std::shared_ptr<Representation> representationMeshA = pair->getFirst();
std::shared_ptr<Representation> representationMeshB = pair->getSecond();
std::shared_ptr<TriangleMesh> collisionMeshA =
std::static_pointer_cast<MeshShape>(representationMeshA->getShape())->getMesh();
std::shared_ptr<TriangleMesh> collisionMeshB =
std::static_pointer_cast<MeshShape>(representationMeshB->getShape())->getMesh();
RigidTransform3d globalCoordinatesFromMeshACoordinates = representationMeshA->getPose();
RigidTransform3d globalCoordinatesFromMeshBCoordinates = representationMeshB->getPose();
RigidTransform3d meshBCoordinatesFromGlobalCoordinates = globalCoordinatesFromMeshBCoordinates.inverse();
RigidTransform3d meshBCoordinatesFromMeshACoordinates = meshBCoordinatesFromGlobalCoordinates
* globalCoordinatesFromMeshACoordinates;
double depth = 0.0;
Vector3d normal;
Vector3d penetrationPointA, penetrationPointB;
for (size_t i = 0; i < collisionMeshA->getNumTriangles(); ++i)
{
// The triangleA vertices.
const Vector3d& triangleA0InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[0]);
const Vector3d& triangleA1InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[1]);
const Vector3d& triangleA2InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[2]);
const Vector3d& normalAInLocalB = meshBCoordinatesFromMeshACoordinates.linear() * collisionMeshA->getNormal(i);
if (normalAInLocalB.isZero())
{
continue;
}
for (size_t j = 0; j < collisionMeshB->getNumTriangles(); ++j)
{
const Vector3d& normalB = collisionMeshB->getNormal(j);
if (normalB.isZero())
{
continue;
}
// The triangleB vertices.
const Vector3d& triangleB0 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[0]);
const Vector3d& triangleB1 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[1]);
const Vector3d& triangleB2 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[2]);
// Check if the triangles intersect.
if (SurgSim::Math::calculateContactTriangleTriangle(triangleA0InLocalB, triangleA1InLocalB,
triangleA2InLocalB,
triangleB0, triangleB1, triangleB2,
normalAInLocalB, normalB, &depth,
&penetrationPointA, &penetrationPointB,
&normal))
{
#ifdef SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT
assertIsCoplanar(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, penetrationPointA);
assertIsCoplanar(triangleB0, triangleB1, triangleB2, penetrationPointB);
assertIsConstrained(
penetrationPointA, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, normalAInLocalB);
assertIsConstrained(penetrationPointB, triangleB0, triangleB1, triangleB2, normalB);
assertIsCorrectNormalAndDepth(normal, depth, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB,
triangleB0, triangleB1, triangleB2);
#endif
// Create the contact.
std::pair<Location, Location> penetrationPoints;
penetrationPoints.first.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates
* penetrationPointA);
penetrationPoints.second.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates
* penetrationPointB);
pair->addContact(std::abs(depth), globalCoordinatesFromMeshBCoordinates.linear() * normal,
penetrationPoints);
}
}
}
}
}; // namespace Collision
}; // namespace SurgSim
<commit_msg>TriangleMeshTriangleMeshDcdContact, fix assertIsCorrectNormalAndDepth<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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.
#include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Geometry.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/RigidTransform.h"
using SurgSim::DataStructures::TriangleMesh;
using SurgSim::DataStructures::TriangleMeshBase;
using SurgSim::Math::MeshShape;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace Collision
{
TriangleMeshTriangleMeshDcdContact::TriangleMeshTriangleMeshDcdContact()
{
}
std::pair<int,int> TriangleMeshTriangleMeshDcdContact::getShapeTypes()
{
return std::pair<int,int>(SurgSim::Math::SHAPE_TYPE_MESH, SurgSim::Math::SHAPE_TYPE_MESH);
}
static void assertIsCoplanar(const Vector3d& triangle0, const Vector3d& triangle1, const Vector3d& triangle2,
const Vector3d& point)
{
SURGSIM_ASSERT(abs((triangle2 - triangle0).dot((triangle1 - triangle0).cross(point - triangle2)))
< SurgSim::Math::Geometry::ScalarEpsilon)
<< "Coplanarity failed with: "
<< "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose()
<< ", pt " << point.transpose();
}
static void assertIsConstrained(const Vector3d& point,
const Vector3d& triangle0,
const Vector3d& triangle1,
const Vector3d& triangle2,
const Vector3d& normal)
{
Vector3d barycentricCoordinate;
SurgSim::Math::barycentricCoordinates(point, triangle0, triangle1, triangle2, normal, &barycentricCoordinate);
SURGSIM_ASSERT(barycentricCoordinate.x() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.x() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose()
<< ", n " << normal.transpose() << ", pt " << point.transpose();
SURGSIM_ASSERT(barycentricCoordinate.y() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.y() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose()
<< ", n " << normal.transpose() << ", pt " << point.transpose();
SURGSIM_ASSERT(barycentricCoordinate.z() >= -SurgSim::Math::Geometry::ScalarEpsilon
&& barycentricCoordinate.z() <= 1.0 + SurgSim::Math::Geometry::ScalarEpsilon)
<< "Constrained failed with: "
<< "t0 " << triangle0.transpose() << ", t1 " << triangle1.transpose() << ", t2 " << triangle2.transpose()
<< ", n " << normal.transpose() << ", pt " << point.transpose();
}
static void assertIsCorrectNormalAndDepth(const Vector3d& normal,
double penetrationDepth,
const Vector3d& triangleA0,
const Vector3d& triangleA1,
const Vector3d& triangleA2,
const Vector3d& triangleB0,
const Vector3d& triangleB1,
const Vector3d& triangleB2)
{
Vector3d correction = normal * (penetrationDepth + 2 * SurgSim::Math::Geometry::DistanceEpsilon);
Vector3d temp1, temp2;
double expectedDistance = SurgSim::Math::distanceTriangleTriangle(
(Vector3d)(triangleA0 + correction), (Vector3d)(triangleA1 + correction), (Vector3d)(triangleA2 + correction),
triangleB0, triangleB1, triangleB2,
&temp1, &temp2);
SURGSIM_ASSERT(expectedDistance > 0.0)
<< "Normal and depth failed with: "
<< "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth
<< ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose()
<< ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose();
SURGSIM_ASSERT(expectedDistance <= 2.1 * SurgSim::Math::Geometry::DistanceEpsilon)
<< "Normal and depth failed with: "
<< "calcD " << expectedDistance << ", n " << normal.transpose() << ", d " << penetrationDepth
<< ", a0 " << triangleA0.transpose() << ", a1 " << triangleA1.transpose() << ", a2 " << triangleA2.transpose()
<< ", b0 " << triangleB0.transpose() << ", b1 " << triangleB1.transpose() << ", b2 " << triangleB2.transpose();
}
void TriangleMeshTriangleMeshDcdContact::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
std::shared_ptr<Representation> representationMeshA = pair->getFirst();
std::shared_ptr<Representation> representationMeshB = pair->getSecond();
std::shared_ptr<TriangleMesh> collisionMeshA =
std::static_pointer_cast<MeshShape>(representationMeshA->getShape())->getMesh();
std::shared_ptr<TriangleMesh> collisionMeshB =
std::static_pointer_cast<MeshShape>(representationMeshB->getShape())->getMesh();
RigidTransform3d globalCoordinatesFromMeshACoordinates = representationMeshA->getPose();
RigidTransform3d globalCoordinatesFromMeshBCoordinates = representationMeshB->getPose();
RigidTransform3d meshBCoordinatesFromGlobalCoordinates = globalCoordinatesFromMeshBCoordinates.inverse();
RigidTransform3d meshBCoordinatesFromMeshACoordinates = meshBCoordinatesFromGlobalCoordinates
* globalCoordinatesFromMeshACoordinates;
double depth = 0.0;
Vector3d normal;
Vector3d penetrationPointA, penetrationPointB;
for (size_t i = 0; i < collisionMeshA->getNumTriangles(); ++i)
{
// The triangleA vertices.
const Vector3d& triangleA0InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[0]);
const Vector3d& triangleA1InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[1]);
const Vector3d& triangleA2InLocalB = meshBCoordinatesFromMeshACoordinates *
collisionMeshA->getVertexPosition(collisionMeshA->getTriangle(i).verticesId[2]);
const Vector3d& normalAInLocalB = meshBCoordinatesFromMeshACoordinates.linear() * collisionMeshA->getNormal(i);
if (normalAInLocalB.isZero())
{
continue;
}
for (size_t j = 0; j < collisionMeshB->getNumTriangles(); ++j)
{
const Vector3d& normalB = collisionMeshB->getNormal(j);
if (normalB.isZero())
{
continue;
}
// The triangleB vertices.
const Vector3d& triangleB0 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[0]);
const Vector3d& triangleB1 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[1]);
const Vector3d& triangleB2 =
collisionMeshB->getVertexPosition(collisionMeshB->getTriangle(j).verticesId[2]);
// Check if the triangles intersect.
if (SurgSim::Math::calculateContactTriangleTriangle(triangleA0InLocalB, triangleA1InLocalB,
triangleA2InLocalB,
triangleB0, triangleB1, triangleB2,
normalAInLocalB, normalB, &depth,
&penetrationPointA, &penetrationPointB,
&normal))
{
#ifdef SURGSIM_DEBUG_TRIANGLETRIANGLECONTACT
assertIsCoplanar(triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, penetrationPointA);
assertIsCoplanar(triangleB0, triangleB1, triangleB2, penetrationPointB);
assertIsConstrained(
penetrationPointA, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB, normalAInLocalB);
assertIsConstrained(penetrationPointB, triangleB0, triangleB1, triangleB2, normalB);
assertIsCorrectNormalAndDepth(normal, depth, triangleA0InLocalB, triangleA1InLocalB, triangleA2InLocalB,
triangleB0, triangleB1, triangleB2);
#endif
// Create the contact.
std::pair<Location, Location> penetrationPoints;
penetrationPoints.first.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates
* penetrationPointA);
penetrationPoints.second.globalPosition.setValue(globalCoordinatesFromMeshBCoordinates
* penetrationPointB);
pair->addContact(std::abs(depth), globalCoordinatesFromMeshBCoordinates.linear() * normal,
penetrationPoints);
}
}
}
}
}; // namespace Collision
}; // namespace SurgSim
<|endoftext|>
|
<commit_before>/* Copyright 2015-2016 Kogutich Denis
*
* 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 "dynamicPropertiesDialog.h"
#include "ui_dynamicPropertiesDialog.h"
#include <qrkernel/settingsManager.h>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QMessageBox>
#include <QtXml/QDomDocument>
#include <QtCore/QUuid>
#include <QtCore/QDir>
using namespace qReal;
using namespace gui;
const bool hideLabels = false;
DynamicPropertiesDialog::DynamicPropertiesDialog(const qReal::Id &id
, qrRepo::LogicalRepoApi &logicalRepoApi
, models::Exploser &exploser
, QWidget *parent)
: QDialog(parent)
, mUi(new Ui::DynamicPropertiesDialog)
, mShapeWidget(new ShapePropertyWidget(this))
, mShapeBackgroundWidget(new ShapePropertyWidget(this))
, mShapeScrollArea(new QScrollArea(this))
, mShapeBackgroundScrollArea(new QScrollArea(this))
, mLogicalRepoApi(logicalRepoApi)
, mExploser(exploser)
, mId(id)
{
mUi->setupUi(this);
setWindowTitle(tr("Properties"));
mUi->labels->setColumnCount(4);
mUi->labels->setHorizontalHeaderLabels({"Name", "Type", "Value", ""});
mUi->labels->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
if (hideLabels) {
mUi->labels->hide();
mUi->addLabel->hide();
mUi->label->hide();
setFixedHeight(350);
}
mShapeScrollArea->setWidget(mShapeWidget);
mShapeScrollArea->setMaximumHeight(93);
mUi->verticalLayout->insertWidget(6, mShapeScrollArea);
mShapeBackgroundScrollArea->setWidget(mShapeBackgroundWidget);
mShapeBackgroundScrollArea->setMaximumHeight(93);
mUi->verticalLayout->insertWidget(8, mShapeBackgroundScrollArea);
init();
connect(mUi->addLabel, &QPushButton::clicked, this, &DynamicPropertiesDialog::addLabelButtonClicked);
connect(mUi->saveAll, &QPushButton::clicked, this, &DynamicPropertiesDialog::saveButtonClicked);
}
DynamicPropertiesDialog::~DynamicPropertiesDialog()
{
delete mUi;
}
QString DynamicPropertiesDialog::generateShapeXml(const QString &foreground, const QString &background)
{
QDomDocument shapeDoc;
QDomElement picture = shapeDoc.createElement("picture");
picture.setAttribute("sizey", 50);
picture.setAttribute("sizex", 50);
if (!background.isEmpty()) {
QDomElement backgroundSdf = shapeDoc.createElement("image");
backgroundSdf.setAttribute("name", background);
backgroundSdf.setAttribute("x1", 0);
backgroundSdf.setAttribute("y1", 0);
backgroundSdf.setAttribute("x2", 50);
backgroundSdf.setAttribute("y2", 50);
picture.appendChild(backgroundSdf);
}
QDomElement foregroundSdf = shapeDoc.createElement("image");
foregroundSdf.setAttribute("name", foreground);
foregroundSdf.setAttribute("x1", 0);
foregroundSdf.setAttribute("y1", 0);
foregroundSdf.setAttribute("x2", 50);
foregroundSdf.setAttribute("y2", 50);
picture.appendChild(foregroundSdf);
shapeDoc.appendChild(picture);
return shapeDoc.toString(0);
}
void DynamicPropertiesDialog::addLabelButtonClicked()
{
QPushButton *button = new QPushButton("Delete", this);
const int rowCount = mUi->labels->rowCount();
mUi->labels->setRowCount(rowCount + 1);
mUi->labels->setCellWidget(rowCount, 3, button);
connect(button, &QPushButton::clicked, this, &DynamicPropertiesDialog::deleteButtonClicked);
QComboBox *types = new QComboBox(this);
types->addItems({"int", "bool", "string"});
mUi->labels->setCellWidget(rowCount, 1, types);
connect(types, &QComboBox::currentTextChanged, this, &DynamicPropertiesDialog::typeChanged);
}
void DynamicPropertiesDialog::saveButtonClicked()
{
const QString error = tryToSave();
if (!error.isEmpty()) {
QMessageBox::critical(this, tr("Error"), error);
return;
}
mLogicalRepoApi.setProperty(mId, "name", mUi->subprogramName->text());
const QString selectedShape = mShapeWidget->selectedShape();
const QString selectedBackground = mShapeBackgroundWidget->selectedShape();
mLogicalRepoApi.setProperty(mId, "shape", generateShapeXml(selectedShape, selectedBackground));
QDomDocument dynamicLabels;
QDomElement labels = dynamicLabels.createElement("labels");
int x = 40;
int y = 60;
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
const QString name = mUi->labels->item(i, 0)->text();
const QString type = qobject_cast<QComboBox *>(mUi->labels->cellWidget(i, 1))->currentText();
const QString value = type == "bool"
? qobject_cast<QComboBox*>(mUi->labels->cellWidget(i, 2))->currentText()
: mUi->labels->item(i, 2) ? mUi->labels->item(i, 2)->text() : "";
QDomElement label = dynamicLabels.createElement("label");
label.setAttribute("x", x);
label.setAttribute("y", y);
label.setAttribute("textBinded", QUuid::createUuid().toString());
label.setAttribute("type", type);
label.setAttribute("value", value);
label.setAttribute("text", name);
labels.appendChild(label);
y += 30;
}
dynamicLabels.appendChild(labels);
mLogicalRepoApi.setProperty(mId, "labels", dynamicLabels.toString(4));
mExploser.explosionTargetCouldChangeProperties(mId);
}
void DynamicPropertiesDialog::deleteButtonClicked()
{
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
if (mUi->labels->cellWidget(i, 3) == sender()) {
mUi->labels->removeRow(i);
break;
}
}
}
void DynamicPropertiesDialog::typeChanged(const QString &newType)
{
int row = -1;
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
if (mUi->labels->cellWidget(i, 1) == sender()) {
row = i;
break;
}
}
if (row < 0) {
return;
}
if (newType == "bool") {
QComboBox *boolValues = new QComboBox();
boolValues->addItems({"false", "true"});
mUi->labels->setCellWidget(row, 2, boolValues);
} else {
mUi->labels->removeCellWidget(row, 2);
}
}
void DynamicPropertiesDialog::init()
{
const QString filePath = SettingsManager::value("pathToImages").toString() + "/subprogramImages";
QDir dir(filePath);
QStringList strList = dir.entryList();
QStringList shapes;
const QRegExp png(".png$");
const QRegExp svg(".svg$");
for (const QString &str : strList) {
if (str.contains(png) || str.contains(svg)) {
shapes << "subprogramImages/" + str;
}
}
dir.setPath(filePath + "/subprogramBackgrounds");
strList = dir.entryList();
QStringList shapesBackgrounds;
for (const QString &str : strList) {
if (str.contains(png) || str.contains(svg)) {
shapesBackgrounds << "subprogramImages/subprogramBackgrounds/" + str;
}
}
QDomDocument shape;
shape.setContent(mLogicalRepoApi.stringProperty(mId, "shape"));
QString currentShape;
QString currentBackground;
const QDomElement shapeElem = shape.firstChildElement("picture").firstChildElement("image");
if (shapeElem.nextSiblingElement("image").isNull()) {
currentShape = shapeElem.attribute("name");
currentBackground = QString();
} else {
currentBackground = shapeElem.attribute("name");
currentShape = shapeElem.nextSiblingElement("image").attribute("name");
}
mShapeWidget->initShapes(shapes, currentShape, false);
mShapeBackgroundWidget->initShapes(shapesBackgrounds, currentBackground, true);
mUi->subprogramName->setText(mLogicalRepoApi.stringProperty(mId, "name"));
const QString labels = mLogicalRepoApi.stringProperty(mId, "labels");
if (labels.isEmpty()) {
return;
}
QDomDocument dynamicLabels;
dynamicLabels.setContent(labels);
for (QDomElement element = dynamicLabels.firstChildElement("labels").firstChildElement("label")
; !element.isNull()
; element = element.nextSiblingElement("label"))
{
const QString type = element.attribute("type");
const QString value = element.attribute("value");
element = element.nextSiblingElement("label");
const QString text = element.attribute("text");
addLabel(text, type, value);
}
}
QString DynamicPropertiesDialog::tryToSave() const
{
QSet<QString> names;
const int rowCount = mUi->labels->rowCount();
for (int i = 0; i < rowCount; ++i) {
// Return false if "Name" not filled
if (!mUi->labels->item(i, 0) || mUi->labels->item(i, 0)->text().isEmpty()) {
return tr("Name is not filled in row %1").arg(i);
}
const QString type = qobject_cast<QComboBox*>(mUi->labels->cellWidget(i, 1))->currentText();
if (type == "int") {
QString value = mUi->labels->item(i, 2) ? mUi->labels->item(i, 2)->text() : "";
if (!value.isEmpty()) {
bool ok;
value.toInt(&ok);
// Return false if "int" value isn't int
if (!ok) {
return tr("Value in row %1 is not integer").arg(i);
}
}
}
names << mUi->labels->item(i, 0)->text();
}
// Return false if some names are the same
if (names.count() < rowCount) {
return tr("Duplicate names");
}
return QString();
}
void DynamicPropertiesDialog::addLabel(const QString &name, const QString &type, const QString &value)
{
QPushButton *button = new QPushButton(tr("Delete"));
int rowCount = mUi->labels->rowCount();
mUi->labels->setRowCount(rowCount + 1);
mUi->labels->setCellWidget(rowCount, 3, button);
connect(button, &QPushButton::clicked, this, &DynamicPropertiesDialog::deleteButtonClicked);
QComboBox *types = new QComboBox(this);
types->addItems({"int", "bool", "string"});
types->setCurrentText(type);
mUi->labels->setCellWidget(rowCount, 1, types);
connect(types, &QComboBox::currentTextChanged, this, &DynamicPropertiesDialog::typeChanged);
QTableWidgetItem *nameItem = new QTableWidgetItem(name);
mUi->labels->setItem(rowCount, 0, nameItem);
if (type == "bool") {
QComboBox *boolValues = new QComboBox(this);
boolValues->addItems({"false", "true"});
boolValues->setCurrentText(value);
mUi->labels->setCellWidget(rowCount, 2, boolValues);
} else {
QTableWidgetItem *valueItem = new QTableWidgetItem(value);
mUi->labels->setItem(rowCount, 2, valueItem);
}
}
<commit_msg>dynamic property widget losing labels -- fixed<commit_after>/* Copyright 2015-2016 Kogutich Denis
*
* 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 "dynamicPropertiesDialog.h"
#include "ui_dynamicPropertiesDialog.h"
#include <qrkernel/settingsManager.h>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QMessageBox>
#include <QtXml/QDomDocument>
#include <QtCore/QUuid>
#include <QtCore/QDir>
using namespace qReal;
using namespace gui;
const bool hideLabels = false;
DynamicPropertiesDialog::DynamicPropertiesDialog(const qReal::Id &id
, qrRepo::LogicalRepoApi &logicalRepoApi
, models::Exploser &exploser
, QWidget *parent)
: QDialog(parent)
, mUi(new Ui::DynamicPropertiesDialog)
, mShapeWidget(new ShapePropertyWidget(this))
, mShapeBackgroundWidget(new ShapePropertyWidget(this))
, mShapeScrollArea(new QScrollArea(this))
, mShapeBackgroundScrollArea(new QScrollArea(this))
, mLogicalRepoApi(logicalRepoApi)
, mExploser(exploser)
, mId(id)
{
mUi->setupUi(this);
setWindowTitle(tr("Properties"));
mUi->labels->setColumnCount(4);
mUi->labels->setHorizontalHeaderLabels({"Name", "Type", "Value", ""});
mUi->labels->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
if (hideLabels) {
mUi->labels->hide();
mUi->addLabel->hide();
mUi->label->hide();
setFixedHeight(350);
}
mShapeScrollArea->setWidget(mShapeWidget);
mShapeScrollArea->setMaximumHeight(93);
mUi->verticalLayout->insertWidget(6, mShapeScrollArea);
mShapeBackgroundScrollArea->setWidget(mShapeBackgroundWidget);
mShapeBackgroundScrollArea->setMaximumHeight(93);
mUi->verticalLayout->insertWidget(8, mShapeBackgroundScrollArea);
init();
connect(mUi->addLabel, &QPushButton::clicked, this, &DynamicPropertiesDialog::addLabelButtonClicked);
connect(mUi->saveAll, &QPushButton::clicked, this, &DynamicPropertiesDialog::saveButtonClicked);
}
DynamicPropertiesDialog::~DynamicPropertiesDialog()
{
delete mUi;
}
QString DynamicPropertiesDialog::generateShapeXml(const QString &foreground, const QString &background)
{
QDomDocument shapeDoc;
QDomElement picture = shapeDoc.createElement("picture");
picture.setAttribute("sizey", 50);
picture.setAttribute("sizex", 50);
if (!background.isEmpty()) {
QDomElement backgroundSdf = shapeDoc.createElement("image");
backgroundSdf.setAttribute("name", background);
backgroundSdf.setAttribute("x1", 0);
backgroundSdf.setAttribute("y1", 0);
backgroundSdf.setAttribute("x2", 50);
backgroundSdf.setAttribute("y2", 50);
picture.appendChild(backgroundSdf);
}
QDomElement foregroundSdf = shapeDoc.createElement("image");
foregroundSdf.setAttribute("name", foreground);
foregroundSdf.setAttribute("x1", 0);
foregroundSdf.setAttribute("y1", 0);
foregroundSdf.setAttribute("x2", 50);
foregroundSdf.setAttribute("y2", 50);
picture.appendChild(foregroundSdf);
shapeDoc.appendChild(picture);
return shapeDoc.toString(0);
}
void DynamicPropertiesDialog::addLabelButtonClicked()
{
QPushButton *button = new QPushButton("Delete", this);
const int rowCount = mUi->labels->rowCount();
mUi->labels->setRowCount(rowCount + 1);
mUi->labels->setCellWidget(rowCount, 3, button);
connect(button, &QPushButton::clicked, this, &DynamicPropertiesDialog::deleteButtonClicked);
QComboBox *types = new QComboBox(this);
types->addItems({"int", "bool", "string"});
mUi->labels->setCellWidget(rowCount, 1, types);
connect(types, &QComboBox::currentTextChanged, this, &DynamicPropertiesDialog::typeChanged);
}
void DynamicPropertiesDialog::saveButtonClicked()
{
const QString error = tryToSave();
if (!error.isEmpty()) {
QMessageBox::critical(this, tr("Error"), error);
return;
}
// dirty hack to forward values. It's is not labels, it's just name for restoring values
mLogicalRepoApi.setProperty(mId, "name", mUi->subprogramName->text());
const QString selectedShape = mShapeWidget->selectedShape();
const QString selectedBackground = mShapeBackgroundWidget->selectedShape();
mLogicalRepoApi.setProperty(mId, "shape", generateShapeXml(selectedShape, selectedBackground));
QDomDocument dynamicLabels;
QDomElement labels = dynamicLabels.createElement("labels");
int x = 40;
int y = 60;
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
const QString name = mUi->labels->item(i, 0)->text();
const QString type = qobject_cast<QComboBox *>(mUi->labels->cellWidget(i, 1))->currentText();
const QString value = type == "bool"
? qobject_cast<QComboBox*>(mUi->labels->cellWidget(i, 2))->currentText()
: mUi->labels->item(i, 2) ? mUi->labels->item(i, 2)->text() : "";
QDomElement label = dynamicLabels.createElement("label");
label.setAttribute("x", x);
label.setAttribute("y", y);
label.setAttribute("textBinded", QUuid::createUuid().toString());
label.setAttribute("type", type);
label.setAttribute("value", value);
label.setAttribute("text", name);
labels.appendChild(label);
y += 30;
}
dynamicLabels.appendChild(labels);
mLogicalRepoApi.setProperty(mId, "labels", dynamicLabels.toString(4));
emit mExploser.explosionTargetCouldChangeProperties(mId);
this->close();
}
void DynamicPropertiesDialog::deleteButtonClicked()
{
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
if (mUi->labels->cellWidget(i, 3) == sender()) {
mUi->labels->removeRow(i);
break;
}
}
}
void DynamicPropertiesDialog::typeChanged(const QString &newType)
{
int row = -1;
for (int i = 0; i < mUi->labels->rowCount(); ++i) {
if (mUi->labels->cellWidget(i, 1) == sender()) {
row = i;
break;
}
}
if (row < 0) {
return;
}
if (newType == "bool") {
QComboBox *boolValues = new QComboBox();
boolValues->addItems({"false", "true"});
mUi->labels->setCellWidget(row, 2, boolValues);
} else {
mUi->labels->removeCellWidget(row, 2);
}
}
void DynamicPropertiesDialog::init()
{
const QString filePath = SettingsManager::value("pathToImages").toString() + "/subprogramImages";
QDir dir(filePath);
QStringList strList = dir.entryList();
QStringList shapes;
const QRegExp png(".png$");
const QRegExp svg(".svg$");
for (const QString &str : strList) {
if (str.contains(png) || str.contains(svg)) {
shapes << "subprogramImages/" + str;
}
}
dir.setPath(filePath + "/subprogramBackgrounds");
strList = dir.entryList();
QStringList shapesBackgrounds;
for (const QString &str : strList) {
if (str.contains(png) || str.contains(svg)) {
shapesBackgrounds << "subprogramImages/subprogramBackgrounds/" + str;
}
}
QDomDocument shape;
shape.setContent(mLogicalRepoApi.stringProperty(mId, "shape"));
QString currentShape;
QString currentBackground;
const QDomElement shapeElem = shape.firstChildElement("picture").firstChildElement("image");
if (shapeElem.nextSiblingElement("image").isNull()) {
currentShape = shapeElem.attribute("name");
currentBackground = QString();
} else {
currentBackground = shapeElem.attribute("name");
currentShape = shapeElem.nextSiblingElement("image").attribute("name");
}
mShapeWidget->initShapes(shapes, currentShape, false);
mShapeBackgroundWidget->initShapes(shapesBackgrounds, currentBackground, true);
mUi->subprogramName->setText(mLogicalRepoApi.stringProperty(mId, "name"));
const QString labels = mLogicalRepoApi.stringProperty(mId, "labels");
if (labels.isEmpty()) {
return;
}
QDomDocument dynamicLabels;
dynamicLabels.setContent(labels);
for (QDomElement element = dynamicLabels.firstChildElement("labels").firstChildElement("label")
; !element.isNull()
; element = element.nextSiblingElement("label"))
{
const QString type = element.attribute("type");
const QString value = element.attribute("value");
const QString text = element.attribute("text");
addLabel(text, type, value);
}
}
QString DynamicPropertiesDialog::tryToSave() const
{
QSet<QString> names;
const int rowCount = mUi->labels->rowCount();
for (int i = 0; i < rowCount; ++i) {
// Return false if "Name" not filled
if (!mUi->labels->item(i, 0) || mUi->labels->item(i, 0)->text().isEmpty()) {
return tr("Name is not filled in row %1").arg(i);
}
const QString type = qobject_cast<QComboBox*>(mUi->labels->cellWidget(i, 1))->currentText();
if (type == "int") {
QString value = mUi->labels->item(i, 2) ? mUi->labels->item(i, 2)->text() : "";
if (!value.isEmpty()) {
bool ok;
value.toInt(&ok);
// Return false if "int" value isn't int
if (!ok) {
return tr("Value in row %1 is not integer").arg(i);
}
}
}
names << mUi->labels->item(i, 0)->text();
}
// Return false if some names are the same
if (names.count() < rowCount) {
return tr("Duplicate names");
}
return QString();
}
void DynamicPropertiesDialog::addLabel(const QString &name, const QString &type, const QString &value)
{
QPushButton *button = new QPushButton(tr("Delete"));
int rowCount = mUi->labels->rowCount();
mUi->labels->setRowCount(rowCount + 1);
mUi->labels->setCellWidget(rowCount, 3, button);
connect(button, &QPushButton::clicked, this, &DynamicPropertiesDialog::deleteButtonClicked);
QComboBox *types = new QComboBox(this);
types->addItems({"int", "bool", "string"});
types->setCurrentText(type);
mUi->labels->setCellWidget(rowCount, 1, types);
connect(types, &QComboBox::currentTextChanged, this, &DynamicPropertiesDialog::typeChanged);
QTableWidgetItem *nameItem = new QTableWidgetItem(name);
mUi->labels->setItem(rowCount, 0, nameItem);
if (type == "bool") {
QComboBox *boolValues = new QComboBox(this);
boolValues->addItems({"false", "true"});
boolValues->setCurrentText(value);
mUi->labels->setCellWidget(rowCount, 2, boolValues);
} else {
QTableWidgetItem *valueItem = new QTableWidgetItem(value);
mUi->labels->setItem(rowCount, 2, valueItem);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_
#include <map>
#include <vector>
#include <utility>
#include "buffer_cache/alt/page_cache.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
#include "utils.hpp"
class serializer_t;
class buf_lock_t;
class alt_cache_config_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;
class perfmon_collection_t;
// KSI: This is kind of F'd up a bit. Throttling doesn't use the stuff we learn in
// inform_memory_change (right now) so this is just a nonsensical mixing of notions.
class alt_memory_tracker_t : public memory_tracker_t {
public:
alt_memory_tracker_t();
~alt_memory_tracker_t();
alt::tracker_acq_t begin_txn_or_throttle(int64_t expected_change_count);
void end_txn(alt::tracker_acq_t acq);
private:
friend class txn_t;
void inform_memory_change(uint64_t in_memory_size,
uint64_t memory_limit);
new_semaphore_t unwritten_changes_semaphore_;
DISABLE_COPYING(alt_memory_tracker_t);
};
class cache_t : public home_thread_mixin_t {
public:
explicit cache_t(serializer_t *serializer,
const alt_cache_config_t &dynamic_config,
perfmon_collection_t *perfmon_collection);
~cache_t();
block_size_t max_block_size() const;
// KSI: Remove this.
block_size_t get_block_size() const { return max_block_size(); }
// These todos come from the mirrored cache. The real problem is that whole
// cache account / priority thing is just one ghetto hack amidst a dozen other
// throttling systems. TODO: Come up with a consistent priority scheme,
// i.e. define a "default" priority etc. TODO: As soon as we can support it, we
// might consider supporting a mem_cap paremeter.
cache_account_t create_cache_account(int priority);
private:
friend class txn_t;
friend class buf_read_t;
friend class buf_write_t;
friend class buf_lock_t;
alt_snapshot_node_t *matching_snapshot_node_or_null(
block_id_t block_id,
alt::block_version_t block_version);
void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
scoped_ptr_t<alt_cache_stats_t> stats_;
// tracker_ is used for throttling (which can cause the txn_t constructor to
// block).
alt_memory_tracker_t tracker_;
alt::page_cache_t page_cache_;
two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;
DISABLE_COPYING(cache_t);
};
class txn_t {
public:
// Constructor for read-only transactions.
txn_t(cache_conn_t *cache_conn, read_access_t read_access);
// KSI: Remove default parameter for expected_change_count.
txn_t(cache_conn_t *cache_conn,
write_durability_t durability,
repli_timestamp_t txn_timestamp,
int64_t expected_change_count = 2);
~txn_t();
cache_t *cache() { return cache_; }
alt::page_txn_t *page_txn() { return page_txn_.get(); }
access_t access() const { return access_; }
void set_account(cache_account_t *cache_account);
cache_account_t *account() { return cache_account_; }
private:
// Resets the *tracker_acq parameter.
static void inform_tracker(cache_t *cache,
alt::tracker_acq_t *tracker_acq);
// Resets the *tracker_acq parameter.
static void pulse_and_inform_tracker(cache_t *cache,
alt::tracker_acq_t *tracker_acq,
cond_t *pulsee);
void help_construct(repli_timestamp_t txn_timestamp,
int64_t expected_change_count,
cache_conn_t *cache_conn);
cache_t *const cache_;
// Initialized to cache()->page_cache_.default_cache_account(), and modified by
// set_account().
cache_account_t *cache_account_;
const access_t access_;
// Only applicable if access_ == write.
const write_durability_t durability_;
scoped_ptr_t<alt::page_txn_t> page_txn_;
DISABLE_COPYING(txn_t);
};
class buf_parent_t;
class buf_lock_t {
public:
buf_lock_t();
// buf_parent_t is a type that either points at a buf_lock_t (its parent) or
// merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
// If acquiring the child for read, the constructor will wait for the parent to
// be acquired for read. Similarly, if acquiring the child for write, the
// constructor will wait for the parent to be acquired for write. Once the
// constructor returns, you are "in line" for the block, meaning you'll acquire
// it in the same order relative other agents as you did when acquiring the same
// parent. (Of course, readers can intermingle.)
// These constructors will _not_ yield the coroutine _if_ the parent is already
// {access}-acquired.
// Acquires an existing block for read or write access.
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
access_t access);
// Creates a new block with a specified block id, one that doesn't have a parent.
buf_lock_t(txn_t *txn,
block_id_t block_id,
alt_create_t create);
// Creates a new block with a specified block id as the child of a parent (if it's
// not just a txn_t *).
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
alt_create_t create);
// Acquires an existing block given the parent.
buf_lock_t(buf_lock_t *parent,
block_id_t block_id,
access_t access);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_parent_t parent,
alt_create_t create);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_lock_t *parent,
alt_create_t create);
~buf_lock_t();
buf_lock_t(buf_lock_t &&movee);
buf_lock_t &operator=(buf_lock_t &&movee);
void swap(buf_lock_t &other);
void reset_buf_lock();
bool empty() const {
return txn_ == NULL;
}
void snapshot_subdag();
void detach_child(block_id_t child_id);
block_id_t block_id() const {
guarantee(txn_ != NULL);
return current_page_acq()->block_id();
}
repli_timestamp_t get_recency() const;
access_t access() const {
guarantee(!empty());
return current_page_acq()->access();
}
signal_t *read_acq_signal() {
guarantee(!empty());
return current_page_acq()->read_acq_signal();
}
signal_t *write_acq_signal() {
guarantee(!empty());
return current_page_acq()->write_acq_signal();
}
void mark_deleted();
txn_t *txn() const { return txn_; }
cache_t *cache() const { return txn_->cache(); }
private:
void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
void help_construct(buf_parent_t parent, alt_create_t create);
void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);
static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id,
cache_account_t *account);
static void wait_for_parent(buf_parent_t parent, access_t access);
static alt_snapshot_node_t *
get_or_create_child_snapshot_node(cache_t *cache,
alt_snapshot_node_t *parent,
block_id_t child_id,
cache_account_t *account);
static void create_empty_child_snapshot_attachments(
cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
static void create_child_snapshot_attachments(cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id,
cache_account_t *account);
alt::current_page_acq_t *current_page_acq() const;
friend class buf_read_t; // for get_held_page_for_read, access_ref_count_.
friend class buf_write_t; // for get_held_page_for_write, access_ref_count_.
alt::page_t *get_held_page_for_read();
alt::page_t *get_held_page_for_write();
txn_t *txn_;
scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;
alt_snapshot_node_t *snapshot_node_;
// Keeps track of how many alt_buf_{read|write}_t have been created for
// this lock, for assertion/guarantee purposes.
intptr_t access_ref_count_;
DISABLE_COPYING(buf_lock_t);
};
class buf_parent_t {
public:
buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }
explicit buf_parent_t(buf_lock_t *lock)
: txn_(lock->txn()), lock_or_null_(lock) {
guarantee(lock != NULL);
guarantee(!lock->empty());
}
explicit buf_parent_t(txn_t *txn)
: txn_(txn), lock_or_null_(NULL) {
rassert(txn != NULL);
}
void detach_child(block_id_t child_id) {
if (lock_or_null_ != NULL) {
lock_or_null_->detach_child(child_id);
}
}
bool empty() const {
return txn_ == NULL;
}
txn_t *txn() const {
guarantee(!empty());
return txn_;
}
cache_t *cache() const {
guarantee(!empty());
return txn_->cache();
}
private:
friend class buf_lock_t;
txn_t *txn_;
buf_lock_t *lock_or_null_;
};
class buf_read_t {
public:
explicit buf_read_t(buf_lock_t *lock);
~buf_read_t();
const void *get_data_read(uint32_t *block_size_out);
const void *get_data_read() {
uint32_t block_size;
const void *data = get_data_read(&block_size);
guarantee(block_size == lock_->cache()->max_block_size().value());
return data;
}
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_read_t);
};
class buf_write_t {
public:
explicit buf_write_t(buf_lock_t *lock);
~buf_write_t();
void *get_data_write(uint32_t block_size);
// Equivalent to passing the max_block_size.
void *get_data_write();
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_write_t);
};
#endif // BUFFER_CACHE_ALT_ALT_HPP_
<commit_msg>Removed utils.hpp from alt.hpp.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_
#include <map>
#include <vector>
#include <utility>
#include "buffer_cache/alt/page_cache.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
class serializer_t;
class buf_lock_t;
class alt_cache_config_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;
class perfmon_collection_t;
// KSI: This is kind of F'd up a bit. Throttling doesn't use the stuff we learn in
// inform_memory_change (right now) so this is just a nonsensical mixing of notions.
class alt_memory_tracker_t : public memory_tracker_t {
public:
alt_memory_tracker_t();
~alt_memory_tracker_t();
alt::tracker_acq_t begin_txn_or_throttle(int64_t expected_change_count);
void end_txn(alt::tracker_acq_t acq);
private:
friend class txn_t;
void inform_memory_change(uint64_t in_memory_size,
uint64_t memory_limit);
new_semaphore_t unwritten_changes_semaphore_;
DISABLE_COPYING(alt_memory_tracker_t);
};
class cache_t : public home_thread_mixin_t {
public:
explicit cache_t(serializer_t *serializer,
const alt_cache_config_t &dynamic_config,
perfmon_collection_t *perfmon_collection);
~cache_t();
block_size_t max_block_size() const;
// KSI: Remove this.
block_size_t get_block_size() const { return max_block_size(); }
// These todos come from the mirrored cache. The real problem is that whole
// cache account / priority thing is just one ghetto hack amidst a dozen other
// throttling systems. TODO: Come up with a consistent priority scheme,
// i.e. define a "default" priority etc. TODO: As soon as we can support it, we
// might consider supporting a mem_cap paremeter.
cache_account_t create_cache_account(int priority);
private:
friend class txn_t;
friend class buf_read_t;
friend class buf_write_t;
friend class buf_lock_t;
alt_snapshot_node_t *matching_snapshot_node_or_null(
block_id_t block_id,
alt::block_version_t block_version);
void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
scoped_ptr_t<alt_cache_stats_t> stats_;
// tracker_ is used for throttling (which can cause the txn_t constructor to
// block).
alt_memory_tracker_t tracker_;
alt::page_cache_t page_cache_;
two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;
DISABLE_COPYING(cache_t);
};
class txn_t {
public:
// Constructor for read-only transactions.
txn_t(cache_conn_t *cache_conn, read_access_t read_access);
// KSI: Remove default parameter for expected_change_count.
txn_t(cache_conn_t *cache_conn,
write_durability_t durability,
repli_timestamp_t txn_timestamp,
int64_t expected_change_count = 2);
~txn_t();
cache_t *cache() { return cache_; }
alt::page_txn_t *page_txn() { return page_txn_.get(); }
access_t access() const { return access_; }
void set_account(cache_account_t *cache_account);
cache_account_t *account() { return cache_account_; }
private:
// Resets the *tracker_acq parameter.
static void inform_tracker(cache_t *cache,
alt::tracker_acq_t *tracker_acq);
// Resets the *tracker_acq parameter.
static void pulse_and_inform_tracker(cache_t *cache,
alt::tracker_acq_t *tracker_acq,
cond_t *pulsee);
void help_construct(repli_timestamp_t txn_timestamp,
int64_t expected_change_count,
cache_conn_t *cache_conn);
cache_t *const cache_;
// Initialized to cache()->page_cache_.default_cache_account(), and modified by
// set_account().
cache_account_t *cache_account_;
const access_t access_;
// Only applicable if access_ == write.
const write_durability_t durability_;
scoped_ptr_t<alt::page_txn_t> page_txn_;
DISABLE_COPYING(txn_t);
};
class buf_parent_t;
class buf_lock_t {
public:
buf_lock_t();
// buf_parent_t is a type that either points at a buf_lock_t (its parent) or
// merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
// If acquiring the child for read, the constructor will wait for the parent to
// be acquired for read. Similarly, if acquiring the child for write, the
// constructor will wait for the parent to be acquired for write. Once the
// constructor returns, you are "in line" for the block, meaning you'll acquire
// it in the same order relative other agents as you did when acquiring the same
// parent. (Of course, readers can intermingle.)
// These constructors will _not_ yield the coroutine _if_ the parent is already
// {access}-acquired.
// Acquires an existing block for read or write access.
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
access_t access);
// Creates a new block with a specified block id, one that doesn't have a parent.
buf_lock_t(txn_t *txn,
block_id_t block_id,
alt_create_t create);
// Creates a new block with a specified block id as the child of a parent (if it's
// not just a txn_t *).
buf_lock_t(buf_parent_t parent,
block_id_t block_id,
alt_create_t create);
// Acquires an existing block given the parent.
buf_lock_t(buf_lock_t *parent,
block_id_t block_id,
access_t access);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_parent_t parent,
alt_create_t create);
// Creates a block, a new child of the given parent. It gets assigned a block id
// from one of the unused block id's.
buf_lock_t(buf_lock_t *parent,
alt_create_t create);
~buf_lock_t();
buf_lock_t(buf_lock_t &&movee);
buf_lock_t &operator=(buf_lock_t &&movee);
void swap(buf_lock_t &other);
void reset_buf_lock();
bool empty() const {
return txn_ == NULL;
}
void snapshot_subdag();
void detach_child(block_id_t child_id);
block_id_t block_id() const {
guarantee(txn_ != NULL);
return current_page_acq()->block_id();
}
repli_timestamp_t get_recency() const;
access_t access() const {
guarantee(!empty());
return current_page_acq()->access();
}
signal_t *read_acq_signal() {
guarantee(!empty());
return current_page_acq()->read_acq_signal();
}
signal_t *write_acq_signal() {
guarantee(!empty());
return current_page_acq()->write_acq_signal();
}
void mark_deleted();
txn_t *txn() const { return txn_; }
cache_t *cache() const { return txn_->cache(); }
private:
void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
void help_construct(buf_parent_t parent, alt_create_t create);
void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);
static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id,
cache_account_t *account);
static void wait_for_parent(buf_parent_t parent, access_t access);
static alt_snapshot_node_t *
get_or_create_child_snapshot_node(cache_t *cache,
alt_snapshot_node_t *parent,
block_id_t child_id,
cache_account_t *account);
static void create_empty_child_snapshot_attachments(
cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id);
static void create_child_snapshot_attachments(cache_t *cache,
alt::block_version_t parent_version,
block_id_t parent_id,
block_id_t child_id,
cache_account_t *account);
alt::current_page_acq_t *current_page_acq() const;
friend class buf_read_t; // for get_held_page_for_read, access_ref_count_.
friend class buf_write_t; // for get_held_page_for_write, access_ref_count_.
alt::page_t *get_held_page_for_read();
alt::page_t *get_held_page_for_write();
txn_t *txn_;
scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;
alt_snapshot_node_t *snapshot_node_;
// Keeps track of how many alt_buf_{read|write}_t have been created for
// this lock, for assertion/guarantee purposes.
intptr_t access_ref_count_;
DISABLE_COPYING(buf_lock_t);
};
class buf_parent_t {
public:
buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }
explicit buf_parent_t(buf_lock_t *lock)
: txn_(lock->txn()), lock_or_null_(lock) {
guarantee(lock != NULL);
guarantee(!lock->empty());
}
explicit buf_parent_t(txn_t *txn)
: txn_(txn), lock_or_null_(NULL) {
rassert(txn != NULL);
}
void detach_child(block_id_t child_id) {
if (lock_or_null_ != NULL) {
lock_or_null_->detach_child(child_id);
}
}
bool empty() const {
return txn_ == NULL;
}
txn_t *txn() const {
guarantee(!empty());
return txn_;
}
cache_t *cache() const {
guarantee(!empty());
return txn_->cache();
}
private:
friend class buf_lock_t;
txn_t *txn_;
buf_lock_t *lock_or_null_;
};
class buf_read_t {
public:
explicit buf_read_t(buf_lock_t *lock);
~buf_read_t();
const void *get_data_read(uint32_t *block_size_out);
const void *get_data_read() {
uint32_t block_size;
const void *data = get_data_read(&block_size);
guarantee(block_size == lock_->cache()->max_block_size().value());
return data;
}
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_read_t);
};
class buf_write_t {
public:
explicit buf_write_t(buf_lock_t *lock);
~buf_write_t();
void *get_data_write(uint32_t block_size);
// Equivalent to passing the max_block_size.
void *get_data_write();
private:
buf_lock_t *lock_;
alt::page_acq_t page_acq_;
DISABLE_COPYING(buf_write_t);
};
#endif // BUFFER_CACHE_ALT_ALT_HPP_
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <list>
#include <ctime>
#include <cmath>
using namespace std;
template<typename T>
string toStr(const T &val)
{
ostringstream ss;
ss << val;
return ss.str();
}
enum Direction
{
North,
South,
East,
West
};
struct Portal
{
sf::Vector2i pos1, pos2;
sf::Color color;
};
class PortalPos
{
public:
PortalPos(const sf::Vector2i &newVal) : val(newVal)
{
}
bool operator() (const Portal &p)
{
return (p.pos1 == val) || (p.pos2 == val);
}
private:
const sf::Vector2i val;
};
int main()
{
const unsigned int magicKey = 1340993809;
bool wrapAround = false;
bool shadow = false;
bool flip = false;
srand(time(NULL));
sf::RenderWindow window(sf::VideoMode(800, 600), "p0rtalSnake");
window.setFramerateLimit(60);
sf::Vector2i sizei = sf::Vector2i(window.getSize().x, window.getSize().y) / 20;
sf::Vector2f sizef(window.getSize().x / sizei.x, window.getSize().y / sizei.y);
sf::SoundBuffer foodBuffer, hurtBuffer, portalBuffer, wrapBuffer, flipBuffer;
foodBuffer.loadFromFile("res/food.wav");
hurtBuffer.loadFromFile("res/hurt.wav");
portalBuffer.loadFromFile("res/portal.wav");
wrapBuffer.loadFromFile("res/wrap.wav");
flipBuffer.loadFromFile("res/flip.wav");
sf::Sound foodSound(foodBuffer), hurtSound(hurtBuffer), portalSound(portalBuffer), wrapSound(wrapBuffer), flipSound(flipBuffer);
sf::Font font;
font.loadFromFile("res/font.ttf");
sf::Text scoreText;
scoreText.setFont(font);
scoreText.setCharacterSize(30);
scoreText.setColor(sf::Color(255, 255, 255, 196));
scoreText.setPosition(sf::Vector2f(20.f, 20.f));
sf::Text maxScoreText;
maxScoreText.setFont(font);
maxScoreText.setCharacterSize(15);
maxScoreText.setColor(sf::Color(255, 255, 255, 196));
maxScoreText.setPosition(sf::Vector2f(25.f, 55.f));
unsigned int maxScore;
{
ifstream fin("res/score.dat");
if (fin >> maxScore)
maxScore ^= magicKey;
else
maxScore = 0;
}
list<sf::Vector2i> snake;
snake.push_back(sf::Vector2i(10, 10));
snake.push_back(sf::Vector2i(10, 11));
snake.push_back(sf::Vector2i(10, 12));
snake.push_back(sf::Vector2i(10, 13));
Direction dir = North;
sf::Clock moveClock;
list<sf::Vector2i> foods;
sf::Clock foodClock;
list<sf::Vector2i> walls;
for (int i = 0; i < (sizei.x * sizei.y * 0.01); i++)
{
sf::Vector2i pos;
do
{
pos.x = rand() % sizei.x;
pos.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos) != snake.end()) || (find(walls.begin(), walls.end(), pos) != walls.end()));
walls.push_back(pos);
}
list<Portal> portals;
for (int i = 0; i < 3; i++)
{
sf::Vector2i pos1, pos2;
do
{
pos1.x = rand() % sizei.x;
pos1.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos1) != snake.end()) || (find(walls.begin(), walls.end(), pos1) != walls.end()) || (find_if(portals.begin(), portals.end(), PortalPos(pos1)) != portals.end()));
do
{
pos2.x = rand() % sizei.x;
pos2.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos2) != snake.end()) || (find(walls.begin(), walls.end(), pos2) != walls.end()) || (find_if(portals.begin(), portals.end(), PortalPos(pos2)) != portals.end()));
sf::Color color(rand() % 256, rand() % 256, rand() % 256);
portals.push_back(Portal{pos1, pos2, color});
}
while (window.isOpen())
{
sf::Event e;
while (window.pollEvent(e))
{
if (e.type == sf::Event::Closed)
{
window.close();
}
else if (e.type == sf::Event::KeyPressed)
{
const sf::Vector2i &head = snake.front();
switch (e.key.code)
{
case sf::Keyboard::Up:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(0, -1)) == snake.end())
dir = North;
break;
case sf::Keyboard::Down:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(0, 1)) == snake.end())
dir = South;
break;
case sf::Keyboard::Right:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(1, 0)) == snake.end())
dir = East;
break;
case sf::Keyboard::Left:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(-1, 0)) == snake.end())
dir = West;
break;
case sf::Keyboard::Space:
{
if (flip)
{
/*
bug when snake.size() == 2 and flipping while being wrapped around
*/
snake.reverse();
const sf::Vector2i &head = snake.front();
list<sf::Vector2i>::iterator second = snake.begin();
second++;
sf::Vector2i d = head - *second;
if (d.y < 0)
dir = North;
else if (d.y > 0)
dir = South;
else if (d.x > 0)
dir = East;
else if (d.x < 0)
dir = West;
else
throw "Shit happened!";
flipSound.play();
}
break;
}
case sf::Keyboard::S:
shadow = !shadow;
break;
case sf::Keyboard::W:
wrapAround = !wrapAround;
break;
case sf::Keyboard::F:
flip = !flip;
break;
default:
break;
}
}
}
if (foodClock.getElapsedTime().asSeconds() >= 2)
{
for (int i = 0; i < sizei.x * sizei.y; i++)
{
sf::Vector2i pos(rand() % sizei.x, rand() % sizei.y);
if ((find(snake.begin(), snake.end(), pos) == snake.end()) && (find(walls.begin(), walls.end(), pos) == walls.end()) && (find(foods.begin(), foods.end(), pos) == foods.end()))
{
foods.push_back(pos);
break;
}
}
foodClock.restart();
}
if (moveClock.getElapsedTime().asMilliseconds() >= (450 / sqrt(snake.size())))
{
sf::Vector2i head = snake.front();
switch (dir)
{
case North:
head.y--;
break;
case South:
head.y++;
break;
case East:
head.x++;
break;
case West:
head.x--;
break;
}
if (wrapAround)
{
if (head.x < 0)
{
head.x += sizei.x;
wrapSound.play();
}
else if (head.x >= sizei.x)
{
head.x %= sizei.x;
wrapSound.play();
}
if (head.y < 0)
{
head.y += sizei.y;
wrapSound.play();
}
else if (head.y >= sizei.y)
{
head.y %= sizei.y;
wrapSound.play();
}
}
for (list<Portal>::iterator it = portals.begin(); it != portals.end(); ++it)
{
bool through = false;
if (head == it->pos1)
{
head = it->pos2;
through = true;
}
else if (head == it->pos2)
{
head = it->pos1;
through = true;
}
if (through)
{
switch (dir)
{
case North:
head.y--;
break;
case South:
head.y++;
break;
case East:
head.x++;
break;
case West:
head.x--;
break;
}
if (wrapAround)
{
if (head.x < 0)
head.x += sizei.x;
else
head.x %= sizei.x;
if (head.y < 0)
head.y += sizei.y;
else
head.y %= sizei.y;
}
portalSound.play();
break;
}
}
if ((find(snake.begin(), snake.end(), head) == snake.end()) && (find(walls.begin(), walls.end(), head) == walls.end()) && (head.x >= 0) && (head.x < sizei.x) && (head.y >= 0) && (head.y < sizei.y))
{
snake.push_front(head);
list<sf::Vector2i>::iterator foodIt = find(foods.begin(), foods.end(), head);
if (foodIt != foods.end())
{
foods.erase(foodIt);
foodSound.play();
}
else
snake.pop_back();
}
else
{
// hits wall/snake
if (snake.size() > 2)
{
snake.pop_back();
hurtSound.play();
}
}
moveClock.restart();
}
if (snake.size() > maxScore)
maxScore = snake.size();
scoreText.setString(toStr(snake.size()));
maxScoreText.setString(toStr(maxScore));
window.clear();
sf::RectangleShape rect;
rect.setSize(sizef - sf::Vector2f(2.f, 2.f));
rect.setOrigin(sf::Vector2f(-1.f, -1.f));
rect.setFillColor(sf::Color(64, 64, 64));
for (int y = 0; y < sizei.y; y++)
{
for (int x = 0; x < sizei.x; x++)
{
rect.setPosition(sf::Vector2f(x * sizef.x, y * sizef.y));
window.draw(rect);
}
}
rect.setFillColor(sf::Color(32, 32, 32));
for (list<sf::Vector2i>::iterator it = walls.begin(); it != walls.end(); ++it)
{
sf::Vector2i &pos = *it;
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
rect.setFillColor(sf::Color::Green);
for (list<sf::Vector2i>::iterator it = foods.begin(); it != foods.end(); ++it)
{
sf::Vector2i &pos = *it;
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
for (list<sf::Vector2i>::iterator it = snake.begin(); it != snake.end(); ++it)
{
sf::Vector2i &pos = *it;
if (it == snake.begin())
rect.setFillColor(sf::Color::Red);
else
{
int mix = max(255 - distance(snake.begin(), it), 32);
rect.setFillColor(sf::Color(mix, mix, 0));
}
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
for (list<Portal>::iterator it = portals.begin(); it != portals.end(); ++it)
{
rect.setFillColor(it->color);
rect.setPosition(sf::Vector2f(it->pos1.x * sizef.x, it->pos1.y * sizef.y));
window.draw(rect);
rect.setPosition(sf::Vector2f(it->pos2.x * sizef.x, it->pos2.y * sizef.y));
window.draw(rect);
}
if (shadow)
{
rect.setFillColor(sf::Color::Black);
for (int y = 0; y < sizei.y; y++)
{
for (int x = 0; x < sizei.x; x++)
{
if ((pow(x - snake.front().x, 2) + pow(y - snake.front().y, 2)) > pow(10, 2))
{
rect.setPosition(sf::Vector2f(x * sizef.x, y * sizef.y));
window.draw(rect);
}
}
}
}
window.draw(scoreText);
window.draw(maxScoreText);
window.display();
}
{
ofstream fout("res/score.dat");
fout << (maxScore ^ magicKey);
}
return 0;
}
<commit_msg>Add some comments<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <list>
#include <ctime>
#include <cmath>
using namespace std;
template<typename T>
string toStr(const T &val)
{
ostringstream ss;
ss << val;
return ss.str();
}
enum Direction
{
North,
South,
East,
West
};
struct Portal
{
sf::Vector2i pos1, pos2;
sf::Color color;
};
class PortalPos
{
public:
PortalPos(const sf::Vector2i &newVal) : val(newVal)
{
}
bool operator() (const Portal &p)
{
return (p.pos1 == val) || (p.pos2 == val);
}
private:
const sf::Vector2i val;
};
int main()
{
const unsigned int magicKey = 1340993809;
bool wrapAround = false;
bool shadow = false;
bool flip = false;
srand(time(NULL));
sf::RenderWindow window(sf::VideoMode(800, 600), "p0rtalSnake");
window.setFramerateLimit(60);
sf::Vector2i sizei = sf::Vector2i(window.getSize().x, window.getSize().y) / 20;
sf::Vector2f sizef(window.getSize().x / sizei.x, window.getSize().y / sizei.y);
// initialize resources
sf::SoundBuffer foodBuffer, hurtBuffer, portalBuffer, wrapBuffer, flipBuffer;
foodBuffer.loadFromFile("res/food.wav");
hurtBuffer.loadFromFile("res/hurt.wav");
portalBuffer.loadFromFile("res/portal.wav");
wrapBuffer.loadFromFile("res/wrap.wav");
flipBuffer.loadFromFile("res/flip.wav");
sf::Sound foodSound(foodBuffer), hurtSound(hurtBuffer), portalSound(portalBuffer), wrapSound(wrapBuffer), flipSound(flipBuffer);
sf::Font font;
font.loadFromFile("res/font.ttf");
sf::Text scoreText;
scoreText.setFont(font);
scoreText.setCharacterSize(30);
scoreText.setColor(sf::Color(255, 255, 255, 196));
scoreText.setPosition(sf::Vector2f(20.f, 20.f));
sf::Text maxScoreText;
maxScoreText.setFont(font);
maxScoreText.setCharacterSize(15);
maxScoreText.setColor(sf::Color(255, 255, 255, 196));
maxScoreText.setPosition(sf::Vector2f(25.f, 55.f));
// load score if found
unsigned int maxScore;
{
ifstream fin("res/score.dat");
if (fin >> maxScore)
maxScore ^= magicKey;
else
maxScore = 0;
}
// initialize snake
list<sf::Vector2i> snake;
snake.push_back(sf::Vector2i(10, 10));
snake.push_back(sf::Vector2i(10, 11));
snake.push_back(sf::Vector2i(10, 12));
snake.push_back(sf::Vector2i(10, 13));
Direction dir = North;
sf::Clock moveClock;
list<sf::Vector2i> foods;
sf::Clock foodClock;
// initialize walls
list<sf::Vector2i> walls;
for (int i = 0; i < (sizei.x * sizei.y * 0.01); i++)
{
sf::Vector2i pos;
do
{
pos.x = rand() % sizei.x;
pos.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos) != snake.end()) || (find(walls.begin(), walls.end(), pos) != walls.end())); // find free position
walls.push_back(pos);
}
// initialize portals
list<Portal> portals;
for (int i = 0; i < 3; i++)
{
sf::Vector2i pos1, pos2;
do
{
pos1.x = rand() % sizei.x;
pos1.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos1) != snake.end()) || (find(walls.begin(), walls.end(), pos1) != walls.end()) || (find_if(portals.begin(), portals.end(), PortalPos(pos1)) != portals.end())); // find free position
do
{
pos2.x = rand() % sizei.x;
pos2.y = rand() % sizei.y;
}
while ((find(snake.begin(), snake.end(), pos2) != snake.end()) || (find(walls.begin(), walls.end(), pos2) != walls.end()) || (find_if(portals.begin(), portals.end(), PortalPos(pos2)) != portals.end())); // find free position
sf::Color color(rand() % 256, rand() % 256, rand() % 256);
portals.push_back(Portal{pos1, pos2, color});
}
// main loop
while (window.isOpen())
{
sf::Event e;
while (window.pollEvent(e))
{
if (e.type == sf::Event::Closed)
{
window.close();
}
else if (e.type == sf::Event::KeyPressed)
{
const sf::Vector2i &head = snake.front();
switch (e.key.code)
{
case sf::Keyboard::Up:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(0, -1)) == snake.end())
dir = North;
break;
case sf::Keyboard::Down:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(0, 1)) == snake.end())
dir = South;
break;
case sf::Keyboard::Right:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(1, 0)) == snake.end())
dir = East;
break;
case sf::Keyboard::Left:
if (find(snake.begin(), snake.end(), head + sf::Vector2i(-1, 0)) == snake.end())
dir = West;
break;
case sf::Keyboard::Space:
{
if (flip)
{
/*
bug when snake.size() == 2 and flipping while being wrapped around
*/
snake.reverse();
const sf::Vector2i &head = snake.front();
list<sf::Vector2i>::iterator second = snake.begin();
second++;
sf::Vector2i d = head - *second;
if (d.y < 0)
dir = North;
else if (d.y > 0)
dir = South;
else if (d.x > 0)
dir = East;
else if (d.x < 0)
dir = West;
else
throw "Shit happened!";
flipSound.play();
}
break;
}
case sf::Keyboard::S:
shadow = !shadow;
break;
case sf::Keyboard::W:
wrapAround = !wrapAround;
break;
case sf::Keyboard::F:
flip = !flip;
break;
default:
break;
}
}
}
// spawn food
if (foodClock.getElapsedTime().asSeconds() >= 2)
{
for (int i = 0; i < sizei.x * sizei.y; i++)
{
sf::Vector2i pos(rand() % sizei.x, rand() % sizei.y);
if ((find(snake.begin(), snake.end(), pos) == snake.end()) && (find(walls.begin(), walls.end(), pos) == walls.end()) && (find(foods.begin(), foods.end(), pos) == foods.end()))
{
foods.push_back(pos);
break;
}
}
foodClock.restart();
}
// move snake
if (moveClock.getElapsedTime().asMilliseconds() >= (450 / sqrt(snake.size())))
{
sf::Vector2i head = snake.front();
switch (dir)
{
case North:
head.y--;
break;
case South:
head.y++;
break;
case East:
head.x++;
break;
case West:
head.x--;
break;
}
if (wrapAround)
{
if (head.x < 0)
{
head.x += sizei.x;
wrapSound.play();
}
else if (head.x >= sizei.x)
{
head.x %= sizei.x;
wrapSound.play();
}
if (head.y < 0)
{
head.y += sizei.y;
wrapSound.play();
}
else if (head.y >= sizei.y)
{
head.y %= sizei.y;
wrapSound.play();
}
}
for (list<Portal>::iterator it = portals.begin(); it != portals.end(); ++it)
{
bool through = false;
if (head == it->pos1)
{
head = it->pos2;
through = true;
}
else if (head == it->pos2)
{
head = it->pos1;
through = true;
}
if (through)
{
switch (dir)
{
case North:
head.y--;
break;
case South:
head.y++;
break;
case East:
head.x++;
break;
case West:
head.x--;
break;
}
if (wrapAround)
{
if (head.x < 0)
head.x += sizei.x;
else
head.x %= sizei.x;
if (head.y < 0)
head.y += sizei.y;
else
head.y %= sizei.y;
}
portalSound.play();
break;
}
}
if ((find(snake.begin(), snake.end(), head) == snake.end()) && (find(walls.begin(), walls.end(), head) == walls.end()) && (head.x >= 0) && (head.x < sizei.x) && (head.y >= 0) && (head.y < sizei.y))
{
snake.push_front(head);
list<sf::Vector2i>::iterator foodIt = find(foods.begin(), foods.end(), head);
if (foodIt != foods.end())
{
foods.erase(foodIt);
foodSound.play();
}
else
snake.pop_back();
}
else
{
// hits wall/snake
if (snake.size() > 2)
{
snake.pop_back();
hurtSound.play();
}
}
moveClock.restart();
}
if (snake.size() > maxScore)
maxScore = snake.size();
scoreText.setString(toStr(snake.size()));
maxScoreText.setString(toStr(maxScore));
window.clear();
sf::RectangleShape rect;
rect.setSize(sizef - sf::Vector2f(2.f, 2.f));
rect.setOrigin(sf::Vector2f(-1.f, -1.f));
// draw background
rect.setFillColor(sf::Color(64, 64, 64));
for (int y = 0; y < sizei.y; y++)
{
for (int x = 0; x < sizei.x; x++)
{
rect.setPosition(sf::Vector2f(x * sizef.x, y * sizef.y));
window.draw(rect);
}
}
// draw walls
rect.setFillColor(sf::Color(32, 32, 32));
for (list<sf::Vector2i>::iterator it = walls.begin(); it != walls.end(); ++it)
{
sf::Vector2i &pos = *it;
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
// draw food
rect.setFillColor(sf::Color::Green);
for (list<sf::Vector2i>::iterator it = foods.begin(); it != foods.end(); ++it)
{
sf::Vector2i &pos = *it;
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
// draw snake
for (list<sf::Vector2i>::iterator it = snake.begin(); it != snake.end(); ++it)
{
sf::Vector2i &pos = *it;
if (it == snake.begin())
rect.setFillColor(sf::Color::Red);
else
{
int mix = max(255 - distance(snake.begin(), it), 32);
rect.setFillColor(sf::Color(mix, mix, 0));
}
rect.setPosition(sf::Vector2f(pos.x * sizef.x, pos.y * sizef.y));
window.draw(rect);
}
// draw portals
for (list<Portal>::iterator it = portals.begin(); it != portals.end(); ++it)
{
rect.setFillColor(it->color);
rect.setPosition(sf::Vector2f(it->pos1.x * sizef.x, it->pos1.y * sizef.y));
window.draw(rect);
rect.setPosition(sf::Vector2f(it->pos2.x * sizef.x, it->pos2.y * sizef.y));
window.draw(rect);
}
// shadow field
if (shadow)
{
rect.setFillColor(sf::Color::Black);
for (int y = 0; y < sizei.y; y++)
{
for (int x = 0; x < sizei.x; x++)
{
if ((pow(x - snake.front().x, 2) + pow(y - snake.front().y, 2)) > pow(10, 2))
{
rect.setPosition(sf::Vector2f(x * sizef.x, y * sizef.y));
window.draw(rect);
}
}
}
}
window.draw(scoreText);
window.draw(maxScoreText);
window.display();
}
// save score
{
ofstream fout("res/score.dat");
fout << (maxScore ^ magicKey);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
class MatMul : public Generator<MatMul> {
public:
// We take 2 8-bit matrices as input.
Input<Buffer<uint8_t>> A{"A", 2};
Input<Buffer<uint8_t>> B{"B", 2};
// We produce a 32 bit matrix result.
Output<Buffer<uint32_t>> output{"output", 2};
std::function<void()> schedule;
void generate() {
Var x{"x"}, y{"y"};
// Align the extent of the K dimension to the product of our split
// factors.
const int k_unroll_factor = 2;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_unroll_factor*4))*(k_unroll_factor*4);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
const int k_split_factor = 4;
RDom rk(0, k_extent/k_split_factor, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
// We need a wrapper for the output so we can schedule the
// multiply update in tiles.
output(x, y) = AB(x, y);
// Schedule.
schedule = [=]() mutable {
const Target &target = get_target();
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
if (use_hexagon) {
Var xo("xo"), yo("yo");
// Split the output into tiles, traversed in columns of tiles
// that we parallelize over.
Func(output).compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
// Compute the product at tiles of the output.
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
AB.update(0)
.reorder(x, y, rk)
.prefetch(A, rk, 2)
.vectorize(x)
.unroll(y)
.unroll(rk, k_unroll_factor);
// Lift the swizzling out of the inner loop.
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.reorder(k, x, y)
.vectorize(x, vector_size_u8, TailStrategy::RoundUp)
.unroll(k);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
Func(output).compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, 4, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize/k_split_factor, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned.
A.dim(0)
.set_bounds(0, (k_extent/vector_size_u8)*vector_size_u8);
A.dim(1)
.set_bounds(0, (A.dim(1).extent()/vector_size_u8)*vector_size_u8)
.set_stride((A.dim(1).stride()/vector_size_u8)*vector_size_u8);
B.dim(0)
.set_bounds(0, (B.dim(0).extent()/vector_size_u8)*vector_size_u8);
B.dim(1)
.set_bounds(0, (k_extent/vector_size_u8)*vector_size_u8)
.set_stride((B.dim(1).stride()/vector_size_u8)*vector_size_u8);
output.dim(0)
.set_bounds(0, (output.dim(0).extent()/vector_size_u32)*vector_size_u32);
output.dim(1)
.set_bounds(0, (output.dim(1).extent()/vector_size_u32)*vector_size_u32)
.set_stride((output.dim(1).stride()/vector_size_u32)*vector_size_u32);
};
}
};
HALIDE_REGISTER_GENERATOR(MatMul, "matmul");
<commit_msg>Faster prefetching schedule, relax alignment requirements.<commit_after>#include "Halide.h"
using namespace Halide;
using namespace Halide::ConciseCasts;
class MatMul : public Generator<MatMul> {
public:
// We take 2 8-bit matrices as input.
Input<Buffer<uint8_t>> A{"A", 2};
Input<Buffer<uint8_t>> B{"B", 2};
// We produce a 32 bit matrix result.
Output<Buffer<uint32_t>> output{"output", 2};
std::function<void()> schedule;
void generate() {
Var x{"x"}, y{"y"};
// Align the extent of the K dimension to the product of our split
// factors.
const int k_unroll_factor = 2;
Expr k_extent = A.dim(0).extent();
k_extent = (k_extent/(k_unroll_factor*4))*(k_unroll_factor*4);
// We split directly in the algorithm by a factor of 4, so we can
// generate vrmpy instructions on Hexagon.
const int k_split_factor = 4;
RDom rk(0, k_extent/k_split_factor, "k");
// Define the reordering of B as a separate stage so we can lift
// the interleaving required by vrmpy out of the inner loop.
Func B_swizzled("B_swizzled");
Var k("k");
B_swizzled(x, y, k) = B(x, 4*y + k);
Func AB("AB");
AB(x, y) = u32(0);
AB(x, y) +=
u32(u16(A(4*rk + 0, y))*u16(B_swizzled(x, rk, 0))) +
u32(u16(A(4*rk + 1, y))*u16(B_swizzled(x, rk, 1))) +
u32(u16(A(4*rk + 2, y))*u16(B_swizzled(x, rk, 2))) +
u32(u16(A(4*rk + 3, y))*u16(B_swizzled(x, rk, 3)));
// We need a wrapper for the output so we can schedule the
// multiply update in tiles.
output(x, y) = AB(x, y);
// Schedule.
schedule = [=]() mutable {
const Target &target = get_target();
int vector_size_u8 = target.natural_vector_size<uint8_t>();
bool use_hexagon = false;
if (target.has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
use_hexagon = true;
} else if (target.has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
use_hexagon = true;
}
int vector_size_u32 = vector_size_u8 / 4;
int tile_rows = 4;
if (use_hexagon) {
Var xo("xo"), yo("yo");
// Split the output into tiles, traversed in columns of tiles
// that we parallelize over.
Func(output).compute_root()
.hexagon()
.tile(x, y, xo, yo, x, y, vector_size_u8, tile_rows, TailStrategy::RoundUp)
.reorder(yo, xo)
.vectorize(x)
.unroll(y)
.parallel(xo);
// Compute the product at tiles of the output.
AB.compute_at(output, yo)
.vectorize(x)
.unroll(y);
RVar rko("rko"), rki("rki");
AB.update(0)
.reorder(x, y, rk)
.split(rk, rko, rki, 16, TailStrategy::GuardWithIf)
.prefetch(A, rko, 1)
.vectorize(x)
.unroll(y)
.unroll(rki, k_unroll_factor);
// Lift the swizzling out of the inner loop.
B_swizzled.compute_at(output, xo)
.reorder_storage(k, x, y)
.reorder(k, x, y)
.vectorize(x, vector_size_u8, TailStrategy::RoundUp)
.unroll(k);
} else {
Var xi("xi"), xii("xii"), yi("yi"), yii("yii");
RVar rki("rki");
// This schedule taken from test/performance/matrix_multiplication.cpp
constexpr int kBlockSize = 32;
const int kBlockSizeXi = 8;
Func(output).compute_root()
.tile(x, y, x, y, xi, yi, vector_size_u8, tile_rows, TailStrategy::RoundUp)
.reorder(xi, yi, x, y)
.vectorize(xi)
.unroll(yi)
.parallel(y);
AB.compute_root()
.vectorize(x, vector_size_u32);
AB.update(0)
.split(x, x, xi, kBlockSize, TailStrategy::GuardWithIf)
.split(xi, xi, xii, kBlockSizeXi, TailStrategy::GuardWithIf)
.split(y, y, yi, kBlockSize, TailStrategy::GuardWithIf)
.split(yi, yi, yii, 4, TailStrategy::GuardWithIf)
.split(rk, rk, rki, kBlockSize/k_split_factor, TailStrategy::GuardWithIf)
.reorder(xii, yii, xi, rki, yi, rk, x, y)
.parallel(y)
.vectorize(xii)
.unroll(xi)
.unroll(yii);
}
// Require scanlines of the input and output to be aligned where necessary.
A.dim(0)
.set_bounds(0, (k_extent/vector_size_u8)*vector_size_u8);
A.dim(1)
.set_bounds(0, (A.dim(1).extent()/tile_rows)*tile_rows)
.set_stride((A.dim(1).stride()/vector_size_u8)*vector_size_u8);
B.dim(0)
.set_bounds(0, (B.dim(0).extent()/vector_size_u8)*vector_size_u8);
B.dim(1)
.set_bounds(0, (k_extent/vector_size_u8)*vector_size_u8)
.set_stride((B.dim(1).stride()/vector_size_u8)*vector_size_u8);
output.dim(0)
.set_bounds(0, (output.dim(0).extent()/vector_size_u32)*vector_size_u32);
output.dim(1)
.set_bounds(0, (output.dim(1).extent()/tile_rows)*tile_rows)
.set_stride((output.dim(1).stride()/vector_size_u32)*vector_size_u32);
};
}
};
HALIDE_REGISTER_GENERATOR(MatMul, "matmul");
<|endoftext|>
|
<commit_before>/**
* A simple Urho3D example in one (big) file.
* Copyright 2014 Peter Gebauer, 2015 gawag.
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*
* Why?
* Because A first "simple" example tutorial shouldn't require additional
* frameworks or special toolchains. This file along with Urho3D and a C++
* compiler should do it. (you might have to change the prefix path in
* MyApp::Setup)
* Many (like me) want to learn themselves and just get an overview
* without the overhead of understanding how the example is built.
* I hope this file covers the basics and is of use to you.
*/
#include <string>
#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
using namespace Urho3D;
/**
* Using the convenient Application API we don't have
* to worry about initializing the engine or writing a main.
* You can probably mess around with initializing the engine
* and running a main manually, but this is convenient and portable.
*/
class MyApp : public Application
{
public:
int framecount_;
float time_;
SharedPtr<Text> text_;
SharedPtr<Scene> scene_;
SharedPtr<Node> boxNode_;
Node* cameraNode_;
/**
* This happens before the engine has been initialized
* so it's usually minimal code setting defaults for
* whatever instance variables you have.
* You can also do this in the Setup method.
*/
MyApp(Context * context) : Application(context),framecount_(0),time_(0)
{
}
/**
* This method is called _before_ the engine has been initialized.
* Thusly, we can setup the engine parameters before anything else
* of engine importance happens (such as windows, search paths,
* resolution and other things that might be user configurable).
*/
virtual void Setup()
{
// These parameters should be self-explanatory.
// See http://urho3d.github.io/documentation/1.32/_main_loop.html
// for a more complete list.
engineParameters_["FullScreen"]=false;
engineParameters_["WindowWidth"]=1280;
engineParameters_["WindowHeight"]=720;
engineParameters_["WindowResizable"]=true;
// Override the resource prefix path to use. "If not specified then the
// default prefix path is set to URHO3D_PREFIX_PATH environment
// variable (if defined) or executable path."
// By default mine was in /usr/local/share, change as needed.
// Remember to use a TRAILING SLASH to your path! (for unknown reason)
//engineParameters_["ResourcePrefixPath"] = "/usr/local/share/Urho3D/Bin/";
}
/**
* This method is called _after_ the engine has been initialized.
* This is where you set up your actual content, such as scenes,
* models, controls and what not. Basically, anything that needs
* the engine initialized and ready goes in here.
*/
virtual void Start()
{
// We will be needing to load resources.
// All the resources used in this example comes with Urho3D.
// If the engine can't find them, check the ResourcePrefixPath.
ResourceCache* cache=GetSubsystem<ResourceCache>();
// Seems like the mouse must be in cursor mode before creating the UI or it won't work.
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
// Let's use the default style that comes with Urho3D.
GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
// Let's create some text to display.
text_=new Text(context_);
// Text will be updated later in the E_UPDATE handler. Keep readin'.
text_->SetText("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\nWait a bit to see FPS.");
// If the engine cannot find the font, it comes with Urho3D.
// Set the environment variables URHO3D_HOME, URHO3D_PREFIX_PATH or
// change the engine parameter "ResourcePrefixPath" in the Setup method.
text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20);
text_->SetColor(Color(.3,0,.3));
text_->SetHorizontalAlignment(HA_CENTER);
text_->SetVerticalAlignment(VA_TOP);
GetSubsystem<UI>()->GetRoot()->AddChild(text_);
// Add a button, just as an interactive UI sample.
Button* button=new Button(context_);
// Note, must be part of the UI system before SetSize calls!
GetSubsystem<UI>()->GetRoot()->AddChild(button);
button->SetName("Button Quit");
button->SetStyle("Button");
//button->SetText("quit");
button->SetSize(32,32);
button->SetPosition(16,16);
// Now we can change the mouse mode.
GetSubsystem<Input>()->SetMouseVisible(false);
GetSubsystem<Input>()->SetMouseGrabbed(true);
// Let's setup a scene to render.
scene_=new Scene(context_);
// Let the scene have an Octree component!
scene_->CreateComponent<Octree>();
// Let's add an additional scene component for fun.
scene_->CreateComponent<DebugRenderer>();
// Let's put some sky in there.
// Again, if the engine can't find these resources you need to check
// the "ResourcePrefixPath". These files come with Urho3D.
Node* skyNode=scene_->CreateChild("Sky");
skyNode->SetScale(500.0f); // The scale actually does not matter
Skybox* skybox=skyNode->CreateComponent<Skybox>();
skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
// Let's put a box in there.
boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(0,0,5));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
// Create a plane out of 900 boxes.
for(int x=-30;x<30;x+=3)
for(int y=-30;y<30;y+=3)
{
Node* boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(x,-3,y));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
boxObject->SetCastShadows(true);
}
// We need a camera from which the viewport can render.
cameraNode_=scene_->CreateChild("Camera");
Camera* camera=cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(2000);
// Create two lights
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(-5,10,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(1,.5,.8,1));
}
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(5,-3,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(.5,.8,1,1));
}
// add one to the camera node as well
{
Light* light=cameraNode_->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10);
light->SetBrightness(2.0);
light->SetColor(Color(.8,1,.8,1.0));
}
// Now we setup the viewport. Ofcourse, you can have more than one!
Renderer* renderer=GetSubsystem<Renderer>();
SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0,viewport);
// We subscribe to the events we'd like to handle.
// In this example we will be showing what most of them do,
// but in reality you would only subscribe to the events
// you really need to handle.
// These are sort of subscribed in the order in which the engine
// would send the events. Read each handler method's comment for
// details.
SubscribeToEvent(E_BEGINFRAME,HANDLER(MyApp,HandleBeginFrame));
SubscribeToEvent(E_KEYDOWN,HANDLER(MyApp,HandleKeyDown));
SubscribeToEvent(E_UIMOUSECLICK,HANDLER(MyApp,HandleControlClicked));
SubscribeToEvent(E_UPDATE,HANDLER(MyApp,HandleUpdate));
SubscribeToEvent(E_POSTUPDATE,HANDLER(MyApp,HandlePostUpdate));
SubscribeToEvent(E_RENDERUPDATE,HANDLER(MyApp,HandleRenderUpdate));
SubscribeToEvent(E_POSTRENDERUPDATE,HANDLER(MyApp,HandlePostRenderUpdate));
SubscribeToEvent(E_ENDFRAME,HANDLER(MyApp,HandleEndFrame));
}
/**
* Good place to get rid of any system resources that requires the
* engine still initialized. You could do the rest in the destructor,
* but there's no need, this method will get called when the engine stops,
* for whatever reason (short of a segfault).
*/
virtual void Stop()
{
}
/**
* Every frame's life must begin somewhere. Here it is.
*/
void HandleBeginFrame(StringHash eventType,VariantMap& eventData)
{
// We really don't have anything useful to do here for this example.
// Probably shouldn't be subscribing to events we don't care about.
}
/**
* Input from keyboard is handled here. I'm assuming that Input, if
* available, will be handled before E_UPDATE.
*/
void HandleKeyDown(StringHash eventType,VariantMap& eventData)
{
using namespace KeyDown;
int key=eventData[P_KEY].GetInt();
// T'is a good default key for quit things.
if(key==KEY_ESC)
engine_->Exit();
if(key==KEY_TAB)
{
GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
}
}
/**
* You can get these events from when ever the user interacts with the UI.
*/
void HandleControlClicked(StringHash eventType,VariantMap& eventData)
{
// Query the clicked UI element.
UIElement* clicked=static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
if(clicked)
if(clicked->GetName()=="Button Quit") // check if the quit button was clicked
engine_->Exit();
}
/**
* Your non-rendering logic should be handled here.
* This could be moving objects, checking collisions and reaction, etc.
*/
void HandleUpdate(StringHash eventType,VariantMap& eventData)
{
float timeStep=eventData[Update::P_TIMESTEP].GetFloat();
framecount_++;
time_+=timeStep;
// Movement speed as world units per second
float MOVE_SPEED=10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY=0.1f;
if(time_ >=1)
{
std::string str;
str.append("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\n");
str.append(std::to_string(framecount_));
str.append(" frames in ");
str.append(std::to_string(time_));
str.append(" seconds = ");
str.append(std::to_string((float)framecount_ / time_));
str.append(" fps");
String s(str.c_str(),str.size());
text_->SetText(s);
framecount_=0;
time_=0;
}
// Rotate the box thingy.
// A much nicer way of doing this would be with a LogicComponent.
// With LogicComponents it is easy to control things like movement
// and animation from some IDE, console or just in game.
// Alas, it is out of the scope for our simple example.
boxNode_->Rotate(Quaternion(8*timeStep,16*timeStep,0));
Input* input=GetSubsystem<Input>();
if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt
MOVE_SPEED*=10;
if(input->GetKeyDown('W'))
cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('S'))
cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('A'))
cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('D'))
cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);
if(!GetSubsystem<Input>()->IsMouseVisible())
{
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove=input->GetMouseMove();
// avoid the weird extrem values before moving the mouse
if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
{
static float yaw_=0;
static float pitch_=0;
yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
pitch_=Clamp(pitch_,-90.0f,90.0f);
// Reset rotation and set yaw and pitch again
cameraNode_->SetDirection(Vector3::FORWARD);
cameraNode_->Yaw(yaw_);
cameraNode_->Pitch(pitch_);
}
}
}
/**
* Anything in the non-rendering logic that requires a second pass,
* it might be well suited to be handled here.
*/
void HandlePostUpdate(StringHash eventType,VariantMap& eventData)
{
// We really don't have anything useful to do here for this example.
// Probably shouldn't be subscribing to events we don't care about.
}
/**
* If you have any details you want to change before the viewport is
* rendered, try putting it here.
* See http://urho3d.github.io/documentation/1.32/_rendering.html
* for details on how the rendering pipeline is setup.
*/
void HandleRenderUpdate(StringHash eventType, VariantMap & eventData)
{
// We really don't have anything useful to do here for this example.
// Probably shouldn't be subscribing to events we don't care about.
}
/**
* After everything is rendered, there might still be things you wish
* to add to the rendering. At this point you cannot modify the scene,
* only post rendering is allowed. Good for adding things like debug
* artifacts on screen or brush up lighting, etc.
*/
void HandlePostRenderUpdate(StringHash eventType, VariantMap & eventData)
{
// We could draw some debuggy looking thing for the octree.
// scene_->GetComponent<Octree>()->DrawDebugGeometry(true);
}
/**
* All good things must come to an end.
*/
void HandleEndFrame(StringHash eventType,VariantMap& eventData)
{
// We really don't have anything useful to do here for this example.
// Probably shouldn't be subscribing to events we don't care about.
}
};
/**
* This macro is expaneded to (roughly, depending on OS) this:
*
* > int RunApplication()
* > {
* > Urho3D::SharedPtr<Urho3D::Context> context(new Urho3D::Context());
* > Urho3D::SharedPtr<className> application(new className(context));
* > return application->Run();
* > }
* >
* > int main(int argc, char** argv)
* > {
* > Urho3D::ParseArguments(argc, argv);
* > return function;
* > }
*/
DEFINE_APPLICATION_MAIN(MyApp)
<commit_msg>Removed all tutorial comments to get a clean project template.<commit_after>/**
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*/
#include <string>
#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
using namespace Urho3D;
class MyApp : public Application
{
public:
int framecount_;
float time_;
SharedPtr<Text> text_;
SharedPtr<Scene> scene_;
SharedPtr<Node> boxNode_;
Node* cameraNode_;
MyApp(Context * context) : Application(context),framecount_(0),time_(0)
{
}
virtual void Setup()
{
engineParameters_["FullScreen"]=false;
engineParameters_["WindowWidth"]=1280;
engineParameters_["WindowHeight"]=720;
engineParameters_["WindowResizable"]=true;
}
virtual void Start()
{
ResourceCache* cache=GetSubsystem<ResourceCache>();
GetSubsystem<Input>()->SetMouseVisible(true);
GetSubsystem<Input>()->SetMouseGrabbed(false);
GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));
text_=new Text(context_);
text_->SetText("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\nWait a bit to see FPS.");
text_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),20);
text_->SetColor(Color(.3,0,.3));
text_->SetHorizontalAlignment(HA_CENTER);
text_->SetVerticalAlignment(VA_TOP);
GetSubsystem<UI>()->GetRoot()->AddChild(text_);
Button* button=new Button(context_);
GetSubsystem<UI>()->GetRoot()->AddChild(button);
button->SetName("Button Quit");
button->SetStyle("Button");
button->SetSize(32,32);
button->SetPosition(16,16);
GetSubsystem<Input>()->SetMouseVisible(false);
GetSubsystem<Input>()->SetMouseGrabbed(true);
scene_=new Scene(context_);
scene_->CreateComponent<Octree>();
scene_->CreateComponent<DebugRenderer>();
Node* skyNode=scene_->CreateChild("Sky");
skyNode->SetScale(500.0f); // The scale actually does not matter
Skybox* skybox=skyNode->CreateComponent<Skybox>();
skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(0,0,5));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
for(int x=-30;x<30;x+=3)
for(int y=-30;y<30;y+=3)
{
Node* boxNode_=scene_->CreateChild("Box");
boxNode_->SetPosition(Vector3(x,-3,y));
StaticModel* boxObject=boxNode_->CreateComponent<StaticModel>();
boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
boxObject->SetCastShadows(true);
}
cameraNode_=scene_->CreateChild("Camera");
Camera* camera=cameraNode_->CreateComponent<Camera>();
camera->SetFarClip(2000);
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(-5,10,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(1,.5,.8,1));
}
{
Node* lightNode=scene_->CreateChild("Light");
lightNode->SetPosition(Vector3(5,-3,5));
Light* light=lightNode->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(50);
light->SetBrightness(1.2);
light->SetColor(Color(.5,.8,1,1));
}
{
Light* light=cameraNode_->CreateComponent<Light>();
light->SetLightType(LIGHT_POINT);
light->SetRange(10);
light->SetBrightness(2.0);
light->SetColor(Color(.8,1,.8,1.0));
}
Renderer* renderer=GetSubsystem<Renderer>();
SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
renderer->SetViewport(0,viewport);
SubscribeToEvent(E_BEGINFRAME,HANDLER(MyApp,HandleBeginFrame));
SubscribeToEvent(E_KEYDOWN,HANDLER(MyApp,HandleKeyDown));
SubscribeToEvent(E_UIMOUSECLICK,HANDLER(MyApp,HandleControlClicked));
SubscribeToEvent(E_UPDATE,HANDLER(MyApp,HandleUpdate));
SubscribeToEvent(E_POSTUPDATE,HANDLER(MyApp,HandlePostUpdate));
SubscribeToEvent(E_RENDERUPDATE,HANDLER(MyApp,HandleRenderUpdate));
SubscribeToEvent(E_POSTRENDERUPDATE,HANDLER(MyApp,HandlePostRenderUpdate));
SubscribeToEvent(E_ENDFRAME,HANDLER(MyApp,HandleEndFrame));
}
virtual void Stop()
{
}
void HandleKeyDown(StringHash eventType,VariantMap& eventData)
{
using namespace KeyDown;
int key=eventData[P_KEY].GetInt();
if(key==KEY_ESC)
engine_->Exit();
if(key==KEY_TAB)
{
GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
}
}
void HandleControlClicked(StringHash eventType,VariantMap& eventData)
{
// Query the clicked UI element.
UIElement* clicked=static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
if(clicked)
if(clicked->GetName()=="Button Quit") // check if the quit button was clicked
engine_->Exit();
}
void HandleUpdate(StringHash eventType,VariantMap& eventData)
{
float timeStep=eventData[Update::P_TIMESTEP].GetFloat();
framecount_++;
time_+=timeStep;
// Movement speed as world units per second
float MOVE_SPEED=10.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY=0.1f;
if(time_ >=1)
{
std::string str;
str.append("Keys: tab = toggle mouse, AWSD = move camera, Shift = fast mode, Esc = quit.\n");
str.append(std::to_string(framecount_));
str.append(" frames in ");
str.append(std::to_string(time_));
str.append(" seconds = ");
str.append(std::to_string((float)framecount_ / time_));
str.append(" fps");
String s(str.c_str(),str.size());
text_->SetText(s);
framecount_=0;
time_=0;
}
// Rotate the box thingy.
// A much nicer way of doing this would be with a LogicComponent.
// With LogicComponents it is easy to control things like movement
// and animation from some IDE, console or just in game.
// Alas, it is out of the scope for our simple example.
boxNode_->Rotate(Quaternion(8*timeStep,16*timeStep,0));
Input* input=GetSubsystem<Input>();
if(input->GetQualifierDown(1)) // 1 is shift, 2 is ctrl, 4 is alt
MOVE_SPEED*=10;
if(input->GetKeyDown('W'))
cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('S'))
cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('A'))
cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
if(input->GetKeyDown('D'))
cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);
if(!GetSubsystem<Input>()->IsMouseVisible())
{
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove=input->GetMouseMove();
// avoid the weird extrem values before moving the mouse
if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
{
static float yaw_=0;
static float pitch_=0;
yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
pitch_=Clamp(pitch_,-90.0f,90.0f);
// Reset rotation and set yaw and pitch again
cameraNode_->SetDirection(Vector3::FORWARD);
cameraNode_->Yaw(yaw_);
cameraNode_->Pitch(pitch_);
}
}
}
void HandleBeginFrame(StringHash eventType,VariantMap& eventData)
{
}
void HandlePostUpdate(StringHash eventType,VariantMap& eventData)
{
}
void HandleRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandlePostRenderUpdate(StringHash eventType, VariantMap & eventData)
{
}
void HandleEndFrame(StringHash eventType,VariantMap& eventData)
{
}
};
/**
* This macro is expaneded to (roughly, depending on OS) this:
*
* > int RunApplication()
* > {
* > Urho3D::SharedPtr<Urho3D::Context> context(new Urho3D::Context());
* > Urho3D::SharedPtr<className> application(new className(context));
* > return application->Run();
* > }
* >
* > int main(int argc, char** argv)
* > {
* > Urho3D::ParseArguments(argc, argv);
* > return function;
* > }
*/
DEFINE_APPLICATION_MAIN(MyApp)
<|endoftext|>
|
<commit_before>#pragma once
#include <experimental/coroutine>
#include "coro.hpp"
BEGIN_ASYNCIO_NAMESPACE;
template <typename ReturnType> class co_runner {
public:
co_runner(coro<ReturnType> &co) : _runner(run(co)) {
_runner.await_suspend(nullptr);
}
co_runner(coro<ReturnType> &&co) : _runner(run(co)) {
_runner.await_suspend(nullptr);
}
co_runner(co_runner &) = delete;
co_runner(co_runner &&) = delete;
std::future<ReturnType> get_future() { return std::move(_future); }
private:
coro<void> _runner;
std::future<ReturnType> _future;
coro<void> run(coro<ReturnType> &co) {
std::promise<ReturnType> promise;
this->_future = promise.get_future();
try {
ReturnType ret = co_await std::move(co);
promise.set_value(ret);
} catch (...) {
promise.set_exception(std::current_exception());
}
}
};
template <> coro<void> inline co_runner<void>::run(coro<void> &co) {
std::promise<void> promise;
this->_future = promise.get_future();
try {
coro<void> co_holder = std::move(co);
co_await co_holder;
promise.set_value();
} catch (...) {
promise.set_exception(std::current_exception());
}
}
class AWaitableBase {
public:
AWaitableBase() : _ready(false), _caller(nullptr) {}
bool await_ready() const noexcept { return _ready; }
bool await_suspend(std::experimental::coroutine_handle<> caller) noexcept {
if (!_ready) {
_caller = caller;
}
return !_ready;
}
void clear() {
_ready = false;
_caller = nullptr;
}
protected:
// void await_resume() const noexcept {}
void setReady() { _ready = true; }
void resumeCaller() {
if (_caller) {
_caller.resume();
}
}
bool _ready;
std::experimental::coroutine_handle<> _caller;
};
template <typename T> class AWaitable : public AWaitableBase {
public:
T await_resume() const noexcept { return _value; }
void resume(T value) {
_value = value;
this->setReady();
this->resumeCaller();
}
private:
T _value;
};
template <> class AWaitable<void> : public AWaitableBase {
public:
void await_resume() const noexcept {}
void resume() {
this->setReady();
this->resumeCaller();
}
};
END_ASYNCIO_NAMESPACE;<commit_msg>make use of std::move in AWaitable<commit_after>#pragma once
#include <experimental/coroutine>
#include "coro.hpp"
BEGIN_ASYNCIO_NAMESPACE;
template <typename ReturnType> class co_runner {
public:
co_runner(coro<ReturnType> &co) : _runner(run(co)) {
_runner.await_suspend(nullptr);
}
co_runner(coro<ReturnType> &&co) : _runner(run(co)) {
_runner.await_suspend(nullptr);
}
co_runner(co_runner &) = delete;
co_runner(co_runner &&) = delete;
std::future<ReturnType> get_future() { return std::move(_future); }
private:
coro<void> _runner;
std::future<ReturnType> _future;
coro<void> run(coro<ReturnType> &co) {
std::promise<ReturnType> promise;
this->_future = promise.get_future();
try {
ReturnType ret = co_await std::move(co);
promise.set_value(ret);
} catch (...) {
promise.set_exception(std::current_exception());
}
}
};
template <> coro<void> inline co_runner<void>::run(coro<void> &co) {
std::promise<void> promise;
this->_future = promise.get_future();
try {
coro<void> co_holder = std::move(co);
co_await co_holder;
promise.set_value();
} catch (...) {
promise.set_exception(std::current_exception());
}
}
class AWaitableBase {
public:
AWaitableBase() : _ready(false), _caller(nullptr) {}
bool await_ready() const noexcept { return _ready; }
bool await_suspend(std::experimental::coroutine_handle<> caller) noexcept {
if (!_ready) {
_caller = caller;
}
return !_ready;
}
void clear() {
_ready = false;
_caller = nullptr;
}
protected:
// void await_resume() const noexcept {}
void setReady() { _ready = true; }
void resumeCaller() {
if (_caller) {
_caller.resume();
}
}
bool _ready;
std::experimental::coroutine_handle<> _caller;
};
template <typename T> class AWaitable : public AWaitableBase {
public:
T await_resume() const noexcept { return std::move(_value); }
void resume(T &&value) {
_value = std::move(value);
this->setReady();
this->resumeCaller();
}
void resume(T &value) {
_value = value;
this->setReady();
this->resumeCaller();
}
private:
T _value;
};
template <> class AWaitable<void> : public AWaitableBase {
public:
void await_resume() const noexcept {}
void resume() {
this->setReady();
this->resumeCaller();
}
};
END_ASYNCIO_NAMESPACE;<|endoftext|>
|
<commit_before>#include "layer.h"
#include "datahandler.h"
#include <opencv2/core.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
const char *keys =
"{ board b || GPU board(s): 0 or 012, etc. }"
"{ data d || Model pbtxt file }"
"{ layer l || Layer pbtxt file }"
"{ output o || Output hdf5 file }";
CommandLineParser parser(argc, argv, keys);
string board(parser.get<string>("board"));
string data_config_file(parser.get<string>("data"));
string layer_config_file(parser.get<string>("layer"));
string output_file(parser.get<string>("output"));
if (board.empty() || data_config_file.empty() || layer_config_file.empty() || output_file.empty()) {
parser.printMessage();
return 1;
}
vector<int> boards;
ParseBoardIds(board, boards);
Matrix::SetupCUDADevice(boards[0]);
cout << "Using board " << boards[0] << endl;
config::DatasetConfig data_config;
ReadPbtxt<config::DatasetConfig>(data_config_file, data_config);
DataHandler* dataset_ = new DataHandler(data_config);
int batch_size = dataset_->GetBatchSize();
int dataset_size = dataset_->GetDataSetSize();
dataset_->AllocateMemory();
cout << "Data set size " << dataset_size << endl;
config::Layer layer_config;
ReadPbtxt<config::Layer>(layer_config_file, layer_config);
Layer *l = Layer::ChooseLayerClass(layer_config);
int num_colors = l->GetNumChannels();
int image_size_y = dataset_->GetImageSizeY(l->GetName());
int image_size_x = dataset_->GetImageSizeX(l->GetName());
l->SetSize(image_size_y, image_size_x, 1);
l->AllocateMemory(batch_size);
vector<Layer*> layers;
layers.push_back(l);
int num_batches = dataset_size / batch_size;
cout << "Image size " << image_size_y << "x" << image_size_x << endl;
Matrix& state = l->GetState();
int num_dims = state.GetCols();
Matrix mean_batch, mean_image, mean_pixel;
Matrix var_batch, var_image, var_pixel;
mean_batch.AllocateGPUMemory(batch_size, num_dims);
mean_image.AllocateGPUMemory(1, num_dims);
mean_pixel.AllocateGPUMemory(1, num_colors);
var_batch.AllocateGPUMemory(batch_size, num_dims);
var_image.AllocateGPUMemory(1, num_dims);
var_pixel.AllocateGPUMemory(1, num_colors);
Matrix pixel_cov, out_p;
pixel_cov.AllocateGPUMemory(num_colors, num_colors);
out_p.AllocateGPUMemory(num_colors, num_colors);
int num_pix = num_dims / num_colors;
mean_batch.Set(0);
var_batch.Set(0);
pixel_cov.Set(0);
cout << "Num batches " << num_batches << endl;
for (int k = 0; k < num_batches; k++) {
cout << "\r" << k+1;
cout.flush();
dataset_->GetBatch(layers);
mean_batch.Add(state);
state.Reshape(-1, num_colors);
Matrix::Dot(state, state, pixel_cov, 1, 1.0 / (batch_size * num_pix) , true, false);
state.Reshape(batch_size, -1);
state.Mult(state);
var_batch.Add(state);
}
dataset_->Sync();
cout << endl;
mean_batch.Divide(num_batches);
var_batch.Divide(num_batches);
pixel_cov.Divide(num_batches);
mean_batch.SumRows(mean_image, 0, 1.0 / batch_size);
mean_image.Reshape(-1, num_colors);
mean_image.SumRows(mean_pixel, 0, 1.0 / mean_image.GetRows());
mean_image.Reshape(1, -1);
Matrix::Dot(mean_pixel, mean_pixel, out_p, 0, 1, true, false);
pixel_cov.Subtract(out_p, pixel_cov);
mean_image.CopyToHost();
mean_pixel.CopyToHost();
cout << output_file << endl;
hid_t file = H5Fcreate(output_file.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
WriteHDF5CPU(file, mean_image.GetHostData(), 1, num_dims, "mean");
WriteHDF5CPU(file, mean_pixel.GetHostData(), 1, num_colors, "pixel_mean");
mean_batch.Mult(mean_batch);
mean_image.Mult(mean_image);
mean_pixel.Mult(mean_pixel);
var_batch.Subtract(mean_batch, var_batch);
var_batch.SumRows(var_image, 0, 1.0 / batch_size);
mean_batch.SumRows(var_image, 1, 1.0 / batch_size);
var_image.Subtract(mean_image, var_image);
var_image.Reshape(-1, num_colors);
mean_image.Reshape(-1, num_colors);
var_image.SumRows(var_pixel, 0, 1.0 / var_image.GetRows());
mean_image.SumRows(var_pixel, 1, 1.0 / var_image.GetRows());
var_pixel.Subtract(mean_pixel, var_pixel);
var_image.Reshape(1, -1);
mean_image.Reshape(1, -1);
var_image.Sqrt();
var_pixel.Sqrt();
var_image.CopyToHost();
var_pixel.CopyToHost();
WriteHDF5CPU(file, var_image.GetHostData(), 1, num_dims, "std");
WriteHDF5CPU(file, var_pixel.GetHostData(), 1, num_colors, "pixel_std");
Matrix::Dot(var_pixel, var_pixel, out_p, 0, 1, true, false);
pixel_cov.Divide(out_p);
pixel_cov.CopyToHost();
WriteHDF5CPU(file, pixel_cov.GetHostData(), num_colors, num_colors, "pixel_cov");
H5Fclose(file);
return 0;
}
<commit_msg>Edited compute mean usage description.<commit_after>#include "layer.h"
#include "datahandler.h"
#include <opencv2/core.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
const char *keys =
"{ board b || GPU board(s): 0 or 012, etc. }"
"{ data d || Data pbtxt file }"
"{ layer l || Layer pbtxt file }"
"{ output o || Output hdf5 file }";
CommandLineParser parser(argc, argv, keys);
string board(parser.get<string>("board"));
string data_config_file(parser.get<string>("data"));
string layer_config_file(parser.get<string>("layer"));
string output_file(parser.get<string>("output"));
if (board.empty() || data_config_file.empty() || layer_config_file.empty() || output_file.empty()) {
parser.printMessage();
return 1;
}
vector<int> boards;
ParseBoardIds(board, boards);
Matrix::SetupCUDADevice(boards[0]);
cout << "Using board " << boards[0] << endl;
config::DatasetConfig data_config;
ReadPbtxt<config::DatasetConfig>(data_config_file, data_config);
DataHandler* dataset_ = new DataHandler(data_config);
int batch_size = dataset_->GetBatchSize();
int dataset_size = dataset_->GetDataSetSize();
dataset_->AllocateMemory();
cout << "Data set size " << dataset_size << endl;
config::Layer layer_config;
ReadPbtxt<config::Layer>(layer_config_file, layer_config);
Layer *l = Layer::ChooseLayerClass(layer_config);
int num_colors = l->GetNumChannels();
int image_size_y = dataset_->GetImageSizeY(l->GetName());
int image_size_x = dataset_->GetImageSizeX(l->GetName());
l->SetSize(image_size_y, image_size_x, 1);
l->AllocateMemory(batch_size);
vector<Layer*> layers;
layers.push_back(l);
int num_batches = dataset_size / batch_size;
cout << "Image size " << image_size_y << "x" << image_size_x << endl;
Matrix& state = l->GetState();
int num_dims = state.GetCols();
Matrix mean_batch, mean_image, mean_pixel;
Matrix var_batch, var_image, var_pixel;
mean_batch.AllocateGPUMemory(batch_size, num_dims);
mean_image.AllocateGPUMemory(1, num_dims);
mean_pixel.AllocateGPUMemory(1, num_colors);
var_batch.AllocateGPUMemory(batch_size, num_dims);
var_image.AllocateGPUMemory(1, num_dims);
var_pixel.AllocateGPUMemory(1, num_colors);
Matrix pixel_cov, out_p;
pixel_cov.AllocateGPUMemory(num_colors, num_colors);
out_p.AllocateGPUMemory(num_colors, num_colors);
int num_pix = num_dims / num_colors;
mean_batch.Set(0);
var_batch.Set(0);
pixel_cov.Set(0);
cout << "Num batches " << num_batches << endl;
for (int k = 0; k < num_batches; k++) {
cout << "\r" << k+1;
cout.flush();
dataset_->GetBatch(layers);
mean_batch.Add(state);
state.Reshape(-1, num_colors);
Matrix::Dot(state, state, pixel_cov, 1, 1.0 / (batch_size * num_pix) , true, false);
state.Reshape(batch_size, -1);
state.Mult(state);
var_batch.Add(state);
}
dataset_->Sync();
cout << endl;
mean_batch.Divide(num_batches);
var_batch.Divide(num_batches);
pixel_cov.Divide(num_batches);
mean_batch.SumRows(mean_image, 0, 1.0 / batch_size);
mean_image.Reshape(-1, num_colors);
mean_image.SumRows(mean_pixel, 0, 1.0 / mean_image.GetRows());
mean_image.Reshape(1, -1);
Matrix::Dot(mean_pixel, mean_pixel, out_p, 0, 1, true, false);
pixel_cov.Subtract(out_p, pixel_cov);
mean_image.CopyToHost();
mean_pixel.CopyToHost();
cout << output_file << endl;
hid_t file = H5Fcreate(output_file.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
WriteHDF5CPU(file, mean_image.GetHostData(), 1, num_dims, "mean");
WriteHDF5CPU(file, mean_pixel.GetHostData(), 1, num_colors, "pixel_mean");
mean_batch.Mult(mean_batch);
mean_image.Mult(mean_image);
mean_pixel.Mult(mean_pixel);
var_batch.Subtract(mean_batch, var_batch);
var_batch.SumRows(var_image, 0, 1.0 / batch_size);
mean_batch.SumRows(var_image, 1, 1.0 / batch_size);
var_image.Subtract(mean_image, var_image);
var_image.Reshape(-1, num_colors);
mean_image.Reshape(-1, num_colors);
var_image.SumRows(var_pixel, 0, 1.0 / var_image.GetRows());
mean_image.SumRows(var_pixel, 1, 1.0 / var_image.GetRows());
var_pixel.Subtract(mean_pixel, var_pixel);
var_image.Reshape(1, -1);
mean_image.Reshape(1, -1);
var_image.Sqrt();
var_pixel.Sqrt();
var_image.CopyToHost();
var_pixel.CopyToHost();
WriteHDF5CPU(file, var_image.GetHostData(), 1, num_dims, "std");
WriteHDF5CPU(file, var_pixel.GetHostData(), 1, num_colors, "pixel_std");
Matrix::Dot(var_pixel, var_pixel, out_p, 0, 1, true, false);
pixel_cov.Divide(out_p);
pixel_cov.CopyToHost();
WriteHDF5CPU(file, pixel_cov.GetHostData(), num_colors, num_colors, "pixel_cov");
H5Fclose(file);
return 0;
}
<|endoftext|>
|
<commit_before>#include "siprouting.h"
#include <QSettings>
#include "common.h"
SIPRouting::SIPRouting(std::shared_ptr<TCPConnection> connection):
connection_(connection),
contactAddress_(""),
contactPort_(0),
first_(true)
{}
void SIPRouting::processOutgoingRequest(SIPRequest& request, QVariant& content)
{
Q_UNUSED(content)
printNormal(this, "Processing outgoing request");
if (connection_ == nullptr)
{
printProgramError(this, "No connection set!");
return;
}
// TODO: Handle this better
if (!connection_->isConnected())
{
printWarning(this, "Socket not connected");
return;
}
if (request.method != SIP_CANCEL)
{
addVia(request.method, request.message,
connection_->localAddress(),
connection_->localPort());
}
else
{
request.message->vias.push_front(previousVia_);
}
if (request.method == SIP_INVITE)
{
addContactField(request.message,
connection_->localAddress(),
connection_->localPort(),
DEFAULT_SIP_TYPE);
}
emit outgoingRequest(request, content);
}
void SIPRouting::processOutgoingResponse(SIPResponse& response, QVariant& content)
{
Q_UNUSED(content)
printNormal(this, "Processing outgoing response");
// TODO: Handle this better
if (!connection_->isConnected())
{
printWarning(this, "Socket not connected");
return;
}
if (response.message->cSeq.method == SIP_INVITE && response.type == SIP_OK)
{
addContactField(response.message,
connection_->localAddress(),
connection_->localPort(),
DEFAULT_SIP_TYPE);
}
emit outgoingResponse(response, content);
}
void SIPRouting::processIncomingResponse(SIPResponse& response, QVariant& content)
{
Q_UNUSED(content)
if (connection_ && connection_->isConnected())
{
processResponseViaFields(response.message->vias,
connection_->localAddress(),
connection_->localPort());
}
else
{
printError(this, "Not connected when checking response via field");
}
emit incomingResponse(response, content);
}
void SIPRouting::processResponseViaFields(QList<ViaField>& vias,
QString localAddress,
uint16_t localPort)
{
// find the via with our address and port
for (ViaField& via : vias)
{
if (via.sentBy == localAddress && via.port == localPort)
{
printNormal(this, "Found our via. This is meant for us!");
if (via.rportValue != 0 && via.receivedAddress != "")
{
printNormal(this, "Found our received address and rport",
{"Address"}, {via.receivedAddress + ":" + QString::number(via.rportValue)});
// we do not update our address, because we want to remove this registration
// first before updating.
if (first_)
{
first_ = false;
}
else
{
contactAddress_ = via.receivedAddress;
contactPort_ = via.rportValue;
}
}
return;
}
}
}
void SIPRouting::addVia(SIPRequestMethod type,
std::shared_ptr<SIPMessageHeader> message,
QString localAddress,
uint16_t localPort)
{
ViaField via = ViaField{SIP_VERSION, DEFAULT_TRANSPORT, localAddress, localPort,
QString(MAGIC_COOKIE + generateRandomString(BRANCH_TAIL_LENGTH)),
false, false, 0, "", {}};
message->vias.push_back(via);
if (type == SIP_INVITE || type == SIP_ACK)
{
message->vias.back().rport = true;
}
if (type == SIP_REGISTER)
{
message->vias.back().rport = true;
}
previousVia_ = message->vias.back();
}
void SIPRouting::addContactField(std::shared_ptr<SIPMessageHeader> message,
QString localAddress, uint16_t localPort,
SIPType type)
{
message->contact.push_back({{"", SIP_URI{type, {getLocalUsername(), ""}, {"", 0}, {}, {}}}, {}});
// use rport address and port if we have them, otherwise use localaddress
if (contactAddress_ != "")
{
message->contact.back().address.uri.hostport.host = contactAddress_;
}
else
{
message->contact.back().address.uri.hostport.host = localAddress;
}
if (contactPort_ != 0)
{
message->contact.back().address.uri.hostport.port = contactPort_;
}
else
{
message->contact.back().address.uri.hostport.port = localPort;
}
}
<commit_msg>feature(Transport): Add contact-field to REGISTER<commit_after>#include "siprouting.h"
#include <QSettings>
#include "common.h"
SIPRouting::SIPRouting(std::shared_ptr<TCPConnection> connection):
connection_(connection),
contactAddress_(""),
contactPort_(0),
first_(true)
{}
void SIPRouting::processOutgoingRequest(SIPRequest& request, QVariant& content)
{
Q_UNUSED(content)
printNormal(this, "Processing outgoing request");
if (connection_ == nullptr)
{
printProgramError(this, "No connection set!");
return;
}
// TODO: Handle this better
if (!connection_->isConnected())
{
printWarning(this, "Socket not connected");
return;
}
if (request.method != SIP_CANCEL)
{
addVia(request.method, request.message,
connection_->localAddress(),
connection_->localPort());
}
else
{
request.message->vias.push_front(previousVia_);
}
if (request.method == SIP_INVITE || request.method == SIP_REGISTER)
{
addContactField(request.message,
connection_->localAddress(),
connection_->localPort(),
DEFAULT_SIP_TYPE);
}
emit outgoingRequest(request, content);
}
void SIPRouting::processOutgoingResponse(SIPResponse& response, QVariant& content)
{
Q_UNUSED(content)
printNormal(this, "Processing outgoing response");
// TODO: Handle this better
if (!connection_->isConnected())
{
printWarning(this, "Socket not connected");
return;
}
if (response.message->cSeq.method == SIP_INVITE && response.type == SIP_OK)
{
addContactField(response.message,
connection_->localAddress(),
connection_->localPort(),
DEFAULT_SIP_TYPE);
}
emit outgoingResponse(response, content);
}
void SIPRouting::processIncomingResponse(SIPResponse& response, QVariant& content)
{
Q_UNUSED(content)
if (connection_ && connection_->isConnected())
{
processResponseViaFields(response.message->vias,
connection_->localAddress(),
connection_->localPort());
}
else
{
printError(this, "Not connected when checking response via field");
}
emit incomingResponse(response, content);
}
void SIPRouting::processResponseViaFields(QList<ViaField>& vias,
QString localAddress,
uint16_t localPort)
{
// find the via with our address and port
for (ViaField& via : vias)
{
if (via.sentBy == localAddress && via.port == localPort)
{
printNormal(this, "Found our via. This is meant for us!");
if (via.rportValue != 0 && via.receivedAddress != "")
{
printNormal(this, "Found our received address and rport",
{"Address"}, {via.receivedAddress + ":" + QString::number(via.rportValue)});
// we do not update our address, because we want to remove this registration
// first before updating.
if (first_)
{
first_ = false;
}
else
{
contactAddress_ = via.receivedAddress;
contactPort_ = via.rportValue;
}
}
return;
}
}
}
void SIPRouting::addVia(SIPRequestMethod type,
std::shared_ptr<SIPMessageHeader> message,
QString localAddress,
uint16_t localPort)
{
ViaField via = ViaField{SIP_VERSION, DEFAULT_TRANSPORT, localAddress, localPort,
QString(MAGIC_COOKIE + generateRandomString(BRANCH_TAIL_LENGTH)),
false, false, 0, "", {}};
message->vias.push_back(via);
if (type == SIP_INVITE || type == SIP_ACK)
{
message->vias.back().rport = true;
}
if (type == SIP_REGISTER)
{
message->vias.back().rport = true;
}
previousVia_ = message->vias.back();
}
void SIPRouting::addContactField(std::shared_ptr<SIPMessageHeader> message,
QString localAddress, uint16_t localPort,
SIPType type)
{
message->contact.push_back({{"", SIP_URI{type, {getLocalUsername(), ""}, {"", 0}, {}, {}}}, {}});
// use rport address and port if we have them, otherwise use localaddress
if (contactAddress_ != "")
{
message->contact.back().address.uri.hostport.host = contactAddress_;
}
else
{
message->contact.back().address.uri.hostport.host = localAddress;
}
if (contactPort_ != 0)
{
message->contact.back().address.uri.hostport.port = contactPort_;
}
else
{
message->contact.back().address.uri.hostport.port = localPort;
}
}
<|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 "AliMUONResponseV0.h"
#include "AliSegmentation.h"
#include <TMath.h>
#include <TRandom.h>
ClassImp(AliMUONResponseV0)
//__________________________________________________________________________
void AliMUONResponseV0::SetSqrtKx3AndDeriveKx2Kx4(Float_t SqrtKx3)
{
// Set to "SqrtKx3" the Mathieson parameter K3 ("fSqrtKx3")
// in the X direction, perpendicular to the wires,
// and derive the Mathieson parameters K2 ("fKx2") and K4 ("fKx4")
// in the same direction
fSqrtKx3 = SqrtKx3;
fKx2 = TMath::Pi() / 2. * (1. - 0.5 * fSqrtKx3);
Float_t cx1 = fKx2 * fSqrtKx3 / 4. / TMath::ATan(Double_t(fSqrtKx3));
fKx4 = cx1 / fKx2 / fSqrtKx3;
}
//__________________________________________________________________________
void AliMUONResponseV0::SetSqrtKy3AndDeriveKy2Ky4(Float_t SqrtKy3)
{
// Set to "SqrtKy3" the Mathieson parameter K3 ("fSqrtKy3")
// in the Y direction, along the wires,
// and derive the Mathieson parameters K2 ("fKy2") and K4 ("fKy4")
// in the same direction
fSqrtKy3 = SqrtKy3;
fKy2 = TMath::Pi() / 2. * (1. - 0.5 * fSqrtKy3);
Float_t cy1 = fKy2 * fSqrtKy3 / 4. / TMath::ATan(Double_t(fSqrtKy3));
fKy4 = cy1 / fKy2 / fSqrtKy3;
}
Float_t AliMUONResponseV0::IntPH(Float_t eloss)
{
// Calculate charge from given ionization energy loss
Int_t nel;
nel= Int_t(eloss*1.e9/27.4);
Float_t charge=0;
if (nel == 0) nel=1;
for (Int_t i=1;i<=nel;i++) {
Float_t arg=0.;
while(!arg) arg = gRandom->Rndm();
charge -= fChargeSlope*TMath::Log(arg);
}
return charge;
}
// -------------------------------------------
Float_t AliMUONResponseV0::IntXY(AliSegmentation * segmentation)
{
// Calculate charge on current pad according to Mathieson distribution
//
const Float_t kInversePitch = 1/fPitch;
//
// Integration limits defined by segmentation model
//
Float_t xi1, xi2, yi1, yi2;
segmentation->IntegrationLimits(xi1,xi2,yi1,yi2);
xi1=xi1*kInversePitch;
xi2=xi2*kInversePitch;
yi1=yi1*kInversePitch;
yi2=yi2*kInversePitch;
//
// The Mathieson function
Double_t ux1=fSqrtKx3*TMath::TanH(fKx2*xi1);
Double_t ux2=fSqrtKx3*TMath::TanH(fKx2*xi2);
Double_t uy1=fSqrtKy3*TMath::TanH(fKy2*yi1);
Double_t uy2=fSqrtKy3*TMath::TanH(fKy2*yi2);
return Float_t(4.*fKx4*(TMath::ATan(ux2)-TMath::ATan(ux1))*
fKy4*(TMath::ATan(uy2)-TMath::ATan(uy1)));
}
Int_t AliMUONResponseV0::DigitResponse(Int_t digit, AliMUONTransientDigit* /*where*/)
{
// add white noise and do zero-suppression and signal truncation
// Float_t meanNoise = gRandom->Gaus(1, 0.2);
// correct noise for slat chambers;
// one more field to add to AliMUONResponseV0 to allow different noises ????
Float_t meanNoise = gRandom->Gaus(1., 0.2);
Float_t noise = gRandom->Gaus(0., meanNoise);
digit+=(Int_t)noise;
if ( digit <= ZeroSuppression()) digit = 0.;
// if ( digit > MaxAdc()) digit=MaxAdc();
if ( digit > Saturation()) digit=Saturation();
return digit;
}
<commit_msg>Removing warning<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 "AliMUONResponseV0.h"
#include "AliSegmentation.h"
#include <TMath.h>
#include <TRandom.h>
ClassImp(AliMUONResponseV0)
//__________________________________________________________________________
void AliMUONResponseV0::SetSqrtKx3AndDeriveKx2Kx4(Float_t SqrtKx3)
{
// Set to "SqrtKx3" the Mathieson parameter K3 ("fSqrtKx3")
// in the X direction, perpendicular to the wires,
// and derive the Mathieson parameters K2 ("fKx2") and K4 ("fKx4")
// in the same direction
fSqrtKx3 = SqrtKx3;
fKx2 = TMath::Pi() / 2. * (1. - 0.5 * fSqrtKx3);
Float_t cx1 = fKx2 * fSqrtKx3 / 4. / TMath::ATan(Double_t(fSqrtKx3));
fKx4 = cx1 / fKx2 / fSqrtKx3;
}
//__________________________________________________________________________
void AliMUONResponseV0::SetSqrtKy3AndDeriveKy2Ky4(Float_t SqrtKy3)
{
// Set to "SqrtKy3" the Mathieson parameter K3 ("fSqrtKy3")
// in the Y direction, along the wires,
// and derive the Mathieson parameters K2 ("fKy2") and K4 ("fKy4")
// in the same direction
fSqrtKy3 = SqrtKy3;
fKy2 = TMath::Pi() / 2. * (1. - 0.5 * fSqrtKy3);
Float_t cy1 = fKy2 * fSqrtKy3 / 4. / TMath::ATan(Double_t(fSqrtKy3));
fKy4 = cy1 / fKy2 / fSqrtKy3;
}
Float_t AliMUONResponseV0::IntPH(Float_t eloss)
{
// Calculate charge from given ionization energy loss
Int_t nel;
nel= Int_t(eloss*1.e9/27.4);
Float_t charge=0;
if (nel == 0) nel=1;
for (Int_t i=1;i<=nel;i++) {
Float_t arg=0.;
while(!arg) arg = gRandom->Rndm();
charge -= fChargeSlope*TMath::Log(arg);
}
return charge;
}
// -------------------------------------------
Float_t AliMUONResponseV0::IntXY(AliSegmentation * segmentation)
{
// Calculate charge on current pad according to Mathieson distribution
//
const Float_t kInversePitch = 1/fPitch;
//
// Integration limits defined by segmentation model
//
Float_t xi1, xi2, yi1, yi2;
segmentation->IntegrationLimits(xi1,xi2,yi1,yi2);
xi1=xi1*kInversePitch;
xi2=xi2*kInversePitch;
yi1=yi1*kInversePitch;
yi2=yi2*kInversePitch;
//
// The Mathieson function
Double_t ux1=fSqrtKx3*TMath::TanH(fKx2*xi1);
Double_t ux2=fSqrtKx3*TMath::TanH(fKx2*xi2);
Double_t uy1=fSqrtKy3*TMath::TanH(fKy2*yi1);
Double_t uy2=fSqrtKy3*TMath::TanH(fKy2*yi2);
return Float_t(4.*fKx4*(TMath::ATan(ux2)-TMath::ATan(ux1))*
fKy4*(TMath::ATan(uy2)-TMath::ATan(uy1)));
}
Int_t AliMUONResponseV0::DigitResponse(Int_t digit, AliMUONTransientDigit* /*where*/)
{
// add white noise and do zero-suppression and signal truncation
// Float_t meanNoise = gRandom->Gaus(1, 0.2);
// correct noise for slat chambers;
// one more field to add to AliMUONResponseV0 to allow different noises ????
Float_t meanNoise = gRandom->Gaus(1., 0.2);
Float_t noise = gRandom->Gaus(0., meanNoise);
digit+=(Int_t)noise;
if ( digit <= ZeroSuppression()) digit = 0;
// if ( digit > MaxAdc()) digit=MaxAdc();
if ( digit > Saturation()) digit=Saturation();
return digit;
}
<|endoftext|>
|
<commit_before>#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
viewer->addImportPath(QLatin1String("modules")); // ADDIMPORTPATH
viewer->setOrientation(QmlApplicationViewer::ScreenOrientationAuto); // ORIENTATION
viewer->setMainQmlFile(QLatin1String("qml/app/main.qml")); // MAINQML
viewer->showExpanded();
return app->exec();
}
<commit_msg>Fix default mainqmlfile in the qtquickapp template<commit_after>#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
viewer->addImportPath(QLatin1String("modules")); // ADDIMPORTPATH
viewer->setOrientation(QmlApplicationViewer::ScreenOrientationAuto); // ORIENTATION
viewer->setMainQmlFile(QLatin1String("qml/app/qtquick10/main.qml")); // MAINQML
viewer->showExpanded();
return app->exec();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "CommPool.h"
#include "TCPConnector.h"
#include "MemPool.h"
using namespace std;
//1024 * 6
#define BUFF_SIZE 6144
#define MAX_PKGLEN 1<<16
namespace KxServer {
char* CTCPConnector::g_RecvBuffer = NULL;
CTCPConnector::CTCPConnector(char* addr, int port, ICommunicationPoller* poller)
:m_Socket(NULL),
m_SendBuffer(NULL),
m_RecvBuffer(NULL),
m_SendBufferLen(0),
m_RecvBufferLen(0),
m_SendBufferOffset(0),
m_RecvBufferOffset(0)
{
//ȫֵĽջ
if (NULL == g_RecvBuffer)
{
g_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(BUFF_SIZE);
}
m_PollType = POLLTYPE_UNKNOWN;
m_Socket = new CBaseSocket(SOCKET_TYPETCP);
m_Socket->SocketInit();
m_Socket->SocketNonBlock(true);
if (NULL != poller)
{
m_Poller = poller;
m_Poller->AddPollObject(this, POLLTYPE_IN);
}
CCommPool::GetInstance()->AddCommuncation(this);
m_Socket->SocketConnect(addr, port);
}
CTCPConnector::~CTCPConnector(void)
{
delete m_Socket;
if (NULL != m_SendBuffer)
{
CMemManager::GetInstance()->MemRecycle(m_SendBuffer, m_SendBufferLen);
}
if (NULL != m_RecvBuffer)
{
CMemManager::GetInstance()->MemRecycle(m_RecvBuffer, m_SendBufferLen);
}
//clear list and data in list
BufferNode* node = m_BufferList.Head();
while(NULL != node)
{
CMemManager::GetInstance()->MemRecycle(node->buffer, node->len);
//delete[] node->buffer;
delete node;
node = m_BufferList.Next();
}
}
//call by user
int CTCPConnector::Send(char* buffer, unsigned int len)
{
int ret = 0;
//no buffer need to send before, or call by OnSend
if (NULL == m_SendBuffer
|| buffer == (m_SendBuffer + m_SendBufferOffset))
{
ret = m_Socket->SocketSend(buffer, len);
}
if(ret <= 0)
{
//if no eagain or ewouldblock
if(m_Socket->IsSocketError()
&& !(m_PollType & POLLTYPE_IN))
{
//user call send, should call OnError
//poller call send, should no call OnError
//socket invalid remove from poll, destroy this
if(NULL != m_Poller)
{
m_Poller->RemovePollObject(this);
}
OnError();
return ret;
}
else
{
//you need send all buffer again
ret = 0;
}
}
if (ret < (int)len)
{
//save to buffer and add pollout
if (NULL != m_Poller
&& ( NULL == m_SendBuffer || buffer != (m_SendBuffer + m_SendBufferOffset)))
{
len -= ret;
char* buf = (char*)CMemManager::GetInstance()->MemAlocate(len);
memcpy(buf, buffer + ret, len);
m_BufferList.PushBack(buf, len);
m_Poller->AddPollObject(this, POLLTYPE_OUT);
}
}
return ret;
}
//call by framework
int CTCPConnector::Recv(char* buffer, unsigned int len)
{
int ret = m_Socket->SocketRecv(buffer, len);
//when ret = 0, socket has been close
if (ret <= 0)
{
if (m_Socket->IsSocketError())
{
//close
ret = -1;
}
else
{
ret = 0;
}
}
return ret;
}
//get communication id, maybe fd int type int linux or SOCKET type in windows
COMMUNICATIONID CTCPConnector::GetCommunicationID()
{
return m_Socket->GetSocket();
}
//call by poller
int CTCPConnector::OnRecv()
{
//recv to globa buffer
memset(g_RecvBuffer, 0, BUFF_SIZE);
int requestLen = 0;
int ret = Recv(g_RecvBuffer, BUFF_SIZE);
//if ret < 0
if (NULL != m_ProcessModule && ret > 0)
{
char* processBuf = g_RecvBuffer;
char* stickBuf = NULL;
//а
if (NULL != m_RecvBuffer)
{
//append to my recvbuffer
unsigned int newsize = ret;
if ((m_RecvBufferLen - m_RecvBufferOffset) < (unsigned int)ret)
{
newsize = m_RecvBufferLen - m_RecvBufferOffset;
//
stickBuf = processBuf + newsize;
}
memcpy(m_RecvBuffer + m_RecvBufferOffset, processBuf, newsize);
//ret all buffer length
ret += m_RecvBufferOffset;
m_RecvBufferOffset += newsize;
processBuf = m_RecvBuffer;
}
requestLen = m_ProcessModule->RequestLen(processBuf, ret);
if (requestLen <= 0 || requestLen > MAX_PKGLEN)
{
//package data error, close socket
return requestLen;
}
if (ret < requestLen)
{
//copy to recv buffer
if (NULL == m_RecvBuffer)
{
m_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(requestLen);
m_RecvBufferLen = requestLen;
m_RecvBufferOffset = ret;
memcpy(m_RecvBuffer, processBuf, ret);
}
//has been append
return ret;
}
while (ret >= requestLen)
{
m_ProcessModule->Process(processBuf, requestLen, this);
//move to next package
processBuf += requestLen;
if (NULL != m_RecvBuffer)
{
processBuf = stickBuf;
CMemManager::GetInstance()->MemRecycle(m_RecvBuffer, m_RecvBufferLen);
m_RecvBuffer = NULL;
m_RecvBufferOffset = m_RecvBufferLen = 0;
}
ret -= requestLen;
if (ret > 0)
{
//next
requestLen = m_ProcessModule->RequestLen(processBuf, ret);
if (requestLen <= 0 || requestLen > MAX_PKGLEN)
{
return requestLen;
}
//
else if (ret < requestLen)
{
m_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(requestLen);
m_RecvBufferLen = requestLen;
m_RecvBufferOffset = ret;
memcpy(m_RecvBuffer, processBuf, ret);
return ret;
}
}
}
}
return ret;
}
//call by poller
int CTCPConnector::OnSend()
{
again:
if (NULL == m_SendBuffer)
{
BufferNode* node = m_BufferList.Next();
if (NULL != node)
{
m_SendBuffer = node->buffer;
m_SendBufferLen = node->len;
m_SendBufferOffset = 0;
delete node;
}
else
{
//nothing need to send
return 0;
}
}
//if the socket invalid, len will be -1
int len = Send(m_SendBuffer, m_SendBufferLen);
//send finish
if(len >= (int)(m_SendBufferLen - m_SendBufferOffset))
{
CMemManager::GetInstance()->MemRecycle(m_SendBuffer, m_SendBufferLen);
BufferNode* node = m_BufferList.Head();
m_SendBuffer = NULL;
m_SendBufferLen = m_SendBufferOffset = 0;
if (NULL == node)
{
//don't send again
m_Poller->ModifyPollObject(this, POLLTYPE_IN);
}
//send next
else
{
goto again;
}
}
//send half, try again
//len < m_SendBufferLen - m_SendBufferOffset && len >= 0
else if(len < (int)(m_SendBufferLen - m_SendBufferOffset) && len >= 0)
{
//Send Again
m_SendBufferOffset += len;
m_Poller->ModifyPollObject(this, m_PollType | POLLTYPE_OUT);
}
return len;
}
//call by poller
int CTCPConnector::OnError()
{
if (NULL != m_ProcessModule)
{
m_ProcessModule->ProcessError(this);
}
//socket is invalid must be close
CCommPool::GetInstance()->RemoveCommuncation(GetCommunicationID());
return 0;
}
void CTCPConnector::Close()
{
if (NULL != m_Poller)
{
m_Poller->RemovePollObject(this);
}
CCommPool::GetInstance()->RemoveCommuncation(GetCommunicationID());
}
}
<commit_msg>Update TCPConnector.cpp<commit_after>#include <iostream>
#include "CommPool.h"
#include "TCPConnector.h"
#include "MemPool.h"
using namespace std;
//1024 * 6
#define BUFF_SIZE 6144
#define MAX_PKGLEN 1<<16
namespace KxServer {
char* CTCPConnector::g_RecvBuffer = NULL;
CTCPConnector::CTCPConnector(char* addr, int port, ICommunicationPoller* poller)
:m_Socket(NULL),
m_SendBuffer(NULL),
m_RecvBuffer(NULL),
m_SendBufferLen(0),
m_RecvBufferLen(0),
m_SendBufferOffset(0),
m_RecvBufferOffset(0)
{
//分配全局的接收缓冲区
if (NULL == g_RecvBuffer)
{
g_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(BUFF_SIZE);
}
m_PollType = POLLTYPE_UNKNOWN;
m_Socket = new CBaseSocket(SOCKET_TYPETCP);
m_Socket->SocketInit();
m_Socket->SocketNonBlock(true);
if (NULL != poller)
{
m_Poller = poller;
m_Poller->AddPollObject(this, POLLTYPE_IN);
}
CCommPool::GetInstance()->AddCommuncation(this);
m_Socket->SocketConnect(addr, port);
}
CTCPConnector::~CTCPConnector(void)
{
delete m_Socket;
if (NULL != m_SendBuffer)
{
CMemManager::GetInstance()->MemRecycle(m_SendBuffer, m_SendBufferLen);
}
if (NULL != m_RecvBuffer)
{
CMemManager::GetInstance()->MemRecycle(m_RecvBuffer, m_SendBufferLen);
}
//clear list and data in list
BufferNode* node = m_BufferList.Head();
while(NULL != node)
{
CMemManager::GetInstance()->MemRecycle(node->buffer, node->len);
//delete[] node->buffer;
delete node;
node = m_BufferList.Next();
}
}
//call by user
int CTCPConnector::Send(char* buffer, unsigned int len)
{
int ret = 0;
//no buffer need to send before, or call by OnSend
if (NULL == m_SendBuffer
|| buffer == (m_SendBuffer + m_SendBufferOffset))
{
ret = m_Socket->SocketSend(buffer, len);
}
if(ret <= 0)
{
//if no eagain or ewouldblock
if(m_Socket->IsSocketError()
&& !(m_PollType & POLLTYPE_IN))
{
//user call send, should call OnError
//poller call send, should no call OnError
//socket invalid remove from poll, destroy this
if(NULL != m_Poller)
{
m_Poller->RemovePollObject(this);
}
OnError();
return ret;
}
else
{
//you need send all buffer again
ret = 0;
}
}
if (ret < (int)len)
{
//save to buffer and add pollout
if (NULL != m_Poller
&& ( NULL == m_SendBuffer || buffer != (m_SendBuffer + m_SendBufferOffset)))
{
len -= ret;
char* buf = (char*)CMemManager::GetInstance()->MemAlocate(len);
memcpy(buf, buffer + ret, len);
m_BufferList.PushBack(buf, len);
m_Poller->AddPollObject(this, POLLTYPE_OUT);
}
}
return ret;
}
//call by framework
int CTCPConnector::Recv(char* buffer, unsigned int len)
{
int ret = m_Socket->SocketRecv(buffer, len);
//when ret = 0, socket has been close
if (ret <= 0)
{
if (m_Socket->IsSocketError())
{
//close
ret = -1;
}
else
{
ret = 0;
}
}
return ret;
}
//get communication id, maybe fd int type int linux or SOCKET type in windows
COMMUNICATIONID CTCPConnector::GetCommunicationID()
{
return m_Socket->GetSocket();
}
//call by poller
int CTCPConnector::OnRecv()
{
//recv to globa buffer
int requestLen = 0;
int ret = Recv(g_RecvBuffer, BUFF_SIZE);
//if ret < 0
if (NULL != m_ProcessModule && ret > 0)
{
char* processBuf = g_RecvBuffer;
char* stickBuf = NULL;
//如果有半包
if (NULL != m_RecvBuffer)
{
//append to my recvbuffer
unsigned int newsize = ret;
if ((m_RecvBufferLen - m_RecvBufferOffset) < (unsigned int)ret)
{
newsize = m_RecvBufferLen - m_RecvBufferOffset;
//后面的连包
stickBuf = processBuf + newsize;
}
memcpy(m_RecvBuffer + m_RecvBufferOffset, processBuf, newsize);
//ret all buffer length
ret += m_RecvBufferOffset;
m_RecvBufferOffset += newsize;
processBuf = m_RecvBuffer;
}
requestLen = m_ProcessModule->RequestLen(processBuf, ret);
if (requestLen <= 0 || requestLen > MAX_PKGLEN)
{
//package data error, close socket
return requestLen;
}
if (ret < requestLen)
{
//copy to recv buffer
if (NULL == m_RecvBuffer)
{
m_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(requestLen);
m_RecvBufferLen = requestLen;
m_RecvBufferOffset = ret;
memcpy(m_RecvBuffer, processBuf, ret);
}
//has been append
return ret;
}
while (ret >= requestLen)
{
m_ProcessModule->Process(processBuf, requestLen, this);
//move to next package
processBuf += requestLen;
if (NULL != m_RecvBuffer)
{
processBuf = stickBuf;
CMemManager::GetInstance()->MemRecycle(m_RecvBuffer, m_RecvBufferLen);
m_RecvBuffer = NULL;
m_RecvBufferOffset = m_RecvBufferLen = 0;
}
ret -= requestLen;
if (ret > 0)
{
//next
requestLen = m_ProcessModule->RequestLen(processBuf, ret);
if (requestLen <= 0 || requestLen > MAX_PKGLEN)
{
return requestLen;
}
//半包缓存
else if (ret < requestLen)
{
m_RecvBuffer = (char*)CMemManager::GetInstance()->MemAlocate(requestLen);
m_RecvBufferLen = requestLen;
m_RecvBufferOffset = ret;
memcpy(m_RecvBuffer, processBuf, ret);
return ret;
}
}
}
}
return ret;
}
//call by poller
int CTCPConnector::OnSend()
{
again:
if (NULL == m_SendBuffer)
{
BufferNode* node = m_BufferList.Next();
if (NULL != node)
{
m_SendBuffer = node->buffer;
m_SendBufferLen = node->len;
m_SendBufferOffset = 0;
delete node;
}
else
{
//nothing need to send
return 0;
}
}
//if the socket invalid, len will be -1
int len = Send(m_SendBuffer, m_SendBufferLen);
//send finish
if(len >= (int)(m_SendBufferLen - m_SendBufferOffset))
{
CMemManager::GetInstance()->MemRecycle(m_SendBuffer, m_SendBufferLen);
BufferNode* node = m_BufferList.Head();
m_SendBuffer = NULL;
m_SendBufferLen = m_SendBufferOffset = 0;
if (NULL == node)
{
//don't send again
m_Poller->ModifyPollObject(this, POLLTYPE_IN);
}
//send next
else
{
goto again;
}
}
//send half, try again
//len < m_SendBufferLen - m_SendBufferOffset && len >= 0
else if(len < (int)(m_SendBufferLen - m_SendBufferOffset) && len >= 0)
{
//Send Again
m_SendBufferOffset += len;
m_Poller->ModifyPollObject(this, m_PollType | POLLTYPE_OUT);
}
return len;
}
//call by poller
int CTCPConnector::OnError()
{
if (NULL != m_ProcessModule)
{
m_ProcessModule->ProcessError(this);
}
//socket is invalid must be close
CCommPool::GetInstance()->RemoveCommuncation(GetCommunicationID());
return 0;
}
void CTCPConnector::Close()
{
if (NULL != m_Poller)
{
m_Poller->RemovePollObject(this);
}
CCommPool::GetInstance()->RemoveCommuncation(GetCommunicationID());
}
}
<|endoftext|>
|
<commit_before>#include "rapid_utils/command_line.h"
#include <iostream>
#include "boost/algorithm/string.hpp"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
namespace rapid {
namespace utils {
void ExitCommand::Execute(const std::vector<std::string>& args) {}
std::string ExitCommand::name() const { return "exit"; }
std::string ExitCommand::description() const { return "- Exit this interface"; }
CommandLine::CommandLine() : name_(""), commands_() {}
CommandLine::CommandLine(const std::string& name) : name_(name), commands_() {}
void CommandLine::AddCommand(CommandInterface* command) {
commands_.push_back(command);
}
bool CommandLine::Next() {
ShowCommands();
cout << "Enter a command: ";
string input;
if (std::getline(std::cin, input)) {
cout << endl;
} else {
cout << endl;
return false;
}
CommandInterface* command;
vector<string> args;
bool valid = ParseLine(input, &command, &args);
if (valid) {
if (command->name() == "exit") {
return false;
}
command->Execute(args);
cout << endl;
} else {
cout << "Invalid command." << endl;
cout << endl;
}
return true;
}
void CommandLine::ShowCommands() const {
if (name_ != "") {
cout << name_ << " - ";
}
cout << "Commands:" << endl;
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
cout << " " << command->name() << " " << command->description() << endl;
}
}
bool CommandLine::ParseLine(const std::string& line,
CommandInterface** command_pp,
std::vector<std::string>* args) const {
vector<string> tokens;
boost::split(tokens, line, boost::is_space());
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
int match_length = ParseCommand(tokens, command->name());
if (match_length == 0) {
continue;
}
// At this point, we have a matching command, which we return.
*command_pp = command;
args->clear();
for (size_t j = match_length; j < tokens.size(); ++j) {
args->push_back(tokens[j]);
}
return true;
}
return false;
}
int CommandLine::ParseCommand(const std::vector<std::string>& tokens,
const std::string& name) const {
vector<string> command_tokens;
boost::split(command_tokens, name, boost::is_space());
if (command_tokens.size() > tokens.size()) {
return 0;
}
for (size_t j = 0; j < command_tokens.size(); ++j) {
if (command_tokens[j] != tokens[j]) {
return 0;
}
}
return command_tokens.size();
}
} // namespace utils
} // namespace rapid
<commit_msg>Use readline for command lines.<commit_after>#include "rapid_utils/command_line.h"
#include <iostream>
#include "boost/algorithm/string.hpp"
#include "readline/history.h"
#include "readline/readline.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
namespace rapid {
namespace utils {
void ExitCommand::Execute(const std::vector<std::string>& args) {}
std::string ExitCommand::name() const { return "exit"; }
std::string ExitCommand::description() const { return "- Exit this interface"; }
CommandLine::CommandLine() : name_(""), commands_() {}
CommandLine::CommandLine(const std::string& name) : name_(name), commands_() {}
void CommandLine::AddCommand(CommandInterface* command) {
commands_.push_back(command);
}
bool CommandLine::Next() {
ShowCommands();
char* line = readline("Enter a command: ");
add_history(line);
if (line) {
cout << endl;
} else {
cout << endl;
return false;
}
CommandInterface* command;
vector<string> args;
bool valid = ParseLine(std::string(line), &command, &args);
if (valid) {
if (command->name() == "exit") {
delete line;
return false;
}
command->Execute(args);
cout << endl;
} else {
cout << "Invalid command." << endl;
cout << endl;
}
delete line;
return true;
}
void CommandLine::ShowCommands() const {
if (name_ != "") {
cout << name_ << " - ";
}
cout << "Commands:" << endl;
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
cout << " " << command->name() << " " << command->description() << endl;
}
}
bool CommandLine::ParseLine(const std::string& line,
CommandInterface** command_pp,
std::vector<std::string>* args) const {
vector<string> tokens;
boost::split(tokens, line, boost::is_space());
for (size_t i = 0; i < commands_.size(); ++i) {
CommandInterface* command = commands_[i];
int match_length = ParseCommand(tokens, command->name());
if (match_length == 0) {
continue;
}
// At this point, we have a matching command, which we return.
*command_pp = command;
args->clear();
for (size_t j = match_length; j < tokens.size(); ++j) {
args->push_back(tokens[j]);
}
return true;
}
return false;
}
int CommandLine::ParseCommand(const std::vector<std::string>& tokens,
const std::string& name) const {
vector<string> command_tokens;
boost::split(command_tokens, name, boost::is_space());
if (command_tokens.size() > tokens.size()) {
return 0;
}
for (size_t j = 0; j < command_tokens.size(); ++j) {
if (command_tokens[j] != tokens[j]) {
return 0;
}
}
return command_tokens.size();
}
} // namespace utils
} // namespace rapid
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/url_request_context_getter.h"
#include "network_delegate.h"
#include "base/string_util.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
namespace brightray {
URLRequestContextGetter::URLRequestContextGetter(
const base::FilePath& base_path,
MessageLoop* io_loop,
MessageLoop* file_loop,
content::ProtocolHandlerMap* protocol_handlers)
: base_path_(base_path),
io_loop_(io_loop),
file_loop_(file_loop) {
// Must first be created on the UI thread.
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
std::swap(protocol_handlers_, *protocol_handlers);
proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(io_loop_->message_loop_proxy(), file_loop_));
}
URLRequestContextGetter::~URLRequestContextGetter() {
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext()
{
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
if (!url_request_context_.get()) {
url_request_context_.reset(new net::URLRequestContext());
network_delegate_.reset(new NetworkDelegate);
url_request_context_->set_network_delegate(network_delegate_.get());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
storage_->set_cookie_store(content::CreatePersistentCookieStore(
base_path_.Append(FILE_PATH_LITERAL("Cookies")),
false,
nullptr,
nullptr));
storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new net::StaticHttpUserAgentSettings(
"en-us,en", EmptyString()));
scoped_ptr<net::HostResolver> host_resolver(
net::HostResolver::CreateDefaultResolver(NULL));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
// TODO(jam): use v8 if possible, look at chrome code.
storage_->set_proxy_service(
net::ProxyService::CreateUsingSystemProxyResolver(
proxy_config_service_.release(),
0,
NULL));
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
storage_->set_http_server_properties(new net::HttpServerPropertiesImpl);
base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
cache_path,
0,
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.server_bound_cert_service =
url_request_context_->server_bound_cert_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors = false;
// Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
storage_->set_host_resolver(host_resolver.Pass());
network_session_params.host_resolver =
url_request_context_->host_resolver();
net::HttpCache* main_cache = new net::HttpCache(
network_session_params, main_backend);
storage_->set_http_transaction_factory(main_cache);
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
for (auto& it : protocol_handlers_) {
bool set_protocol = job_factory->SetProtocolHandler(it.first, it.second.release());
DCHECK(set_protocol);
}
protocol_handlers_.clear();
storage_->set_job_factory(job_factory.release());
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const
{
return content::BrowserThread::GetMessageLoopProxyForThread(content::BrowserThread::IO);
}
}
<commit_msg>Don't use range-based for loops<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/url_request_context_getter.h"
#include "network_delegate.h"
#include "base/string_util.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
namespace brightray {
URLRequestContextGetter::URLRequestContextGetter(
const base::FilePath& base_path,
MessageLoop* io_loop,
MessageLoop* file_loop,
content::ProtocolHandlerMap* protocol_handlers)
: base_path_(base_path),
io_loop_(io_loop),
file_loop_(file_loop) {
// Must first be created on the UI thread.
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
std::swap(protocol_handlers_, *protocol_handlers);
proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(io_loop_->message_loop_proxy(), file_loop_));
}
URLRequestContextGetter::~URLRequestContextGetter() {
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext()
{
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
if (!url_request_context_.get()) {
url_request_context_.reset(new net::URLRequestContext());
network_delegate_.reset(new NetworkDelegate);
url_request_context_->set_network_delegate(network_delegate_.get());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
storage_->set_cookie_store(content::CreatePersistentCookieStore(
base_path_.Append(FILE_PATH_LITERAL("Cookies")),
false,
nullptr,
nullptr));
storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
new net::DefaultServerBoundCertStore(NULL),
base::WorkerPool::GetTaskRunner(true)));
storage_->set_http_user_agent_settings(
new net::StaticHttpUserAgentSettings(
"en-us,en", EmptyString()));
scoped_ptr<net::HostResolver> host_resolver(
net::HostResolver::CreateDefaultResolver(NULL));
storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
// TODO(jam): use v8 if possible, look at chrome code.
storage_->set_proxy_service(
net::ProxyService::CreateUsingSystemProxyResolver(
proxy_config_service_.release(),
0,
NULL));
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
storage_->set_http_auth_handler_factory(
net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
storage_->set_http_server_properties(new net::HttpServerPropertiesImpl);
base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
cache_path,
0,
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::CACHE));
net::HttpNetworkSession::Params network_session_params;
network_session_params.cert_verifier =
url_request_context_->cert_verifier();
network_session_params.server_bound_cert_service =
url_request_context_->server_bound_cert_service();
network_session_params.proxy_service =
url_request_context_->proxy_service();
network_session_params.ssl_config_service =
url_request_context_->ssl_config_service();
network_session_params.http_auth_handler_factory =
url_request_context_->http_auth_handler_factory();
network_session_params.network_delegate =
url_request_context_->network_delegate();
network_session_params.http_server_properties =
url_request_context_->http_server_properties();
network_session_params.ignore_certificate_errors = false;
// Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
storage_->set_host_resolver(host_resolver.Pass());
network_session_params.host_resolver =
url_request_context_->host_resolver();
net::HttpCache* main_cache = new net::HttpCache(
network_session_params, main_backend);
storage_->set_http_transaction_factory(main_cache);
scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl());
for (auto it = protocol_handlers_.begin(),
end = protocol_handlers_.end(); it != end; ++it) {
bool set_protocol = job_factory->SetProtocolHandler(it->first, it->second.release());
DCHECK(set_protocol);
}
protocol_handlers_.clear();
storage_->set_job_factory(job_factory.release());
}
return url_request_context_.get();
}
scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const
{
return content::BrowserThread::GetMessageLoopProxyForThread(content::BrowserThread::IO);
}
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "extract/filewalk.hpp"
#include "config/cmd_args.hpp"
#include "errors.hpp"
#include "logger.hpp"
namespace extract {
void usage(const char *name) {
// Note: some error messages may refer to the names of command
// line options here, so keep them updated accordingly.
printf("Usage:\n");
printf(" %s [OPTIONS] -f data_file [-o dumpfile]\n", name);
printf("\nOptions:\n"
" -h --help Print these usage options.\n"
" --force-block-size Specifies block size, overriding file headers\n"
" --force-extent-size Specifies extent size, overriding file headers\n"
" --force-mod-count Specifies number of slices in *this* file,\n"
" overriding file headers.\n"
" -f --file Path to file or block device where part or all of\n"
" the database exists.\n"
" -l --log-file File to log to. If not provided, messages will be\n"
" printed to stderr.\n"
" -o --output-file File to which to output text memcached protocol\n"
" messages. This file must not already exist.\n");
printf(" Defaults to \"%s\"\n", EXTRACT_CONFIG_DEFAULT_OUTPUT_FILE);
exit(-1);
}
enum { force_block_size = 256, // Start these values above the ASCII range.
force_extent_size,
force_mod_count
};
void parse_cmd_args(int argc, char **argv, extract_config_t *config) {
config->init();
optind = 1; // reinit getopt.
for (;;) {
int do_help = 0;
struct option long_options[] =
{
{"force-block-size", required_argument, 0, force_block_size},
{"force-extent-size", required_argument, 0, force_extent_size},
{"force-mod-count", required_argument, 0, force_mod_count},
{"file", required_argument, 0, 'f'},
{"log-file", required_argument, 0, 'l'},
{"output-file", required_argument, 0, 'o'},
{"help", no_argument, &do_help, 1},
{0, 0, 0, 0}
};
int option_index = 0;
int c = getopt_long(argc, argv, "f:l:o:h", long_options, &option_index);
if (do_help) {
c = 'h';
}
// Detect the end of the options.
if (c == -1)
break;
switch (c) {
case 0:
break;
case 'f':
config->input_files.push_back(optarg);
break;
case 'l':
config->log_file_name = optarg;
break;
case 'o':
config->output_file = optarg;
break;
case force_block_size: {
char *endptr;
config->overrides.block_size = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.block_size <= 0) {
fail("Block size must be a positive integer.\n");
}
} break;
case force_extent_size: {
char *endptr;
config->overrides.extent_size = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.extent_size <= 0) {
fail("Extent size must be a positive integer.\n");
}
} break;
case force_mod_count: {
char *endptr;
config->overrides.mod_count = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.mod_count <= 0) {
fail("The mod count must be a positive integer.\n");
}
} break;
case 'h':
usage(argv[0]);
break;
default:
// getopt_long already printed an error message.
usage(argv[0]);
}
}
if (optind < argc) {
fail("Unexpected extra argument: \"%s\"", argv[optind]);
}
// Sanity-check the input.
if (config->input_files.empty()) {
fail("A path must be specified with -f.");
}
if (config->overrides.any() && config->input_files.size() >= 2) {
fail("--force-* options can only be used with one file at a time.");
}
}
} // namespace extract
int main(int argc, char **argv) {
install_generic_crash_handler();
extract_config_t config;
extract::parse_cmd_args(argc, argv, &config);
if (config.log_file_name != "") {
log_file = fopen(config.log_file_name.c_str(), "w");
}
// Initial CPU message to start server
struct server_starter_t :
public cpu_message_t
{
extract_config_t *config;
thread_pool_t *pool;
void on_cpu_switch() {
dumpfile(*config);
pool->shutdown();
}
} starter;
starter.config = &config;
// Run the server
thread_pool_t thread_pool(1);
starter.pool = &thread_pool;
thread_pool.run(&starter);
return 0;
}
<commit_msg>Removed useless thread_pool and server_starter_t stuff in the single-threaded executable rethinkdb-extract.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "extract/filewalk.hpp"
#include "config/cmd_args.hpp"
#include "errors.hpp"
#include "logger.hpp"
namespace extract {
void usage(const char *name) {
// Note: some error messages may refer to the names of command
// line options here, so keep them updated accordingly.
printf("Usage:\n");
printf(" %s [OPTIONS] -f data_file [-o dumpfile]\n", name);
printf("\nOptions:\n"
" -h --help Print these usage options.\n"
" --force-block-size Specifies block size, overriding file headers\n"
" --force-extent-size Specifies extent size, overriding file headers\n"
" --force-mod-count Specifies number of slices in *this* file,\n"
" overriding file headers.\n"
" -f --file Path to file or block device where part or all of\n"
" the database exists.\n"
" -l --log-file File to log to. If not provided, messages will be\n"
" printed to stderr.\n"
" -o --output-file File to which to output text memcached protocol\n"
" messages. This file must not already exist.\n");
printf(" Defaults to \"%s\"\n", EXTRACT_CONFIG_DEFAULT_OUTPUT_FILE);
exit(-1);
}
enum { force_block_size = 256, // Start these values above the ASCII range.
force_extent_size,
force_mod_count
};
void parse_cmd_args(int argc, char **argv, extract_config_t *config) {
config->init();
optind = 1; // reinit getopt.
for (;;) {
int do_help = 0;
struct option long_options[] =
{
{"force-block-size", required_argument, 0, force_block_size},
{"force-extent-size", required_argument, 0, force_extent_size},
{"force-mod-count", required_argument, 0, force_mod_count},
{"file", required_argument, 0, 'f'},
{"log-file", required_argument, 0, 'l'},
{"output-file", required_argument, 0, 'o'},
{"help", no_argument, &do_help, 1},
{0, 0, 0, 0}
};
int option_index = 0;
int c = getopt_long(argc, argv, "f:l:o:h", long_options, &option_index);
if (do_help) {
c = 'h';
}
// Detect the end of the options.
if (c == -1)
break;
switch (c) {
case 0:
break;
case 'f':
config->input_files.push_back(optarg);
break;
case 'l':
config->log_file_name = optarg;
break;
case 'o':
config->output_file = optarg;
break;
case force_block_size: {
char *endptr;
config->overrides.block_size = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.block_size <= 0) {
fail("Block size must be a positive integer.\n");
}
} break;
case force_extent_size: {
char *endptr;
config->overrides.extent_size = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.extent_size <= 0) {
fail("Extent size must be a positive integer.\n");
}
} break;
case force_mod_count: {
char *endptr;
config->overrides.mod_count = strtol(optarg, &endptr, 10);
if (*endptr != '\0' || config->overrides.mod_count <= 0) {
fail("The mod count must be a positive integer.\n");
}
} break;
case 'h':
usage(argv[0]);
break;
default:
// getopt_long already printed an error message.
usage(argv[0]);
}
}
if (optind < argc) {
fail("Unexpected extra argument: \"%s\"", argv[optind]);
}
// Sanity-check the input.
if (config->input_files.empty()) {
fail("A path must be specified with -f.");
}
if (config->overrides.any() && config->input_files.size() >= 2) {
fail("--force-* options can only be used with one file at a time.");
}
}
} // namespace extract
int main(int argc, char **argv) {
install_generic_crash_handler();
extract_config_t config;
extract::parse_cmd_args(argc, argv, &config);
if (config.log_file_name != "") {
log_file = fopen(config.log_file_name.c_str(), "w");
}
dumpfile(config);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <dirent.h>
#include <sys/stat.h>
#include <CoreServices/CoreServices.h>
#include <list>
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/System.hpp>
namespace core {
namespace system {
namespace file_monitor {
namespace {
int entryFilter(struct dirent *entry)
{
if (::strcmp(entry->d_name, ".") == 0 || ::strcmp(entry->d_name, "..") == 0)
return 0;
else
return 1;
}
Error scan(tree<FileInfo>* pTree,
const tree<FileInfo>::iterator_base& node,
bool recursive)
{
// clear all existing
pTree->erase_children(node);
// create FilePath for root
FilePath rootPath(node->absolutePath());
// read directory contents
struct dirent **namelist;
int entries = ::scandir(node->absolutePath().c_str(),
&namelist,
entryFilter,
::alphasort);
if (entries == -1)
{
Error error = systemError(boost::system::errc::no_such_file_or_directory,
ERROR_LOCATION);
error.addProperty("path", node->absolutePath());
return error;
}
// iterate over entries
for(int i=0; i<entries; i++)
{
// get the entry (then free it) and compute the path
dirent entry = *namelist[i];
::free(namelist[i]);
std::string name(entry.d_name, entry.d_namlen);
std::string path = rootPath.childPath(name).absolutePath();
// get the attributes
struct stat st;
int res = ::lstat(path.c_str(), &st);
if (res == -1)
{
LOG_ERROR(systemError(errno, ERROR_LOCATION));
continue;
}
// add the correct type of FileEntry
if ( S_ISDIR(st.st_mode))
{
tree<FileInfo>::iterator_base child =
pTree->append_child(node, FileInfo(path, true));
if (recursive)
{
Error error = scan(pTree, child, true);
if (error)
{
LOG_ERROR(error);
continue;
}
}
}
else
{
pTree->append_child(node, FileInfo(path,
false,
st.st_size,
st.st_mtimespec.tv_sec));
}
}
// free the namelist
::free(namelist);
// return success
return Success();
}
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
};
void addEvent(FileChangeEvent::Type type,
const FileInfo& fileInfo,
std::vector<FileChangeEvent>* pEvents)
{
pEvents->push_back(FileChangeEvent(type, fileInfo));
}
Error processAdded(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
if (fileChange.fileInfo().isDirectory())
{
tree<FileInfo> subTree;
Error error = scan(&subTree,
subTree.set_head(fileChange.fileInfo()),
true);
if (error)
return error;
// merge in the sub-tree
tree<FileInfo>::sibling_iterator addedIter =
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pContext->fileTree.insert_subtree_after(addedIter,
subTree.begin());
pContext->fileTree.erase(addedIter);
// generate events
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileAdded,
_1,
pFileChanges));
}
else
{
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pFileChanges->push_back(fileChange);
}
// sort the container after insert (so future calls to collectFileChangeEvents
// can rely on this order)
pContext->fileTree.sort(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileInfoPathLessThan,
false);
return Success();
}
void processModified(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
tree<FileInfo>::sibling_iterator modIt =
std::find_if(
pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
boost::bind(fileInfoHasPath,
_1,
fileChange.fileInfo().absolutePath()));
if (modIt != pContext->fileTree.end(parentIt))
pContext->fileTree.replace(modIt, fileChange.fileInfo());
// add it to the fileChanges
pFileChanges->push_back(fileChange);
}
void processRemoved(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
// find the item in the current tree
tree<FileInfo>::sibling_iterator remIt =
std::find(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileChange.fileInfo());
if (remIt != pContext->fileTree.end(parentIt))
{
// if this is folder then we need to generate recursive
// remove events, otherwise can just add single event
if (remIt->isDirectory())
{
tree<FileInfo> subTree(remIt);
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileRemoved,
_1,
pFileChanges));
}
else
{
pFileChanges->push_back(fileChange);
}
// remove it from the tree
pContext->fileTree.erase(remIt);
}
}
Error processFileChanges(const FileInfo& fileInfo,
bool recursive,
FileEventContext* pContext)
{
// scan this directory into a new tree which we can compare to the old tree
tree<FileInfo> subdirTree;
Error error = scan(&subdirTree, subdirTree.set_head(fileInfo), recursive);
if (error)
return error;
// find this path in our fileTree
tree<FileInfo>::iterator it = std::find(pContext->fileTree.begin(),
pContext->fileTree.end(),
fileInfo);
if (it != pContext->fileTree.end())
{
// handle recursive vs. non-recursive scan differnetly
if (recursive)
{
// check for changes on full subtree
std::vector<FileChangeEvent> fileChanges;
tree<FileInfo> existingSubtree(it);
collectFileChangeEvents(existingSubtree.begin(),
existingSubtree.end(),
subdirTree.begin(),
subdirTree.end(),
&fileChanges);
// fire events
pContext->onFilesChanged(fileChanges);
// wholesale replace subtree
pContext->fileTree.insert_subtree_after(it, subdirTree.begin());
pContext->fileTree.erase(it);
}
else
{
// scan for changes on just the children
std::vector<FileChangeEvent> childrenFileChanges;
collectFileChangeEvents(pContext->fileTree.begin(it),
pContext->fileTree.end(it),
subdirTree.begin(subdirTree.begin()),
subdirTree.end(subdirTree.begin()),
&childrenFileChanges);
// build up actual file changes and mutate the tree as appropriate
std::vector<FileChangeEvent> fileChanges;
BOOST_FOREACH(const FileChangeEvent& fileChange, childrenFileChanges)
{
switch(fileChange.type())
{
case FileChangeEvent::FileAdded:
{
Error error = processAdded(it, fileChange, pContext, &fileChanges);
if (error)
LOG_ERROR(error);
break;
}
case FileChangeEvent::FileModified:
{
processModified(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::FileRemoved:
{
processRemoved(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::None:
default:
break;
}
}
// fire events
pContext->onFilesChanged(fileChanges);
}
}
else
{
LOG_WARNING_MESSAGE("Unable to find treeItem for " +
fileInfo.absolutePath());
}
return Success();
}
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = processFileChanges(fileInfo, recursive, pContext);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
// track active handles so we can implement unregisterAll
std::list<Handle> s_activeHandles;
} // anonymous namespace
namespace detail {
// register a new file monitor
void registerMonitor(const core::FilePath& filePath, const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// scan the files
Error error = scan(&pContext->fileTree,
pContext->fileTree.set_head(FileInfo(filePath)),
true);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// track the handle
s_activeHandles.push_back((Handle*)pContext);
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// untrack the handle
s_activeHandles.remove(handle);
// delete context
delete pContext;
}
void unregisterAll()
{
// make a copy of all active handles so we can unregister them
// (unregistering mutates the list so that's why we need a copy)
std::vector<Handle> activeHandles;
std::copy(s_activeHandles.begin(),
s_activeHandles.end(),
std::back_inserter(activeHandles));
// unregister all
std::for_each(activeHandles.begin(), activeHandles.end(), unregisterMonitor);
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
// if we were stopped then break
if (reason == kCFRunLoopRunStopped)
{
unregisterAll();
break;
}
// check for input
checkForInput();
}
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<commit_msg>make alternate version of scanFiles constructor available<commit_after>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <dirent.h>
#include <sys/stat.h>
#include <CoreServices/CoreServices.h>
#include <list>
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/System.hpp>
namespace core {
namespace system {
namespace file_monitor {
namespace {
int entryFilter(struct dirent *entry)
{
if (::strcmp(entry->d_name, ".") == 0 || ::strcmp(entry->d_name, "..") == 0)
return 0;
else
return 1;
}
Error scanFiles(const tree<FileInfo>::iterator_base& fromNode,
bool recursive,
tree<FileInfo>* pTree)
{
// clear all existing
pTree->erase_children(fromNode);
// create FilePath for root
FilePath rootPath(fromNode->absolutePath());
// read directory contents
struct dirent **namelist;
int entries = ::scandir(fromNode->absolutePath().c_str(),
&namelist,
entryFilter,
::alphasort);
if (entries == -1)
{
Error error = systemError(boost::system::errc::no_such_file_or_directory,
ERROR_LOCATION);
error.addProperty("path", fromNode->absolutePath());
return error;
}
// iterate over entries
for(int i=0; i<entries; i++)
{
// get the entry (then free it) and compute the path
dirent entry = *namelist[i];
::free(namelist[i]);
std::string name(entry.d_name, entry.d_namlen);
std::string path = rootPath.childPath(name).absolutePath();
// get the attributes
struct stat st;
int res = ::lstat(path.c_str(), &st);
if (res == -1)
{
LOG_ERROR(systemError(errno, ERROR_LOCATION));
continue;
}
// add the correct type of FileEntry
if ( S_ISDIR(st.st_mode))
{
tree<FileInfo>::iterator_base child =
pTree->append_child(fromNode, FileInfo(path, true));
if (recursive)
{
Error error = scanFiles(child, true, pTree);
if (error)
{
LOG_ERROR(error);
continue;
}
}
}
else
{
pTree->append_child(fromNode, FileInfo(path,
false,
st.st_size,
st.st_mtimespec.tv_sec));
}
}
// free the namelist
::free(namelist);
// return success
return Success();
}
Error scanFiles(const FileInfo& fromRoot,
bool recursive,
tree<FileInfo>* pTree)
{
return scanFiles(pTree->set_head(fromRoot), recursive, pTree);
}
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
};
void addEvent(FileChangeEvent::Type type,
const FileInfo& fileInfo,
std::vector<FileChangeEvent>* pEvents)
{
pEvents->push_back(FileChangeEvent(type, fileInfo));
}
Error processAdded(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
if (fileChange.fileInfo().isDirectory())
{
tree<FileInfo> subTree;
Error error = scanFiles(fileChange.fileInfo(),
true,
&subTree);
if (error)
return error;
// merge in the sub-tree
tree<FileInfo>::sibling_iterator addedIter =
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pContext->fileTree.insert_subtree_after(addedIter,
subTree.begin());
pContext->fileTree.erase(addedIter);
// generate events
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileAdded,
_1,
pFileChanges));
}
else
{
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pFileChanges->push_back(fileChange);
}
// sort the container after insert (so future calls to collectFileChangeEvents
// can rely on this order)
pContext->fileTree.sort(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileInfoPathLessThan,
false);
return Success();
}
void processModified(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
tree<FileInfo>::sibling_iterator modIt =
std::find_if(
pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
boost::bind(fileInfoHasPath,
_1,
fileChange.fileInfo().absolutePath()));
if (modIt != pContext->fileTree.end(parentIt))
pContext->fileTree.replace(modIt, fileChange.fileInfo());
// add it to the fileChanges
pFileChanges->push_back(fileChange);
}
void processRemoved(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
// find the item in the current tree
tree<FileInfo>::sibling_iterator remIt =
std::find(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileChange.fileInfo());
if (remIt != pContext->fileTree.end(parentIt))
{
// if this is folder then we need to generate recursive
// remove events, otherwise can just add single event
if (remIt->isDirectory())
{
tree<FileInfo> subTree(remIt);
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileRemoved,
_1,
pFileChanges));
}
else
{
pFileChanges->push_back(fileChange);
}
// remove it from the tree
pContext->fileTree.erase(remIt);
}
}
Error processFileChanges(const FileInfo& fileInfo,
bool recursive,
FileEventContext* pContext)
{
// scan this directory into a new tree which we can compare to the old tree
tree<FileInfo> subdirTree;
Error error = scanFiles(fileInfo, recursive, &subdirTree);
if (error)
return error;
// find this path in our fileTree
tree<FileInfo>::iterator it = std::find(pContext->fileTree.begin(),
pContext->fileTree.end(),
fileInfo);
if (it != pContext->fileTree.end())
{
// handle recursive vs. non-recursive scan differnetly
if (recursive)
{
// check for changes on full subtree
std::vector<FileChangeEvent> fileChanges;
tree<FileInfo> existingSubtree(it);
collectFileChangeEvents(existingSubtree.begin(),
existingSubtree.end(),
subdirTree.begin(),
subdirTree.end(),
&fileChanges);
// fire events
pContext->onFilesChanged(fileChanges);
// wholesale replace subtree
pContext->fileTree.insert_subtree_after(it, subdirTree.begin());
pContext->fileTree.erase(it);
}
else
{
// scan for changes on just the children
std::vector<FileChangeEvent> childrenFileChanges;
collectFileChangeEvents(pContext->fileTree.begin(it),
pContext->fileTree.end(it),
subdirTree.begin(subdirTree.begin()),
subdirTree.end(subdirTree.begin()),
&childrenFileChanges);
// build up actual file changes and mutate the tree as appropriate
std::vector<FileChangeEvent> fileChanges;
BOOST_FOREACH(const FileChangeEvent& fileChange, childrenFileChanges)
{
switch(fileChange.type())
{
case FileChangeEvent::FileAdded:
{
Error error = processAdded(it, fileChange, pContext, &fileChanges);
if (error)
LOG_ERROR(error);
break;
}
case FileChangeEvent::FileModified:
{
processModified(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::FileRemoved:
{
processRemoved(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::None:
default:
break;
}
}
// fire events
pContext->onFilesChanged(fileChanges);
}
}
else
{
LOG_WARNING_MESSAGE("Unable to find treeItem for " +
fileInfo.absolutePath());
}
return Success();
}
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = processFileChanges(fileInfo, recursive, pContext);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
// track active handles so we can implement unregisterAll
std::list<Handle> s_activeHandles;
} // anonymous namespace
namespace detail {
// register a new file monitor
void registerMonitor(const core::FilePath& filePath, const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// scan the files
Error error = scanFiles(FileInfo(filePath),
true,
&pContext->fileTree);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// track the handle
s_activeHandles.push_back((Handle*)pContext);
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// untrack the handle
s_activeHandles.remove(handle);
// delete context
delete pContext;
}
void unregisterAll()
{
// make a copy of all active handles so we can unregister them
// (unregistering mutates the list so that's why we need a copy)
std::vector<Handle> activeHandles;
std::copy(s_activeHandles.begin(),
s_activeHandles.end(),
std::back_inserter(activeHandles));
// unregister all
std::for_each(activeHandles.begin(), activeHandles.end(), unregisterMonitor);
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
// if we were stopped then break
if (reason == kCFRunLoopRunStopped)
{
unregisterAll();
break;
}
// check for input
checkForInput();
}
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<|endoftext|>
|
<commit_before>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2016-09-08 osfans <waxaca@163.com>
//
#include <rime/candidate.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/ticket.h>
#include <rime/translation.h>
#include <rime/gear/codepoint_translator.h>
#include <rime/gear/translator_commons.h>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/locale.hpp>
namespace rime {
CodepointTranslator::CodepointTranslator(const Ticket& ticket)
: Translator(ticket), tag_("charset") {
if (!ticket.schema)
return;
Config* config = ticket.schema->config();
config->GetString(name_space_ + "/tag", &tag_);
}
void CodepointTranslator::Initialize() {
initialized_ = true; // no retry
if (!engine_)
return;
Ticket ticket(engine_, name_space_);
Config* config = engine_->schema()->config();
if (!config)
return;
config->GetString(name_space_ + "/prefix", &prefix_);
config->GetString(name_space_ + "/suffix", &suffix_);
config->GetString(name_space_ + "/tips", &tips_);
config->GetString(name_space_ + "/charset", &charset_);
}
an<Translation> CodepointTranslator::Query(const string& input,
const Segment& segment) {
if (!segment.HasTag(tag_))
return nullptr;
if (!initialized_)
Initialize();
DLOG(INFO) << "input = '" << input
<< "', [" << segment.start << ", " << segment.end << ")";
size_t start = 0;
if (!prefix_.empty() && boost::starts_with(input, prefix_)) {
start = prefix_.length();
}
string code = input.substr(start);
if (!suffix_.empty() && boost::ends_with(code, suffix_)) {
code.resize(code.length() - suffix_.length());
}
if (start > 0) {
// usually translators do not modify the segment directly;
// prompt text is best set by a processor or a segmentor.
const_cast<Segment*>(&segment)->prompt = tips_;
}
int n = code.length();
if (n == 0) return nullptr;
string s = "";
try {
if (charset_.compare("") == 0 || charset_.compare("utf") == 0
|| charset_.compare("codepoint") == 0) {
uint32_t i = 0;
sscanf(code.c_str(), "%x", &i);
if (i == 0) return nullptr;
s = boost::locale::conv::utf_to_utf<char>(&i, &i+1);
} else if (charset_.compare("dec") == 0 || charset_.compare("xml") == 0) {
uint32_t i = 0;
sscanf(code.c_str(), "%u", &i);
if (i == 0) return nullptr;
s = boost::locale::conv::utf_to_utf<char>(&i, &i+1);
} else if (charset_.compare("quwei") == 0) {
uint16_t i = 0;
sscanf(code.c_str(), "%hu", &i);
if (i < 1601 || i > 9494) return nullptr;
i = (i/100 + 0xa0)<<8 | (i%100 + 0xa0);
i = ntohs(i);
s = boost::locale::conv::to_utf<char>((const char*)&i, "gb2312");
} else {
uint32_t i = 0;
if (n < 8) code.append(8 - n, '0');
sscanf(code.c_str(), "%x", &i);
if (i == 0) return nullptr;
i = ntohl(i);
const char* c = (const char*)&i;
s = boost::locale::conv::to_utf<char>(c, c + 4, charset_);
}
}
catch (...) {
LOG(ERROR) << "Error conv charset.";
return nullptr;
}
auto candidate = New<SimpleCandidate>("raw",
segment.start,
segment.end,
s);
return New<UniqueTranslation>(candidate);
}
} // namespace rime
<commit_msg>codepoint_translator: use function maps<commit_after>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2016-09-08 osfans <waxaca@163.com>
//
#include <rime/candidate.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/segmentation.h>
#include <rime/ticket.h>
#include <rime/translation.h>
#include <rime/gear/codepoint_translator.h>
#include <rime/gear/translator_commons.h>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/locale.hpp>
namespace rime {
CodepointTranslator::CodepointTranslator(const Ticket& ticket)
: Translator(ticket), tag_("charset") {
if (!ticket.schema)
return;
Config* config = ticket.schema->config();
config->GetString(name_space_ + "/tag", &tag_);
}
void CodepointTranslator::Initialize() {
initialized_ = true; // no retry
if (!engine_)
return;
Ticket ticket(engine_, name_space_);
Config* config = engine_->schema()->config();
if (!config)
return;
config->GetString(name_space_ + "/prefix", &prefix_);
config->GetString(name_space_ + "/suffix", &suffix_);
config->GetString(name_space_ + "/tips", &tips_);
config->GetString(name_space_ + "/charset", &charset_);
}
string conv_to_utf(const string& input, const string& charset) {
string s = "";
uint32_t codepoint = 0;
string code = input;
size_t n = code.length();
size_t padding = 8 - (n % 8);
if (padding < 8) code.append(padding, '0');
sscanf(code.c_str(), "%x", &codepoint);
if (codepoint > 0) {
codepoint = ntohl(codepoint);
const char* c = (const char*)&codepoint;
s += boost::locale::conv::to_utf<char>(c, c + 4, charset);
}
return s;
}
an<Translation> CodepointTranslator::Query(const string& input,
const Segment& segment) {
if (!segment.HasTag(tag_))
return nullptr;
if (!initialized_)
Initialize();
DLOG(INFO) << "input = '" << input
<< "', [" << segment.start << ", " << segment.end << ")";
size_t start = 0;
if (!prefix_.empty() && boost::starts_with(input, prefix_)) {
start = prefix_.length();
}
string code = input.substr(start);
if (!suffix_.empty() && boost::ends_with(code, suffix_)) {
code.resize(code.length() - suffix_.length());
}
if (start > 0) {
// usually translators do not modify the segment directly;
// prompt text is best set by a processor or a segmentor.
const_cast<Segment*>(&segment)->prompt = tips_;
}
if (code.length() == 0) return nullptr;
map<string /*encoding*/, function<string /*converted text*/ (const string& query)>> converters;
converters["utf"] = [](string code) {
string s = "";
uint32_t i = 0;
sscanf(code.c_str(), "%x", &i);
if (i > 0) {
s = boost::locale::conv::utf_to_utf<char>(&i, &i+1);
}
return s;
};
converters["xml"] = [](string code) {
string s = "";
uint32_t i = 0;
sscanf(code.c_str(), "%u", &i);
if (i > 0) {
s = boost::locale::conv::utf_to_utf<char>(&i, &i+1);
}
return s;
};
converters["quwei"] = [](string code) {
string s = "";
uint16_t i = 0;
sscanf(code.c_str(), "%hu", &i);
if (i >= 1601 && i <= 9494) {
i = (i/100 + 0xa0)<<8 | (i%100 + 0xa0);
i = ntohs(i);
s = boost::locale::conv::to_utf<char>((const char*)&i, "gb2312");
}
return s;
};
converters[""] = converters["codepoint"] = converters["utf"]; // aliases
converters["dec"] = converters["xml"];
try {
string converted = "";
if (converters.find(charset_) != converters.end()) {
converted = converters[charset_](code);
} else {
converted = conv_to_utf(code, charset_);
}
if (converted == "") return nullptr;
auto candidate = New<SimpleCandidate>("raw",
segment.start,
segment.end,
converted);
return New<UniqueTranslation>(candidate);
} catch (...) {
return nullptr;
}
}
} // namespace rime
<|endoftext|>
|
<commit_before>
#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
template <class config_t>
writeback_tmpl_t<config_t>::writeback_tmpl_t(
cache_t *cache,
bool wait_for_flush,
unsigned int flush_interval_ms,
unsigned int force_flush_threshold)
: safety_timer(NULL),
wait_for_flush(wait_for_flush),
interval_ms(flush_interval_ms),
force_flush_threshold(force_flush_threshold),
cache(cache),
num_txns(0),
shutdown_callback(NULL),
final_sync(NULL),
state(state_none),
transaction(NULL) {
}
template <class config_t>
writeback_tmpl_t<config_t>::~writeback_tmpl_t() {
gdelete(flush_lock);
}
template <class config_t>
void writeback_tmpl_t<config_t>::start() {
flush_lock =
gnew<rwi_lock_t>(&get_cpu_context()->event_queue->message_hub,
get_cpu_context()->event_queue->queue_id);
// If interval_ms is NEVER_FLUSH, then neither timer should be started
if (interval_ms != NEVER_FLUSH) {
// 50ms is an arbitrary interval for the threshold timer to run on
get_cpu_context()->event_queue->add_timer(50, threshold_timer_callback, this);
}
start_safety_timer();
}
template <class config_t>
void writeback_tmpl_t<config_t>::shutdown(sync_callback_t *callback) {
assert(shutdown_callback == NULL);
shutdown_callback = callback;
if (!num_txns && state == state_none) // If num_txns, commit() will do this
sync(callback);
}
template <class config_t>
void writeback_tmpl_t<config_t>::sync(sync_callback_t *callback) {
sync_callbacks.push_back(callback);
// Start a new writeback process if one isn't in progress.
if (state == state_none)
writeback(NULL);
}
template <class config_t>
bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) {
assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);
// TODO(NNW): If there's ever any asynchrony between socket reads and
// begin_transaction, we'll need a better check here.
assert(shutdown_callback == NULL || final_sync);
num_txns++;
if (txn->get_access() == rwi_read)
return true;
bool locked = flush_lock->lock(rwi_read, txn);
return locked;
}
template <class config_t>
bool writeback_tmpl_t<config_t>::commit(transaction_t *txn,
transaction_commit_callback_t *callback) {
if (!--num_txns && shutdown_callback != NULL) {
// All txns shut down, start final sync.
sync(shutdown_callback);
}
if (txn->get_access() == rwi_read)
return true;
flush_lock->unlock();
if (!wait_for_flush)
return true;
txns.push_back(new txn_state_t(txn, callback));
return false;
}
template <class config_t>
void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) {
if (written)
writeback(buf);
}
template <class config_t>
void writeback_tmpl_t<config_t>::deadlock_debug() {
printf("\n----- Writeback -----\n");
const char *st_name;
switch(state) {
case state_none: st_name = "state_none"; break;
case state_locking: st_name = "state_locking"; break;
case state_locked: st_name = "state_locked"; break;
case state_write_bufs: st_name = "state_write_bufs"; break;
default: st_name = "<invalid state>"; break;
}
printf("state = %s\n", st_name);
}
template <class config_t>
void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) {
// 'super' is actually 'this', but as a buf_t* instead of a local_buf_t*
if(!dirty) {
// Mark block as dirty if it hasn't been already
dirty = true;
writeback->dirty_bufs.push_back(super);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::start_safety_timer() {
if (interval_ms != NEVER_FLUSH && interval_ms != 0) {
event_queue_t *eq = get_cpu_context()->event_queue;
if (safety_timer) {
eq->cancel_timer(safety_timer);
safety_timer = NULL;
}
safety_timer = eq->fire_timer_once(interval_ms, safety_timer_callback, this);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::safety_timer_callback(void *ctx) {
writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx);
self->safety_timer = NULL;
// TODO(NNW): We can't start writeback when it's already started, but we
// may want a more thorough way of dealing with this case.
if (self->state == state_none)
self->writeback(NULL);
}
template <class config_t>
void writeback_tmpl_t<config_t>::threshold_timer_callback(void *ctx) {
writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx);
if (self->state == state_none) {
if (self->dirty_bufs.size() > self->force_flush_threshold) {
self->writeback(NULL);
}
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::on_lock_available() {
assert(state == state_locking);
if (state == state_locking) {
state = state_locked;
writeback(NULL);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::writeback(buf_t *buf) {
//printf("Writeback being called, state %d\n", state);
if (state == state_none) {
assert(buf == NULL);
if (dirty_bufs.size() == 0) {
/* Well, that was easy. There's nothing to do! */
start_safety_timer();
return;
}
/* Start a read transaction so we can request bufs. */
assert(transaction == NULL);
if (shutdown_callback) // Backdoor around "no new transactions" assert.
final_sync = true;
transaction = cache->begin_transaction(rwi_read, NULL);
final_sync = false;
assert(transaction != NULL); // Read txns always start immediately.
/* Request exclusive flush_lock, forcing all write txns to complete. */
state = state_locking;
bool locked = flush_lock->lock(rwi_write, this);
if (locked) {
state = state_locked;
}
}
if (state == state_locked) {
assert(buf == NULL);
assert(flush_bufs.empty());
assert(flush_txns.empty());
flush_txns.append_and_clear(&txns);
/* Request read locks on all of the blocks we need to flush. */
// TODO: optimize away dynamic allocation
typename serializer_t::write *writes =
(typename serializer_t::write*)calloc(dirty_bufs.size(), sizeof *writes);
int i;
typename intrusive_list_t<buf_t>::iterator it;
for (it = dirty_bufs.begin(), i = 0; it != dirty_bufs.end(); it++, i++) {
buf_t *_buf = &*it;
// Acquire the blocks
buf_t *buf = transaction->acquire(_buf->get_block_id(), rwi_read, NULL);
assert(buf); // Acquire must succeed since we hold the flush_lock.
assert(buf == _buf); // Acquire should return the same buf we stored earlier.
// Fill the serializer structure
writes[i].block_id = buf->get_block_id();
writes[i].buf = buf->ptr();
writes[i].callback = buf;
}
flush_bufs.append_and_clear(&dirty_bufs);
flush_lock->unlock(); // Write transactions can now proceed again.
/* Start writing all the dirty bufs down, as a transaction. */
// TODO(NNW): Now that the serializer/aio-system breaks writes up into
// chunks, we may want to worry about submitting more heavily contended
// bufs earlier in the process so more write FSMs can proceed sooner.
if (flush_bufs.size())
cache->do_write(get_cpu_context()->event_queue, writes,
flush_bufs.size());
free(writes);
state = state_write_bufs;
}
if (state == state_write_bufs) {
if (buf) {
flush_bufs.remove(buf);
buf->set_clean();
buf->release();
}
if (flush_bufs.empty()) {
/* Notify all waiting transactions of completion. */
typename intrusive_list_t<txn_state_t>::iterator it;
for (it = flush_txns.begin(); it != flush_txns.end(); ) {
txn_state_t *txn_state = &*it;
it++;
txn_state->txn->committed(txn_state->callback);
flush_txns.remove(txn_state);
delete txn_state;
}
assert(flush_txns.empty());
for (typename std::vector<sync_callback_t*, gnew_alloc<sync_callback_t*> >::iterator it =
sync_callbacks.begin(); it != sync_callbacks.end(); ++it)
(*it)->on_sync();
sync_callbacks.clear();
/* Reset all of our state. */
bool committed = transaction->commit(NULL);
assert(committed); // Read-only transactions commit immediately.
transaction = NULL;
state = state_none;
// The timer for the next flush is not started until the current flush is complete. This
// is a bit dangerous because if anything causes the current flush to abort prematurely,
// the flush timer will never get restarted. As of 2010-06-28 this should never happen,
// but keep it in mind when changing the behavior of the writeback.
start_safety_timer();
//printf("Writeback complete\n");
} else {
//printf("Flush bufs, waiting for %ld more\n", flush_bufs.size());
}
}
}
#endif // __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
<commit_msg>Fixed a stupid bug I introduced in my last commit, which would cause shutdown not to happen properly.<commit_after>
#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
template <class config_t>
writeback_tmpl_t<config_t>::writeback_tmpl_t(
cache_t *cache,
bool wait_for_flush,
unsigned int flush_interval_ms,
unsigned int force_flush_threshold)
: safety_timer(NULL),
wait_for_flush(wait_for_flush),
interval_ms(flush_interval_ms),
force_flush_threshold(force_flush_threshold),
cache(cache),
num_txns(0),
shutdown_callback(NULL),
final_sync(NULL),
state(state_none),
transaction(NULL) {
}
template <class config_t>
writeback_tmpl_t<config_t>::~writeback_tmpl_t() {
gdelete(flush_lock);
}
template <class config_t>
void writeback_tmpl_t<config_t>::start() {
flush_lock =
gnew<rwi_lock_t>(&get_cpu_context()->event_queue->message_hub,
get_cpu_context()->event_queue->queue_id);
// If interval_ms is NEVER_FLUSH, then neither timer should be started
if (interval_ms != NEVER_FLUSH) {
// 50ms is an arbitrary interval for the threshold timer to run on
get_cpu_context()->event_queue->add_timer(50, threshold_timer_callback, this);
}
start_safety_timer();
}
template <class config_t>
void writeback_tmpl_t<config_t>::shutdown(sync_callback_t *callback) {
assert(shutdown_callback == NULL);
shutdown_callback = callback;
if (!num_txns && state == state_none) // If num_txns, commit() will do this
sync(callback);
}
template <class config_t>
void writeback_tmpl_t<config_t>::sync(sync_callback_t *callback) {
sync_callbacks.push_back(callback);
// Start a new writeback process if one isn't in progress.
if (state == state_none)
writeback(NULL);
}
template <class config_t>
bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) {
assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);
// TODO(NNW): If there's ever any asynchrony between socket reads and
// begin_transaction, we'll need a better check here.
assert(shutdown_callback == NULL || final_sync);
num_txns++;
if (txn->get_access() == rwi_read)
return true;
bool locked = flush_lock->lock(rwi_read, txn);
return locked;
}
template <class config_t>
bool writeback_tmpl_t<config_t>::commit(transaction_t *txn,
transaction_commit_callback_t *callback) {
if (!--num_txns && shutdown_callback != NULL) {
// All txns shut down, start final sync.
sync(shutdown_callback);
}
if (txn->get_access() == rwi_read)
return true;
flush_lock->unlock();
if (!wait_for_flush)
return true;
txns.push_back(new txn_state_t(txn, callback));
return false;
}
template <class config_t>
void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) {
if (written)
writeback(buf);
}
template <class config_t>
void writeback_tmpl_t<config_t>::deadlock_debug() {
printf("\n----- Writeback -----\n");
const char *st_name;
switch(state) {
case state_none: st_name = "state_none"; break;
case state_locking: st_name = "state_locking"; break;
case state_locked: st_name = "state_locked"; break;
case state_write_bufs: st_name = "state_write_bufs"; break;
default: st_name = "<invalid state>"; break;
}
printf("state = %s\n", st_name);
}
template <class config_t>
void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) {
// 'super' is actually 'this', but as a buf_t* instead of a local_buf_t*
if(!dirty) {
// Mark block as dirty if it hasn't been already
dirty = true;
writeback->dirty_bufs.push_back(super);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::start_safety_timer() {
if (interval_ms != NEVER_FLUSH && interval_ms != 0) {
event_queue_t *eq = get_cpu_context()->event_queue;
if (safety_timer) {
eq->cancel_timer(safety_timer);
safety_timer = NULL;
}
safety_timer = eq->fire_timer_once(interval_ms, safety_timer_callback, this);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::safety_timer_callback(void *ctx) {
writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx);
self->safety_timer = NULL;
// TODO(NNW): We can't start writeback when it's already started, but we
// may want a more thorough way of dealing with this case.
if (self->state == state_none)
self->writeback(NULL);
}
template <class config_t>
void writeback_tmpl_t<config_t>::threshold_timer_callback(void *ctx) {
writeback_tmpl_t *self = static_cast<writeback_tmpl_t *>(ctx);
if (self->state == state_none) {
if (self->dirty_bufs.size() > self->force_flush_threshold) {
self->writeback(NULL);
}
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::on_lock_available() {
assert(state == state_locking);
if (state == state_locking) {
state = state_locked;
writeback(NULL);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::writeback(buf_t *buf) {
//printf("Writeback being called, state %d\n", state);
if (state == state_none) {
assert(buf == NULL);
/* Start a read transaction so we can request bufs. */
assert(transaction == NULL);
if (shutdown_callback) // Backdoor around "no new transactions" assert.
final_sync = true;
transaction = cache->begin_transaction(rwi_read, NULL);
final_sync = false;
assert(transaction != NULL); // Read txns always start immediately.
/* Request exclusive flush_lock, forcing all write txns to complete. */
state = state_locking;
bool locked = flush_lock->lock(rwi_write, this);
if (locked) {
state = state_locked;
}
}
if (state == state_locked) {
assert(buf == NULL);
assert(flush_bufs.empty());
assert(flush_txns.empty());
flush_txns.append_and_clear(&txns);
/* Request read locks on all of the blocks we need to flush. */
// TODO: optimize away dynamic allocation
typename serializer_t::write *writes =
(typename serializer_t::write*)calloc(dirty_bufs.size(), sizeof *writes);
int i;
typename intrusive_list_t<buf_t>::iterator it;
for (it = dirty_bufs.begin(), i = 0; it != dirty_bufs.end(); it++, i++) {
buf_t *_buf = &*it;
// Acquire the blocks
buf_t *buf = transaction->acquire(_buf->get_block_id(), rwi_read, NULL);
assert(buf); // Acquire must succeed since we hold the flush_lock.
assert(buf == _buf); // Acquire should return the same buf we stored earlier.
// Fill the serializer structure
writes[i].block_id = buf->get_block_id();
writes[i].buf = buf->ptr();
writes[i].callback = buf;
}
flush_bufs.append_and_clear(&dirty_bufs);
flush_lock->unlock(); // Write transactions can now proceed again.
/* Start writing all the dirty bufs down, as a transaction. */
// TODO(NNW): Now that the serializer/aio-system breaks writes up into
// chunks, we may want to worry about submitting more heavily contended
// bufs earlier in the process so more write FSMs can proceed sooner.
if (flush_bufs.size())
cache->do_write(get_cpu_context()->event_queue, writes,
flush_bufs.size());
free(writes);
state = state_write_bufs;
}
if (state == state_write_bufs) {
if (buf) {
flush_bufs.remove(buf);
buf->set_clean();
buf->release();
}
if (flush_bufs.empty()) {
/* Notify all waiting transactions of completion. */
typename intrusive_list_t<txn_state_t>::iterator it;
for (it = flush_txns.begin(); it != flush_txns.end(); ) {
txn_state_t *txn_state = &*it;
it++;
txn_state->txn->committed(txn_state->callback);
flush_txns.remove(txn_state);
delete txn_state;
}
assert(flush_txns.empty());
for (typename std::vector<sync_callback_t*, gnew_alloc<sync_callback_t*> >::iterator it =
sync_callbacks.begin(); it != sync_callbacks.end(); ++it)
(*it)->on_sync();
sync_callbacks.clear();
/* Reset all of our state. */
bool committed = transaction->commit(NULL);
assert(committed); // Read-only transactions commit immediately.
transaction = NULL;
state = state_none;
// The timer for the next flush is not started until the current flush is complete. This
// is a bit dangerous because if anything causes the current flush to abort prematurely,
// the flush timer will never get restarted. As of 2010-06-28 this should never happen,
// but keep it in mind when changing the behavior of the writeback.
start_safety_timer();
//printf("Writeback complete\n");
} else {
//printf("Flush bufs, waiting for %ld more\n", flush_bufs.size());
}
}
}
#endif // __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
<|endoftext|>
|
<commit_before>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: python/pybind11_Image.hpp
*
* Copyright 2017 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
#include "pybind11/numpy.h"
#include "Eigen/Core"
#include <cstddef>
#include <vector>
NAMESPACE_BEGIN(pybind11)
NAMESPACE_BEGIN(detail)
/**
* @file python/pybind11_Image.hpp
* @brief Transparent conversion to and from Python for eos::core::Image.
*
* Numpy uses row-major storage order by default.
* eos::core::Image uses col-major storage (like Eigen).
*
* If given non-standard strides or something from numpy, probably doesn't work.
* May need to .clone()? in numpy before passing to the C++ function.
*/
/**
* @brief Transparent conversion for eos::core::Image3u to and from Python.
*
* Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays,
* as well as potentially other Python array types.
*
* Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage
* order, or has non-standard strides. It may or may not work.
*/
template<>
struct type_caster<eos::core::Image3u>
{
bool load(handle src, bool)
{
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))
{
return false; // we only convert uint8_t for now.
}
if (buf.ndim() != 3) {
return false; // we expected a numpy array with 3 dimensions.
}
// We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):
if (buf.shape(2) != 3) {
return false; // We expected a 3-channel image.
}
// Note: If our Image class had support for col/row major, we could just map buf.mutable_data().
// Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
// But since it doesn't, we just copy the data for now:
value = eos::core::Image3u(buf.shape(0), buf.shape(1));
array_t<std::uint8_t> buf_as_array(buf);
for (int r = 0; r < buf.shape(0); ++r) {
for (int c = 0; c < buf.shape(1); ++c) {
value(r, c)[0] = buf_as_array.at(r, c, 0);
value(r, c)[1] = buf_as_array.at(r, c, 1);
value(r, c)[2] = buf_as_array.at(r, c, 2);
}
}
return true;
};
static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */)
{
const std::size_t num_channels = 3;
std::vector<std::size_t> shape = { src.rows, src.cols, num_channels };
// (2048, 4, 1) is default which results in transposed image
// Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?
std::vector<std::size_t> strides = { num_channels, num_channels * src.rows, 1 }; // might be cols or rows...? I think rows?
return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src.data[0]).release();
};
PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]"));
};
/**
* @brief Transparent conversion for eos::core::Image4u to and from Python.
*
* Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays,
* as well as potentially other Python array types.
*
* Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage
* order, or has non-standard strides. It may or may not work.
*/
template<>
struct type_caster<eos::core::Image4u>
{
bool load(handle src, bool)
{
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))
{
return false; // we only convert uint8_t for now.
}
if (buf.ndim() != 3) {
return false; // we expected a numpy array with 3 dimensions.
}
// We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):
if (buf.shape(2) != 4) {
return false; // We expected a 4-channel image.
}
// Note: If our Image class had support for col/row major, we could just map buf.mutable_data().
// Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
// But since it doesn't, we just copy the data for now:
value = eos::core::Image4u(buf.shape(0), buf.shape(1));
array_t<std::uint8_t> buf_as_array(buf);
for (int r = 0; r < buf.shape(0); ++r) {
for (int c = 0; c < buf.shape(1); ++c) {
value(r, c)[0] = buf_as_array.at(r, c, 0);
value(r, c)[1] = buf_as_array.at(r, c, 1);
value(r, c)[2] = buf_as_array.at(r, c, 2);
value(r, c)[3] = buf_as_array.at(r, c, 3);
}
}
return true;
};
static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */)
{
const std::size_t num_chanels = 4;
std::vector<std::size_t> shape;
shape = { src.rows, src.cols, num_chanels };
// (2048, 4, 1) is default which results in transposed image
// Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?
std::vector<size_t> strides = { num_chanels, num_chanels * src.rows, 1 }; // might be cols or rows...? I think rows?
return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src.data[0]).release();
};
PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]"));
};
NAMESPACE_END(detail)
NAMESPACE_END(pybind11)
<commit_msg>Added missing include guard to pybind11_Image.hpp<commit_after>/*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: python/pybind11_Image.hpp
*
* Copyright 2017 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 EOS_PYBIND11_IMAGE_HPP_
#define EOS_PYBIND11_IMAGE_HPP_
#include "pybind11/numpy.h"
#include "Eigen/Core"
#include <cstddef>
#include <vector>
NAMESPACE_BEGIN(pybind11)
NAMESPACE_BEGIN(detail)
/**
* @file python/pybind11_Image.hpp
* @brief Transparent conversion to and from Python for eos::core::Image.
*
* Numpy uses row-major storage order by default.
* eos::core::Image uses col-major storage (like Eigen).
*
* If given non-standard strides or something from numpy, probably doesn't work.
* May need to .clone()? in numpy before passing to the C++ function.
*/
/**
* @brief Transparent conversion for eos::core::Image3u to and from Python.
*
* Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays,
* as well as potentially other Python array types.
*
* Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage
* order, or has non-standard strides. It may or may not work.
*/
template<>
struct type_caster<eos::core::Image3u>
{
bool load(handle src, bool)
{
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))
{
return false; // we only convert uint8_t for now.
}
if (buf.ndim() != 3) {
return false; // we expected a numpy array with 3 dimensions.
}
// We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):
if (buf.shape(2) != 3) {
return false; // We expected a 3-channel image.
}
// Note: If our Image class had support for col/row major, we could just map buf.mutable_data().
// Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
// But since it doesn't, we just copy the data for now:
value = eos::core::Image3u(buf.shape(0), buf.shape(1));
array_t<std::uint8_t> buf_as_array(buf);
for (int r = 0; r < buf.shape(0); ++r) {
for (int c = 0; c < buf.shape(1); ++c) {
value(r, c)[0] = buf_as_array.at(r, c, 0);
value(r, c)[1] = buf_as_array.at(r, c, 1);
value(r, c)[2] = buf_as_array.at(r, c, 2);
}
}
return true;
};
static handle cast(const eos::core::Image3u& src, return_value_policy /* policy */, handle /* parent */)
{
const std::size_t num_channels = 3;
std::vector<std::size_t> shape = { src.rows, src.cols, num_channels };
// (2048, 4, 1) is default which results in transposed image
// Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?
std::vector<std::size_t> strides = { num_channels, num_channels * src.rows, 1 }; // might be cols or rows...? I think rows?
return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src.data[0]).release();
};
PYBIND11_TYPE_CASTER(eos::core::Image3u, _("numpy.ndarray[uint8[m, n, 3]]"));
};
/**
* @brief Transparent conversion for eos::core::Image4u to and from Python.
*
* Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays,
* as well as potentially other Python array types.
*
* Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage
* order, or has non-standard strides. It may or may not work.
*/
template<>
struct type_caster<eos::core::Image4u>
{
bool load(handle src, bool)
{
auto buf = pybind11::array::ensure(src);
if (!buf)
return false;
// Todo: We should probably check that buf.strides(i) is "default", by dividing it by the Scalar type or something.
if (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))
{
return false; // we only convert uint8_t for now.
}
if (buf.ndim() != 3) {
return false; // we expected a numpy array with 3 dimensions.
}
// We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):
if (buf.shape(2) != 4) {
return false; // We expected a 4-channel image.
}
// Note: If our Image class had support for col/row major, we could just map buf.mutable_data().
// Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());
// But since it doesn't, we just copy the data for now:
value = eos::core::Image4u(buf.shape(0), buf.shape(1));
array_t<std::uint8_t> buf_as_array(buf);
for (int r = 0; r < buf.shape(0); ++r) {
for (int c = 0; c < buf.shape(1); ++c) {
value(r, c)[0] = buf_as_array.at(r, c, 0);
value(r, c)[1] = buf_as_array.at(r, c, 1);
value(r, c)[2] = buf_as_array.at(r, c, 2);
value(r, c)[3] = buf_as_array.at(r, c, 3);
}
}
return true;
};
static handle cast(const eos::core::Image4u& src, return_value_policy /* policy */, handle /* parent */)
{
const std::size_t num_chanels = 4;
std::vector<std::size_t> shape;
shape = { src.rows, src.cols, num_chanels };
// (2048, 4, 1) is default which results in transposed image
// Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?
std::vector<size_t> strides = { num_chanels, num_chanels * src.rows, 1 }; // might be cols or rows...? I think rows?
return array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src.data[0]).release();
};
PYBIND11_TYPE_CASTER(eos::core::Image4u, _("numpy.ndarray[uint8[m, n, 4]]"));
};
NAMESPACE_END(detail)
NAMESPACE_END(pybind11)
#endif /* EOS_PYBIND11_IMAGE_HPP_ */
<|endoftext|>
|
<commit_before>
#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
template <class config_t>
writeback_tmpl_t<config_t>::writeback_tmpl_t(cache_t *cache,
bool wait_for_flush, unsigned int flush_interval_ms)
: wait_for_flush(wait_for_flush),
interval_ms(flush_interval_ms),
cache(cache),
num_txns(0),
shutdown_callback(NULL),
final_sync(NULL),
state(state_none),
transaction(NULL) {
}
template <class config_t>
writeback_tmpl_t<config_t>::~writeback_tmpl_t() {
delete flush_lock;
}
template <class config_t>
void writeback_tmpl_t<config_t>::start() {
flush_lock =
new rwi_lock<config_t>(&get_cpu_context()->event_queue->message_hub,
get_cpu_context()->event_queue->queue_id);
start_flush_timer();
}
template <class config_t>
void writeback_tmpl_t<config_t>::shutdown(sync_callback<config_t> *callback) {
assert(shutdown_callback == NULL);
shutdown_callback = callback;
if (!num_txns && state == state_none) // If num_txns, commit() will do this
sync(callback);
}
template <class config_t>
void writeback_tmpl_t<config_t>::sync(sync_callback<config_t> *callback) {
sync_callbacks.push_back(callback);
// Start a new writeback process if one isn't in progress.
if (state == state_none)
writeback(NULL);
}
template <class config_t>
bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) {
assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);
// TODO(NNW): If there's ever any asynchrony between socket reads and
// begin_transaction, we'll need a better check here.
assert(shutdown_callback == NULL || final_sync);
num_txns++;
if (txn->get_access() == rwi_read)
return true;
bool locked = flush_lock->lock(rwi_read, txn);
return locked;
}
template <class config_t>
bool writeback_tmpl_t<config_t>::commit(transaction_t *txn,
transaction_commit_callback_t *callback) {
if (!--num_txns && shutdown_callback != NULL) {
sync(shutdown_callback); // All txns shut down, start final sync.
}
if (txn->get_access() == rwi_read)
return true;
flush_lock->unlock();
if (!wait_for_flush)
return true;
txns.insert(txn_state_t(txn, callback));
return false;
}
template <class config_t>
void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) {
if (written)
writeback(buf);
}
template <class config_t>
void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) {
if (!dirty)
super->pin();
dirty = true;
writeback->dirty_blocks.insert(super->get_block_id());
}
template <class config_t>
void writeback_tmpl_t<config_t>::start_flush_timer() {
if (interval_ms != NEVER_FLUSH && interval_ms != 0) {
timespec ts;
ts.tv_sec = interval_ms / 1000;
ts.tv_nsec = (interval_ms % 1000) * 1000 * 1000;
get_cpu_context()->event_queue->timer_once(&ts, timer_callback, this);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::timer_callback(void *ctx) {
// TODO(NNW): We can't start writeback when it's already started, but we
// may want a more thorough way of dealing with this case.
if (static_cast<writeback_tmpl_t *>(ctx)->state == state_none)
static_cast<writeback_tmpl_t *>(ctx)->writeback(NULL);
}
template <class config_t>
void writeback_tmpl_t<config_t>::on_lock_available() {
assert(state == state_locking);
if (state == state_locking) {
state = state_locked;
writeback(NULL);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::writeback(buf_t *buf) {
//printf("Writeback being called, state %d\n", state);
if (state == state_none) {
assert(buf == NULL);
/* Start a read transaction so we can request bufs. */
assert(transaction == NULL);
if (shutdown_callback) // Backdoor around "no new transactions" assert.
final_sync = true;
transaction = cache->begin_transaction(rwi_read, NULL);
final_sync = false;
assert(transaction != NULL); // Read txns always start immediately.
/* Request exclusive flush_lock, forcing all write txns to complete. */
state = state_locking;
bool locked = flush_lock->lock(rwi_write, this);
if (locked)
state = state_locked;
}
if (state == state_locked) {
assert(buf == NULL);
assert(flush_bufs.empty());
assert(flush_txns.empty());
flush_txns = txns;
txns.clear();
/* Request read locks on all of the blocks we need to flush. */
for (typename std::set<block_id_t>::iterator it = dirty_blocks.begin();
it != dirty_blocks.end(); ++it) {
buf_t *buf = transaction->acquire(*it, rwi_read, NULL);
assert(buf); // Acquire must succeed since we hold the flush_lock.
flush_bufs.insert(buf);
}
dirty_blocks.clear();
flush_lock->unlock(); // Write transactions can now proceed again.
/* Start writing all the dirty bufs down, as a transaction. */
typename serializer_t::write *writes =
(typename serializer_t::write *)calloc(flush_bufs.size(),
sizeof *writes);
int i = 0;
for (typename std::set<buf_t *>::iterator it = flush_bufs.begin();
it != flush_bufs.end(); ++it, i++) {
writes[i].block_id = (*it)->get_block_id();
writes[i].buf = (*it)->ptr();
writes[i].callback = (*it);
}
// TODO(NNW): Now that the serializer/aio-system breaks writes up into
// chunks, we may want to worry about submitting more heavily contended
// bufs earlier in the process so more write FSMs can proceed sooner.
if (flush_bufs.size())
cache->do_write(get_cpu_context()->event_queue, writes,
flush_bufs.size());
free(writes);
state = state_write_bufs;
}
if (state == state_write_bufs) {
if (buf) {
assert(flush_bufs.find(buf) != flush_bufs.end());
flush_bufs.erase(buf);
buf->set_clean();
buf->release();
}
if (flush_bufs.empty()) {
/* Notify all waiting transactions of completion. */
for (typename std::set<txn_state_t>::iterator it =
flush_txns.begin(); it != flush_txns.end(); ++it) {
it->first->committed(it->second);
}
flush_txns.clear();
for (typename std::vector<sync_callback_t *>::iterator it =
sync_callbacks.begin(); it != sync_callbacks.end(); ++it)
(*it)->on_sync();
sync_callbacks.clear();
/* Reset all of our state. */
bool committed = transaction->commit(NULL);
assert(committed); // Read-only transactions commit immediately.
transaction = NULL;
state = state_none;
// The timer for the next flush is not started until the current flush is complete. This
// is a bit dangerous because if anything causes the current flush to abort prematurely,
// the flush timer will never get restarted. As of 2010-06-28 this should never happen,
// but keep it in mind when changing the behavior of the writeback.
start_flush_timer();
//printf("Writeback complete\n");
} else {
//printf("Flush bufs, waiting for %ld more\n", flush_bufs.size());
}
}
}
#endif // __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
<commit_msg>Made a note about a memory leak if the server terminates while a client is waiting for flush.<commit_after>
#ifndef __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
#define __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
template <class config_t>
writeback_tmpl_t<config_t>::writeback_tmpl_t(cache_t *cache,
bool wait_for_flush, unsigned int flush_interval_ms)
: wait_for_flush(wait_for_flush),
interval_ms(flush_interval_ms),
cache(cache),
num_txns(0),
shutdown_callback(NULL),
final_sync(NULL),
state(state_none),
transaction(NULL) {
}
template <class config_t>
writeback_tmpl_t<config_t>::~writeback_tmpl_t() {
delete flush_lock;
}
template <class config_t>
void writeback_tmpl_t<config_t>::start() {
flush_lock =
new rwi_lock<config_t>(&get_cpu_context()->event_queue->message_hub,
get_cpu_context()->event_queue->queue_id);
start_flush_timer();
}
template <class config_t>
void writeback_tmpl_t<config_t>::shutdown(sync_callback<config_t> *callback) {
assert(shutdown_callback == NULL);
shutdown_callback = callback;
if (!num_txns && state == state_none) // If num_txns, commit() will do this
sync(callback);
}
template <class config_t>
void writeback_tmpl_t<config_t>::sync(sync_callback<config_t> *callback) {
sync_callbacks.push_back(callback);
// Start a new writeback process if one isn't in progress.
if (state == state_none)
writeback(NULL);
}
template <class config_t>
bool writeback_tmpl_t<config_t>::begin_transaction(transaction_t *txn) {
assert(txn->get_access() == rwi_read || txn->get_access() == rwi_write);
// TODO(NNW): If there's ever any asynchrony between socket reads and
// begin_transaction, we'll need a better check here.
assert(shutdown_callback == NULL || final_sync);
num_txns++;
if (txn->get_access() == rwi_read)
return true;
bool locked = flush_lock->lock(rwi_read, txn);
return locked;
}
template <class config_t>
bool writeback_tmpl_t<config_t>::commit(transaction_t *txn,
transaction_commit_callback_t *callback) {
if (!--num_txns && shutdown_callback != NULL) {
sync(shutdown_callback); // All txns shut down, start final sync.
}
if (txn->get_access() == rwi_read)
return true;
flush_lock->unlock();
// TODO: If wait_for_flush is true but the server shuts down before the next writeback, then
// there is a memory leak of some sort. Problem can be demonstrated with:
// Terminal 1:
// ./rethinkdb --flush-interval 1000000 --wait-for-flush y
// Terminal 2:
// telnet localhost 8080
// set 1 0 0 1
// 8
// Terminal 3:
// telnet localhost 8080
// shutdown
// After issuing the "set" command, terminal 2 will block because data has not been flushed to
// disk. When terminal 3 issues the "shutdown" command, the server will shut down, but a message
// like "Memory leak detected: Interrupted system call" will be printed on terminal 1.
if (!wait_for_flush)
return true;
txns.insert(txn_state_t(txn, callback));
return false;
}
template <class config_t>
void writeback_tmpl_t<config_t>::aio_complete(buf_t *buf, bool written) {
if (written)
writeback(buf);
}
template <class config_t>
void writeback_tmpl_t<config_t>::local_buf_t::set_dirty(buf_t *super) {
if (!dirty)
super->pin();
dirty = true;
writeback->dirty_blocks.insert(super->get_block_id());
}
template <class config_t>
void writeback_tmpl_t<config_t>::start_flush_timer() {
if (interval_ms != NEVER_FLUSH && interval_ms != 0) {
timespec ts;
ts.tv_sec = interval_ms / 1000;
ts.tv_nsec = (interval_ms % 1000) * 1000 * 1000;
get_cpu_context()->event_queue->timer_once(&ts, timer_callback, this);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::timer_callback(void *ctx) {
// TODO(NNW): We can't start writeback when it's already started, but we
// may want a more thorough way of dealing with this case.
if (static_cast<writeback_tmpl_t *>(ctx)->state == state_none)
static_cast<writeback_tmpl_t *>(ctx)->writeback(NULL);
}
template <class config_t>
void writeback_tmpl_t<config_t>::on_lock_available() {
assert(state == state_locking);
if (state == state_locking) {
state = state_locked;
writeback(NULL);
}
}
template <class config_t>
void writeback_tmpl_t<config_t>::writeback(buf_t *buf) {
//printf("Writeback being called, state %d\n", state);
if (state == state_none) {
assert(buf == NULL);
/* Start a read transaction so we can request bufs. */
assert(transaction == NULL);
if (shutdown_callback) // Backdoor around "no new transactions" assert.
final_sync = true;
transaction = cache->begin_transaction(rwi_read, NULL);
final_sync = false;
assert(transaction != NULL); // Read txns always start immediately.
/* Request exclusive flush_lock, forcing all write txns to complete. */
state = state_locking;
bool locked = flush_lock->lock(rwi_write, this);
if (locked)
state = state_locked;
}
if (state == state_locked) {
assert(buf == NULL);
assert(flush_bufs.empty());
assert(flush_txns.empty());
flush_txns = txns;
txns.clear();
/* Request read locks on all of the blocks we need to flush. */
for (typename std::set<block_id_t>::iterator it = dirty_blocks.begin();
it != dirty_blocks.end(); ++it) {
buf_t *buf = transaction->acquire(*it, rwi_read, NULL);
assert(buf); // Acquire must succeed since we hold the flush_lock.
flush_bufs.insert(buf);
}
dirty_blocks.clear();
flush_lock->unlock(); // Write transactions can now proceed again.
/* Start writing all the dirty bufs down, as a transaction. */
typename serializer_t::write *writes =
(typename serializer_t::write *)calloc(flush_bufs.size(),
sizeof *writes);
int i = 0;
for (typename std::set<buf_t *>::iterator it = flush_bufs.begin();
it != flush_bufs.end(); ++it, i++) {
writes[i].block_id = (*it)->get_block_id();
writes[i].buf = (*it)->ptr();
writes[i].callback = (*it);
}
// TODO(NNW): Now that the serializer/aio-system breaks writes up into
// chunks, we may want to worry about submitting more heavily contended
// bufs earlier in the process so more write FSMs can proceed sooner.
if (flush_bufs.size())
cache->do_write(get_cpu_context()->event_queue, writes,
flush_bufs.size());
free(writes);
state = state_write_bufs;
}
if (state == state_write_bufs) {
if (buf) {
assert(flush_bufs.find(buf) != flush_bufs.end());
flush_bufs.erase(buf);
buf->set_clean();
buf->release();
}
if (flush_bufs.empty()) {
/* Notify all waiting transactions of completion. */
for (typename std::set<txn_state_t>::iterator it =
flush_txns.begin(); it != flush_txns.end(); ++it) {
it->first->committed(it->second);
}
flush_txns.clear();
for (typename std::vector<sync_callback_t *>::iterator it =
sync_callbacks.begin(); it != sync_callbacks.end(); ++it)
(*it)->on_sync();
sync_callbacks.clear();
/* Reset all of our state. */
bool committed = transaction->commit(NULL);
assert(committed); // Read-only transactions commit immediately.
transaction = NULL;
state = state_none;
// The timer for the next flush is not started until the current flush is complete. This
// is a bit dangerous because if anything causes the current flush to abort prematurely,
// the flush timer will never get restarted. As of 2010-06-28 this should never happen,
// but keep it in mind when changing the behavior of the writeback.
start_flush_timer();
//printf("Writeback complete\n");
} else {
//printf("Flush bufs, waiting for %ld more\n", flush_bufs.size());
}
}
}
#endif // __BUFFER_CACHE_WRITEBACK_IMPL_HPP__
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// A Simple Idler system that keeps track chain tension by pre-loading a
// spring/damper elemnt
//
// =============================================================================
#include <cstdio>
#include "IdlerSimple.h"
#include "assets/ChAsset.h"
#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChColorAsset.h"
// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
namespace chrono {
// Static variables
const double IdlerSimple::m_mass = 429.6;
const ChVector<> IdlerSimple::m_inertia = ChVector<>(14.7, 12.55, 12.55);
const std::string IdlerSimple::m_meshName = "idler_mesh";
const std::string IdlerSimple::m_meshFile = utils::GetModelDataFile("data/idlerMesh.obj");
// guessing at these values
const double IdlerSimple::m_radius = 0.255;
const double IdlerSimple::m_width = 0.166;
const double IdlerSimple::m_widthGap = 0.092;
const double IdlerSimple::m_springK = 100000;
const double IdlerSimple::m_springC = 1000;
const double IdlerSimple::m_springRestLength = 1.0;
/*
// -----------------------------------------------------------------------------
// Default shock and spring functors (used for linear elements)
// -----------------------------------------------------------------------------
class LinearSpringForce : public ChSpringForceCallback
{
public:
LinearSpringForce(double k) : m_k(k) {}
virtual double operator()(double time, // current time
double rest_length, // undeformed length
double length, // current length
double vel) // current velocity (positive when extending)
{
return -m_k * (length - rest_length);
}
private:
double m_k;
};
class LinearShockForce : public ChSpringForceCallback
{
public:
LinearShockForce(double c) : m_c(c) {}
virtual double operator()(double time, // current time
double rest_length, // undeformed length
double length, // current length
double vel) // current velocity (positive when extending)
{
return -m_c * vel;
}
private:
double m_c;
};
*/
IdlerSimple::IdlerSimple(const std::string& name,
VisualizationType vis,
CollisionType collide)
: m_vis(vis), m_collide(collide)
// , m_shockCB(NULL), m_springCB(NULL)
{
// create the body, set the basic info
m_idler = ChSharedPtr<ChBody>(new ChBody);
m_idler->SetNameString(name + "_body");
m_idler->SetMass(m_mass);
m_idler->SetInertiaXX(m_inertia);
// create the idler joint
m_idler_joint = ChSharedPtr<ChLinkLockRevolutePrismatic>(new ChLinkLockRevolutePrismatic);
m_idler_joint->SetNameString(name + "_idler_joint");
// create the tensioning linear spring-shock
m_shock = ChSharedPtr<ChLinkSpring>(new ChLinkSpring);
m_shock->SetNameString(name + "_shock");
m_shock->Set_SpringK(m_springK);
m_shock->Set_SpringR(m_springC);
m_shock->Set_SpringRestLength(m_springRestLength);
AddVisualization();
}
IdlerSimple::~IdlerSimple()
{
// delete m_springCB;
// delete m_shockCB;
}
void IdlerSimple::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChCoordsys<>& local_Csys)
{
// add collision geometry
AddCollisionGeometry();
// Express the steering reference frame in the absolute coordinate system.
ChFrame<> idler_to_abs(local_Csys);
idler_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());
// transform the idler body, add to system
m_idler->SetPos(idler_to_abs.GetPos());
m_idler->SetRot(idler_to_abs.GetRot());
chassis->GetSystem()->Add(m_idler);
// init joint, add to system
// body 1 should rotate about z-axis, translate about x-axis of body2
// TODO: (check) idler joint translates, rotates in correct direction.
// NOTE: I created the idler to translate x-dir, rotate about z-dir, according
// to how the chassis is rotated by default.
m_idler_joint->Initialize(m_idler, chassis, m_idler->GetCoord() );
chassis->GetSystem()->AddLink(m_idler_joint);
// init shock, add to system
// put the second marker some length in front of marker1, based on desired preload
double preLoad = 10000; // [N]
// chassis spring attachment point is towards the center of the vehicle
ChVector<> pos_chassis_abs = local_Csys.pos;
if(local_Csys.pos.x < 0 )
pos_chassis_abs.x += m_springRestLength - (preLoad / m_springK);
else
pos_chassis_abs.x -= m_springRestLength - (preLoad / m_springK);
// transform 2nd attachment point to abs coords
pos_chassis_abs = chassis->GetCoord().TransformPointLocalToParent(pos_chassis_abs);
// init. points based on desired preload and free lengths
m_shock->Initialize(m_idler, chassis, false, m_idler->GetPos(), pos_chassis_abs );
// setting rest length should yield desired preload at time = 0
m_shock->Set_SpringRestLength(m_springRestLength);
chassis->GetSystem()->AddLink(m_shock);
}
void IdlerSimple::AddVisualization()
{
// add visualization asset
switch (m_vis) {
case VisualizationType::PRIMITIVES:
{
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
// define the shape with two concentric cyclinders, with a gap.
cyl->GetCylinderGeometry().p1 = ChVector<>(0, 0, m_width/2.0);
cyl->GetCylinderGeometry().p2 = ChVector<>(0, 0, m_widthGap/2.0);
cyl->GetCylinderGeometry().rad = m_radius;
m_idler->AddAsset(cyl);
// second cylinder is a mirror of the first
cyl->GetCylinderGeometry().p1.z = -m_width/2.0;
cyl->GetCylinderGeometry().p2.z = -m_widthGap/2.0;
m_idler->AddAsset(cyl);
// add a color asset
ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
m_idler->AddAsset(mcolor);
break;
}
case VisualizationType::MESH:
{
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(getMeshFile(), false, false);
ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName(getMeshName());
m_idler->AddAsset(trimesh_shape);
// add a color asset
ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
m_idler->AddAsset(mcolor);
break;
}
} // end switch
}
void IdlerSimple::AddCollisionGeometry()
{
// add collision geometrey to the chassis, if enabled
m_idler->SetCollide(true);
m_idler->GetCollisionModel()->ClearModel();
switch (m_collide) {
case CollisionType::NONE:
{
m_idler->SetCollide(false);
}
case CollisionType::PRIMITIVES:
{
// use a simple cylinder
m_idler->GetCollisionModel()->AddCylinder(m_radius, m_radius, m_width,
ChVector<>(),Q_from_AngAxis(CH_C_PI_2,VECT_X));
break;
}
case CollisionType::MESH:
{
// use a triangle mesh
geometry::ChTriangleMeshSoup temp_trianglemesh;
// TODO: fill the triangleMesh here with some track shoe geometry
m_idler->GetCollisionModel()->SetSafeMargin(0.004); // inward safe margin
m_idler->GetCollisionModel()->SetEnvelope(0.010); // distance of the outward "collision envelope"
m_idler->GetCollisionModel()->ClearModel();
// is there an offset??
double shoelength = 0.2;
ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass
m_idler->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);
break;
}
case CollisionType::CONVEXHULL:
{
// use convex hulls, loaded from file
ChStreamInAsciiFile chull_file(GetChronoDataFile("idler.chulls").c_str());
// transform the collision geometry as needed
double mangle = 45.0; // guess
ChQuaternion<>rot;
rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
ChMatrix33<> rot_offset(rot);
ChVector<> disp_offset(0,0,0); // no displacement offset
m_idler->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
break;
}
} // end switch
// setup collision family
m_idler->GetCollisionModel()->SetFamily( (int)CollisionFam::GEARS );
// don't collide with other roling elements or the ground
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::HULL );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GEARS );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::WHEELS );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GROUND );
m_idler->GetCollisionModel()->BuildModel();
}
} // end namespace chrono
<commit_msg>simplest idler collision shape is two cylinders.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// A Simple Idler system that keeps track chain tension by pre-loading a
// spring/damper elemnt
//
// =============================================================================
#include <cstdio>
#include "IdlerSimple.h"
#include "assets/ChAsset.h"
#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChColorAsset.h"
// collision mesh
#include "geometry/ChCTriangleMeshSoup.h"
#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"
namespace chrono {
// Static variables
const double IdlerSimple::m_mass = 429.6;
const ChVector<> IdlerSimple::m_inertia = ChVector<>(14.7, 12.55, 12.55);
const std::string IdlerSimple::m_meshName = "idler_mesh";
const std::string IdlerSimple::m_meshFile = utils::GetModelDataFile("data/idlerMesh.obj");
// guessing at these values
const double IdlerSimple::m_radius = 0.255;
const double IdlerSimple::m_width = 0.166;
const double IdlerSimple::m_widthGap = 0.092;
const double IdlerSimple::m_springK = 100000;
const double IdlerSimple::m_springC = 1000;
const double IdlerSimple::m_springRestLength = 1.0;
/*
// -----------------------------------------------------------------------------
// Default shock and spring functors (used for linear elements)
// -----------------------------------------------------------------------------
class LinearSpringForce : public ChSpringForceCallback
{
public:
LinearSpringForce(double k) : m_k(k) {}
virtual double operator()(double time, // current time
double rest_length, // undeformed length
double length, // current length
double vel) // current velocity (positive when extending)
{
return -m_k * (length - rest_length);
}
private:
double m_k;
};
class LinearShockForce : public ChSpringForceCallback
{
public:
LinearShockForce(double c) : m_c(c) {}
virtual double operator()(double time, // current time
double rest_length, // undeformed length
double length, // current length
double vel) // current velocity (positive when extending)
{
return -m_c * vel;
}
private:
double m_c;
};
*/
IdlerSimple::IdlerSimple(const std::string& name,
VisualizationType vis,
CollisionType collide)
: m_vis(vis), m_collide(collide)
// , m_shockCB(NULL), m_springCB(NULL)
{
// create the body, set the basic info
m_idler = ChSharedPtr<ChBody>(new ChBody);
m_idler->SetNameString(name + "_body");
m_idler->SetMass(m_mass);
m_idler->SetInertiaXX(m_inertia);
// create the idler joint
m_idler_joint = ChSharedPtr<ChLinkLockRevolutePrismatic>(new ChLinkLockRevolutePrismatic);
m_idler_joint->SetNameString(name + "_idler_joint");
// create the tensioning linear spring-shock
m_shock = ChSharedPtr<ChLinkSpring>(new ChLinkSpring);
m_shock->SetNameString(name + "_shock");
m_shock->Set_SpringK(m_springK);
m_shock->Set_SpringR(m_springC);
m_shock->Set_SpringRestLength(m_springRestLength);
AddVisualization();
}
IdlerSimple::~IdlerSimple()
{
// delete m_springCB;
// delete m_shockCB;
}
void IdlerSimple::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChCoordsys<>& local_Csys)
{
// add collision geometry
AddCollisionGeometry();
// Express the steering reference frame in the absolute coordinate system.
ChFrame<> idler_to_abs(local_Csys);
idler_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());
// transform the idler body, add to system
m_idler->SetPos(idler_to_abs.GetPos());
m_idler->SetRot(idler_to_abs.GetRot());
chassis->GetSystem()->Add(m_idler);
// init joint, add to system
// body 1 should rotate about z-axis, translate about x-axis of body2
// TODO: (check) idler joint translates, rotates in correct direction.
// NOTE: I created the idler to translate x-dir, rotate about z-dir, according
// to how the chassis is rotated by default.
m_idler_joint->Initialize(m_idler, chassis, m_idler->GetCoord() );
chassis->GetSystem()->AddLink(m_idler_joint);
// init shock, add to system
// put the second marker some length in front of marker1, based on desired preload
double preLoad = 10000; // [N]
// chassis spring attachment point is towards the center of the vehicle
ChVector<> pos_chassis_abs = local_Csys.pos;
if(local_Csys.pos.x < 0 )
pos_chassis_abs.x += m_springRestLength - (preLoad / m_springK);
else
pos_chassis_abs.x -= m_springRestLength - (preLoad / m_springK);
// transform 2nd attachment point to abs coords
pos_chassis_abs = chassis->GetCoord().TransformPointLocalToParent(pos_chassis_abs);
// init. points based on desired preload and free lengths
m_shock->Initialize(m_idler, chassis, false, m_idler->GetPos(), pos_chassis_abs );
// setting rest length should yield desired preload at time = 0
m_shock->Set_SpringRestLength(m_springRestLength);
chassis->GetSystem()->AddLink(m_shock);
}
void IdlerSimple::AddVisualization()
{
// add visualization asset
switch (m_vis) {
case VisualizationType::PRIMITIVES:
{
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
// define the shape with two concentric cyclinders, with a gap.
cyl->GetCylinderGeometry().p1 = ChVector<>(0, 0, m_width/2.0);
cyl->GetCylinderGeometry().p2 = ChVector<>(0, 0, m_widthGap/2.0);
cyl->GetCylinderGeometry().rad = m_radius;
m_idler->AddAsset(cyl);
// second cylinder is a mirror of the first
cyl->GetCylinderGeometry().p1.z = -m_width/2.0;
cyl->GetCylinderGeometry().p2.z = -m_widthGap/2.0;
m_idler->AddAsset(cyl);
// add a color asset
ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
m_idler->AddAsset(mcolor);
break;
}
case VisualizationType::MESH:
{
geometry::ChTriangleMeshConnected trimesh;
trimesh.LoadWavefrontMesh(getMeshFile(), false, false);
ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
trimesh_shape->SetMesh(trimesh);
trimesh_shape->SetName(getMeshName());
m_idler->AddAsset(trimesh_shape);
// add a color asset
ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.5f, 0.1f, 0.4f));
m_idler->AddAsset(mcolor);
break;
}
} // end switch
}
void IdlerSimple::AddCollisionGeometry()
{
// add collision geometrey to the chassis, if enabled
m_idler->SetCollide(true);
m_idler->GetCollisionModel()->ClearModel();
switch (m_collide) {
case CollisionType::NONE:
{
m_idler->SetCollide(false);
}
case CollisionType::PRIMITIVES:
{
double half_cyl_width = (m_width - m_widthGap)/2.0;
ChVector<> shape_offset = ChVector<>(0, 0, half_cyl_width + m_widthGap/2.0);
// use two cylinders.
m_idler->GetCollisionModel()->AddCylinder(m_radius, m_radius, half_cyl_width,
shape_offset,Q_from_AngAxis(CH_C_PI_2,VECT_X));
// mirror first cylinder about the x-y plane
shape_offset.z *= -1;
m_idler->GetCollisionModel()->AddCylinder(m_radius, m_radius, half_cyl_width,
shape_offset,Q_from_AngAxis(CH_C_PI_2,VECT_X));
break;
}
case CollisionType::MESH:
{
// use a triangle mesh
geometry::ChTriangleMeshSoup temp_trianglemesh;
// TODO: fill the triangleMesh here with some track shoe geometry
m_idler->GetCollisionModel()->SetSafeMargin(0.004); // inward safe margin
m_idler->GetCollisionModel()->SetEnvelope(0.010); // distance of the outward "collision envelope"
m_idler->GetCollisionModel()->ClearModel();
// is there an offset??
double shoelength = 0.2;
ChVector<> mesh_displacement(shoelength*0.5,0,0); // since mesh origin is not in body center of mass
m_idler->GetCollisionModel()->AddTriangleMesh(temp_trianglemesh, false, false, mesh_displacement);
break;
}
case CollisionType::CONVEXHULL:
{
// use convex hulls, loaded from file
ChStreamInAsciiFile chull_file(GetChronoDataFile("idler.chulls").c_str());
// transform the collision geometry as needed
double mangle = 45.0; // guess
ChQuaternion<>rot;
rot.Q_from_AngAxis(mangle*(CH_C_PI/180.),VECT_X);
ChMatrix33<> rot_offset(rot);
ChVector<> disp_offset(0,0,0); // no displacement offset
m_idler->GetCollisionModel()->AddConvexHullsFromFile(chull_file, disp_offset, rot_offset);
break;
}
} // end switch
// setup collision family
m_idler->GetCollisionModel()->SetFamily( (int)CollisionFam::GEARS );
// don't collide with other roling elements or the ground
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::HULL );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GEARS );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::WHEELS );
m_idler->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily( (int)CollisionFam::GROUND );
m_idler->GetCollisionModel()->BuildModel();
}
} // end namespace chrono
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief primary index
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "PrimaryIndex.h"
#include "Basics/Exceptions.h"
#include "Basics/hashes.h"
#include "Basics/logging.h"
#include "VocBase/document-collection.h"
#include "VocBase/transaction.h"
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
static uint64_t HashKey (char const* key) {
return TRI_FnvHashString(key);
}
static uint64_t HashElement (TRI_doc_mptr_t const* element) {
return element->_hash;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief determines if a key corresponds to an element
////////////////////////////////////////////////////////////////////////////////
static bool IsEqualKeyElement (char const* key,
TRI_doc_mptr_t const* element) {
// Performance?
// uint64_t hash = HashKey(key);
// return (hash == element->_hash &&
return strcmp(key, TRI_EXTRACT_MARKER_KEY(element)) == 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief determines if two elements are equal
////////////////////////////////////////////////////////////////////////////////
static bool IsEqualElementElement (TRI_doc_mptr_t const* left,
TRI_doc_mptr_t const* right) {
return left->_hash == right->_hash
&& strcmp(TRI_EXTRACT_MARKER_KEY(left), TRI_EXTRACT_MARKER_KEY(right)) == 0;
}
// -----------------------------------------------------------------------------
// --SECTION-- class PrimaryIndex
// -----------------------------------------------------------------------------
uint64_t const PrimaryIndex::InitialSize = 251;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
PrimaryIndex::PrimaryIndex (TRI_document_collection_t* collection)
: Index(0, collection, std::vector<std::vector<triagens::basics::AttributeName>>( { { { TRI_VOC_ATTRIBUTE_KEY, false } } } )) {
uint32_t indexBuckets = 1;
if (collection != nullptr) {
// document is a nullptr in the coordinator case
indexBuckets = collection->_info._indexBuckets;
}
_primaryIndex = new TRI_PrimaryIndex_t(HashKey,
HashElement,
IsEqualKeyElement,
IsEqualElementElement,
indexBuckets,
[] () -> std::string { return "primary"; }
);
}
PrimaryIndex::~PrimaryIndex () {
delete _primaryIndex;
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
size_t PrimaryIndex::size () const {
return _primaryIndex->size();
}
size_t PrimaryIndex::memory () const {
return static_cast<size_t>(
_primaryIndex->size() * sizeof(TRI_doc_mptr_t*) +
_primaryIndex->memoryUsage()
);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return a JSON representation of the index
////////////////////////////////////////////////////////////////////////////////
triagens::basics::Json PrimaryIndex::toJson (TRI_memory_zone_t* zone,
bool withFigures) const {
auto json = Index::toJson(zone, withFigures);
// hard-coded
json("unique", triagens::basics::Json(true))
("sparse", triagens::basics::Json(false));
return json;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return a JSON representation of the index figures
////////////////////////////////////////////////////////////////////////////////
triagens::basics::Json PrimaryIndex::toJsonFigures (TRI_memory_zone_t* zone) const {
triagens::basics::Json json(zone, triagens::basics::Json::Object);
json("memory", triagens::basics::Json(static_cast<double>(memory())));
_primaryIndex->appendToJson(zone, json);
return json;
}
int PrimaryIndex::insert (TRI_doc_mptr_t const*,
bool) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED);
}
int PrimaryIndex::remove (TRI_doc_mptr_t const*,
bool) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief looks up an element given a key
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupKey (char const* key) const {
return _primaryIndex->findByKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief looks up an element given a key
/// returns the index position into which a key would belong in the second
/// parameter. sets position to UINT64_MAX if the position cannot be determined
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupKey (char const* key,
uint64_t& position) const {
// TODO we ignore the position right now. It should be the position it would fit into
position = 0;
return lookupKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// a random order.
/// Returns nullptr if all documents have been returned.
/// Convention: step === 0 indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupRandom(uint64_t& initialPosition,
uint64_t& position,
uint64_t& step,
uint64_t& total) {
return _primaryIndex->findRandom(initialPosition, position, step, total);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// a sequential order.
/// Returns nullptr if all documents have been returned.
/// Convention: position === 0 indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupSequential(uint64_t& position,
uint64_t& total) {
return _primaryIndex->findSequential(position, total);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// reversed sequential order.
/// Returns nullptr if all documents have been returned.
/// Convention: position === UINT64_MAX indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupSequentialReverse(uint64_t& position) {
return _primaryIndex->findSequentialReverse(position);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// returns a status code, and *found will contain a found element (if any)
////////////////////////////////////////////////////////////////////////////////
int PrimaryIndex::insertKey (TRI_doc_mptr_t* header,
void const** found) {
*found = nullptr;
int res = _primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
if (res == TRI_ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED) {
*found = _primaryIndex->find(header);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// this is a special, optimized (read: reduced) variant of the above insert
/// function
////////////////////////////////////////////////////////////////////////////////
void PrimaryIndex::insertKey (TRI_doc_mptr_t* header) {
_primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// this is a special, optimized version that receives the target slot index
/// from a previous lookupKey call
////////////////////////////////////////////////////////////////////////////////
void PrimaryIndex::insertKey (TRI_doc_mptr_t* header,
uint64_t slot) {
_primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
// TODO slot is hint where to insert the element. It is not yet used
//
// if (slot != UINT64_MAX) {
// i = k = slot;
// }
// else {
// i = k = header->_hash % n;
// }
//
}
////////////////////////////////////////////////////////////////////////////////
/// @brief removes an key/element from the index
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::removeKey (char const* key) {
return _primaryIndex->removeByKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief resizes the index
////////////////////////////////////////////////////////////////////////////////
int PrimaryIndex::resize (size_t targetSize) {
return _primaryIndex->resize(targetSize);
}
uint64_t PrimaryIndex::calculateHash (char const* key) {
return HashKey(key);
}
uint64_t PrimaryIndex::calculateHash (char const* key,
size_t length) {
return TRI_FnvHashPointer(static_cast<void const*>(key), length);
}
void PrimaryIndex::invokeOnAllElements (std::function<void(TRI_doc_mptr_t*)> work) {
_primaryIndex->invokeOnAllElements(work);
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Fixed Memory calculation of new Primary Index<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief primary index
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "PrimaryIndex.h"
#include "Basics/Exceptions.h"
#include "Basics/hashes.h"
#include "Basics/logging.h"
#include "VocBase/document-collection.h"
#include "VocBase/transaction.h"
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- private functions
// -----------------------------------------------------------------------------
static uint64_t HashKey (char const* key) {
return TRI_FnvHashString(key);
}
static uint64_t HashElement (TRI_doc_mptr_t const* element) {
return element->_hash;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief determines if a key corresponds to an element
////////////////////////////////////////////////////////////////////////////////
static bool IsEqualKeyElement (char const* key,
TRI_doc_mptr_t const* element) {
// Performance?
// uint64_t hash = HashKey(key);
// return (hash == element->_hash &&
return strcmp(key, TRI_EXTRACT_MARKER_KEY(element)) == 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief determines if two elements are equal
////////////////////////////////////////////////////////////////////////////////
static bool IsEqualElementElement (TRI_doc_mptr_t const* left,
TRI_doc_mptr_t const* right) {
return left->_hash == right->_hash
&& strcmp(TRI_EXTRACT_MARKER_KEY(left), TRI_EXTRACT_MARKER_KEY(right)) == 0;
}
// -----------------------------------------------------------------------------
// --SECTION-- class PrimaryIndex
// -----------------------------------------------------------------------------
uint64_t const PrimaryIndex::InitialSize = 251;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
PrimaryIndex::PrimaryIndex (TRI_document_collection_t* collection)
: Index(0, collection, std::vector<std::vector<triagens::basics::AttributeName>>( { { { TRI_VOC_ATTRIBUTE_KEY, false } } } )) {
uint32_t indexBuckets = 1;
if (collection != nullptr) {
// document is a nullptr in the coordinator case
indexBuckets = collection->_info._indexBuckets;
}
_primaryIndex = new TRI_PrimaryIndex_t(HashKey,
HashElement,
IsEqualKeyElement,
IsEqualElementElement,
indexBuckets,
[] () -> std::string { return "primary"; }
);
}
PrimaryIndex::~PrimaryIndex () {
delete _primaryIndex;
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
size_t PrimaryIndex::size () const {
return _primaryIndex->size();
}
size_t PrimaryIndex::memory () const {
return _primaryIndex->memoryUsage();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return a JSON representation of the index
////////////////////////////////////////////////////////////////////////////////
triagens::basics::Json PrimaryIndex::toJson (TRI_memory_zone_t* zone,
bool withFigures) const {
auto json = Index::toJson(zone, withFigures);
// hard-coded
json("unique", triagens::basics::Json(true))
("sparse", triagens::basics::Json(false));
return json;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief return a JSON representation of the index figures
////////////////////////////////////////////////////////////////////////////////
triagens::basics::Json PrimaryIndex::toJsonFigures (TRI_memory_zone_t* zone) const {
triagens::basics::Json json(zone, triagens::basics::Json::Object);
json("memory", triagens::basics::Json(static_cast<double>(memory())));
_primaryIndex->appendToJson(zone, json);
return json;
}
int PrimaryIndex::insert (TRI_doc_mptr_t const*,
bool) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED);
}
int PrimaryIndex::remove (TRI_doc_mptr_t const*,
bool) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_NOT_IMPLEMENTED);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief looks up an element given a key
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupKey (char const* key) const {
return _primaryIndex->findByKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief looks up an element given a key
/// returns the index position into which a key would belong in the second
/// parameter. sets position to UINT64_MAX if the position cannot be determined
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupKey (char const* key,
uint64_t& position) const {
// TODO we ignore the position right now. It should be the position it would fit into
position = 0;
return lookupKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// a random order.
/// Returns nullptr if all documents have been returned.
/// Convention: step === 0 indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupRandom(uint64_t& initialPosition,
uint64_t& position,
uint64_t& step,
uint64_t& total) {
return _primaryIndex->findRandom(initialPosition, position, step, total);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// a sequential order.
/// Returns nullptr if all documents have been returned.
/// Convention: position === 0 indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupSequential(uint64_t& position,
uint64_t& total) {
return _primaryIndex->findSequential(position, total);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief a method to iterate over all elements in the index in
/// reversed sequential order.
/// Returns nullptr if all documents have been returned.
/// Convention: position === UINT64_MAX indicates a new start.
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::lookupSequentialReverse(uint64_t& position) {
return _primaryIndex->findSequentialReverse(position);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// returns a status code, and *found will contain a found element (if any)
////////////////////////////////////////////////////////////////////////////////
int PrimaryIndex::insertKey (TRI_doc_mptr_t* header,
void const** found) {
*found = nullptr;
int res = _primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
if (res == TRI_ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED) {
*found = _primaryIndex->find(header);
}
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// this is a special, optimized (read: reduced) variant of the above insert
/// function
////////////////////////////////////////////////////////////////////////////////
void PrimaryIndex::insertKey (TRI_doc_mptr_t* header) {
_primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief adds a key/element to the index
/// this is a special, optimized version that receives the target slot index
/// from a previous lookupKey call
////////////////////////////////////////////////////////////////////////////////
void PrimaryIndex::insertKey (TRI_doc_mptr_t* header,
uint64_t slot) {
_primaryIndex->insert(TRI_EXTRACT_MARKER_KEY(header), header, false);
// TODO slot is hint where to insert the element. It is not yet used
//
// if (slot != UINT64_MAX) {
// i = k = slot;
// }
// else {
// i = k = header->_hash % n;
// }
//
}
////////////////////////////////////////////////////////////////////////////////
/// @brief removes an key/element from the index
////////////////////////////////////////////////////////////////////////////////
TRI_doc_mptr_t* PrimaryIndex::removeKey (char const* key) {
return _primaryIndex->removeByKey(key);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief resizes the index
////////////////////////////////////////////////////////////////////////////////
int PrimaryIndex::resize (size_t targetSize) {
return _primaryIndex->resize(targetSize);
}
uint64_t PrimaryIndex::calculateHash (char const* key) {
return HashKey(key);
}
uint64_t PrimaryIndex::calculateHash (char const* key,
size_t length) {
return TRI_FnvHashPointer(static_cast<void const*>(key), length);
}
void PrimaryIndex::invokeOnAllElements (std::function<void(TRI_doc_mptr_t*)> work) {
_primaryIndex->invokeOnAllElements(work);
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>
|
<commit_before>//
// Typer.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/06/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "Typer.hpp"
using namespace Utility;
Typer::Typer(const std::string &string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate) :
frequency_(frequency),
counter_(-delay),
delegate_(delegate),
character_mapper_(std::move(character_mapper)) {
// Retain only those characters that actually map to something.
if(sequence_for_character(Typer::BeginString)) {
string_ += Typer::BeginString;
}
if(sequence_for_character(Typer::EndString)) {
string_ += Typer::EndString;
}
append(string);
}
void Typer::run_for(const HalfCycles duration) {
if(string_pointer_ >= string_.size()) {
return;
}
if(counter_ < 0 && counter_ + duration >= 0) {
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
counter_ += duration;
while(string_pointer_ < string_.size() && counter_ > frequency_) {
counter_ -= frequency_;
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
}
void Typer::append(const std::string &string) {
// Remove any characters that are already completely done;
// otherwise things may accumulate here indefinitely.
string_.erase(string_.begin(), string_.begin() + ssize_t(string_pointer_));
string_pointer_ = 0;
// If the final character in the string is not Typer::EndString
// then this machine doesn't need Begin and End, so don't worry about it.
ssize_t insertion_position = ssize_t(string_.size());
if(string_.back() == Typer::EndString) --insertion_position;
string_.reserve(string_.size() + string.size());
for(const char c : string) {
if(sequence_for_character(c)) {
string_.insert(string_.begin() + insertion_position, c);
++insertion_position;
}
}
}
const uint16_t *Typer::sequence_for_character(char c) const {
const uint16_t *const sequence = character_mapper_->sequence_for_character(c);
if(!sequence || sequence[0] == KeyboardMachine::MappedMachine::KeyNotMapped) {
return nullptr;
}
return sequence;
}
uint16_t Typer::try_type_next_character() {
const uint16_t *const sequence = sequence_for_character(string_[string_pointer_]);
if(!sequence) {
return 0;
}
// If this is the start of the output sequence, start with a reset all keys.
// Then pause unless the caracter mapper says not to.
if(!phase_) {
delegate_->clear_all_keys();
if(character_mapper_->needs_pause_after_reset_all_keys()) {
return 0xffff; // Arbitrarily. Anything non-zero will do.
}
}
// Advance phase.
++phase_;
// If the sequence is over, stop.
if(sequence[phase_ - 1] == KeyboardMachine::MappedMachine::KeyEndSequence) {
return 0;
}
// Otherwise, type the key.
delegate_->set_key_state(sequence[phase_ - 1], true);
return sequence[phase_ - 1];
}
bool Typer::type_next_character() {
if(string_pointer_ == string_.size()) return false;
while(true) {
const uint16_t key_pressed = try_type_next_character();
if(!key_pressed) {
phase_ = 0;
++string_pointer_;
if(string_pointer_ == string_.size()) return false;
}
if(character_mapper_->needs_pause_after_key(key_pressed)) {
break;
}
}
return true;
}
// MARK: - Character mapper
uint16_t *CharacterMapper::table_lookup_sequence_for_character(KeySequence *sequences, std::size_t length, char character) {
std::size_t ucharacter = static_cast<std::size_t>((unsigned char)character);
if(ucharacter > (length / sizeof(KeySequence))) return nullptr;
if(sequences[ucharacter][0] == KeyboardMachine::MappedMachine::KeyNotMapped) return nullptr;
return sequences[ucharacter];
}
<commit_msg>Fixes off-by-one range test.<commit_after>//
// Typer.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/06/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "Typer.hpp"
using namespace Utility;
Typer::Typer(const std::string &string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate) :
frequency_(frequency),
counter_(-delay),
delegate_(delegate),
character_mapper_(std::move(character_mapper)) {
// Retain only those characters that actually map to something.
if(sequence_for_character(Typer::BeginString)) {
string_ += Typer::BeginString;
}
if(sequence_for_character(Typer::EndString)) {
string_ += Typer::EndString;
}
append(string);
}
void Typer::run_for(const HalfCycles duration) {
if(string_pointer_ >= string_.size()) {
return;
}
if(counter_ < 0 && counter_ + duration >= 0) {
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
counter_ += duration;
while(string_pointer_ < string_.size() && counter_ > frequency_) {
counter_ -= frequency_;
if(!type_next_character()) {
delegate_->typer_reset(this);
}
}
}
void Typer::append(const std::string &string) {
// Remove any characters that are already completely done;
// otherwise things may accumulate here indefinitely.
string_.erase(string_.begin(), string_.begin() + ssize_t(string_pointer_));
string_pointer_ = 0;
// If the final character in the string is not Typer::EndString
// then this machine doesn't need Begin and End, so don't worry about it.
ssize_t insertion_position = ssize_t(string_.size());
if(string_.back() == Typer::EndString) --insertion_position;
string_.reserve(string_.size() + string.size());
for(const char c : string) {
if(sequence_for_character(c)) {
string_.insert(string_.begin() + insertion_position, c);
++insertion_position;
}
}
}
const uint16_t *Typer::sequence_for_character(char c) const {
const uint16_t *const sequence = character_mapper_->sequence_for_character(c);
if(!sequence || sequence[0] == KeyboardMachine::MappedMachine::KeyNotMapped) {
return nullptr;
}
return sequence;
}
uint16_t Typer::try_type_next_character() {
const uint16_t *const sequence = sequence_for_character(string_[string_pointer_]);
if(!sequence) {
return 0;
}
// If this is the start of the output sequence, start with a reset all keys.
// Then pause unless the caracter mapper says not to.
if(!phase_) {
delegate_->clear_all_keys();
if(character_mapper_->needs_pause_after_reset_all_keys()) {
return 0xffff; // Arbitrarily. Anything non-zero will do.
}
}
// Advance phase.
++phase_;
// If the sequence is over, stop.
if(sequence[phase_ - 1] == KeyboardMachine::MappedMachine::KeyEndSequence) {
return 0;
}
// Otherwise, type the key.
delegate_->set_key_state(sequence[phase_ - 1], true);
return sequence[phase_ - 1];
}
bool Typer::type_next_character() {
if(string_pointer_ == string_.size()) return false;
while(true) {
const uint16_t key_pressed = try_type_next_character();
if(!key_pressed) {
phase_ = 0;
++string_pointer_;
if(string_pointer_ == string_.size()) return false;
}
if(character_mapper_->needs_pause_after_key(key_pressed)) {
break;
}
}
return true;
}
// MARK: - Character mapper
uint16_t *CharacterMapper::table_lookup_sequence_for_character(KeySequence *sequences, std::size_t length, char character) {
std::size_t ucharacter = static_cast<std::size_t>((unsigned char)character);
if(ucharacter >= (length / sizeof(KeySequence))) return nullptr;
if(sequences[ucharacter][0] == KeyboardMachine::MappedMachine::KeyNotMapped) return nullptr;
return sequences[ucharacter];
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "grpc_cb_core/server.h"
int main() {
grpc_cb_core::Server server;
return 0;
}
<commit_msg>Fix include.<commit_after>#include <iostream>
#include "grpc_cb_core/server/server.h"
int main() {
grpc_cb_core::Server server;
return 0;
}
<|endoftext|>
|
<commit_before>
#include <binder/ProcessState.h>
#include <cutils/properties.h>
#include <utils/SystemClock.h>
#include <fcntl.h>
#include <time.h>
#include <vector>
#include "libpreview.h"
#include "SimpleH264Encoder.h"
using android::Mutex;
libpreview::Client *libpreviewClient;
SimpleH264Encoder *simpleH264Encoder;
Mutex simpleH264EncoderLock;
int fd;
std::vector<int> outputFrameSize;
void libpreview_FrameCallback(void *userData,
void *frame,
libpreview::FrameFormat format,
size_t width,
size_t height,
libpreview::FrameOwner owner)
{
(void) userData;
Mutex::Autolock autolock(simpleH264EncoderLock);
if (simpleH264Encoder == nullptr) {
libpreviewClient->releaseFrame(owner);
return;
}
SimpleH264Encoder::InputFrame inputFrame;
SimpleH264Encoder::InputFrameInfo inputFrameInfo;
#ifdef ANDROID
inputFrameInfo.captureTimeMs = android::elapsedRealtime();
#else
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
inputFrameInfo.captureTimeMs = (int64_t)now.tv_sec * 1e3 + (int64_t)now.tv_nsec / 1e6;
#endif
if (!simpleH264Encoder->getInputFrame(inputFrame)) {
printf("Unable to get input frame\n");
return;
}
switch (format) {
case libpreview::FRAMEFORMAT_YVU420SP:
if (inputFrame.format != libpreview::FRAMEFORMAT_YVU420SP) {
printf(
"Unsupported encoder format: %d = %d\n",
inputFrame.format,
libpreview::FRAMEFORMAT_YVU420SP
);
return;
}
// Copy Y plane
memcpy(inputFrame.data, frame, width * height);
// Copy UV plane while converting from YVU420SemiPlaner to YUV420SemiPlaner
{
uint8_t *s = static_cast<uint8_t *>(frame) + width * height;
uint8_t *d = static_cast<uint8_t *>(inputFrame.data) + width * height;
uint8_t *dEnd = d + width * height / 2;
for (; d < dEnd; s += 2, d += 2) {
d[0] = s[1];
d[1] = s[0];
}
}
break;
case libpreview::FRAMEFORMAT_YUV420SP:
if (inputFrame.format != format) {
if (inputFrame.format == libpreview::FRAMEFORMAT_YUV420SP_VENUS &&
libpreview::VENUS_Y_STRIDE(width) == width &&
libpreview::VENUS_C_PLANE_OFFSET(width, height) == width * height) {
// FRAMEFORMAT_YUV420SP_VENUS == FRAMEFORMAT_YUV420SP in this case so
// don't abort
} else {
printf("Unsupported encoder formaT: %d != %d\n", inputFrame.format, format);
return;
}
}
memcpy(inputFrame.data, frame, inputFrame.size);
break;
case libpreview::FRAMEFORMAT_YUV420SP_VENUS:
if (inputFrame.format != format) {
printf("Unsupported encoder format: %d != %d\n", inputFrame.format, format);
return;
}
switch (inputFrame.format) {
case libpreview::FRAMEFORMAT_YUV420SP_VENUS:
memcpy(inputFrame.data, frame, inputFrame.size);
break;
case libpreview::FRAMEFORMAT_YUV420SP:
// Copy Y plane
memcpy(inputFrame.data, frame, width * height);
// Pack and copy UV plane
memcpy(
static_cast<uint8_t *>(inputFrame.data) + width * height,
static_cast<uint8_t *>(frame) + libpreview::VENUS_C_PLANE_OFFSET(width, height),
width * height / 2
);
break;
default:
break;
}
break;
default:
printf("Unsupported format: %d\n", format);
return;
}
simpleH264Encoder->nextFrame(inputFrame, inputFrameInfo);
libpreviewClient->releaseFrame(owner);
}
void libpreview_AbandonedCallback(void *userData)
{
(void) userData;
printf("libpreview_AbandonedCallback\n");
exit(1);
}
void frameOutCallback(SimpleH264Encoder::EncodedFrameInfo& info) {
outputFrameSize.erase(outputFrameSize.begin());
outputFrameSize.push_back(info.encodedFrameLength);
int64_t bitrate = 0;
for (auto i = 0; i < outputFrameSize.size(); i++) {
bitrate += outputFrameSize[i] * 8;
}
printf("Frame %lld size=%8d keyframe=%d (bitrate: %lld)\n",
info.input.captureTimeMs,
info.encodedFrameLength,
info.keyFrame,
bitrate
);
TEMP_FAILURE_RETRY(
write(
fd,
info.encodedFrame,
info.encodedFrameLength
)
);
}
int main(int argc, char **argv)
{
(void) argc;
(void) argv;
#ifdef ANDROID
android::sp<android::ProcessState> ps = android::ProcessState::self();
ps->startThreadPool();
#endif
libpreviewClient = libpreview::open(libpreview_FrameCallback, libpreview_AbandonedCallback, 0);
if (!libpreviewClient) {
printf("Unable to open libpreview\n");
return 1;
}
size_t width;
size_t height;
libpreviewClient->getSize(width, height);
int vbr = property_get_int32("ro.silk.camera.vbr", 1024);
int fps = property_get_int32("ro.silk.camera.fps", 24);
outputFrameSize.resize(fps);
for (auto i = 0; i < fps; i++) {
outputFrameSize.push_back(0);
}
for (auto i = 0; i < 1; i++) {
char filename[32];
snprintf(filename, sizeof(filename) - 1, "/data/vid_%d.h264", i);
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0440);
if (fd < 0) {
printf("Unable to open output file: %s\n", filename);
}
printf("Output file: %s\n", filename);
{
Mutex::Autolock autolock(simpleH264EncoderLock);
simpleH264Encoder = SimpleH264Encoder::Create(
width, height, vbr, fps,
frameOutCallback,
nullptr
);
}
printf("Encoder started\n");
if (simpleH264Encoder == nullptr) {
printf("Unable to create a SimpleH264Encoder\n");
return 1;
}
// Fiddle with the bitrate while recording just because we can
for (int j = 0; j < 10; j++) {
int bitRateK = 1000 * (j+1) / 10;
simpleH264Encoder->setBitRate(bitRateK);
printf(". (bitrate=%dk)\n", bitRateK);
sleep(1);
}
simpleH264Encoder->stop();
{
Mutex::Autolock autolock(simpleH264EncoderLock);
delete simpleH264Encoder;
simpleH264Encoder = nullptr;
}
close(fd);
printf("Encoder stopped\n");
sleep(1); // Take a breath...
}
printf("Releasing libpreview\n");
libpreviewClient->release();
return 0;
}
<commit_msg>++casts for picky compilers<commit_after>
#include <binder/ProcessState.h>
#include <cutils/properties.h>
#include <utils/SystemClock.h>
#include <fcntl.h>
#include <time.h>
#include <vector>
#include "libpreview.h"
#include "SimpleH264Encoder.h"
using android::Mutex;
libpreview::Client *libpreviewClient;
SimpleH264Encoder *simpleH264Encoder;
Mutex simpleH264EncoderLock;
int fd;
std::vector<int> outputFrameSize;
void libpreview_FrameCallback(void *userData,
void *frame,
libpreview::FrameFormat format,
size_t width,
size_t height,
libpreview::FrameOwner owner)
{
(void) userData;
Mutex::Autolock autolock(simpleH264EncoderLock);
if (simpleH264Encoder == nullptr) {
libpreviewClient->releaseFrame(owner);
return;
}
SimpleH264Encoder::InputFrame inputFrame;
SimpleH264Encoder::InputFrameInfo inputFrameInfo;
#ifdef ANDROID
inputFrameInfo.captureTimeMs = android::elapsedRealtime();
#else
timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
inputFrameInfo.captureTimeMs = (int64_t)now.tv_sec * 1e3 + (int64_t)now.tv_nsec / 1e6;
#endif
if (!simpleH264Encoder->getInputFrame(inputFrame)) {
printf("Unable to get input frame\n");
return;
}
switch (format) {
case libpreview::FRAMEFORMAT_YVU420SP:
if (inputFrame.format != libpreview::FRAMEFORMAT_YVU420SP) {
printf(
"Unsupported encoder format: %d = %d\n",
inputFrame.format,
libpreview::FRAMEFORMAT_YVU420SP
);
return;
}
// Copy Y plane
memcpy(inputFrame.data, frame, width * height);
// Copy UV plane while converting from YVU420SemiPlaner to YUV420SemiPlaner
{
uint8_t *s = static_cast<uint8_t *>(frame) + width * height;
uint8_t *d = static_cast<uint8_t *>(inputFrame.data) + width * height;
uint8_t *dEnd = d + width * height / 2;
for (; d < dEnd; s += 2, d += 2) {
d[0] = s[1];
d[1] = s[0];
}
}
break;
case libpreview::FRAMEFORMAT_YUV420SP:
if (inputFrame.format != format) {
if (inputFrame.format == libpreview::FRAMEFORMAT_YUV420SP_VENUS &&
libpreview::VENUS_Y_STRIDE(width) == static_cast<int>(width) &&
libpreview::VENUS_C_PLANE_OFFSET(width, height) == static_cast<int>(width * height)) {
// FRAMEFORMAT_YUV420SP_VENUS == FRAMEFORMAT_YUV420SP in this case so
// don't abort
} else {
printf("Unsupported encoder formaT: %d != %d\n", inputFrame.format, format);
return;
}
}
memcpy(inputFrame.data, frame, inputFrame.size);
break;
case libpreview::FRAMEFORMAT_YUV420SP_VENUS:
if (inputFrame.format != format) {
printf("Unsupported encoder format: %d != %d\n", inputFrame.format, format);
return;
}
switch (inputFrame.format) {
case libpreview::FRAMEFORMAT_YUV420SP_VENUS:
memcpy(inputFrame.data, frame, inputFrame.size);
break;
case libpreview::FRAMEFORMAT_YUV420SP:
// Copy Y plane
memcpy(inputFrame.data, frame, width * height);
// Pack and copy UV plane
memcpy(
static_cast<uint8_t *>(inputFrame.data) + width * height,
static_cast<uint8_t *>(frame) + libpreview::VENUS_C_PLANE_OFFSET(width, height),
width * height / 2
);
break;
default:
break;
}
break;
default:
printf("Unsupported format: %d\n", format);
return;
}
simpleH264Encoder->nextFrame(inputFrame, inputFrameInfo);
libpreviewClient->releaseFrame(owner);
}
void libpreview_AbandonedCallback(void *userData)
{
(void) userData;
printf("libpreview_AbandonedCallback\n");
exit(1);
}
void frameOutCallback(SimpleH264Encoder::EncodedFrameInfo& info) {
outputFrameSize.erase(outputFrameSize.begin());
outputFrameSize.push_back(info.encodedFrameLength);
int64_t bitrate = 0;
for (auto i = 0u; i < outputFrameSize.size(); i++) {
bitrate += outputFrameSize[i] * 8;
}
printf("Frame %lld size=%8d keyframe=%d (bitrate: %lld)\n",
info.input.captureTimeMs,
info.encodedFrameLength,
info.keyFrame,
bitrate
);
TEMP_FAILURE_RETRY(
write(
fd,
info.encodedFrame,
info.encodedFrameLength
)
);
}
int main(int argc, char **argv)
{
(void) argc;
(void) argv;
#ifdef ANDROID
android::sp<android::ProcessState> ps = android::ProcessState::self();
ps->startThreadPool();
#endif
libpreviewClient = libpreview::open(libpreview_FrameCallback, libpreview_AbandonedCallback, 0);
if (!libpreviewClient) {
printf("Unable to open libpreview\n");
return 1;
}
size_t width;
size_t height;
libpreviewClient->getSize(width, height);
int vbr = property_get_int32("ro.silk.camera.vbr", 1024);
int fps = property_get_int32("ro.silk.camera.fps", 24);
outputFrameSize.resize(fps);
for (auto i = 0; i < fps; i++) {
outputFrameSize.push_back(0);
}
for (auto i = 0; i < 1; i++) {
char filename[32];
snprintf(filename, sizeof(filename) - 1, "/data/vid_%d.h264", i);
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0440);
if (fd < 0) {
printf("Unable to open output file: %s\n", filename);
}
printf("Output file: %s\n", filename);
{
Mutex::Autolock autolock(simpleH264EncoderLock);
simpleH264Encoder = SimpleH264Encoder::Create(
width, height, vbr, fps,
frameOutCallback,
nullptr
);
}
printf("Encoder started\n");
if (simpleH264Encoder == nullptr) {
printf("Unable to create a SimpleH264Encoder\n");
return 1;
}
// Fiddle with the bitrate while recording just because we can
for (int j = 0; j < 10; j++) {
int bitRateK = 1000 * (j+1) / 10;
simpleH264Encoder->setBitRate(bitRateK);
printf(". (bitrate=%dk)\n", bitRateK);
sleep(1);
}
simpleH264Encoder->stop();
{
Mutex::Autolock autolock(simpleH264EncoderLock);
delete simpleH264Encoder;
simpleH264Encoder = nullptr;
}
close(fd);
printf("Encoder stopped\n");
sleep(1); // Take a breath...
}
printf("Releasing libpreview\n");
libpreviewClient->release();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: WinFOPImpl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hro $ $Date: 2002-08-14 15:45:02 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _WINDIRBROWSEIMPL_HXX_
#include "WinFOPImpl.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_FILEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _FOPEVENTDISPATCHER_HXX_
#include "FopEvtDisp.hxx"
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _FOLDERPICKER_HXX_
#include "FolderPicker.hxx"
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::EventObject;
using rtl::OUString;
using namespace com::sun::star::ui::dialogs;
using osl::FileBase;
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
const OUString BACKSLASH = OUString::createFromAscii( "\\" );
//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
CWinFolderPickerImpl::CWinFolderPickerImpl( CFolderPicker* aFolderPicker ) :
CMtaFolderPicker( BIF_RETURNONLYFSDIRS | BIF_RETURNFSANCESTORS | BIF_EDITBOX | BIF_VALIDATE ),
m_pFolderPicker( aFolderPicker ),
m_nLastDlgResult( ::com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL )
{
}
//------------------------------------------------------------------------
// get directory in URL format, convert it to system format and set the
// member variable
// If the given URL for the directory is invalid the function throws an
// IllegalArgumentException
// If the specified path is well formed but invalid for the underlying
// OS the FolderPicker starts in the root of the file system hierarchie
//------------------------------------------------------------------------
void SAL_CALL CWinFolderPickerImpl::setDisplayDirectory( const OUString& aDirectory )
throw( IllegalArgumentException, RuntimeException )
{
OUString sysDir;
if( aDirectory.getLength( ) )
{
// assuming that this function succeeds after successful execution
// of getAbsolutePath
::osl::FileBase::RC rc =
::osl::FileBase::getSystemPathFromFileURL( aDirectory, sysDir );
if ( ::osl::FileBase::E_None != rc )
throw IllegalArgumentException(
OUString::createFromAscii( "directory is not a valid file url" ),
static_cast< XFolderPicker* >( m_pFolderPicker ),
1 );
// we ensure that there is a trailing '/' at the end of
// he given file url, because the windows functions only
// works correctly when providing "c:\" or an environment
// variable like "=c:=c:\.." etc. is set, else the
// FolderPicker would stand in the root of the shell
// hierarchie which is the desktop folder
if ( sysDir.lastIndexOf( BACKSLASH ) != (sysDir.getLength( ) - 1) )
sysDir += BACKSLASH;
}
// call base class method
CMtaFolderPicker::setDisplayDirectory( sysDir );
}
//------------------------------------------------------------------------
// we return the directory in URL format
//------------------------------------------------------------------------
OUString CWinFolderPickerImpl::getDisplayDirectory( )
throw( RuntimeException )
{
// call base class method to get the directory in system format
OUString displayDirectory = CMtaFolderPicker::getDisplayDirectory( );
OUString displayDirectoryURL;
if ( displayDirectory.getLength( ) )
::osl::FileBase::getFileURLFromSystemPath( displayDirectory, displayDirectoryURL );
return displayDirectoryURL;
}
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
OUString SAL_CALL CWinFolderPickerImpl::getDirectory( ) throw( RuntimeException )
{
OUString sysDir = CMtaFolderPicker::getDirectory( );
OUString dirURL;
if ( sysDir.getLength( ) )
::osl::FileBase::getFileURLFromSystemPath( sysDir, dirURL );
return dirURL;
}
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
sal_Int16 SAL_CALL CWinFolderPickerImpl::execute( ) throw( RuntimeException )
{
return m_nLastDlgResult = CMtaFolderPicker::browseForFolder( ) ?
::com::sun::star::ui::dialogs::ExecutableDialogResults::OK :
::com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL;
}
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
void CWinFolderPickerImpl::onSelChanged( const OUString& aNewPath )
{
setStatusText( aNewPath );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.152); FILE MERGED 2005/09/05 17:13:44 rt 1.2.152.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: WinFOPImpl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:50:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _WINDIRBROWSEIMPL_HXX_
#include "WinFOPImpl.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_FILEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _FOPEVENTDISPATCHER_HXX_
#include "FopEvtDisp.hxx"
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _FOLDERPICKER_HXX_
#include "FolderPicker.hxx"
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::EventObject;
using rtl::OUString;
using namespace com::sun::star::ui::dialogs;
using osl::FileBase;
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
const OUString BACKSLASH = OUString::createFromAscii( "\\" );
//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
CWinFolderPickerImpl::CWinFolderPickerImpl( CFolderPicker* aFolderPicker ) :
CMtaFolderPicker( BIF_RETURNONLYFSDIRS | BIF_RETURNFSANCESTORS | BIF_EDITBOX | BIF_VALIDATE ),
m_pFolderPicker( aFolderPicker ),
m_nLastDlgResult( ::com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL )
{
}
//------------------------------------------------------------------------
// get directory in URL format, convert it to system format and set the
// member variable
// If the given URL for the directory is invalid the function throws an
// IllegalArgumentException
// If the specified path is well formed but invalid for the underlying
// OS the FolderPicker starts in the root of the file system hierarchie
//------------------------------------------------------------------------
void SAL_CALL CWinFolderPickerImpl::setDisplayDirectory( const OUString& aDirectory )
throw( IllegalArgumentException, RuntimeException )
{
OUString sysDir;
if( aDirectory.getLength( ) )
{
// assuming that this function succeeds after successful execution
// of getAbsolutePath
::osl::FileBase::RC rc =
::osl::FileBase::getSystemPathFromFileURL( aDirectory, sysDir );
if ( ::osl::FileBase::E_None != rc )
throw IllegalArgumentException(
OUString::createFromAscii( "directory is not a valid file url" ),
static_cast< XFolderPicker* >( m_pFolderPicker ),
1 );
// we ensure that there is a trailing '/' at the end of
// he given file url, because the windows functions only
// works correctly when providing "c:\" or an environment
// variable like "=c:=c:\.." etc. is set, else the
// FolderPicker would stand in the root of the shell
// hierarchie which is the desktop folder
if ( sysDir.lastIndexOf( BACKSLASH ) != (sysDir.getLength( ) - 1) )
sysDir += BACKSLASH;
}
// call base class method
CMtaFolderPicker::setDisplayDirectory( sysDir );
}
//------------------------------------------------------------------------
// we return the directory in URL format
//------------------------------------------------------------------------
OUString CWinFolderPickerImpl::getDisplayDirectory( )
throw( RuntimeException )
{
// call base class method to get the directory in system format
OUString displayDirectory = CMtaFolderPicker::getDisplayDirectory( );
OUString displayDirectoryURL;
if ( displayDirectory.getLength( ) )
::osl::FileBase::getFileURLFromSystemPath( displayDirectory, displayDirectoryURL );
return displayDirectoryURL;
}
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
OUString SAL_CALL CWinFolderPickerImpl::getDirectory( ) throw( RuntimeException )
{
OUString sysDir = CMtaFolderPicker::getDirectory( );
OUString dirURL;
if ( sysDir.getLength( ) )
::osl::FileBase::getFileURLFromSystemPath( sysDir, dirURL );
return dirURL;
}
//------------------------------------------------------------------------
//
//------------------------------------------------------------------------
sal_Int16 SAL_CALL CWinFolderPickerImpl::execute( ) throw( RuntimeException )
{
return m_nLastDlgResult = CMtaFolderPicker::browseForFolder( ) ?
::com::sun::star::ui::dialogs::ExecutableDialogResults::OK :
::com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL;
}
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
void CWinFolderPickerImpl::onSelChanged( const OUString& aNewPath )
{
setStatusText( aNewPath );
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "ListenTask.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/Logger.h"
#include "Scheduler/Acceptor.h"
#include "Ssl/SslServerFeature.h"
using namespace arangodb;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
ListenTask::ListenTask(EventLoop loop, Endpoint* endpoint)
: Task(loop, "ListenTask"),
_endpoint(endpoint),
_bound(false),
_ioService(loop._ioService),
_acceptor(Acceptor::factory(*loop._ioService, endpoint)) {}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void ListenTask::start() {
try {
_acceptor->open();
_bound = true;
} catch (boost::system::system_error const& err) {
LOG(WARN) << "failed to open endpoint '" << _endpoint->specification()
<< "' with error: " << err.what();
return;
} catch (std::exception const& err) {
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "failed to open endpoint '" << _endpoint->specification()
<< "' with error: " << err.what();
}
_handler = [this](boost::system::error_code const& ec) {
if (ec) {
if (ec == boost::asio::error::operation_aborted) {
return;
}
++_acceptFailures;
if (_acceptFailures < MAX_ACCEPT_ERRORS) {
LOG(WARN) << "accept failed: " << ec.message();
} else if (_acceptFailures == MAX_ACCEPT_ERRORS) {
LOG(WARN) << "accept failed: " << ec.message();
LOG(WARN) << "too many accept failures, stopping to report";
}
}
ConnectionInfo info;
auto peer = _acceptor->movePeer();
// set the endpoint
info.endpoint = _endpoint->specification();
info.endpointType = _endpoint->domainType();
info.encryptionType = _endpoint->encryption();
info.clientAddress = peer->peerAddress();
info.clientPort = peer->peerPort();
info.serverAddress = _endpoint->host();
info.serverPort = _endpoint->port();
handleConnected(std::move(peer), std::move(info));
if (_bound) {
_acceptor->asyncAccept(_handler);
}
};
_acceptor->asyncAccept(_handler);
}
void ListenTask::stop() {
if (!_bound) {
return;
}
_bound = false;
_acceptor->close();
}
<commit_msg>fix logtopic<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "ListenTask.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/Logger.h"
#include "Scheduler/Acceptor.h"
#include "Ssl/SslServerFeature.h"
using namespace arangodb;
using namespace arangodb::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
ListenTask::ListenTask(EventLoop loop, Endpoint* endpoint)
: Task(loop, "ListenTask"),
_endpoint(endpoint),
_bound(false),
_ioService(loop._ioService),
_acceptor(Acceptor::factory(*loop._ioService, endpoint)) {}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void ListenTask::start() {
try {
_acceptor->open();
_bound = true;
} catch (boost::system::system_error const& err) {
LOG_TOPIC(WARN, arangodb::Logger::COMMUNICATION) << "failed to open endpoint '" << _endpoint->specification()
<< "' with error: " << err.what();
return;
} catch (std::exception const& err) {
LOG_TOPIC(WARN, arangodb::Logger::COMMUNICATION) << "failed to open endpoint '" << _endpoint->specification()
<< "' with error: " << err.what();
}
_handler = [this](boost::system::error_code const& ec) {
if (ec) {
if (ec == boost::asio::error::operation_aborted) {
return;
}
++_acceptFailures;
if (_acceptFailures < MAX_ACCEPT_ERRORS) {
LOG(WARN) << "accept failed: " << ec.message();
} else if (_acceptFailures == MAX_ACCEPT_ERRORS) {
LOG(WARN) << "accept failed: " << ec.message();
LOG(WARN) << "too many accept failures, stopping to report";
}
}
ConnectionInfo info;
auto peer = _acceptor->movePeer();
// set the endpoint
info.endpoint = _endpoint->specification();
info.endpointType = _endpoint->domainType();
info.encryptionType = _endpoint->encryption();
info.clientAddress = peer->peerAddress();
info.clientPort = peer->peerPort();
info.serverAddress = _endpoint->host();
info.serverPort = _endpoint->port();
handleConnected(std::move(peer), std::move(info));
if (_bound) {
_acceptor->asyncAccept(_handler);
}
};
_acceptor->asyncAccept(_handler);
}
void ListenTask::stop() {
if (!_bound) {
return;
}
_bound = false;
_acceptor->close();
}
<|endoftext|>
|
<commit_before>
// A Sample of ORM Lite
// https://github.com/BOT-Man-JL/ORM-Lite
// BOT Man, 2016
// gcc -std=c++11 Sample.cpp "src/sqlite3.c" -lstdc++ -lpthread -ldl -o Sample
#include <string>
#include <iostream>
#include "src/ORMLite.h"
using namespace BOT_ORM;
/* #0 Basic Usage */
class MyClass
{
// Inject ORM-Lite into this Class
ORMAP (MyClass, id, score, name)
public:
long id;
double score;
std::string name;
};
int main ()
{
/* #1 Basic Usage */
// Store the Data in "test.db"
ORMapper<MyClass> mapper ("test.db");
// Create a table for "MyClass"
mapper.CreateTbl ();
// Insert Values into the table
std::vector<MyClass> initObjs =
{
{ 0, 0.2, "John" },
{ 1, 0.4, "Jack" },
{ 2, 0.6, "Jess" }
};
for (const auto obj : initObjs)
mapper.Insert (obj);
// Update Entry by KEY (id)
initObjs[1].score = 1.0;
mapper.Update (initObjs[1]);
// Delete Entry by KEY (id)
mapper.Delete (initObjs[2]);
// Select All to Vector
auto query0 = mapper.Query (MyClass ()).ToVector ();
// query0 = [{ 0, 0.2, "John"},
// { 1, 1.0, "Jack"}]
// If 'Insert' Failed, Print the latest Error Message
if (!mapper.Insert (MyClass { 1, 0, "Joke" }))
auto err = mapper.ErrMsg ();
// err = "SQL error: UNIQUE constraint failed: MyClass.id"
/* #2 Batch Operations */
// Insert by Batch Insert
// Performance is much Better than Separated Insert :-)
std::vector<MyClass> dataToSeed;
for (long i = 50; i < 10000; i++)
dataToSeed.emplace_back (MyClass { i, i * 0.2, "July" });
auto tb = clock ();
mapper.Insert (dataToSeed);
std::cout << clock () - tb << std::endl;
// Update by Batch Update
for (size_t i = 0; i < 9950; i++)
dataToSeed[i].score += 1;
mapper.Update (dataToSeed);
/* #3 Composite Query */
// Define a Query Helper Object
MyClass _mc;
// Select by Query :-)
auto query1 = mapper.Query (_mc) // Link '_mc' to its fields
.Where (
Expr (_mc.name, "=", "July") &&
(
Expr (_mc.id, "<=", 90) &&
Expr (_mc.id, ">=", 60)
)
)
.OrderBy (_mc.id, true)
.Limit (3, 10)
.ToVector ();
// Select by SQL, NOT Recommended :-(
std::vector<MyClass> query2;
mapper.Select (query2,
"where (name='July' and (id<=90 and id>=60))"
" order by id desc"
" limit 3 offset 10");
// Note that: query1 = query2 =
// [{ 80, 17.0, "July"}, { 79, 16.8, "July"}, { 78, 16.6, "July"}]
// Count by Query :-)
auto count1 = mapper.Query (_mc) // Link '_mc' to its fields
// Auto Cosntruct Expr { _mc.name, "=", "July" } :-)
.Where ({ _mc.name, "=", "July" })
.Count ();
// Count by SQL, NOT Recommended :-(
auto count2 = mapper.Count ("where (name='July')");
// Note that:
// count1 = count2 = 50
// Delete by Query :-)
mapper.Query (_mc) // Link '_mc' to its fields
// Auto Cosntruct Expr { _mc.name, "=", "July" } :-)
.Where ({ _mc.name = "July" })
.Delete ();
// Delete by SQL, NOT Recommended :-(
mapper.Delete ("where (name='July')");
// Drop the table "MyClass"
mapper.DropTbl ();
// Output to Console
auto printVec = [] (const std::vector<MyClass> vec)
{
for (auto& item : vec)
std::cout << item.id << "\t" << item.score
<< "\t" << item.name << std::endl;
std::cout << std::endl;
};
printVec (query0);
printVec (query1);
printVec (query2);
std::cout << count1 << " " << count2 << std::endl;
std::cin.get ();
return 0;
}
<commit_msg>Rollback Sample.cpp<commit_after>
// A Sample of ORM Lite
// https://github.com/BOT-Man-JL/ORM-Lite
// BOT Man, 2016
// gcc -std=c++11 Sample.cpp "src/sqlite3.c" -lstdc++ -lpthread -ldl -o Sample
#include <string>
#include <iostream>
#include "src/ORMLite.h"
using namespace BOT_ORM;
/* #0 Basic Usage */
class MyClass
{
// Inject ORM-Lite into this Class
ORMAP (MyClass, id, score, name)
public:
long id;
double score;
std::string name;
};
int main ()
{
/* #1 Basic Usage */
// Store the Data in "test.db"
ORMapper<MyClass> mapper ("test.db");
// Create a table for "MyClass"
mapper.CreateTbl ();
// Insert Values into the table
std::vector<MyClass> initObjs =
{
{ 0, 0.2, "John" },
{ 1, 0.4, "Jack" },
{ 2, 0.6, "Jess" }
};
for (const auto obj : initObjs)
mapper.Insert (obj);
// Update Entry by KEY (id)
initObjs[1].score = 1.0;
mapper.Update (initObjs[1]);
// Delete Entry by KEY (id)
mapper.Delete (initObjs[2]);
// Select All to Vector
auto query0 = mapper.Query (MyClass ()).ToVector ();
// query0 = [{ 0, 0.2, "John"},
// { 1, 1.0, "Jack"}]
// If 'Insert' Failed, Print the latest Error Message
if (!mapper.Insert (MyClass { 1, 0, "Joke" }))
auto err = mapper.ErrMsg ();
// err = "SQL error: UNIQUE constraint failed: MyClass.id"
/* #2 Batch Operations */
// Insert by Batch Insert
// Performance is much Better than Separated Insert :-)
std::vector<MyClass> dataToSeed;
for (long i = 50; i < 100; i++)
dataToSeed.emplace_back (MyClass { i, i * 0.2, "July" });
mapper.Insert (dataToSeed);
// Update by Batch Update
for (size_t i = 0; i < 50; i++)
dataToSeed[i].score += 1;
mapper.Update (dataToSeed);
/* #3 Composite Query */
// Define a Query Helper Object
MyClass _mc;
// Select by Query :-)
auto query1 = mapper.Query (_mc) // Link '_mc' to its fields
.Where (
Expr (_mc.name, "=", "July") &&
(
Expr (_mc.id, "<=", 90) &&
Expr (_mc.id, ">=", 60)
)
)
.OrderBy (_mc.id, true)
.Limit (3, 10)
.ToVector ();
// Select by SQL, NOT Recommended :-(
std::vector<MyClass> query2;
mapper.Select (query2,
"where (name='July' and (id<=90 and id>=60))"
" order by id desc"
" limit 3 offset 10");
// Note that: query1 = query2 =
// [{ 80, 17.0, "July"}, { 79, 16.8, "July"}, { 78, 16.6, "July"}]
// Count by Query :-)
auto count1 = mapper.Query (_mc) // Link '_mc' to its fields
// Auto Cosntruct Expr { _mc.name, "=", "July" } :-)
.Where ({ _mc.name, "=", "July" })
.Count ();
// Count by SQL, NOT Recommended :-(
auto count2 = mapper.Count ("where (name='July')");
// Note that:
// count1 = count2 = 50
// Delete by Query :-)
mapper.Query (_mc) // Link '_mc' to its fields
// Auto Cosntruct Expr { _mc.name, "=", "July" } :-)
.Where ({ _mc.name = "July" })
.Delete ();
// Delete by SQL, NOT Recommended :-(
mapper.Delete ("where (name='July')");
// Drop the table "MyClass"
mapper.DropTbl ();
// Output to Console
auto printVec = [] (const std::vector<MyClass> vec)
{
for (auto& item : vec)
std::cout << item.id << "\t" << item.score
<< "\t" << item.name << std::endl;
std::cout << std::endl;
};
printVec (query0);
printVec (query1);
printVec (query2);
std::cout << count1 << " " << count2 << std::endl;
std::cin.get ();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2001 by Norman Krmer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/system.h"
#include "apps/video/video.h"
#include "csengine/sector.h"
#include "csengine/engine.h"
#include "csengine/csview.h"
#include "csengine/camera.h"
#include "csengine/light.h"
#include "csengine/polygon.h"
#include "csengine/meshobj.h"
#include "csengine/texture.h"
#include "csengine/thing.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivaria/conout.h"
//------------------------------------------------- We need the 3D engine -----
REGISTER_STATIC_LIBRARY (engine)
REGISTER_STATIC_LIBRARY (lvlload)
//-----------------------------------------------------------------------------
Video::Video ()
{
view = NULL;
engine = NULL;
pVStream = NULL;
pVideoFormat = NULL;
LevelLoader = NULL;
}
Video::~Video ()
{
if (pVStream) pVStream->DecRef ();
if (pVideoFormat)
{
pVideoFormat->Unload ();
pVideoFormat->DecRef ();
}
delete view;
if (LevelLoader) LevelLoader->DecRef();
}
void cleanup ()
{
System->console_out ("Cleaning up...\n");
delete System;
}
bool Video::Initialize (int argc, const char* const argv[],
const char *iConfigName)
{
if (!superclass::Initialize (argc, argv, iConfigName))
return false;
// Find the pointer to engine plugin
iEngine *Engine = QUERY_PLUGIN (this, iEngine);
if (!Engine)
{
CsPrintf (MSG_FATAL_ERROR, "No iEngine plugin!\n");
abort ();
}
engine = Engine->GetCsEngine ();
Engine->DecRef ();
// Find the pointer to level loader plugin
LevelLoader = QUERY_PLUGIN_ID (this, CS_FUNCID_LVLLOADER, iLoaderNew);
if (!LevelLoader)
{
CsPrintf (MSG_FATAL_ERROR, "No iLoaderNew plugin!\n");
abort ();
}
// Open the main system. This will open all the previously loaded plug-ins.
if (!Open ("Video Crystal Space Application"))
{
Printf (MSG_FATAL_ERROR, "Error opening system!\n");
cleanup ();
exit (1);
}
// Setup the texture manager
iTextureManager* txtmgr = G3D->GetTextureManager ();
txtmgr->SetVerbose (true);
// Initialize the texture manager
txtmgr->ResetPalette ();
// Allocate a uniformly distributed in R,G,B space palette for console
// The console will crash on some platforms if this isn't initialize properly
int r,g,b;
for (r = 0; r < 8; r++)
for (g = 0; g < 8; g++)
for (b = 0; b < 4; b++)
txtmgr->ReserveColor (r * 32, g * 32, b * 64);
txtmgr->SetPalette ();
// Some commercials...
Printf (MSG_INITIALIZATION,
"Video Crystal Space Application version 0.1.\n");
// First disable the lighting cache. Our app is simple enough
// not to need this.
engine->EnableLightingCache (false);
// Create our world.
Printf (MSG_INITIALIZATION, "Creating world!...\n");
LevelLoader->LoadTexture ("stone", "/lib/std/stone4.gif");
csMaterialWrapper* tm = engine->GetMaterials ()->FindByName ("stone");
iMaterialWrapper *iMW = QUERY_INTERFACE (tm, iMaterialWrapper);
room = engine->CreateCsSector ("room");
iThing* walls = QUERY_INTERFACE (engine->CreateSectorWallsMesh (room, "walls")->GetMeshObject (), iThing);
csVector3
f1 (-5, 20, 5),
f2 ( 5, 20, 5),
f3 ( 5, 0, 5),
f4 (-5, 0, 5),
b1 (-5, 20, -5),
b2 ( 5, 20, -5),
b3 ( 5, 0, -5),
b4 (-5, 0, -5);
iPolygon3D* p = walls->CreatePolygon ("back");
p->SetMaterial (iMW);
p->CreateVertex (b4);
p->CreateVertex (b3);
p->CreateVertex (b2);
p->CreateVertex (b1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("front");
p->SetMaterial (iMW);
p->CreateVertex (f1);
p->CreateVertex (f2);
p->CreateVertex (f3);
p->CreateVertex (f4);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("top");
p->SetMaterial (iMW);
p->CreateVertex (b1);
p->CreateVertex (b2);
p->CreateVertex (f2);
p->CreateVertex (f1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("right");
p->SetMaterial (iMW);
p->CreateVertex (f2);
p->CreateVertex (b2);
p->CreateVertex (b3);
p->CreateVertex (f3);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("left");
p->SetMaterial (iMW);
p->CreateVertex (f1);
p->CreateVertex (f4);
p->CreateVertex (b4);
p->CreateVertex (b1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("bottom");
p->SetMaterial (iMW);
p->CreateVertex (f4);
p->CreateVertex (f3);
p->CreateVertex (b3);
p->CreateVertex (b4);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
iMW->DecRef ();
walls->DecRef ();
csStatLight* light;
light = new csStatLight (-3, 5, 0, 10, 1, 0, 0, false);
room->AddLight (light);
light = new csStatLight (3, 5, 0, 10, 0, 0, 1, false);
room->AddLight (light);
light = new csStatLight (0, 5, -3, 10, 0, 1, 0, false);
room->AddLight (light);
engine->Prepare ();
Printf (MSG_INITIALIZATION, "--------------------------------------\n");
// csView is a view encapsulating both a camera and a clipper.
// You don't have to use csView as you can do the same by
// manually creating a camera and a clipper but it makes things a little
// easier.
view = new csView (engine, G3D);
view->SetSector (room);
view->GetCamera ()->SetPosition (csVector3 (0, 5, -3));
view->SetRectangle (0, 0, FrameWidth, FrameHeight);
txtmgr->SetPalette ();
// load the videoformat plugin
iSCF *pSCF = QUERY_INTERFACE (this, iSCF);
Printf (MSG_INITIALIZATION, "Loading an iVideoFormat.\n");
pVideoFormat = (iStreamFormat*)pSCF->scfCreateInstance ("crystalspace.video.format.avi",
"iStreamFormat", 0);
pSCF->DecRef ();
Printf (MSG_INITIALIZATION, "initializing iVideoFormat.\n");
if (pVideoFormat && pVideoFormat->Initialize (this))
{
iVFS *pVFS = QUERY_PLUGIN (this, iVFS);
if (pVFS)
{
Printf (MSG_INITIALIZATION, "Opening the video file.\n");
iFile *pFile = pVFS->Open ("/this/data/video.avi", VFS_FILE_READ);
pVFS->DecRef ();
Printf (MSG_INITIALIZATION, "Scanning the video file.\n");
if (pFile && pVideoFormat->Load (pFile))
{
pFile->DecRef ();
// get a iterator to enumerate all streams found
iStreamIterator *it = pVideoFormat->GetStreamIterator ();
// look up an video stream
csStreamDescription desc;
iStream *pStream=NULL, *pS;
Printf (MSG_INITIALIZATION, "Looking for video stream.\n");
while (it->HasNext ())
{
pS= it->GetNext ();
pS->GetStreamDescription (desc);
if (desc.type == CS_STREAMTYPE_VIDEO)
{
Printf (MSG_INITIALIZATION, "found video stream.\n");
pStream = pS;
break;
}
}
it->DecRef ();
if (pStream)
{
pVStream = QUERY_INTERFACE (pStream, iVideoStream);
// show some data we gathered
csVideoStreamDescription desc;
pVStream->GetStreamDescription (desc);
Printf (MSG_INITIALIZATION, "======= video stream data ======\n");
Printf (MSG_INITIALIZATION, "Colordepth : %d\n", desc.colordepth);
Printf (MSG_INITIALIZATION, "Framecount : %ld\n", desc.framecount);
Printf (MSG_INITIALIZATION, "Width x Height : %d x %d\n", desc.width, desc.height);
Printf (MSG_INITIALIZATION, "Framerate : %g\n", desc.framerate);
Printf (MSG_INITIALIZATION, "Duration : %ld\n", desc.duration);
Printf (MSG_INITIALIZATION, "CODEC : %s\n", desc.codec);
Printf (MSG_INITIALIZATION, "================================\n");
// show the video in the center of the window
int vw = desc.width/2, vh = desc.height/2;
// vw = 750, vh =580;
int x = (FrameWidth - vw)/2;
int y = (FrameHeight - vh)/2;
//pVStream->SetRect (x, y, desc.width, desc.height);
pVStream->SetRect (x, y, vw, vh);
}
else
Printf (MSG_DEBUG_0, "No video stream found in video file.\n");
}
else
Printf (MSG_DEBUG_0, "Could not load the video file.\n");
}
else
Printf (MSG_DEBUG_0, "Could not query VFS plugin.\n");
}
else
Printf (MSG_DEBUG_0, "Could not create or initialize an instance of crystalspace.video.format.avi.\n");
// @@@ DEBUG: IF THIS IS REMOVED THE SPRITE CRASHES!
engine->Prepare ();
return true;
}
void Video::NextFrame ()
{
SysSystemDriver::NextFrame ();
cs_time elapsed_time, current_time;
GetElapsedTime (elapsed_time, current_time);
// Now rotate the camera according to keyboard state
float speed = (elapsed_time / 1000.) * (0.03 * 20);
if (GetKeyState (CSKEY_RIGHT))
view->GetCamera ()->Rotate (VEC_ROT_RIGHT, speed);
if (GetKeyState (CSKEY_LEFT))
view->GetCamera ()->Rotate (VEC_ROT_LEFT, speed);
if (GetKeyState (CSKEY_PGUP))
view->GetCamera ()->Rotate (VEC_TILT_UP, speed);
if (GetKeyState (CSKEY_PGDN))
view->GetCamera ()->Rotate (VEC_TILT_DOWN, speed);
if (GetKeyState (CSKEY_UP))
view->GetCamera ()->Move (VEC_FORWARD * 4.0f * speed);
if (GetKeyState (CSKEY_DOWN))
view->GetCamera ()->Move (VEC_BACKWARD * 4.0f * speed);
// Tell 3D driver we're going to display 3D things.
if (!G3D->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
return;
view->Draw ();
// Start drawing 2D graphics.
if (!G3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;
if (pVStream)
pVStream->NextFrame ();
// Drawing code ends here.
G3D->FinishDraw ();
// Print the final output.
G3D->Print (NULL);
}
bool Video::HandleEvent (iEvent &Event)
{
if (superclass::HandleEvent (Event))
return true;
if ((Event.Type == csevKeyDown) && (Event.Key.Code == CSKEY_ESC))
{
Shutdown = true;
return true;
}
return false;
}
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
srand (time (NULL));
// Create our main class.
System = new Video ();
// We want at least the minimal set of plugins
System->RequestPlugin ("crystalspace.kernel.vfs:VFS");
System->RequestPlugin ("crystalspace.font.server.default:FontServer");
System->RequestPlugin ("crystalspace.image.loader:ImageLoader");
System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver");
System->RequestPlugin ("crystalspace.engine.core:Engine");
System->RequestPlugin ("crystalspace.console.output.standard:Console.Output");
System->RequestPlugin ("crystalspace.level.loader:LevelLoader");
// Initialize the main system. This will load all needed plug-ins
// (3D, 2D, network, sound, ...) and initialize them.
if (!System->Initialize (argc, argv, NULL))
{
System->Printf (MSG_FATAL_ERROR, "Error initializing system!\n");
cleanup ();
exit (1);
}
// Main loop.
System->Loop ();
// Cleanup.
cleanup ();
return 0;
}
<commit_msg>Updated to take account of Martins move of ImageLoad(), fixing crasher in app.<commit_after>/*
Copyright (C) 2001 by Norman Krmer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/system.h"
#include "apps/video/video.h"
#include "csengine/sector.h"
#include "csengine/engine.h"
#include "csengine/csview.h"
#include "csengine/camera.h"
#include "csengine/light.h"
#include "csengine/polygon.h"
#include "csengine/meshobj.h"
#include "csengine/texture.h"
#include "csengine/thing.h"
#include "ivideo/graph3d.h"
#include "ivideo/txtmgr.h"
#include "ivaria/conout.h"
#include "imap/parser.h"
//------------------------------------------------- We need the 3D engine -----
REGISTER_STATIC_LIBRARY (engine)
REGISTER_STATIC_LIBRARY (lvlload)
//-----------------------------------------------------------------------------
Video::Video ()
{
view = NULL;
engine = NULL;
pVStream = NULL;
pVideoFormat = NULL;
LevelLoader = NULL;
}
Video::~Video ()
{
if (pVStream) pVStream->DecRef ();
if (pVideoFormat)
{
pVideoFormat->Unload ();
pVideoFormat->DecRef ();
}
delete view;
if (LevelLoader) LevelLoader->DecRef();
}
void cleanup ()
{
System->console_out ("Cleaning up...\n");
delete System;
}
bool Video::Initialize (int argc, const char* const argv[],
const char *iConfigName)
{
if (!superclass::Initialize (argc, argv, iConfigName))
return false;
// Find the pointer to engine plugin
iEngine *Engine = QUERY_PLUGIN (this, iEngine);
if (!Engine)
{
CsPrintf (MSG_FATAL_ERROR, "No iEngine plugin!\n");
abort ();
}
engine = Engine->GetCsEngine ();
Engine->DecRef ();
// Find the pointer to level loader plugin
LevelLoader = QUERY_PLUGIN_ID (this, CS_FUNCID_LVLLOADER, iLoaderNew);
if (!LevelLoader)
{
CsPrintf (MSG_FATAL_ERROR, "No iLoaderNew plugin!\n");
abort ();
}
// Open the main system. This will open all the previously loaded plug-ins.
if (!Open ("Video Crystal Space Application"))
{
Printf (MSG_FATAL_ERROR, "Error opening system!\n");
cleanup ();
exit (1);
}
// Setup the texture manager
iTextureManager* txtmgr = G3D->GetTextureManager ();
txtmgr->SetVerbose (true);
// Initialize the texture manager
txtmgr->ResetPalette ();
// Allocate a uniformly distributed in R,G,B space palette for console
// The console will crash on some platforms if this isn't initialize properly
int r,g,b;
for (r = 0; r < 8; r++)
for (g = 0; g < 8; g++)
for (b = 0; b < 4; b++)
txtmgr->ReserveColor (r * 32, g * 32, b * 64);
txtmgr->SetPalette ();
// Some commercials...
Printf (MSG_INITIALIZATION,
"Video Crystal Space Application version 0.1.\n");
// First disable the lighting cache. Our app is simple enough
// not to need this.
engine->EnableLightingCache (false);
// Create our world.
Printf (MSG_INITIALIZATION, "Creating world!...\n");
LevelLoader->LoadTexture ("stone", "/lib/std/stone4.gif");
csMaterialWrapper* tm = engine->GetMaterials ()->FindByName ("stone");
iMaterialWrapper *iMW = QUERY_INTERFACE (tm, iMaterialWrapper);
room = engine->CreateCsSector ("room");
iThing* walls = QUERY_INTERFACE (engine->CreateSectorWallsMesh (room, "walls")->GetMeshObject (), iThing);
csVector3
f1 (-5, 20, 5),
f2 ( 5, 20, 5),
f3 ( 5, 0, 5),
f4 (-5, 0, 5),
b1 (-5, 20, -5),
b2 ( 5, 20, -5),
b3 ( 5, 0, -5),
b4 (-5, 0, -5);
iPolygon3D* p = walls->CreatePolygon ("back");
p->SetMaterial (iMW);
p->CreateVertex (b4);
p->CreateVertex (b3);
p->CreateVertex (b2);
p->CreateVertex (b1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("front");
p->SetMaterial (iMW);
p->CreateVertex (f1);
p->CreateVertex (f2);
p->CreateVertex (f3);
p->CreateVertex (f4);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("top");
p->SetMaterial (iMW);
p->CreateVertex (b1);
p->CreateVertex (b2);
p->CreateVertex (f2);
p->CreateVertex (f1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("right");
p->SetMaterial (iMW);
p->CreateVertex (f2);
p->CreateVertex (b2);
p->CreateVertex (b3);
p->CreateVertex (f3);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("left");
p->SetMaterial (iMW);
p->CreateVertex (f1);
p->CreateVertex (f4);
p->CreateVertex (b4);
p->CreateVertex (b1);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
p = walls->CreatePolygon ("bottom");
p->SetMaterial (iMW);
p->CreateVertex (f4);
p->CreateVertex (f3);
p->CreateVertex (b3);
p->CreateVertex (b4);
p->SetTextureSpace (p->GetVertex (0), p->GetVertex (1), 3);
iMW->DecRef ();
walls->DecRef ();
csStatLight* light;
light = new csStatLight (-3, 5, 0, 10, 1, 0, 0, false);
room->AddLight (light);
light = new csStatLight (3, 5, 0, 10, 0, 0, 1, false);
room->AddLight (light);
light = new csStatLight (0, 5, -3, 10, 0, 1, 0, false);
room->AddLight (light);
engine->Prepare ();
Printf (MSG_INITIALIZATION, "--------------------------------------\n");
// csView is a view encapsulating both a camera and a clipper.
// You don't have to use csView as you can do the same by
// manually creating a camera and a clipper but it makes things a little
// easier.
view = new csView (engine, G3D);
view->SetSector (room);
view->GetCamera ()->SetPosition (csVector3 (0, 5, -3));
view->SetRectangle (0, 0, FrameWidth, FrameHeight);
txtmgr->SetPalette ();
// load the videoformat plugin
iSCF *pSCF = QUERY_INTERFACE (this, iSCF);
Printf (MSG_INITIALIZATION, "Loading an iVideoFormat.\n");
pVideoFormat = (iStreamFormat*)pSCF->scfCreateInstance ("crystalspace.video.format.avi",
"iStreamFormat", 0);
pSCF->DecRef ();
Printf (MSG_INITIALIZATION, "initializing iVideoFormat.\n");
if (pVideoFormat && pVideoFormat->Initialize (this))
{
iVFS *pVFS = QUERY_PLUGIN (this, iVFS);
if (pVFS)
{
Printf (MSG_INITIALIZATION, "Opening the video file.\n");
iFile *pFile = pVFS->Open ("/this/data/video.avi", VFS_FILE_READ);
pVFS->DecRef ();
Printf (MSG_INITIALIZATION, "Scanning the video file.\n");
if (pFile && pVideoFormat->Load (pFile))
{
pFile->DecRef ();
// get a iterator to enumerate all streams found
iStreamIterator *it = pVideoFormat->GetStreamIterator ();
// look up an video stream
csStreamDescription desc;
iStream *pStream=NULL, *pS;
Printf (MSG_INITIALIZATION, "Looking for video stream.\n");
while (it->HasNext ())
{
pS= it->GetNext ();
pS->GetStreamDescription (desc);
if (desc.type == CS_STREAMTYPE_VIDEO)
{
Printf (MSG_INITIALIZATION, "found video stream.\n");
pStream = pS;
break;
}
}
it->DecRef ();
if (pStream)
{
pVStream = QUERY_INTERFACE (pStream, iVideoStream);
// show some data we gathered
csVideoStreamDescription desc;
pVStream->GetStreamDescription (desc);
Printf (MSG_INITIALIZATION, "======= video stream data ======\n");
Printf (MSG_INITIALIZATION, "Colordepth : %d\n", desc.colordepth);
Printf (MSG_INITIALIZATION, "Framecount : %ld\n", desc.framecount);
Printf (MSG_INITIALIZATION, "Width x Height : %d x %d\n", desc.width, desc.height);
Printf (MSG_INITIALIZATION, "Framerate : %g\n", desc.framerate);
Printf (MSG_INITIALIZATION, "Duration : %ld\n", desc.duration);
Printf (MSG_INITIALIZATION, "CODEC : %s\n", desc.codec);
Printf (MSG_INITIALIZATION, "================================\n");
// show the video in the center of the window
int vw = desc.width/2, vh = desc.height/2;
// vw = 750, vh =580;
int x = (FrameWidth - vw)/2;
int y = (FrameHeight - vh)/2;
//pVStream->SetRect (x, y, desc.width, desc.height);
pVStream->SetRect (x, y, vw, vh);
}
else
Printf (MSG_DEBUG_0, "No video stream found in video file.\n");
}
else
Printf (MSG_DEBUG_0, "Could not load the video file.\n");
}
else
Printf (MSG_DEBUG_0, "Could not query VFS plugin.\n");
}
else
Printf (MSG_DEBUG_0, "Could not create or initialize an instance of crystalspace.video.format.avi.\n");
// @@@ DEBUG: IF THIS IS REMOVED THE SPRITE CRASHES!
engine->Prepare ();
return true;
}
void Video::NextFrame ()
{
SysSystemDriver::NextFrame ();
cs_time elapsed_time, current_time;
GetElapsedTime (elapsed_time, current_time);
// Now rotate the camera according to keyboard state
float speed = (elapsed_time / 1000.) * (0.03 * 20);
if (GetKeyState (CSKEY_RIGHT))
view->GetCamera ()->Rotate (VEC_ROT_RIGHT, speed);
if (GetKeyState (CSKEY_LEFT))
view->GetCamera ()->Rotate (VEC_ROT_LEFT, speed);
if (GetKeyState (CSKEY_PGUP))
view->GetCamera ()->Rotate (VEC_TILT_UP, speed);
if (GetKeyState (CSKEY_PGDN))
view->GetCamera ()->Rotate (VEC_TILT_DOWN, speed);
if (GetKeyState (CSKEY_UP))
view->GetCamera ()->Move (VEC_FORWARD * 4.0f * speed);
if (GetKeyState (CSKEY_DOWN))
view->GetCamera ()->Move (VEC_BACKWARD * 4.0f * speed);
// Tell 3D driver we're going to display 3D things.
if (!G3D->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
return;
view->Draw ();
// Start drawing 2D graphics.
if (!G3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;
if (pVStream)
pVStream->NextFrame ();
// Drawing code ends here.
G3D->FinishDraw ();
// Print the final output.
G3D->Print (NULL);
}
bool Video::HandleEvent (iEvent &Event)
{
if (superclass::HandleEvent (Event))
return true;
if ((Event.Type == csevKeyDown) && (Event.Key.Code == CSKEY_ESC))
{
Shutdown = true;
return true;
}
return false;
}
/*---------------------------------------------------------------------*
* Main function
*---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
srand (time (NULL));
// Create our main class.
System = new Video ();
// We want at least the minimal set of plugins
System->RequestPlugin ("crystalspace.kernel.vfs:VFS");
System->RequestPlugin ("crystalspace.font.server.default:FontServer");
System->RequestPlugin ("crystalspace.image.loader:ImageLoader");
System->RequestPlugin ("crystalspace.graphics3d.software:VideoDriver");
System->RequestPlugin ("crystalspace.engine.core:Engine");
System->RequestPlugin ("crystalspace.console.output.standard:Console.Output");
System->RequestPlugin ("crystalspace.level.loader:LevelLoader");
// Initialize the main system. This will load all needed plug-ins
// (3D, 2D, network, sound, ...) and initialize them.
if (!System->Initialize (argc, argv, NULL))
{
System->Printf (MSG_FATAL_ERROR, "Error initializing system!\n");
cleanup ();
exit (1);
}
// Main loop.
System->Loop ();
// Cleanup.
cleanup ();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTableHeaderFooterContext.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:58:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SC_XMLTABLEHEADERFOOTERCONTEXT_HXX_
#define _SC_XMLTABLEHEADERFOOTERCONTEXT_HXX_
#ifndef _XMLOFF_XMLICTXT_HXX_
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX_
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XHEADERFOOTERCONTENT_HPP_
#include <com/sun/star/sheet/XHeaderFooterContent.hpp>
#endif
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; }
namespace beans { class XPropertySet; }
} } }
class XMLTableHeaderFooterContext: public SvXMLImportContext
{
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xOldTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet > xPropSet;
::com::sun::star::uno::Reference <
::com::sun::star::sheet::XHeaderFooterContent > xHeaderFooterContent;
const ::rtl::OUString sOn;
const ::rtl::OUString sShareContent;
const ::rtl::OUString sContent;
const ::rtl::OUString sContentLeft;
const ::rtl::OUString sEmpty;
rtl::OUString sCont;
sal_Bool bDisplay;
sal_Bool bInsertContent;
sal_Bool bLeft;
sal_Bool bContainsLeft;
sal_Bool bContainsRight;
sal_Bool bContainsCenter;
public:
TYPEINFO();
XMLTableHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const ::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet > & rPageStylePropSet,
sal_Bool bFooter, sal_Bool bLft );
virtual ~XMLTableHeaderFooterContext();
virtual SvXMLImportContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
};
class XMLHeaderFooterRegionContext: public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor >& xTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xOldTextCursor;
public:
TYPEINFO();
XMLHeaderFooterRegionContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
com::sun::star::uno::Reference< com::sun::star::text::XTextCursor >& xCursor );
virtual ~XMLHeaderFooterRegionContext();
virtual SvXMLImportContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.698); FILE MERGED 2008/04/01 12:36:32 thb 1.6.698.2: #i85898# Stripping all external header guards 2008/03/31 17:14:56 rt 1.6.698.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTableHeaderFooterContext.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SC_XMLTABLEHEADERFOOTERCONTEXT_HXX_
#define _SC_XMLTABLEHEADERFOOTERCONTEXT_HXX_
#ifndef _XMLOFF_XMLICTXT_HXX_
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX_
#include <xmloff/xmlimp.hxx>
#endif
#include <com/sun/star/sheet/XHeaderFooterContent.hpp>
namespace com { namespace sun { namespace star {
namespace text { class XTextCursor; }
namespace beans { class XPropertySet; }
} } }
class XMLTableHeaderFooterContext: public SvXMLImportContext
{
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xOldTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet > xPropSet;
::com::sun::star::uno::Reference <
::com::sun::star::sheet::XHeaderFooterContent > xHeaderFooterContent;
const ::rtl::OUString sOn;
const ::rtl::OUString sShareContent;
const ::rtl::OUString sContent;
const ::rtl::OUString sContentLeft;
const ::rtl::OUString sEmpty;
rtl::OUString sCont;
sal_Bool bDisplay;
sal_Bool bInsertContent;
sal_Bool bLeft;
sal_Bool bContainsLeft;
sal_Bool bContainsRight;
sal_Bool bContainsCenter;
public:
TYPEINFO();
XMLTableHeaderFooterContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const ::com::sun::star::uno::Reference <
::com::sun::star::beans::XPropertySet > & rPageStylePropSet,
sal_Bool bFooter, sal_Bool bLft );
virtual ~XMLTableHeaderFooterContext();
virtual SvXMLImportContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
};
class XMLHeaderFooterRegionContext: public SvXMLImportContext
{
private:
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor >& xTextCursor;
::com::sun::star::uno::Reference <
::com::sun::star::text::XTextCursor > xOldTextCursor;
public:
TYPEINFO();
XMLHeaderFooterRegionContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList > & xAttrList,
com::sun::star::uno::Reference< com::sun::star::text::XTextCursor >& xCursor );
virtual ~XMLHeaderFooterRegionContext();
virtual SvXMLImportContext *CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList );
virtual void EndElement();
};
#endif
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "PyEvents.h"
#include "PyBZFlag.h"
namespace Python
{
void
PythonHandler::emit (PyObject *arglist, int event)
{
PyObject *listeners = parent->GetListeners (event);
if (listeners == NULL || !PyList_Check(listeners)) {
// FIXME - throw error
fprintf (stderr, "tick listeners is not a list!\n");
return;
}
// Call out
int size = PyList_Size (listeners);
for (int i = 0; i < size; i++) {
PyObject *handler = PyList_GetItem (listeners, i);
if (!PyCallable_Check (handler)) {
// FIXME - throw error
fprintf (stderr, "%d listener is not callable\n", event);
Py_DECREF (arglist);
return;
}
PyErr_Clear ();
PyEval_CallObject (handler, arglist);
if (PyErr_Occurred ()) {
PyErr_Print ();
return;
}
}
}
void
CaptureHandler::process (bz_EventData *eventData)
{
bz_CTFCaptureEventData *ced = (bz_CTFCaptureEventData *) eventData;
PyObject *arglist = Py_BuildValue ("(iii(fff)fd",
ced->teamCaped,
ced->teamCaping,
ced->playerCaping,
ced->pos[0],
ced->pos[1],
ced->pos[2],
ced->rot,
ced->time);
emit (arglist, bz_eCaptureEvent);
Py_DECREF (arglist);
}
void
DieHandler::process (bz_EventData *eventData)
{
bz_PlayerDieEventData *pded = (bz_PlayerDieEventData *) eventData;
PyObject *arglist = Py_BuildValue ("iiiis(fff)fd",
pded->playerID,
pded->teamID,
pded->killerID,
pded->killerTeamID,
pded->flagKilledWith.c_str(),
pded->pos[0],
pded->pos[1],
pded->pos[2],
pded->rot,
pded->time);
emit (arglist, bz_ePlayerDieEvent);
Py_DECREF (arglist);
}
void
JoinHandler::process (bz_EventData *eventData)
{
bz_PlayerJoinPartEventData *pjped = (bz_PlayerJoinPartEventData*) eventData;
parent->AddPlayer (pjped->playerID);
emit (NULL /* FIXME */, bz_ePlayerJoinEvent);
}
void
PartHandler::process (bz_EventData *eventData)
{
bz_PlayerJoinPartEventData *pjped = (bz_PlayerJoinPartEventData*) eventData;
parent->RemovePlayer (pjped->playerID);
emit (NULL /* FIXME */, bz_ePlayerPartEvent);
}
void
TickHandler::process (bz_EventData *eventData)
{
bz_TickEventData *ted = (bz_TickEventData*) eventData;
PyObject *arglist = Py_BuildValue ("(d)", ted->time);
emit (arglist, bz_eTickEvent);
Py_DECREF (arglist);
}
};
<commit_msg>add args for join/part handlers<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "PyEvents.h"
#include "PyBZFlag.h"
namespace Python
{
void
PythonHandler::emit (PyObject *arglist, int event)
{
PyObject *listeners = parent->GetListeners (event);
if (listeners == NULL || !PyList_Check(listeners)) {
// FIXME - throw error
fprintf (stderr, "tick listeners is not a list!\n");
return;
}
// Call out
int size = PyList_Size (listeners);
for (int i = 0; i < size; i++) {
PyObject *handler = PyList_GetItem (listeners, i);
if (!PyCallable_Check (handler)) {
// FIXME - throw error
fprintf (stderr, "%d listener is not callable\n", event);
Py_DECREF (arglist);
return;
}
PyErr_Clear ();
PyEval_CallObject (handler, arglist);
if (PyErr_Occurred ()) {
PyErr_Print ();
return;
}
}
}
void
CaptureHandler::process (bz_EventData *eventData)
{
bz_CTFCaptureEventData *ced = (bz_CTFCaptureEventData *) eventData;
PyObject *arglist = Py_BuildValue ("(iii(fff)fd",
ced->teamCaped,
ced->teamCaping,
ced->playerCaping,
ced->pos[0],
ced->pos[1],
ced->pos[2],
ced->rot,
ced->time);
emit (arglist, bz_eCaptureEvent);
Py_DECREF (arglist);
}
void
DieHandler::process (bz_EventData *eventData)
{
bz_PlayerDieEventData *pded = (bz_PlayerDieEventData *) eventData;
PyObject *arglist = Py_BuildValue ("iiiis(fff)fd",
pded->playerID,
pded->teamID,
pded->killerID,
pded->killerTeamID,
pded->flagKilledWith.c_str(),
pded->pos[0],
pded->pos[1],
pded->pos[2],
pded->rot,
pded->time);
emit (arglist, bz_ePlayerDieEvent);
Py_DECREF (arglist);
}
void
JoinHandler::process (bz_EventData *eventData)
{
bz_PlayerJoinPartEventData *pjped = (bz_PlayerJoinPartEventData*) eventData;
parent->AddPlayer (pjped->playerID);
PyObject *arglist = Py_BuildValue ("iissd",
pjped->playerID,
pjped->teamID,
pjped->callsign.c_str (),
pjped->reason.c_str (),
pjped->time);
emit (arglist, bz_ePlayerJoinEvent);
Py_DECREF (arglist);
}
void
PartHandler::process (bz_EventData *eventData)
{
bz_PlayerJoinPartEventData *pjped = (bz_PlayerJoinPartEventData*) eventData;
parent->RemovePlayer (pjped->playerID);
PyObject *arglist = Py_BuildValue ("iissd",
pjped->playerID,
pjped->teamID,
pjped->callsign.c_str (),
pjped->reason.c_str (),
pjped->time);
emit (arglist, bz_ePlayerPartEvent);
Py_DECREF (arglist);
}
void
TickHandler::process (bz_EventData *eventData)
{
bz_TickEventData *ted = (bz_TickEventData*) eventData;
PyObject *arglist = Py_BuildValue ("(d)", ted->time);
emit (arglist, bz_eTickEvent);
Py_DECREF (arglist);
}
};
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ElementDeleterBase.h"
#include "MooseMesh.h"
#include "libmesh/remote_elem.h"
template<>
InputParameters validParams<ElementDeleterBase>()
{
InputParameters params = validParams<MeshModifier>();
return params;
}
ElementDeleterBase::ElementDeleterBase(const InputParameters & parameters) :
MeshModifier(parameters)
{}
void
ElementDeleterBase::modify()
{
// Check that we have access to the mesh
if (!_mesh_ptr)
mooseError("_mesh_ptr must be initialized before calling ElementDeleterBase::modify()");
MeshBase & mesh = _mesh_ptr->getMesh();
// Elements that the deleter will remove
std::set<Elem *> deleteable_elems;
// First let's figure out which elements need to be deleted
const MeshBase::const_element_iterator end = mesh.elements_end();
for (MeshBase::const_element_iterator elem_it = mesh.elements_begin(); elem_it != end; ++elem_it)
{
Elem * elem = *elem_it;
if (shouldDelete(elem))
deleteable_elems.insert(elem);
}
/**
* Delete all of the elements
*
* TODO: We need to sort these not because they have to be deleted in a certain order in libMesh,
* but because the order of deletion might impact what happens to any existing sidesets or nodesets.
*/
for (const auto & elem : deleteable_elems)
{
// On distributed meshes, we'll need neighbor links to be useable
// shortly, so we can't just leave dangling pointers.
//
// FIXME - this could be made AMR-aware and refactored into
// libMesh - roystgnr
unsigned int n_sides = elem->n_sides();
for (unsigned int n = 0; n != n_sides; ++n)
{
Elem * neighbor = elem->neighbor(n);
if (!neighbor || neighbor == remote_elem)
continue;
const unsigned int return_side =
neighbor->which_neighbor_am_i(elem);
if (neighbor->neighbor(return_side) == elem)
neighbor->set_neighbor(return_side, nullptr);
}
mesh.delete_elem(elem);
}
/**
* If we are on a distributed mesh, we may have deleted elements
* which are remote_elem neighbors on other processors, and we need
* to make those neighbor links into NULL pointers (i.e. domain
* boundaries) instead.
*/
if (!mesh.is_serial())
{
const processor_id_type my_n_proc = mesh.n_processors();
const processor_id_type my_proc_id = mesh.processor_id();
typedef std::vector<std::pair<dof_id_type, unsigned int> > vec_type;
std::vector<vec_type> queries(my_n_proc);
// Loop over the elements looking for those with remote neighbors.
// The ghost_elements iterators in libMesh need to be updated
// before we can use them safely here, so we'll test for
// ghost-vs-local manually.
for (MeshBase::const_element_iterator
el = mesh.elements_begin(),
end_el = mesh.elements_end();
el != end_el ; ++el)
{
const Elem* elem = *el;
const processor_id_type pid = elem->processor_id();
if (pid == my_proc_id)
continue;
const unsigned int n_sides = elem->n_sides();
for (unsigned int n=0; n != n_sides; ++n)
if (elem->neighbor(n) == remote_elem)
queries[pid].push_back
(std::make_pair(elem->id(), n));
}
Parallel::MessageTag
queries_tag = mesh.comm().get_unique_tag(42),
replies_tag = mesh.comm().get_unique_tag(6*9);
std::vector<Parallel::Request> query_requests(my_n_proc-1),
reply_requests(my_n_proc-1);
// Make all requests
for (processor_id_type p=0; p != my_n_proc; ++p)
{
if (p == my_proc_id)
continue;
Parallel::Request &request =
query_requests[p - (p > my_proc_id)];
mesh.comm().send
(p, queries[p], request, queries_tag);
}
// Reply to all requests
std::vector<vec_type> responses(my_n_proc-1);
for (processor_id_type p=1; p != my_n_proc; ++p)
{
vec_type query;
Parallel::Status
status(mesh.comm().probe (Parallel::any_source, queries_tag));
const processor_id_type
source_pid = cast_int<processor_id_type>(status.source());
mesh.comm().receive
(source_pid, query, queries_tag);
Parallel::Request &request =
reply_requests[p-1];
for (const auto & q : query)
{
const Elem * elem = mesh.elem_ptr(q.first);
const unsigned int side = q.second;
const Elem * neighbor = elem->neighbor(side);
if (neighbor == NULL) // neighboring element was deleted!
responses[p-1].push_back(std::make_pair(elem->id(), side));
}
mesh.comm().send
(source_pid, responses[p-1], request, replies_tag);
}
// Process all incoming replies
for (processor_id_type p=1; p != my_n_proc; ++p)
{
Parallel::Status status
(this->comm().probe (Parallel::any_source, replies_tag));
const processor_id_type
source_pid = cast_int<processor_id_type>(status.source());
vec_type response;
this->comm().receive
(source_pid, response, replies_tag);
for (const auto & r : response)
{
Elem * elem = mesh.elem_ptr(r.first);
const unsigned int side = r.second;
elem->set_neighbor(side, libmesh_nullptr);
}
}
Parallel::wait (query_requests);
Parallel::wait (reply_requests);
}
/**
* If we are on a ReplicatedMesh, deleting nodes and elements leaves
* NULLs in the mesh datastructure. We ought to get rid of those.
* For now, we'll call contract and notify the SetupMeshComplete
* Action that we need to re-prepare the mesh.
*/
mesh.contract();
_mesh_ptr->needsPrepareForUse();
}
<commit_msg>Use nullptr, add libmesh_assert<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ElementDeleterBase.h"
#include "MooseMesh.h"
#include "libmesh/remote_elem.h"
template<>
InputParameters validParams<ElementDeleterBase>()
{
InputParameters params = validParams<MeshModifier>();
return params;
}
ElementDeleterBase::ElementDeleterBase(const InputParameters & parameters) :
MeshModifier(parameters)
{}
void
ElementDeleterBase::modify()
{
// Check that we have access to the mesh
if (!_mesh_ptr)
mooseError("_mesh_ptr must be initialized before calling ElementDeleterBase::modify()");
MeshBase & mesh = _mesh_ptr->getMesh();
// Elements that the deleter will remove
std::set<Elem *> deleteable_elems;
// First let's figure out which elements need to be deleted
const MeshBase::const_element_iterator end = mesh.elements_end();
for (MeshBase::const_element_iterator elem_it = mesh.elements_begin(); elem_it != end; ++elem_it)
{
Elem * elem = *elem_it;
if (shouldDelete(elem))
deleteable_elems.insert(elem);
}
/**
* Delete all of the elements
*
* TODO: We need to sort these not because they have to be deleted in a certain order in libMesh,
* but because the order of deletion might impact what happens to any existing sidesets or nodesets.
*/
for (const auto & elem : deleteable_elems)
{
// On distributed meshes, we'll need neighbor links to be useable
// shortly, so we can't just leave dangling pointers.
//
// FIXME - this could be made AMR-aware and refactored into
// libMesh - roystgnr
unsigned int n_sides = elem->n_sides();
for (unsigned int n = 0; n != n_sides; ++n)
{
Elem * neighbor = elem->neighbor(n);
if (!neighbor || neighbor == remote_elem)
continue;
const unsigned int return_side =
neighbor->which_neighbor_am_i(elem);
if (neighbor->neighbor(return_side) == elem)
neighbor->set_neighbor(return_side, nullptr);
}
mesh.delete_elem(elem);
}
/**
* If we are on a distributed mesh, we may have deleted elements
* which are remote_elem neighbors on other processors, and we need
* to make those neighbor links into NULL pointers (i.e. domain
* boundaries) instead.
*/
if (!mesh.is_serial())
{
const processor_id_type my_n_proc = mesh.n_processors();
const processor_id_type my_proc_id = mesh.processor_id();
typedef std::vector<std::pair<dof_id_type, unsigned int> > vec_type;
std::vector<vec_type> queries(my_n_proc);
// Loop over the elements looking for those with remote neighbors.
// The ghost_elements iterators in libMesh need to be updated
// before we can use them safely here, so we'll test for
// ghost-vs-local manually.
for (MeshBase::const_element_iterator
el = mesh.elements_begin(),
end_el = mesh.elements_end();
el != end_el ; ++el)
{
const Elem* elem = *el;
const processor_id_type pid = elem->processor_id();
if (pid == my_proc_id)
continue;
const unsigned int n_sides = elem->n_sides();
for (unsigned int n=0; n != n_sides; ++n)
if (elem->neighbor(n) == remote_elem)
queries[pid].push_back
(std::make_pair(elem->id(), n));
}
Parallel::MessageTag
queries_tag = mesh.comm().get_unique_tag(42),
replies_tag = mesh.comm().get_unique_tag(6*9);
std::vector<Parallel::Request> query_requests(my_n_proc-1),
reply_requests(my_n_proc-1);
// Make all requests
for (processor_id_type p=0; p != my_n_proc; ++p)
{
if (p == my_proc_id)
continue;
Parallel::Request &request =
query_requests[p - (p > my_proc_id)];
mesh.comm().send
(p, queries[p], request, queries_tag);
}
// Reply to all requests
std::vector<vec_type> responses(my_n_proc-1);
for (processor_id_type p=1; p != my_n_proc; ++p)
{
vec_type query;
Parallel::Status
status(mesh.comm().probe (Parallel::any_source, queries_tag));
const processor_id_type
source_pid = cast_int<processor_id_type>(status.source());
mesh.comm().receive
(source_pid, query, queries_tag);
Parallel::Request &request =
reply_requests[p-1];
for (const auto & q : query)
{
const Elem * elem = mesh.elem_ptr(q.first);
const unsigned int side = q.second;
const Elem * neighbor = elem->neighbor(side);
if (neighbor == nullptr) // neighboring element was deleted!
responses[p-1].push_back(std::make_pair(elem->id(), side));
}
mesh.comm().send
(source_pid, responses[p-1], request, replies_tag);
}
// Process all incoming replies
for (processor_id_type p=1; p != my_n_proc; ++p)
{
Parallel::Status status
(this->comm().probe (Parallel::any_source, replies_tag));
const processor_id_type
source_pid = cast_int<processor_id_type>(status.source());
vec_type response;
this->comm().receive
(source_pid, response, replies_tag);
for (const auto & r : response)
{
Elem * elem = mesh.elem_ptr(r.first);
const unsigned int side = r.second;
libmesh_assert(elem->neighbor(side) == remote_elem);
elem->set_neighbor(side, nullptr);
}
}
Parallel::wait (query_requests);
Parallel::wait (reply_requests);
}
/**
* If we are on a ReplicatedMesh, deleting nodes and elements leaves
* NULLs in the mesh datastructure. We ought to get rid of those.
* For now, we'll call contract and notify the SetupMeshComplete
* Action that we need to re-prepare the mesh.
*/
mesh.contract();
_mesh_ptr->needsPrepareForUse();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.