text
stringlengths
54
60.6k
<commit_before>#include "bufferAgent.h" using boost::shared_ptr; using boost::thread; using boost::bind; using std::string; namespace veil { namespace helpers { BufferAgent::BufferAgent(write_fun w, read_fun r) : m_agentActive(false), doWrite(w), doRead(r) { agentStart(); } BufferAgent::~BufferAgent() { agentStop(); } int BufferAgent::onOpen(std::string path, ffi_type ffi) { unique_lock guard(m_loopMutex); m_cacheMap.erase(ffi->fh); buffer_ptr lCache(new LockableCache()); lCache->fileName = path; lCache->buffer = newFileCache(); lCache->ffi = *ffi; m_cacheMap[ffi->fh] = lCache; return 0; } int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_loopMutex); buffer_ptr wrapper = m_cacheMap[ffi->fh]; guard.unlock(); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->byteSize() > 1024 * 1024 * 10) { wrapper->cond.wait(buff_guard); } wrapper->buffer->writeData(offset, buf); guard.lock(); m_jobQueue.push_back(ffi->fh); return size; } int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi) { boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex); return EOPNOTSUPP; } int BufferAgent::onFlush(std::string path, ffi_type ffi) { unique_lock guard(m_loopMutex); buffer_ptr wrapper = m_cacheMap[ffi->fh]; guard.unlock(); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->blockCount() > 0) { block_ptr block = wrapper->buffer->removeOldestBlock(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); if(res < 0) { while(wrapper->buffer->blockCount() > 0) { (void) wrapper->buffer->removeOldestBlock(); } return res; } } guard.lock(); m_jobQueue.remove(ffi->fh); return 0; } int BufferAgent::onRelease(std::string path, ffi_type ffi) { boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex); m_cacheMap.erase(ffi->fh); return 0; } void BufferAgent::agentStart(int worker_count) { m_workers.clear(); m_agentActive = true; while(worker_count--) { m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this)))); } } void BufferAgent::agentStop() { m_agentActive = false; m_loopCond.notify_all(); while(m_workers.size() > 0) { m_workers.back()->join(); m_workers.pop_back(); } } void BufferAgent::workerLoop() { unique_lock guard(m_loopMutex); while(m_agentActive) { while(m_jobQueue.empty() && m_agentActive) m_loopCond.wait(guard); if(!m_agentActive) return; fd_type file = m_jobQueue.front(); buffer_ptr wrapper = m_cacheMap[file]; m_jobQueue.pop_front(); m_loopCond.notify_all(); if(!wrapper) continue; { guard.unlock(); unique_lock buff_guard(wrapper->mutex); block_ptr block = wrapper->buffer->removeOldestBlock(); if(block) { int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); wrapper->cond.notify_all(); } guard.lock(); if(wrapper->buffer->blockCount() > 0) { m_jobQueue.push_back(file); } } } } boost::shared_ptr<FileCache> BufferAgent::newFileCache() { return boost::shared_ptr<FileCache>(new FileCache(100 * 1024)); } } // namespace helpers } // namespace veil <commit_msg>VFS-292: debug<commit_after>#include "bufferAgent.h" using boost::shared_ptr; using boost::thread; using boost::bind; using std::string; namespace veil { namespace helpers { BufferAgent::BufferAgent(write_fun w, read_fun r) : m_agentActive(false), doWrite(w), doRead(r) { agentStart(); } BufferAgent::~BufferAgent() { agentStop(); } int BufferAgent::onOpen(std::string path, ffi_type ffi) { unique_lock guard(m_loopMutex); m_cacheMap.erase(ffi->fh); buffer_ptr lCache(new LockableCache()); lCache->fileName = path; lCache->buffer = newFileCache(); lCache->ffi = *ffi; m_cacheMap[ffi->fh] = lCache; return 0; } int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_loopMutex); buffer_ptr wrapper = m_cacheMap[ffi->fh]; guard.unlock(); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->byteSize() > 1024 * 1024 * 10) { guard.lock(); m_jobQueue.push_front(ffi->fh); m_loopCond.notify_all(); guard.unlock(); wrapper->cond.wait(buff_guard); } wrapper->buffer->writeData(offset, buf); guard.lock(); m_jobQueue.push_back(ffi->fh); return size; } int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi) { boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex); return EOPNOTSUPP; } int BufferAgent::onFlush(std::string path, ffi_type ffi) { unique_lock guard(m_loopMutex); buffer_ptr wrapper = m_cacheMap[ffi->fh]; guard.unlock(); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->blockCount() > 0) { block_ptr block = wrapper->buffer->removeOldestBlock(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); if(res < 0) { while(wrapper->buffer->blockCount() > 0) { (void) wrapper->buffer->removeOldestBlock(); } return res; } } guard.lock(); m_jobQueue.remove(ffi->fh); return 0; } int BufferAgent::onRelease(std::string path, ffi_type ffi) { boost::unique_lock<boost::recursive_mutex> guard(m_loopMutex); m_cacheMap.erase(ffi->fh); return 0; } void BufferAgent::agentStart(int worker_count) { m_workers.clear(); m_agentActive = true; while(worker_count--) { m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::workerLoop, this)))); } } void BufferAgent::agentStop() { m_agentActive = false; m_loopCond.notify_all(); while(m_workers.size() > 0) { m_workers.back()->join(); m_workers.pop_back(); } } void BufferAgent::workerLoop() { unique_lock guard(m_loopMutex); while(m_agentActive) { while(m_jobQueue.empty() && m_agentActive) m_loopCond.wait(guard); if(!m_agentActive) return; fd_type file = m_jobQueue.front(); buffer_ptr wrapper = m_cacheMap[file]; m_jobQueue.pop_front(); m_loopCond.notify_all(); if(!wrapper) continue; { guard.unlock(); unique_lock buff_guard(wrapper->mutex); block_ptr block = wrapper->buffer->removeOldestBlock(); if(block) { int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); wrapper->cond.notify_all(); } buff_guard.unlock(); guard.lock(); if(wrapper->buffer->blockCount() > 0) { m_jobQueue.push_back(file); } } } } boost::shared_ptr<FileCache> BufferAgent::newFileCache() { return boost::shared_ptr<FileCache>(new FileCache(100 * 1024)); } } // namespace helpers } // namespace veil <|endoftext|>
<commit_before>#include "calcengine.h" #include <stdexcept> #include <cmath> #include <queue> #include <stack> //Environment Environment::Environment() { mValues = { { "pi", 3.141592653589793238463 } }; } const std::unordered_map<std::string, double>& Environment::variables() { return mValues; } void Environment::set(std::string variable, double value) { mValues[variable] = value; } bool Environment::getVariable(std::string variable, double& value) const { if (mValues.count(variable) > 0) { value = mValues.at(variable); return true; } else { return false; } } double Environment::valueOf(std::string variable) const { return mValues.at(variable); } //Calc engine Operator::Operator(char op, int precedence, OperatorAssociativity associativity, ApplyBinaryOperator applyFn) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mBinaryApplyFn(applyFn), mIsUnary(false) { } Operator::Operator(char op, int precedence, OperatorAssociativity associativity, ApplyUnaryOperator applyFn) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mUnaryApplyFn(applyFn), mIsUnary(true) { } Operator::Operator(char op, int precedence, OperatorAssociativity associativity) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mBinaryApplyFn([](double, double) { return 0; }), mIsUnary(true) { } char Operator::op() const { return mOp; } int Operator::precedence() const { return mPrecedence; } OperatorAssociativity Operator::associativity() const { return mAssociativity; } double Operator::apply(double x, double y) const { return mBinaryApplyFn(x, y); } double Operator::apply(double x) const { return mUnaryApplyFn(x); } bool Operator::isUnary() const { return mIsUnary; } CalcEngine::CalcEngine() { mBinaryOperators = { { '^', Operator('^', 4, OperatorAssociativity::RIGHT, [](double x, double y) { return pow(x, y); }) }, { '*', Operator('*', 3, OperatorAssociativity::LEFT, [](double x, double y) { return x * y; }) }, { '/', Operator('/', 3, OperatorAssociativity::LEFT, [](double x, double y) { return x / y; }) }, { '%', Operator('%', 3, OperatorAssociativity::LEFT, [](double x, double y) { return (int)x % (int)y; }) }, { '+', Operator('+', 2, OperatorAssociativity::LEFT, [](double x, double y) { return x + y; }) }, { '-', Operator('-', 2, OperatorAssociativity::LEFT, [](double x, double y) { return x - y; }) }, { '=', Operator('=', 1, OperatorAssociativity::RIGHT) } }; mUnaryOperators = { { '-', Operator('-', 5, OperatorAssociativity::LEFT, [](double x) { return -x; }) }, }; mFunctions = { { "sin", [](double x) { return sin(x); } }, { "cos", [](double x) { return cos(x); } }, { "tan", [](double x) { return tan(x); } }, { "sqrt", [](double x) { return sqrt(x); } }, { "asin", [](double x) { return asin(x); } }, { "acos", [](double x) { return acos(x); } }, { "atan", [](double x) { return atan(x); } }, { "ln", [](double x) { return log(x); } }, { "log", [](double x) { return log10(x); } }, }; } std::vector<Token> CalcEngine::tokenize(std::string str) { std::vector<Token> tokens; for (std::size_t i = 0; i < str.size(); i++) { char current = str[i]; //Skip whitespaces if (isspace(current)) { continue; } //Parenthesis if (current == '(') { tokens.push_back({ TokenType::LEFT_PARENTHESIS }); continue; } if (current == ')') { tokens.push_back({ TokenType::RIGHT_PARENTHESIS }); continue; } //Number if (isdigit(current)) { std::string num { current }; bool hasDecimalPoint = false; int base = 10; //Check if different base if (current == '0' && (i + 1) < str.size()) { char baseChar = str[i + 1]; if (baseChar == 'b') { base = 2; num = ""; i++; } else if (baseChar == 'x') { base = 16; num = ""; i++; } } while (true) { std::size_t next = i + 1; if (next >= str.size()) { break; } current = std::tolower(str[next]); if (current == '.') { if (!hasDecimalPoint) { if (base == 10) { hasDecimalPoint = true; } else { throw std::runtime_error("Decimal points are only allowed in base 10."); } } else { throw std::runtime_error("The token already contains a decimal point."); } } else { if (base == 2) { if (!(current == '0' || current == '1')) { break; } } else if (base == 10) { if (!isdigit(current)) { break; } } else if (base == 16) { if (!(isdigit(current) || current == 'a' || current == 'b' || current == 'c' || current == 'd' || current == 'e' || current == 'f')) { break; } } } num += current; i = next; } if (base == 10) { tokens.push_back(Token(std::stod(num))); } else { tokens.push_back(Token(std::stoi(num, nullptr, base))); } continue; } //Identifier if (isalpha(current)) { std::string identifier { current }; while (true) { std::size_t next = i + 1; if (next >= str.size()) { break; } current = str[next]; if (!(isdigit(current) || isalpha(current))) { break; } identifier += current; i = next; } tokens.push_back(Token(identifier)); continue; } //Operator tokens.push_back({ TokenType::OPERATOR, current }); } return tokens; } //Returns the next token Token nextToken(std::vector<Token>& tokens, std::size_t& index) { index++; if (index >= tokens.size()) { throw std::runtime_error("Reached end of tokens"); } return tokens[index]; } const Operator& CalcEngine::getOperator(char op, bool isUnary) const { if (isUnary) { if (mUnaryOperators.count(op) > 0) { return mUnaryOperators.at(op); } else { throw std::runtime_error("'" + std::string { op } + "' is not a defined unary operator."); } } else { if (mBinaryOperators.count(op) > 0) { return mBinaryOperators.at(op); } else { throw std::runtime_error("'" + std::string { op } + "' is not a defined binary operator."); } } } std::vector<Token> CalcEngine::toPostfix(std::vector<Token> tokens) { std::vector<Token> outputQueue; std::stack<Token> operatorStack; Token prevToken(TokenType::OPERATOR, 0); for (int i = 0; i < tokens.size(); ++i) { auto currentToken = tokens[i]; switch (currentToken.type()) { case TokenType::NUMBER: outputQueue.push_back(currentToken); break; case TokenType::IDENTIFIER: //Check if function if (mFunctions.count(currentToken.identifier())) { currentToken.makeFunction(); operatorStack.push(currentToken); } else { outputQueue.push_back(currentToken); } break; case TokenType::OPERATOR: { //Check if a unary operator if (prevToken.type() == TokenType::OPERATOR || prevToken.type() == TokenType::LEFT_PARENTHESIS) { currentToken.makeUnary(); } auto op1 = getOperator(currentToken.charValue(), currentToken.isUnary()); while (true) { //Check for termination if (!operatorStack.empty()) { auto topToken = operatorStack.top(); if (topToken.type() == TokenType::OPERATOR) { auto op2 = getOperator(topToken.charValue(), currentToken.isUnary()); if (op1.associativity() == OperatorAssociativity::LEFT) { if (op1.precedence() > op2.precedence()) { break; } } else { if (op1.precedence() >= op2.precedence()) { break; } } } else { break; } } else { break; } //Pop op2 from the operator stack and push it to the output queue outputQueue.push_back(operatorStack.top()); operatorStack.pop(); } operatorStack.push(currentToken); } break; case TokenType::LEFT_PARENTHESIS: operatorStack.push(currentToken); break; case TokenType::RIGHT_PARENTHESIS: { while (true) { //If empty, than the parenthesis does not match if (operatorStack.empty()) { throw std::runtime_error("The parenthesis does not match."); } auto op = operatorStack.top(); operatorStack.pop(); if (op.type() == TokenType::OPERATOR) { outputQueue.push_back(op); } else if (op.type() == TokenType::LEFT_PARENTHESIS) { break; } } } break; default: break; } prevToken = currentToken; } //Push the remaining operators to the output queue while (!operatorStack.empty()) { auto op = operatorStack.top(); if (op.type() == TokenType::LEFT_PARENTHESIS || op.type() == TokenType::RIGHT_PARENTHESIS) { throw std::runtime_error("The parenthsis does not match."); } operatorStack.pop(); outputQueue.push_back(op); } return outputQueue; } double CalcEngine::eval(std::string expression) { Environment env; return eval(expression, env); } //Returns the value of the given token double getValue(Environment& env, Token token) { if (token.type() == TokenType::IDENTIFIER) { double value; if (env.getVariable(token.identifier(), value)) { return value; } else { throw std::runtime_error("There exists no variable called '" + token.identifier() + "'."); } } else { return token.doubleValue(); } } double CalcEngine::eval(std::string expression, Environment& env) { //Tokenize auto tokens = toPostfix(tokenize(expression)); //Evaluate the resul std::stack<Token> valueStack; for (auto token : tokens) { switch (token.type()) { case TokenType::NUMBER: valueStack.push(token); break; case TokenType::IDENTIFIER: { if (token.isFunction()) { if (valueStack.size() < 1) { throw std::runtime_error("Expected one operand."); } auto op = valueStack.top(); valueStack.pop(); //Function valueStack.push(mFunctions[token.identifier()](getValue(env, op))); } else { //Variable valueStack.push(token); } } break; case TokenType::OPERATOR: { if (token.isUnary()) { if (valueStack.size() < 1) { throw std::runtime_error("Expected one operand."); } auto op1 = valueStack.top(); valueStack.pop(); auto op = getOperator(token.charValue(), true); valueStack.push(Token(op.apply(getValue(env, op1)))); } else { if (valueStack.size() < 2) { throw std::runtime_error("Expected two operands."); } auto op2 = valueStack.top(); valueStack.pop(); auto op1 = valueStack.top(); valueStack.pop(); if (token.charValue() == '=') { //Assignment env.set(op1.identifier(), op2.doubleValue()); valueStack.push(op2); } else { auto op = getOperator(token.charValue()); valueStack.push(Token(op.apply(getValue(env, op1), getValue(env, op2)))); } } } break; default: break; } } if (valueStack.empty()) { throw std::runtime_error("Expected result."); } return getValue(env, valueStack.top()); } <commit_msg>Fixed error with functions.<commit_after>#include "calcengine.h" #include <stdexcept> #include <cmath> #include <queue> #include <stack> //Environment Environment::Environment() { mValues = { { "pi", 3.141592653589793238463 } }; } const std::unordered_map<std::string, double>& Environment::variables() { return mValues; } void Environment::set(std::string variable, double value) { mValues[variable] = value; } bool Environment::getVariable(std::string variable, double& value) const { if (mValues.count(variable) > 0) { value = mValues.at(variable); return true; } else { return false; } } double Environment::valueOf(std::string variable) const { return mValues.at(variable); } //Calc engine Operator::Operator(char op, int precedence, OperatorAssociativity associativity, ApplyBinaryOperator applyFn) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mBinaryApplyFn(applyFn), mIsUnary(false) { } Operator::Operator(char op, int precedence, OperatorAssociativity associativity, ApplyUnaryOperator applyFn) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mUnaryApplyFn(applyFn), mIsUnary(true) { } Operator::Operator(char op, int precedence, OperatorAssociativity associativity) : mOp(op), mPrecedence(precedence), mAssociativity(associativity), mBinaryApplyFn([](double, double) { return 0; }), mIsUnary(true) { } char Operator::op() const { return mOp; } int Operator::precedence() const { return mPrecedence; } OperatorAssociativity Operator::associativity() const { return mAssociativity; } double Operator::apply(double x, double y) const { return mBinaryApplyFn(x, y); } double Operator::apply(double x) const { return mUnaryApplyFn(x); } bool Operator::isUnary() const { return mIsUnary; } CalcEngine::CalcEngine() { mBinaryOperators = { { '^', Operator('^', 4, OperatorAssociativity::RIGHT, [](double x, double y) { return pow(x, y); }) }, { '*', Operator('*', 3, OperatorAssociativity::LEFT, [](double x, double y) { return x * y; }) }, { '/', Operator('/', 3, OperatorAssociativity::LEFT, [](double x, double y) { return x / y; }) }, { '%', Operator('%', 3, OperatorAssociativity::LEFT, [](double x, double y) { return (int)x % (int)y; }) }, { '+', Operator('+', 2, OperatorAssociativity::LEFT, [](double x, double y) { return x + y; }) }, { '-', Operator('-', 2, OperatorAssociativity::LEFT, [](double x, double y) { return x - y; }) }, { '=', Operator('=', 1, OperatorAssociativity::RIGHT) } }; mUnaryOperators = { { '-', Operator('-', 5, OperatorAssociativity::LEFT, [](double x) { return -x; }) }, }; mFunctions = { { "sin", [](double x) { return sin(x); } }, { "cos", [](double x) { return cos(x); } }, { "tan", [](double x) { return tan(x); } }, { "sqrt", [](double x) { return sqrt(x); } }, { "asin", [](double x) { return asin(x); } }, { "acos", [](double x) { return acos(x); } }, { "atan", [](double x) { return atan(x); } }, { "ln", [](double x) { return log(x); } }, { "log", [](double x) { return log10(x); } }, }; } std::vector<Token> CalcEngine::tokenize(std::string str) { std::vector<Token> tokens; for (std::size_t i = 0; i < str.size(); i++) { char current = str[i]; //Skip whitespaces if (isspace(current)) { continue; } //Parenthesis if (current == '(') { tokens.push_back({ TokenType::LEFT_PARENTHESIS }); continue; } if (current == ')') { tokens.push_back({ TokenType::RIGHT_PARENTHESIS }); continue; } //Number if (isdigit(current)) { std::string num { current }; bool hasDecimalPoint = false; int base = 10; //Check if different base if (current == '0' && (i + 1) < str.size()) { char baseChar = str[i + 1]; if (baseChar == 'b') { base = 2; num = ""; i++; } else if (baseChar == 'x') { base = 16; num = ""; i++; } } while (true) { std::size_t next = i + 1; if (next >= str.size()) { break; } current = std::tolower(str[next]); if (current == '.') { if (!hasDecimalPoint) { if (base == 10) { hasDecimalPoint = true; } else { throw std::runtime_error("Decimal points are only allowed in base 10."); } } else { throw std::runtime_error("The token already contains a decimal point."); } } else { if (base == 2) { if (!(current == '0' || current == '1')) { break; } } else if (base == 10) { if (!isdigit(current)) { break; } } else if (base == 16) { if (!(isdigit(current) || current == 'a' || current == 'b' || current == 'c' || current == 'd' || current == 'e' || current == 'f')) { break; } } } num += current; i = next; } if (base == 10) { tokens.push_back(Token(std::stod(num))); } else { tokens.push_back(Token(std::stoi(num, nullptr, base))); } continue; } //Identifier if (isalpha(current)) { std::string identifier { current }; while (true) { std::size_t next = i + 1; if (next >= str.size()) { break; } current = str[next]; if (!(isdigit(current) || isalpha(current))) { break; } identifier += current; i = next; } tokens.push_back(Token(identifier)); continue; } //Operator tokens.push_back({ TokenType::OPERATOR, current }); } return tokens; } //Returns the next token Token nextToken(std::vector<Token>& tokens, std::size_t& index) { index++; if (index >= tokens.size()) { throw std::runtime_error("Reached end of tokens"); } return tokens[index]; } const Operator& CalcEngine::getOperator(char op, bool isUnary) const { if (isUnary) { if (mUnaryOperators.count(op) > 0) { return mUnaryOperators.at(op); } else { throw std::runtime_error("'" + std::string { op } + "' is not a defined unary operator."); } } else { if (mBinaryOperators.count(op) > 0) { return mBinaryOperators.at(op); } else { throw std::runtime_error("'" + std::string { op } + "' is not a defined binary operator."); } } } std::vector<Token> CalcEngine::toPostfix(std::vector<Token> tokens) { std::vector<Token> outputQueue; std::stack<Token> operatorStack; Token prevToken(TokenType::OPERATOR, 0); for (int i = 0; i < tokens.size(); ++i) { auto currentToken = tokens[i]; switch (currentToken.type()) { case TokenType::NUMBER: outputQueue.push_back(currentToken); break; case TokenType::IDENTIFIER: //Check if function if (mFunctions.count(currentToken.identifier())) { currentToken.makeFunction(); operatorStack.push(currentToken); } else { outputQueue.push_back(currentToken); } break; case TokenType::OPERATOR: { //Check if a unary operator if (prevToken.type() == TokenType::OPERATOR || prevToken.type() == TokenType::LEFT_PARENTHESIS) { currentToken.makeUnary(); } auto op1 = getOperator(currentToken.charValue(), currentToken.isUnary()); while (true) { //Check for termination if (!operatorStack.empty()) { auto topToken = operatorStack.top(); if (topToken.type() == TokenType::OPERATOR) { auto op2 = getOperator(topToken.charValue(), currentToken.isUnary()); if (op1.associativity() == OperatorAssociativity::LEFT) { if (op1.precedence() > op2.precedence()) { break; } } else { if (op1.precedence() >= op2.precedence()) { break; } } } else { break; } } else { break; } //Pop op2 from the operator stack and push it to the output queue outputQueue.push_back(operatorStack.top()); operatorStack.pop(); } operatorStack.push(currentToken); } break; case TokenType::LEFT_PARENTHESIS: operatorStack.push(currentToken); break; case TokenType::RIGHT_PARENTHESIS: { while (true) { //If empty, than the parenthesis does not match if (operatorStack.empty()) { throw std::runtime_error("The parenthesis does not match."); } auto op = operatorStack.top(); operatorStack.pop(); if (op.type() == TokenType::OPERATOR) { outputQueue.push_back(op); } else if (op.type() == TokenType::LEFT_PARENTHESIS) { break; } else if (op.type() == TokenType::IDENTIFIER) { if (op.isFunction()) { outputQueue.push_back(op); } } } } break; default: break; } prevToken = currentToken; } //Push the remaining operators to the output queue while (!operatorStack.empty()) { auto op = operatorStack.top(); if (op.type() == TokenType::LEFT_PARENTHESIS || op.type() == TokenType::RIGHT_PARENTHESIS) { throw std::runtime_error("The parenthsis does not match."); } operatorStack.pop(); outputQueue.push_back(op); } return outputQueue; } double CalcEngine::eval(std::string expression) { Environment env; return eval(expression, env); } //Returns the value of the given token double getValue(Environment& env, Token token) { if (token.type() == TokenType::IDENTIFIER) { double value; if (env.getVariable(token.identifier(), value)) { return value; } else { throw std::runtime_error("There exists no variable called '" + token.identifier() + "'."); } } else { return token.doubleValue(); } } double CalcEngine::eval(std::string expression, Environment& env) { //Tokenize auto tokens = toPostfix(tokenize(expression)); //Evaluate the resul std::stack<Token> valueStack; for (auto token : tokens) { switch (token.type()) { case TokenType::NUMBER: valueStack.push(token); break; case TokenType::IDENTIFIER: { if (token.isFunction()) { if (valueStack.size() < 1) { throw std::runtime_error("Expected one operand."); } auto op = valueStack.top(); valueStack.pop(); //Function valueStack.push(mFunctions[token.identifier()](getValue(env, op))); } else { //Variable valueStack.push(token); } } break; case TokenType::OPERATOR: { if (token.isUnary()) { if (valueStack.size() < 1) { throw std::runtime_error("Expected one operand."); } auto op1 = valueStack.top(); valueStack.pop(); auto op = getOperator(token.charValue(), true); valueStack.push(Token(op.apply(getValue(env, op1)))); } else { if (valueStack.size() < 2) { throw std::runtime_error("Expected two operands."); } auto op2 = valueStack.top(); valueStack.pop(); auto op1 = valueStack.top(); valueStack.pop(); if (token.charValue() == '=') { //Assignment env.set(op1.identifier(), op2.doubleValue()); valueStack.push(op2); } else { auto op = getOperator(token.charValue()); valueStack.push(Token(op.apply(getValue(env, op1), getValue(env, op2)))); } } } break; default: break; } } if (valueStack.empty()) { throw std::runtime_error("Expected result."); } return getValue(env, valueStack.top()); } <|endoftext|>
<commit_before>// Author : Andrei Gheata 02/10/00 #include "HelpTextTV.h" #ifndef WIN32 const char gTVHelpAbout[] = "\ TTreeView is GUI version of TTreeViewer, designed to handle ROOT trees and\n\ to take advantage of TTree class features in a graphical manner. It uses only\n\ ROOT native GUI widgets and has capability to work with several trees in the\n\ same session. It provides the following functionalities :\n\n\ - browsing all root files in the working directory and mapping trees inside;\n\ - once a tree is mapped, the user can browse branches and work with the\n\ corresponding sub-branches if there is no need for the whole tree;\n\ - fast drawing of branches by double-click;\n\ - easy edit the expressions to be drawn on X, Y and Z axis and/or selection;\n\ - dragging expressions to one axis and aliasing of expression names;\n\ - handle input/output event lists;\n\ - usage of predefined compatible drawing options;\n\ - possibility of executing user commands and macros and echoing of the current\n\ command;\n\ - possibility of interrupting the current command or the event loop (not yet);\n\ - possibility of selecting the tree entries to be processed (not yet);\n\ - take advantage of TTree class features via context menu;\n\n\ "; const char gTVHelpStart[] = "\ The quickest way to start the tree viewer is to start a ROOT session in \n\ your working directory where you have the root files containing trees.\n\ You will need first to load the library for TTreeView and optionally other\n\ libraries for user defined classes (you can do this later in the session) :\n\ root [0] gSystem->Load(\"TTreeView\");\n\ root [1] new TTreeView;\n\ or, to load the tree Mytree from the file Myfile :\n\ root [1] TFile file(\"Myfile\");\n\ root [2] new TTreeView(\"Mytree\");\n\n\ This will work if uou have the path to the library TTreeView defined in your\n\ .rootrc file.\n\n\ "; const char gTVHelpLayout[] = "\ The layout has the following items :\n\n\ - a menu bar with entries : File, Edit, Run, Options and Help;\n\ - a toolbar in the upper part where you can issue user commands, change\n\ the drawing option and the histogram name, two check buttons Hist and Rec\n\ which toggles histogram drawing mode and command recording respectively;\n\ - a button bar in the lower part with : buttons DRAW/STOP that issue histogram\n\ drawing and stop the current command respectively, two text widgets where \n\ input and output event lists can be specified, a message box and a RESET\n\ button on the right that clear edited expression content (see Editing...)\n\ - a tree-type list on the main left panel where you can browse the root files\n\ from the working directory and load the trees inside by double clicking.\n\ When the first tree is loaded, a new item called \"TreeList\" will pop-up on\n\ the list menu and will have the selected tree inside with all branches mapped\n\ Mapped trees are provided with context menus, activated by right-clicking;\n\ - a view-type list on the main right panel. The first column contain X, Y and\n\ Z expression items, an optional cut and ten optional editable expressions.\n\ The other items in this list are activated when a mapped item from the\n\ \"TreeList\" is left-clicked (tree or branch) and will describe the conyent\n\ of the tree (branch). Expressions and leaf-type items can be dragged or\n\ deleted. A right click on the list-box or item activates a general context\n\ menu.\n\n\ "; const char gTVHelpBrowse[] = "\ Browsing root files from the working directory :\n\n\ Just double-click on the directory item on the left and you will see all\n\ root files from this directory. Do it once more on the files with a leading +\n\ and you will see the trees inside. If you want one or more of those to\n\ be loaded, double-click on them and they will be mapped in a new item called\n\ \"TreeList\".\n\n\ Browsing trees :\n\n\ Left-clicking on trees from the TreeList will expand their content on the list\n\ from the right side. Double-clicking them will also open their content on the\n\ left, where you can click on branches to expand them on the right.\n\n\ "; const char gTVHelpDraggingItems[] = "\ Items that can be dragged from the list in the right : expressions and \n\ leaves. Dragging an item and dropping to another will copy the content of first\n\ to the last (leaf->expression, expression->expression). Items far to the right\n\ side of the list can be easily dragged to the left (where expressions are\n\ placed) by dragging them to the left at least 10 pixels.\n\n\ "; const char gTVHelpEditExpressions[] = "\ All editable expressions from the right panel has two components : a\n\ true name (that will be used when TTree::Draw() commands are issued) and an\n\ alias (used for labeling axes - not yet). The visible name is the alias if\n\ there is one and the true name otherwise.\n\n\ The expression editor can be activated by right clicking on an\n\ expression item via the command EditExpression from the context menu.\n\ An alternative is to use the Edit-Expression menu after the desired expression\n\ is selected. The editor will pop-up in the left part, but it can be moved.\n\ The editor usage is the following :\n\ - you can write C expressions made of leaf names by hand or you can insert\n\ any item from the right panel by clicking on it (recommandable);\n\ - you should write the item alias by hand since it not ony make the expression\n\ meaningfull, but it also highly improve the layout for big expressions\n\n\ "; const char gTVHelpUserCommands[] = "\ User commands can be issued directly from the textbox labeled \"Command\"\n\ from the upper-left toolbar by typing and pressing Enter at the end.\n\ An other way is from the right panel context menu : ExecuteCommand.\n\n\ All commands can be interrupted at any time by pressing the STOP button\n\ from the bottom-left (not yet)\n\n\ You can toggle recording of the current command in the history file by\n\ checking the Rec button from the top-right\n\n\ "; const char gTVHelpContext[] = "\ You can activate context menus by right-clicking on items or inside the\n\ box from the right.\n\n\ Context menus for mapped items from the left tree-type list :\n\n\ The items from the left that are provided with context menus are tree and\n\ branch items. You can directly activate the *MENU* marked methods of TTree\n\ from this menu.\n\n\ Context menu for the right panel :\n\n\ A general context manu of class TTreeView is acivated if the user\n\ right-clicks the right panel. Commands are :\n\ - ClearAll : clears the content of all expressions;\n\ - ClearExpression : clear the content of the clicked expression;\n\ - EditExpression : pops-up the expression editor;\n\ - ExecuteCommand : execute a user command;\n\ - MakeSelector : equivalent of TTree::MakeSelector();\n\ - Process : equivalent of TTree::Process();\n\ - RemoveExpression: removes clicked item from the list;\n\n\ "; const char gTVHelpDrawing[] = "\ Fast variable drawing : Just double-click an item from the right list.\n\n\ Normal drawing : Edit the X, Y, Z fields as you wish, fill input-output list\n\ names if you have them. You can change output histogram name, or toggle Hist\n\ and Scan modes by checking the corresponding buttons.\n\ Hist mode implies that the current histogram will be redrawn with the current\n\ graphics options, while Scan mode implies TTree::Scan()\n\n\ You have a complete list of histogram options in multicheckable lists from\n\ the Option menu. When using this menu, only the options compatible with the\n\ current histogram dimension will be available. You can check multiple options\n\ and reset them by checking the Default entries.\n\n\ After completing the previous operations you can issue the draw command by\n\ pressing the DRAW button.\n\n\ "; const char gTVHelpMacros[] = "\ Macros can be loaded and executed in this version only by issuing\n\ the corresponding user commands (see help on user commands)\n\n\ "; #else const char gTVHelpAbout[] = "empty"; const char gTVHelpStart[] = "empty"; const char gTVHelpLayout[] = "empty"; const char gTVHelpBrowse[] = "empty"; const char gTVHelpDraggingItems[] = "empty"; const char gTVHelpEditExpressions[] = "empty"; const char gTVHelpUserCommands[] = "empty"; const char gTVHelpLoopingEvents[] = "empty"; const char gTVHelpDrawing[] = "empty"; const char gTVHelpMacros[] = "empty"; #endif <commit_msg>terminators<commit_after>// Author : Andrei Gheata 02/10/00 #include "HelpTextTV.h" #ifndef WIN32 const char gTVHelpAbout[] = "\ TTreeView is GUI version of TTreeViewer, designed to handle ROOT trees and\n\ to take advantage of TTree class features in a graphical manner. It uses only\n\ ROOT native GUI widgets and has capability to work with several trees in the\n\ same session. It provides the following functionalities :\n\n\ - browsing all root files in the working directory and mapping trees inside;\n\ - once a tree is mapped, the user can browse branches and work with the\n\ corresponding sub-branches if there is no need for the whole tree;\n\ - fast drawing of branches by double-click;\n\ - easy edit the expressions to be drawn on X, Y and Z axis and/or selection;\n\ - dragging expressions to one axis and aliasing of expression names;\n\ - handle input/output event lists;\n\ - usage of predefined compatible drawing options;\n\ - possibility of executing user commands and macros and echoing of the current\n\ command;\n\ - possibility of interrupting the current command or the event loop (not yet);\n\ - possibility of selecting the tree entries to be processed (not yet);\n\ - take advantage of TTree class features via context menu;\n\n\ "; const char gTVHelpStart[] = "\ The quickest way to start the tree viewer is to start a ROOT session in \n\ your working directory where you have the root files containing trees.\n\ You will need first to load the library for TTreeView and optionally other\n\ libraries for user defined classes (you can do this later in the session) :\n\ root [0] gSystem->Load(\"TTreeView\");\n\ root [1] new TTreeView;\n\ or, to load the tree Mytree from the file Myfile :\n\ root [1] TFile file(\"Myfile\");\n\ root [2] new TTreeView(\"Mytree\");\n\n\ This will work if uou have the path to the library TTreeView defined in your\n\ .rootrc file.\n\n\ "; const char gTVHelpLayout[] = "\ The layout has the following items :\n\n\ - a menu bar with entries : File, Edit, Run, Options and Help;\n\ - a toolbar in the upper part where you can issue user commands, change\n\ the drawing option and the histogram name, two check buttons Hist and Rec\n\ which toggles histogram drawing mode and command recording respectively;\n\ - a button bar in the lower part with : buttons DRAW/STOP that issue histogram\n\ drawing and stop the current command respectively, two text widgets where \n\ input and output event lists can be specified, a message box and a RESET\n\ button on the right that clear edited expression content (see Editing...)\n\ - a tree-type list on the main left panel where you can browse the root files\n\ from the working directory and load the trees inside by double clicking.\n\ When the first tree is loaded, a new item called \"TreeList\" will pop-up on\n\ the list menu and will have the selected tree inside with all branches mapped\n\ Mapped trees are provided with context menus, activated by right-clicking;\n\ - a view-type list on the main right panel. The first column contain X, Y and\n\ Z expression items, an optional cut and ten optional editable expressions.\n\ The other items in this list are activated when a mapped item from the\n\ \"TreeList\" is left-clicked (tree or branch) and will describe the conyent\n\ of the tree (branch). Expressions and leaf-type items can be dragged or\n\ deleted. A right click on the list-box or item activates a general context\n\ menu.\n\n\ "; const char gTVHelpBrowse[] = "\ Browsing root files from the working directory :\n\n\ Just double-click on the directory item on the left and you will see all\n\ root files from this directory. Do it once more on the files with a leading +\n\ and you will see the trees inside. If you want one or more of those to\n\ be loaded, double-click on them and they will be mapped in a new item called\n\ \"TreeList\".\n\n\ Browsing trees :\n\n\ Left-clicking on trees from the TreeList will expand their content on the list\n\ from the right side. Double-clicking them will also open their content on the\n\ left, where you can click on branches to expand them on the right.\n\n\ "; const char gTVHelpDraggingItems[] = "\ Items that can be dragged from the list in the right : expressions and \n\ leaves. Dragging an item and dropping to another will copy the content of first\n\ to the last (leaf->expression, expression->expression). Items far to the right\n\ side of the list can be easily dragged to the left (where expressions are\n\ placed) by dragging them to the left at least 10 pixels.\n\n\ "; const char gTVHelpEditExpressions[] = "\ All editable expressions from the right panel has two components : a\n\ true name (that will be used when TTree::Draw() commands are issued) and an\n\ alias (used for labeling axes - not yet). The visible name is the alias if\n\ there is one and the true name otherwise.\n\n\ The expression editor can be activated by right clicking on an\n\ expression item via the command EditExpression from the context menu.\n\ An alternative is to use the Edit-Expression menu after the desired expression\n\ is selected. The editor will pop-up in the left part, but it can be moved.\n\ The editor usage is the following :\n\ - you can write C expressions made of leaf names by hand or you can insert\n\ any item from the right panel by clicking on it (recommandable);\n\ - you should write the item alias by hand since it not ony make the expression\n\ meaningfull, but it also highly improve the layout for big expressions\n\n\ "; const char gTVHelpUserCommands[] = "\ User commands can be issued directly from the textbox labeled \"Command\"\n\ from the upper-left toolbar by typing and pressing Enter at the end.\n\ An other way is from the right panel context menu : ExecuteCommand.\n\n\ All commands can be interrupted at any time by pressing the STOP button\n\ from the bottom-left (not yet)\n\n\ You can toggle recording of the current command in the history file by\n\ checking the Rec button from the top-right\n\n\ "; const char gTVHelpContext[] = "\ You can activate context menus by right-clicking on items or inside the\n\ box from the right.\n\n\ Context menus for mapped items from the left tree-type list :\n\n\ The items from the left that are provided with context menus are tree and\n\ branch items. You can directly activate the *MENU* marked methods of TTree\n\ from this menu.\n\n\ Context menu for the right panel :\n\n\ A general context manu of class TTreeView is acivated if the user\n\ right-clicks the right panel. Commands are :\n\ - ClearAll : clears the content of all expressions;\n\ - ClearExpression : clear the content of the clicked expression;\n\ - EditExpression : pops-up the expression editor;\n\ - ExecuteCommand : execute a user command;\n\ - MakeSelector : equivalent of TTree::MakeSelector();\n\ - Process : equivalent of TTree::Process();\n\ - RemoveExpression: removes clicked item from the list;\n\n\ "; const char gTVHelpDrawing[] = "\ Fast variable drawing : Just double-click an item from the right list.\n\n\ Normal drawing : Edit the X, Y, Z fields as you wish, fill input-output list\n\ names if you have them. You can change output histogram name, or toggle Hist\n\ and Scan modes by checking the corresponding buttons.\n\ Hist mode implies that the current histogram will be redrawn with the current\n\ graphics options, while Scan mode implies TTree::Scan()\n\n\ You have a complete list of histogram options in multicheckable lists from\n\ the Option menu. When using this menu, only the options compatible with the\n\ current histogram dimension will be available. You can check multiple options\n\ and reset them by checking the Default entries.\n\n\ After completing the previous operations you can issue the draw command by\n\ pressing the DRAW button.\n\n\ "; const char gTVHelpMacros[] = "\ Macros can be loaded and executed in this version only by issuing\n\ the corresponding user commands (see help on user commands)\n\n\ "; #else const char gTVHelpAbout[] = "empty"; const char gTVHelpStart[] = "empty"; const char gTVHelpLayout[] = "empty"; const char gTVHelpBrowse[] = "empty"; const char gTVHelpDraggingItems[] = "empty"; const char gTVHelpEditExpressions[] = "empty"; const char gTVHelpUserCommands[] = "empty"; const char gTVHelpLoopingEvents[] = "empty"; const char gTVHelpDrawing[] = "empty"; const char gTVHelpMacros[] = "empty"; #endif <|endoftext|>
<commit_before>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_Config = new exConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_Lexers = new exLexers(exFileName("../data/lexers.xml")); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_TextFile = new exTextFile(exFileName("test.h"), m_Config, m_Lexers); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() == "test.h"); // test exFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test exFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test exLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2"); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test exLexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); // 80 - 4 (comments) - 2 (spaces) // test exRCS CPPUNIT_ASSERT(m_RCS->GetAuthor().empty()); CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test exTextFile CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); // do the same test CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_HEADER)); CPPUNIT_ASSERT(m_TextFile->GetTool().GetId() == ID_TOOL_REPORT_HEADER); //wxLogMessage(m_TextFile->GetStatistics().Get() + m_TextFile->GetRCS().GetDescription()); // CPPUNIT_ASSERT(m_TextFile->GetRCS().GetDescription() == // "Declaration of classes for wxextension cpp unit testing"); CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD)); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer != NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { m_Dir = new exDir("./"); m_Grid = new exGrid(wxTheApp->GetTopWindow()); m_ListView = new exListView(wxTheApp->GetTopWindow()); m_STC = new exSTC(wxTheApp->GetTopWindow(), exFileName("test.h")); m_STCShell = new exSTCShell(wxTheApp->GetTopWindow()); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testConstructors() { } void exAppTestFixture::testMethods() { // test exApp CPPUNIT_ASSERT(exApp::GetConfig() != NULL); CPPUNIT_ASSERT(exApp::GetLexers() != NULL); CPPUNIT_ASSERT(exApp::GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->FindFiles() > 0); CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetSelectedCellsValue() == "test"); // test exListView exListView->InsertColumn("String", exColumn::COL_STRING); exListView->InsertColumn("Number", exColumn::COL_INT); CPPUNIT_ASSERT(exListView->FindColumn("String") == 0); CPPUNIT_ASSERT(exListView->FindColumn("Number") == 1); // test exSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // test exSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); CPPUNIT_ASSERT(m_STCShell->GetHistory().Contains("test4")); // test exSVN CPPUNIT_ASSERT(m_SVN->GetInfo(false) == 0); // do not use a dialog // The contents depends on the svn stat, of course, // so do not assert on it. m_SVN->GetContents(); // test util CPPUNIT_ASSERT(exClipboardAdd("test")); CPPUNIT_ASSERT(exClipboardGet() == "test"); CPPUNIT_ASSERT(exGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(exGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(!exMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(exMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(exSkipWhiteSpace("t es t") == "t es t"); } void exAppTestFixture::tearDown() { } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { #ifndef APP_TEST // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingConfig", &exTestFixture::testTimingConfig)); #else addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); #endif } <commit_msg>fixed tests<commit_after>/******************************************************************************\ * File: test.cpp * Purpose: Implementation for wxextension cpp unit testing * Author: Anton van Wezenbeek * RCS-ID: $Id$ * Created: za 17 jan 2009 11:51:20 CET * * Copyright (c) 2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <TestCaller.h> #include "test.h" void exTestFixture::setUp() { m_Config = new exConfig("test.cfg", wxCONFIG_USE_LOCAL_FILE); m_File = new exFile("test.h"); m_FileName = new exFileName("test.h"); m_FileNameStatistics = new exFileNameStatistics("test.h"); m_Lexer = new exLexer(); m_Lexers = new exLexers(exFileName("../data/lexers.xml")); m_RCS = new exRCS(); m_Stat = new exStat("test.h"); m_Statistics = new exStatistics<long>(); m_TextFile = new exTextFile(exFileName("test.h"), m_Config, m_Lexers); m_Tool = new exTool(ID_TOOL_REPORT_COUNT); } void exTestFixture::testConstructors() { CPPUNIT_ASSERT(m_File != NULL); } void exTestFixture::testMethods() { // test exConfig CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val"); CPPUNIT_ASSERT(m_Config->Get("keylong", 12) == 12); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true)); CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL); m_Config->Set("keystring", "val2"); CPPUNIT_ASSERT(m_Config->Get("keystring", "val") == "val2"); m_Config->Set("keylong", 15); CPPUNIT_ASSERT(m_Config->Get("keylong", 7) == 15); m_Config->SetBool("keybool", false); CPPUNIT_ASSERT(m_Config->GetBool("keybool", true) == false); m_Config->Toggle("keybool"); CPPUNIT_ASSERT(m_Config->GetBool("keybool", false)); // test exFile CPPUNIT_ASSERT(m_File->GetStat().IsOk()); CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() == "test.h"); // test exFileName CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty()); CPPUNIT_ASSERT(m_FileName->GetStat().IsOk()); m_FileName->Assign("xxx"); m_FileName->GetStat().Update("xxx"); CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk()); // test exFileNameStatistics CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty()); CPPUNIT_ASSERT(m_FileNameStatistics->Get("xx") == 0); // test exLexer *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); // we have no lexers m_Lexer->SetKeywords("test11 test21:1 test31:1 test12:2 test22:2"); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test11")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test21")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test12")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("test22")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("te")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xx")); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); // test exLexers CPPUNIT_ASSERT(m_Lexers->Read()); *m_Lexer = m_Lexers->FindByText("// this is a cpp comment text"); CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName("test.h")).GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->FindByName("cpp").GetScintillaLexer() == "cpp"); CPPUNIT_ASSERT(m_Lexers->Count() > 0); CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName("test.h")).empty()); CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty()); CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty()); CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty()); CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty()); CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty()); CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty()); CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty()); CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty()); CPPUNIT_ASSERT(m_Lexer->IsKeyword("class")); CPPUNIT_ASSERT(m_Lexer->IsKeyword("const")); CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith("cla")); CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith("xxx")); CPPUNIT_ASSERT(!m_Lexer->MakeComment("test", true).empty()); CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); // 80 - 4 (comments) - 2 (spaces) // test exRCS CPPUNIT_ASSERT(m_RCS->GetAuthor().empty()); CPPUNIT_ASSERT(m_RCS->GetDescription().empty()); CPPUNIT_ASSERT(m_RCS->GetUser().empty()); // test exStat CPPUNIT_ASSERT(!m_Stat->IsLink()); CPPUNIT_ASSERT(m_Stat->IsOk()); CPPUNIT_ASSERT(!m_Stat->IsReadOnly()); CPPUNIT_ASSERT(m_Stat->Update("testlink")); // CPPUNIT_ASSERT(m_Stat->IsLink()); // test exStatistics m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 1); m_Statistics->Inc("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 2); m_Statistics->Set("test", 13); CPPUNIT_ASSERT(m_Statistics->Get("test") == 13); m_Statistics->Dec("test"); CPPUNIT_ASSERT(m_Statistics->Get("test") == 12); m_Statistics->Inc("test2"); CPPUNIT_ASSERT(m_Statistics->Get("test2") == 1); m_Statistics->Clear(); CPPUNIT_ASSERT(m_Statistics->GetItems().empty()); // test exTextFile CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); // do the same test CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty()); CPPUNIT_ASSERT(!m_TextFile->IsOpened()); // file should be closed after running tool CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_HEADER)); CPPUNIT_ASSERT(m_TextFile->GetTool().GetId() == ID_TOOL_REPORT_HEADER); //wxLogMessage(m_TextFile->GetStatistics().Get() + m_TextFile->GetRCS().GetDescription()); // CPPUNIT_ASSERT(m_TextFile->GetRCS().GetDescription() == // "Declaration of classes for wxextension cpp unit testing"); CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD)); // CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty()); // test exTool CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0); } void exTestFixture::testTiming() { exFile file("test.h"); CPPUNIT_ASSERT(file.IsOpened()); wxStopWatch sw; const int max = 10000; for (int i = 0; i < max; i++) { wxString* buffer = file.Read(); CPPUNIT_ASSERT(buffer != NULL); delete buffer; } const long exfile_read = sw.Time(); sw.Start(); wxFile wxfile("test.h"); for (int j = 0; j < max; j++) { char* charbuffer = new char[wxfile.Length()]; wxfile.Read(charbuffer, wxfile.Length()); wxString* buffer = new wxString(charbuffer, wxfile.Length()); delete charbuffer; delete buffer; } const long file_read = sw.Time(); printf( "exFile::Read:%ld wxFile::Read:%ld\n", exfile_read, file_read); } void exTestFixture::testTimingAttrib() { const int max = 1000; wxStopWatch sw; const exFileName exfile("test.h"); int checked = 0; for (int i = 0; i < max; i++) { checked += exfile.GetStat().IsReadOnly(); } const long exfile_time = sw.Time(); sw.Start(); const wxFileName file("test.h"); for (int j = 0; j < max; j++) { checked += file.IsFileWritable(); } const long file_time = sw.Time(); printf( "exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\n", exfile_time, file_time); } void exTestFixture::testTimingConfig() { const int max = 100000; wxStopWatch sw; for (int i = 0; i < max; i++) { m_Config->Get("test", 0); } const long exconfig = sw.Time(); sw.Start(); for (int j = 0; j < max; j++) { m_Config->Read("test", 0l); } const long config = sw.Time(); printf( "exConfig::Get:%ld wxConfig::Read:%ld\n", exconfig, config); } void exTestFixture::tearDown() { } void exAppTestFixture::setUp() { m_Dir = new exDir("./"); m_Grid = new exGrid(wxTheApp->GetTopWindow()); m_ListView = new exListView(wxTheApp->GetTopWindow()); m_STC = new exSTC(wxTheApp->GetTopWindow(), exFileName("test.h")); m_STCShell = new exSTCShell(wxTheApp->GetTopWindow()); m_SVN = new exSVN(SVN_STAT, "test.h"); } void exAppTestFixture::testConstructors() { } void exAppTestFixture::testMethods() { // test exApp CPPUNIT_ASSERT(exApp::GetConfig() != NULL); CPPUNIT_ASSERT(exApp::GetLexers() != NULL); CPPUNIT_ASSERT(exApp::GetPrinter() != NULL); // test exDir CPPUNIT_ASSERT(m_Dir->FindFiles() > 0); CPPUNIT_ASSERT(m_Dir->GetFiles().GetCount() > 0); // test exGrid CPPUNIT_ASSERT(m_Grid->CreateGrid(5, 5)); m_Grid->SelectAll(); m_Grid->SetGridCellValue(wxGridCellCoords(0, 0), "test"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test"); m_Grid->SetCellsValue(wxGridCellCoords(0, 0), "test1\ttest2\ntest3\ttest4\n"); CPPUNIT_ASSERT(m_Grid->GetCellValue(0, 0) == "test1"); // test exListView m_ListView->SetSingleStyle(wxLC_REPORT); // wxLC_ICON); m_ListView->InsertColumn("String", exColumn::COL_STRING); m_ListView->InsertColumn("Number", exColumn::COL_INT); CPPUNIT_ASSERT(m_ListView->FindColumn("String") == 0); CPPUNIT_ASSERT(m_ListView->FindColumn("Number") == 1); // test exSTC CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h"); // test exSTCShell m_STCShell->Prompt("test1"); m_STCShell->Prompt("test2"); m_STCShell->Prompt("test3"); m_STCShell->Prompt("test4"); // Prompting does not add a command to history... // TODO: Make a better test. CPPUNIT_ASSERT(!m_STCShell->GetHistory().Contains("test4")); // test exSVN CPPUNIT_ASSERT(m_SVN->GetInfo(false) == 0); // do not use a dialog // The contents depends on the svn stat, of course, // so do not assert on it. m_SVN->GetContents(); // test util CPPUNIT_ASSERT(exClipboardAdd("test")); CPPUNIT_ASSERT(exClipboardGet() == "test"); CPPUNIT_ASSERT(exGetNumberOfLines("test\ntest\n") == 3); CPPUNIT_ASSERT(exGetLineNumberFromText("test on line: 1200") == 1200); CPPUNIT_ASSERT(!exMatchesOneOf(wxFileName("test.txt"), "*.cpp")); CPPUNIT_ASSERT(exMatchesOneOf(wxFileName("test.txt"), "*.cpp;*.txt")); CPPUNIT_ASSERT(exSkipWhiteSpace("t es t") == "t es t"); } void exAppTestFixture::tearDown() { } exTestSuite::exTestSuite() : CppUnit::TestSuite("wxextension test suite") { #ifndef APP_TEST // Add the tests. addTest(new CppUnit::TestCaller<exTestFixture>( "testConstructors", &exTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exTestFixture>( "testMethods", &exTestFixture::testMethods)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTiming", &exTestFixture::testTiming)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingAttrib", &exTestFixture::testTimingAttrib)); addTest(new CppUnit::TestCaller<exTestFixture>( "testTimingConfig", &exTestFixture::testTimingConfig)); #else addTest(new CppUnit::TestCaller<exAppTestFixture>( "testConstructors", &exAppTestFixture::testConstructors)); addTest(new CppUnit::TestCaller<exAppTestFixture>( "testMethods", &exAppTestFixture::testMethods)); #endif } <|endoftext|>
<commit_before>#include <gl/glew.h> #include "SpriteRenderer.h" #include "ShaderMgr.h" #include "ScreenFBO.h" #include "BlendShader.h" #include "dataset/ISprite.h" #include "dataset/ISymbol.h" #include "dataset/SpriteTools.h" #include "view/Camera.h" namespace d2d { SpriteRenderer* SpriteRenderer::m_instance = NULL; SpriteRenderer::SpriteRenderer() : m_fbo(600, 600) , m_cam(NULL) { } void SpriteRenderer::Draw(const ISprite* sprite, const d2d::Matrix& mt, const Colorf& mul, const Colorf& add, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans, bool multi_draw) const { if (!sprite->visiable) return; if (!multi_draw || sprite->GetBlendMode() == BM_NORMAL) { DrawImpl(sprite, mt, mul, add, r_trans, g_trans, b_trans); } else { DrawImplBlend(sprite); } } void SpriteRenderer::Draw(const ISymbol* symbol, const d2d::Matrix& mt, const Vector& pos, float angle/* = 0.0f*/, float xScale/* = 1.0f*/, float yScale/* = 1.0f*/, float xShear/* = 0.0f*/, float yShear/* = 0.0f*/, const Colorf& mul /*= Colorf(1,1,1,1)*/, const Colorf& add /*= Colorf(0,0,0,0)*/, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans) const { Matrix t; t.setTransformation(pos.x, pos.y, angle, xScale, yScale, 0, 0, xShear, yShear); t = mt * t; symbol->draw(t, mul, add, r_trans, g_trans, b_trans); } void SpriteRenderer::DrawImpl(const ISprite* sprite, const d2d::Matrix& mt, const Colorf& mul, const Colorf& add, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans) const { Matrix t; sprite->GetTransMatrix(t); t = mt * t; Colorf _mul = cMul(sprite->multiCol, mul), _add = cAdd(sprite->addCol, add); Colorf _r_trans, _g_trans, _b_trans; _r_trans.r = sprite->r_trans.r * r_trans.r + sprite->r_trans.g * g_trans.r + sprite->r_trans.b * b_trans.r; _r_trans.g = sprite->r_trans.r * r_trans.g + sprite->r_trans.g * g_trans.g + sprite->r_trans.b * b_trans.g; _r_trans.b = sprite->r_trans.r * r_trans.b + sprite->r_trans.g * g_trans.b + sprite->r_trans.b * b_trans.b; _g_trans.r = sprite->g_trans.r * r_trans.r + sprite->g_trans.g * g_trans.r + sprite->g_trans.b * b_trans.r; _g_trans.g = sprite->g_trans.r * r_trans.g + sprite->g_trans.g * g_trans.g + sprite->g_trans.b * b_trans.g; _g_trans.b = sprite->g_trans.r * r_trans.b + sprite->g_trans.g * g_trans.b + sprite->g_trans.b * b_trans.b; _b_trans.r = sprite->b_trans.r * r_trans.r + sprite->b_trans.g * g_trans.r + sprite->b_trans.b * b_trans.r; _b_trans.g = sprite->b_trans.r * r_trans.g + sprite->b_trans.g * g_trans.g + sprite->b_trans.b * b_trans.g; _b_trans.b = sprite->b_trans.r * r_trans.b + sprite->b_trans.g * g_trans.b + sprite->b_trans.b * b_trans.b; sprite->getSymbol().draw(t, _mul, _add, _r_trans, _g_trans, _b_trans, sprite); SpriteTools::DrawName(sprite, t); } void SpriteRenderer::DrawImplBlend(const ISprite* sprite) const { // DrawUnderToTmp(sprite); DrawSprToTmp(sprite); DrawTmpToScreen(sprite); } void SpriteRenderer::DrawUnderToTmp(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(m_fbo.GetFboID()); mgr->SetBlendMode(BM_NORMAL); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); // src Vector src[4]; Rect src_rect = sprite->GetRect(); int scr_w = scr_fbo.GetWidth(), scr_h = scr_fbo.GetHeight(); src[0] = m_cam->transPosProjectToScreen(Vector(src_rect.xMin, src_rect.yMin), scr_w, scr_h); src[1] = m_cam->transPosProjectToScreen(Vector(src_rect.xMax, src_rect.yMin), scr_w, scr_h); src[2] = m_cam->transPosProjectToScreen(Vector(src_rect.xMax, src_rect.yMax), scr_w, scr_h); src[3] = m_cam->transPosProjectToScreen(Vector(src_rect.xMin, src_rect.yMax), scr_w, scr_h); for (int i = 0; i < 4; ++i) { src[i].y = scr_h - 1 - src[i].y; src[i].x /= scr_w; src[i].y /= scr_h; src[i].x = std::min(std::max(0.0f, src[i].x), 1.0f); src[i].y = std::min(std::max(0.0f, src[i].y), 1.0f); } // dst Vector dst[4]; Rect dst_rect = sprite->getSymbol().getSize(); dst[0] = Vector(dst_rect.xMin, dst_rect.yMin); dst[1] = Vector(dst_rect.xMax, dst_rect.yMin); dst[2] = Vector(dst_rect.xMax, dst_rect.yMax); dst[3] = Vector(dst_rect.xMin, dst_rect.yMax); Vector offset; float scale; mgr->GetModelView(offset, scale); mgr->SetModelView(Vector(0, 0), 1); Rect r = sprite->getSymbol().getSize(); mgr->SetProjection(r.xLength(), r.yLength()); glViewport(0, 0, r.xLength(), r.yLength()); BlendShader* blend_shader = static_cast<BlendShader*>(mgr->GetSpriteShader()); blend_shader->SetBaseTexID(scr_fbo.GetTexID()); blend_shader->DrawBlend(dst, src, src, scr_fbo.GetTexID()); mgr->Commit(); mgr->SetModelView(offset, scale); mgr->SetProjection(scr_fbo.GetWidth(), scr_fbo.GetHeight()); glViewport(0, 0, scr_fbo.GetWidth(), scr_fbo.GetHeight()); } void SpriteRenderer::DrawSprToTmp(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(m_fbo.GetFboID()); mgr->SetBlendMode(sprite->GetBlendMode()); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); Vector offset; float scale; mgr->GetModelView(offset, scale); mgr->SetModelView(Vector(0, 0), 1); Rect r = sprite->getSymbol().getSize(); mgr->SetProjection(r.xLength(), r.yLength()); glViewport(0, 0, r.xLength(), r.yLength()); BlendShader* blend_shader = static_cast<BlendShader*>(mgr->GetSpriteShader()); blend_shader->SetBaseTexID(scr_fbo.GetTexID()); // blend_shader->SetBaseTexID(m_fbo.GetTexID()); sprite->getSymbol().draw(Matrix(), Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0), Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0), sprite); mgr->Commit(); mgr->SetModelView(offset, scale); mgr->SetProjection(scr_fbo.GetWidth(), scr_fbo.GetHeight()); glViewport(0, 0, scr_fbo.GetWidth(), scr_fbo.GetHeight()); } void SpriteRenderer::DrawTmpToScreen(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(0); mgr->SetFBO(scr_fbo.GetFboID()); mgr->SetBlendMode(BM_NORMAL); const d2d::Rect& r_dst = sprite->GetRect(); float xmin = r_dst.xMin, xmax = r_dst.xMax; float ymin = r_dst.yMin, ymax = r_dst.yMax; d2d::Rect r_src = sprite->getSymbol().getSize(); // float txmin = r_src.xMin / m_fbo.GetWidth() + 0.5f, // txmax = r_src.xMax / m_fbo.GetWidth() + 0.5f; // float tymin = r_src.yMin / m_fbo.GetHeight() + 0.5f, // tymax = r_src.yMax / m_fbo.GetHeight() + 0.5f; float txmin = 0, txmax = r_src.xLength() / m_fbo.GetWidth(); float tymin = 0, tymax = r_src.yLength() / m_fbo.GetHeight(); const float vertices[] = { xmin, ymin, txmin, tymin, txmin, tymin, xmin, ymax, txmin, tymax, txmin, tymax, xmax, ymax, txmax, tymax, txmax, tymax, xmax, ymin, txmax, tymin, txmax, tymin }; BlendShader* blend_shader = static_cast<BlendShader*>(mgr->GetSpriteShader()); blend_shader->DrawBlend(vertices, m_fbo.GetTexID()); mgr->Commit(); } SpriteRenderer* SpriteRenderer::Instance() { if (!m_instance) { m_instance = new SpriteRenderer(); } return m_instance; } } // d2d<commit_msg>[FIXED] 用普通sprite shader时blend不正确<commit_after>#include <gl/glew.h> #include "SpriteRenderer.h" #include "ShaderMgr.h" #include "ScreenFBO.h" #include "BlendShader.h" #include "dataset/ISprite.h" #include "dataset/ISymbol.h" #include "dataset/SpriteTools.h" #include "view/Camera.h" namespace d2d { SpriteRenderer* SpriteRenderer::m_instance = NULL; SpriteRenderer::SpriteRenderer() : m_fbo(600, 600) , m_cam(NULL) { } void SpriteRenderer::Draw(const ISprite* sprite, const d2d::Matrix& mt, const Colorf& mul, const Colorf& add, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans, bool multi_draw) const { if (!sprite->visiable) return; if (!multi_draw || sprite->GetBlendMode() == BM_NORMAL) { DrawImpl(sprite, mt, mul, add, r_trans, g_trans, b_trans); } else { DrawImplBlend(sprite); } } void SpriteRenderer::Draw(const ISymbol* symbol, const d2d::Matrix& mt, const Vector& pos, float angle/* = 0.0f*/, float xScale/* = 1.0f*/, float yScale/* = 1.0f*/, float xShear/* = 0.0f*/, float yShear/* = 0.0f*/, const Colorf& mul /*= Colorf(1,1,1,1)*/, const Colorf& add /*= Colorf(0,0,0,0)*/, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans) const { Matrix t; t.setTransformation(pos.x, pos.y, angle, xScale, yScale, 0, 0, xShear, yShear); t = mt * t; symbol->draw(t, mul, add, r_trans, g_trans, b_trans); } void SpriteRenderer::DrawImpl(const ISprite* sprite, const d2d::Matrix& mt, const Colorf& mul, const Colorf& add, const Colorf& r_trans, const Colorf& g_trans, const Colorf& b_trans) const { Matrix t; sprite->GetTransMatrix(t); t = mt * t; Colorf _mul = cMul(sprite->multiCol, mul), _add = cAdd(sprite->addCol, add); Colorf _r_trans, _g_trans, _b_trans; _r_trans.r = sprite->r_trans.r * r_trans.r + sprite->r_trans.g * g_trans.r + sprite->r_trans.b * b_trans.r; _r_trans.g = sprite->r_trans.r * r_trans.g + sprite->r_trans.g * g_trans.g + sprite->r_trans.b * b_trans.g; _r_trans.b = sprite->r_trans.r * r_trans.b + sprite->r_trans.g * g_trans.b + sprite->r_trans.b * b_trans.b; _g_trans.r = sprite->g_trans.r * r_trans.r + sprite->g_trans.g * g_trans.r + sprite->g_trans.b * b_trans.r; _g_trans.g = sprite->g_trans.r * r_trans.g + sprite->g_trans.g * g_trans.g + sprite->g_trans.b * b_trans.g; _g_trans.b = sprite->g_trans.r * r_trans.b + sprite->g_trans.g * g_trans.b + sprite->g_trans.b * b_trans.b; _b_trans.r = sprite->b_trans.r * r_trans.r + sprite->b_trans.g * g_trans.r + sprite->b_trans.b * b_trans.r; _b_trans.g = sprite->b_trans.r * r_trans.g + sprite->b_trans.g * g_trans.g + sprite->b_trans.b * b_trans.g; _b_trans.b = sprite->b_trans.r * r_trans.b + sprite->b_trans.g * g_trans.b + sprite->b_trans.b * b_trans.b; sprite->getSymbol().draw(t, _mul, _add, _r_trans, _g_trans, _b_trans, sprite); SpriteTools::DrawName(sprite, t); } void SpriteRenderer::DrawImplBlend(const ISprite* sprite) const { // DrawUnderToTmp(sprite); DrawSprToTmp(sprite); DrawTmpToScreen(sprite); } void SpriteRenderer::DrawUnderToTmp(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(m_fbo.GetFboID()); mgr->SetBlendMode(BM_NORMAL); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); // src Vector src[4]; Rect src_rect = sprite->GetRect(); int scr_w = scr_fbo.GetWidth(), scr_h = scr_fbo.GetHeight(); src[0] = m_cam->transPosProjectToScreen(Vector(src_rect.xMin, src_rect.yMin), scr_w, scr_h); src[1] = m_cam->transPosProjectToScreen(Vector(src_rect.xMax, src_rect.yMin), scr_w, scr_h); src[2] = m_cam->transPosProjectToScreen(Vector(src_rect.xMax, src_rect.yMax), scr_w, scr_h); src[3] = m_cam->transPosProjectToScreen(Vector(src_rect.xMin, src_rect.yMax), scr_w, scr_h); for (int i = 0; i < 4; ++i) { src[i].y = scr_h - 1 - src[i].y; src[i].x /= scr_w; src[i].y /= scr_h; src[i].x = std::min(std::max(0.0f, src[i].x), 1.0f); src[i].y = std::min(std::max(0.0f, src[i].y), 1.0f); } // dst Vector dst[4]; Rect dst_rect = sprite->getSymbol().getSize(); dst[0] = Vector(dst_rect.xMin, dst_rect.yMin); dst[1] = Vector(dst_rect.xMax, dst_rect.yMin); dst[2] = Vector(dst_rect.xMax, dst_rect.yMax); dst[3] = Vector(dst_rect.xMin, dst_rect.yMax); Vector offset; float scale; mgr->GetModelView(offset, scale); mgr->SetModelView(Vector(0, 0), 1); Rect r = sprite->getSymbol().getSize(); mgr->SetProjection(r.xLength(), r.yLength()); glViewport(0, 0, r.xLength(), r.yLength()); BlendShader* blend_shader = static_cast<BlendShader*>(mgr->GetSpriteShader()); blend_shader->SetBaseTexID(scr_fbo.GetTexID()); blend_shader->DrawBlend(dst, src, src, scr_fbo.GetTexID()); mgr->Commit(); mgr->SetModelView(offset, scale); mgr->SetProjection(scr_fbo.GetWidth(), scr_fbo.GetHeight()); glViewport(0, 0, scr_fbo.GetWidth(), scr_fbo.GetHeight()); } void SpriteRenderer::DrawSprToTmp(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(m_fbo.GetFboID()); mgr->SetBlendMode(sprite->GetBlendMode()); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); Vector offset; float scale; mgr->GetModelView(offset, scale); mgr->SetModelView(Vector(0, 0), 1); Rect r = sprite->getSymbol().getSize(); mgr->SetProjection(r.xLength(), r.yLength()); glViewport(0, 0, r.xLength(), r.yLength()); BlendShader* blend_shader = static_cast<BlendShader*>(mgr->GetSpriteShader()); blend_shader->SetBaseTexID(scr_fbo.GetTexID()); // blend_shader->SetBaseTexID(m_fbo.GetTexID()); sprite->getSymbol().draw(Matrix(), Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0), Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0), sprite); mgr->Commit(); mgr->SetModelView(offset, scale); mgr->SetProjection(scr_fbo.GetWidth(), scr_fbo.GetHeight()); glViewport(0, 0, scr_fbo.GetWidth(), scr_fbo.GetHeight()); } void SpriteRenderer::DrawTmpToScreen(const ISprite* sprite) const { ShaderMgr* mgr = ShaderMgr::Instance(); FBO& scr_fbo = ScreenFBO::Instance()->GetFBO(); mgr->sprite(); mgr->SetFBO(0); mgr->SetFBO(scr_fbo.GetFboID()); mgr->SetBlendMode(BM_NORMAL); const d2d::Rect& r_dst = sprite->GetRect(); float xmin = r_dst.xMin, xmax = r_dst.xMax; float ymin = r_dst.yMin, ymax = r_dst.yMax; d2d::Rect r_src = sprite->getSymbol().getSize(); // float txmin = r_src.xMin / m_fbo.GetWidth() + 0.5f, // txmax = r_src.xMax / m_fbo.GetWidth() + 0.5f; // float tymin = r_src.yMin / m_fbo.GetHeight() + 0.5f, // tymax = r_src.yMax / m_fbo.GetHeight() + 0.5f; float txmin = 0, txmax = r_src.xLength() / m_fbo.GetWidth(); float tymin = 0, tymax = r_src.yLength() / m_fbo.GetHeight(); if (BlendShader* blend_shader = dynamic_cast<BlendShader*>(mgr->GetSpriteShader())) { const float vertices[] = { xmin, ymin, txmin, tymin, txmin, tymin, xmin, ymax, txmin, tymax, txmin, tymax, xmax, ymax, txmax, tymax, txmax, tymax, xmax, ymin, txmax, tymin, txmax, tymin }; blend_shader->DrawBlend(vertices, m_fbo.GetTexID()); } else { const float vertices[] = { xmin, ymin, txmin, tymin, xmin, ymax, txmin, tymax, xmax, ymax, txmax, tymax, xmax, ymin, txmax, tymin}; mgr->Draw(vertices, m_fbo.GetTexID()); } mgr->Commit(); } SpriteRenderer* SpriteRenderer::Instance() { if (!m_instance) { m_instance = new SpriteRenderer(); } return m_instance; } } // d2d<|endoftext|>
<commit_before>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget("CellmlModelRepositoryWidget", this); mUi->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive, QRegExp::RegExp2))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach(const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mUi->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the window, the focus to the nameValue widget QWidget *focusedWidget = QApplication::focusWidget(); mUi->nameValue->setFocus(); if (focusedWidget && (QApplication::focusWidget()->parentWidget() != focusedWidget->parentWidget())) focusedWidget->setFocus(); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mUi->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor editing of a comment.<commit_after>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget("CellmlModelRepositoryWidget", this); mUi->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive, QRegExp::RegExp2))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach(const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mUi->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the window, the focus to the nameValue widget, but then set // the focus to whoever had it before, if needed QWidget *focusedWidget = QApplication::focusWidget(); mUi->nameValue->setFocus(); if (focusedWidget && (QApplication::focusWidget()->parentWidget() != focusedWidget->parentWidget())) focusedWidget->setFocus(); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mUi->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* * Copyright 2011-2013 Branimir Karadzic. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include <bgfx.h> #include <bx/bx.h> #include <bx/timer.h> #include <bx/uint32_t.h> #include "../common/entry.h" #include "../common/dbg.h" #include "../common/math.h" #include "../common/processevents.h" #include "../common/packrect.h" #include <stdio.h> #include <string.h> #include <list> struct PosColorVertex { float m_x; float m_y; float m_z; float m_u; float m_v; float m_w; }; static bgfx::VertexDecl s_PosTexcoordDecl; static PosColorVertex s_cubeVertices[24] = { {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 8, 10, 9, // 4 9, 10, 11, 12, 14, 13, // 6 14, 15, 13, 16, 18, 17, // 8 18, 19, 17, 20, 22, 21, // 10 21, 22, 23, }; static const char* s_shaderPath = NULL; static void shaderFilePath(char* _out, const char* _name) { strcpy(_out, s_shaderPath); strcat(_out, _name); strcat(_out, ".bin"); } long int fsize(FILE* _file) { long int pos = ftell(_file); fseek(_file, 0L, SEEK_END); long int size = ftell(_file); fseek(_file, pos, SEEK_SET); return size; } static const bgfx::Memory* load(const char* _filePath) { FILE* file = fopen(_filePath, "rb"); if (NULL != file) { uint32_t size = (uint32_t)fsize(file); const bgfx::Memory* mem = bgfx::alloc(size+1); size_t ignore = fread(mem->data, 1, size, file); BX_UNUSED(ignore); fclose(file); mem->data[mem->size-1] = '\0'; return mem; } return NULL; } static const bgfx::Memory* loadShader(const char* _name) { char filePath[512]; shaderFilePath(filePath, _name); return load(filePath); } int _main_(int _argc, char** _argv) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_NONE; bgfx::init(); bgfx::reset(width, height); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; break; } // Create vertex stream declaration. s_PosTexcoordDecl.begin(); s_PosTexcoordDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.add(bgfx::Attrib::TexCoord0, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.end(); const bgfx::Memory* mem; // Create static vertex buffer. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosTexcoordDecl); // Create static index buffer. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem); // Create texture sampler uniforms. bgfx::UniformHandle u_texCube = bgfx::createUniform("u_texCube", bgfx::UniformType::Uniform1iv); // Load vertex shader. mem = loadShader("vs_update"); bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem); // Load fragment shader. mem = loadShader("fs_update"); bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem); // Create program from shaders. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh); bgfx::destroyFragmentShader(fsh); uint32_t blockSide = 0; const uint32_t textureSide = 2048; bgfx::TextureHandle textureCube = bgfx::createTextureCube(6 , textureSide , 1 , bgfx::TextureFormat::BGRA8 , BGFX_TEXTURE_MIN_POINT|BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIP_POINT ); uint8_t rr = rand()%255; uint8_t gg = rand()%255; uint8_t bb = rand()%255; int64_t updateTime = 0; RectPackCubeT<256> cube(textureSide); uint32_t hit = 0; uint32_t miss = 0; std::list<PackCube> quads; while (!processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const int64_t freq = bx::getHPFrequency(); const double toMs = 1000.0/double(freq); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/08-update"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating textures."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); if (now > updateTime) { PackCube face; uint32_t bw = bx::uint16_max(1, rand()%(textureSide/4) ); uint32_t bh = bx::uint16_max(1, rand()%(textureSide/4) ); if (cube.find(bw, bh, face) ) { quads.push_back(face); ++hit; bgfx::TextureInfo ti; const Pack2D& rect = face.m_rect; bgfx::calcTextureSize(ti, rect.m_width, rect.m_height, 1, 1, bgfx::TextureFormat::BGRA8); // updateTime = now + freq/10; const bgfx::Memory* mem = bgfx::alloc(ti.storageSize); uint8_t* data = (uint8_t*)mem->data; for (uint32_t ii = 0, num = ti.storageSize*8/ti.bitsPerPixel; ii < num; ++ii) { data[0] = bb; data[1] = rr; data[2] = gg; data[3] = 0xff; data += 4; } bgfx::updateTextureCube(textureCube, face.m_side, 0, rect.m_x, rect.m_y, rect.m_width, rect.m_height, mem); rr = rand()%255; gg = rand()%255; bb = rand()%255; } else { ++miss; for (uint32_t ii = 0, num = bx::uint32_min(10, (uint32_t)quads.size() ); ii < num; ++ii) { const PackCube& face = quads.front(); cube.clear(face); quads.pop_front(); } } } bgfx::dbgTextPrintf(0, 4, 0x0f, "hit: %d, miss %d", hit, miss); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -5.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, 16.0f/9.0f, 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float time = (float)(bx::getHPCounter()/double(bx::getHPFrequency() ) ); float mtx[16]; mtxRotateXY(mtx, time, time*0.37f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind texture. bgfx::setTexture(0, u_texCube, textureCube); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(program); bgfx::destroyTexture(textureCube); bgfx::destroyUniform(u_texCube); // Shutdown bgfx. bgfx::shutdown(); return 0; } <commit_msg>Fixed GCC warning.<commit_after>/* * Copyright 2011-2013 Branimir Karadzic. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include <bgfx.h> #include <bx/bx.h> #include <bx/timer.h> #include <bx/uint32_t.h> #include "../common/entry.h" #include "../common/dbg.h" #include "../common/math.h" #include "../common/processevents.h" #include "../common/packrect.h" #include <stdio.h> #include <string.h> #include <list> struct PosColorVertex { float m_x; float m_y; float m_z; float m_u; float m_v; float m_w; }; static bgfx::VertexDecl s_PosTexcoordDecl; static PosColorVertex s_cubeVertices[24] = { {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, {-1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }, {-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }, { 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f }, {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f }, {-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 8, 10, 9, // 4 9, 10, 11, 12, 14, 13, // 6 14, 15, 13, 16, 18, 17, // 8 18, 19, 17, 20, 22, 21, // 10 21, 22, 23, }; static const char* s_shaderPath = NULL; static void shaderFilePath(char* _out, const char* _name) { strcpy(_out, s_shaderPath); strcat(_out, _name); strcat(_out, ".bin"); } long int fsize(FILE* _file) { long int pos = ftell(_file); fseek(_file, 0L, SEEK_END); long int size = ftell(_file); fseek(_file, pos, SEEK_SET); return size; } static const bgfx::Memory* load(const char* _filePath) { FILE* file = fopen(_filePath, "rb"); if (NULL != file) { uint32_t size = (uint32_t)fsize(file); const bgfx::Memory* mem = bgfx::alloc(size+1); size_t ignore = fread(mem->data, 1, size, file); BX_UNUSED(ignore); fclose(file); mem->data[mem->size-1] = '\0'; return mem; } return NULL; } static const bgfx::Memory* loadShader(const char* _name) { char filePath[512]; shaderFilePath(filePath, _name); return load(filePath); } int _main_(int _argc, char** _argv) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_NONE; bgfx::init(); bgfx::reset(width, height); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; break; } // Create vertex stream declaration. s_PosTexcoordDecl.begin(); s_PosTexcoordDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.add(bgfx::Attrib::TexCoord0, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.end(); const bgfx::Memory* mem; // Create static vertex buffer. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosTexcoordDecl); // Create static index buffer. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem); // Create texture sampler uniforms. bgfx::UniformHandle u_texCube = bgfx::createUniform("u_texCube", bgfx::UniformType::Uniform1iv); // Load vertex shader. mem = loadShader("vs_update"); bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem); // Load fragment shader. mem = loadShader("fs_update"); bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem); // Create program from shaders. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh); bgfx::destroyFragmentShader(fsh); const uint32_t textureSide = 2048; bgfx::TextureHandle textureCube = bgfx::createTextureCube(6 , textureSide , 1 , bgfx::TextureFormat::BGRA8 , BGFX_TEXTURE_MIN_POINT|BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIP_POINT ); uint8_t rr = rand()%255; uint8_t gg = rand()%255; uint8_t bb = rand()%255; int64_t updateTime = 0; RectPackCubeT<256> cube(textureSide); uint32_t hit = 0; uint32_t miss = 0; std::list<PackCube> quads; while (!processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const int64_t freq = bx::getHPFrequency(); const double toMs = 1000.0/double(freq); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/08-update"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating textures."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); if (now > updateTime) { PackCube face; uint32_t bw = bx::uint16_max(1, rand()%(textureSide/4) ); uint32_t bh = bx::uint16_max(1, rand()%(textureSide/4) ); if (cube.find(bw, bh, face) ) { quads.push_back(face); ++hit; bgfx::TextureInfo ti; const Pack2D& rect = face.m_rect; bgfx::calcTextureSize(ti, rect.m_width, rect.m_height, 1, 1, bgfx::TextureFormat::BGRA8); // updateTime = now + freq/10; const bgfx::Memory* mem = bgfx::alloc(ti.storageSize); uint8_t* data = (uint8_t*)mem->data; for (uint32_t ii = 0, num = ti.storageSize*8/ti.bitsPerPixel; ii < num; ++ii) { data[0] = bb; data[1] = rr; data[2] = gg; data[3] = 0xff; data += 4; } bgfx::updateTextureCube(textureCube, face.m_side, 0, rect.m_x, rect.m_y, rect.m_width, rect.m_height, mem); rr = rand()%255; gg = rand()%255; bb = rand()%255; } else { ++miss; for (uint32_t ii = 0, num = bx::uint32_min(10, (uint32_t)quads.size() ); ii < num; ++ii) { const PackCube& face = quads.front(); cube.clear(face); quads.pop_front(); } } } bgfx::dbgTextPrintf(0, 4, 0x0f, "hit: %d, miss %d", hit, miss); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -5.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, 16.0f/9.0f, 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float time = (float)(bx::getHPCounter()/double(bx::getHPFrequency() ) ); float mtx[16]; mtxRotateXY(mtx, time, time*0.37f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind texture. bgfx::setTexture(0, u_texCube, textureCube); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(program); bgfx::destroyTexture(textureCube); bgfx::destroyUniform(u_texCube); // Shutdown bgfx. bgfx::shutdown(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> Copyright (c) 2007 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "itemsync.h" #include <libakonadi/item.h> #include <libakonadi/itemappendjob.h> #include <libakonadi/itemdeletejob.h> #include <libakonadi/itemfetchjob.h> #include <libakonadi/itemstorejob.h> #include <kdebug.h> using namespace Akonadi; class ItemSync::Private { public: Private() : pendingJobs( 0 ), progress( 0 ), incremental( false ) { } Collection syncCollection; QHash<int, Akonadi::Item> localItemsById; QHash<QString, Akonadi::Item> localItemsByRemoteId; QSet<Akonadi::Item> unprocessedLocalItems; // remote items Akonadi::Item::List remoteItems; // removed remote items Item::List removedRemoteItems; // create counter int pendingJobs; int progress; bool incremental; }; ItemSync::ItemSync( const Collection &collection, QObject *parent ) : TransactionSequence( parent ), d( new Private ) { d->syncCollection = collection; } ItemSync::~ItemSync() { delete d; } void ItemSync::setRemoteItems( const Item::List & remoteItems ) { d->remoteItems = remoteItems; setTotalAmount( KJob::Bytes, d->remoteItems.count() ); } void ItemSync::setRemoteItems( const Item::List & changedItems, const Item::List & removedItems ) { d->incremental = true; d->remoteItems = changedItems; d->removedRemoteItems = removedItems; setTotalAmount( KJob::Bytes, d->remoteItems.count() + d->removedRemoteItems.count() ); } void ItemSync::doStart() { ItemFetchJob* job = new ItemFetchJob( d->syncCollection, this ); // FIXME this will deadlock, we only can fetch parts already in the cache // if ( !d->incremental ) // job->fetchAllParts(); connect( job, SIGNAL( result( KJob* ) ), SLOT( slotLocalListDone( KJob* ) ) ); } void ItemSync::slotLocalListDone( KJob * job ) { if ( job->error() ) return; const Item::List list = static_cast<ItemFetchJob*>( job )->items(); foreach ( const Item item, list ) { d->localItemsById.insert( item.reference().id(), item ); d->localItemsByRemoteId.insert( item.reference().remoteId(), item ); d->unprocessedLocalItems.insert( item ); } // added / updated foreach ( const Item remoteItem, d->remoteItems ) { #ifndef NDEBUG if ( remoteItem.reference().remoteId().isEmpty() ) { kWarning( 5250 ) << "Item " << remoteItem.reference().id() << " does not have a remote identifier"; } #endif Item localItem = d->localItemsById.value( remoteItem.reference().id() ); if ( !localItem.isValid() ) localItem = d->localItemsByRemoteId.value( remoteItem.reference().remoteId() ); d->unprocessedLocalItems.remove( localItem ); // missing locally if ( !localItem.isValid() ) { createLocalItem( remoteItem ); continue; } bool needsUpdate = false; if ( d->incremental ) { /** * We know that this item has changed (as it is part of the * incremental changed list), so we just put it into the * storage. */ needsUpdate = true; } else { if ( localItem.flags() != remoteItem.flags() ) { // Check whether the flags differ kDebug( 5250 ) << "Local flags " << localItem.flags() << "remote flags " << remoteItem.flags(); needsUpdate = true; } else { /* * Check whether the new item contains unknown parts */ const QStringList localParts = localItem.availableParts(); QStringList missingParts = localParts; foreach( const QString remotePart, remoteItem.availableParts() ) missingParts.removeAll( remotePart ); if ( !missingParts.isEmpty() ) needsUpdate = true; else { /** * If the available part identifiers don't differ, check * whether the content of the parts differs. */ foreach ( const QString partId, localParts ) { if ( localItem.part( partId ) != remoteItem.part( partId ) ) { needsUpdate = true; break; } } } } } if ( needsUpdate ) { d->pendingJobs++; Item i( remoteItem ); i.setReference( DataReference( localItem.reference().id(), remoteItem.reference().remoteId() ) ); i.setRev( localItem.rev() ); ItemStoreJob *mod = new ItemStoreJob( (const Item)i, this ); mod->storePayload(); mod->setCollection( d->syncCollection ); connect( mod, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } else { d->progress++; } } // removed if ( !d->incremental ) d->removedRemoteItems = d->unprocessedLocalItems.toList(); foreach ( const Item item, d->removedRemoteItems ) { d->pendingJobs++; ItemDeleteJob *job = new ItemDeleteJob( item.reference(), this ); connect( job, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } d->localItemsById.clear(); d->localItemsByRemoteId.clear(); checkDone(); } void ItemSync::createLocalItem( const Item & item ) { d->pendingJobs++; ItemAppendJob *create = new ItemAppendJob( item, d->syncCollection, this ); connect( create, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } void ItemSync::checkDone() { setProcessedAmount( KJob::Bytes, d->progress ); if ( d->pendingJobs > 0 ) return; commit(); } void ItemSync::slotLocalChangeDone( KJob * job ) { if ( job->error() ) return; d->pendingJobs--; d->progress++; checkDone(); } #include "itemsync.moc" <commit_msg>Make the flags work.<commit_after>/* Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> Copyright (c) 2007 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "itemsync.h" #include <libakonadi/item.h> #include <libakonadi/itemappendjob.h> #include <libakonadi/itemdeletejob.h> #include <libakonadi/itemfetchjob.h> #include <libakonadi/itemstorejob.h> #include <kdebug.h> using namespace Akonadi; class ItemSync::Private { public: Private() : pendingJobs( 0 ), progress( 0 ), incremental( false ) { } Collection syncCollection; QHash<int, Akonadi::Item> localItemsById; QHash<QString, Akonadi::Item> localItemsByRemoteId; QSet<Akonadi::Item> unprocessedLocalItems; // remote items Akonadi::Item::List remoteItems; // removed remote items Item::List removedRemoteItems; // create counter int pendingJobs; int progress; bool incremental; }; ItemSync::ItemSync( const Collection &collection, QObject *parent ) : TransactionSequence( parent ), d( new Private ) { d->syncCollection = collection; } ItemSync::~ItemSync() { delete d; } void ItemSync::setRemoteItems( const Item::List & remoteItems ) { d->remoteItems = remoteItems; setTotalAmount( KJob::Bytes, d->remoteItems.count() ); } void ItemSync::setRemoteItems( const Item::List & changedItems, const Item::List & removedItems ) { d->incremental = true; d->remoteItems = changedItems; d->removedRemoteItems = removedItems; setTotalAmount( KJob::Bytes, d->remoteItems.count() + d->removedRemoteItems.count() ); } void ItemSync::doStart() { ItemFetchJob* job = new ItemFetchJob( d->syncCollection, this ); // FIXME this will deadlock, we only can fetch parts already in the cache // if ( !d->incremental ) // job->fetchAllParts(); connect( job, SIGNAL( result( KJob* ) ), SLOT( slotLocalListDone( KJob* ) ) ); } void ItemSync::slotLocalListDone( KJob * job ) { if ( job->error() ) return; const Item::List list = static_cast<ItemFetchJob*>( job )->items(); foreach ( const Item item, list ) { d->localItemsById.insert( item.reference().id(), item ); d->localItemsByRemoteId.insert( item.reference().remoteId(), item ); d->unprocessedLocalItems.insert( item ); } // added / updated foreach ( const Item remoteItem, d->remoteItems ) { #ifndef NDEBUG if ( remoteItem.reference().remoteId().isEmpty() ) { kWarning( 5250 ) << "Item " << remoteItem.reference().id() << " does not have a remote identifier"; } #endif Item localItem = d->localItemsById.value( remoteItem.reference().id() ); if ( !localItem.isValid() ) localItem = d->localItemsByRemoteId.value( remoteItem.reference().remoteId() ); d->unprocessedLocalItems.remove( localItem ); // missing locally if ( !localItem.isValid() ) { createLocalItem( remoteItem ); continue; } bool needsUpdate = false; if ( d->incremental ) { /** * We know that this item has changed (as it is part of the * incremental changed list), so we just put it into the * storage. */ needsUpdate = true; } else { if ( localItem.flags() != remoteItem.flags() ) { // Check whether the flags differ kDebug( 5250 ) << "Local flags " << localItem.flags() << "remote flags " << remoteItem.flags(); needsUpdate = true; } else { /* * Check whether the new item contains unknown parts */ const QStringList localParts = localItem.availableParts(); QStringList missingParts = localParts; foreach( const QString remotePart, remoteItem.availableParts() ) missingParts.removeAll( remotePart ); if ( !missingParts.isEmpty() ) needsUpdate = true; else { /** * If the available part identifiers don't differ, check * whether the content of the parts differs. */ foreach ( const QString partId, localParts ) { if ( localItem.part( partId ) != remoteItem.part( partId ) ) { needsUpdate = true; break; } } } } } if ( needsUpdate ) { d->pendingJobs++; Item i( remoteItem ); i.setReference( DataReference( localItem.reference().id(), remoteItem.reference().remoteId() ) ); i.setRev( localItem.rev() ); ItemStoreJob *mod = new ItemStoreJob( (const Item)i, this ); mod->storePayload(); mod->setFlags( i.flags() ); mod->setCollection( d->syncCollection ); connect( mod, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } else { d->progress++; } } // removed if ( !d->incremental ) d->removedRemoteItems = d->unprocessedLocalItems.toList(); foreach ( const Item item, d->removedRemoteItems ) { d->pendingJobs++; ItemDeleteJob *job = new ItemDeleteJob( item.reference(), this ); connect( job, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } d->localItemsById.clear(); d->localItemsByRemoteId.clear(); checkDone(); } void ItemSync::createLocalItem( const Item & item ) { d->pendingJobs++; ItemAppendJob *create = new ItemAppendJob( item, d->syncCollection, this ); connect( create, SIGNAL( result( KJob* ) ), SLOT( slotLocalChangeDone( KJob* ) ) ); } void ItemSync::checkDone() { setProcessedAmount( KJob::Bytes, d->progress ); if ( d->pendingJobs > 0 ) return; commit(); } void ItemSync::slotLocalChangeDone( KJob * job ) { if ( job->error() ) return; d->pendingJobs--; d->progress++; checkDone(); } #include "itemsync.moc" <|endoftext|>
<commit_before>/* This file is part of Akregator. Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "feed.h" #include "addfeeddialog.h" #include <qcheckbox.h> #include <kapplication.h> #include <kurl.h> #include <klocale.h> #include <klineedit.h> #include <kiconloader.h> #include <kicontheme.h> #include <kdebug.h> #include <ksqueezedtextlabel.h> #include <kmessagebox.h> using namespace Akregator; AddFeedWidget::AddFeedWidget(QWidget *parent, const char *name) : AddFeedWidgetBase(parent, name) { pixmapLabel1->setPixmap(kapp->iconLoader()->loadIcon( "package_network",KIcon::Desktop,KIcon::SizeHuge, KIcon::DefaultState, 0, true)); statusLabel->setText(QString::null); } AddFeedWidget::~AddFeedWidget() {} AddFeedDialog::AddFeedDialog(QWidget *parent, const char *name) : KDialogBase(KDialogBase::Swallow, Qt::WStyle_DialogBorder, parent, name, true, i18n("Add Feed"), KDialogBase::Ok|KDialogBase::Cancel) { widget = new AddFeedWidget(this); connect(widget->urlEdit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); enableButtonOK(false); setMainWidget(widget); } AddFeedDialog::~AddFeedDialog() {} void AddFeedDialog::setURL(const QString& t) { widget->urlEdit->setText(t); } void AddFeedDialog::slotOk( ) { enableButtonOK(false); feedURL = widget->urlEdit->text().stripWhiteSpace(); Feed *f=new Feed(); feed=f; if (feedURL.find(":/") == -1) feedURL.prepend("http://"); f->setXmlUrl(feedURL); widget->statusLabel->setText( i18n("Downloading %1").arg(feedURL) ); connect( feed, SIGNAL(fetched(Feed* )), this, SLOT(fetchCompleted(Feed *)) ); connect( feed, SIGNAL(fetchError(Feed* )), this, SLOT(fetchError(Feed *)) ); connect( feed, SIGNAL(fetchDiscovery(Feed* )), this, SLOT(fetchDiscovery(Feed *)) ); f->fetch(true); } void AddFeedDialog::fetchCompleted(Feed */*f*/) { KDialogBase::slotOk(); } void AddFeedDialog::fetchError(Feed *) { KMessageBox::error(this, i18n("Feed not found from %1.").arg(feedURL)); KDialogBase::slotCancel(); } void AddFeedDialog::fetchDiscovery(Feed *f) { widget->statusLabel->setText( i18n("Feed found, downloading...") ); feedURL=f->xmlUrl(); } void AddFeedDialog::textChanged(const QString& text) { if(text.isEmpty()) enableButtonOK(false); else enableButtonOK(true); } #include "addfeeddialog.moc" // vim: ts=4 sw=4 et <commit_msg>make it better way as Binner suggested<commit_after>/* This file is part of Akregator. Copyright (C) 2004 Stanislav Karchebny <Stanislav.Karchebny@kdemail.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "feed.h" #include "addfeeddialog.h" #include <qcheckbox.h> #include <kapplication.h> #include <kurl.h> #include <klocale.h> #include <klineedit.h> #include <kiconloader.h> #include <kicontheme.h> #include <kdebug.h> #include <ksqueezedtextlabel.h> #include <kmessagebox.h> using namespace Akregator; AddFeedWidget::AddFeedWidget(QWidget *parent, const char *name) : AddFeedWidgetBase(parent, name) { pixmapLabel1->setPixmap(kapp->iconLoader()->loadIcon( "package_network",KIcon::Desktop,KIcon::SizeHuge, KIcon::DefaultState, 0, true)); statusLabel->setText(QString::null); } AddFeedWidget::~AddFeedWidget() {} AddFeedDialog::AddFeedDialog(QWidget *parent, const char *name) : KDialogBase(KDialogBase::Swallow, Qt::WStyle_DialogBorder, parent, name, true, i18n("Add Feed"), KDialogBase::Ok|KDialogBase::Cancel) { widget = new AddFeedWidget(this); connect(widget->urlEdit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); enableButtonOK(false); setMainWidget(widget); } AddFeedDialog::~AddFeedDialog() {} void AddFeedDialog::setURL(const QString& t) { widget->urlEdit->setText(t); } void AddFeedDialog::slotOk( ) { enableButtonOK(false); feedURL = widget->urlEdit->text().stripWhiteSpace(); Feed *f=new Feed(); feed=f; if (feedURL.find(":/") == -1) feedURL.prepend("http://"); f->setXmlUrl(feedURL); widget->statusLabel->setText( i18n("Downloading %1").arg(feedURL) ); connect( feed, SIGNAL(fetched(Feed* )), this, SLOT(fetchCompleted(Feed *)) ); connect( feed, SIGNAL(fetchError(Feed* )), this, SLOT(fetchError(Feed *)) ); connect( feed, SIGNAL(fetchDiscovery(Feed* )), this, SLOT(fetchDiscovery(Feed *)) ); f->fetch(true); } void AddFeedDialog::fetchCompleted(Feed */*f*/) { KDialogBase::slotOk(); } void AddFeedDialog::fetchError(Feed *) { KMessageBox::error(this, i18n("Feed not found from %1.").arg(feedURL)); KDialogBase::slotCancel(); } void AddFeedDialog::fetchDiscovery(Feed *f) { widget->statusLabel->setText( i18n("Feed found, downloading...") ); feedURL=f->xmlUrl(); } void AddFeedDialog::textChanged(const QString& text) { enableButtonOK(!text.isEmpty()); } #include "addfeeddialog.moc" // vim: ts=4 sw=4 et <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * 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 "test.hpp" #include <array> #include <iostream> #include <iterator> #include <limits> #include <memory> #include <miopen/activ.hpp> #include <miopen/miopen.h> #include <miopen/stringutils.hpp> #include <miopen/tensor.hpp> #include <utility> #include "driver.hpp" #include "get_handle.hpp" #include "tensor_holder.hpp" #include "verify.hpp" std::string to_name(miopenActivationMode_t m) { #define STRING_CASE(x) \ case x: return #x; break; switch(m) { STRING_CASE(miopenActivationPATHTRU) STRING_CASE(miopenActivationLOGISTIC) STRING_CASE(miopenActivationTANH) STRING_CASE(miopenActivationRELU) STRING_CASE(miopenActivationSOFTRELU) STRING_CASE(miopenActivationABS) STRING_CASE(miopenActivationPOWER) } return ""; } template <class T> struct verify_forward_activation { tensor<T> input; miopen::ActivationDescriptor desc; template <class A> tensor<T> cpu(A a) { auto out = input; input.par_for_each( [&](int o, int w, int i, int j) { out(o, w, i, j) = a(input(o, w, i, j)); }); return out; } template <class A> tensor<T> gpu(A) { auto&& handle = get_handle(); auto out = input; auto in_dev = handle.Write(input.data); auto out_dev = handle.Write(out.data); float alpha = 1, beta = 0; desc.Forward(handle, &alpha, input.desc, in_dev.get(), &beta, out.desc, out_dev.get()); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } template <class A> void fail(float, A) { std::cout << "Forward Activation: " << to_name(desc.GetMode()) << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; } }; template <class T> struct verify_backwards_activation { tensor<T> input; tensor<T> dout; tensor<T> out; miopen::ActivationDescriptor desc; template <class A> tensor<T> cpu(A a) { auto dinput = input; input.par_for_each([&](int o, int w, int i, int j) { dinput(o, w, i, j) = a(dout(o, w, i, j), input(o, w, i, j), out(o, w, i, j)); }); return dinput; } template <class A> tensor<T> gpu(A) { auto&& handle = get_handle(); auto dinput = input; auto in_dev = handle.Write(input.data); auto dout_dev = handle.Write(dout.data); auto out_dev = handle.Write(out.data); auto din_dev = handle.Write(dinput.data); float alpha = 1, beta = 0; desc.Forward(handle, &alpha, input.desc, in_dev.get(), &beta, out.desc, out_dev.get()); desc.Backward(handle, &alpha, // y out.desc, out_dev.get(), // dy dout.desc, dout_dev.get(), // x input.desc, in_dev.get(), &beta, // dx dinput.desc, din_dev.get()); dinput.data = handle.Read<T>(din_dev, dinput.data.size()); return dinput; } template <class A> void fail(float, A) { std::cout << "Backwards Activation: " << to_name(desc.GetMode()) << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; } }; struct select_first { template <class T> auto operator()(const T& x) MIOPEN_RETURNS(x.first); }; template <class T> struct activation_driver : test_driver { tensor<T> input; double alpha = 1; double beta = 0; double power = 1; std::string mode = "PATHTRU"; std::unordered_map<std::string, std::function<void()>> lookup; template <class A> struct callback { void operator()(activation_driver* self) const { self->template run<A>(); } }; template <class Forward, class Backward> void add_mode(miopenActivationMode_t m, Forward f, Backward b) { lookup.emplace(transform_mode(to_name(m)), [=] { this->run(m, f, b); }); } activation_driver() { add_mode(miopenActivationPATHTRU, [=](T x) { return x; }, [=](T, T x, T) { return x; }); add_mode(miopenActivationLOGISTIC, [=](T x) { return 1 / (1 + std::exp(-x)); }, [=](T dy, T, T y) { return dy * y * (1 - y); }); add_mode(miopenActivationTANH, [=](T x) { return alpha * std::tanh(beta * x); }, [=](T dy, T, T y) { return dy * (1 - y * y); }); add_mode(miopenActivationRELU, [=](T x) { return (x > 0) ? x : x * beta; }, [=](T dy, T, T) { return std::max<T>(0, dy); }); add_mode(miopenActivationSOFTRELU, [=](T x) { return std::log(1 + std::exp(x)); }, [=](T dy, T x, T) { static const float threshold = 50.; T expval = std::exp(std::min(x, static_cast<T>(threshold))); return dy * expval / (expval + 1.0); }); add_mode(miopenActivationABS, [=](T x) { return std::abs(x); }, [=](T dy, T x, T) { return dy * ((x >= 0) ? 1 : -1); }); add_mode(miopenActivationPOWER, [=](T x) { return std::pow(alpha + beta * x, power); }, [=](T, T x, T y) { auto divisor = alpha + beta * x; return (miopen::float_equal(divisor, 0)) ? 0 : alpha * beta * y / divisor; }); add(input, "input", get_input_tensor()); add(alpha, "alpha"); add(beta, "beta"); add(power, "power"); add(mode, "mode", generate_data(modes())); } std::vector<std::string> modes() { std::vector<std::string> result(lookup.size()); std::transform(lookup.begin(), lookup.end(), result.begin(), select_first{}); return result; } miopen::ActivationDescriptor make_descriptor(miopenActivationMode_t m) const { return {m, alpha, beta, power}; } static std::string transform_mode(std::string s) { return miopen::RemovePrefix(miopen::ToUpper(s), "MIOPENACTIVATION"); } void run() { lookup[transform_mode(mode)](); } template <class Forward, class Backward> void run(miopenActivationMode_t m, Forward f, Backward b) { auto desc = make_descriptor(m); auto out = verify(verify_forward_activation<T>{input, desc}, f); auto dout = out.first; dout.generate([&](int n, int c, int h, int w) { T x = out.first(n, c, h, w); double y = (877 * n + 547 * c + 701 * h + 1049 * w + static_cast<int>(769 * x)) % 2503; return ((x * y) / 1301.0); }); verify(verify_backwards_activation<T>{input, dout, out.first, desc}, b); } }; int main(int argc, const char* argv[]) { test_drive<activation_driver<float>>(argc, argv); } <commit_msg>fixed activation tests<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * 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 "test.hpp" #include <array> #include <iostream> #include <iterator> #include <limits> #include <memory> #include <miopen/activ.hpp> #include <miopen/miopen.h> #include <miopen/stringutils.hpp> #include <miopen/tensor.hpp> #include <utility> #include "driver.hpp" #include "get_handle.hpp" #include "tensor_holder.hpp" #include "verify.hpp" std::string to_name(miopenActivationMode_t m) { #define STRING_CASE(x) \ case x: return #x; break; switch(m) { STRING_CASE(miopenActivationPATHTRU) STRING_CASE(miopenActivationLOGISTIC) STRING_CASE(miopenActivationTANH) STRING_CASE(miopenActivationRELU) STRING_CASE(miopenActivationSOFTRELU) STRING_CASE(miopenActivationABS) STRING_CASE(miopenActivationPOWER) } return ""; } template <class T> struct verify_forward_activation { tensor<T> input; miopen::ActivationDescriptor desc; template <class A> tensor<T> cpu(A a) { auto out = input; input.par_for_each( [&](int o, int w, int i, int j) { out(o, w, i, j) = a(input(o, w, i, j)); }); return out; } template <class A> tensor<T> gpu(A) { auto&& handle = get_handle(); auto out = input; auto in_dev = handle.Write(input.data); auto out_dev = handle.Write(out.data); float alpha = 1, beta = 0; desc.Forward(handle, &alpha, input.desc, in_dev.get(), &beta, out.desc, out_dev.get()); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } template <class A> void fail(float, A) { std::cout << "Forward Activation: " << to_name(desc.GetMode()) << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; } }; template <class T> struct verify_backwards_activation { tensor<T> input; tensor<T> dout; tensor<T> out; miopen::ActivationDescriptor desc; template <class A> tensor<T> cpu(A a) { auto dinput = input; input.par_for_each([&](int o, int w, int i, int j) { dinput(o, w, i, j) = a(dout(o, w, i, j), input(o, w, i, j), out(o, w, i, j)); }); return dinput; } template <class A> tensor<T> gpu(A) { auto&& handle = get_handle(); auto dinput = input; auto in_dev = handle.Write(input.data); auto dout_dev = handle.Write(dout.data); auto out_dev = handle.Write(out.data); auto din_dev = handle.Write(dinput.data); float alpha = 1, beta = 0; desc.Forward(handle, &alpha, input.desc, in_dev.get(), &beta, out.desc, out_dev.get()); desc.Backward(handle, &alpha, // y out.desc, out_dev.get(), // dy dout.desc, dout_dev.get(), // x input.desc, in_dev.get(), &beta, // dx dinput.desc, din_dev.get()); dinput.data = handle.Read<T>(din_dev, dinput.data.size()); return dinput; } template <class A> void fail(float, A) { std::cout << "Backwards Activation: " << to_name(desc.GetMode()) << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; } }; struct select_first { template <class T> auto operator()(const T& x) MIOPEN_RETURNS(x.first); }; template <class T> struct activation_driver : test_driver { tensor<T> input; double alpha = 1; double beta = 1; double power = 1; std::string mode = "PATHTRU"; std::unordered_map<std::string, std::function<void()>> lookup; template <class A> struct callback { void operator()(activation_driver* self) const { self->template run<A>(); } }; template <class Forward, class Backward> void add_mode(miopenActivationMode_t m, Forward f, Backward b) { lookup.emplace(transform_mode(to_name(m)), [=] { this->run(m, f, b); }); } activation_driver() { add_mode(miopenActivationPATHTRU, [=](T x) { return x; }, [=](T, T x, T) { return x; }); add_mode(miopenActivationLOGISTIC, [=](T x) { return 1 / (1 + std::exp(-x)); }, [=](T dy, T, T y) { return dy * y * (1 - y); }); add_mode(miopenActivationTANH, [=](T x) { return alpha * std::tanh(beta * x); }, [=](T dy, T, T y) { return dy * (1 - y * y); }); add_mode(miopenActivationRELU, [=](T x) { return (x > 0) ? x : x * beta; }, [=](T dy, T, T) { return std::max<T>(0, dy); }); add_mode(miopenActivationSOFTRELU, [=](T x) { return std::log(1 + std::exp(x)); }, [=](T dy, T x, T) { static const float threshold = 50.; T expval = std::exp(std::min(x, static_cast<T>(threshold))); return dy * expval / (expval + 1.0); }); add_mode(miopenActivationABS, [=](T x) { return std::abs(x); }, [=](T dy, T x, T) { return dy * ((x >= 0) ? 1 : -1); }); add_mode(miopenActivationPOWER, [=](T x) { return std::pow(alpha + beta * x, power); }, [=](T, T x, T y) { auto divisor = alpha + beta * x; return (miopen::float_equal(divisor, 0)) ? 0 : alpha * beta * y / divisor; }); add(input, "input", get_input_tensor()); add(alpha, "alpha"); add(beta, "beta"); add(power, "power"); add(mode, "mode", generate_data(modes())); } std::vector<std::string> modes() { std::vector<std::string> result(lookup.size()); std::transform(lookup.begin(), lookup.end(), result.begin(), select_first{}); return result; } miopen::ActivationDescriptor make_descriptor(miopenActivationMode_t m) const { return {m, alpha, beta, power}; } static std::string transform_mode(std::string s) { return miopen::RemovePrefix(miopen::ToUpper(s), "MIOPENACTIVATION"); } void run() { lookup[transform_mode(mode)](); } template <class Forward, class Backward> void run(miopenActivationMode_t m, Forward f, Backward b) { auto desc = make_descriptor(m); auto out = verify(verify_forward_activation<T>{input, desc}, f); auto dout = out.first; dout.generate([&](int n, int c, int h, int w) { T x = out.first(n, c, h, w); double y = (877 * n + 547 * c + 701 * h + 1049 * w + static_cast<int>(769 * x)) % 2503; return ((x * y) / 1301.0); }); verify(verify_backwards_activation<T>{input, dout, out.first, desc}, b); } }; int main(int argc, const char* argv[]) { test_drive<activation_driver<float>>(argc, argv); } <|endoftext|>
<commit_before>#include <string.h> #include <iostream.h> #include <stdlib.h> #include <string> using namespace std; int main() { string SizeE; int SizeA, SizeB, SizeD, SizeC; cout << "The Breast Measurer v2.0" << endl << "by endura29@hotmail.com" << endl; cout << "Enter the Measurement (in inches) just below the breast: "; cin >> SizeA; cout << "Enter the Measurement (in inches) at the Nipple: "; cin >> SizeB; //SizeD = (SizeA + 5); //SizeC = (SizeB - SizeD); SizeC = SizeB - SizeA; //if (SizeD % 2) // SizeD++; if (SizeC < 0) { cout << "\n" << "Now, that's less than a mouthful!!" << endl; return 0; } switch (SizeC) { case 0: SizeE = "AA"; break; case 1: SizeE = "A"; break; case 2: SizeE = "B"; break; case 3: SizeE = "C"; break; case 4: SizeE = "D"; break; case 5: SizeE = "DD"; break; case 6: SizeE = "F"; break; case 7: SizeE = "G"; break; case 8: SizeE = "H"; break; case 9: SizeE = "I"; break; default: cout << "Damn, that's a lotta boobs!" << endl; return 0; } cout << "Bra Size: " << SizeA << SizeE.c_str() << endl; return 0; } <commit_msg>Removed<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "fltlst.hxx" #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/uno/Any.hxx> #include <comphelper/processfactory.hxx> #include <sfx2/sfxuno.hxx> #include <sfx2/docfac.hxx> #include <vcl/svapp.hxx> #include <osl/mutex.hxx> //***************************************************************************************************************** // namespaces //***************************************************************************************************************** using namespace ::com::sun::star; class SfxRefreshListener : public ::cppu::WeakImplHelper1<com::sun::star::util::XRefreshListener> { private: SfxFilterListener *m_pOwner; public: SfxRefreshListener(SfxFilterListener *pOwner) : m_pOwner(pOwner) { } virtual ~SfxRefreshListener() { } // util.XRefreshListener virtual void SAL_CALL refreshed( const ::com::sun::star::lang::EventObject& rEvent ) throw(com::sun::star::uno::RuntimeException) { m_pOwner->refreshed(rEvent); } // lang.XEventListener virtual void SAL_CALL disposing(const com::sun::star::lang::EventObject& rEvent) throw(com::sun::star::uno::RuntimeException) { m_pOwner->disposing(rEvent); } }; /*-************************************************************************************************************//** @short ctor @descr These initialize an instance of a SfxFilterListener class. Created object listen automaticly on right FilterFactory-Service for all changes and synchronize right SfxFilterContainer with corresponding framework-cache. We use given "sFactory" value to decide which query must be used to fill "pContainer" with new values. Given "pContainer" hold us alive as uno reference and we use it to syschronize it with framework caches. We will die, if he die! see dtor for further informations. @seealso dtor @seealso class framework::FilterCache @seealso service ::document::FilterFactory @param "sFactory" , short name of module which contains filter container @param "pContainer", pointer to filter container which will be informed @return - @onerror We show some assertions in non product version. Otherwise we do nothing! @threadsafe yes *//*-*************************************************************************************************************/ SfxFilterListener::SfxFilterListener() { uno::Reference< lang::XMultiServiceFactory > xSmgr = ::comphelper::getProcessServiceFactory(); if( xSmgr.is() == sal_True ) { uno::Reference< util::XRefreshable > xNotifier( xSmgr->createInstance( "com.sun.star.document.FilterConfigRefresh" ), uno::UNO_QUERY ); if( xNotifier.is() == sal_True ) { m_xFilterCache = xNotifier; m_xFilterCacheListener = new SfxRefreshListener(this); m_xFilterCache->addRefreshListener( m_xFilterCacheListener ); } } } SfxFilterListener::~SfxFilterListener() { } void SAL_CALL SfxFilterListener::refreshed( const lang::EventObject& aSource ) throw( uno::RuntimeException ) { SolarMutexGuard aGuard; uno::Reference< util::XRefreshable > xContainer( aSource.Source, uno::UNO_QUERY ); if( (xContainer.is() ) && (xContainer==m_xFilterCache) ) { SfxFilterContainer::ReadFilters_Impl( sal_True ); } } void SAL_CALL SfxFilterListener::disposing( const lang::EventObject& aSource ) throw( uno::RuntimeException ) { SolarMutexGuard aGuard; uno::Reference< util::XRefreshable > xNotifier( aSource.Source, uno::UNO_QUERY ); if (!xNotifier.is()) return; if (xNotifier == m_xFilterCache) m_xFilterCache.clear(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fdo#46808, use service constructor for document::FilterConfigRefresh<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "fltlst.hxx" #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/document/FilterConfigRefresh.hpp> #include <comphelper/processfactory.hxx> #include <sfx2/sfxuno.hxx> #include <sfx2/docfac.hxx> #include <vcl/svapp.hxx> #include <osl/mutex.hxx> //***************************************************************************************************************** // namespaces //***************************************************************************************************************** using namespace ::com::sun::star; class SfxRefreshListener : public ::cppu::WeakImplHelper1<com::sun::star::util::XRefreshListener> { private: SfxFilterListener *m_pOwner; public: SfxRefreshListener(SfxFilterListener *pOwner) : m_pOwner(pOwner) { } virtual ~SfxRefreshListener() { } // util.XRefreshListener virtual void SAL_CALL refreshed( const ::com::sun::star::lang::EventObject& rEvent ) throw(com::sun::star::uno::RuntimeException) { m_pOwner->refreshed(rEvent); } // lang.XEventListener virtual void SAL_CALL disposing(const com::sun::star::lang::EventObject& rEvent) throw(com::sun::star::uno::RuntimeException) { m_pOwner->disposing(rEvent); } }; /*-************************************************************************************************************//** @short ctor @descr These initialize an instance of a SfxFilterListener class. Created object listen automaticly on right FilterFactory-Service for all changes and synchronize right SfxFilterContainer with corresponding framework-cache. We use given "sFactory" value to decide which query must be used to fill "pContainer" with new values. Given "pContainer" hold us alive as uno reference and we use it to syschronize it with framework caches. We will die, if he die! see dtor for further informations. @seealso dtor @seealso class framework::FilterCache @seealso service ::document::FilterFactory @param "sFactory" , short name of module which contains filter container @param "pContainer", pointer to filter container which will be informed @return - @onerror We show some assertions in non product version. Otherwise we do nothing! @threadsafe yes *//*-*************************************************************************************************************/ SfxFilterListener::SfxFilterListener() { m_xFilterCache = document::FilterConfigRefresh::create( comphelper::getProcessComponentContext() ); m_xFilterCacheListener = new SfxRefreshListener(this); m_xFilterCache->addRefreshListener( m_xFilterCacheListener ); } SfxFilterListener::~SfxFilterListener() { } void SAL_CALL SfxFilterListener::refreshed( const lang::EventObject& aSource ) throw( uno::RuntimeException ) { SolarMutexGuard aGuard; uno::Reference< util::XRefreshable > xContainer( aSource.Source, uno::UNO_QUERY ); if( (xContainer.is() ) && (xContainer==m_xFilterCache) ) { SfxFilterContainer::ReadFilters_Impl( sal_True ); } } void SAL_CALL SfxFilterListener::disposing( const lang::EventObject& aSource ) throw( uno::RuntimeException ) { SolarMutexGuard aGuard; uno::Reference< util::XRefreshable > xNotifier( aSource.Source, uno::UNO_QUERY ); if (!xNotifier.is()) return; if (xNotifier == m_xFilterCache) m_xFilterCache.clear(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* Copyright (c) David Cunningham and the Grit Game Engine project 2012 * * 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 <cstdlib> #include <string> #include <windows.h> #include <unicode_util.h> #include "../clipboard.h" void clipboard_init (void) { (void) win; } void clipboard_shutdown (void) { } void clipboard_pump (void) { } void clipboard_set (const std::string &s_) { std::wstring s = utf8_to_utf16(s_);; const size_t len = s.size() + 1; HGLOBAL gmem = GlobalAlloc(GMEM_MOVEABLE, len); ::memcpy(GlobalLock(gmem), s.c_str(), len); GlobalUnlock(gmem); if (!OpenClipboard(0)) return; EmptyClipboard(); SetClipboardData(CF_TEXT, gmem); CloseClipboard(); } void clipboard_selection_set (const std::string &s) { clipboard_set(s); } std::string clipboard_get (void) { if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return ""; if (!OpenClipboard(0)) return ""; HGLOBAL gmem = GetClipboardData(CF_UNICODETEXT); std::wstring r; LPWSTR gmem_ = (LPWSTR)GlobalLock(gmem); if (gmem_) r = gmem_; GlobalUnlock(gmem); CloseClipboard(); return utf16_to_utf8(r);; } std::string clipboard_selection_get (void) { return clipboard_get(); } // vim: shiftwidth=8:tabstop=8:expandtab <commit_msg>Fix build error with win32 clipboard<commit_after>/* Copyright (c) David Cunningham and the Grit Game Engine project 2012 * * 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 <cstdlib> #include <string> #include <windows.h> #include <unicode_util.h> #include "../clipboard.h" void clipboard_init (void) { } void clipboard_shutdown (void) { } void clipboard_pump (void) { } void clipboard_set (const std::string &s_) { std::wstring s = utf8_to_utf16(s_);; const size_t len = s.size() + 1; HGLOBAL gmem = GlobalAlloc(GMEM_MOVEABLE, len); ::memcpy(GlobalLock(gmem), s.c_str(), len); GlobalUnlock(gmem); if (!OpenClipboard(0)) return; EmptyClipboard(); SetClipboardData(CF_TEXT, gmem); CloseClipboard(); } void clipboard_selection_set (const std::string &s) { clipboard_set(s); } std::string clipboard_get (void) { if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return ""; if (!OpenClipboard(0)) return ""; HGLOBAL gmem = GetClipboardData(CF_UNICODETEXT); std::wstring r; LPWSTR gmem_ = (LPWSTR)GlobalLock(gmem); if (gmem_) r = gmem_; GlobalUnlock(gmem); CloseClipboard(); return utf16_to_utf8(r);; } std::string clipboard_selection_get (void) { return clipboard_get(); } // vim: shiftwidth=8:tabstop=8:expandtab <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impframe.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 16:49: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef GCC #endif #include "impframe.hxx" #include <svtools/smplhint.hxx> #include "frame.hxx" #include "bindings.hxx" #include "viewfrm.hxx" void SfxFrame_Impl::Notify( SfxBroadcaster& /*rBC*/, const SfxHint& rHint ) { SfxSimpleHint* pHint = PTR_CAST( SfxSimpleHint, &rHint ); if( pHint && pHint->GetId() == SFX_HINT_CANCELLABLE && pCurrentViewFrame ) { // vom Cancel-Manager SfxBindings &rBind = pCurrentViewFrame->GetBindings(); rBind.Invalidate( SID_BROWSE_STOP ); if ( !rBind.IsInRegistrations() ) rBind.Update( SID_BROWSE_STOP ); rBind.Invalidate( SID_BROWSE_STOP ); } } <commit_msg>INTEGRATION: CWS vgbugs07 (1.7.218); FILE MERGED 2007/06/04 13:35:02 vg 1.7.218.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: impframe.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 23:33:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #ifndef GCC #endif #include "impframe.hxx" #include <svtools/smplhint.hxx> #include <sfx2/frame.hxx> #include <sfx2/bindings.hxx> #include <sfx2/viewfrm.hxx> void SfxFrame_Impl::Notify( SfxBroadcaster& /*rBC*/, const SfxHint& rHint ) { SfxSimpleHint* pHint = PTR_CAST( SfxSimpleHint, &rHint ); if( pHint && pHint->GetId() == SFX_HINT_CANCELLABLE && pCurrentViewFrame ) { // vom Cancel-Manager SfxBindings &rBind = pCurrentViewFrame->GetBindings(); rBind.Invalidate( SID_BROWSE_STOP ); if ( !rBind.IsInRegistrations() ) rBind.Update( SID_BROWSE_STOP ); rBind.Invalidate( SID_BROWSE_STOP ); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnisotropicFourthOrderLevelSetImageFilter.txx" #include "itkAntiAliasBinaryImageFilter.txx" #include "itkAutomaticTopologyMeshSource.txx" #include "itkBalloonForceFilter.txx" #include "itkBinaryMask3DMeshSource.txx" #include "itkBinaryMedialNodeMetric.txx" #include "itkBinaryMinMaxCurvatureFlowFunction.txx" #include "itkBinaryMinMaxCurvatureFlowImageFilter.txx" #include "itkBioGene.h" #include "itkBioGeneNetwork.h" #include "itkCannySegmentationLevelSetFunction.txx" #include "itkCannySegmentationLevelSetImageFilter.txx" #include "itkClassifierBase.txx" #include "itkCompareHistogramImageToImageMetric.txx" #include "itkConnectedRegionsMeshFilter.txx" #include "itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx" #include "itkCorrelationCoefficientHistogramImageToImageMetric.txx" #include "itkCurvatureFlowFunction.txx" #include "itkCurvatureFlowImageFilter.txx" #include "itkCurvesLevelSetFunction.txx" #include "itkCurvesLevelSetImageFilter.txx" #include "itkDeformableMesh3DFilter.txx" #include "itkDemonsRegistrationFilter.txx" #include "itkDemonsRegistrationFunction.txx" #include "itkExtensionVelocitiesImageFilter.txx" #include "itkFEMFiniteDifferenceFunctionLoad.txx" #include "itkFEMRegistrationFilter.txx" #include "itkFastChamferDistanceImageFilter.txx" #include "itkFastMarchingExtensionImageFilter.txx" #include "itkFastMarchingImageFilter.txx" #include "itkGeodesicActiveContourLevelSetFunction.txx" #include "itkGeodesicActiveContourLevelSetImageFilter.txx" #include "itkGeodesicActiveContourShapePriorLevelSetFunction.txx" #include "itkGeodesicActiveContourShapePriorLevelSetImageFilter.txx" #include "itkGradientVectorFlowImageFilter.txx" #include "itkHistogramImageToImageMetric.txx" #include "itkHistogramMatchingImageFilter.txx" #include "itkImageClassifierBase.txx" #include "itkImageGaussianModelEstimator.txx" #include "itkImageKmeansModelEstimator.txx" #include "itkImageModelEstimatorBase.txx" #include "itkImageMomentsCalculator.txx" #include "itkImagePCAShapeModelEstimator.txx" #include "itkImageRegistrationMethod.txx" #include "itkImageShapeModelEstimatorBase.txx" #include "itkImageToImageMetric.txx" #include "itkImageToSpatialObjectMetric.txx" #include "itkImageToSpatialObjectRegistrationMethod.txx" #include "itkIsoContourDistanceImageFilter.txx" #include "itkIsotropicFourthOrderLevelSetImageFilter.txx" #include "itkKLMRegionGrowImageFilter.txx" #include "itkKalmanLinearEstimator.h" #include "itkKullbackLieblerCompareHistogramImageToImageMetric.txx" #include "itkLaplacianSegmentationLevelSetFunction.txx" #include "itkLaplacianSegmentationLevelSetImageFilter.txx" #include "itkLevelSetNeighborhoodExtractor.txx" #include "itkLevelSetVelocityNeighborhoodExtractor.txx" #include "itkMIRegistrationFunction.txx" #include "itkMRASlabIdentifier.txx" #include "itkMRFImageFilter.txx" #include "itkMRIBiasFieldCorrectionFilter.txx" #include "itkMattesMutualInformationImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx" #include "itkMeanSquareRegistrationFunction.txx" #include "itkMeanSquaresHistogramImageToImageMetric.txx" #include "itkMeanSquaresImageToImageMetric.txx" #include "itkMeanSquaresPointSetToImageMetric.txx" #include "itkMedialNodePairCorrespondenceProcess.txx" #include "itkMedialNodeTripletCorrespondenceProcess.txx" #include "itkMinMaxCurvatureFlowFunction.txx" #include "itkMinMaxCurvatureFlowImageFilter.txx" #include "itkMultiResolutionImageRegistrationMethod.txx" #include "itkMultiResolutionPDEDeformableRegistration.txx" #include "itkMultiResolutionPyramidImageFilter.txx" #include "itkMutualInformationHistogramImageToImageMetric.txx" #include "itkMutualInformationImageToImageMetric.txx" #include "itkNCCRegistrationFunction.txx" #include "itkNarrowBandCurvesLevelSetImageFilter.txx" #include "itkNarrowBandLevelSetImageFilter.txx" #include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.txx" #include "itkNormalizedCorrelationImageToImageMetric.txx" #include "itkNormalizedCorrelationPointSetToImageMetric.txx" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.txx" #include "itkOrthogonalSwath2DPathFilter.txx" #include "itkOtsuThresholdImageCalculator.txx" #include "itkPDEDeformableRegistrationFilter.txx" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPointSetToImageMetric.txx" #include "itkPointSetToImageRegistrationMethod.txx" #include "itkRGBGibbsPriorFilter.txx" #include "itkRayCastInterpolateImageFunction.txx" #include "itkRecursiveMultiResolutionPyramidImageFilter.txx" #include "itkRegionGrowImageFilter.txx" #include "itkReinitializeLevelSetImageFilter.txx" #include "itkSegmentationLevelSetImageFilter.txx" #include "itkShapeDetectionLevelSetFunction.txx" #include "itkShapeDetectionLevelSetImageFilter.txx" #include "itkShapePriorMAPCostFunction.txx" #include "itkShapePriorMAPCostFunctionBase.txx" #include "itkShapePriorSegmentationLevelSetFunction.txx" #include "itkShapePriorSegmentationLevelSetImageFilter.txx" #include "itkSimpleFuzzyConnectednessImageFilterBase.txx" #include "itkSimpleFuzzyConnectednessRGBImageFilter.txx" #include "itkSimpleFuzzyConnectednessScalarImageFilter.txx" #include "itkSphereMeshSource.txx" #include "itkStructHashFunction.h" #include "itkSwathChainCodePathFilter.txx" #include "itkThresholdSegmentationLevelSetFunction.txx" #include "itkThresholdSegmentationLevelSetImageFilter.txx" #include "itkUnaryMedialNodeMetric.txx" #include "itkUnsharpMaskLevelSetImageFilter.txx" #include "itkVectorFuzzyConnectednessImageFilter.txx" #include "itkVoronoiDiagram2D.txx" #include "itkVoronoiDiagram2DGenerator.txx" #include "itkVoronoiPartitioningImageFilter.txx" #include "itkVoronoiSegmentationImageFilter.txx" #include "itkVoronoiSegmentationImageFilterBase.txx" #include "itkVoronoiSegmentationRGBImageFilter.txx" #include "itkWatershedBoundary.txx" #include "itkWatershedBoundaryResolver.txx" #include "itkWatershedEquivalenceRelabeler.txx" #include "itkWatershedImageFilter.txx" #include "itkWatershedMiniPipelineProgressCommand.h" #include "itkWatershedRelabeler.txx" #include "itkWatershedSegmentTable.txx" #include "itkWatershedSegmentTree.txx" #include "itkWatershedSegmentTreeGenerator.txx" #include "itkWatershedSegmenter.txx" int main ( int , char* ) { return 0; } <commit_msg>ENH: Added new classes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnisotropicFourthOrderLevelSetImageFilter.txx" #include "itkAntiAliasBinaryImageFilter.txx" #include "itkAutomaticTopologyMeshSource.txx" #include "itkBalloonForceFilter.txx" #include "itkBinaryMask3DMeshSource.txx" #include "itkBinaryMedialNodeMetric.txx" #include "itkBinaryMinMaxCurvatureFlowFunction.txx" #include "itkBinaryMinMaxCurvatureFlowImageFilter.txx" #include "itkBioGene.h" #include "itkBioGeneNetwork.h" #include "itkCannySegmentationLevelSetFunction.txx" #include "itkCannySegmentationLevelSetImageFilter.txx" #include "itkClassifierBase.txx" #include "itkCompareHistogramImageToImageMetric.txx" #include "itkConnectedRegionsMeshFilter.txx" #include "itkCoreAtomImageToUnaryCorrespondenceMatrixProcess.txx" #include "itkCorrelationCoefficientHistogramImageToImageMetric.txx" #include "itkCurvatureFlowFunction.txx" #include "itkCurvatureFlowImageFilter.txx" #include "itkCurvesLevelSetFunction.txx" #include "itkCurvesLevelSetImageFilter.txx" #include "itkDeformableMesh3DFilter.txx" #include "itkDemonsRegistrationFilter.txx" #include "itkDemonsRegistrationFunction.txx" #include "itkExtensionVelocitiesImageFilter.txx" #include "itkFEMFiniteDifferenceFunctionLoad.txx" #include "itkFEMRegistrationFilter.txx" #include "itkFFTComplexConjugateToRealImageFilter.txx" #include "itkFFTRealToComplexConjugateImageFilter.txx" #include "itkFFTWComplexConjugateToRealImageFilter.txx" #include "itkFFTWRealToComplexConjugateImageFilter.txx" #include "itkFastChamferDistanceImageFilter.txx" #include "itkFastMarchingExtensionImageFilter.txx" #include "itkFastMarchingImageFilter.txx" #include "itkGeodesicActiveContourLevelSetFunction.txx" #include "itkGeodesicActiveContourLevelSetImageFilter.txx" #include "itkGeodesicActiveContourShapePriorLevelSetFunction.txx" #include "itkGeodesicActiveContourShapePriorLevelSetImageFilter.txx" #include "itkGradientDifferenceImageToImageMetric.txx" #include "itkGradientVectorFlowImageFilter.txx" #include "itkHistogramImageToImageMetric.txx" #include "itkHistogramMatchingImageFilter.txx" #include "itkImageClassifierBase.txx" #include "itkImageGaussianModelEstimator.txx" #include "itkImageKmeansModelEstimator.txx" #include "itkImageModelEstimatorBase.txx" #include "itkImageMomentsCalculator.txx" #include "itkImagePCAShapeModelEstimator.txx" #include "itkImageRegistrationMethod.txx" #include "itkImageShapeModelEstimatorBase.txx" #include "itkImageToImageMetric.txx" #include "itkImageToSpatialObjectMetric.txx" #include "itkImageToSpatialObjectRegistrationMethod.txx" #include "itkIsoContourDistanceImageFilter.txx" #include "itkIsotropicFourthOrderLevelSetImageFilter.txx" #include "itkIterativeClosestPointMetric.txx" #include "itkKLMRegionGrowImageFilter.txx" #include "itkKalmanLinearEstimator.h" #include "itkKullbackLieblerCompareHistogramImageToImageMetric.txx" #include "itkLaplacianSegmentationLevelSetFunction.txx" #include "itkLaplacianSegmentationLevelSetImageFilter.txx" #include "itkLevelSetNeighborhoodExtractor.txx" #include "itkLevelSetVelocityNeighborhoodExtractor.txx" #include "itkMIRegistrationFunction.txx" #include "itkMRASlabIdentifier.txx" #include "itkMRFImageFilter.txx" #include "itkMRIBiasFieldCorrectionFilter.txx" #include "itkMattesMutualInformationImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx" #include "itkMeanSquareRegistrationFunction.txx" #include "itkMeanSquaresHistogramImageToImageMetric.txx" #include "itkMeanSquaresImageToImageMetric.txx" #include "itkMeanSquaresPointSetToImageMetric.txx" #include "itkMedialNodePairCorrespondenceProcess.txx" #include "itkMedialNodeTripletCorrespondenceProcess.txx" #include "itkMinMaxCurvatureFlowFunction.txx" #include "itkMinMaxCurvatureFlowImageFilter.txx" #include "itkMultiResolutionImageRegistrationMethod.txx" #include "itkMultiResolutionPDEDeformableRegistration.txx" #include "itkMultiResolutionPyramidImageFilter.txx" #include "itkMutualInformationHistogramImageToImageMetric.txx" #include "itkMutualInformationImageToImageMetric.txx" #include "itkNCCRegistrationFunction.txx" #include "itkNarrowBandCurvesLevelSetImageFilter.txx" #include "itkNarrowBandLevelSetImageFilter.txx" #include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.txx" #include "itkNormalizedCorrelationImageToImageMetric.txx" #include "itkNormalizedCorrelationPointSetToImageMetric.txx" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.txx" #include "itkOrthogonalSwath2DPathFilter.txx" #include "itkOtsuThresholdImageCalculator.txx" #include "itkPDEDeformableRegistrationFilter.txx" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPointSetToImageMetric.txx" #include "itkPointSetToImageRegistrationMethod.txx" #include "itkPointSetToPointSetMetric.txx" #include "itkPointSetToPointSetRegistrationMethod.txx" #include "itkRGBGibbsPriorFilter.txx" #include "itkRayCastInterpolateImageFunction.txx" #include "itkRecursiveMultiResolutionPyramidImageFilter.txx" #include "itkRegionGrowImageFilter.txx" #include "itkReinitializeLevelSetImageFilter.txx" #include "itkSCSLComplexConjugateToRealImageFilter.txx" #include "itkSCSLRealToComplexConjugateImageFilter.txx" #include "itkSegmentationLevelSetImageFilter.txx" #include "itkShapeDetectionLevelSetFunction.txx" #include "itkShapeDetectionLevelSetImageFilter.txx" #include "itkShapePriorMAPCostFunction.txx" #include "itkShapePriorMAPCostFunctionBase.txx" #include "itkShapePriorSegmentationLevelSetFunction.txx" #include "itkShapePriorSegmentationLevelSetImageFilter.txx" #include "itkSimpleFuzzyConnectednessImageFilterBase.txx" #include "itkSimpleFuzzyConnectednessRGBImageFilter.txx" #include "itkSimpleFuzzyConnectednessScalarImageFilter.txx" #include "itkSphereMeshSource.txx" #include "itkStructHashFunction.h" #include "itkSwathChainCodePathFilter.txx" #include "itkThresholdSegmentationLevelSetFunction.txx" #include "itkThresholdSegmentationLevelSetImageFilter.txx" #include "itkUnaryMedialNodeMetric.txx" #include "itkUnsharpMaskLevelSetImageFilter.txx" #include "itkVectorFuzzyConnectednessImageFilter.txx" #include "itkVectorThresholdSegmentationLevelSetFunction.txx" #include "itkVectorThresholdSegmentationLevelSetImageFilter.txx" #include "itkVnlFFTComplexConjugateToRealImageFilter.txx" #include "itkVnlFFTRealToComplexConjugateImageFilter.txx" #include "itkVoronoiDiagram2D.txx" #include "itkVoronoiDiagram2DGenerator.txx" #include "itkVoronoiPartitioningImageFilter.txx" #include "itkVoronoiSegmentationImageFilter.txx" #include "itkVoronoiSegmentationImageFilterBase.txx" #include "itkVoronoiSegmentationRGBImageFilter.txx" #include "itkWatershedBoundary.txx" #include "itkWatershedBoundaryResolver.txx" #include "itkWatershedEquivalenceRelabeler.txx" #include "itkWatershedImageFilter.txx" #include "itkWatershedMiniPipelineProgressCommand.h" #include "itkWatershedRelabeler.txx" #include "itkWatershedSegmentTable.txx" #include "itkWatershedSegmentTree.txx" #include "itkWatershedSegmentTreeGenerator.txx" #include "itkWatershedSegmenter.txx" #include "vnl_fft_3d.h" int main ( int , char* ) { return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkBalloonForce3DFilter.h" #include "itkBalloonForceFilter.h" #include "itkClassifier.h" #include "itkConnectedRegionsMeshFilter.h" #include "itkCurvatureFlowFunction.h" #include "itkCurvatureFlowImageFilter.h" #include "itkDeformableMesh.h" #include "itkDeformableMesh3DFilter.h" #include "itkDeformableMeshFilter.h" #include "itkDemonsRegistrationFilter.h" #include "itkDemonsRegistrationFunction.h" #include "itkExtensionVelocitiesImageFilter.h" #include "itkFastMarchingExtensionImageFilter.h" #include "itkFastMarchingImageFilter.h" #include "itkFuzzyConnectednessImageFilter.h" #include "itkFuzzyConnectednessRGBImageFilter.h" #include "itkGaussianSupervisedClassifier.h" #include "itkGeodesicActiveContourImageFilter.h" #include "itkGibbsPriorFilter.h" #include "itkHybridFilter.h" #include "itkImageMapper.h" #include "itkImageMomentsCalculator.h" #include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h" #include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h" #include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h" #include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h" #include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h" #include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h" #include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h" #include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkKLMRegionGrowImageFilter.h" #include "itkKalmanLinearEstimator.h" #include "itkKmeansUnsupervisedClassifier.h" #include "itkLevelSet.h" #include "itkLevelSet2DFunction.h" #include "itkLevelSetFunction.h" #include "itkLevelSetImageFilter.h" #include "itkLevelSetNeighborhoodExtractor.h" #include "itkLevelSetVelocityNeighborhoodExtractor.h" #include "itkMRASlabIdentifier.h" #include "itkMRFImageFilter.h" #include "itkMRIBiasFieldCorrectionFilter.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMeanSquaresPointSetToImageMetric.h" #include "itkMinimumMaximumImageCalculator.h" #include "itkMultiResolutionMutualInformationAffineRegistration.h" #include "itkMultiResolutionMutualInformationRigidRegistration.h" #include "itkMultiResolutionPDEDeformableRegistration.h" #include "itkMultiResolutionPyramidImageFilter.h" #include "itkMultiResolutionRegistration.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkNormalizedCorrelationPointSetToImageMetric.h" #include "itkPDEDeformableRegistrationFilter.h" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPatternIntensityImageToImageMetric.h" #include "itkPatternIntensityPointSetToImageMetric.h" #include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h" #include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h" #include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h" #include "itkProcrustesRegistrationMetric.h" #include "itkRGBGibbsPriorFilter.h" #include "itkRecursiveMultiResolutionPyramidImageFilter.h" #include "itkRegionGrowImageFilter.h" #include "itkRegistrationMapper.h" #include "itkRegistrationMapperImage.h" #include "itkRegistrationMapperProcrustes.h" #include "itkRegistrationMethod.h" #include "itkRegistrationTransform.h" #include "itkReinitializeLevelSetImageFilter.h" #include "itkShapeDetectionLevelSetFilter.h" #include "itkSimilarityRegistrationMetric.h" #include "itkSimpleFuzzyConnectednessImageFilterBase.h" #include "itkSphereMeshSource.h" #include "itkSphereSource.h" #include "itkSupervisedClassifier.h" #include "itkUnsupervisedClassifier.h" #include "itkVectorFuzzyConnectednessImageFilter.h" #include "itkVoronoiDiagram2D.h" #include "itkVoronoiDiagram2DGenerator.h" #include "itkVoronoiSegmentationImageFilter.h" #include "itkVoronoiSegmentationImageFilterBase.h" #include "itkVoronoiSegmentationRGBImageFilter.h" #include "itkWatershedBoundary.h" #include "itkWatershedBoundaryResolver.h" #include "itkWatershedEquivalenceRelabeler.h" #include "itkWatershedEquivalencyTable.h" #include "itkWatershedImageFilter.h" #include "itkWatershedOneWayEquivalencyTable.h" #include "itkWatershedRelabeler.h" #include "itkWatershedSegmentTable.h" #include "itkWatershedSegmentTree.h" #include "itkWatershedSegmentTreeGenerator.h" #include "itkWatershedSegmenter.h" int main ( int argc, char* argv ) { return 0; } <commit_msg>Removed non-existent headers.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkBalloonForce3DFilter.h" #include "itkBalloonForceFilter.h" #include "itkClassifier.h" #include "itkConnectedRegionsMeshFilter.h" #include "itkCurvatureFlowFunction.h" #include "itkCurvatureFlowImageFilter.h" #include "itkDeformableMesh.h" #include "itkDeformableMesh3DFilter.h" #include "itkDeformableMeshFilter.h" #include "itkDemonsRegistrationFilter.h" #include "itkDemonsRegistrationFunction.h" #include "itkExtensionVelocitiesImageFilter.h" #include "itkFastMarchingExtensionImageFilter.h" #include "itkFastMarchingImageFilter.h" #include "itkFuzzyConnectednessImageFilter.h" #include "itkFuzzyConnectednessRGBImageFilter.h" #include "itkGaussianSupervisedClassifier.h" #include "itkGeodesicActiveContourImageFilter.h" #include "itkGibbsPriorFilter.h" #include "itkHybridFilter.h" #include "itkImageMapper.h" #include "itkImageMomentsCalculator.h" #include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h" #include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h" #include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h" #include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h" #include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h" #include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h" #include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h" #include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkKLMRegionGrowImageFilter.h" #include "itkKalmanLinearEstimator.h" #include "itkKmeansUnsupervisedClassifier.h" #include "itkLevelSet.h" #include "itkLevelSet2DFunction.h" #include "itkLevelSetFunction.h" #include "itkLevelSetImageFilter.h" #include "itkLevelSetNeighborhoodExtractor.h" #include "itkLevelSetVelocityNeighborhoodExtractor.h" #include "itkMRASlabIdentifier.h" #include "itkMRFImageFilter.h" #include "itkMRIBiasFieldCorrectionFilter.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMeanSquaresPointSetToImageMetric.h" #include "itkMinimumMaximumImageCalculator.h" #include "itkMultiResolutionMutualInformationAffineRegistration.h" #include "itkMultiResolutionMutualInformationRigidRegistration.h" #include "itkMultiResolutionPDEDeformableRegistration.h" #include "itkMultiResolutionPyramidImageFilter.h" #include "itkMultiResolutionRegistration.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkNormalizedCorrelationPointSetToImageMetric.h" #include "itkPDEDeformableRegistrationFilter.h" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPatternIntensityImageToImageMetric.h" #include "itkPatternIntensityPointSetToImageMetric.h" #include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h" #include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h" #include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h" #include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h" #include "itkProcrustesRegistrationMetric.h" #include "itkRGBGibbsPriorFilter.h" #include "itkRecursiveMultiResolutionPyramidImageFilter.h" #include "itkRegionGrowImageFilter.h" #include "itkRegistrationMapper.h" #include "itkRegistrationMapperProcrustes.h" #include "itkRegistrationMethod.h" #include "itkReinitializeLevelSetImageFilter.h" #include "itkShapeDetectionLevelSetFilter.h" #include "itkSimilarityRegistrationMetric.h" #include "itkSimpleFuzzyConnectednessImageFilterBase.h" #include "itkSphereMeshSource.h" #include "itkSphereSource.h" #include "itkSupervisedClassifier.h" #include "itkUnsupervisedClassifier.h" #include "itkVectorFuzzyConnectednessImageFilter.h" #include "itkVoronoiDiagram2D.h" #include "itkVoronoiDiagram2DGenerator.h" #include "itkVoronoiSegmentationImageFilter.h" #include "itkVoronoiSegmentationImageFilterBase.h" #include "itkVoronoiSegmentationRGBImageFilter.h" #include "itkWatershedBoundary.h" #include "itkWatershedBoundaryResolver.h" #include "itkWatershedEquivalenceRelabeler.h" #include "itkWatershedEquivalencyTable.h" #include "itkWatershedImageFilter.h" #include "itkWatershedOneWayEquivalencyTable.h" #include "itkWatershedRelabeler.h" #include "itkWatershedSegmentTable.h" #include "itkWatershedSegmentTree.h" #include "itkWatershedSegmentTreeGenerator.h" #include "itkWatershedSegmenter.h" int main ( int argc, char* argv ) { return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnisotropicFourthOrderLevelSetImageFilter.txx" #include "itkAntiAliasBinaryImageFilter.txx" #include "itkAutomaticTopologyMeshSource.txx" #include "itkBalloonForceFilter.txx" #include "itkBinaryMask3DMeshSource.txx" #include "itkBinaryMinMaxCurvatureFlowFunction.txx" #include "itkBinaryMinMaxCurvatureFlowImageFilter.txx" #include "itkBioGene.h" #include "itkBioGeneNetwork.h" #include "itkCannySegmentationLevelSetFunction.txx" #include "itkCannySegmentationLevelSetImageFilter.txx" #include "itkClassifierBase.txx" #include "itkConnectedRegionsMeshFilter.txx" #include "itkCorrelationCoefficientHistogramImageToImageMetric.txx" #include "itkCurvatureFlowFunction.txx" #include "itkCurvatureFlowImageFilter.txx" #include "itkCurvesLevelSetFunction.txx" #include "itkCurvesLevelSetImageFilter.txx" #include "itkDeformableMesh3DFilter.txx" #include "itkDemonsRegistrationFilter.txx" #include "itkDemonsRegistrationFunction.txx" #include "itkExtensionVelocitiesImageFilter.txx" #include "itkFEMRegistrationFilter.txx" #include "itkFastMarchingExtensionImageFilter.txx" #include "itkFastMarchingImageFilter.txx" #include "itkGeodesicActiveContourLevelSetFunction.txx" #include "itkGeodesicActiveContourLevelSetImageFilter.txx" #include "itkGeodesicActiveContourShapePriorLevelSetFunction.txx" #include "itkGeodesicActiveContourShapePriorLevelSetImageFilter.txx" #include "itkGradientVectorFlowImageFilter.txx" #include "itkHistogramImageToImageMetric.txx" #include "itkHistogramMatchingImageFilter.txx" #include "itkImageClassifierBase.txx" #include "itkImageGaussianModelEstimator.txx" #include "itkImageKmeansModelEstimator.txx" #include "itkImageModelEstimatorBase.txx" #include "itkImageMomentsCalculator.txx" #include "itkImagePCAShapeModelEstimator.txx" #include "itkImageRegistrationMethod.txx" #include "itkImageShapeModelEstimatorBase.txx" #include "itkImageToImageMetric.txx" #include "itkImageToSpatialObjectMetric.txx" #include "itkImageToSpatialObjectRegistrationMethod.txx" #include "itkIsoContourDistanceImageFilter.txx" #include "itkIsotropicFourthOrderLevelSetImageFilter.txx" #include "itkKLMRegionGrowImageFilter.txx" #include "itkKalmanLinearEstimator.h" #include "itkLaplacianSegmentationLevelSetFunction.txx" #include "itkLaplacianSegmentationLevelSetImageFilter.txx" #include "itkLevelSetNeighborhoodExtractor.txx" #include "itkLevelSetVelocityNeighborhoodExtractor.txx" #include "itkMRASlabIdentifier.txx" #include "itkMRFImageFilter.txx" #include "itkMRIBiasFieldCorrectionFilter.txx" #include "itkMattesMutualInformationImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx" #include "itkMeanSquaresHistogramImageToImageMetric.txx" #include "itkMeanSquaresImageToImageMetric.txx" #include "itkMeanSquaresPointSetToImageMetric.txx" #include "itkMinMaxCurvatureFlowFunction.txx" #include "itkMinMaxCurvatureFlowImageFilter.txx" #include "itkMultiResolutionImageRegistrationMethod.txx" #include "itkMultiResolutionPDEDeformableRegistration.txx" #include "itkMultiResolutionPyramidImageFilter.txx" #include "itkMutualInformationHistogramImageToImageMetric.txx" #include "itkMutualInformationImageToImageMetric.txx" #include "itkNarrowBandCurvesLevelSetImageFilter.txx" #include "itkNarrowBandLevelSetImageFilter.txx" #include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.txx" #include "itkNormalizedCorrelationImageToImageMetric.txx" #include "itkNormalizedCorrelationPointSetToImageMetric.txx" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.txx" #include "itkOtsuThresholdImageCalculator.txx" #include "itkPDEDeformableRegistrationFilter.txx" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPointSetToImageMetric.txx" #include "itkPointSetToImageRegistrationMethod.txx" #include "itkRGBGibbsPriorFilter.txx" #include "itkRayCastInterpolateImageFunction.txx" #include "itkRecursiveMultiResolutionPyramidImageFilter.txx" #include "itkRegionGrowImageFilter.txx" #include "itkRegistrationMethod.txx" #include "itkReinitializeLevelSetImageFilter.txx" #include "itkSegmentationLevelSetImageFilter.txx" #include "itkShapeDetectionLevelSetFunction.txx" #include "itkShapeDetectionLevelSetImageFilter.txx" #include "itkShapePriorMAPCostFunction.txx" #include "itkShapePriorMAPCostFunctionBase.txx" #include "itkShapePriorSegmentationLevelSetFunction.txx" #include "itkShapePriorSegmentationLevelSetImageFilter.txx" #include "itkSimpleFuzzyConnectednessImageFilterBase.txx" #include "itkSimpleFuzzyConnectednessRGBImageFilter.txx" #include "itkSimpleFuzzyConnectednessScalarImageFilter.txx" #include "itkSphereMeshSource.txx" #include "itkStructHashFunction.h" #include "itkThresholdSegmentationLevelSetFunction.txx" #include "itkThresholdSegmentationLevelSetImageFilter.txx" #include "itkUnsharpMaskLevelSetImageFilter.txx" #include "itkVectorFuzzyConnectednessImageFilter.txx" #include "itkVoronoiDiagram2D.txx" #include "itkVoronoiDiagram2DGenerator.txx" #include "itkVoronoiPartitioningImageFilter.txx" #include "itkVoronoiSegmentationImageFilter.txx" #include "itkVoronoiSegmentationImageFilterBase.txx" #include "itkVoronoiSegmentationRGBImageFilter.txx" #include "itkWatershedBoundary.txx" #include "itkWatershedBoundaryResolver.txx" #include "itkWatershedEquivalenceRelabeler.txx" #include "itkWatershedImageFilter.txx" #include "itkWatershedMiniPipelineProgressCommand.h" #include "itkWatershedRelabeler.txx" #include "itkWatershedSegmentTable.txx" #include "itkWatershedSegmentTree.txx" #include "itkWatershedSegmentTreeGenerator.txx" #include "itkWatershedSegmenter.txx" int main ( int , char* ) { return 0; } <commit_msg>ENH: Updated to latest headers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAnisotropicFourthOrderLevelSetImageFilter.txx" #include "itkAntiAliasBinaryImageFilter.txx" #include "itkAutomaticTopologyMeshSource.txx" #include "itkBalloonForceFilter.txx" #include "itkBinaryMask3DMeshSource.txx" #include "itkBinaryMinMaxCurvatureFlowFunction.txx" #include "itkBinaryMinMaxCurvatureFlowImageFilter.txx" #include "itkBioGene.h" #include "itkBioGeneNetwork.h" #include "itkCannySegmentationLevelSetFunction.txx" #include "itkCannySegmentationLevelSetImageFilter.txx" #include "itkClassifierBase.txx" #include "itkConnectedRegionsMeshFilter.txx" #include "itkCorrelationCoefficientHistogramImageToImageMetric.txx" #include "itkCurvatureFlowFunction.txx" #include "itkCurvatureFlowImageFilter.txx" #include "itkCurvesLevelSetFunction.txx" #include "itkCurvesLevelSetImageFilter.txx" #include "itkDeformableMesh3DFilter.txx" #include "itkDemonsRegistrationFilter.txx" #include "itkDemonsRegistrationFunction.txx" #include "itkExtensionVelocitiesImageFilter.txx" #include "itkFEMFiniteDifferenceFunctionLoad.txx" #include "itkFEMRegistrationFilter.txx" #include "itkFastChamferDistanceImageFilter.txx" #include "itkFastMarchingExtensionImageFilter.txx" #include "itkFastMarchingImageFilter.txx" #include "itkGeodesicActiveContourLevelSetFunction.txx" #include "itkGeodesicActiveContourLevelSetImageFilter.txx" #include "itkGeodesicActiveContourShapePriorLevelSetFunction.txx" #include "itkGeodesicActiveContourShapePriorLevelSetImageFilter.txx" #include "itkGradientVectorFlowImageFilter.txx" #include "itkHistogramImageToImageMetric.txx" #include "itkHistogramMatchingImageFilter.txx" #include "itkImageClassifierBase.txx" #include "itkImageGaussianModelEstimator.txx" #include "itkImageKmeansModelEstimator.txx" #include "itkImageModelEstimatorBase.txx" #include "itkImageMomentsCalculator.txx" #include "itkImagePCAShapeModelEstimator.txx" #include "itkImageRegistrationMethod.txx" #include "itkImageShapeModelEstimatorBase.txx" #include "itkImageToImageMetric.txx" #include "itkImageToSpatialObjectMetric.txx" #include "itkImageToSpatialObjectRegistrationMethod.txx" #include "itkIsoContourDistanceImageFilter.txx" #include "itkIsotropicFourthOrderLevelSetImageFilter.txx" #include "itkKLMRegionGrowImageFilter.txx" #include "itkKalmanLinearEstimator.h" #include "itkLaplacianSegmentationLevelSetFunction.txx" #include "itkLaplacianSegmentationLevelSetImageFilter.txx" #include "itkLevelSetNeighborhoodExtractor.txx" #include "itkLevelSetVelocityNeighborhoodExtractor.txx" #include "itkMIRegistrationFunction.txx" #include "itkMRASlabIdentifier.txx" #include "itkMRFImageFilter.txx" #include "itkMRIBiasFieldCorrectionFilter.txx" #include "itkMattesMutualInformationImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.txx" #include "itkMeanReciprocalSquareDifferencePointSetToImageMetric.txx" #include "itkMeanSquareRegistrationFunction.txx" #include "itkMeanSquaresHistogramImageToImageMetric.txx" #include "itkMeanSquaresImageToImageMetric.txx" #include "itkMeanSquaresPointSetToImageMetric.txx" #include "itkMinMaxCurvatureFlowFunction.txx" #include "itkMinMaxCurvatureFlowImageFilter.txx" #include "itkMultiResolutionImageRegistrationMethod.txx" #include "itkMultiResolutionPDEDeformableRegistration.txx" #include "itkMultiResolutionPyramidImageFilter.txx" #include "itkMutualInformationHistogramImageToImageMetric.txx" #include "itkMutualInformationImageToImageMetric.txx" #include "itkNCCRegistrationFunction.txx" #include "itkNarrowBandCurvesLevelSetImageFilter.txx" #include "itkNarrowBandLevelSetImageFilter.txx" #include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.txx" #include "itkNormalizedCorrelationImageToImageMetric.txx" #include "itkNormalizedCorrelationPointSetToImageMetric.txx" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.txx" #include "itkOtsuThresholdImageCalculator.txx" #include "itkPDEDeformableRegistrationFilter.txx" #include "itkPDEDeformableRegistrationFunction.h" #include "itkPointSetToImageMetric.txx" #include "itkPointSetToImageRegistrationMethod.txx" #include "itkRGBGibbsPriorFilter.txx" #include "itkRayCastInterpolateImageFunction.txx" #include "itkRecursiveMultiResolutionPyramidImageFilter.txx" #include "itkRegionGrowImageFilter.txx" #include "itkRegistrationMethod.txx" #include "itkReinitializeLevelSetImageFilter.txx" #include "itkSegmentationLevelSetImageFilter.txx" #include "itkShapeDetectionLevelSetFunction.txx" #include "itkShapeDetectionLevelSetImageFilter.txx" #include "itkShapePriorMAPCostFunction.txx" #include "itkShapePriorMAPCostFunctionBase.txx" #include "itkShapePriorSegmentationLevelSetFunction.txx" #include "itkShapePriorSegmentationLevelSetImageFilter.txx" #include "itkSimpleFuzzyConnectednessImageFilterBase.txx" #include "itkSimpleFuzzyConnectednessRGBImageFilter.txx" #include "itkSimpleFuzzyConnectednessScalarImageFilter.txx" #include "itkSphereMeshSource.txx" #include "itkStructHashFunction.h" #include "itkThresholdSegmentationLevelSetFunction.txx" #include "itkThresholdSegmentationLevelSetImageFilter.txx" #include "itkUnsharpMaskLevelSetImageFilter.txx" #include "itkVectorFuzzyConnectednessImageFilter.txx" #include "itkVoronoiDiagram2D.txx" #include "itkVoronoiDiagram2DGenerator.txx" #include "itkVoronoiPartitioningImageFilter.txx" #include "itkVoronoiSegmentationImageFilter.txx" #include "itkVoronoiSegmentationImageFilterBase.txx" #include "itkVoronoiSegmentationRGBImageFilter.txx" #include "itkWatershedBoundary.txx" #include "itkWatershedBoundaryResolver.txx" #include "itkWatershedEquivalenceRelabeler.txx" #include "itkWatershedImageFilter.txx" #include "itkWatershedMiniPipelineProgressCommand.h" #include "itkWatershedRelabeler.txx" #include "itkWatershedSegmentTable.txx" #include "itkWatershedSegmentTree.txx" #include "itkWatershedSegmentTreeGenerator.txx" #include "itkWatershedSegmenter.txx" int main ( int , char* ) { return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAffineMutualInformationImageMetric.h" #include "itkBalloonForceFilter.h" #include "itkClassifier.h" #include "itkConnectedRegionsMeshFilter.h" #include "itkCurvatureFlowImageFilter.h" #include "itkDeformableMesh.h" #include "itkDynamicPolygonCell.h" #include "itkExtensionVelocitiesImageFilter.h" #include "itkFastMarchingExtensionImageFilter.h" #include "itkFastMarchingImageFilter.h" #include "itkFuzzyConnectednessImageFilter.h" #include "itkGaussianSupervisedClassifier.h" #include "itkGeodesicActiveContourImageFilter.h" #include "itkGibbsPriorFilter.h" #include "itkImageMomentsCalculator.h" #include "itkKLMRegionGrowImageFilter.h" #include "itkKLMSegmentationBorder.h" #include "itkKLMSegmentationRegion.h" #include "itkKMeansUnsupervisedClassifier.h" #include "itkKalmanLinearEstimator.h" #include "itkKernelFunction.h" #include "itkLevelSet.h" #include "itkLevelSetImageFilter.h" #include "itkLevelSetNeighborhoodExtractor.h" #include "itkLevelSetVelocityNeighborhoodExtractor.h" #include "itkMRFImageFilter.h" #include "itkMutualInformationAffineRegistrator.h" #include "itkMutualInformationImageMetric.h" #include "itkParzenWindowAffineMutualInformationMetric.h" #include "itkParzenWindowMutualInformationAffineRegistrator.h" #include "itkProcrustesRegistrationMetric.h" #include "itkRegionGrowImageFilter.h" #include "itkRegistrationMapper.h" #include "itkRegistrationMapperImage.h" #include "itkRegistrationMapperProcrustes.h" #include "itkRegistrationTransform.h" #include "itkReinitializeLevelSetImageFilter.h" #include "itkRelabelWatershedImageFilter.h" #include "itkSegmentationBorder.h" #include "itkSegmentationRegion.h" #include "itkShapeDetectionLevelSetFilter.h" #include "itkSimilarityRegistrationMetric.h" #include "itkSupervisedClassifier.h" #include "itkUnsupervisedClassifier.h" #include "itkVoronoi2DDiagram.h" #include "itkVoronoiSegmentationImageFilter.h" #include "itkWatershedImageFilter.h" int main ( int argc, char* argv ) { return 0; } <commit_msg>EHN: new classes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAffineMutualInformationImageMetric.h" #include "itkBalloonForceFilter.h" #include "itkClassifier.h" #include "itkConnectedRegionsMeshFilter.h" #include "itkCurvatureFlowImageFilter.h" #include "itkDeformableMesh.h" #include "itkDynamicPolygonCell.h" #include "itkExtensionVelocitiesImageFilter.h" #include "itkFastMarchingExtensionImageFilter.h" #include "itkFastMarchingImageFilter.h" #include "itkFuzzyConnectednessImageFilter.h" #include "itkFuzzyConnectednessRGBImageFilter.h" #include "itkGaussianSupervisedClassifier.h" #include "itkGeodesicActiveContourImageFilter.h" #include "itkGibbsPriorFilter.h" #include "itkImageMapper.h" #include "itkImageMomentsCalculator.h" #include "itkImageToImageAffineMeanSquaresRegistration.h" #include "itkImageToImageTranslationMeanSquaresRegistration.h" #include "itkKLMRegionGrowImageFilter.h" #include "itkKLMSegmentationBorder.h" #include "itkKLMSegmentationRegion.h" #include "itkKMeansUnsupervisedClassifier.h" #include "itkKalmanLinearEstimator.h" #include "itkKernelFunction.h" #include "itkLevelSet.h" #include "itkLevelSetImageFilter.h" #include "itkLevelSetNeighborhoodExtractor.h" #include "itkLevelSetVelocityNeighborhoodExtractor.h" #include "itkMRFImageFilter.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMutualInformationAffineRegistrator.h" #include "itkMutualInformationImageMetric.h" #include "itkParzenWindowAffineMutualInformationMetric.h" #include "itkParzenWindowMutualInformationAffineRegistrator.h" #include "itkProcrustesRegistrationMetric.h" #include "itkRegionGrowImageFilter.h" #include "itkRegistrationMapper.h" #include "itkRegistrationMapperImage.h" #include "itkRegistrationMapperProcrustes.h" #include "itkRegistrationTransform.h" #include "itkReinitializeLevelSetImageFilter.h" #include "itkRelabelWatershedImageFilter.h" #include "itkSegmentationBorder.h" #include "itkSegmentationRegion.h" #include "itkShapeDetectionLevelSetFilter.h" #include "itkSimilarityRegistrationMetric.h" #include "itkSupervisedClassifier.h" #include "itkUnsupervisedClassifier.h" #include "itkVoronoi2DDiagram.h" #include "itkVoronoiSegmentationImageFilter.h" #include "itkWatershedImageFilter.h" int main ( int argc, char* argv ) { return 0; } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_graphics /// \notebook /// This macro draws all the high definition palettes available in ROOT. /// It generates a png file for each palette and one pdf file, with a table of /// content, containing all the palettes /// /// \macro_image /// \macro_code /// /// \author Olivier Couet TCanvas *c; void draw_palette(int p, TString n){ delete c; c = new TCanvas("c","Contours",0,0,500,500); TF2 *f2 = new TF2("f2","0.1+(1-(x-2)*(x-2))*(1-(y-2)*(y-2))",0.999,3.002,0.999,3.002); f2->SetContour(99); gStyle->SetPalette(p); f2->SetLineWidth(1); f2->SetLineColor(kBlack); f2->Draw("surf1z"); // Title TPaveText *pt = new TPaveText(10,11,10,11,"blNDC"); pt->SetName("title"); pt->Draw(); TString num = n; num.ReplaceAll(" ",""); TLatex *l = new TLatex(-0.8704441,0.9779387,Form("Palette #%d: %s #scale[0.7]{(#font[82]{k%s})}",p,n.Data(),num.Data())); l->SetTextFont(42); l->SetTextSize(0.035); l->Draw(); c->Update(); c->Print(Form("palette_%d.png",p)); if (p==51) {c->Print("palettes.pdf(", Form("Title:%s",n.Data())); return;} if (p==111) {c->Print("palettes.pdf)", Form("Title:%s",n.Data())); return;} c->Print("palettes.pdf", Form("Title:%s",n.Data())); } void palettes() { gROOT->SetBatch(1); c = new TCanvas("c","Contours",0,0,500,500); draw_palette(kDeepSea, "Deap Sea"); draw_palette(kGreyScale, "Grey Scale"); draw_palette(kDarkBodyRadiator, "Dark Body Radiator"); draw_palette(kBlueYellow, "Blue Yellow"); draw_palette(kRainBow, "Rain Bow"); draw_palette(kInvertedDarkBodyRadiator, "Inverted Dark Body Radiator"); draw_palette(kBird, "Bird"); draw_palette(kCubehelix, "Cube helix"); draw_palette(kGreenRedViolet, "Green Red Violet"); draw_palette(kBlueRedYellow, "Blue Red Yellow"); draw_palette(kOcean, "Ocean"); draw_palette(kColorPrintableOnGrey, "Color Printable On Grey"); draw_palette(kAlpine, "Alpine"); draw_palette(kAquamarine, "Aquamarine"); draw_palette(kArmy, "Army"); draw_palette(kAtlantic, "Atlantic"); draw_palette(kAurora, "Aurora"); draw_palette(kAvocado, "Avocado"); draw_palette(kBeach, "Beach"); draw_palette(kBlackBody, "Black Body"); draw_palette(kBlueGreenYellow, "Blue Green Yellow"); draw_palette(kBrownCyan, "Brown Cyan"); draw_palette(kCMYK, "CMYK"); draw_palette(kCandy, "Candy"); draw_palette(kCherry, "Cherry"); draw_palette(kCoffee, "Coffee"); draw_palette(kDarkRainBow, "Dark Rain Bow"); draw_palette(kDarkTerrain, "Dark Terrain"); draw_palette(kFall, "Fall"); draw_palette(kFruitPunch, "Fruit Punch"); draw_palette(kFuchsia, "Fuchsia"); draw_palette(kGreyYellow, "Grey Yellow"); draw_palette(kGreenBrownTerrain, "Green Brown Terrain"); draw_palette(kGreenPink, "Green Pink"); draw_palette(kIsland, "Island"); draw_palette(kLake, "Lake"); draw_palette(kLightTemperature, "Light Temperature"); draw_palette(kLightTerrain, "Light Terrain"); draw_palette(kMint, "Mint"); draw_palette(kNeon, "Neon"); draw_palette(kPastel, "Pastel"); draw_palette(kPearl, "Pearl"); draw_palette(kPigeon, "Pigeon"); draw_palette(kPlum, "Plum"); draw_palette(kRedBlue, "Red Blue"); draw_palette(kRose, "Rose"); draw_palette(kRust, "Rust"); draw_palette(kSandyTerrain, "Sandy Terrain"); draw_palette(kSienna, "Sienna"); draw_palette(kSolar, "Solar"); draw_palette(kSouthWest, "South West"); draw_palette(kStarryNight, "Starry Night"); draw_palette(kSunset, "Sunset"); draw_palette(kTemperatureMap, "Temperature Map"); draw_palette(kThermometer, "Thermometer"); draw_palette(kValentine, "Valentine"); draw_palette(kVisibleSpectrum, "Visible Spectrum"); draw_palette(kWaterMelon, "Water Melon"); draw_palette(kCool, "Cool"); draw_palette(kCopper, "Copper"); draw_palette(kGistEarth, "Gist Earth"); draw_palette(kViridis, "Viridis"); draw_palette(kCividis, "Cividis"); } <commit_msg>Add a link to the list of palettes. As requested here in ROOT-10214<commit_after>/// \file /// \ingroup tutorial_graphics /// \notebook /// This macro draws all the high definition palettes available in ROOT. /// It generates a png file for each palette and one pdf file, with a table of /// content, containing all the palettes. /// /// In ROOT, [more than 60 high quality palettes are predefined with 255 colors each](https://root.cern/doc/master/classTColor.html#C06). /// /// These palettes can be accessed "by name" with `gStyle->SetPalette(num)`. num /// can be taken within the enum given in the previous link. As an example /// `gStyle->SetPalette(kCividis)` will select the following palette. /// /// \macro_image /// \macro_code /// /// \author Olivier Couet TCanvas *c; void draw_palette(int p, TString n){ delete c; c = new TCanvas("c","Contours",0,0,500,500); TF2 *f2 = new TF2("f2","0.1+(1-(x-2)*(x-2))*(1-(y-2)*(y-2))",0.999,3.002,0.999,3.002); f2->SetContour(99); gStyle->SetPalette(p); f2->SetLineWidth(1); f2->SetLineColor(kBlack); f2->Draw("surf1z"); // Title TPaveText *pt = new TPaveText(10,11,10,11,"blNDC"); pt->SetName("title"); pt->Draw(); TString num = n; num.ReplaceAll(" ",""); TLatex *l = new TLatex(-0.8704441,0.9779387,Form("Palette #%d: %s #scale[0.7]{(#font[82]{k%s})}",p,n.Data(),num.Data())); l->SetTextFont(42); l->SetTextSize(0.035); l->Draw(); c->Update(); c->Print(Form("palette_%d.png",p)); if (p==51) {c->Print("palettes.pdf(", Form("Title:%s",n.Data())); return;} if (p==111) {c->Print("palettes.pdf)", Form("Title:%s",n.Data())); return;} c->Print("palettes.pdf", Form("Title:%s",n.Data())); } void palettes() { gROOT->SetBatch(1); c = new TCanvas("c","Contours",0,0,500,500); draw_palette(kDeepSea, "Deap Sea"); draw_palette(kGreyScale, "Grey Scale"); draw_palette(kDarkBodyRadiator, "Dark Body Radiator"); draw_palette(kBlueYellow, "Blue Yellow"); draw_palette(kRainBow, "Rain Bow"); draw_palette(kInvertedDarkBodyRadiator, "Inverted Dark Body Radiator"); draw_palette(kBird, "Bird"); draw_palette(kCubehelix, "Cube helix"); draw_palette(kGreenRedViolet, "Green Red Violet"); draw_palette(kBlueRedYellow, "Blue Red Yellow"); draw_palette(kOcean, "Ocean"); draw_palette(kColorPrintableOnGrey, "Color Printable On Grey"); draw_palette(kAlpine, "Alpine"); draw_palette(kAquamarine, "Aquamarine"); draw_palette(kArmy, "Army"); draw_palette(kAtlantic, "Atlantic"); draw_palette(kAurora, "Aurora"); draw_palette(kAvocado, "Avocado"); draw_palette(kBeach, "Beach"); draw_palette(kBlackBody, "Black Body"); draw_palette(kBlueGreenYellow, "Blue Green Yellow"); draw_palette(kBrownCyan, "Brown Cyan"); draw_palette(kCMYK, "CMYK"); draw_palette(kCandy, "Candy"); draw_palette(kCherry, "Cherry"); draw_palette(kCoffee, "Coffee"); draw_palette(kDarkRainBow, "Dark Rain Bow"); draw_palette(kDarkTerrain, "Dark Terrain"); draw_palette(kFall, "Fall"); draw_palette(kFruitPunch, "Fruit Punch"); draw_palette(kFuchsia, "Fuchsia"); draw_palette(kGreyYellow, "Grey Yellow"); draw_palette(kGreenBrownTerrain, "Green Brown Terrain"); draw_palette(kGreenPink, "Green Pink"); draw_palette(kIsland, "Island"); draw_palette(kLake, "Lake"); draw_palette(kLightTemperature, "Light Temperature"); draw_palette(kLightTerrain, "Light Terrain"); draw_palette(kMint, "Mint"); draw_palette(kNeon, "Neon"); draw_palette(kPastel, "Pastel"); draw_palette(kPearl, "Pearl"); draw_palette(kPigeon, "Pigeon"); draw_palette(kPlum, "Plum"); draw_palette(kRedBlue, "Red Blue"); draw_palette(kRose, "Rose"); draw_palette(kRust, "Rust"); draw_palette(kSandyTerrain, "Sandy Terrain"); draw_palette(kSienna, "Sienna"); draw_palette(kSolar, "Solar"); draw_palette(kSouthWest, "South West"); draw_palette(kStarryNight, "Starry Night"); draw_palette(kSunset, "Sunset"); draw_palette(kTemperatureMap, "Temperature Map"); draw_palette(kThermometer, "Thermometer"); draw_palette(kValentine, "Valentine"); draw_palette(kVisibleSpectrum, "Visible Spectrum"); draw_palette(kWaterMelon, "Water Melon"); draw_palette(kCool, "Cool"); draw_palette(kCopper, "Copper"); draw_palette(kGistEarth, "Gist Earth"); draw_palette(kViridis, "Viridis"); draw_palette(kCividis, "Cividis"); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include <cmath> TEMPLATE_TEST_CASE_2("fast_matrix/max", "fast_matrix::max", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = max(a, 1.0); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 2.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("fast_matrix/min", "fast_matrix::min", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = min(a, 1.0); REQUIRE_EQUALS(d[0], -1.0); REQUIRE_EQUALS(d[1], 1.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("pow/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 0.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, 2); REQUIRE_EQUALS_APPROX(d[0], Z(1.0)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(0.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/1", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow((a >> a) + 1.0, 2); REQUIRE_EQUALS_APPROX(d[0], Z(4.0)); REQUIRE_EQUALS_APPROX(d[1], Z(25.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(4.0)); } TEMPLATE_TEST_CASE_2("pow/2", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow(a, 2.0); REQUIRE_EQUALS_APPROX(d[0], Z(1.0)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(0.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); } TEMPLATE_TEST_CASE_2("pow/3", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 9.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, -2.0); REQUIRE_EQUALS_APPROX(d[0], Z(1.0)); REQUIRE_EQUALS_APPROX(d[1], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0) / Z(81.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(1.0) / Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(1.0) / Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(1.0) / Z(36.0)); } TEMPLATE_TEST_CASE_2("pow_int/0", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 0.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_int(a, 2); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 4.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); REQUIRE_EQUALS(d[4], 4.0); REQUIRE_EQUALS(d[5], 16.0); REQUIRE_EQUALS(d[6], 25.0); REQUIRE_EQUALS(d[7], 36.0); } TEMPLATE_TEST_CASE_2("pow_int/1", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow_int((a >> a) + 1.0, 2); REQUIRE_EQUALS(d[0], 4.0); REQUIRE_EQUALS(d[1], 25.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 4.0); } <commit_msg>Review pow tests<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include <cmath> TEMPLATE_TEST_CASE_2("fast_matrix/max", "fast_matrix::max", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = max(a, 1.0); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 2.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("fast_matrix/min", "fast_matrix::min", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = min(a, 1.0); REQUIRE_EQUALS(d[0], -1.0); REQUIRE_EQUALS(d[1], 1.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); } TEMPLATE_TEST_CASE_2("pow/0", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.1, 2.0, 1.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(36.0)); } TEMPLATE_TEST_CASE_2("pow/1", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow((a >> a) + 1.0, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(4.0)); REQUIRE_EQUALS_APPROX(d[1], Z(25.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0)); REQUIRE_EQUALS_APPROX(d[3], Z(4.0)); } TEMPLATE_TEST_CASE_2("pow/2", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {0.1, 2.0, 0.5, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow(a, Z(2)); REQUIRE_EQUALS_APPROX(d[0], Z(0.01)); REQUIRE_EQUALS_APPROX(d[1], Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(0.25)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); } TEMPLATE_TEST_CASE_2("pow/3", "[fast][pow]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {0.01, 2.0, 9.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow(a, -2.0); REQUIRE_EQUALS_APPROX(d[0], Z(10000.0)); REQUIRE_EQUALS_APPROX(d[1], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[2], Z(1.0) / Z(81.0)); REQUIRE_EQUALS_APPROX(d[3], Z(1.0)); REQUIRE_EQUALS_APPROX(d[4], Z(1.0) / Z(4.0)); REQUIRE_EQUALS_APPROX(d[5], Z(1.0) / Z(16.0)); REQUIRE_EQUALS_APPROX(d[6], Z(1.0) / Z(25.0)); REQUIRE_EQUALS_APPROX(d[7], Z(1.0) / Z(36.0)); } TEMPLATE_TEST_CASE_2("pow_int/0", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 4> a = {-1.0, 2.0, 0.0, 1.0, 2.0, 4.0, 5.0, 6.0}; etl::fast_matrix<Z, 2, 4> d; d = pow_int(a, 2); REQUIRE_EQUALS(d[0], 1.0); REQUIRE_EQUALS(d[1], 4.0); REQUIRE_EQUALS(d[2], 0.0); REQUIRE_EQUALS(d[3], 1.0); REQUIRE_EQUALS(d[4], 4.0); REQUIRE_EQUALS(d[5], 16.0); REQUIRE_EQUALS(d[6], 25.0); REQUIRE_EQUALS(d[7], 36.0); } TEMPLATE_TEST_CASE_2("pow_int/1", "[fast][pow_int]", Z, float, double) { etl::fast_matrix<Z, 2, 2> a = {-1.0, 2.0, 0.0, 1.0}; etl::fast_matrix<Z, 2, 2> d; d = pow_int((a >> a) + 1.0, 2); REQUIRE_EQUALS(d[0], 4.0); REQUIRE_EQUALS(d[1], 25.0); REQUIRE_EQUALS(d[2], 1.0); REQUIRE_EQUALS(d[3], 4.0); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDijkstraImageContourLineInterpolator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDijkstraImageContourLineInterpolator.h" #include "vtkCellArray.h" #include "vtkCellLocator.h" #include "vtkContourRepresentation.h" #include "vtkDijkstraImageGeodesicPath.h" #include "vtkImageActor.h" #include "vtkImageActorPointPlacer.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkDijkstraImageContourLineInterpolator,"1.1"); vtkStandardNewMacro(vtkDijkstraImageContourLineInterpolator); //---------------------------------------------------------------------- vtkDijkstraImageContourLineInterpolator ::vtkDijkstraImageContourLineInterpolator() { this->DijkstraImageGeodesicPath = vtkDijkstraImageGeodesicPath::New(); this->CostImage = NULL; } //---------------------------------------------------------------------- vtkDijkstraImageContourLineInterpolator ::~vtkDijkstraImageContourLineInterpolator() { this->DijkstraImageGeodesicPath->Delete(); this->CostImage = NULL; } //---------------------------------------------------------------------------- void vtkDijkstraImageContourLineInterpolator::SetCostImage( vtkImageData *arg ) { if ( this->CostImage == arg ) { return; } this->CostImage = arg; if ( this->CostImage ) { this->DijkstraImageGeodesicPath->SetCostImage( this->CostImage ); } } //---------------------------------------------------------------------- int vtkDijkstraImageContourLineInterpolator::InterpolateLine( vtkRenderer* vtkNotUsed(ren), vtkContourRepresentation *rep, int idx1, int idx2 ) { vtkImageActorPointPlacer *placer = vtkImageActorPointPlacer::SafeDownCast(rep->GetPointPlacer()); if ( !placer ) { return 1; } // if the user didn't set the image, try to get it from the actor if ( !this->CostImage ) { vtkImageActor* actor = placer->GetImageActor(); if ( !actor || !(this->CostImage = actor->GetInput()) ) { return 1; } this->DijkstraImageGeodesicPath->SetCostImage( this->CostImage ); } double p1[3], p2[3]; rep->GetNthNodeWorldPosition( idx1, p1 ); rep->GetNthNodeWorldPosition( idx2, p2 ); vtkIdType beginVertId = this->CostImage->FindPoint( p1 ); vtkIdType endVertId = this->CostImage->FindPoint( p2 ); // Could not find the starting and ending cells. We can't interpolate. if ( beginVertId == -1 || endVertId == -1 ) { return 0; } // In some implementations, a vtkPolyData is not necessary for the // interpolator, but is still required for the filter. if ( !this->DijkstraImageGeodesicPath->GetInput() ) { vtkPolyData* dummy = vtkPolyData::New(); this->DijkstraImageGeodesicPath->SetInput(dummy); dummy->Delete(); } this->DijkstraImageGeodesicPath->SetStartVertex( endVertId ); this->DijkstraImageGeodesicPath->SetEndVertex( beginVertId ); this->DijkstraImageGeodesicPath->Update(); vtkPolyData *pd = this->DijkstraImageGeodesicPath->GetOutput(); vtkIdType npts = 0, *pts = NULL; pd->GetLines()->InitTraversal(); pd->GetLines()->GetNextCell( npts, pts ); for ( int i = 0; i < npts; ++i ) { rep->AddIntermediatePointWorldPosition( idx1, pd->GetPoint( pts[i] ) ); } return 1; } //---------------------------------------------------------------------- void vtkDijkstraImageContourLineInterpolator::PrintSelf( ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } <commit_msg>BUG: fix printself defect<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDijkstraImageContourLineInterpolator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDijkstraImageContourLineInterpolator.h" #include "vtkCellArray.h" #include "vtkCellLocator.h" #include "vtkContourRepresentation.h" #include "vtkDijkstraImageGeodesicPath.h" #include "vtkImageActor.h" #include "vtkImageActorPointPlacer.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkDijkstraImageContourLineInterpolator,"1.2"); vtkStandardNewMacro(vtkDijkstraImageContourLineInterpolator); //---------------------------------------------------------------------- vtkDijkstraImageContourLineInterpolator ::vtkDijkstraImageContourLineInterpolator() { this->DijkstraImageGeodesicPath = vtkDijkstraImageGeodesicPath::New(); this->CostImage = NULL; } //---------------------------------------------------------------------- vtkDijkstraImageContourLineInterpolator ::~vtkDijkstraImageContourLineInterpolator() { this->DijkstraImageGeodesicPath->Delete(); this->CostImage = NULL; } //---------------------------------------------------------------------------- void vtkDijkstraImageContourLineInterpolator::SetCostImage( vtkImageData *arg ) { if ( this->CostImage == arg ) { return; } this->CostImage = arg; if ( this->CostImage ) { this->DijkstraImageGeodesicPath->SetCostImage( this->CostImage ); } } //---------------------------------------------------------------------- int vtkDijkstraImageContourLineInterpolator::InterpolateLine( vtkRenderer* vtkNotUsed(ren), vtkContourRepresentation *rep, int idx1, int idx2 ) { vtkImageActorPointPlacer *placer = vtkImageActorPointPlacer::SafeDownCast(rep->GetPointPlacer()); if ( !placer ) { return 1; } // if the user didn't set the image, try to get it from the actor if ( !this->CostImage ) { vtkImageActor* actor = placer->GetImageActor(); if ( !actor || !(this->CostImage = actor->GetInput()) ) { return 1; } this->DijkstraImageGeodesicPath->SetCostImage( this->CostImage ); } double p1[3], p2[3]; rep->GetNthNodeWorldPosition( idx1, p1 ); rep->GetNthNodeWorldPosition( idx2, p2 ); vtkIdType beginVertId = this->CostImage->FindPoint( p1 ); vtkIdType endVertId = this->CostImage->FindPoint( p2 ); // Could not find the starting and ending cells. We can't interpolate. if ( beginVertId == -1 || endVertId == -1 ) { return 0; } // In some implementations, a vtkPolyData is not necessary for the // interpolator, but is still required for the filter. if ( !this->DijkstraImageGeodesicPath->GetInput() ) { vtkPolyData* dummy = vtkPolyData::New(); this->DijkstraImageGeodesicPath->SetInput(dummy); dummy->Delete(); } this->DijkstraImageGeodesicPath->SetStartVertex( endVertId ); this->DijkstraImageGeodesicPath->SetEndVertex( beginVertId ); this->DijkstraImageGeodesicPath->Update(); vtkPolyData *pd = this->DijkstraImageGeodesicPath->GetOutput(); vtkIdType npts = 0, *pts = NULL; pd->GetLines()->InitTraversal(); pd->GetLines()->GetNextCell( npts, pts ); for ( int i = 0; i < npts; ++i ) { rep->AddIntermediatePointWorldPosition( idx1, pd->GetPoint( pts[i] ) ); } return 1; } //---------------------------------------------------------------------- void vtkDijkstraImageContourLineInterpolator::PrintSelf( ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "DijkstraImageGeodesicPath: " << this->DijkstraImageGeodesicPath << endl; os << indent << "CostImage: " << this->GetCostImage() << endl; } <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "itkAnisotropicDiffusiveRegistrationFilter.h" #include "itkImageLinearIteratorWithIndex.h" #include "itkImageFileWriter.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #include "vtkPlaneSource.h" #include "vtkPolyDataNormals.h" #include "vtkSmartPointer.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkPolyDataWriter.h" int itkAnisotropicDiffusiveRegistrationRegularizationTest( int argc, char* argv [] ) { if( argc < 7 ) { std::cerr << "Missing arguments." << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << "smoothed motion field image, " << "noise variance, " << "border slope, " << "number of iterations, " << "time step, " << "should use anisotropic regularization" << std::endl; return EXIT_FAILURE; } // Typedefs const unsigned int Dimension = 3; typedef double PixelType; typedef double VectorScalarType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::Vector< VectorScalarType, Dimension > VectorType; typedef itk::Image< VectorType, Dimension > VectorImageType; typedef itk::Image< VectorType, Dimension > DeformationFieldType; typedef itk::ImageRegionIterator< DeformationFieldType > IteratorType; typedef itk::Index< Dimension > IndexType; // Image parameters int startValue = 0; int sizeValue = 10; double spacingValue = 1.0; double originValue = 0.0; // Allocate the motion field image DeformationFieldType::Pointer deformationField = DeformationFieldType::New(); DeformationFieldType::IndexType start; start.Fill( startValue ); DeformationFieldType::SizeType size; size.Fill( sizeValue ); DeformationFieldType::RegionType region; region.SetSize( size ); region.SetIndex( start ); DeformationFieldType::SpacingType spacing; spacing.Fill( spacingValue ); DeformationFieldType::PointType origin; origin.Fill( originValue); deformationField->SetRegions( region ); deformationField->SetSpacing( spacing ); deformationField->SetOrigin( origin ); deformationField->Allocate(); // Fill the motion field image: // Top half has vectors like \, bottom half has vectors like /, // with additional noise PixelType borderSlope; VectorType borderN( 0.0 ); // normal to the border VectorType perpN; // perpendicular to the border borderSlope = atof( argv[3] ); if( borderSlope == 0 ) { borderN[0] = 0.0; borderN[1] = 1.0; borderN[0] = 0.0; perpN[0] = 1.0; perpN[1] = 0.0; perpN[2] = 0.0; } else { borderN[0] = -1.0; borderN[1] = 1.0 / borderSlope; borderN[2] = 0.0; perpN[0] = -1.0 / borderSlope; perpN[1] = -1.0; perpN[2] = 0.0; } // Normalize the normals borderN = borderN / borderN.GetNorm(); perpN = perpN / perpN.GetNorm(); VectorType topHalfPixel; VectorType bottomHalfPixel; topHalfPixel = borderN + perpN; bottomHalfPixel = borderN - perpN; // The index at the center of the image is on the plane VectorType center; for( unsigned int i = 0; i < Dimension; i++ ) { center[i] = deformationField->GetLargestPossibleRegion().GetSize()[i] / 2.0; } // Create the polydata for the surface vtkSmartPointer< vtkPlaneSource > plane = vtkPlaneSource::New(); plane->SetCenter( center[0], center[1], center[2] ); plane->SetNormal( borderN[0], borderN[1], borderN[2] ); plane->Update(); VectorType pixel; IteratorType it( deformationField, deformationField->GetLargestPossibleRegion() ); IndexType index; VectorType indexAsVector; itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randGenerator->Initialize( 137593424 ); PixelType randX = 0; PixelType randY = 0; PixelType randZ = 0; double mean = 0; double variance = atof(argv[2]); for( it.GoToBegin(); ! it.IsAtEnd(); ++it ) { index = it.GetIndex(); for( unsigned int i = 0; i < Dimension; i++ ) { indexAsVector[i] = index[i]; } // Use definition of a plane to decide which side we are on if ( borderN * ( center - indexAsVector ) < 0 ) { pixel = bottomHalfPixel; } else { pixel = topHalfPixel; } // Add random noise randX = randGenerator->GetNormalVariate( mean, variance ); randY = randGenerator->GetNormalVariate( mean, variance ); randZ = randGenerator->GetNormalVariate( mean, variance ); pixel[0] += randX; pixel[1] += randY; pixel[2] += randZ; it.Set(pixel); } // Setup the images to be registered FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); fixedImage->SetRegions( region ); fixedImage->SetSpacing( spacing ); fixedImage->SetOrigin( origin ); fixedImage->Allocate(); fixedImage->FillBuffer(0.0); movingImage->SetRegions( region ); movingImage->SetSpacing( spacing ); movingImage->SetOrigin( origin ); movingImage->Allocate(); movingImage->FillBuffer(0.0); // Setup the registrator object typedef itk::DiffusiveRegistrationFilter < FixedImageType, MovingImageType, DeformationFieldType > DiffusiveRegistrationFilterType; typedef itk::AnisotropicDiffusiveRegistrationFilter < FixedImageType, MovingImageType, DeformationFieldType > AnisotropicDiffusiveRegistrationFilterType; DiffusiveRegistrationFilterType::Pointer registrator = 0; AnisotropicDiffusiveRegistrationFilterType::Pointer anisotropicRegistrator = 0; int useAnisotropic = atoi( argv[6] ); if( useAnisotropic ) { registrator = AnisotropicDiffusiveRegistrationFilterType::New(); anisotropicRegistrator = dynamic_cast < AnisotropicDiffusiveRegistrationFilterType * >( registrator.GetPointer() ); } else { registrator = DiffusiveRegistrationFilterType::New(); } registrator->SetInitialDisplacementField( deformationField ); registrator->SetMovingImage( movingImage ); registrator->SetFixedImage( fixedImage ); // because we are just doing motion field regularization in this test: registrator->SetComputeIntensityDistanceTerm( false ); registrator->SetTimeStep( atof( argv[5] ) ); registrator->SetNumberOfIterations( atoi( argv[4] ) ); if( anisotropicRegistrator ) { anisotropicRegistrator->SetBorderSurface( plane->GetOutput() ); } // Save the smoothed deformation field typedef itk::ImageFileWriter< DeformationFieldType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[1] ); writer->SetInput( registrator->GetOutput() ); writer->SetUseCompression( true ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Exception caught: " << err << std::endl; return EXIT_FAILURE; } // Check to make sure the border normals were calculated correctly by the // registrator if( anisotropicRegistrator ) { vtkPolyData * normalPolyData = anisotropicRegistrator->GetBorderSurface(); vtkSmartPointer< vtkDataArray > normalData = normalPolyData->GetPointData()->GetNormals(); // test to make sure the extracted normals match the known normals double ep = 0.00005; double test[3]; for( int i = 0; i < normalData->GetNumberOfTuples(); i++ ) { normalData->GetTuple( i, test ); if( fabs( test[0] - borderN[0] ) > ep || fabs( test[1] - borderN[1] ) > ep || fabs( test[2] - borderN[2] ) > ep ) { std::cerr << "index i=" << i << ": extracted normal [" << test[0] << " " << test[1] << " " << test[2] << "]" << std::endl; std::cerr << "does not match known border normal [" << borderN[0] << " " << borderN[1] << " " << borderN[2] << "]" << std::endl; return EXIT_FAILURE; } } if( plane->GetOutput()->GetPointData()->GetNumberOfTuples() != normalPolyData->GetPointData()->GetNumberOfTuples() ) { std::cerr << "number of tuples in original plane does not match number of " << "tuples in border normal" << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } <commit_msg>BUG: Fix memory leak in itkAnisotropicDiffusiveRegistrationRegularizationTest<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "itkAnisotropicDiffusiveRegistrationFilter.h" #include "itkImageLinearIteratorWithIndex.h" #include "itkImageFileWriter.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #include "vtkPlaneSource.h" #include "vtkPolyDataNormals.h" #include "vtkSmartPointer.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkPolyDataWriter.h" int itkAnisotropicDiffusiveRegistrationRegularizationTest( int argc, char* argv [] ) { if( argc < 7 ) { std::cerr << "Missing arguments." << std::endl; std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << "smoothed motion field image, " << "noise variance, " << "border slope, " << "number of iterations, " << "time step, " << "should use anisotropic regularization" << std::endl; return EXIT_FAILURE; } // Typedefs const unsigned int Dimension = 3; typedef double PixelType; typedef double VectorScalarType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::Vector< VectorScalarType, Dimension > VectorType; typedef itk::Image< VectorType, Dimension > VectorImageType; typedef itk::Image< VectorType, Dimension > DeformationFieldType; typedef itk::ImageRegionIterator< DeformationFieldType > IteratorType; typedef itk::Index< Dimension > IndexType; // Image parameters int startValue = 0; int sizeValue = 10; double spacingValue = 1.0; double originValue = 0.0; // Allocate the motion field image DeformationFieldType::Pointer deformationField = DeformationFieldType::New(); DeformationFieldType::IndexType start; start.Fill( startValue ); DeformationFieldType::SizeType size; size.Fill( sizeValue ); DeformationFieldType::RegionType region; region.SetSize( size ); region.SetIndex( start ); DeformationFieldType::SpacingType spacing; spacing.Fill( spacingValue ); DeformationFieldType::PointType origin; origin.Fill( originValue); deformationField->SetRegions( region ); deformationField->SetSpacing( spacing ); deformationField->SetOrigin( origin ); deformationField->Allocate(); // Fill the motion field image: // Top half has vectors like \, bottom half has vectors like /, // with additional noise PixelType borderSlope; VectorType borderN( 0.0 ); // normal to the border VectorType perpN; // perpendicular to the border borderSlope = atof( argv[3] ); if( borderSlope == 0 ) { borderN[0] = 0.0; borderN[1] = 1.0; borderN[0] = 0.0; perpN[0] = 1.0; perpN[1] = 0.0; perpN[2] = 0.0; } else { borderN[0] = -1.0; borderN[1] = 1.0 / borderSlope; borderN[2] = 0.0; perpN[0] = -1.0 / borderSlope; perpN[1] = -1.0; perpN[2] = 0.0; } // Normalize the normals borderN = borderN / borderN.GetNorm(); perpN = perpN / perpN.GetNorm(); VectorType topHalfPixel; VectorType bottomHalfPixel; topHalfPixel = borderN + perpN; bottomHalfPixel = borderN - perpN; // The index at the center of the image is on the plane VectorType center; for( unsigned int i = 0; i < Dimension; i++ ) { center[i] = deformationField->GetLargestPossibleRegion().GetSize()[i] / 2.0; } // Create the polydata for the surface vtkSmartPointer< vtkPlaneSource > plane = vtkSmartPointer< vtkPlaneSource >::New(); plane->SetCenter( center[0], center[1], center[2] ); plane->SetNormal( borderN[0], borderN[1], borderN[2] ); plane->Update(); VectorType pixel; IteratorType it( deformationField, deformationField->GetLargestPossibleRegion() ); IndexType index; VectorType indexAsVector; itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randGenerator->Initialize( 137593424 ); PixelType randX = 0; PixelType randY = 0; PixelType randZ = 0; double mean = 0; double variance = atof(argv[2]); for( it.GoToBegin(); ! it.IsAtEnd(); ++it ) { index = it.GetIndex(); for( unsigned int i = 0; i < Dimension; i++ ) { indexAsVector[i] = index[i]; } // Use definition of a plane to decide which side we are on if ( borderN * ( center - indexAsVector ) < 0 ) { pixel = bottomHalfPixel; } else { pixel = topHalfPixel; } // Add random noise randX = randGenerator->GetNormalVariate( mean, variance ); randY = randGenerator->GetNormalVariate( mean, variance ); randZ = randGenerator->GetNormalVariate( mean, variance ); pixel[0] += randX; pixel[1] += randY; pixel[2] += randZ; it.Set(pixel); } // Setup the images to be registered FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); fixedImage->SetRegions( region ); fixedImage->SetSpacing( spacing ); fixedImage->SetOrigin( origin ); fixedImage->Allocate(); fixedImage->FillBuffer(0.0); movingImage->SetRegions( region ); movingImage->SetSpacing( spacing ); movingImage->SetOrigin( origin ); movingImage->Allocate(); movingImage->FillBuffer(0.0); // Setup the registrator object typedef itk::DiffusiveRegistrationFilter < FixedImageType, MovingImageType, DeformationFieldType > DiffusiveRegistrationFilterType; typedef itk::AnisotropicDiffusiveRegistrationFilter < FixedImageType, MovingImageType, DeformationFieldType > AnisotropicDiffusiveRegistrationFilterType; DiffusiveRegistrationFilterType::Pointer registrator = 0; AnisotropicDiffusiveRegistrationFilterType::Pointer anisotropicRegistrator = 0; int useAnisotropic = atoi( argv[6] ); if( useAnisotropic ) { registrator = AnisotropicDiffusiveRegistrationFilterType::New(); anisotropicRegistrator = dynamic_cast < AnisotropicDiffusiveRegistrationFilterType * >( registrator.GetPointer() ); } else { registrator = DiffusiveRegistrationFilterType::New(); } registrator->SetInitialDisplacementField( deformationField ); registrator->SetMovingImage( movingImage ); registrator->SetFixedImage( fixedImage ); // because we are just doing motion field regularization in this test: registrator->SetComputeIntensityDistanceTerm( false ); registrator->SetTimeStep( atof( argv[5] ) ); registrator->SetNumberOfIterations( atoi( argv[4] ) ); if( anisotropicRegistrator ) { anisotropicRegistrator->SetBorderSurface( plane->GetOutput() ); } // Save the smoothed deformation field typedef itk::ImageFileWriter< DeformationFieldType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[1] ); writer->SetInput( registrator->GetOutput() ); writer->SetUseCompression( true ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Exception caught: " << err << std::endl; return EXIT_FAILURE; } // Check to make sure the border normals were calculated correctly by the // registrator if( anisotropicRegistrator ) { vtkPolyData * normalPolyData = anisotropicRegistrator->GetBorderSurface(); vtkSmartPointer< vtkDataArray > normalData = normalPolyData->GetPointData()->GetNormals(); // test to make sure the extracted normals match the known normals double ep = 0.00005; double test[3]; for( int i = 0; i < normalData->GetNumberOfTuples(); i++ ) { normalData->GetTuple( i, test ); if( fabs( test[0] - borderN[0] ) > ep || fabs( test[1] - borderN[1] ) > ep || fabs( test[2] - borderN[2] ) > ep ) { std::cerr << "index i=" << i << ": extracted normal [" << test[0] << " " << test[1] << " " << test[2] << "]" << std::endl; std::cerr << "does not match known border normal [" << borderN[0] << " " << borderN[1] << " " << borderN[2] << "]" << std::endl; return EXIT_FAILURE; } } if( plane->GetOutput()->GetPointData()->GetNumberOfTuples() != normalPolyData->GetPointData()->GetNumberOfTuples() ) { std::cerr << "number of tuples in original plane does not match number of " << "tuples in border normal" << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE TestCuFFT #include "libraries/cufft/cufft_helper.hpp" #include <boost/test/unit_test.hpp> #include <iostream> using namespace gearshifft::CuFFT; BOOST_AUTO_TEST_CASE( Device ) { int nr=0; try { CHECK_CUDA( cudaGetDeviceCount(&nr) ); for( auto i=0; i<nr; ++i ) { CHECK_CUDA( cudaSetDevice(i) ); CHECK_CUDA( cudaDeviceReset() ); } }catch(const std::runtime_error& e){ BOOST_FAIL("CUDA Error: " << e.what()); } BOOST_CHECK( true ); } BOOST_AUTO_TEST_CASE( CuFFT_Single ) { cufftComplex* data = nullptr; cufftComplex* data_transform = nullptr; cufftHandle plan = 0; CHECK_CUDA( cudaSetDevice(0) ); std::vector< std::array<size_t, 1> > vec_extents; std::array<size_t, 1> e0 = {{128}}; std::array<size_t, 1> e1 = {{125}}; std::array<size_t, 1> e2 = {{169}}; std::array<size_t, 1> e3 = {{170}}; vec_extents.push_back( e0 ); vec_extents.push_back( e1 ); vec_extents.push_back( e2 ); vec_extents.push_back( e3 ); for( auto extents : vec_extents ) { size_t data_size = extents[0]*sizeof(cufftComplex); size_t data_transform_size = extents[0]*sizeof(cufftComplex); size_t s = 0; try { CHECK_CUDA( cudaMalloc(&data, data_size)); CHECK_CUDA( cudaMalloc(&data_transform, data_transform_size)); CHECK_CUDA( cufftPlan1d(&plan, extents[0], CUFFT_C2C, 1)); CHECK_CUDA( cufftExecC2C(plan, data, data_transform, CUFFT_FORWARD)); CHECK_CUDA( cufftExecC2C(plan, data_transform, data, CUFFT_INVERSE)); CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); CHECK_CUDA( cufftDestroy(plan) ); plan = 0; }catch(std::runtime_error& e){ // cleanup #1 CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); if(plan) { CHECK_CUDA( cufftDestroy(plan) ); plan=0; } BOOST_ERROR("Error for nx="<<extents[0]<<": "<<e.what()); } } CHECK_CUDA( cudaDeviceReset() ); BOOST_CHECK( true ); } BOOST_AUTO_TEST_CASE( CuFFT_Double ) { cufftDoubleComplex* data = nullptr; cufftDoubleComplex* data_transform = nullptr; cufftHandle plan = 0; CHECK_CUDA( cudaSetDevice(0) ); std::vector< std::array<size_t, 1> > vec_extents; std::array<size_t, 1> e0 = {{128}}; std::array<size_t, 1> e1 = {{125}}; std::array<size_t, 1> e2 = {{169}}; std::array<size_t, 1> e3 = {{170}}; vec_extents.push_back( e0 ); vec_extents.push_back( e1 ); vec_extents.push_back( e2 ); vec_extents.push_back( e3 ); for( auto extents : vec_extents ) { size_t data_size = extents[0]*sizeof(cufftDoubleComplex); size_t data_transform_size = extents[0]*sizeof(cufftDoubleComplex); size_t s = 0; try { CHECK_CUDA( cudaMalloc(&data, data_size)); CHECK_CUDA( cudaMalloc(&data_transform, data_transform_size)); CHECK_CUDA( cufftPlan1d(&plan, extents[0], CUFFT_Z2Z, 1)); CHECK_CUDA( cufftExecZ2Z(plan, data, data_transform, CUFFT_FORWARD)); CHECK_CUDA( cufftExecZ2Z(plan, data_transform, data, CUFFT_INVERSE)); CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); CHECK_CUDA( cufftDestroy(plan) ); plan = 0; }catch(std::runtime_error& e){ // cleanup #1 CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); if(plan) { CHECK_CUDA( cufftDestroy(plan) ); plan=0; } BOOST_ERROR("Error for nx="<<extents[0]<<": "<<e.what()); } } CHECK_CUDA( cudaDeviceReset() ); BOOST_CHECK( true ); } <commit_msg>Removes unused variable s.<commit_after>#define BOOST_TEST_MODULE TestCuFFT #include "libraries/cufft/cufft_helper.hpp" #include <boost/test/unit_test.hpp> #include <iostream> using namespace gearshifft::CuFFT; BOOST_AUTO_TEST_CASE( Device ) { int nr=0; try { CHECK_CUDA( cudaGetDeviceCount(&nr) ); for( auto i=0; i<nr; ++i ) { CHECK_CUDA( cudaSetDevice(i) ); CHECK_CUDA( cudaDeviceReset() ); } }catch(const std::runtime_error& e){ BOOST_FAIL("CUDA Error: " << e.what()); } BOOST_CHECK( true ); } BOOST_AUTO_TEST_CASE( CuFFT_Single ) { cufftComplex* data = nullptr; cufftComplex* data_transform = nullptr; cufftHandle plan = 0; CHECK_CUDA( cudaSetDevice(0) ); std::vector< std::array<size_t, 1> > vec_extents; std::array<size_t, 1> e0 = {{128}}; std::array<size_t, 1> e1 = {{125}}; std::array<size_t, 1> e2 = {{169}}; std::array<size_t, 1> e3 = {{170}}; vec_extents.push_back( e0 ); vec_extents.push_back( e1 ); vec_extents.push_back( e2 ); vec_extents.push_back( e3 ); for( auto extents : vec_extents ) { size_t data_size = extents[0]*sizeof(cufftComplex); size_t data_transform_size = extents[0]*sizeof(cufftComplex); try { CHECK_CUDA( cudaMalloc(&data, data_size)); CHECK_CUDA( cudaMalloc(&data_transform, data_transform_size)); CHECK_CUDA( cufftPlan1d(&plan, extents[0], CUFFT_C2C, 1)); CHECK_CUDA( cufftExecC2C(plan, data, data_transform, CUFFT_FORWARD)); CHECK_CUDA( cufftExecC2C(plan, data_transform, data, CUFFT_INVERSE)); CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); CHECK_CUDA( cufftDestroy(plan) ); plan = 0; }catch(std::runtime_error& e){ // cleanup #1 CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); if(plan) { CHECK_CUDA( cufftDestroy(plan) ); plan=0; } BOOST_ERROR("Error for nx="<<extents[0]<<": "<<e.what()); } } CHECK_CUDA( cudaDeviceReset() ); BOOST_CHECK( true ); } BOOST_AUTO_TEST_CASE( CuFFT_Double ) { cufftDoubleComplex* data = nullptr; cufftDoubleComplex* data_transform = nullptr; cufftHandle plan = 0; CHECK_CUDA( cudaSetDevice(0) ); std::vector< std::array<size_t, 1> > vec_extents; std::array<size_t, 1> e0 = {{128}}; std::array<size_t, 1> e1 = {{125}}; std::array<size_t, 1> e2 = {{169}}; std::array<size_t, 1> e3 = {{170}}; vec_extents.push_back( e0 ); vec_extents.push_back( e1 ); vec_extents.push_back( e2 ); vec_extents.push_back( e3 ); for( auto extents : vec_extents ) { size_t data_size = extents[0]*sizeof(cufftDoubleComplex); size_t data_transform_size = extents[0]*sizeof(cufftDoubleComplex); try { CHECK_CUDA( cudaMalloc(&data, data_size)); CHECK_CUDA( cudaMalloc(&data_transform, data_transform_size)); CHECK_CUDA( cufftPlan1d(&plan, extents[0], CUFFT_Z2Z, 1)); CHECK_CUDA( cufftExecZ2Z(plan, data, data_transform, CUFFT_FORWARD)); CHECK_CUDA( cufftExecZ2Z(plan, data_transform, data, CUFFT_INVERSE)); CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); CHECK_CUDA( cufftDestroy(plan) ); plan = 0; }catch(std::runtime_error& e){ // cleanup #1 CHECK_CUDA( cudaFree(data) ); CHECK_CUDA( cudaFree(data_transform) ); if(plan) { CHECK_CUDA( cufftDestroy(plan) ); plan=0; } BOOST_ERROR("Error for nx="<<extents[0]<<": "<<e.what()); } } CHECK_CUDA( cudaDeviceReset() ); BOOST_CHECK( true ); } <|endoftext|>
<commit_before>/** * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia * Author: Silvio Traversaro * website: http://www.codyco.eu */ #include "kdl_codyco/crba_loops.hpp" #include <kdl/kinfam.hpp> #include <kdl_codyco/regressor_utils.hpp> #include "kdl_codyco/undirectedtree.hpp" #ifndef NDEBUG #include <iostream> #endif #include <Eigen/Core> namespace KDL { namespace CoDyCo { int crba_fixed_base_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, JntSpaceInertiaMatrix & H) { double q_; Wrench F; //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index] = link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } Ic[parent_index] = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; H(dof_id,dof_id) = dot(S_link_parent,F); { assert(parent_it != undirected_tree.getInvalidLinkIterator()); double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while( true ) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } Twist S_successor_predecessor = predecessor_it->S(successor_it,q__); if( dof_id_ >= 0 ) { H(dof_id_,dof_id) = dot(S_successor_predecessor,F); H(dof_id,dof_id_) = H(dof_id_,dof_id); } } } } } return 0; } int crba_floating_base_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, FloatingJntSpaceInertiaMatrix & H) { double q_; Wrench F = Wrench::Zero(); //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index]=link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } RigidBodyInertia buf; buf = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; Ic[parent_index] = buf; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; H(6+dof_id,6+dof_id) = dot(S_link_parent,F); if( traversal.getParentLink(link_it) != undirected_tree.getInvalidLinkIterator() ) { double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while(true) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } #ifndef NDEBUG std::cout << "F migrated from frame " << successor_it->getLinkIndex() << " to frame " << successor_it->getLinkIndex() << std::endl; #endif F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } Twist S_successor_predecessor = predecessor_it->S(successor_it,q__); if( dof_id_ >= 0 ) { H(6+dof_id_,6+dof_id) = dot(S_successor_predecessor,F); H(6+dof_id,6+dof_id_) = H(6+dof_id_,6+dof_id); } } if( dof_id >= 0 ) { H.data.block(0,6+dof_id,6,1) = toEigen(F); H.data.block(6+dof_id,0,1,6) = toEigen(F).transpose(); } } } } //The first 6x6 submatrix of the FlotingBase Inertia Matrix are simply the spatial inertia //of all the structure expressed in the base reference frame H.data.block(0,0,6,6) = toEigen(Ic[traversal.getBaseLink()->getLinkIndex()]); return 0; } int crba_momentum_jacobian_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, MomentumJacobian & H, RigidBodyInertia & InertiaCOM ) { #ifndef NDEBUG if( undirected_tree.getNrOfLinks() != traversal.getNrOfVisitedLinks() || undirected_tree.getNrOfDOFs() != q.rows() || Ic.size() != undirected_tree.getNrOfLinks() || H.columns() != (undirected_tree.getNrOfDOFs() + 6) ) { std::cerr << "crba_momentum_jacobian_loop: input data error" << std::endl; return -1; } #endif double q_; Wrench F = Wrench::Zero(); //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index]=link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } Ic[parent_index] = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; if( traversal.getParentLink(link_it) != undirected_tree.getInvalidLinkIterator() ) { double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while(true) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } } if( dof_id >= 0 ) { H.data.block(0,6+dof_id,6,1) = toEigen(F); } //The first 6x6 submatrix of the Momentum Jacobian are simply the spatial inertia //of all the structure expressed in the base reference frame H.data.block(0,0,6,6) = toEigen(Ic[traversal.getBaseLink()->getLinkIndex()]); } } } //We have then to translate the reference point of the obtained jacobian to the com //The Ic[traversal.order[0]->getLink(index)] contain the spatial inertial of all the tree //expressed in link coordite frames Vector com = Ic[traversal.getBaseLink()->getLinkIndex()].getCOG(); H.changeRefPoint(com); InertiaCOM = Frame(com)*Ic[traversal.getBaseLink()->getLinkIndex()]; return 0; } } } <commit_msg>removed debug message<commit_after>/** * Copyright (C) 2013 IIT - Istituto Italiano di Tecnologia * Author: Silvio Traversaro * website: http://www.codyco.eu */ #include "kdl_codyco/crba_loops.hpp" #include <kdl/kinfam.hpp> #include <kdl_codyco/regressor_utils.hpp> #include "kdl_codyco/undirectedtree.hpp" #ifndef NDEBUG #include <iostream> #endif #include <Eigen/Core> namespace KDL { namespace CoDyCo { int crba_fixed_base_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, JntSpaceInertiaMatrix & H) { double q_; Wrench F; //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index] = link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } Ic[parent_index] = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; H(dof_id,dof_id) = dot(S_link_parent,F); { assert(parent_it != undirected_tree.getInvalidLinkIterator()); double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while( true ) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } Twist S_successor_predecessor = predecessor_it->S(successor_it,q__); if( dof_id_ >= 0 ) { H(dof_id_,dof_id) = dot(S_successor_predecessor,F); H(dof_id,dof_id_) = H(dof_id_,dof_id); } } } } } return 0; } int crba_floating_base_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, FloatingJntSpaceInertiaMatrix & H) { double q_; Wrench F = Wrench::Zero(); //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index]=link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } RigidBodyInertia buf; buf = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; Ic[parent_index] = buf; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; H(6+dof_id,6+dof_id) = dot(S_link_parent,F); if( traversal.getParentLink(link_it) != undirected_tree.getInvalidLinkIterator() ) { double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while(true) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } #ifndef NDEBUG //std::cout << "F migrated from frame " << successor_it->getLinkIndex() << " to frame " << successor_it->getLinkIndex() << std::endl; #endif F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } Twist S_successor_predecessor = predecessor_it->S(successor_it,q__); if( dof_id_ >= 0 ) { H(6+dof_id_,6+dof_id) = dot(S_successor_predecessor,F); H(6+dof_id,6+dof_id_) = H(6+dof_id_,6+dof_id); } } if( dof_id >= 0 ) { H.data.block(0,6+dof_id,6,1) = toEigen(F); H.data.block(6+dof_id,0,1,6) = toEigen(F).transpose(); } } } } //The first 6x6 submatrix of the FlotingBase Inertia Matrix are simply the spatial inertia //of all the structure expressed in the base reference frame H.data.block(0,0,6,6) = toEigen(Ic[traversal.getBaseLink()->getLinkIndex()]); return 0; } int crba_momentum_jacobian_loop(const UndirectedTree & undirected_tree, const Traversal & traversal, const JntArray & q, std::vector<RigidBodyInertia> & Ic, MomentumJacobian & H, RigidBodyInertia & InertiaCOM ) { #ifndef NDEBUG if( undirected_tree.getNrOfLinks() != traversal.getNrOfVisitedLinks() || undirected_tree.getNrOfDOFs() != q.rows() || Ic.size() != undirected_tree.getNrOfLinks() || H.columns() != (undirected_tree.getNrOfDOFs() + 6) ) { std::cerr << "crba_momentum_jacobian_loop: input data error" << std::endl; return -1; } #endif double q_; Wrench F = Wrench::Zero(); //Sweep from root to leaf for(int i=0;i<(int)traversal.getNrOfVisitedLinks();i++) { LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); //Collect RigidBodyInertia Ic[link_index]=link_it->getInertia(); } for(int i=(int)traversal.getNrOfVisitedLinks()-1; i >= 1; i-- ) { int dof_id; LinkMap::const_iterator link_it = traversal.getOrderedLink(i); int link_index = link_it->getLinkIndex(); LinkMap::const_iterator parent_it = traversal.getParentLink(link_index); int parent_index = parent_it->getLinkIndex(); if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { dof_id = link_it->getAdjacentJoint(parent_it)->getDOFIndex(); q_ = q(dof_id); } else { q_ = 0.0; dof_id = -1; } Ic[parent_index] = Ic[parent_index]+link_it->pose(parent_it,q_)*Ic[link_index]; if( link_it->getAdjacentJoint(parent_it)->getNrOfDOFs() == 1 ) { KDL::Twist S_link_parent = parent_it->S(link_it,q_); F = Ic[link_index]*S_link_parent; if( traversal.getParentLink(link_it) != undirected_tree.getInvalidLinkIterator() ) { double q__; int dof_id_; LinkMap::const_iterator predecessor_it = traversal.getParentLink(link_it); LinkMap::const_iterator successor_it = link_it; while(true) { if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { q__ = q( predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex()); } else { q__ = 0.0; } F = successor_it->pose(predecessor_it,q__)*F; successor_it = predecessor_it; predecessor_it = traversal.getParentLink(predecessor_it); if( predecessor_it == undirected_tree.getInvalidLinkIterator() ) { break; } if( predecessor_it->getAdjacentJoint(successor_it)->getNrOfDOFs() == 1 ) { dof_id_ = predecessor_it->getAdjacentJoint(successor_it)->getDOFIndex(); q__ = q(dof_id_); } else { q__ = 0.0; dof_id_ = -1; } } if( dof_id >= 0 ) { H.data.block(0,6+dof_id,6,1) = toEigen(F); } //The first 6x6 submatrix of the Momentum Jacobian are simply the spatial inertia //of all the structure expressed in the base reference frame H.data.block(0,0,6,6) = toEigen(Ic[traversal.getBaseLink()->getLinkIndex()]); } } } //We have then to translate the reference point of the obtained jacobian to the com //The Ic[traversal.order[0]->getLink(index)] contain the spatial inertial of all the tree //expressed in link coordite frames Vector com = Ic[traversal.getBaseLink()->getLinkIndex()].getCOG(); H.changeRefPoint(com); InertiaCOM = Frame(com)*Ic[traversal.getBaseLink()->getLinkIndex()]; return 0; } } } <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #pragma once #include <chrono> #include <random> #include <tuple> #include <boost/graph/graphml.hpp> #include "algorithm.hpp" #include "graph.hpp" template <class Iterator> void generate_seeds(Iterator begin, Iterator end, std::string seed) { std::seed_seq seq(seed.begin(), seed.end()); seq.generate(begin, end); } double pr_within(double x) { return x <= 1 ? .5*x*x*x*x - 8./3*x*x*x + M_PI*x*x : -.5*x*x*x*x - 4*x*x*atan(sqrt(x*x-1)) + 4./3*(2*x*x+1)*sqrt(x*x-1) + (M_PI-2)*x*x + 1./3; }; template <class Graph> class test_suite { public: unsigned size() const { return seeds.size() * degrees.size() * sizes.size(); } std::string type() const { return t; } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { auto run = i % seeds.size(); std::default_random_engine generator(seeds[run]); auto expected_degree = degrees[(i / seeds.size()) % degrees.size()]; auto n = sizes[i / seeds.size() / degrees.size()]; auto d = expected_degree; auto tree_degree = 2.*(n-1)/n; bool mst = found("mst", t); bool unite = !found("++", t); Graph G(n), G_shuffled(n); // use d in [0,1] to mean density (since connected graphs have d > 1 anyway) if(unite && d <= 1) d *= n-1; if(found("path", t)) { add_spider(G, 1, generator); // the overlap satisfies y = a x + b // full graph satisfies: 0 = a (n-1) + b // tree graph satisfies: 2(n-1)/n = a 2(n-1)/n + b // so we must subtract this: if(unite) d -= 2./(2.-n) * d + 1. + n/(n-2.); } double parameter; if(found("rgg", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/sinh(d-sqrt(2.)); // approximate fit parameter = find_argument(d/(n-1), pr_within, 0, sqrt(2.)); Geometric points(n, generator); points.add_random_geometric(G, parameter); if(mst) points.add_mst(G); } else if(found("gnp", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/(2*M_PI*sinh(d-M_PI/sqrt(3.))); // approximate fit parameter = d<0 ? 0 : d/(n-1); add_edges_uniform(G, parameter, generator, mst); } copy_edges_shuffled(G, G_shuffled, generator); return std::make_tuple(G_shuffled, run, expected_degree, parameter); } template<class Sizes, class Degrees> test_suite(std::string t, unsigned z, Sizes ns, Degrees ds, std::string seed) : t(t), sizes(ns), degrees(ds) { seeds.resize(z); generate_seeds(seeds.begin(), seeds.end(), seed); } private: std::string t; std::vector<unsigned> sizes; std::vector<double> degrees; std::vector<unsigned> seeds; }; template <class Graph> class file_suite { public: std::tuple<Graph, unsigned, double, double> get(unsigned i) const { return std::make_tuple(graphs[i], i, 0, 0); } unsigned size() const { return graphs.size(); } file_suite(std::string f) : t(f.substr(0, f.find('.'))) { std::ifstream file(f); if(!file.good()) { throw std::invalid_argument("File does not exist: " + f); } int z, n, m, s, t; file >> z; while(z--) { file >> n >> m; Graph G(n); for(int i = 0; i < m; ++i) { file >> s >> t; add_edge(s, t, G); } graphs.push_back(G); } file.close(); } std::string type() const { return t; } private: std::string t; std::vector<Graph> graphs; }; template <class Graph> class real_suite { public: unsigned size() const { return seeds.size(); } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { std::default_random_engine generator(seeds[i]); Graph g(num_vertices(G)); copy_edges_shuffled(G, g, generator); return std::make_tuple(g, i, 0, 0); } real_suite(std::string f, unsigned size, std::string seed) : G(0), t(f.substr(f.rfind('/')+1, f.rfind('.')-f.rfind('/')-1)), seeds(size) { std::ifstream file(f); if (!file.good()) { throw std::invalid_argument("File does not exist: " + f); } boost::dynamic_properties dp; read_graphml(file, G, dp); generate_seeds(seeds.begin(), seeds.end(), seed); } std::string type() const { return t; } private: Graph G; std::string t; std::vector<unsigned> seeds; }; <commit_msg>model name in file suite<commit_after>// (C) 2014 Arek Olek #pragma once #include <chrono> #include <random> #include <tuple> #include <boost/graph/graphml.hpp> #include "algorithm.hpp" #include "graph.hpp" template <class Iterator> void generate_seeds(Iterator begin, Iterator end, std::string seed) { std::seed_seq seq(seed.begin(), seed.end()); seq.generate(begin, end); } double pr_within(double x) { return x <= 1 ? .5*x*x*x*x - 8./3*x*x*x + M_PI*x*x : -.5*x*x*x*x - 4*x*x*atan(sqrt(x*x-1)) + 4./3*(2*x*x+1)*sqrt(x*x-1) + (M_PI-2)*x*x + 1./3; }; template <class Graph> class test_suite { public: unsigned size() const { return seeds.size() * degrees.size() * sizes.size(); } std::string type() const { return t; } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { auto run = i % seeds.size(); std::default_random_engine generator(seeds[run]); auto expected_degree = degrees[(i / seeds.size()) % degrees.size()]; auto n = sizes[i / seeds.size() / degrees.size()]; auto d = expected_degree; auto tree_degree = 2.*(n-1)/n; bool mst = found("mst", t); bool unite = !found("++", t); Graph G(n), G_shuffled(n); // use d in [0,1] to mean density (since connected graphs have d > 1 anyway) if(unite && d <= 1) d *= n-1; if(found("path", t)) { add_spider(G, 1, generator); // the overlap satisfies y = a x + b // full graph satisfies: 0 = a (n-1) + b // tree graph satisfies: 2(n-1)/n = a 2(n-1)/n + b // so we must subtract this: if(unite) d -= 2./(2.-n) * d + 1. + n/(n-2.); } double parameter; if(found("rgg", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/sinh(d-sqrt(2.)); // approximate fit parameter = find_argument(d/(n-1), pr_within, 0, sqrt(2.)); Geometric points(n, generator); points.add_random_geometric(G, parameter); if(mst) points.add_mst(G); } else if(found("gnp", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/(2*M_PI*sinh(d-M_PI/sqrt(3.))); // approximate fit parameter = d<0 ? 0 : d/(n-1); add_edges_uniform(G, parameter, generator, mst); } copy_edges_shuffled(G, G_shuffled, generator); return std::make_tuple(G_shuffled, run, expected_degree, parameter); } template<class Sizes, class Degrees> test_suite(std::string t, unsigned z, Sizes ns, Degrees ds, std::string seed) : t(t), sizes(ns), degrees(ds) { seeds.resize(z); generate_seeds(seeds.begin(), seeds.end(), seed); } private: std::string t; std::vector<unsigned> sizes; std::vector<double> degrees; std::vector<unsigned> seeds; }; template <class Graph> class file_suite { public: std::tuple<Graph, unsigned, double, double> get(unsigned i) const { return std::make_tuple(graphs[i], i, 0, 0); } unsigned size() const { return graphs.size(); } file_suite(std::string f) : t(f.substr(f.rfind('/')+1, f.rfind('.')-f.rfind('/')-1)) { std::ifstream file(f); if(!file.good()) { throw std::invalid_argument("File does not exist: " + f); } int z, n, m, s, t; file >> z; while(z--) { file >> n >> m; Graph G(n); for(int i = 0; i < m; ++i) { file >> s >> t; add_edge(s, t, G); } graphs.push_back(G); } file.close(); } std::string type() const { return t; } private: std::string t; std::vector<Graph> graphs; }; template <class Graph> class real_suite { public: unsigned size() const { return seeds.size(); } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { std::default_random_engine generator(seeds[i]); Graph g(num_vertices(G)); copy_edges_shuffled(G, g, generator); return std::make_tuple(g, i, 0, 0); } real_suite(std::string f, unsigned size, std::string seed) : G(0), t(f.substr(f.rfind('/')+1, f.rfind('.')-f.rfind('/')-1)), seeds(size) { std::ifstream file(f); if (!file.good()) { throw std::invalid_argument("File does not exist: " + f); } boost::dynamic_properties dp; read_graphml(file, G, dp); generate_seeds(seeds.begin(), seeds.end(), seed); } std::string type() const { return t; } private: Graph G; std::string t; std::vector<unsigned> seeds; }; <|endoftext|>
<commit_before>// Alexis Giraudet // Théo Cesbron #ifndef DICTIONARY_HPP #define DICTIONARY_HPP #include <ostream> #include <iostream> #include <exception> template <typename K, typename V> class dictionary { struct _link { K key; V value; _link *previous; _link *next; }; private: _link *_head; _link *_tail; int _size; public: dictionary(); ~dictionary(); void clear(); bool contains_key(K key); bool contains_value(V value); bool count(V value);//todo V get(K key); bool is_empty(); //K* keys_array(); std::ostream& print(); std::ostream& print(std::ostream &os); bool put(K key, V value); bool remove(K key); int size(); //V* values_array(); void trousseau(K *clfs, int &n); }; template <typename K, typename V> dictionary<K,V>::dictionary(): _head(0), _tail(0), _size(0) { ; } template <typename K, typename V> dictionary<K,V>::~dictionary() { clear(); } template <typename K, typename V> void dictionary<K,V>::clear() { _link *tmp_link = _head; while(tmp_link != 0) { _link *del_link = tmp_link; tmp_link = (*tmp_link).next; delete del_link; } _head = 0; _tail = 0; _size = 0; } template <typename K, typename V> bool dictionary<K,V>::contains_key(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> bool dictionary<K,V>::contains_value(V value) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).value == value) { return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> V dictionary<K,V>::get(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { return (*tmp_link).value; } tmp_link = (*tmp_link).next; } throw std::exception(); } template <typename K, typename V> bool dictionary<K,V>::is_empty() { return (_head == 0) && (_tail == 0); } template <typename K, typename V> std::ostream& dictionary<K,V>::print() { return print(std::cout); } template <typename K, typename V> std::ostream& dictionary<K,V>::print(std::ostream &os) { _link *tmp_link = _head; os << "size = " << _size << std::endl; while(tmp_link != 0) { os << (*tmp_link).key << " : " << (*tmp_link).value << std::endl; tmp_link = (*tmp_link).next; } return os; } template <typename K, typename V> bool dictionary<K,V>::put(K key, V value) { if(is_empty()) { _link *new_link = new _link; (*new_link).key = key; (*new_link).value = value; (*new_link).previous = 0; (*new_link).next = 0; _head = new_link; _tail = new_link; return true; } else { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { (*tmp_link).value = value; return false; } tmp_link = (*tmp_link).next; } _link *new_link = new _link; (*new_link).key = key; (*new_link).value = value; (*new_link).previous = _tail; (*new_link).next = 0; (*_tail).next = new_link; _tail = new_link; } _size++; return true; } template <typename K, typename V> bool dictionary<K,V>::remove(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { if(tmp_link == _head) { _head = (*tmp_link).next; } else { (*(*tmp_link).previous).next = (*tmp_link).next; } if(tmp_link == _tail) { _tail = (*tmp_link).previous; } else { (*(*tmp_link).next).previous = (*tmp_link).previous; } delete tmp_link; _size--; return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> int dictionary<K,V>::size() { return _size; } template <typename K, typename V> std::ostream& operator<< (std::ostream &os, dictionary<K,V> &m)//todo fix set const dictionary { return m.print(os); } template <typename K, typename V> void dictionary<K,V>::trousseau(K *clfs, int &n) { n = _size; int i = 0; _link *tmp_link = _head; while(tmp_link != 0) { clfs[i] = (*tmp_link).key; i++; } } #endif <commit_msg>implement keys_array and values_array functions<commit_after>// Alexis Giraudet // Théo Cesbron #ifndef DICTIONARY_HPP #define DICTIONARY_HPP #include <ostream> #include <iostream> #include <exception> template <typename K, typename V> class dictionary { struct _link { K key; V value; _link *previous; _link *next; }; private: _link *_head; _link *_tail; int _size; public: dictionary(); ~dictionary(); void clear(); bool contains_key(K key); bool contains_value(V value); bool count(V value);//todo V get(K key); bool is_empty(); K* keys_array(); std::ostream& print(); std::ostream& print(std::ostream &os); bool put(K key, V value); bool remove(K key); int size(); V* values_array(); void trousseau(K *clfs, int &n); }; template <typename K, typename V> dictionary<K,V>::dictionary(): _head(0), _tail(0), _size(0) { ; } template <typename K, typename V> dictionary<K,V>::~dictionary() { clear(); } template <typename K, typename V> void dictionary<K,V>::clear() { _link *tmp_link = _head; while(tmp_link != 0) { _link *del_link = tmp_link; tmp_link = (*tmp_link).next; delete del_link; } _head = 0; _tail = 0; _size = 0; } template <typename K, typename V> bool dictionary<K,V>::contains_key(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> bool dictionary<K,V>::contains_value(V value) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).value == value) { return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> V dictionary<K,V>::get(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { return (*tmp_link).value; } tmp_link = (*tmp_link).next; } throw std::exception(); } template <typename K, typename V> bool dictionary<K,V>::is_empty() { return (_head == 0) && (_tail == 0); } template <typename K, typename V> K* dictionary<K,V>::keys_array() { K *res = new K[_size]; int i=0; _link *tmp_link = _head; while(tmp_link != 0) { res[i] = (*tmp_link).key; i++; } return res; } template <typename K, typename V> std::ostream& dictionary<K,V>::print() { return print(std::cout); } template <typename K, typename V> std::ostream& dictionary<K,V>::print(std::ostream &os) { _link *tmp_link = _head; os << "size = " << _size << std::endl; while(tmp_link != 0) { os << (*tmp_link).key << " : " << (*tmp_link).value << std::endl; tmp_link = (*tmp_link).next; } return os; } template <typename K, typename V> bool dictionary<K,V>::put(K key, V value) { if(is_empty()) { _link *new_link = new _link; (*new_link).key = key; (*new_link).value = value; (*new_link).previous = 0; (*new_link).next = 0; _head = new_link; _tail = new_link; return true; } else { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { (*tmp_link).value = value; return false; } tmp_link = (*tmp_link).next; } _link *new_link = new _link; (*new_link).key = key; (*new_link).value = value; (*new_link).previous = _tail; (*new_link).next = 0; (*_tail).next = new_link; _tail = new_link; } _size++; return true; } template <typename K, typename V> bool dictionary<K,V>::remove(K key) { _link *tmp_link = _head; while(tmp_link != 0) { if((*tmp_link).key == key) { if(tmp_link == _head) { _head = (*tmp_link).next; } else { (*(*tmp_link).previous).next = (*tmp_link).next; } if(tmp_link == _tail) { _tail = (*tmp_link).previous; } else { (*(*tmp_link).next).previous = (*tmp_link).previous; } delete tmp_link; _size--; return true; } tmp_link = (*tmp_link).next; } return false; } template <typename K, typename V> int dictionary<K,V>::size() { return _size; } template <typename K, typename V> V* dictionary<K,V>::values_array() { V *res = new V[_size]; int i=0; _link *tmp_link = _head; while(tmp_link != 0) { res[i] = (*tmp_link).value; i++; } return res; } template <typename K, typename V> std::ostream& operator<< (std::ostream &os, dictionary<K,V> &m)//todo fix set const dictionary { return m.print(os); } template <typename K, typename V> void dictionary<K,V>::trousseau(K *clfs, int &n) { n = _size; int i = 0; _link *tmp_link = _head; while(tmp_link != 0) { clfs[i] = (*tmp_link).key; i++; } } #endif <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrRenderTargetContext.h" #include "GrGpu.h" #include "GrRenderTarget.h" #include "GrResourceProvider.h" #include "GrTexture.h" static bool check_rect(GrRenderTargetContext* rtc, const SkIRect& rect, uint32_t expectedValue, uint32_t* actualValue, int* failX, int* failY) { int w = rect.width(); int h = rect.height(); std::unique_ptr<uint32_t[]> pixels(new uint32_t[w * h]); memset(pixels.get(), ~expectedValue, sizeof(uint32_t) * w * h); SkImageInfo dstInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType); if (!rtc->readPixels(dstInfo, pixels.get(), 0, rect.fLeft, rect.fTop)) { return false; } for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { uint32_t pixel = pixels.get()[y * w + x]; if (pixel != expectedValue) { *actualValue = pixel; *failX = x + rect.fLeft; *failY = y + rect.fTop; return false; } } } return true; } // TODO: this test does this thorough purging of the rendertargets b.c. right now // the clear optimizations rely on the rendertarget's uniqueID. It can be // relaxed when we switch that over to using rendertargetcontext ids (although // we probably will want to have more clear values then too) static bool reset_rtc(sk_sp<GrRenderTargetContext>* rtc, GrContext* context, int w, int h) { #ifdef SK_DEBUG GrGpuResource::UniqueID oldID = GrGpuResource::UniqueID::InvalidID(); #endif if (*rtc) { SkDEBUGCODE(oldID = (*rtc)->accessRenderTarget()->uniqueID();) rtc->reset(nullptr); } context->freeGpuResources(); *rtc = context->makeDeferredRenderTargetContext(SkBackingFit::kExact, w, h, kRGBA_8888_GrPixelConfig, nullptr); SkASSERT((*rtc)->accessRenderTarget()->uniqueID() != oldID); return *rtc != nullptr; } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ClearOp, reporter, ctxInfo) { GrContext* context = ctxInfo.grContext(); static const int kW = 10; static const int kH = 10; SkIRect fullRect = SkIRect::MakeWH(kW, kH); sk_sp<GrRenderTargetContext> rtContext; // A rectangle that is inset by one on all sides and the 1-pixel wide rectangles that surround // it. SkIRect mid1Rect = SkIRect::MakeXYWH(1, 1, kW-2, kH-2); SkIRect outerLeftEdge = SkIRect::MakeXYWH(0, 0, 1, kH); SkIRect outerTopEdge = SkIRect::MakeXYWH(0, 0, kW, 1); SkIRect outerRightEdge = SkIRect::MakeXYWH(kW-1, 0, 1, kH); SkIRect outerBottomEdge = SkIRect::MakeXYWH(0, kH-1, kW, 1); // A rectangle that is inset by two on all sides and the 1-pixel wide rectangles that surround // it. SkIRect mid2Rect = SkIRect::MakeXYWH(2, 2, kW-4, kH-4); SkIRect innerLeftEdge = SkIRect::MakeXYWH(1, 1, 1, kH-2); SkIRect innerTopEdge = SkIRect::MakeXYWH(1, 1, kW-2, 1); SkIRect innerRightEdge = SkIRect::MakeXYWH(kW-2, 1, 1, kH-2); SkIRect innerBottomEdge = SkIRect::MakeXYWH(1, kH-2, kW-2, 1); uint32_t actualValue; int failX, failY; static const GrColor kColor1 = 0xABCDEF01; static const GrColor kColor2 = ~kColor1; if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Check a full clear rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Check two full clears, same color rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Check two full clears, different colors rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&fullRect, kColor2, false); if (!check_rect(rtContext.get(), fullRect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Test a full clear followed by a same color inset clear rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Test a inset clear followed by same color full clear rtContext->clear(&mid1Rect, kColor1, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Test a full clear followed by a different color inset clear rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); if (!check_rect(rtContext.get(), mid1Rect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Test a inset clear followed by a different full clear rtContext->clear(&mid1Rect, kColor2, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Check three nested clears from largest to smallest where outermost and innermost are same // color. rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); rtContext->clear(&mid2Rect, kColor1, false); if (!check_rect(rtContext.get(), mid2Rect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!check_rect(rtContext.get(), innerLeftEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerTopEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerRightEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerBottomEdge, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!reset_rtc(&rtContext, context, kW, kH)) { ERRORF(reporter, "Could not create render target context."); return; } // Swap the order of the second two clears in the above test. rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid2Rect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); if (!check_rect(rtContext.get(), mid1Rect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } } #endif <commit_msg>Remove accessRenderTarget call from Clear tests<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrRenderTargetContext.h" #include "GrGpu.h" #include "GrRenderTarget.h" #include "GrResourceProvider.h" #include "GrTexture.h" static bool check_rect(GrRenderTargetContext* rtc, const SkIRect& rect, uint32_t expectedValue, uint32_t* actualValue, int* failX, int* failY) { int w = rect.width(); int h = rect.height(); std::unique_ptr<uint32_t[]> pixels(new uint32_t[w * h]); memset(pixels.get(), ~expectedValue, sizeof(uint32_t) * w * h); SkImageInfo dstInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType); if (!rtc->readPixels(dstInfo, pixels.get(), 0, rect.fLeft, rect.fTop)) { return false; } for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { uint32_t pixel = pixels.get()[y * w + x]; if (pixel != expectedValue) { *actualValue = pixel; *failX = x + rect.fLeft; *failY = y + rect.fTop; return false; } } } return true; } sk_sp<GrRenderTargetContext> newRTC(GrContext* context, int w, int h) { return context->makeDeferredRenderTargetContext(SkBackingFit::kExact, w, h, kRGBA_8888_GrPixelConfig, nullptr); } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ClearOp, reporter, ctxInfo) { GrContext* context = ctxInfo.grContext(); static const int kW = 10; static const int kH = 10; SkIRect fullRect = SkIRect::MakeWH(kW, kH); sk_sp<GrRenderTargetContext> rtContext; // A rectangle that is inset by one on all sides and the 1-pixel wide rectangles that surround // it. SkIRect mid1Rect = SkIRect::MakeXYWH(1, 1, kW-2, kH-2); SkIRect outerLeftEdge = SkIRect::MakeXYWH(0, 0, 1, kH); SkIRect outerTopEdge = SkIRect::MakeXYWH(0, 0, kW, 1); SkIRect outerRightEdge = SkIRect::MakeXYWH(kW-1, 0, 1, kH); SkIRect outerBottomEdge = SkIRect::MakeXYWH(0, kH-1, kW, 1); // A rectangle that is inset by two on all sides and the 1-pixel wide rectangles that surround // it. SkIRect mid2Rect = SkIRect::MakeXYWH(2, 2, kW-4, kH-4); SkIRect innerLeftEdge = SkIRect::MakeXYWH(1, 1, 1, kH-2); SkIRect innerTopEdge = SkIRect::MakeXYWH(1, 1, kW-2, 1); SkIRect innerRightEdge = SkIRect::MakeXYWH(kW-2, 1, 1, kH-2); SkIRect innerBottomEdge = SkIRect::MakeXYWH(1, kH-2, kW-2, 1); uint32_t actualValue; int failX, failY; static const GrColor kColor1 = 0xABCDEF01; static const GrColor kColor2 = ~kColor1; rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Check a full clear rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Check two full clears, same color rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Check two full clears, different colors rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&fullRect, kColor2, false); if (!check_rect(rtContext.get(), fullRect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Test a full clear followed by a same color inset clear rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Test a inset clear followed by same color full clear rtContext->clear(&mid1Rect, kColor1, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Test a full clear followed by a different color inset clear rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); if (!check_rect(rtContext.get(), mid1Rect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Test a inset clear followed by a different full clear rtContext->clear(&mid1Rect, kColor2, false); rtContext->clear(&fullRect, kColor1, false); if (!check_rect(rtContext.get(), fullRect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Check three nested clears from largest to smallest where outermost and innermost are same // color. rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); rtContext->clear(&mid2Rect, kColor1, false); if (!check_rect(rtContext.get(), mid2Rect, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } if (!check_rect(rtContext.get(), innerLeftEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerTopEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerRightEdge, kColor2, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), innerBottomEdge, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } rtContext = newRTC(context, kW, kH); SkASSERT(rtContext); // Swap the order of the second two clears in the above test. rtContext->clear(&fullRect, kColor1, false); rtContext->clear(&mid2Rect, kColor1, false); rtContext->clear(&mid1Rect, kColor2, false); if (!check_rect(rtContext.get(), mid1Rect, kColor2, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor2, actualValue, failX, failY); } if (!check_rect(rtContext.get(), outerLeftEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerTopEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerRightEdge, kColor1, &actualValue, &failX, &failY) || !check_rect(rtContext.get(), outerBottomEdge, kColor1, &actualValue, &failX, &failY)) { ERRORF(reporter, "Expected 0x%08x but got 0x%08x at (%d, %d).", kColor1, actualValue, failX, failY); } } #endif <|endoftext|>
<commit_before>#include <cmath> #include "unit-tests-common.h" #include <librealsense2/hpp/rs_types.hpp> #include <librealsense2/hpp/rs_frame.hpp> #include <iostream> #include <chrono> #include <ctime> #include <algorithm> #include <librealsense2/rsutil.h> #include <sys/wait.h> #include <semaphore.h> #include <fcntl.h> using namespace rs2; using namespace std::chrono; bool stream(std::string serial_number, sem_t* sem2, bool do_query) { signal(SIGTERM, [](int signum) { std::cout << "SIGTERM: " << getpid() << std::endl; exit(1);}); rs2::context ctx; if (do_query) { rs2::device_list list(ctx.query_devices()); bool found_sn(false); for (auto&& dev : ctx.query_devices()) { if (dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) == serial_number) { found_sn = true; } } REQUIRE(found_sn); } rs2::pipeline pipe(ctx); rs2::config cfg; cfg.enable_device(serial_number); std::cout << "pipe starting: " << serial_number << std::endl; pipe.start(cfg); std::cout << "pipe started: " << serial_number << std::endl; double max_milli_between_frames(3000); double last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); bool is_running(true); int sem_value; while (is_running && crnt_time-last_frame_time < max_milli_between_frames) { rs2::frameset fs; if (pipe.poll_for_frames(&fs)) { last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); sem_getvalue(sem2, &sem_value); is_running = (sem_value == 0); } pipe.stop(); } void multiple_stream(std::string serial_number, sem_t* sem, bool do_query) { size_t max_iterations(10); pid_t pid; std::stringstream sem_name; sem_name << "sem_" << serial_number << "_" << 0; bool is_running(true); int sem_value; for (size_t counter=0; counter<10 && is_running; counter++) { sem_unlink(sem_name.str().c_str()); sem_t *sem2 = sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem2 == SEM_FAILED); pid = fork(); if (pid == 0) // child process { std::cout << "Start streaming: " << serial_number << " : (" << counter+1 << "/" << max_iterations << ")" << std::endl; stream(serial_number, sem2, do_query); //on normal behavior - should block break; } else { std::this_thread::sleep_for(std::chrono::seconds(5)); int status; pid_t w = waitpid(pid, &status, WNOHANG); bool child_alive(w == 0); if (child_alive) { sem_post(sem2); // Give 2 seconds to quit before kill: double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); while (child_alive && (crnt_time - start_time < 2000)) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); pid_t w = waitpid(pid, &status, WNOHANG); child_alive = (w == 0); crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } if (child_alive) { std::cout << "Failed to start streaming: " << serial_number << std::endl; int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); exit(2); } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { std::cout << "Frames did not arrive: " << serial_number << std::endl; exit(1); } } sem_getvalue(sem, &sem_value); is_running = (sem_value == 0); } if (pid != 0) { sem_unlink(sem_name.str().c_str()); } exit(0); } TEST_CASE("multicam_streaming", "[code][live]") { // Test will start and stop streaming on 2 devices simultaneously for 10 times, thus testing the named_mutex mechnism. rs2::context ctx; rs2::device_list list(ctx.query_devices()); REQUIRE(list.size() >= 2); std::vector<std::string> serials_numbers; for (auto&& dev : ctx.query_devices()) { serials_numbers.push_back(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)); } std::vector<pid_t> pids; pid_t pid; bool do_query(true); std::vector<sem_t*> sems; for (size_t idx = 0; idx < serials_numbers.size(); idx++) { std::stringstream sem_name; sem_name << "sem_" << idx; sem_unlink(sem_name.str().c_str()); sems.push_back(sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0)); CHECK_FALSE(sems[idx] == SEM_FAILED); pid = fork(); if (pid == 0) // child { multiple_stream(serials_numbers[idx], sems[idx], do_query); //on normal behavior - should block } else { std::this_thread::sleep_for(std::chrono::milliseconds(100)); pids.push_back(pid); } } if (pid != 0) { int status0; pid_t pid = wait(&status0); std::cout << "status0 = " << status0 << std::endl; for (auto sem : sems) { sem_post(sem); } for (auto pid : pids) { int status; pid_t w = waitpid(pid, &status, WNOHANG); std::cout << "status: " << pid << " : " << status << std::endl; bool child_alive(w == 0); double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); while (child_alive && (crnt_time - start_time < 6000)) { std::cout << "waiting for: " << pid << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); pid_t w = waitpid(pid, &status, WNOHANG); child_alive = (w == 0); crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } if (child_alive) { std::cout << "kill: " << pid << std::endl; int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); std::cout << "status: " << status << ", " << w << std::endl; } } REQUIRE(status0 == 0); } }<commit_msg>fix multicam_streaming test to validate 2 devices connected with usb3.2 are available.<commit_after>#include <cmath> #include "unit-tests-common.h" #include <librealsense2/hpp/rs_types.hpp> #include <librealsense2/hpp/rs_frame.hpp> #include <iostream> #include <chrono> #include <ctime> #include <algorithm> #include <librealsense2/rsutil.h> #include <sys/wait.h> #include <semaphore.h> #include <fcntl.h> using namespace rs2; using namespace std::chrono; bool stream(std::string serial_number, sem_t* sem2, bool do_query) { signal(SIGTERM, [](int signum) { std::cout << "SIGTERM: " << getpid() << std::endl; exit(1);}); rs2::context ctx; if (do_query) { rs2::device_list list(ctx.query_devices()); bool found_sn(false); for (auto&& dev : ctx.query_devices()) { if (dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER) == serial_number) { found_sn = true; } } REQUIRE(found_sn); } rs2::pipeline pipe(ctx); rs2::config cfg; cfg.enable_device(serial_number); std::cout << "pipe starting: " << serial_number << std::endl; pipe.start(cfg); std::cout << "pipe started: " << serial_number << std::endl; double max_milli_between_frames(3000); double last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); bool is_running(true); int sem_value; while (is_running && crnt_time-last_frame_time < max_milli_between_frames) { rs2::frameset fs; if (pipe.poll_for_frames(&fs)) { last_frame_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); sem_getvalue(sem2, &sem_value); is_running = (sem_value == 0); } pipe.stop(); } void multiple_stream(std::string serial_number, sem_t* sem, bool do_query) { size_t max_iterations(10); pid_t pid; std::stringstream sem_name; sem_name << "sem_" << serial_number << "_" << 0; bool is_running(true); int sem_value; for (size_t counter=0; counter<10 && is_running; counter++) { sem_unlink(sem_name.str().c_str()); sem_t *sem2 = sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0); CHECK_FALSE(sem2 == SEM_FAILED); pid = fork(); if (pid == 0) // child process { std::cout << "Start streaming: " << serial_number << " : (" << counter+1 << "/" << max_iterations << ")" << std::endl; stream(serial_number, sem2, do_query); //on normal behavior - should block break; } else { std::this_thread::sleep_for(std::chrono::seconds(5)); int status; pid_t w = waitpid(pid, &status, WNOHANG); bool child_alive(w == 0); if (child_alive) { sem_post(sem2); // Give 2 seconds to quit before kill: double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); while (child_alive && (crnt_time - start_time < 2000)) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); pid_t w = waitpid(pid, &status, WNOHANG); child_alive = (w == 0); crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } if (child_alive) { std::cout << "Failed to start streaming: " << serial_number << std::endl; int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); exit(2); } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { std::cout << "Frames did not arrive: " << serial_number << std::endl; exit(1); } } sem_getvalue(sem, &sem_value); is_running = (sem_value == 0); } if (pid != 0) { sem_unlink(sem_name.str().c_str()); } exit(0); } TEST_CASE("multicam_streaming", "[code][live]") { // Test will start and stop streaming on 2 devices simultaneously for 10 times, thus testing the named_mutex mechnism. rs2::context ctx; std::vector<std::string> serials_numbers; for (auto&& dev : ctx.query_devices()) { std::string serial(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)); std::string usb_type(dev.get_info(RS2_CAMERA_INFO_USB_TYPE_DESCRIPTOR)); if ( usb_type != "3.2") { std::cout << "Device " << serial << " with usb_type " << usb_type << " is skipped."; continue; } serials_numbers.push_back(serial); } REQUIRE(serials_numbers.size() >= 2); std::vector<pid_t> pids; pid_t pid; bool do_query(true); std::vector<sem_t*> sems; for (size_t idx = 0; idx < serials_numbers.size(); idx++) { std::stringstream sem_name; sem_name << "sem_" << idx; sem_unlink(sem_name.str().c_str()); sems.push_back(sem_open(sem_name.str().c_str(), O_CREAT|O_EXCL, S_IRWXU, 0)); CHECK_FALSE(sems[idx] == SEM_FAILED); pid = fork(); if (pid == 0) // child { multiple_stream(serials_numbers[idx], sems[idx], do_query); //on normal behavior - should block } else { std::this_thread::sleep_for(std::chrono::milliseconds(100)); pids.push_back(pid); } } if (pid != 0) { int status0; pid_t pid = wait(&status0); std::cout << "status0 = " << status0 << std::endl; for (auto sem : sems) { sem_post(sem); } for (auto pid : pids) { int status; pid_t w = waitpid(pid, &status, WNOHANG); std::cout << "status: " << pid << " : " << status << std::endl; bool child_alive(w == 0); double start_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); double crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); while (child_alive && (crnt_time - start_time < 6000)) { std::cout << "waiting for: " << pid << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(500)); pid_t w = waitpid(pid, &status, WNOHANG); child_alive = (w == 0); crnt_time = duration<double, std::milli>(system_clock::now().time_since_epoch()).count(); } if (child_alive) { std::cout << "kill: " << pid << std::endl; int res = kill(pid,SIGTERM); pid_t w = waitpid(pid, &status, 0); std::cout << "status: " << status << ", " << w << std::endl; } } REQUIRE(status0 == 0); } }<|endoftext|>
<commit_before>#include "Test.h" #include "SkRandom.h" #include "SkRefCnt.h" #include "SkTSearch.h" #include "SkTSort.h" #include "SkUtils.h" class RefClass : public SkRefCnt { public: RefClass(int n) : fN(n) {} int get() const { return fN; } private: int fN; }; static void test_refptr(skiatest::Reporter* reporter) { RefClass* r0 = new RefClass(0); SkRefPtr<RefClass> rc0; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); SkRefPtr<RefClass> rc1; REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() != r0); rc0 = r0; REPORTER_ASSERT(reporter, rc0); REPORTER_ASSERT(reporter, rc0 != rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc1 = rc0; REPORTER_ASSERT(reporter, rc1); REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc0 = NULL; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); REPORTER_ASSERT(reporter, rc0 != rc1); r0->unref(); } static void test_autounref(skiatest::Reporter* reporter) { RefClass obj(0); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); SkAutoTUnref<RefClass> tmp(&obj); REPORTER_ASSERT(reporter, &obj == tmp.get()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, &obj == tmp.detach()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, NULL == tmp.detach()); REPORTER_ASSERT(reporter, NULL == tmp.get()); obj.ref(); REPORTER_ASSERT(reporter, 2 == obj.getRefCnt()); { SkAutoTUnref<RefClass> tmp2(&obj); } REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); } ////////////////////////////////////////////////////////////////////////////// #define kSEARCH_COUNT 91 static void test_search(skiatest::Reporter* reporter) { int i, array[kSEARCH_COUNT]; SkRandom rand; for (i = 0; i < kSEARCH_COUNT; i++) { array[i] = rand.nextS(); } SkTHeapSort<int>(array, kSEARCH_COUNT); // make sure we got sorted properly for (i = 1; i < kSEARCH_COUNT; i++) { REPORTER_ASSERT(reporter, array[i-1] <= array[i]); } // make sure we can find all of our values for (i = 0; i < kSEARCH_COUNT; i++) { int index = SkTSearch<int>(array, kSEARCH_COUNT, array[i], sizeof(int)); REPORTER_ASSERT(reporter, index == i); } // make sure that random values are either found, or the correct // insertion index is returned for (i = 0; i < 10000; i++) { int value = rand.nextS(); int index = SkTSearch<int>(array, kSEARCH_COUNT, value, sizeof(int)); if (index >= 0) { REPORTER_ASSERT(reporter, index < kSEARCH_COUNT && array[index] == value); } else { index = ~index; REPORTER_ASSERT(reporter, index <= kSEARCH_COUNT); if (index < kSEARCH_COUNT) { REPORTER_ASSERT(reporter, value < array[index]); if (index > 0) { REPORTER_ASSERT(reporter, value > array[index - 1]); } } else { // we should append the new value REPORTER_ASSERT(reporter, value > array[kSEARCH_COUNT - 1]); } } } } static void test_utf16(skiatest::Reporter* reporter) { static const SkUnichar gUni[] = { 0x10000, 0x18080, 0x20202, 0xFFFFF, 0x101234 }; uint16_t buf[2]; for (size_t i = 0; i < SK_ARRAY_COUNT(gUni); i++) { size_t count = SkUTF16_FromUnichar(gUni[i], buf); REPORTER_ASSERT(reporter, count == 2); size_t count2 = SkUTF16_CountUnichars(buf, 2); REPORTER_ASSERT(reporter, count2 == 1); const uint16_t* ptr = buf; SkUnichar c = SkUTF16_NextUnichar(&ptr); REPORTER_ASSERT(reporter, c == gUni[i]); REPORTER_ASSERT(reporter, ptr - buf == 2); } } static void TestUTF(skiatest::Reporter* reporter) { static const struct { const char* fUtf8; SkUnichar fUni; } gTest[] = { { "a", 'a' }, { "\x7f", 0x7f }, { "\xC2\x80", 0x80 }, { "\xC3\x83", (3 << 6) | 3 }, { "\xDF\xBF", 0x7ff }, { "\xE0\xA0\x80", 0x800 }, { "\xE0\xB0\xB8", 0xC38 }, { "\xE3\x83\x83", (3 << 12) | (3 << 6) | 3 }, { "\xEF\xBF\xBF", 0xFFFF }, { "\xF0\x90\x80\x80", 0x10000 }, { "\xF3\x83\x83\x83", (3 << 18) | (3 << 12) | (3 << 6) | 3 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTest); i++) { const char* p = gTest[i].fUtf8; int n = SkUTF8_CountUnichars(p); SkUnichar u0 = SkUTF8_ToUnichar(gTest[i].fUtf8); SkUnichar u1 = SkUTF8_NextUnichar(&p); REPORTER_ASSERT(reporter, n == 1); REPORTER_ASSERT(reporter, u0 == u1); REPORTER_ASSERT(reporter, u0 == gTest[i].fUni); REPORTER_ASSERT(reporter, p - gTest[i].fUtf8 == (int)strlen(gTest[i].fUtf8)); } test_utf16(reporter); test_search(reporter); test_refptr(reporter); test_autounref(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Utils", UtfTestClass, TestUTF) <commit_msg>Tiny comment-only change to trigger buildbot<commit_after>#include "Test.h" #include "SkRandom.h" #include "SkRefCnt.h" #include "SkTSearch.h" #include "SkTSort.h" #include "SkUtils.h" class RefClass : public SkRefCnt { public: RefClass(int n) : fN(n) {} int get() const { return fN; } private: int fN; }; static void test_refptr(skiatest::Reporter* reporter) { RefClass* r0 = new RefClass(0); SkRefPtr<RefClass> rc0; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); SkRefPtr<RefClass> rc1; REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() != r0); rc0 = r0; REPORTER_ASSERT(reporter, rc0); REPORTER_ASSERT(reporter, rc0 != rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc1 = rc0; REPORTER_ASSERT(reporter, rc1); REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc0 = NULL; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); REPORTER_ASSERT(reporter, rc0 != rc1); r0->unref(); } static void test_autounref(skiatest::Reporter* reporter) { RefClass obj(0); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); SkAutoTUnref<RefClass> tmp(&obj); REPORTER_ASSERT(reporter, &obj == tmp.get()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, &obj == tmp.detach()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, NULL == tmp.detach()); REPORTER_ASSERT(reporter, NULL == tmp.get()); obj.ref(); REPORTER_ASSERT(reporter, 2 == obj.getRefCnt()); { SkAutoTUnref<RefClass> tmp2(&obj); } REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); } /////////////////////////////////////////////////////////////////////////////// #define kSEARCH_COUNT 91 static void test_search(skiatest::Reporter* reporter) { int i, array[kSEARCH_COUNT]; SkRandom rand; for (i = 0; i < kSEARCH_COUNT; i++) { array[i] = rand.nextS(); } SkTHeapSort<int>(array, kSEARCH_COUNT); // make sure we got sorted properly for (i = 1; i < kSEARCH_COUNT; i++) { REPORTER_ASSERT(reporter, array[i-1] <= array[i]); } // make sure we can find all of our values for (i = 0; i < kSEARCH_COUNT; i++) { int index = SkTSearch<int>(array, kSEARCH_COUNT, array[i], sizeof(int)); REPORTER_ASSERT(reporter, index == i); } // make sure that random values are either found, or the correct // insertion index is returned for (i = 0; i < 10000; i++) { int value = rand.nextS(); int index = SkTSearch<int>(array, kSEARCH_COUNT, value, sizeof(int)); if (index >= 0) { REPORTER_ASSERT(reporter, index < kSEARCH_COUNT && array[index] == value); } else { index = ~index; REPORTER_ASSERT(reporter, index <= kSEARCH_COUNT); if (index < kSEARCH_COUNT) { REPORTER_ASSERT(reporter, value < array[index]); if (index > 0) { REPORTER_ASSERT(reporter, value > array[index - 1]); } } else { // we should append the new value REPORTER_ASSERT(reporter, value > array[kSEARCH_COUNT - 1]); } } } } static void test_utf16(skiatest::Reporter* reporter) { static const SkUnichar gUni[] = { 0x10000, 0x18080, 0x20202, 0xFFFFF, 0x101234 }; uint16_t buf[2]; for (size_t i = 0; i < SK_ARRAY_COUNT(gUni); i++) { size_t count = SkUTF16_FromUnichar(gUni[i], buf); REPORTER_ASSERT(reporter, count == 2); size_t count2 = SkUTF16_CountUnichars(buf, 2); REPORTER_ASSERT(reporter, count2 == 1); const uint16_t* ptr = buf; SkUnichar c = SkUTF16_NextUnichar(&ptr); REPORTER_ASSERT(reporter, c == gUni[i]); REPORTER_ASSERT(reporter, ptr - buf == 2); } } static void TestUTF(skiatest::Reporter* reporter) { static const struct { const char* fUtf8; SkUnichar fUni; } gTest[] = { { "a", 'a' }, { "\x7f", 0x7f }, { "\xC2\x80", 0x80 }, { "\xC3\x83", (3 << 6) | 3 }, { "\xDF\xBF", 0x7ff }, { "\xE0\xA0\x80", 0x800 }, { "\xE0\xB0\xB8", 0xC38 }, { "\xE3\x83\x83", (3 << 12) | (3 << 6) | 3 }, { "\xEF\xBF\xBF", 0xFFFF }, { "\xF0\x90\x80\x80", 0x10000 }, { "\xF3\x83\x83\x83", (3 << 18) | (3 << 12) | (3 << 6) | 3 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTest); i++) { const char* p = gTest[i].fUtf8; int n = SkUTF8_CountUnichars(p); SkUnichar u0 = SkUTF8_ToUnichar(gTest[i].fUtf8); SkUnichar u1 = SkUTF8_NextUnichar(&p); REPORTER_ASSERT(reporter, n == 1); REPORTER_ASSERT(reporter, u0 == u1); REPORTER_ASSERT(reporter, u0 == gTest[i].fUni); REPORTER_ASSERT(reporter, p - gTest[i].fUtf8 == (int)strlen(gTest[i].fUtf8)); } test_utf16(reporter); test_search(reporter); test_refptr(reporter); test_autounref(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Utils", UtfTestClass, TestUTF) <|endoftext|>
<commit_before>#include "Test.h" #include "SkRandom.h" #include "SkRefCnt.h" #include "SkTSearch.h" #include "SkTSort.h" #include "SkUtils.h" class RefClass : public SkRefCnt { public: RefClass(int n) : fN(n) {} int get() const { return fN; } private: int fN; }; static void test_refptr(skiatest::Reporter* reporter) { RefClass* r0 = new RefClass(0); SkRefPtr<RefClass> rc0; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); SkRefPtr<RefClass> rc1; REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() != r0); rc0 = r0; REPORTER_ASSERT(reporter, rc0); REPORTER_ASSERT(reporter, rc0 != rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc1 = rc0; REPORTER_ASSERT(reporter, rc1); REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc0 = NULL; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); REPORTER_ASSERT(reporter, rc0 != rc1); r0->unref(); } static void test_autounref(skiatest::Reporter* reporter) { RefClass obj(0); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); SkAutoTUnref<RefClass> tmp(&obj); REPORTER_ASSERT(reporter, &obj == tmp.get()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, &obj == tmp.detach()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, NULL == tmp.detach()); REPORTER_ASSERT(reporter, NULL == tmp.get()); obj.ref(); REPORTER_ASSERT(reporter, 2 == obj.getRefCnt()); { SkAutoTUnref<RefClass> tmp2(&obj); } REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); } /////////////////////////////////////////////////////////////////////////////// #define kSEARCH_COUNT 91 static void test_search(skiatest::Reporter* reporter) { int i, array[kSEARCH_COUNT]; SkRandom rand; for (i = 0; i < kSEARCH_COUNT; i++) { array[i] = rand.nextS(); } SkTHeapSort<int>(array, kSEARCH_COUNT); // make sure we got sorted properly for (i = 1; i < kSEARCH_COUNT; i++) { REPORTER_ASSERT(reporter, array[i-1] <= array[i]); } // make sure we can find all of our values for (i = 0; i < kSEARCH_COUNT; i++) { int index = SkTSearch<int>(array, kSEARCH_COUNT, array[i], sizeof(int)); REPORTER_ASSERT(reporter, index == i); } // make sure that random values are either found, or the correct // insertion index is returned for (i = 0; i < 10000; i++) { int value = rand.nextS(); int index = SkTSearch<int>(array, kSEARCH_COUNT, value, sizeof(int)); if (index >= 0) { REPORTER_ASSERT(reporter, index < kSEARCH_COUNT && array[index] == value); } else { index = ~index; REPORTER_ASSERT(reporter, index <= kSEARCH_COUNT); if (index < kSEARCH_COUNT) { REPORTER_ASSERT(reporter, value < array[index]); if (index > 0) { REPORTER_ASSERT(reporter, value > array[index - 1]); } } else { // we should append the new value REPORTER_ASSERT(reporter, value > array[kSEARCH_COUNT - 1]); } } } } static void test_utf16(skiatest::Reporter* reporter) { static const SkUnichar gUni[] = { 0x10000, 0x18080, 0x20202, 0xFFFFF, 0x101234 }; uint16_t buf[2]; for (size_t i = 0; i < SK_ARRAY_COUNT(gUni); i++) { size_t count = SkUTF16_FromUnichar(gUni[i], buf); REPORTER_ASSERT(reporter, count == 2); size_t count2 = SkUTF16_CountUnichars(buf, 2); REPORTER_ASSERT(reporter, count2 == 1); const uint16_t* ptr = buf; SkUnichar c = SkUTF16_NextUnichar(&ptr); REPORTER_ASSERT(reporter, c == gUni[i]); REPORTER_ASSERT(reporter, ptr - buf == 2); } } static void TestUTF(skiatest::Reporter* reporter) { static const struct { const char* fUtf8; SkUnichar fUni; } gTest[] = { { "a", 'a' }, { "\x7f", 0x7f }, { "\xC2\x80", 0x80 }, { "\xC3\x83", (3 << 6) | 3 }, { "\xDF\xBF", 0x7ff }, { "\xE0\xA0\x80", 0x800 }, { "\xE0\xB0\xB8", 0xC38 }, { "\xE3\x83\x83", (3 << 12) | (3 << 6) | 3 }, { "\xEF\xBF\xBF", 0xFFFF }, { "\xF0\x90\x80\x80", 0x10000 }, { "\xF3\x83\x83\x83", (3 << 18) | (3 << 12) | (3 << 6) | 3 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTest); i++) { const char* p = gTest[i].fUtf8; int n = SkUTF8_CountUnichars(p); SkUnichar u0 = SkUTF8_ToUnichar(gTest[i].fUtf8); SkUnichar u1 = SkUTF8_NextUnichar(&p); REPORTER_ASSERT(reporter, n == 1); REPORTER_ASSERT(reporter, u0 == u1); REPORTER_ASSERT(reporter, u0 == gTest[i].fUni); REPORTER_ASSERT(reporter, p - gTest[i].fUtf8 == (int)strlen(gTest[i].fUtf8)); } test_utf16(reporter); test_search(reporter); test_refptr(reporter); test_autounref(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Utils", UtfTestClass, TestUTF) <commit_msg>Tiny comment-only change to trigger update<commit_after>#include "Test.h" #include "SkRandom.h" #include "SkRefCnt.h" #include "SkTSearch.h" #include "SkTSort.h" #include "SkUtils.h" class RefClass : public SkRefCnt { public: RefClass(int n) : fN(n) {} int get() const { return fN; } private: int fN; }; static void test_refptr(skiatest::Reporter* reporter) { RefClass* r0 = new RefClass(0); SkRefPtr<RefClass> rc0; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); SkRefPtr<RefClass> rc1; REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() != r0); rc0 = r0; REPORTER_ASSERT(reporter, rc0); REPORTER_ASSERT(reporter, rc0 != rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc1 = rc0; REPORTER_ASSERT(reporter, rc1); REPORTER_ASSERT(reporter, rc0 == rc1); REPORTER_ASSERT(reporter, rc0.get() == r0); rc0 = NULL; REPORTER_ASSERT(reporter, rc0.get() == NULL); REPORTER_ASSERT(reporter, !rc0); REPORTER_ASSERT(reporter, rc0 != rc1); r0->unref(); } static void test_autounref(skiatest::Reporter* reporter) { RefClass obj(0); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); SkAutoTUnref<RefClass> tmp(&obj); REPORTER_ASSERT(reporter, &obj == tmp.get()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, &obj == tmp.detach()); REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); REPORTER_ASSERT(reporter, NULL == tmp.detach()); REPORTER_ASSERT(reporter, NULL == tmp.get()); obj.ref(); REPORTER_ASSERT(reporter, 2 == obj.getRefCnt()); { SkAutoTUnref<RefClass> tmp2(&obj); } REPORTER_ASSERT(reporter, 1 == obj.getRefCnt()); } ////////////////////////////////////////////////////////////////////////////// #define kSEARCH_COUNT 91 static void test_search(skiatest::Reporter* reporter) { int i, array[kSEARCH_COUNT]; SkRandom rand; for (i = 0; i < kSEARCH_COUNT; i++) { array[i] = rand.nextS(); } SkTHeapSort<int>(array, kSEARCH_COUNT); // make sure we got sorted properly for (i = 1; i < kSEARCH_COUNT; i++) { REPORTER_ASSERT(reporter, array[i-1] <= array[i]); } // make sure we can find all of our values for (i = 0; i < kSEARCH_COUNT; i++) { int index = SkTSearch<int>(array, kSEARCH_COUNT, array[i], sizeof(int)); REPORTER_ASSERT(reporter, index == i); } // make sure that random values are either found, or the correct // insertion index is returned for (i = 0; i < 10000; i++) { int value = rand.nextS(); int index = SkTSearch<int>(array, kSEARCH_COUNT, value, sizeof(int)); if (index >= 0) { REPORTER_ASSERT(reporter, index < kSEARCH_COUNT && array[index] == value); } else { index = ~index; REPORTER_ASSERT(reporter, index <= kSEARCH_COUNT); if (index < kSEARCH_COUNT) { REPORTER_ASSERT(reporter, value < array[index]); if (index > 0) { REPORTER_ASSERT(reporter, value > array[index - 1]); } } else { // we should append the new value REPORTER_ASSERT(reporter, value > array[kSEARCH_COUNT - 1]); } } } } static void test_utf16(skiatest::Reporter* reporter) { static const SkUnichar gUni[] = { 0x10000, 0x18080, 0x20202, 0xFFFFF, 0x101234 }; uint16_t buf[2]; for (size_t i = 0; i < SK_ARRAY_COUNT(gUni); i++) { size_t count = SkUTF16_FromUnichar(gUni[i], buf); REPORTER_ASSERT(reporter, count == 2); size_t count2 = SkUTF16_CountUnichars(buf, 2); REPORTER_ASSERT(reporter, count2 == 1); const uint16_t* ptr = buf; SkUnichar c = SkUTF16_NextUnichar(&ptr); REPORTER_ASSERT(reporter, c == gUni[i]); REPORTER_ASSERT(reporter, ptr - buf == 2); } } static void TestUTF(skiatest::Reporter* reporter) { static const struct { const char* fUtf8; SkUnichar fUni; } gTest[] = { { "a", 'a' }, { "\x7f", 0x7f }, { "\xC2\x80", 0x80 }, { "\xC3\x83", (3 << 6) | 3 }, { "\xDF\xBF", 0x7ff }, { "\xE0\xA0\x80", 0x800 }, { "\xE0\xB0\xB8", 0xC38 }, { "\xE3\x83\x83", (3 << 12) | (3 << 6) | 3 }, { "\xEF\xBF\xBF", 0xFFFF }, { "\xF0\x90\x80\x80", 0x10000 }, { "\xF3\x83\x83\x83", (3 << 18) | (3 << 12) | (3 << 6) | 3 } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTest); i++) { const char* p = gTest[i].fUtf8; int n = SkUTF8_CountUnichars(p); SkUnichar u0 = SkUTF8_ToUnichar(gTest[i].fUtf8); SkUnichar u1 = SkUTF8_NextUnichar(&p); REPORTER_ASSERT(reporter, n == 1); REPORTER_ASSERT(reporter, u0 == u1); REPORTER_ASSERT(reporter, u0 == gTest[i].fUni); REPORTER_ASSERT(reporter, p - gTest[i].fUtf8 == (int)strlen(gTest[i].fUtf8)); } test_utf16(reporter); test_search(reporter); test_refptr(reporter); test_autounref(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("Utils", UtfTestClass, TestUTF) <|endoftext|>
<commit_before>/* */ #include <synext.hpp> #include <parse/tokentree.hpp> #include <parse/lex.hpp> #include <parse/common.hpp> #include "cfg.hpp" #include <ast/expr.hpp> // Needed to clear a ExprNodeP #include <map> #include <set> ::std::map< ::std::string, ::std::string> g_cfg_values; ::std::map< ::std::string, ::std::function<bool(const ::std::string&)> > g_cfg_value_fcns; ::std::set< ::std::string > g_cfg_flags; void Cfg_SetFlag(::std::string name) { g_cfg_flags.insert( mv$(name) ); } void Cfg_SetValue(::std::string name, ::std::string val) { g_cfg_values.insert( ::std::make_pair(mv$(name), mv$(val)) ); } void Cfg_SetValueCb(::std::string name, ::std::function<bool(const ::std::string&)> cb) { g_cfg_value_fcns.insert( ::std::make_pair(mv$(name), mv$(cb)) ); } bool check_cfg(Span sp, const ::AST::MetaItem& mi) { if( mi.has_sub_items() ) { // Must be `any`/`not`/`all` if( mi.name() == "any" || mi.name() == "cfg" ) { for(const auto& si : mi.items()) { if( check_cfg(sp, si) ) return true; } return false; } else if( mi.name() == "not" ) { if( mi.items().size() != 1 ) ERROR(sp, E0000, "cfg(not()) with != 1 argument"); return !check_cfg(sp, mi.items()[0]); } else if( mi.name() == "all" ) { for(const auto& si : mi.items()) { if( ! check_cfg(sp, si) ) return false; } return true; } else { // oops ERROR(sp, E0000, "Unknown cfg() function - " << mi.name()); } } else if( mi.has_string() ) { // Equaliy auto it = g_cfg_values.find(mi.name()); if( it != g_cfg_values.end() ) { DEBUG(""<<mi.name()<<": '"<<it->second<<"' == '"<<mi.string()<<"'"); return it->second == mi.string(); } auto it2 = g_cfg_value_fcns.find(mi.name()); if(it2 != g_cfg_value_fcns.end() ) { DEBUG(""<<mi.name()<<": ('"<<mi.string()<<"')?"); return it2->second( mi.string() ); } WARNING(sp, W0000, "Unknown cfg() param '" << mi.name() << "'"); return false; } else { // Flag auto it = g_cfg_flags.find(mi.name()); return (it != g_cfg_flags.end()); } BUG(sp, "Fell off the end of check_cfg"); } class CCfgExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { if( ident != "" ) { ERROR(sp, E0000, "cfg! doesn't take an identifier"); } auto lex = TTStream(tt); auto attrs = Parse_MetaItem(lex); DEBUG("cfg!() - " << attrs); if( check_cfg(sp, attrs) ) { return box$( TTStreamO(TokenTree(TOK_RWORD_TRUE )) ); } else { return box$( TTStreamO(TokenTree(TOK_RWORD_FALSE)) ); } } }; class CCfgHandler: public ExpandDecorator { AttrStage stage() const override { return AttrStage::Pre; } void handle(const Span& sp, const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item&i) const override { TRACE_FUNCTION_FR("#[cfg] item - " << mi, (i.is_None() ? "Deleted" : "")); if( check_cfg(sp, mi) ) { // Leave } else { i = AST::Item::make_None({}); } } void handle(const Span& sp, const AST::MetaItem& mi, ::AST::Crate& crate, ::std::unique_ptr<AST::ExprNode>& expr) const override { DEBUG("#[cfg] expr - " << mi); if( check_cfg(sp, mi) ) { // Leave } else { expr.reset(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override { DEBUG("#[cfg] impl - " << mi); if( check_cfg(sp, mi) ) { // Leave } else { impl.type() = ::TypeRef(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::StructItem& si) const override { DEBUG("#[cfg] struct item - " << mi); if( !check_cfg(sp, mi) ) { si.m_name = ""; } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::TupleItem& i) const override { DEBUG("#[cfg] tuple item - " << mi); if( !check_cfg(sp, mi) ) { i.m_type = ::TypeRef(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::EnumVariant& i) const override { DEBUG("#[cfg] enum variant - " << mi); if( !check_cfg(sp, mi) ) { i.m_name = ""; } } }; STATIC_MACRO("cfg", CCfgExpander); STATIC_DECORATOR("cfg", CCfgHandler); <commit_msg>Expand/cfg - Support #[cfg] on crates by nuking all items<commit_after>/* */ #include <synext.hpp> #include <parse/tokentree.hpp> #include <parse/lex.hpp> #include <parse/common.hpp> #include "cfg.hpp" #include <ast/expr.hpp> // Needed to clear a ExprNodeP #include <ast/crate.hpp> #include <map> #include <set> ::std::map< ::std::string, ::std::string> g_cfg_values; ::std::map< ::std::string, ::std::function<bool(const ::std::string&)> > g_cfg_value_fcns; ::std::set< ::std::string > g_cfg_flags; void Cfg_SetFlag(::std::string name) { g_cfg_flags.insert( mv$(name) ); } void Cfg_SetValue(::std::string name, ::std::string val) { g_cfg_values.insert( ::std::make_pair(mv$(name), mv$(val)) ); } void Cfg_SetValueCb(::std::string name, ::std::function<bool(const ::std::string&)> cb) { g_cfg_value_fcns.insert( ::std::make_pair(mv$(name), mv$(cb)) ); } bool check_cfg(Span sp, const ::AST::MetaItem& mi) { if( mi.has_sub_items() ) { // Must be `any`/`not`/`all` if( mi.name() == "any" || mi.name() == "cfg" ) { for(const auto& si : mi.items()) { if( check_cfg(sp, si) ) return true; } return false; } else if( mi.name() == "not" ) { if( mi.items().size() != 1 ) ERROR(sp, E0000, "cfg(not()) with != 1 argument"); return !check_cfg(sp, mi.items()[0]); } else if( mi.name() == "all" ) { for(const auto& si : mi.items()) { if( ! check_cfg(sp, si) ) return false; } return true; } else { // oops ERROR(sp, E0000, "Unknown cfg() function - " << mi.name()); } } else if( mi.has_string() ) { // Equaliy auto it = g_cfg_values.find(mi.name()); if( it != g_cfg_values.end() ) { DEBUG(""<<mi.name()<<": '"<<it->second<<"' == '"<<mi.string()<<"'"); return it->second == mi.string(); } auto it2 = g_cfg_value_fcns.find(mi.name()); if(it2 != g_cfg_value_fcns.end() ) { DEBUG(""<<mi.name()<<": ('"<<mi.string()<<"')?"); return it2->second( mi.string() ); } WARNING(sp, W0000, "Unknown cfg() param '" << mi.name() << "'"); return false; } else { // Flag auto it = g_cfg_flags.find(mi.name()); return (it != g_cfg_flags.end()); } BUG(sp, "Fell off the end of check_cfg"); } class CCfgExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override { if( ident != "" ) { ERROR(sp, E0000, "cfg! doesn't take an identifier"); } auto lex = TTStream(tt); auto attrs = Parse_MetaItem(lex); DEBUG("cfg!() - " << attrs); if( check_cfg(sp, attrs) ) { return box$( TTStreamO(TokenTree(TOK_RWORD_TRUE )) ); } else { return box$( TTStreamO(TokenTree(TOK_RWORD_FALSE)) ); } } }; class CCfgHandler: public ExpandDecorator { AttrStage stage() const override { return AttrStage::Pre; } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate) const override { DEBUG("#[cfg] crate - " << mi); // Ignore, as #[cfg] on a crate is handled in expand/mod.cpp if( check_cfg(sp, mi) ) { } else { crate.m_root_module.items().clear(); } } void handle(const Span& sp, const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item&i) const override { TRACE_FUNCTION_FR("#[cfg] item - " << mi, (i.is_None() ? "Deleted" : "")); if( check_cfg(sp, mi) ) { // Leave } else { i = AST::Item::make_None({}); } } void handle(const Span& sp, const AST::MetaItem& mi, ::AST::Crate& crate, ::std::unique_ptr<AST::ExprNode>& expr) const override { DEBUG("#[cfg] expr - " << mi); if( check_cfg(sp, mi) ) { // Leave } else { expr.reset(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, const AST::Module& mod, AST::ImplDef& impl) const override { DEBUG("#[cfg] impl - " << mi); if( check_cfg(sp, mi) ) { // Leave } else { impl.type() = ::TypeRef(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::StructItem& si) const override { DEBUG("#[cfg] struct item - " << mi); if( !check_cfg(sp, mi) ) { si.m_name = ""; } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::TupleItem& i) const override { DEBUG("#[cfg] tuple item - " << mi); if( !check_cfg(sp, mi) ) { i.m_type = ::TypeRef(); } } void handle(const Span& sp, const AST::MetaItem& mi, AST::Crate& crate, ::AST::EnumVariant& i) const override { DEBUG("#[cfg] enum variant - " << mi); if( !check_cfg(sp, mi) ) { i.m_name = ""; } } }; STATIC_MACRO("cfg", CCfgExpander); STATIC_DECORATOR("cfg", CCfgHandler); <|endoftext|>
<commit_before>#include <asymmTree.hpp> #include <point.hpp> #include <random> #include <fstream> template<typename realScalarType> class GaussLikelihood { public: GaussLikelihood(size_t numDims) :mNumDims(numDims) { } realScalarType logLik(std::vector<realScalarType> const & x) { assert(x.size()==mNumDims); // assume that the mean and sigma in all dimensions are (0,1) realScalarType llik(0); for(size_t i=0;i<mNumDims;++i) { llik -= x[i]*x[i]; } return 0.5*llik; } private: size_t mNumDims; }; int testConstructor(void) { typedef point<double> pointType; typedef std::vector<pointType> pointsArrayType; typedef asymmTree<pointType> asymmTreeType; typedef GaussLikelihood<double> GaussLikelihoodType; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(-5.,5.); const size_t numDims = 3; const size_t numPoints = 500; // define the bounds pointType boundMin(numDims,double(0)); pointType boundMax(numDims,double(0)); for(size_t i=0;i<numDims;++i) { boundMin[i] = -double(5); boundMax[i] = double(5); } // define the Gauss dist for computing weights GaussLikelihoodType gauss(numDims); // define the points array for the tree pointsArrayType pts(numPoints); for(size_t i=0;i<numPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { coords[j] = distribution(generator); } // compute the weight double weight = gauss.logLik(coords); pointType pv(coords,weight); pts[i] = pv; } size_t threshold = 200; size_t treeIndex = 0; size_t level = 0; asymmTreeType ast(pts,boundMin,boundMax,threshold,treeIndex,level); std::ofstream outFile; outFile.open("tree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); return EXIT_SUCCESS; } int testAsymmTreeInit(void) { typedef point<double> pointType; typedef std::vector<pointType> pointsArrayType; typedef asymmTree<pointType> asymmTreeType; typedef GaussLikelihood<double> GaussLikelihoodType; //asymmTreeType ast; std::default_random_engine generator; std::uniform_real_distribution<double> distribution0(-5.,5.); std::uniform_real_distribution<double> distribution1(-5.,15.); const size_t numDims = 2; const size_t numPoints = 500; // define the bounds pointType boundMin(numDims,double(0)); pointType boundMax(numDims,double(0)); for(size_t i=0;i<numDims;++i) { if(i==0) { boundMin[i] = -double(5); boundMax[i] = double(5); } else { boundMin[i] = -double(5); boundMax[i] = double(15); } } // define the Gauss dist for computing weights GaussLikelihoodType gauss(numDims); // define the points array for the tree pointsArrayType pts(numPoints); // assign points and their weights std::ofstream outFile; outFile.open("points.dat",std::ios::trunc); for(size_t i=0;i<numPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { if(j==0) { coords[j] = distribution0(generator); } else { coords[j] = distribution1(generator); } } // compute the weight double weight = gauss.logLik(coords); for(size_t j=0;j<coords.size();++j) { outFile<<coords[j]<<","; } outFile<<weight<<std::endl; pointType pv(coords,weight); pts[i] = pv; } outFile.close(); asymmTreeType ast(pts,boundMin,boundMax,200,0,0); outFile.open("tree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); std::vector<size_t> inds; ast.getTreeIndices(inds); for(size_t i=0;i<inds.size();++i) { std::cout<<i<<"\t"<<inds[i]<<std::endl; } //return EXIT_SUCCESS; // delete some nodes ast.deleteNodes(-50.0); outFile.open("delTree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); std::cout<<"After deletion we get"<<std::endl; std::vector<size_t> newInds; ast.getTreeIndices(newInds); for(size_t i=0;i<newInds.size();++i) { std::cout<<i<<"\t"<<newInds[i]<<std::endl; } pointType bMin; pointType bMax; ast.getBounds(bMin,bMax,size_t(3)); std::cout<<"Bound min is "<<bMin[0]<<"\t"<<bMin[1]<<std::endl; std::cout<<"Bound max is "<<bMax[0]<<"\t"<<bMax[1]<<std::endl; pointType randPnt = ast.randomPoint(); outFile.open("newRandPoint.dat",std::ios::trunc); for(size_t i=0;i<randPnt.size()-1;++i) { outFile<<randPnt[i]<<","; } outFile<<randPnt[randPnt.size()-1]<<std::endl; outFile.close(); return EXIT_SUCCESS; // get some more points to add outFile.open("newPoints.dat",std::ios::trunc); const size_t numNewPoints = 500; //numPoints/2 pointsArrayType ptsNew(numNewPoints); for(size_t i=0;i<numNewPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { if(j==0) { coords[j] = distribution0(generator); outFile<<coords[j]<<","; } else { coords[j] = distribution1(generator); outFile<<coords[j]<<","; } } // compute the weight double weight = gauss.logLik(coords); outFile<<weight<<std::endl; pointType pv(coords,weight); ptsNew[i] = pv; } outFile.close(); /* ast.addPoints(ptsNew); outFile.open("newTree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); */ return EXIT_SUCCESS; } int main(void) { int ret = 0; ret += (int)testConstructor(); //ret += (int)testAsymmTreeInit(); return ret; } <commit_msg>multi-dim space tested<commit_after>#include <asymmTree.hpp> #include <point.hpp> #include <random> #include <fstream> template<typename realScalarType> class GaussLikelihood { public: GaussLikelihood(size_t numDims) :mNumDims(numDims) { } realScalarType logLik(std::vector<realScalarType> const & x) { assert(x.size()==mNumDims); // assume that the mean and sigma in all dimensions are (0,1) realScalarType llik(0); for(size_t i=0;i<mNumDims;++i) { llik -= x[i]*x[i]; } return 0.5*llik; } private: size_t mNumDims; }; int testConstructor(void) { typedef point<double> pointType; typedef std::vector<pointType> pointsArrayType; typedef asymmTree<pointType> asymmTreeType; typedef GaussLikelihood<double> GaussLikelihoodType; std::default_random_engine generator; std::uniform_real_distribution<double> distribution(-5.,5.); const size_t numDims = 5; const size_t numPoints = 1000; // define the bounds pointType boundMin(numDims,double(0)); pointType boundMax(numDims,double(0)); for(size_t i=0;i<numDims;++i) { boundMin[i] = -double(5); boundMax[i] = double(5); } // define the Gauss dist for computing weights GaussLikelihoodType gauss(numDims); // define the points array for the tree pointsArrayType pts(numPoints); for(size_t i=0;i<numPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { coords[j] = distribution(generator); } // compute the weight double weight = gauss.logLik(coords); pointType pv(coords,weight); pts[i] = pv; } size_t threshold = 100; size_t treeIndex = 0; size_t level = 0; asymmTreeType ast(pts,boundMin,boundMax,threshold,treeIndex,level); std::ofstream outFile; outFile.open("tree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); return EXIT_SUCCESS; } int testAsymmTreeInit(void) { typedef point<double> pointType; typedef std::vector<pointType> pointsArrayType; typedef asymmTree<pointType> asymmTreeType; typedef GaussLikelihood<double> GaussLikelihoodType; //asymmTreeType ast; std::default_random_engine generator; std::uniform_real_distribution<double> distribution0(-5.,5.); std::uniform_real_distribution<double> distribution1(-5.,15.); const size_t numDims = 2; const size_t numPoints = 500; // define the bounds pointType boundMin(numDims,double(0)); pointType boundMax(numDims,double(0)); for(size_t i=0;i<numDims;++i) { if(i==0) { boundMin[i] = -double(5); boundMax[i] = double(5); } else { boundMin[i] = -double(5); boundMax[i] = double(15); } } // define the Gauss dist for computing weights GaussLikelihoodType gauss(numDims); // define the points array for the tree pointsArrayType pts(numPoints); // assign points and their weights std::ofstream outFile; outFile.open("points.dat",std::ios::trunc); for(size_t i=0;i<numPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { if(j==0) { coords[j] = distribution0(generator); } else { coords[j] = distribution1(generator); } } // compute the weight double weight = gauss.logLik(coords); for(size_t j=0;j<coords.size();++j) { outFile<<coords[j]<<","; } outFile<<weight<<std::endl; pointType pv(coords,weight); pts[i] = pv; } outFile.close(); asymmTreeType ast(pts,boundMin,boundMax,200,0,0); outFile.open("tree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); std::vector<size_t> inds; ast.getTreeIndices(inds); for(size_t i=0;i<inds.size();++i) { std::cout<<i<<"\t"<<inds[i]<<std::endl; } //return EXIT_SUCCESS; // delete some nodes ast.deleteNodes(-50.0); outFile.open("delTree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); std::cout<<"After deletion we get"<<std::endl; std::vector<size_t> newInds; ast.getTreeIndices(newInds); for(size_t i=0;i<newInds.size();++i) { std::cout<<i<<"\t"<<newInds[i]<<std::endl; } pointType bMin; pointType bMax; ast.getBounds(bMin,bMax,size_t(3)); std::cout<<"Bound min is "<<bMin[0]<<"\t"<<bMin[1]<<std::endl; std::cout<<"Bound max is "<<bMax[0]<<"\t"<<bMax[1]<<std::endl; pointType randPnt = ast.randomPoint(); outFile.open("newRandPoint.dat",std::ios::trunc); for(size_t i=0;i<randPnt.size()-1;++i) { outFile<<randPnt[i]<<","; } outFile<<randPnt[randPnt.size()-1]<<std::endl; outFile.close(); return EXIT_SUCCESS; // get some more points to add outFile.open("newPoints.dat",std::ios::trunc); const size_t numNewPoints = 500; //numPoints/2 pointsArrayType ptsNew(numNewPoints); for(size_t i=0;i<numNewPoints;++i) { // get the coordinates of the point std::vector<double> coords(numDims,0.); for(size_t j=0;j<numDims;++j) { if(j==0) { coords[j] = distribution0(generator); outFile<<coords[j]<<","; } else { coords[j] = distribution1(generator); outFile<<coords[j]<<","; } } // compute the weight double weight = gauss.logLik(coords); outFile<<weight<<std::endl; pointType pv(coords,weight); ptsNew[i] = pv; } outFile.close(); /* ast.addPoints(ptsNew); outFile.open("newTree.dat",std::ios::trunc); ast.dumpTree(outFile); outFile.close(); */ return EXIT_SUCCESS; } int main(void) { int ret = 0; ret += (int)testConstructor(); //ret += (int)testAsymmTreeInit(); return ret; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator_part.h" #include "akregator_view.h" #include "akregatorconfig.h" #include <kparts/genericfactory.h> #include <kapplication.h> #include <kinstance.h> #include <kaction.h> #include <kactionclasses.h> #include <kstandarddirs.h> #include <kstdaction.h> #include <kfiledialog.h> #include <qfile.h> using namespace Akregator; typedef KParts::GenericFactory< aKregatorPart > aKregatorFactory; K_EXPORT_COMPONENT_FACTORY( libakregatorpart, aKregatorFactory ) aKregatorPart::aKregatorPart( QWidget *parentWidget, const char * /*widgetName*/, QObject *parent, const char *name, const QStringList& ) : KParts::ReadWritePart(parent, name) { // we need an instance setInstance( aKregatorFactory::instance() ); m_view=new aKregatorView(this, parentWidget, "Akregator View"); extension=new KParts::BrowserExtension(this, "ak_extension"); // notify the part that this is our internal widget setWidget(m_view); // create our actions KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection()); KStdAction::save(this, SLOT(save()), actionCollection()); recentFilesAction = KStdAction::openRecent( this, SLOT(openURL(const KURL&)), actionCollection(), "file_open_recent" ); new KAction(i18n("&Import Feeds..."), "", "", this, SLOT(fileImport()), actionCollection(), "file_import"); /* -- ACTIONS */ /* --- Feed popup menu */ new KAction(i18n("&Add..."), "bookmark_add", "Alt+Insert", m_view, SLOT(slotFeedAdd()), actionCollection(), "feed_add"); new KAction(i18n("New &Folder..."), "folder_new", "Alt+Shift+Insert", m_view, SLOT(slotFeedAddGroup()), actionCollection(), "feed_add_group"); new KAction(i18n("&Delete"), "editdelete", "Shift+Delete", m_view, SLOT(slotFeedRemove()), actionCollection(), "feed_remove"); new KAction(i18n("&Edit"), "edit", "F2", m_view, SLOT(slotFeedModify()), actionCollection(), "feed_modify"); new KAction(i18n("&Fetch"), "down", "Alt+Ctrl+F", m_view, SLOT(slotFetchCurrentFeed()), actionCollection(), "feed_fetch"); new KAction(i18n("Fe&tch All"), "bottom", "Alt+Ctrl+A", m_view, SLOT(slotFetchAllFeeds()), actionCollection(), "feed_fetch_all"); new KAction(i18n("Mark All as Read"), "", "Ctrl+R", m_view, SLOT(slotMarkAllRead()), actionCollection(), "feed_mark_all_as_read"); KRadioAction *ra=new KRadioAction(i18n("&Normal View"), "view_top_bottom", "Alt+Ctrl+1", m_view, SLOT(slotNormalView()), actionCollection(), "normal_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Widescreen View"), "view_left_right", "Alt+Ctrl+2", m_view, SLOT(slotWidescreenView()), actionCollection(), "widescreen_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Combined View"), "view_text", "Alt+Ctrl+3", m_view, SLOT(slotCombinedView()), actionCollection(), "combined_view"); ra->setExclusiveGroup( "ViewMode" ); // set our XML-UI resource file setXMLFile("akregator_part.rc"); readRecentFileEntries(); // we are read-write by default setReadWrite(true); // we are not modified since we haven't done anything yet setModified(false); } aKregatorPart::~aKregatorPart() { Settings::writeConfig(); } void aKregatorPart::readRecentFileEntries() { KConfig *config = new KConfig("akregatorrc"); // move to shell! recentFilesAction->loadEntries(config,"Recent Files"); delete config; } void aKregatorPart::setReadWrite(bool rw) { ReadWritePart::setReadWrite(rw); } void aKregatorPart::setModified(bool modified) { // get a handle on our Save action and make sure it is valid KAction *save = actionCollection()->action(KStdAction::stdName(KStdAction::Save)); if (!save) return; // if so, we either enable or disable it based on the current // state if (modified) save->setEnabled(true); else save->setEnabled(false); // in any event, we want our parent to do it's thing ReadWritePart::setModified(modified); } void aKregatorPart::changePart(KParts::Part *p) { emit partChanged(p); } void aKregatorPart::setStatusBar(const QString &text) { emit setStatusBarText(text); } void aKregatorPart::setProgress(int percent) { emit extension->loadingProgress(percent); } /*************************************************************************************************/ /* LOAD */ /*************************************************************************************************/ bool aKregatorPart::openURL(const KURL& url) { recentFilesAction->addURL(url); return inherited::openURL(url); } bool aKregatorPart::openFile() { // m_file is always local so we can use QFile on it QFile file(m_file); if (file.open(IO_ReadOnly) == false) return false; setProgress(0); kapp->processEvents(); // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return false; if (!m_view->loadFeeds(doc)) // will take care of building feeds tree and loading archive return false; // just for fun, set the status bar setStatusBar( m_url.prettyURL() ); return true; } /*************************************************************************************************/ /* SAVE */ /*************************************************************************************************/ bool aKregatorPart::saveFile() { // if we aren't read-write, return immediately if (isReadWrite() == false) return false; // m_file is always local, so we use QFile QFile file(m_file); if (file.open(IO_WriteOnly) == false) return fileSaveAs(); // use QTextStream to dump the text to the file QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // Write OPML data file. // Archive data files are saved elsewhere. QDomDocument newdoc; QDomElement root = newdoc.createElement( "opml" ); root.setAttribute( "version", "1.0" ); newdoc.appendChild( root ); QDomElement head = newdoc.createElement( "head" ); root.appendChild( head ); QDomElement title = newdoc.createElement( "text" ); head.appendChild( title ); QDomText t = newdoc.createTextNode( "aKregator Feeds" ); title.appendChild( t ); QDomElement body = newdoc.createElement( "body" ); root.appendChild( body ); m_view->storeTree( body, newdoc); stream << newdoc.toString(); file.close(); return true; } void aKregatorPart::importFile(QString file_name) { QFile file(file_name); if (file.open(IO_ReadOnly) == false) return; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return; if (m_view->importFeeds(doc)) setModified(true); } /*************************************************************************************************/ /* SLOTS */ /*************************************************************************************************/ void aKregatorPart::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked QString file_name = KFileDialog::getOpenFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) openURL(file_name); } bool aKregatorPart::fileSaveAs() { // this slot is called whenever the File->Save As menu is selected, QString file_name = KFileDialog::getSaveFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) { saveAs(file_name); return true; } return false; } void aKregatorPart::fileImport() { QString file_name = KFileDialog::getOpenFileName( locate( "appdata", "kde.opml" ), "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) importFile(file_name); } /*************************************************************************************************/ /* STATIC METHODS */ /*************************************************************************************************/ KAboutData* aKregatorPart::s_about = 0L; KAboutData *aKregatorPart::createAboutData() { if ( !s_about ) { s_about = new KAboutData("akregatorpart", I18N_NOOP("aKregatorPart"), "0.9", I18N_NOOP("This is a KPart for RSS aggregator"), KAboutData::License_GPL, "(C) 2004 Stanislav Karchebny", 0, "http://berk.upnet.ru/projects/kde/akregator", "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Stanislav Karchebny", I18N_NOOP("Author, Developer, Maintainer"), "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Sashmit Bhaduri", I18N_NOOP("Developer"), "smt@vfemail.net"); } return s_about; } #include "akregator_part.moc" <commit_msg>hide statusbar on feed list load error<commit_after>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator_part.h" #include "akregator_view.h" #include "akregatorconfig.h" #include <kparts/genericfactory.h> #include <kapplication.h> #include <kinstance.h> #include <kaction.h> #include <kactionclasses.h> #include <kstandarddirs.h> #include <kstdaction.h> #include <kfiledialog.h> #include <qfile.h> using namespace Akregator; typedef KParts::GenericFactory< aKregatorPart > aKregatorFactory; K_EXPORT_COMPONENT_FACTORY( libakregatorpart, aKregatorFactory ) aKregatorPart::aKregatorPart( QWidget *parentWidget, const char * /*widgetName*/, QObject *parent, const char *name, const QStringList& ) : KParts::ReadWritePart(parent, name) { // we need an instance setInstance( aKregatorFactory::instance() ); m_view=new aKregatorView(this, parentWidget, "Akregator View"); extension=new KParts::BrowserExtension(this, "ak_extension"); // notify the part that this is our internal widget setWidget(m_view); // create our actions KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection()); KStdAction::save(this, SLOT(save()), actionCollection()); recentFilesAction = KStdAction::openRecent( this, SLOT(openURL(const KURL&)), actionCollection(), "file_open_recent" ); new KAction(i18n("&Import Feeds..."), "", "", this, SLOT(fileImport()), actionCollection(), "file_import"); /* -- ACTIONS */ /* --- Feed popup menu */ new KAction(i18n("&Add..."), "bookmark_add", "Alt+Insert", m_view, SLOT(slotFeedAdd()), actionCollection(), "feed_add"); new KAction(i18n("New &Folder..."), "folder_new", "Alt+Shift+Insert", m_view, SLOT(slotFeedAddGroup()), actionCollection(), "feed_add_group"); new KAction(i18n("&Delete"), "editdelete", "Shift+Delete", m_view, SLOT(slotFeedRemove()), actionCollection(), "feed_remove"); new KAction(i18n("&Edit"), "edit", "F2", m_view, SLOT(slotFeedModify()), actionCollection(), "feed_modify"); new KAction(i18n("&Fetch"), "down", "Alt+Ctrl+F", m_view, SLOT(slotFetchCurrentFeed()), actionCollection(), "feed_fetch"); new KAction(i18n("Fe&tch All"), "bottom", "Alt+Ctrl+A", m_view, SLOT(slotFetchAllFeeds()), actionCollection(), "feed_fetch_all"); new KAction(i18n("Mark All as Read"), "", "Ctrl+R", m_view, SLOT(slotMarkAllRead()), actionCollection(), "feed_mark_all_as_read"); KRadioAction *ra=new KRadioAction(i18n("&Normal View"), "view_top_bottom", "Alt+Ctrl+1", m_view, SLOT(slotNormalView()), actionCollection(), "normal_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Widescreen View"), "view_left_right", "Alt+Ctrl+2", m_view, SLOT(slotWidescreenView()), actionCollection(), "widescreen_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Combined View"), "view_text", "Alt+Ctrl+3", m_view, SLOT(slotCombinedView()), actionCollection(), "combined_view"); ra->setExclusiveGroup( "ViewMode" ); // set our XML-UI resource file setXMLFile("akregator_part.rc"); readRecentFileEntries(); // we are read-write by default setReadWrite(true); // we are not modified since we haven't done anything yet setModified(false); } aKregatorPart::~aKregatorPart() { Settings::writeConfig(); } void aKregatorPart::readRecentFileEntries() { KConfig *config = new KConfig("akregatorrc"); // move to shell! recentFilesAction->loadEntries(config,"Recent Files"); delete config; } void aKregatorPart::setReadWrite(bool rw) { ReadWritePart::setReadWrite(rw); } void aKregatorPart::setModified(bool modified) { // get a handle on our Save action and make sure it is valid KAction *save = actionCollection()->action(KStdAction::stdName(KStdAction::Save)); if (!save) return; // if so, we either enable or disable it based on the current // state if (modified) save->setEnabled(true); else save->setEnabled(false); // in any event, we want our parent to do it's thing ReadWritePart::setModified(modified); } void aKregatorPart::changePart(KParts::Part *p) { emit partChanged(p); } void aKregatorPart::setStatusBar(const QString &text) { emit setStatusBarText(text); } void aKregatorPart::setProgress(int percent) { emit extension->loadingProgress(percent); } /*************************************************************************************************/ /* LOAD */ /*************************************************************************************************/ bool aKregatorPart::openURL(const KURL& url) { recentFilesAction->addURL(url); return inherited::openURL(url); } bool aKregatorPart::openFile() { // m_file is always local so we can use QFile on it QFile file(m_file); if (file.open(IO_ReadOnly) == false) return false; setProgress(0); kapp->processEvents(); // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) { emit extension->loadingProgress(-1); return false; } if (!m_view->loadFeeds(doc)) // will take care of building feeds tree and loading archive { emit extension->loadingProgress(-1); return false; } // just for fun, set the status bar setStatusBar( m_url.prettyURL() ); return true; } /*************************************************************************************************/ /* SAVE */ /*************************************************************************************************/ bool aKregatorPart::saveFile() { // if we aren't read-write, return immediately if (isReadWrite() == false) return false; // m_file is always local, so we use QFile QFile file(m_file); if (file.open(IO_WriteOnly) == false) return fileSaveAs(); // use QTextStream to dump the text to the file QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // Write OPML data file. // Archive data files are saved elsewhere. QDomDocument newdoc; QDomElement root = newdoc.createElement( "opml" ); root.setAttribute( "version", "1.0" ); newdoc.appendChild( root ); QDomElement head = newdoc.createElement( "head" ); root.appendChild( head ); QDomElement title = newdoc.createElement( "text" ); head.appendChild( title ); QDomText t = newdoc.createTextNode( "aKregator Feeds" ); title.appendChild( t ); QDomElement body = newdoc.createElement( "body" ); root.appendChild( body ); m_view->storeTree( body, newdoc); stream << newdoc.toString(); file.close(); return true; } void aKregatorPart::importFile(QString file_name) { QFile file(file_name); if (file.open(IO_ReadOnly) == false) return; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return; if (m_view->importFeeds(doc)) setModified(true); } /*************************************************************************************************/ /* SLOTS */ /*************************************************************************************************/ void aKregatorPart::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked QString file_name = KFileDialog::getOpenFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) openURL(file_name); } bool aKregatorPart::fileSaveAs() { // this slot is called whenever the File->Save As menu is selected, QString file_name = KFileDialog::getSaveFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) { saveAs(file_name); return true; } return false; } void aKregatorPart::fileImport() { QString file_name = KFileDialog::getOpenFileName( locate( "appdata", "kde.opml" ), "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) importFile(file_name); } /*************************************************************************************************/ /* STATIC METHODS */ /*************************************************************************************************/ KAboutData* aKregatorPart::s_about = 0L; KAboutData *aKregatorPart::createAboutData() { if ( !s_about ) { s_about = new KAboutData("akregatorpart", I18N_NOOP("aKregatorPart"), "0.9", I18N_NOOP("This is a KPart for RSS aggregator"), KAboutData::License_GPL, "(C) 2004 Stanislav Karchebny", 0, "http://berk.upnet.ru/projects/kde/akregator", "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Stanislav Karchebny", I18N_NOOP("Author, Developer, Maintainer"), "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Sashmit Bhaduri", I18N_NOOP("Developer"), "smt@vfemail.net"); } return s_about; } #include "akregator_part.moc" <|endoftext|>
<commit_before>#include "GUI.hpp" #include "Level.hpp" #include "FROG/Control.hpp" #include "FROG/Control/ControlComponent.hpp" #include "FROG/Debug.hpp" #include "FROG/Translator.hpp" #include "FROG/App.hpp" #include "FROG/Random.hpp" #include "FROG/Rendering/Sprite.hpp" #include "FROG/Rendering/TextSprite.hpp" #include "FROG/Physics/PhysicBody.hpp" #include "MovePlayer.hpp" #include "JoystickMover.hpp" #include "FROG/Rendering/RenderingComponent.hpp" #include <SFML/Graphics.hpp> #include <iostream> // TODO remove using namespace frog; #define PLAYER_SPEED 512 class Collider : virtual public sap::ActionManager{ private: std::shared_ptr<Player> m_player; Renderer * m_renderer; std::list<std::shared_ptr<GameObject> > * m_targets; public: Collider(std::shared_ptr<Player> p, std::list< std::shared_ptr<GameObject> > * t, Renderer * r) : m_player(p), m_renderer(r), m_targets(t) {} virtual void onCollision(sap::Collisionable * a, sap::Collisionable * b){ } virtual void onSeparation(sap::Collisionable *, sap::Collisionable *){ } }; const unsigned short TERRAIN_LAYER = 0; const unsigned short TARGET_LAYER = 1; const unsigned short PLAYER_LAYER = 2; const unsigned short ENEMY_LAYER = 3; const unsigned short GUI_LAYER = 4; Level::Level(AppInfo& appinfo) : Scene(), m_appinfo(appinfo), m_player(new Player), m_terrain(new GameObject), m_gui(new GameObject) { Collider * am = new Collider(m_player, &m_targets, m_renderer); m_collider = new sap::LSAP(am); m_fontManager.loadFromFile("assets/fonts/Hyperspace_Bold.ttf", GUI_FONT); } Level::~Level() { // delete m_player; } void Level::enter() { setControls(m_player.get(), m_appinfo ); m_terrain->addComponent( new Sprite(m_textureManager.get("TERRAIN_TEXTURE") ), "RENDERING" ); m_terrain->transform->setPosition(0, 0); m_terrain->transform->layer = TERRAIN_LAYER; addObject(m_terrain); m_player->addComponent( new Sprite(m_textureManager.get("FROG_TEXTURE") ), "RENDERING" ); m_player->transform->setPosition( 400, 400 ); m_player->transform->layer = PLAYER_LAYER; addObject(m_player); std::shared_ptr<GUI> pgui(new GUI(800, 64, m_fontManager.get(GUI_FONT), 3) ); m_gui->addComponent( pgui, "GUI" ); m_gui->transform->layer = GUI_LAYER; m_gui->addComponent( new RenderingComponent(pgui.get() ), "RENDERING" ); addObject(m_gui); } void Level::update(const AppInfo& appinfo) { Scene::update(appinfo); // m_collider->updateObject( m_player.get() ); updateEnemies(); updateTargets(); sf::Time t = m_clock.getElapsedTime(); if( t.asSeconds() > 0.2f && m_targets.size() < 4 ){ spawnTarget(); } if(t.asSeconds() > 0.4f ){ spawnEnemy(); m_clock.restart(); } } void Level::setControls(GameObject * go, const AppInfo& appinfo) { auto moveleft = new MovePlayer(m_player.get(), -PLAYER_SPEED, 0, appinfo); auto moveright = new MovePlayer(m_player.get(), PLAYER_SPEED, 0, appinfo); auto moveup = new MovePlayer(m_player.get(), 0, -PLAYER_SPEED, appinfo); auto movedown = new MovePlayer(m_player.get(), 0, PLAYER_SPEED, appinfo); auto qkey = new KeyboardButton(sf::Keyboard::Q); auto dkey = new KeyboardButton(sf::Keyboard::D); auto zkey = new KeyboardButton(sf::Keyboard::Z); auto skey = new KeyboardButton(sf::Keyboard::S); std::shared_ptr<ControlComponent> ctrl(new ControlComponent(appinfo.eventList)); ctrl->bind(qkey, moveleft ); ctrl->bind(dkey, moveright ); ctrl->bind(zkey, moveup ); ctrl->bind(skey, movedown ); go->addComponent(ctrl, "CONTROL"); go->addComponent( new JoystickMover(PLAYER_SPEED/60.0f, (sf::Joystick::Axis)XBOX::LSTICK_X, (sf::Joystick::Axis)XBOX::LSTICK_Y, 25), "JOYSTICK"); } void Level::spawnEnemy() { std::shared_ptr<GameObject> e(new GameObject() ); e->transform->layer = ENEMY_LAYER; e->transform->setPosition(Random::get(100, 700), 50); sf::RectangleShape * r = new sf::RectangleShape(sf::Vector2f(25,25) ); r->setFillColor(sf::Color::Red); // m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) ); // m_boundingBox->setFillColor(sf::Color::Red); e->addComponent(new PhysicBody(), "PHYSICS"); auto phi = e->getComponent<PhysicBody>("PHYSICS"); phi->applyForce(sf::Vector2f(Random::get(-2,2), Random::get(4, 5.5) ) ); e->addComponent(new RenderingComponent(r), "RENDERING" ); m_ennemies.push_back(e); addObject(e); } void Level::spawnTarget() { std::shared_ptr<GameObject> e(new GameObject() ); // m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) ); // m_boundingBox->setFillColor(sf::Color::Green); e->addComponent(new Sprite(m_textureManager.get("BONUS_TEXTURE") ), "RENDERING" ); e->transform->setPosition(Random::get(100, 700), Random::get(50, 550) ); e->transform->layer = TARGET_LAYER; e->addComponent(new PhysicBody(), "PHYSICS"); auto phi = e->getComponent<PhysicBody>("PHYSICS"); phi->applyForce(sf::Vector2f(Random::get(-10, 10) / 10.f, Random::get(-10, 10) / 10.f ) ); m_targets.push_back(e); addObject(e); } void Level::updateEnemies() { for(auto it = m_ennemies.begin(); it != m_ennemies.end(); ++it) { // PhysicEngine::update( it->get() ); if((*it)->getComponent<Transform>("TRANSFORM")->getPosition().x > 800 || (*it)->getComponent<Transform>("TRANSFORM")->getPosition().y > 600) { removeObject(*it); it->reset(); *it = nullptr; } } m_ennemies.remove(nullptr); } void Level::updateTargets() { for(auto it = m_targets.begin(); it != m_targets.end(); ++it) { // PhysicEngine::update( it->get() ); // m_collider->updateObject( it->get() ); auto tr = (*it)->getComponent<Transform>("TRANSFORM"); if ( tr->getPosition().x > 800 || tr->getPosition().y > 600 || tr->getPosition().x < -32 || tr->getPosition().y < -32){ removeObject(*it); it->reset(); *it = nullptr; } } m_targets.remove(nullptr); } <commit_msg>reduced size of bonuses<commit_after>#include "GUI.hpp" #include "Level.hpp" #include "FROG/Control.hpp" #include "FROG/Control/ControlComponent.hpp" #include "FROG/Debug.hpp" #include "FROG/Translator.hpp" #include "FROG/App.hpp" #include "FROG/Random.hpp" #include "FROG/Rendering/Sprite.hpp" #include "FROG/Rendering/TextSprite.hpp" #include "FROG/Physics/PhysicBody.hpp" #include "MovePlayer.hpp" #include "JoystickMover.hpp" #include "FROG/Rendering/RenderingComponent.hpp" #include <SFML/Graphics.hpp> #include <iostream> // TODO remove using namespace frog; #define PLAYER_SPEED 512 class Collider : virtual public sap::ActionManager{ private: std::shared_ptr<Player> m_player; Renderer * m_renderer; std::list<std::shared_ptr<GameObject> > * m_targets; public: Collider(std::shared_ptr<Player> p, std::list< std::shared_ptr<GameObject> > * t, Renderer * r) : m_player(p), m_renderer(r), m_targets(t) {} virtual void onCollision(sap::Collisionable * a, sap::Collisionable * b){ } virtual void onSeparation(sap::Collisionable *, sap::Collisionable *){ } }; const unsigned short TERRAIN_LAYER = 0; const unsigned short TARGET_LAYER = 1; const unsigned short PLAYER_LAYER = 2; const unsigned short ENEMY_LAYER = 3; const unsigned short GUI_LAYER = 4; Level::Level(AppInfo& appinfo) : Scene(), m_appinfo(appinfo), m_player(new Player), m_terrain(new GameObject), m_gui(new GameObject) { Collider * am = new Collider(m_player, &m_targets, m_renderer); m_collider = new sap::LSAP(am); m_fontManager.loadFromFile("assets/fonts/Hyperspace_Bold.ttf", GUI_FONT); } Level::~Level() { // delete m_player; } void Level::enter() { setControls(m_player.get(), m_appinfo ); m_terrain->addComponent( new Sprite(m_textureManager.get("TERRAIN_TEXTURE") ), "RENDERING" ); m_terrain->transform->setPosition(0, 0); m_terrain->transform->layer = TERRAIN_LAYER; addObject(m_terrain); m_player->addComponent( new Sprite(m_textureManager.get("FROG_TEXTURE") ), "RENDERING" ); m_player->transform->setPosition( 400, 400 ); m_player->transform->layer = PLAYER_LAYER; addObject(m_player); std::shared_ptr<GUI> pgui(new GUI(800, 64, m_fontManager.get(GUI_FONT), 3) ); m_gui->addComponent( pgui, "GUI" ); m_gui->transform->layer = GUI_LAYER; m_gui->addComponent( new RenderingComponent(pgui.get() ), "RENDERING" ); addObject(m_gui); } void Level::update(const AppInfo& appinfo) { Scene::update(appinfo); // m_collider->updateObject( m_player.get() ); updateEnemies(); updateTargets(); sf::Time t = m_clock.getElapsedTime(); if( t.asSeconds() > 0.2f && m_targets.size() < 4 ){ spawnTarget(); } if(t.asSeconds() > 0.4f ){ spawnEnemy(); m_clock.restart(); } } void Level::setControls(GameObject * go, const AppInfo& appinfo) { auto moveleft = new MovePlayer(m_player.get(), -PLAYER_SPEED, 0, appinfo); auto moveright = new MovePlayer(m_player.get(), PLAYER_SPEED, 0, appinfo); auto moveup = new MovePlayer(m_player.get(), 0, -PLAYER_SPEED, appinfo); auto movedown = new MovePlayer(m_player.get(), 0, PLAYER_SPEED, appinfo); auto qkey = new KeyboardButton(sf::Keyboard::Q); auto dkey = new KeyboardButton(sf::Keyboard::D); auto zkey = new KeyboardButton(sf::Keyboard::Z); auto skey = new KeyboardButton(sf::Keyboard::S); std::shared_ptr<ControlComponent> ctrl(new ControlComponent(appinfo.eventList)); ctrl->bind(qkey, moveleft ); ctrl->bind(dkey, moveright ); ctrl->bind(zkey, moveup ); ctrl->bind(skey, movedown ); go->addComponent(ctrl, "CONTROL"); go->addComponent( new JoystickMover(PLAYER_SPEED/60.0f, (sf::Joystick::Axis)XBOX::LSTICK_X, (sf::Joystick::Axis)XBOX::LSTICK_Y, 25), "JOYSTICK"); } void Level::spawnEnemy() { std::shared_ptr<GameObject> e(new GameObject() ); e->transform->layer = ENEMY_LAYER; e->transform->setPosition(Random::get(100, 700), 50); sf::RectangleShape * r = new sf::RectangleShape(sf::Vector2f(25,25) ); r->setFillColor(sf::Color::Red); // m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) ); // m_boundingBox->setFillColor(sf::Color::Red); e->addComponent(new PhysicBody(), "PHYSICS"); auto phi = e->getComponent<PhysicBody>("PHYSICS"); phi->applyForce(sf::Vector2f(Random::get(-2,2), Random::get(4, 5.5) ) ); e->addComponent(new RenderingComponent(r), "RENDERING" ); m_ennemies.push_back(e); addObject(e); } void Level::spawnTarget() { std::shared_ptr<GameObject> e(new GameObject() ); // m_boundingBox = new sf::RectangleShape(sf::Vector2f(25, 25) ); // m_boundingBox->setFillColor(sf::Color::Green); e->addComponent(new Sprite(m_textureManager.get("BONUS_TEXTURE") ), "RENDERING" ); e->transform->setPosition(Random::get(100, 700), Random::get(50, 550) ); e->transform->layer = TARGET_LAYER; e->transform->setScale(0.5f, 0.5f); e->addComponent(new PhysicBody(), "PHYSICS"); auto phi = e->getComponent<PhysicBody>("PHYSICS"); phi->applyForce(sf::Vector2f(Random::get(-10, 10) / 10.f, Random::get(-10, 10) / 10.f ) ); m_targets.push_back(e); addObject(e); } void Level::updateEnemies() { for(auto it = m_ennemies.begin(); it != m_ennemies.end(); ++it) { // PhysicEngine::update( it->get() ); if((*it)->getComponent<Transform>("TRANSFORM")->getPosition().x > 800 || (*it)->getComponent<Transform>("TRANSFORM")->getPosition().y > 600) { removeObject(*it); it->reset(); *it = nullptr; } } m_ennemies.remove(nullptr); } void Level::updateTargets() { for(auto it = m_targets.begin(); it != m_targets.end(); ++it) { // PhysicEngine::update( it->get() ); // m_collider->updateObject( it->get() ); auto tr = (*it)->getComponent<Transform>("TRANSFORM"); if ( tr->getPosition().x > 800 || tr->getPosition().y > 600 || tr->getPosition().x < -32 || tr->getPosition().y < -32){ removeObject(*it); it->reset(); *it = nullptr; } } m_targets.remove(nullptr); } <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: examples/fit-model-simple.cpp * * Copyright 2015 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "eos/core/Landmark.hpp" #include "eos/core/LandmarkMapper.hpp" #include "eos/fitting/orthographic_camera_estimation_linear.hpp" #include "eos/fitting/RenderingParameters.hpp" #include "eos/fitting/linear_shape_fitting.hpp" #include "eos/render/utils.hpp" #include "eos/render/texture_extraction.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "boost/program_options.hpp" #include "boost/filesystem.hpp" #include <vector> #include <iostream> #include <fstream> using namespace eos; namespace po = boost::program_options; namespace fs = boost::filesystem; using eos::core::Landmark; using eos::core::LandmarkCollection; using cv::Mat; using cv::Vec2f; using cv::Vec3f; using cv::Vec4f; using std::cout; using std::endl; using std::vector; using std::string; /** * Reads an ibug .pts landmark file and returns an ordered vector with * the 68 2D landmark coordinates. * * @param[in] filename Path to a .pts file. * @return An ordered vector with the 68 ibug landmarks. */ LandmarkCollection<cv::Vec2f> read_pts_landmarks(std::string filename) { using std::getline; using cv::Vec2f; using std::string; LandmarkCollection<Vec2f> landmarks; landmarks.reserve(68); std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error(string("Could not open landmark file: " + filename)); } string line; // Skip the first 3 lines, they're header lines: getline(file, line); // 'version: 1' getline(file, line); // 'n_points : 68' getline(file, line); // '{' int ibugId = 1; while (getline(file, line)) { if (line == "}") { // end of the file break; } std::stringstream lineStream(line); Landmark<Vec2f> landmark; landmark.name = std::to_string(ibugId); if (!(lineStream >> landmark.coordinates[0] >> landmark.coordinates[1])) { throw std::runtime_error(string("Landmark format error while parsing the line: " + line)); } // From the iBug website: // "Please note that the re-annotated data for this challenge are saved in the Matlab convention of 1 being // the first index, i.e. the coordinates of the top left pixel in an image are x=1, y=1." // ==> So we shift every point by 1: landmark.coordinates[0] -= 1.0f; landmark.coordinates[1] -= 1.0f; landmarks.emplace_back(landmark); ++ibugId; } return landmarks; }; /** * This app demonstrates estimation of the camera and fitting of the shape * model of a 3D Morphable Model from an ibug LFPW image with its landmarks. * * First, the 68 ibug landmarks are loaded from the .pts file and converted * to vertex indices using the LandmarkMapper. Then, an orthographic camera * is estimated, and then, using this camera matrix, the shape is fitted * to the landmarks. */ int main(int argc, char *argv[]) { fs::path modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, outputfile; try { po::options_description desc("Allowed options"); desc.add_options() ("help,h", "display the help message") ("model,m", po::value<fs::path>(&modelfile)->required()->default_value("../share/sfm_shape_3448.bin"), "a Morphable Model stored as cereal BinaryArchive") ("image,i", po::value<fs::path>(&imagefile)->required()->default_value("data/image_0010.png"), "an input image") ("landmarks,l", po::value<fs::path>(&landmarksfile)->required()->default_value("data/image_0010.pts"), "2D landmarks for the image, in ibug .pts format") ("mapping,p", po::value<fs::path>(&mappingsfile)->required()->default_value("../share/ibug_to_sfm.txt"), "landmark identifier to model vertex number mapping") ("output,o", po::value<fs::path>(&outputfile)->required()->default_value("out"), "basename for the output rendering and obj files") ; po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); if (vm.count("help")) { cout << "Usage: fit-model-simple [options]" << endl; cout << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error& e) { cout << "Error while parsing command-line arguments: " << e.what() << endl; cout << "Use --help to display a list of options." << endl; return EXIT_FAILURE; } // Load the image, landmarks, LandmarkMapper and the Morphable Model: Mat image = cv::imread(imagefile.string()); LandmarkCollection<cv::Vec2f> landmarks; try { landmarks = read_pts_landmarks(landmarksfile.string()); } catch (const std::runtime_error& e) { cout << "Error reading the landmarks: " << e.what() << endl; return EXIT_FAILURE; } morphablemodel::MorphableModel morphable_model; try { morphable_model = morphablemodel::load_model(modelfile.string()); } catch (const std::runtime_error& e) { cout << "Error loading the Morphable Model: " << e.what() << endl; return EXIT_FAILURE; } core::LandmarkMapper landmark_mapper = mappingsfile.empty() ? core::LandmarkMapper() : core::LandmarkMapper(mappingsfile); // Draw the loaded landmarks: Mat outimg = image.clone(); for (auto&& lm : landmarks) { cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), { 255, 0, 0 }); } // These will be the final 2D and 3D points used for the fitting: vector<Vec4f> model_points; // the points in the 3D shape model vector<int> vertex_indices; // their vertex indices vector<Vec2f> image_points; // the corresponding 2D landmark points // Sub-select all the landmarks which we have a mapping for (i.e. that are defined in the 3DMM): for (int i = 0; i < landmarks.size(); ++i) { auto converted_name = landmark_mapper.convert(landmarks[i].name); if (!converted_name) { // no mapping defined for the current landmark continue; } int vertex_idx = std::stoi(converted_name.get()); Vec4f vertex = morphable_model.get_shape_model().get_mean_at_point(vertex_idx); model_points.emplace_back(vertex); vertex_indices.emplace_back(vertex_idx); image_points.emplace_back(landmarks[i].coordinates); } // Estimate the camera (pose) from the 2D - 3D point correspondences fitting::ScaledOrthoProjectionParameters pose = fitting::estimate_orthographic_projection_linear(image_points, model_points, true, image.rows); fitting::RenderingParameters rendering_params(pose, image.cols, image.rows); // The 3D head pose can be recovered as follows: float yaw_angle = glm::degrees(glm::yaw(rendering_params.get_rotation())); // and similarly for pitch and roll. // Estimate the shape coefficients by fitting the shape to the landmarks: Mat affine_from_ortho = fitting::get_3x4_affine_camera_matrix(rendering_params, image.cols, image.rows); vector<float> fitted_coeffs = fitting::fit_shape_to_landmarks_linear(morphable_model, affine_from_ortho, image_points, vertex_indices); // Obtain the full mesh with the estimated coefficients: core::Mesh mesh = morphable_model.draw_sample(fitted_coeffs, vector<float>()); // Extract the texture from the image using given mesh and camera parameters: Mat isomap = render::extract_texture(mesh, affine_from_ortho, image); // Save the mesh as textured obj: outputfile += fs::path(".obj"); core::write_textured_obj(mesh, outputfile.string()); // And save the isomap: outputfile.replace_extension(".isomap.png"); cv::imwrite(outputfile.string(), isomap); cout << "Finished fitting and wrote result mesh and isomap to files with basename " << outputfile.stem().stem() << "." << endl; return EXIT_SUCCESS; } <commit_msg>Fix compile error, make fit-model-simple use Eigen<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: examples/fit-model-simple.cpp * * Copyright 2015 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "eos/core/Landmark.hpp" #include "eos/core/LandmarkMapper.hpp" #include "eos/fitting/orthographic_camera_estimation_linear.hpp" #include "eos/fitting/RenderingParameters.hpp" #include "eos/fitting/linear_shape_fitting.hpp" #include "eos/render/utils.hpp" #include "eos/render/texture_extraction.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "boost/program_options.hpp" #include "boost/filesystem.hpp" #include <vector> #include <iostream> #include <fstream> using namespace eos; namespace po = boost::program_options; namespace fs = boost::filesystem; using eos::core::Landmark; using eos::core::LandmarkCollection; using cv::Mat; using cv::Vec2f; using cv::Vec3f; using cv::Vec4f; using std::cout; using std::endl; using std::vector; using std::string; /** * Reads an ibug .pts landmark file and returns an ordered vector with * the 68 2D landmark coordinates. * * @param[in] filename Path to a .pts file. * @return An ordered vector with the 68 ibug landmarks. */ LandmarkCollection<cv::Vec2f> read_pts_landmarks(std::string filename) { using std::getline; using cv::Vec2f; using std::string; LandmarkCollection<Vec2f> landmarks; landmarks.reserve(68); std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error(string("Could not open landmark file: " + filename)); } string line; // Skip the first 3 lines, they're header lines: getline(file, line); // 'version: 1' getline(file, line); // 'n_points : 68' getline(file, line); // '{' int ibugId = 1; while (getline(file, line)) { if (line == "}") { // end of the file break; } std::stringstream lineStream(line); Landmark<Vec2f> landmark; landmark.name = std::to_string(ibugId); if (!(lineStream >> landmark.coordinates[0] >> landmark.coordinates[1])) { throw std::runtime_error(string("Landmark format error while parsing the line: " + line)); } // From the iBug website: // "Please note that the re-annotated data for this challenge are saved in the Matlab convention of 1 being // the first index, i.e. the coordinates of the top left pixel in an image are x=1, y=1." // ==> So we shift every point by 1: landmark.coordinates[0] -= 1.0f; landmark.coordinates[1] -= 1.0f; landmarks.emplace_back(landmark); ++ibugId; } return landmarks; }; /** * This app demonstrates estimation of the camera and fitting of the shape * model of a 3D Morphable Model from an ibug LFPW image with its landmarks. * * First, the 68 ibug landmarks are loaded from the .pts file and converted * to vertex indices using the LandmarkMapper. Then, an orthographic camera * is estimated, and then, using this camera matrix, the shape is fitted * to the landmarks. */ int main(int argc, char *argv[]) { fs::path modelfile, isomapfile, imagefile, landmarksfile, mappingsfile, outputfile; try { po::options_description desc("Allowed options"); desc.add_options() ("help,h", "display the help message") ("model,m", po::value<fs::path>(&modelfile)->required()->default_value("../share/sfm_shape_3448.bin"), "a Morphable Model stored as cereal BinaryArchive") ("image,i", po::value<fs::path>(&imagefile)->required()->default_value("data/image_0010.png"), "an input image") ("landmarks,l", po::value<fs::path>(&landmarksfile)->required()->default_value("data/image_0010.pts"), "2D landmarks for the image, in ibug .pts format") ("mapping,p", po::value<fs::path>(&mappingsfile)->required()->default_value("../share/ibug_to_sfm.txt"), "landmark identifier to model vertex number mapping") ("output,o", po::value<fs::path>(&outputfile)->required()->default_value("out"), "basename for the output rendering and obj files") ; po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); if (vm.count("help")) { cout << "Usage: fit-model-simple [options]" << endl; cout << desc; return EXIT_SUCCESS; } po::notify(vm); } catch (const po::error& e) { cout << "Error while parsing command-line arguments: " << e.what() << endl; cout << "Use --help to display a list of options." << endl; return EXIT_FAILURE; } // Load the image, landmarks, LandmarkMapper and the Morphable Model: Mat image = cv::imread(imagefile.string()); LandmarkCollection<cv::Vec2f> landmarks; try { landmarks = read_pts_landmarks(landmarksfile.string()); } catch (const std::runtime_error& e) { cout << "Error reading the landmarks: " << e.what() << endl; return EXIT_FAILURE; } morphablemodel::MorphableModel morphable_model; try { morphable_model = morphablemodel::load_model(modelfile.string()); } catch (const std::runtime_error& e) { cout << "Error loading the Morphable Model: " << e.what() << endl; return EXIT_FAILURE; } core::LandmarkMapper landmark_mapper = mappingsfile.empty() ? core::LandmarkMapper() : core::LandmarkMapper(mappingsfile); // Draw the loaded landmarks: Mat outimg = image.clone(); for (auto&& lm : landmarks) { cv::rectangle(outimg, cv::Point2f(lm.coordinates[0] - 2.0f, lm.coordinates[1] - 2.0f), cv::Point2f(lm.coordinates[0] + 2.0f, lm.coordinates[1] + 2.0f), { 255, 0, 0 }); } // These will be the final 2D and 3D points used for the fitting: vector<Vec4f> model_points; // the points in the 3D shape model vector<int> vertex_indices; // their vertex indices vector<Vec2f> image_points; // the corresponding 2D landmark points // Sub-select all the landmarks which we have a mapping for (i.e. that are defined in the 3DMM): for (int i = 0; i < landmarks.size(); ++i) { auto converted_name = landmark_mapper.convert(landmarks[i].name); if (!converted_name) { // no mapping defined for the current landmark continue; } int vertex_idx = std::stoi(converted_name.get()); auto vertex = morphable_model.get_shape_model().get_mean_at_point(vertex_idx); model_points.emplace_back(Vec4f(vertex.x(), vertex.y(), vertex.z(), 1.0f)); vertex_indices.emplace_back(vertex_idx); image_points.emplace_back(landmarks[i].coordinates); } // Estimate the camera (pose) from the 2D - 3D point correspondences fitting::ScaledOrthoProjectionParameters pose = fitting::estimate_orthographic_projection_linear(image_points, model_points, true, image.rows); fitting::RenderingParameters rendering_params(pose, image.cols, image.rows); // The 3D head pose can be recovered as follows: float yaw_angle = glm::degrees(glm::yaw(rendering_params.get_rotation())); // and similarly for pitch and roll. // Estimate the shape coefficients by fitting the shape to the landmarks: Mat affine_from_ortho = fitting::get_3x4_affine_camera_matrix(rendering_params, image.cols, image.rows); vector<float> fitted_coeffs = fitting::fit_shape_to_landmarks_linear(morphable_model, affine_from_ortho, image_points, vertex_indices); // Obtain the full mesh with the estimated coefficients: core::Mesh mesh = morphable_model.draw_sample(fitted_coeffs, vector<float>()); // Extract the texture from the image using given mesh and camera parameters: Mat isomap = render::extract_texture(mesh, affine_from_ortho, image); // Save the mesh as textured obj: outputfile += fs::path(".obj"); core::write_textured_obj(mesh, outputfile.string()); // And save the isomap: outputfile.replace_extension(".isomap.png"); cv::imwrite(outputfile.string(), isomap); cout << "Finished fitting and wrote result mesh and isomap to files with basename " << outputfile.stem().stem() << "." << endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "gsspp/gsscontext.h" #include "gsspp/gssbuffer.h" #include "gsspp/gssname.h" #include "gsspp/gsscredential.h" #include "gsspp/gssmech.h" #include "gsspp/gssexception.h" #include <gssapi.h> GSSContext::GSSContext( const GSSBuffer& buff ) { import_context( buff ); } void GSSContext::clear() { OM_uint32 x; gss_delete_sec_context( &x, &_context, GSS_C_NO_BUFFER ); } bool GSSContext::initialize( GSSBuffer& input, const GSSName& target, const Flags& flags, GSSCredential cred, GSSMech mech, OM_uint32 time, gss_channel_bindings_t bindings ) { GSSBuffer recv_tok, send_tok; OM_uint32 maj_stat, min_stat, ret_flags; maj_stat = gss_init_sec_context( &min_stat, cred, &_context, target, mech, flags, time, bindings, input, 0, send_tok, &ret_flags, 0 ); if ( !valid() || ( maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED ) ) { throw GSSException( maj_stat, min_stat, "gss_init_sec_context" ); } input.swap( send_tok ); return maj_stat == GSS_S_CONTINUE_NEEDED; } void GSSContext::import_context( const GSSBuffer& buff ) { OM_uint32 maj, min; maj = gss_import_sec_context( &min, const_cast<GSSBuffer&>( buff ), &_context ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_import_sec_context" ); } } GSSBuffer GSSContext::export_context() { OM_uint32 maj, min; GSSBuffer exported; gss_export_sec_context( &min, &_context, exported ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_export_sec_context" ); } return exported; } GSSBuffer GSSContext::get_mic( const GSSBuffer& message, gss_qop_t qop = GSS_C_QOP_DEFAULT ) const { OM_uint32 maj, min; GSSBuffer mic; maj = gss_get_mic( &min, &_context, qop, message, mic ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_get_mic" ); } return mic; } bool GSSContext::verify_mic( const GSSBuffer& message, const GSSBuffer& mic ) { OM_uint32 maj, min; maj = gss_verify_mic( &min, &_context, message, mic, 0 ); if ( maj == GSS_S_COMPLETE ) return true; if ( maj == GSS_S_BAD_SIG ) return false; throw GSSException( maj, min, "gss_verify_mic" ); } GSSBuffer GSSContext::wrap( const GSSBuffer& message, bool encrypt, gss_qop_t qop ) const { return wrap( *this, message, encrypt, qop ); } GSSBuffer GSSContext::wrap( const GSSContext& context, const GSSBuffer& message, bool encrypt, gss_qop_t qop ) { OM_uint32 maj, min; GSSBuffer wrapped; maj = gss_wrap( &min, context, encrypt, qop, const_cast<GSSBuffer&>( message ), 0, wrapped ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_wrap" ); } return wrapped; } void GSSContext::wrap_in_place( GSSBuffer& message, bool encrypt, gss_qop_t qop ) const { wrap_in_place( *this, message, encrypt, qop ); } void GSSContext::wrap_in_place( const GSSContext& context, GSSBuffer& message, bool encrypt, gss_qop_t qop ) { GSSBuffer tmp( wrap( context, message, encrypt, qop ) ); message.swap( tmp ); } GSSBuffer GSSContext::unwrap( const GSSBuffer& wrapped ) const { return unwrap( *this, wrapped ); } GSSBuffer GSSContext::unwrap( const GSSContext& context, const GSSBuffer& message ) { OM_uint32 maj, min; GSSBuffer unwrapped; maj = gss_unwrap( &min, context, const_cast<GSSBuffer&>( message ), unwrapped, 0, 0 ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_unwrap" ); } return unwrapped; } void GSSContext::unwrap_in_place( GSSBuffer& wrapped ) const { unwrap_in_place( *this, wrapped ); } void GSSContext::unwrap_in_place( const GSSContext& context, GSSBuffer& message ) { GSSBuffer tmp( unwrap( context, message ) ); message.swap( tmp ); } <commit_msg>fixed compiler errors in gsscontext.cpp<commit_after>#include "gsspp/gsscontext.h" #include "gsspp/gssbuffer.h" #include "gsspp/gssname.h" #include "gsspp/gsscredential.h" #include "gsspp/gssmech.h" #include "gsspp/gssexception.h" #include <gssapi.h> GSSContext::GSSContext( const GSSBuffer& buff ) { import_context( buff ); } void GSSContext::clear() { OM_uint32 x; gss_delete_sec_context( &x, &_context, GSS_C_NO_BUFFER ); } bool GSSContext::initialize( GSSBuffer& input, const GSSName& target, const Flags& flags, GSSCredential cred, GSSMech mech, OM_uint32 time, gss_channel_bindings_t bindings ) { GSSBuffer recv_tok, send_tok; OM_uint32 maj_stat, min_stat, ret_flags; maj_stat = gss_init_sec_context( &min_stat, cred, &_context, target, mech, flags, time, bindings, input, 0, send_tok, &ret_flags, 0 ); if ( !valid() || ( maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED ) ) { throw GSSException( maj_stat, min_stat, "gss_init_sec_context" ); } input.swap( send_tok ); return maj_stat == GSS_S_CONTINUE_NEEDED; } void GSSContext::import_context( const GSSBuffer& buff ) { OM_uint32 maj, min; maj = gss_import_sec_context( &min, const_cast<GSSBuffer&>( buff ), &_context ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_import_sec_context" ); } } GSSBuffer GSSContext::export_context() { OM_uint32 maj, min; GSSBuffer exported; gss_export_sec_context( &min, &_context, exported ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_export_sec_context" ); } return exported; } GSSBuffer GSSContext::get_mic( const GSSBuffer& message, gss_qop_t qop ) const { OM_uint32 maj, min; GSSBuffer mic; maj = gss_get_mic( &min, _context, qop, const_cast<GSSBuffer&>( message ), mic ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_get_mic" ); } return mic; } bool GSSContext::verify_mic( const GSSBuffer& message, const GSSBuffer& mic ) { OM_uint32 maj, min; maj = gss_verify_mic( &min, _context, const_cast<GSSBuffer&>( message ), const_cast<GSSBuffer&>( mic ), 0 ); if ( maj == GSS_S_COMPLETE ) return true; if ( maj == GSS_S_BAD_SIG ) return false; throw GSSException( maj, min, "gss_verify_mic" ); } GSSBuffer GSSContext::wrap( const GSSBuffer& message, bool encrypt, gss_qop_t qop ) const { return wrap( *this, message, encrypt, qop ); } GSSBuffer GSSContext::wrap( const GSSContext& context, const GSSBuffer& message, bool encrypt, gss_qop_t qop ) { OM_uint32 maj, min; GSSBuffer wrapped; maj = gss_wrap( &min, context, encrypt, qop, const_cast<GSSBuffer&>( message ), 0, wrapped ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_wrap" ); } return wrapped; } void GSSContext::wrap_in_place( GSSBuffer& message, bool encrypt, gss_qop_t qop ) const { wrap_in_place( *this, message, encrypt, qop ); } void GSSContext::wrap_in_place( const GSSContext& context, GSSBuffer& message, bool encrypt, gss_qop_t qop ) { GSSBuffer tmp( wrap( context, message, encrypt, qop ) ); message.swap( tmp ); } GSSBuffer GSSContext::unwrap( const GSSBuffer& wrapped ) const { return unwrap( *this, wrapped ); } GSSBuffer GSSContext::unwrap( const GSSContext& context, const GSSBuffer& message ) { OM_uint32 maj, min; GSSBuffer unwrapped; maj = gss_unwrap( &min, context, const_cast<GSSBuffer&>( message ), unwrapped, 0, 0 ); if ( maj != GSS_S_COMPLETE ) { throw GSSException( maj, min, "gss_unwrap" ); } return unwrapped; } void GSSContext::unwrap_in_place( GSSBuffer& wrapped ) const { unwrap_in_place( *this, wrapped ); } void GSSContext::unwrap_in_place( const GSSContext& context, GSSBuffer& message ) { GSSBuffer tmp( unwrap( context, message ) ); message.swap( tmp ); } <|endoftext|>
<commit_before>#include <easylogging.h> #include "gui/window.h" #include <functional> #include <stdexcept> using namespace std::placeholders; namespace gui { const glm::vec3& initial_camera_pos = glm::vec3(0, 25, -5); const glm::vec3& initial_camera_dir = glm::vec3(-0.2f, -0.1f, 0.9f); window::window(const std::string& window_title, const glm::ivec2& dims) : m_cursor_locked(false), m_dims(dims), m_fps(60), m_fft(glm::ivec2(2048)), m_context(window_title, dims, std::bind(&window::on_mouse_up, this, _1), std::bind(&window::on_mouse_down, this, _1), std::bind(&window::on_mouse_move, this, _1), std::bind(&window::on_key_press, this, _1), std::bind(&window::on_key_up, this, _1), std::bind(&window::on_special, this, _1), std::bind(&window::on_special_up, this, _1), std::bind(&window::on_resize, this, _1), std::bind(&window::on_display, this), std::bind(&window::on_update, this)), m_bar("main", "Configuration"), d_bar("debug", "Configuration"), m_camera(m_dims, initial_camera_pos, initial_camera_dir, glm::radians(m_bar.cam_fov)), models( { std::shared_ptr<Model>(new Model("models/Lighthouse.obj")), std::shared_ptr<Model>(new Model("models/OutBuilding.obj")), std::shared_ptr<Model>(new Model("models/Terrain.obj")), std::shared_ptr<Model>(new Model("models/Tree.obj")), std::shared_ptr<Model>(new Model("models/STLamp.obj")) }), m_skybox(), #if !NO_LENS_FLARES m_overlay(m_bar.lens_density), m_aperture(m_fft), m_occlusion(), #endif m_framebuffer(m_dims), m_light_renderer() { LOG(INFO) << "All components initialized."; LOG(TRACE) << "Window resolution is " << m_dims.x << " by " << m_dims.y << " pixels."; on_update(); } void window::run() { m_context.main_loop(); } void window::on_resize(const glm::ivec2& new_dims) { m_framebuffer.resize(m_dims = new_dims); m_camera.resize(m_dims = new_dims); } void window::on_display() { //translate lamp models.back().get()->setTransform(glm::translate(glm::mat4(1.0f), d_bar.translateLight)); std::vector<light> lights; lights.push_back(skybox::calcLight(m_bar.Atmos)); for (auto& m : models) { for (light l : m.get()->getLights()) lights.push_back(l); } // --- end of light precomputations --- m_framebuffer.bind(); m_framebuffer.clear(true); m_skybox.display(m_camera,m_bar.Atmos); m_light_renderer.display(m_camera, lights); for (auto& m : models) { m.get()->display(m_camera, lights); } #if !NO_LENS_FLARES const auto& occlusion = m_occlusion.query( lights, m_framebuffer, m_camera ); m_aperture.render_flare(lights, occlusion, m_camera, m_bar.lens_flare_intensity); m_aperture.render_ghosts(lights, occlusion, m_camera, m_bar.lens_flare_intensity, m_bar.lens_ghost_count, m_bar.lens_ghost_max_size, m_bar.lens_ghost_brightness); if (m_bar.lens_overlay) { m_overlay.render(lights, occlusion, m_camera, m_bar.lens_reflectivity); } #endif m_framebuffer.render(m_bar.lens_exposure); TwDraw(); glutSwapBuffers(); m_fps.add_frame(); if (m_fps.average_ready()) { const int period = (int)(20.0 * 60.0f); int fps = (int)(1.0 / m_fps.get_average() + 0.5); LOG_EVERY_N(period, INFO) << fps << " frames per second."; } GLenum err = glGetError(); if (err != GL_NO_ERROR) { LOG(WARNING) << "OpenGL: " << (char*)gluErrorString(err) << "."; } } void window::on_update() { #if !NO_LENS_FLARES if (m_bar.lens_update_btn) { m_bar.lens_update_btn = false; m_aperture.load_aperture(m_bar.lens_aperture, m_bar.lens_aperture_f_number); } if (m_overlay.get_density() != m_bar.lens_density) { m_overlay.regenerate_film(m_bar.lens_density); } #endif float move_speed = m_bar.cam_move_speed / 60.0f; if (m_keys['w']) m_camera.move(glm::vec3(0.0f, 0.0f, -1.0f) * move_speed); if (m_keys['s']) m_camera.move(glm::vec3(0.0f, 0.0f, +1.0f) * move_speed); if (m_keys['a']) m_camera.move(glm::vec3(-1.0f, 0.0f, 0.0f) * move_speed); if (m_keys['d']) m_camera.move(glm::vec3(+1.0f, 0.0f, 0.0f) * move_speed); if (m_keys['c']) m_camera.move(glm::vec3(0.0f, -1.0f, 0.0f) * move_speed); if (m_keys[' ']) m_camera.move(glm::vec3(0.0f, +1.0f, 0.0f) * move_speed); if (m_cursor_locked) { glutWarpPointer(m_dims.x / 2, m_dims.y / 2); m_mouse.set_pos((glm::vec2)(m_dims / 2) / (float)m_dims.x); } m_camera.set_fov(glm::radians(m_bar.cam_fov)); m_bar.cam_locked = m_cursor_locked; m_bar.refresh(); if (m_keys[27 /* escape */]) { glutLeaveMainLoop(); return; } } void window::on_key_up(unsigned char key) { m_keys[key] = false; } void window::on_key_press(unsigned char key) { m_keys[key] = true; } void window::on_special_up(int key) { m_keys[key] = false; } void window::on_special(int key) { m_keys[key] = true; } void window::on_mouse_up(int button) { m_buttons[button] = false; } void window::on_mouse_down(int button) { m_buttons[button] = true; if (button == GLUT_RIGHT_BUTTON) { m_cursor_locked = !m_cursor_locked; glutSetCursor(m_cursor_locked ? GLUT_CURSOR_NONE : GLUT_CURSOR_INHERIT); } } void window::on_mouse_move(const glm::ivec2& pos) { auto mouse_pos = (glm::vec2)pos / (float)m_dims.x; if (m_cursor_locked || m_buttons[GLUT_LEFT_BUTTON]) { m_camera.turn(m_mouse.delta(mouse_pos) * m_bar.cam_sensitivity); } m_mouse.set_pos(mouse_pos); } } <commit_msg>forgot to assign title to debug_bar<commit_after>#include <easylogging.h> #include "gui/window.h" #include <functional> #include <stdexcept> using namespace std::placeholders; namespace gui { const glm::vec3& initial_camera_pos = glm::vec3(0, 25, -5); const glm::vec3& initial_camera_dir = glm::vec3(-0.2f, -0.1f, 0.9f); window::window(const std::string& window_title, const glm::ivec2& dims) : m_cursor_locked(false), m_dims(dims), m_fps(60), m_fft(glm::ivec2(2048)), m_context(window_title, dims, std::bind(&window::on_mouse_up, this, _1), std::bind(&window::on_mouse_down, this, _1), std::bind(&window::on_mouse_move, this, _1), std::bind(&window::on_key_press, this, _1), std::bind(&window::on_key_up, this, _1), std::bind(&window::on_special, this, _1), std::bind(&window::on_special_up, this, _1), std::bind(&window::on_resize, this, _1), std::bind(&window::on_display, this), std::bind(&window::on_update, this)), m_bar("main", "Configuration"), d_bar("debug", "Debug"), m_camera(m_dims, initial_camera_pos, initial_camera_dir, glm::radians(m_bar.cam_fov)), models( { std::shared_ptr<Model>(new Model("models/Lighthouse.obj")), std::shared_ptr<Model>(new Model("models/OutBuilding.obj")), std::shared_ptr<Model>(new Model("models/Terrain.obj")), std::shared_ptr<Model>(new Model("models/Tree.obj")), std::shared_ptr<Model>(new Model("models/STLamp.obj")) }), m_skybox(), #if !NO_LENS_FLARES m_overlay(m_bar.lens_density), m_aperture(m_fft), m_occlusion(), #endif m_framebuffer(m_dims), m_light_renderer() { LOG(INFO) << "All components initialized."; LOG(TRACE) << "Window resolution is " << m_dims.x << " by " << m_dims.y << " pixels."; on_update(); } void window::run() { m_context.main_loop(); } void window::on_resize(const glm::ivec2& new_dims) { m_framebuffer.resize(m_dims = new_dims); m_camera.resize(m_dims = new_dims); } void window::on_display() { //translate lamp models.back().get()->setTransform(glm::translate(glm::mat4(1.0f), d_bar.translateLight)); std::vector<light> lights; lights.push_back(skybox::calcLight(m_bar.Atmos)); for (auto& m : models) { for (light l : m.get()->getLights()) lights.push_back(l); } // --- end of light precomputations --- m_framebuffer.bind(); m_framebuffer.clear(true); m_skybox.display(m_camera,m_bar.Atmos); m_light_renderer.display(m_camera, lights); for (auto& m : models) { m.get()->display(m_camera, lights); } #if !NO_LENS_FLARES const auto& occlusion = m_occlusion.query( lights, m_framebuffer, m_camera ); m_aperture.render_flare(lights, occlusion, m_camera, m_bar.lens_flare_intensity); m_aperture.render_ghosts(lights, occlusion, m_camera, m_bar.lens_flare_intensity, m_bar.lens_ghost_count, m_bar.lens_ghost_max_size, m_bar.lens_ghost_brightness); if (m_bar.lens_overlay) { m_overlay.render(lights, occlusion, m_camera, m_bar.lens_reflectivity); } #endif m_framebuffer.render(m_bar.lens_exposure); TwDraw(); glutSwapBuffers(); m_fps.add_frame(); if (m_fps.average_ready()) { const int period = (int)(20.0 * 60.0f); int fps = (int)(1.0 / m_fps.get_average() + 0.5); LOG_EVERY_N(period, INFO) << fps << " frames per second."; } GLenum err = glGetError(); if (err != GL_NO_ERROR) { LOG(WARNING) << "OpenGL: " << (char*)gluErrorString(err) << "."; } } void window::on_update() { #if !NO_LENS_FLARES if (m_bar.lens_update_btn) { m_bar.lens_update_btn = false; m_aperture.load_aperture(m_bar.lens_aperture, m_bar.lens_aperture_f_number); } if (m_overlay.get_density() != m_bar.lens_density) { m_overlay.regenerate_film(m_bar.lens_density); } #endif float move_speed = m_bar.cam_move_speed / 60.0f; if (m_keys['w']) m_camera.move(glm::vec3(0.0f, 0.0f, -1.0f) * move_speed); if (m_keys['s']) m_camera.move(glm::vec3(0.0f, 0.0f, +1.0f) * move_speed); if (m_keys['a']) m_camera.move(glm::vec3(-1.0f, 0.0f, 0.0f) * move_speed); if (m_keys['d']) m_camera.move(glm::vec3(+1.0f, 0.0f, 0.0f) * move_speed); if (m_keys['c']) m_camera.move(glm::vec3(0.0f, -1.0f, 0.0f) * move_speed); if (m_keys[' ']) m_camera.move(glm::vec3(0.0f, +1.0f, 0.0f) * move_speed); if (m_cursor_locked) { glutWarpPointer(m_dims.x / 2, m_dims.y / 2); m_mouse.set_pos((glm::vec2)(m_dims / 2) / (float)m_dims.x); } m_camera.set_fov(glm::radians(m_bar.cam_fov)); m_bar.cam_locked = m_cursor_locked; m_bar.refresh(); if (m_keys[27 /* escape */]) { glutLeaveMainLoop(); return; } } void window::on_key_up(unsigned char key) { m_keys[key] = false; } void window::on_key_press(unsigned char key) { m_keys[key] = true; } void window::on_special_up(int key) { m_keys[key] = false; } void window::on_special(int key) { m_keys[key] = true; } void window::on_mouse_up(int button) { m_buttons[button] = false; } void window::on_mouse_down(int button) { m_buttons[button] = true; if (button == GLUT_RIGHT_BUTTON) { m_cursor_locked = !m_cursor_locked; glutSetCursor(m_cursor_locked ? GLUT_CURSOR_NONE : GLUT_CURSOR_INHERIT); } } void window::on_mouse_move(const glm::ivec2& pos) { auto mouse_pos = (glm::vec2)pos / (float)m_dims.x; if (m_cursor_locked || m_buttons[GLUT_LEFT_BUTTON]) { m_camera.turn(m_mouse.delta(mouse_pos) * m_bar.cam_sensitivity); } m_mouse.set_pos(mouse_pos); } } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020 Intel Corporation. All Rights Reserved. #include "hdr-config.h" #include "ds5/ds5-private.h" namespace librealsense { hdr_config::hdr_config(hw_monitor& hwm, std::shared_ptr<sensor_base> depth_ep) : _hwm(hwm), _sensor(depth_ep), _options_ranges_initialized(false), _is_enabled(false), _is_config_in_process(false), _has_config_changed(false), _current_hdr_sequence_index(DEFAULT_CURRENT_HDR_SEQUENCE_INDEX), _auto_exposure_to_be_restored(false), _emitter_on_off_to_be_restored(false), _id(DEFAULT_HDR_ID), _sequence_size(DEFAULT_HDR_SEQUENCE_SIZE) { _hdr_sequence_params.clear(); _hdr_sequence_params.resize(DEFAULT_HDR_SEQUENCE_SIZE); } void hdr_config::set_default_config() { float exposure_default_value = _exposure_range.def; float gain_default_value = _gain_range.def; hdr_params params_0(0, exposure_default_value, gain_default_value); _hdr_sequence_params[0] = params_0; float exposure_low_value = DEFAULT_CONFIG_LOW_EXPOSURE; float gain_min_value = _gain_range.min; hdr_params params_1(1, exposure_low_value, gain_min_value); _hdr_sequence_params[1] = params_1; } float hdr_config::get(rs2_option option) const { float rv = 0.f; switch (option) { case RS2_OPTION_SUBPRESET_ID: rv = static_cast<float>(_id); break; case RS2_OPTION_SUBPRESET_SEQUENCE_SIZE: rv = static_cast<float>(_sequence_size); break; case RS2_OPTION_SUBPRESET_SEQUENCE_ID: rv = static_cast<float>(_current_hdr_sequence_index + 1); break; case RS2_OPTION_HDR_MODE: rv = static_cast<float>(is_enabled()); break; case RS2_OPTION_EXPOSURE: try { rv = _hdr_sequence_params[_current_hdr_sequence_index]._exposure; } // should never happen catch (std::out_of_range) { throw invalid_value_exception(to_string() << "hdr_config::get(...) failed! Index is above the sequence size."); } break; case RS2_OPTION_GAIN: try { rv = _hdr_sequence_params[_current_hdr_sequence_index]._gain; } // should never happen catch (std::out_of_range) { throw invalid_value_exception(to_string() << "hdr_config::get(...) failed! Index is above the sequence size."); } break; default: throw invalid_value_exception("option is not an HDR option"); } return rv; } void hdr_config::set(rs2_option option, float value, option_range range) { if (!_options_ranges_initialized) { initialize_options_ranges(); _options_ranges_initialized = true; set_default_config(); } if (value < range.min || value > range.max) throw invalid_value_exception(to_string() << "hdr_config::set(...) failed! value is out of the option range."); switch (option) { case RS2_OPTION_SUBPRESET_ID: set_id(value); break; case RS2_OPTION_SUBPRESET_SEQUENCE_SIZE: set_sequence_size(value); break; case RS2_OPTION_SUBPRESET_SEQUENCE_ID: set_sequence_index(value); break; case RS2_OPTION_HDR_MODE: set_enable_status(value); break; case RS2_OPTION_EXPOSURE: set_exposure(value, range); break; case RS2_OPTION_GAIN: set_gain(value); break; default: throw invalid_value_exception("option is not an HDR option"); } // subpreset configuration change is immediately sent to firmware if HDR is already running if (_is_enabled && _has_config_changed) { send_sub_preset_to_fw(); } } bool hdr_config::is_config_in_process() const { return _is_config_in_process; } bool hdr_config::is_enabled() const { float rv = 0.f; command cmd(ds::GETSUBPRESETID); // if no subpreset is streaming, the firmware returns "ON_DATA_TO_RETURN" error try { auto res = _hwm.send(cmd); // if a subpreset is streaming, checking this is the current HDR sub preset rv = (res[0] == _id) ? 1.0f : 0.f; } catch (...) { rv = 0.f; } _is_enabled = (rv == 1.f); return rv; } void hdr_config::set_enable_status(float value) { if (value) { if (validate_config()) { // saving status of options that are not compatible with hdr, // so that they could be reenabled after hdr disable set_options_to_be_restored_after_disable(); send_sub_preset_to_fw(); _is_enabled = true; _has_config_changed = false; } else // msg to user to be improved later on throw invalid_value_exception("config is not valid"); } else { disable(); _is_enabled = false; // re-enabling options that were disabled in order to permit the hdr restore_options_after_disable(); } } void hdr_config::initialize_options_ranges() { _exposure_range = _sensor->get_option(RS2_OPTION_EXPOSURE).get_range(); _gain_range = _sensor->get_option(RS2_OPTION_GAIN).get_range(); } void hdr_config::set_options_to_be_restored_after_disable() { // AUTO EXPOSURE if (_sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).query()) { _sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).set(0.f); _auto_exposure_to_be_restored = true; } // EMITTER ON OFF if (_sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).query()) { //_sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).set(0.f); _emitter_on_off_to_be_restored = true; } } void hdr_config::restore_options_after_disable() { // AUTO EXPOSURE if (_auto_exposure_to_be_restored) { _sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).set(1.f); _auto_exposure_to_be_restored = false; } // EMITTER ON OFF if (_emitter_on_off_to_be_restored) { _sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).set(1.f); _emitter_on_off_to_be_restored = false; } } void hdr_config::send_sub_preset_to_fw() { // prepare sub-preset command command cmd = prepare_hdr_sub_preset_command(); auto res = _hwm.send(cmd); } void hdr_config::disable() { // sending empty sub preset std::vector<uint8_t> pattern{}; // TODO - make it usable not only for ds - use _sensor command cmd(ds::SETSUBPRESET, static_cast<int>(pattern.size())); cmd.data = pattern; auto res = _hwm.send(cmd); } //helper method - for debug only - to be deleted std::string hdrchar2hex(unsigned char n) { std::string res; do { res += "0123456789ABCDEF"[n % 16]; n >>= 4; } while (n); reverse(res.begin(), res.end()); if (res.size() == 1) { res.insert(0, "0"); } return res; } command hdr_config::prepare_hdr_sub_preset_command() const { std::vector<uint8_t> subpreset_header = prepare_sub_preset_header(); std::vector<uint8_t> subpreset_frames_config = prepare_sub_preset_frames_config(); std::vector<uint8_t> pattern{}; if (subpreset_frames_config.size() > 0) { pattern.insert(pattern.end(), &subpreset_header[0], &subpreset_header[0] + subpreset_header.size()); pattern.insert(pattern.end(), &subpreset_frames_config[0], &subpreset_frames_config[0] + subpreset_frames_config.size()); } /*std::cout << "pattern for hdr sub-preset: "; for (int i = 0; i < pattern.size(); ++i) std::cout << hdrchar2hex(pattern[i]) << " "; std::cout << std::endl; std::ofstream outFile("subpreset_bytes.txt", std::ofstream::out); outFile << "pattern for hdr sub-preset: "; for (int i = 0; i < pattern.size(); ++i) outFile << hdrchar2hex(pattern[i]) << " "; outFile << std::endl;*/ //uint8_t sub_preset_opcode = _sensor->get_set_sub_preset_opcode(); // TODO - make it usable not only for ds - use _sensor command cmd(ds::SETSUBPRESET, static_cast<int>(pattern.size())); cmd.data = pattern; return cmd; } std::vector<uint8_t> hdr_config::prepare_sub_preset_header() const { //size uint8_t header_size = 5; //id - from member (uint8_t) //iterations - always 0 so that it will be continuous until stopped uint16_t iterations = 0; //sequence size uint8_t num_of_items = static_cast<uint8_t>(_sequence_size); std::vector<uint8_t> header; header.insert(header.end(), &header_size, &header_size + 1); header.insert(header.end(), &_id, &_id + 1); header.insert(header.end(), (uint8_t*)&iterations, (uint8_t*)&iterations + 2); header.insert(header.end(), &num_of_items, &num_of_items + 1); return header; } std::vector<uint8_t> hdr_config::prepare_sub_preset_frames_config() const { //size for each frame header uint8_t frame_header_size = 4; //number of iterations for each frame uint16_t iterations = 1; // number of Controls for current frame uint8_t num_of_controls = 2; std::vector<uint8_t> frame_header; frame_header.insert(frame_header.end(), &frame_header_size, &frame_header_size + 1); frame_header.insert(frame_header.end(), (uint8_t*)&iterations, (uint8_t*)&iterations + 2); frame_header.insert(frame_header.end(), &num_of_controls, &num_of_controls + 1); std::vector<uint8_t> frames_config; for (int i = 0; i < _sequence_size; ++i) { frames_config.insert(frames_config.end(), &frame_header[0], &frame_header[0] + frame_header.size()); uint32_t exposure_value = static_cast<uint32_t>(_hdr_sequence_params[i]._exposure); frames_config.insert(frames_config.end(), &CONTROL_ID_EXPOSURE, &CONTROL_ID_EXPOSURE + 1); frames_config.insert(frames_config.end(), (uint8_t*)&exposure_value, (uint8_t*)&exposure_value + 4); uint32_t gain_value = static_cast<uint32_t>(_hdr_sequence_params[i]._gain); frames_config.insert(frames_config.end(), &CONTROL_ID_GAIN, &CONTROL_ID_GAIN + 1); frames_config.insert(frames_config.end(), (uint8_t*)&gain_value, (uint8_t*)&gain_value + 4); } return frames_config; } bool hdr_config::validate_config() const { // to be elaborated or deleted return true; } void hdr_config::set_id(float value) { int new_id = static_cast<int>(value); if (new_id != _id) { _id = new_id; } } void hdr_config::set_sequence_size(float value) { size_t new_size = static_cast<size_t>(value); if (new_size > 3 || new_size < 2) throw invalid_value_exception(to_string() << "hdr_config::set_sequence_size(...) failed! Only size 2 or 3 are supported."); if (new_size != _sequence_size) { _hdr_sequence_params.resize(new_size); _sequence_size = new_size; } } void hdr_config::set_sequence_index(float value) { size_t new_index = static_cast<size_t>(value); _is_config_in_process = (new_index != 0); if (new_index <= _hdr_sequence_params.size()) { _current_hdr_sequence_index = new_index - 1; _has_config_changed = true; } else throw invalid_value_exception(to_string() << "hdr_config::set_sequence_index(...) failed! Index above sequence size."); } void hdr_config::set_exposure(float value, option_range range) { /* TODO - add limitation on max exposure to be below frame interval - is range really needed for this?*/ _hdr_sequence_params[_current_hdr_sequence_index]._exposure = value; _has_config_changed = true; } void hdr_config::set_gain(float value) { _hdr_sequence_params[_current_hdr_sequence_index]._gain = value; _has_config_changed = true; } hdr_params::hdr_params() : _sequence_id(0), _exposure(0.f), _gain(0.f) {} hdr_params::hdr_params(int sequence_id, float exposure, float gain) : _sequence_id(sequence_id), _exposure(exposure), _gain(gain) {} hdr_params& hdr_params::operator=(const hdr_params& other) { _sequence_id = other._sequence_id; _exposure = other._exposure; _gain = other._gain; return *this; } // explanation for the sub-preset: /* the structure is: #define SUB_PRESET_BUFFER_SIZE 0x400 #pragma pack(push, 1) typedef struct SubPresetHeader { uint8_t headerSize; uint8_t id; uint16_t iterations; uint8_t numOfItems; }SubPresetHeader; typedef struct SubPresetItemHeader { uint8_t headerSize; uint16_t iterations; uint8_t numOfControls; }SubPresetItemHeader; typedef struct SubPresetControl { uint8_t controlId; uint32_t controlValue; }SubPresetControl; #pragma pack(pop) */ }<commit_msg>checking AE and emitter on off are supported before query<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020 Intel Corporation. All Rights Reserved. #include "hdr-config.h" #include "ds5/ds5-private.h" namespace librealsense { hdr_config::hdr_config(hw_monitor& hwm, std::shared_ptr<sensor_base> depth_ep) : _hwm(hwm), _sensor(depth_ep), _options_ranges_initialized(false), _is_enabled(false), _is_config_in_process(false), _has_config_changed(false), _current_hdr_sequence_index(DEFAULT_CURRENT_HDR_SEQUENCE_INDEX), _auto_exposure_to_be_restored(false), _emitter_on_off_to_be_restored(false), _id(DEFAULT_HDR_ID), _sequence_size(DEFAULT_HDR_SEQUENCE_SIZE) { _hdr_sequence_params.clear(); _hdr_sequence_params.resize(DEFAULT_HDR_SEQUENCE_SIZE); } void hdr_config::set_default_config() { float exposure_default_value = _exposure_range.def; float gain_default_value = _gain_range.def; hdr_params params_0(0, exposure_default_value, gain_default_value); _hdr_sequence_params[0] = params_0; float exposure_low_value = DEFAULT_CONFIG_LOW_EXPOSURE; float gain_min_value = _gain_range.min; hdr_params params_1(1, exposure_low_value, gain_min_value); _hdr_sequence_params[1] = params_1; } float hdr_config::get(rs2_option option) const { float rv = 0.f; switch (option) { case RS2_OPTION_SUBPRESET_ID: rv = static_cast<float>(_id); break; case RS2_OPTION_SUBPRESET_SEQUENCE_SIZE: rv = static_cast<float>(_sequence_size); break; case RS2_OPTION_SUBPRESET_SEQUENCE_ID: rv = static_cast<float>(_current_hdr_sequence_index + 1); break; case RS2_OPTION_HDR_MODE: rv = static_cast<float>(is_enabled()); break; case RS2_OPTION_EXPOSURE: try { rv = _hdr_sequence_params[_current_hdr_sequence_index]._exposure; } // should never happen catch (std::out_of_range) { throw invalid_value_exception(to_string() << "hdr_config::get(...) failed! Index is above the sequence size."); } break; case RS2_OPTION_GAIN: try { rv = _hdr_sequence_params[_current_hdr_sequence_index]._gain; } // should never happen catch (std::out_of_range) { throw invalid_value_exception(to_string() << "hdr_config::get(...) failed! Index is above the sequence size."); } break; default: throw invalid_value_exception("option is not an HDR option"); } return rv; } void hdr_config::set(rs2_option option, float value, option_range range) { if (!_options_ranges_initialized) { initialize_options_ranges(); _options_ranges_initialized = true; set_default_config(); } if (value < range.min || value > range.max) throw invalid_value_exception(to_string() << "hdr_config::set(...) failed! value is out of the option range."); switch (option) { case RS2_OPTION_SUBPRESET_ID: set_id(value); break; case RS2_OPTION_SUBPRESET_SEQUENCE_SIZE: set_sequence_size(value); break; case RS2_OPTION_SUBPRESET_SEQUENCE_ID: set_sequence_index(value); break; case RS2_OPTION_HDR_MODE: set_enable_status(value); break; case RS2_OPTION_EXPOSURE: set_exposure(value, range); break; case RS2_OPTION_GAIN: set_gain(value); break; default: throw invalid_value_exception("option is not an HDR option"); } // subpreset configuration change is immediately sent to firmware if HDR is already running if (_is_enabled && _has_config_changed) { send_sub_preset_to_fw(); } } bool hdr_config::is_config_in_process() const { return _is_config_in_process; } bool hdr_config::is_enabled() const { float rv = 0.f; command cmd(ds::GETSUBPRESETID); // if no subpreset is streaming, the firmware returns "ON_DATA_TO_RETURN" error try { auto res = _hwm.send(cmd); // if a subpreset is streaming, checking this is the current HDR sub preset rv = (res[0] == _id) ? 1.0f : 0.f; } catch (...) { rv = 0.f; } _is_enabled = (rv == 1.f); return rv; } void hdr_config::set_enable_status(float value) { if (value) { if (validate_config()) { // saving status of options that are not compatible with hdr, // so that they could be reenabled after hdr disable set_options_to_be_restored_after_disable(); send_sub_preset_to_fw(); _is_enabled = true; _has_config_changed = false; } else // msg to user to be improved later on throw invalid_value_exception("config is not valid"); } else { disable(); _is_enabled = false; // re-enabling options that were disabled in order to permit the hdr restore_options_after_disable(); } } void hdr_config::initialize_options_ranges() { _exposure_range = _sensor->get_option(RS2_OPTION_EXPOSURE).get_range(); _gain_range = _sensor->get_option(RS2_OPTION_GAIN).get_range(); } void hdr_config::set_options_to_be_restored_after_disable() { // AUTO EXPOSURE if (_sensor->supports_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE)) { if (_sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).query()) { _sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).set(0.f); _auto_exposure_to_be_restored = true; } } // EMITTER ON OFF if (_sensor->supports_option(RS2_OPTION_EMITTER_ON_OFF)) { if (_sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).query()) { //_sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).set(0.f); _emitter_on_off_to_be_restored = true; } } } void hdr_config::restore_options_after_disable() { // AUTO EXPOSURE if (_auto_exposure_to_be_restored) { _sensor->get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE).set(1.f); _auto_exposure_to_be_restored = false; } // EMITTER ON OFF if (_emitter_on_off_to_be_restored) { _sensor->get_option(RS2_OPTION_EMITTER_ON_OFF).set(1.f); _emitter_on_off_to_be_restored = false; } } void hdr_config::send_sub_preset_to_fw() { // prepare sub-preset command command cmd = prepare_hdr_sub_preset_command(); auto res = _hwm.send(cmd); } void hdr_config::disable() { // sending empty sub preset std::vector<uint8_t> pattern{}; // TODO - make it usable not only for ds - use _sensor command cmd(ds::SETSUBPRESET, static_cast<int>(pattern.size())); cmd.data = pattern; auto res = _hwm.send(cmd); } //helper method - for debug only - to be deleted std::string hdrchar2hex(unsigned char n) { std::string res; do { res += "0123456789ABCDEF"[n % 16]; n >>= 4; } while (n); reverse(res.begin(), res.end()); if (res.size() == 1) { res.insert(0, "0"); } return res; } command hdr_config::prepare_hdr_sub_preset_command() const { std::vector<uint8_t> subpreset_header = prepare_sub_preset_header(); std::vector<uint8_t> subpreset_frames_config = prepare_sub_preset_frames_config(); std::vector<uint8_t> pattern{}; if (subpreset_frames_config.size() > 0) { pattern.insert(pattern.end(), &subpreset_header[0], &subpreset_header[0] + subpreset_header.size()); pattern.insert(pattern.end(), &subpreset_frames_config[0], &subpreset_frames_config[0] + subpreset_frames_config.size()); } /*std::cout << "pattern for hdr sub-preset: "; for (int i = 0; i < pattern.size(); ++i) std::cout << hdrchar2hex(pattern[i]) << " "; std::cout << std::endl; std::ofstream outFile("subpreset_bytes.txt", std::ofstream::out); outFile << "pattern for hdr sub-preset: "; for (int i = 0; i < pattern.size(); ++i) outFile << hdrchar2hex(pattern[i]) << " "; outFile << std::endl;*/ //uint8_t sub_preset_opcode = _sensor->get_set_sub_preset_opcode(); // TODO - make it usable not only for ds - use _sensor command cmd(ds::SETSUBPRESET, static_cast<int>(pattern.size())); cmd.data = pattern; return cmd; } std::vector<uint8_t> hdr_config::prepare_sub_preset_header() const { //size uint8_t header_size = 5; //id - from member (uint8_t) //iterations - always 0 so that it will be continuous until stopped uint16_t iterations = 0; //sequence size uint8_t num_of_items = static_cast<uint8_t>(_sequence_size); std::vector<uint8_t> header; header.insert(header.end(), &header_size, &header_size + 1); header.insert(header.end(), &_id, &_id + 1); header.insert(header.end(), (uint8_t*)&iterations, (uint8_t*)&iterations + 2); header.insert(header.end(), &num_of_items, &num_of_items + 1); return header; } std::vector<uint8_t> hdr_config::prepare_sub_preset_frames_config() const { //size for each frame header uint8_t frame_header_size = 4; //number of iterations for each frame uint16_t iterations = 1; // number of Controls for current frame uint8_t num_of_controls = 2; std::vector<uint8_t> frame_header; frame_header.insert(frame_header.end(), &frame_header_size, &frame_header_size + 1); frame_header.insert(frame_header.end(), (uint8_t*)&iterations, (uint8_t*)&iterations + 2); frame_header.insert(frame_header.end(), &num_of_controls, &num_of_controls + 1); std::vector<uint8_t> frames_config; for (int i = 0; i < _sequence_size; ++i) { frames_config.insert(frames_config.end(), &frame_header[0], &frame_header[0] + frame_header.size()); uint32_t exposure_value = static_cast<uint32_t>(_hdr_sequence_params[i]._exposure); frames_config.insert(frames_config.end(), &CONTROL_ID_EXPOSURE, &CONTROL_ID_EXPOSURE + 1); frames_config.insert(frames_config.end(), (uint8_t*)&exposure_value, (uint8_t*)&exposure_value + 4); uint32_t gain_value = static_cast<uint32_t>(_hdr_sequence_params[i]._gain); frames_config.insert(frames_config.end(), &CONTROL_ID_GAIN, &CONTROL_ID_GAIN + 1); frames_config.insert(frames_config.end(), (uint8_t*)&gain_value, (uint8_t*)&gain_value + 4); } return frames_config; } bool hdr_config::validate_config() const { // to be elaborated or deleted return true; } void hdr_config::set_id(float value) { int new_id = static_cast<int>(value); if (new_id != _id) { _id = new_id; } } void hdr_config::set_sequence_size(float value) { size_t new_size = static_cast<size_t>(value); if (new_size > 3 || new_size < 2) throw invalid_value_exception(to_string() << "hdr_config::set_sequence_size(...) failed! Only size 2 or 3 are supported."); if (new_size != _sequence_size) { _hdr_sequence_params.resize(new_size); _sequence_size = new_size; } } void hdr_config::set_sequence_index(float value) { size_t new_index = static_cast<size_t>(value); _is_config_in_process = (new_index != 0); if (new_index <= _hdr_sequence_params.size()) { _current_hdr_sequence_index = new_index - 1; _has_config_changed = true; } else throw invalid_value_exception(to_string() << "hdr_config::set_sequence_index(...) failed! Index above sequence size."); } void hdr_config::set_exposure(float value, option_range range) { /* TODO - add limitation on max exposure to be below frame interval - is range really needed for this?*/ _hdr_sequence_params[_current_hdr_sequence_index]._exposure = value; _has_config_changed = true; } void hdr_config::set_gain(float value) { _hdr_sequence_params[_current_hdr_sequence_index]._gain = value; _has_config_changed = true; } hdr_params::hdr_params() : _sequence_id(0), _exposure(0.f), _gain(0.f) {} hdr_params::hdr_params(int sequence_id, float exposure, float gain) : _sequence_id(sequence_id), _exposure(exposure), _gain(gain) {} hdr_params& hdr_params::operator=(const hdr_params& other) { _sequence_id = other._sequence_id; _exposure = other._exposure; _gain = other._gain; return *this; } // explanation for the sub-preset: /* the structure is: #define SUB_PRESET_BUFFER_SIZE 0x400 #pragma pack(push, 1) typedef struct SubPresetHeader { uint8_t headerSize; uint8_t id; uint16_t iterations; uint8_t numOfItems; }SubPresetHeader; typedef struct SubPresetItemHeader { uint8_t headerSize; uint16_t iterations; uint8_t numOfControls; }SubPresetItemHeader; typedef struct SubPresetControl { uint8_t controlId; uint32_t controlValue; }SubPresetControl; #pragma pack(pop) */ }<|endoftext|>
<commit_before>// clang-3.3 `pkg-config --cflags --libs opencv` cam.cpp -o opencv #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, const char** argv) { Mat img = imread("../classifiers/demo.jpg", CV_LOAD_IMAGE_UNCHANGED); if (img.empty()) { cout << "Error : Image cannot be loaded..!!" << endl; return -1; } namedWindow("App", CV_WINDOW_AUTOSIZE); imshow("App", img); waitKey(0); destroyWindow("MyWindow"); return 0; } <commit_msg>image_read<commit_after>// clang-3.3 `pkg-config --cflags --libs opencv` cam.cpp -o opencv #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, const char** argv) { Mat img = imread("../classifiers/demo.jpg", CV_LOAD_IMAGE_UNCHANGED); if (img.empty()) { cout << "Error : Image cannot be loaded..!!" << endl; return -1; } namedWindow("App", CV_WINDOW_AUTOSIZE); imshow("App", img); waitKey(0); destroyWindow("App"); return 0; } <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $ #include <string> #include <png.h> #include <jpeglib.h> #include "graphics.hpp" #include "image_util.hpp" #include "memory.hpp" namespace mapnik { //use memory manager for mem allocation in libpng png_voidp malloc_fn(png_structp png_ptr,png_size_t size) { return Object::operator new(size); } void free_fn(png_structp png_ptr, png_voidp ptr) { Object::operator delete(ptr); } // void ImageUtils::save_to_file(const std::string& filename,const std::string& type,const Image32& image) { //all that should go into image_writer factory if (type=="png") { save_as_png(filename,image); } else if (type=="jpeg") { save_as_jpeg(filename,85,image); } } void ImageUtils::save_as_png(const std::string& filename,const Image32& image) { FILE *fp=fopen(filename.c_str(), "wb"); if (!fp) return; png_voidp mem_ptr=0; png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)mem_ptr,0, 0); if (!png_ptr) return; png_set_mem_fn(png_ptr,mem_ptr,malloc_fn,free_fn); // switch on optimization //#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) //png_uint_32 mask, flags; //flags = png_get_asm_flags(png_ptr); //mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE); //png_set_asm_flags(png_ptr, flags | mask); //#endif png_set_filter (png_ptr, 0, PNG_FILTER_NONE); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)0); fclose(fp); return; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return; } png_init_io(png_ptr, fp); //png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); //png_set_compression_strategy(png_ptr, Z_FILTERED); png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8, PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); const ImageData32& imageData=image.data(); for (unsigned i=0;i<image.height();i++) { png_write_row(png_ptr,(png_bytep)imageData.getRow(i)); } png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); } void ImageUtils::save_as_jpeg(const std::string& filename,int quality, const Image32& image) { FILE *fp=fopen(filename.c_str(), "wb"); if (!fp) return; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int width=image.width(); int height=image.height(); cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, fp); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality,1); jpeg_start_compress(&cinfo, 1); JSAMPROW row_pointer[1]; JSAMPLE* row=new JSAMPLE[width*3]; const ImageData32& imageData=image.data(); while (cinfo.next_scanline < cinfo.image_height) { const unsigned* imageRow=imageData.getRow(cinfo.next_scanline); int index=0; for (int i=0;i<width;++i) { row[index++]=(imageRow[i])&0xff; row[index++]=(imageRow[i]>>8)&0xff; row[index++]=(imageRow[i]>>16)&0xff; } row_pointer[0] = &row[0]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } delete [] row; jpeg_finish_compress(&cinfo); fclose(fp); jpeg_destroy_compress(&cinfo); } } <commit_msg>switched on optimization in png writing code<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $ #include <string> #include <png.h> #include <jpeglib.h> #include "graphics.hpp" #include "image_util.hpp" #include "memory.hpp" namespace mapnik { //use memory manager for mem allocation in libpng png_voidp malloc_fn(png_structp png_ptr,png_size_t size) { return Object::operator new(size); } void free_fn(png_structp png_ptr, png_voidp ptr) { Object::operator delete(ptr); } // void ImageUtils::save_to_file(const std::string& filename,const std::string& type,const Image32& image) { //all that should go into image_writer factory if (type=="png") { save_as_png(filename,image); } else if (type=="jpeg") { save_as_jpeg(filename,85,image); } } void ImageUtils::save_as_png(const std::string& filename,const Image32& image) { FILE *fp=fopen(filename.c_str(), "wb"); if (!fp) return; png_voidp mem_ptr=0; png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)mem_ptr,0, 0); if (!png_ptr) return; png_set_mem_fn(png_ptr,mem_ptr,malloc_fn,free_fn); // switch on optimization #if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) png_uint_32 mask, flags; flags = png_get_asm_flags(png_ptr); mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE); png_set_asm_flags(png_ptr, flags | mask); #endif png_set_filter (png_ptr, 0, PNG_FILTER_NONE); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)0); fclose(fp); return; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return; } png_init_io(png_ptr, fp); //png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); //png_set_compression_strategy(png_ptr, Z_FILTERED); png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8, PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); const ImageData32& imageData=image.data(); for (unsigned i=0;i<image.height();i++) { png_write_row(png_ptr,(png_bytep)imageData.getRow(i)); } png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); } void ImageUtils::save_as_jpeg(const std::string& filename,int quality, const Image32& image) { FILE *fp=fopen(filename.c_str(), "wb"); if (!fp) return; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int width=image.width(); int height=image.height(); cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, fp); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality,1); jpeg_start_compress(&cinfo, 1); JSAMPROW row_pointer[1]; JSAMPLE* row=new JSAMPLE[width*3]; const ImageData32& imageData=image.data(); while (cinfo.next_scanline < cinfo.image_height) { const unsigned* imageRow=imageData.getRow(cinfo.next_scanline); int index=0; for (int i=0;i<width;++i) { row[index++]=(imageRow[i])&0xff; row[index++]=(imageRow[i]>>8)&0xff; row[index++]=(imageRow[i]>>16)&0xff; } row_pointer[0] = &row[0]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } delete [] row; jpeg_finish_compress(&cinfo); fclose(fp); jpeg_destroy_compress(&cinfo); } } <|endoftext|>
<commit_before>/********************************************************************************** Infomap software package for multi-level network clustering Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall For more information, see <http://www.mapequation.org> This file is part of Infomap software package. Infomap software package is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Infomap software package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Infomap software package. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "version.h" namespace infomap { const char* INFOMAP_VERSION = "1.0.0-beta.8"; } <commit_msg>v1.0.0-beta.9<commit_after>/********************************************************************************** Infomap software package for multi-level network clustering Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall For more information, see <http://www.mapequation.org> This file is part of Infomap software package. Infomap software package is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Infomap software package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Infomap software package. If not, see <http://www.gnu.org/licenses/>. **********************************************************************************/ #include "version.h" namespace infomap { const char* INFOMAP_VERSION = "1.0.0-beta.9"; } <|endoftext|>
<commit_before>/// /// @file iterator-c.cpp /// @brief C port of primesieve::iterator. /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve.h> #include <primesieve/forward.hpp> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <primesieve/macros.hpp> #include <primesieve/pod_vector.hpp> #include <stdint.h> #include <cerrno> #include <exception> #include <iostream> #include <vector> namespace { using namespace primesieve; void deletePrimeGenerator(primesieve_iterator* it) { delete (PrimeGenerator*) it->primeGenerator; it->primeGenerator = nullptr; } void deletePrimesVector(primesieve_iterator* it) { delete (pod_vector<uint64_t>*) it->vector; it->vector = nullptr; } pod_vector<uint64_t>& getPrimes(primesieve_iterator* it) { return *(pod_vector<uint64_t>*) it->vector; } } // namespace /// C constructor void primesieve_init(primesieve_iterator* it) { it->i = 0; it->last_idx = 0; it->start = 0; it->stop = 0; it->stop_hint = std::numeric_limits<uint64_t>::max(); it->dist = 0; it->primes = nullptr; it->vector = nullptr; it->primeGenerator = nullptr; it->is_error = false; } void primesieve_skipto(primesieve_iterator* it, uint64_t start, uint64_t stop_hint) { it->i = 0; it->last_idx = 0; it->start = start; it->stop = start; it->stop_hint = stop_hint; it->dist = 0; it->primes = nullptr; deletePrimeGenerator(it); // We don't delete/free the primesVector as // it will likely be reused again. } /// C destructor void primesieve_free_iterator(primesieve_iterator* it) { if (it) { deletePrimeGenerator(it); deletePrimesVector(it); } } void primesieve_generate_next_primes(primesieve_iterator* it) { std::size_t size = 0; try { while (!size) { auto* primeGenerator = (PrimeGenerator*) it->primeGenerator; if (!primeGenerator) { IteratorHelper::next(&it->start, &it->stop, it->stop_hint, &it->dist); primeGenerator = new PrimeGenerator(it->start, it->stop); it->primeGenerator = primeGenerator; if (!it->vector) it->vector = new pod_vector<uint64_t>(); } auto& primes = getPrimes(it); primeGenerator->fillNextPrimes(primes, &size); // There are 3 different cases here: // 1) The primes array contains a few primes (<= 512). // In this case we return the primes to the user. // 2) The primes array is empty because the next // prime > stop. In this case we reset the // primeGenerator object, increase the start & stop // numbers and sieve the next segment. // 3) The next prime > 2^64. In this case the primes // array contains an error code (UINT64_MAX) which // is returned to the user. if (size == 0) deletePrimeGenerator(it); } } catch (const std::exception& e) { std::cerr << "primesieve_iterator: " << e.what() << std::endl; deletePrimeGenerator(it); if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); primes.clear(); primes.push_back(PRIMESIEVE_ERROR); size = primes.size(); it->is_error = true; errno = EDOM; } auto& primes = getPrimes(it); it->i = 0; it->last_idx = size - 1; it->primes = &primes[0]; } void primesieve_generate_prev_primes(primesieve_iterator* it) { std::size_t size = 0; try { if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); // Special case if generate_next_primes() has // been used before generate_prev_primes(). if_unlikely(it->primeGenerator) { assert(!primes.empty()); it->start = primes.front(); deletePrimeGenerator(it); } while (!size) { IteratorHelper::prev(&it->start, &it->stop, it->stop_hint, &it->dist); PrimeGenerator primeGenerator(it->start, it->stop); primeGenerator.fillPrevPrimes(primes, &size); } } catch (const std::exception& e) { std::cerr << "primesieve_iterator: " << e.what() << std::endl; deletePrimeGenerator(it); if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); primes.clear(); primes.push_back(PRIMESIEVE_ERROR); size = primes.size(); it->is_error = true; errno = EDOM; } auto& primes = getPrimes(it); it->last_idx = size - 1; it->i = it->last_idx; it->primes = &primes[0]; } <commit_msg>Remove unused headers<commit_after>/// /// @file iterator-c.cpp /// @brief C port of primesieve::iterator. /// /// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve.h> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <primesieve/macros.hpp> #include <primesieve/pod_vector.hpp> #include <stdint.h> #include <cerrno> #include <exception> #include <iostream> namespace { using namespace primesieve; void deletePrimeGenerator(primesieve_iterator* it) { delete (PrimeGenerator*) it->primeGenerator; it->primeGenerator = nullptr; } void deletePrimesVector(primesieve_iterator* it) { delete (pod_vector<uint64_t>*) it->vector; it->vector = nullptr; } pod_vector<uint64_t>& getPrimes(primesieve_iterator* it) { return *(pod_vector<uint64_t>*) it->vector; } } // namespace /// C constructor void primesieve_init(primesieve_iterator* it) { it->i = 0; it->last_idx = 0; it->start = 0; it->stop = 0; it->stop_hint = std::numeric_limits<uint64_t>::max(); it->dist = 0; it->primes = nullptr; it->vector = nullptr; it->primeGenerator = nullptr; it->is_error = false; } void primesieve_skipto(primesieve_iterator* it, uint64_t start, uint64_t stop_hint) { it->i = 0; it->last_idx = 0; it->start = start; it->stop = start; it->stop_hint = stop_hint; it->dist = 0; it->primes = nullptr; deletePrimeGenerator(it); // We don't delete/free the primesVector as // it will likely be reused again. } /// C destructor void primesieve_free_iterator(primesieve_iterator* it) { if (it) { deletePrimeGenerator(it); deletePrimesVector(it); } } void primesieve_generate_next_primes(primesieve_iterator* it) { std::size_t size = 0; try { while (!size) { auto* primeGenerator = (PrimeGenerator*) it->primeGenerator; if (!primeGenerator) { IteratorHelper::next(&it->start, &it->stop, it->stop_hint, &it->dist); primeGenerator = new PrimeGenerator(it->start, it->stop); it->primeGenerator = primeGenerator; if (!it->vector) it->vector = new pod_vector<uint64_t>(); } auto& primes = getPrimes(it); primeGenerator->fillNextPrimes(primes, &size); // There are 3 different cases here: // 1) The primes array contains a few primes (<= 512). // In this case we return the primes to the user. // 2) The primes array is empty because the next // prime > stop. In this case we reset the // primeGenerator object, increase the start & stop // numbers and sieve the next segment. // 3) The next prime > 2^64. In this case the primes // array contains an error code (UINT64_MAX) which // is returned to the user. if (size == 0) deletePrimeGenerator(it); } } catch (const std::exception& e) { std::cerr << "primesieve_iterator: " << e.what() << std::endl; deletePrimeGenerator(it); if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); primes.clear(); primes.push_back(PRIMESIEVE_ERROR); size = primes.size(); it->is_error = true; errno = EDOM; } auto& primes = getPrimes(it); it->i = 0; it->last_idx = size - 1; it->primes = &primes[0]; } void primesieve_generate_prev_primes(primesieve_iterator* it) { std::size_t size = 0; try { if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); // Special case if generate_next_primes() has // been used before generate_prev_primes(). if_unlikely(it->primeGenerator) { assert(!primes.empty()); it->start = primes.front(); deletePrimeGenerator(it); } while (!size) { IteratorHelper::prev(&it->start, &it->stop, it->stop_hint, &it->dist); PrimeGenerator primeGenerator(it->start, it->stop); primeGenerator.fillPrevPrimes(primes, &size); } } catch (const std::exception& e) { std::cerr << "primesieve_iterator: " << e.what() << std::endl; deletePrimeGenerator(it); if (!it->vector) it->vector = new pod_vector<uint64_t>(); auto& primes = getPrimes(it); primes.clear(); primes.push_back(PRIMESIEVE_ERROR); size = primes.size(); it->is_error = true; errno = EDOM; } auto& primes = getPrimes(it); it->last_idx = size - 1; it->i = it->last_idx; it->primes = &primes[0]; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 FS_COMMON_HPP #define FS_COMMON_HPP #include <memory> #include <string> namespace fs { /** * @brief Type used as a building block to represent buffers * within the filesystem subsystem */ using buffer_t = std::shared_ptr<uint8_t>; struct error_t { enum token_t { NO_ERR = 0, E_IO, // general I/O error E_MNT, E_NOENT, E_NOTDIR, E_NOTFILE }; //< enum token_t /** * @brief Constructor * * @param tk: An error token * @param rsn: The reason for the error */ error_t(const token_t tk, const std::string& rsn) noexcept : token_{tk} , reason_{rsn} {} /** * @brief Get a human-readable description of the token * * @return Description of the token as a {std::string} */ const std::string& token() const noexcept; /** * @brief Get an explanation for error */ const std::string& reason() const noexcept { return reason_; } /** * @brief Get a {std::string} representation of this type * * Format "description: reason" * * @return {std::string} representation of this type */ std::string to_string() const { return token() + ": " + reason(); } /** * @brief Check if the object of this type represents * an error * * @return true if its an error, false otherwise */ operator bool () const noexcept { return token_ not_eq NO_ERR; } private: const token_t token_; const std::string reason_; }; //< struct error_t /** * @brief Type used for buffers within the filesystem * subsystem */ struct Buffer { Buffer(error_t e, buffer_t b, size_t l) : err(e), buffer(b), len(l) {} // returns true if this buffer is valid bool is_valid() const noexcept { return buffer != nullptr; } operator bool () const noexcept { return is_valid(); } uint8_t* data() { return buffer.get(); } size_t size() const noexcept { return len; } // create a std::string from the stored buffer and return it std::string to_string() const noexcept { return std::string((char*) buffer.get(), size()); } error_t err; buffer_t buffer; uint64_t len; }; //< struct Buffer /** @var no_error: Always returns boolean false when used in expressions */ extern error_t no_error; } //< namespace fs #endif //< FS_ERROR_HPP <commit_msg>Removed noexcept from error_t constructor since it can throw while copying rsn<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 FS_COMMON_HPP #define FS_COMMON_HPP #include <memory> #include <string> namespace fs { /** * @brief Type used as a building block to represent buffers * within the filesystem subsystem */ using buffer_t = std::shared_ptr<uint8_t>; struct error_t { enum token_t { NO_ERR = 0, E_IO, // general I/O error E_MNT, E_NOENT, E_NOTDIR, E_NOTFILE }; //< enum token_t /** * @brief Constructor * * @param tk: An error token * @param rsn: The reason for the error */ error_t(const token_t tk, const std::string& rsn) : token_{tk} , reason_{rsn} {} /** * @brief Get a human-readable description of the token * * @return Description of the token as a {std::string} */ const std::string& token() const noexcept; /** * @brief Get an explanation for error */ const std::string& reason() const noexcept { return reason_; } /** * @brief Get a {std::string} representation of this type * * Format "description: reason" * * @return {std::string} representation of this type */ std::string to_string() const { return token() + ": " + reason(); } /** * @brief Check if the object of this type represents * an error * * @return true if its an error, false otherwise */ operator bool () const noexcept { return token_ not_eq NO_ERR; } private: const token_t token_; const std::string reason_; }; //< struct error_t /** * @brief Type used for buffers within the filesystem * subsystem */ struct Buffer { Buffer(error_t e, buffer_t b, size_t l) : err(e), buffer(b), len(l) {} // returns true if this buffer is valid bool is_valid() const noexcept { return buffer != nullptr; } operator bool () const noexcept { return is_valid(); } uint8_t* data() { return buffer.get(); } size_t size() const noexcept { return len; } // create a std::string from the stored buffer and return it std::string to_string() const noexcept { return std::string((char*) buffer.get(), size()); } error_t err; buffer_t buffer; uint64_t len; }; //< struct Buffer /** @var no_error: Always returns boolean false when used in expressions */ extern error_t no_error; } //< namespace fs #endif //< FS_ERROR_HPP <|endoftext|>
<commit_before>/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ecclesia/lib/redfish/transport/grpc.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ecclesia/lib/file/test_filesystem.h" #include "ecclesia/lib/network/testing.h" #include "ecclesia/lib/redfish/testing/fake_redfish_server.h" #include "ecclesia/lib/redfish/testing/grpc_dynamic_mockup_server.h" #include "ecclesia/lib/status/rpc.h" #include "ecclesia/lib/testing/status.h" namespace ecclesia { namespace { using ::testing::Eq; TEST(GrpcRedfishTransport, Get) { absl::flat_hash_map<std::string, std::string> headers; int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); } TEST(GrpcRedfishTransport, PostPatchGetDelete) { absl::flat_hash_map<std::string, std::string> headers; int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); nlohmann::json expected_post = nlohmann::json::parse(R"json({})json", nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_post = transport.Post("/redfish/v1/Chassis", R"json({ "ChassisType": "RackMount", "Name": "MyChassis" })json"); ASSERT_THAT(res_post, IsOk()); EXPECT_THAT(res_post->body, expected_post); absl::string_view expected_get_str = R"json({ "@odata.context":"/redfish/v1/$metadata#ChassisCollection.ChassisCollection", "@odata.id":"/redfish/v1/Chassis", "@odata.type":"#ChassisCollection.ChassisCollection", "Members":[ { "@odata.id":"/redfish/v1/Chassis/chassis" }, { "@odata.id":"/redfish/v1/Chassis/Member1", "ChassisType":"RackMount", "Id":"Member1", "Name":"MyChassis" } ], "Members@odata.count":2.0,"Name":"Chassis Collection" })json"; nlohmann::json expected_get = nlohmann::json::parse(expected_get_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1/Chassis"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected_get)); absl::string_view data_patch = R"json({ "Name": "MyPatchChassis" })json"; nlohmann::json expected_patch = nlohmann::json::parse(R"json({})json", nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_patch = transport.Patch("/redfish/v1/Chassis/Member1", data_patch); ASSERT_THAT(res_patch, IsOk()); EXPECT_THAT(res_patch->body, Eq(expected_patch)); expected_get_str = R"json({ "@odata.context":"/redfish/v1/$metadata#ChassisCollection.ChassisCollection", "@odata.id":"/redfish/v1/Chassis", "@odata.type":"#ChassisCollection.ChassisCollection", "Members":[ { "@odata.id":"/redfish/v1/Chassis/chassis" }, { "@odata.id":"/redfish/v1/Chassis/Member1", "ChassisType":"RackMount", "Id":"Member1", "Name":"MyPatchChassis" } ], "Members@odata.count":2.0,"Name":"Chassis Collection" })json"; expected_get = nlohmann::json::parse(expected_get_str, nullptr, false); res_get = transport.Get("/redfish/v1/Chassis"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected_get)); EXPECT_THAT( transport.Delete("/redfish/v1/Chassis/Member1", "{}"), internal_status::IsStatusPolyMatcher(absl::StatusCode::kUnimplemented)); } TEST(GrpcRedfishTransport, GetRootUri) { int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); EXPECT_EQ(transport.GetRootUri(), "/redfish/v1"); } TEST(GrpcRedfishTransport, UpdateToNetworkEndpoint) { absl::flat_hash_map<std::string, std::string> headers; int port1 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server1("barebones_session_auth/mockup.shar", "[::1]", port1); int port2 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port2); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port1)); transport.UpdateToNetworkEndpoint(absl::StrCat("[::1]:", port2)); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); } TEST(GrpcRedfishTransport, UpdateToUdsEndpoint) { absl::flat_hash_map<std::string, std::string> headers; int port1 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server1("barebones_session_auth/mockup.shar", "[::1]", port1); std::string mockup_uds = absl::StrCat(GetTestTempUdsDirectory(), "/mockup.socket"); GrpcDynamicMockupServer mockup_server2("barebones_session_auth/mockup.shar", mockup_uds); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port1)); transport.UpdateToUdsEndpoint(mockup_uds); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); } } // namespace } // namespace ecclesia <commit_msg>Internal change<commit_after>/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ecclesia/lib/redfish/transport/grpc.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ecclesia/lib/file/test_filesystem.h" #include "ecclesia/lib/network/testing.h" #include "ecclesia/lib/redfish/testing/fake_redfish_server.h" #include "ecclesia/lib/redfish/testing/grpc_dynamic_mockup_server.h" #include "ecclesia/lib/status/rpc.h" #include "ecclesia/lib/testing/status.h" namespace ecclesia { namespace { using ::testing::Eq; TEST(GrpcRedfishTransport, Get) { absl::flat_hash_map<std::string, std::string> headers; int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); EXPECT_THAT(res_get->code, Eq(200)); } TEST(GrpcRedfishTransport, PostPatchGetDelete) { absl::flat_hash_map<std::string, std::string> headers; int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); nlohmann::json expected_post = nlohmann::json::parse(R"json({})json", nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_post = transport.Post("/redfish/v1/Chassis", R"json({ "ChassisType": "RackMount", "Name": "MyChassis" })json"); ASSERT_THAT(res_post, IsOk()); EXPECT_THAT(res_post->body, expected_post); EXPECT_THAT(res_post->code, Eq(204)); absl::string_view expected_get_str = R"json({ "@odata.context":"/redfish/v1/$metadata#ChassisCollection.ChassisCollection", "@odata.id":"/redfish/v1/Chassis", "@odata.type":"#ChassisCollection.ChassisCollection", "Members":[ { "@odata.id":"/redfish/v1/Chassis/chassis" }, { "@odata.id":"/redfish/v1/Chassis/Member1", "ChassisType":"RackMount", "Id":"Member1", "Name":"MyChassis" } ], "Members@odata.count":2.0,"Name":"Chassis Collection" })json"; nlohmann::json expected_get = nlohmann::json::parse(expected_get_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1/Chassis"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected_get)); EXPECT_THAT(res_get->code, Eq(200)); absl::string_view data_patch = R"json({ "Name": "MyPatchChassis" })json"; nlohmann::json expected_patch = nlohmann::json::parse(R"json({})json", nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_patch = transport.Patch("/redfish/v1/Chassis/Member1", data_patch); ASSERT_THAT(res_patch, IsOk()); EXPECT_THAT(res_patch->body, Eq(expected_patch)); EXPECT_THAT(res_patch->code, Eq(204)); expected_get_str = R"json({ "@odata.context":"/redfish/v1/$metadata#ChassisCollection.ChassisCollection", "@odata.id":"/redfish/v1/Chassis", "@odata.type":"#ChassisCollection.ChassisCollection", "Members":[ { "@odata.id":"/redfish/v1/Chassis/chassis" }, { "@odata.id":"/redfish/v1/Chassis/Member1", "ChassisType":"RackMount", "Id":"Member1", "Name":"MyPatchChassis" } ], "Members@odata.count":2.0,"Name":"Chassis Collection" })json"; expected_get = nlohmann::json::parse(expected_get_str, nullptr, false); res_get = transport.Get("/redfish/v1/Chassis"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected_get)); EXPECT_THAT(res_get->code, Eq(200)); EXPECT_THAT( transport.Delete("/redfish/v1/Chassis/Member1", "{}"), internal_status::IsStatusPolyMatcher(absl::StatusCode::kUnimplemented)); } TEST(GrpcRedfishTransport, GetRootUri) { int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); EXPECT_EQ(transport.GetRootUri(), "/redfish/v1"); } TEST(GrpcRedfishTransport, UpdateToNetworkEndpoint) { absl::flat_hash_map<std::string, std::string> headers; int port1 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server1("barebones_session_auth/mockup.shar", "[::1]", port1); int port2 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port2); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port1)); transport.UpdateToNetworkEndpoint(absl::StrCat("[::1]:", port2)); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); EXPECT_THAT(res_get->code, Eq(200)); } TEST(GrpcRedfishTransport, UpdateToUdsEndpoint) { absl::flat_hash_map<std::string, std::string> headers; int port1 = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server1("barebones_session_auth/mockup.shar", "[::1]", port1); std::string mockup_uds = absl::StrCat(GetTestTempUdsDirectory(), "/mockup.socket"); GrpcDynamicMockupServer mockup_server2("barebones_session_auth/mockup.shar", mockup_uds); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port1)); transport.UpdateToUdsEndpoint(mockup_uds); absl::string_view expected_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expected_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); EXPECT_THAT(res_get->code, Eq(200)); } TEST(GrpcRedfishTransport, ResourceNotFound) { int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); auto result_get = transport.Get("/redfish/v1/Chassis/noexist"); EXPECT_THAT(result_get, IsOk()); nlohmann::json expected_get = nlohmann::json::parse(R"json({})json", nullptr, false); EXPECT_THAT(result_get->body, Eq(expected_get)); EXPECT_THAT(result_get->code, Eq(404)); } TEST(GrpcRedfishTransport, NotAllowed) { int port = ecclesia::FindUnusedPortOrDie(); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port)); std::string_view data_post = R"json({ "ChassisType": "RackMount", "Name": "MyChassis" })json"; auto result_post = transport.Post("/redfish", data_post); EXPECT_THAT(result_post, IsOk()); nlohmann::json expected_post = nlohmann::json::parse(R"json({})json", nullptr, false); EXPECT_THAT(result_post->body, Eq(expected_post)); EXPECT_THAT(result_post->code, Eq(405)); auto result_patch = transport.Patch("/redfish", data_post); EXPECT_THAT(result_patch, IsOk()); nlohmann::json expected_patch = nlohmann::json::parse(R"json({})json", nullptr, false); EXPECT_THAT(result_patch->body, Eq(expected_patch)); EXPECT_THAT(result_patch->code, Eq(204)); } TEST(GrpcRedfishTransport, Timeout) { int port = ecclesia::FindUnusedPortOrDie(); testing::internal::Notification notification; GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", "[::1]", port); mockup_server.AddHttpGetHandler( "/redfish/v1", [&](grpc::ServerContext* context, const ::redfish::v1::Request* request, redfish::v1::Response* response) -> grpc::Status { absl::SleepFor(absl::Milliseconds(100)); notification.Notify(); return grpc::Status::OK; }); GrpcRedfishTransport::Params params; params.timeout = absl::AbsDuration(absl::Milliseconds(50)); GrpcRedfishTransport transport(absl::StrCat("[::1]:", port), params); EXPECT_THAT(transport.Get("/redfish/v1"), internal_status::IsStatusPolyMatcher( absl::StatusCode::kDeadlineExceeded)); notification.WaitForNotification(); } } // namespace } // namespace ecclesia <|endoftext|>
<commit_before>#include <iostream> #include <climits> using namespace std; int flip(int a, int pos); void flip(int* a, int pos); void print(int a); int solve(int a, int tgt); int topDown2LeftRight(int a); int reverseDirection(int a); int main() { int a = 0; for (int i = 0; i < 4; i++) { string line; cin >> line; for (int j = 0; j < 4; j++) { char c = line[j]; int tmp = (c == 'b') ? 1 : 0; int shift = i * 4 + j; a = a | (tmp << shift); } } int arr[4]; arr[0] = a; /* print(arr[0]); arr[2] = reverseDirection(a); print(arr[2]); */ arr[1] = reverseDirection(a); arr[2] = topDown2LeftRight(a); arr[3] = reverseDirection(arr[2]); int minFlip = INT_MAX; for (int i = 0; i < 2; i++) for (int j = 0; j < 4; j++) { int tmp = solve(arr[j], i); if (tmp < INT_MAX) minFlip = tmp; } if (minFlip == INT_MAX) cout << "Impossible" << endl; else cout << minFlip << endl; } int topDown2LeftRight(int a) { int ret = 0; int shift = 0; for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int pos = row * 4 + col; int tmp = a; ret = ret | (((tmp >> pos) & 1) << shift); shift++; } } return ret; } int reverseDirection(int a) { int ret = 0; int mask = 0xf; int shift = 12; while (a) { ret = ret | ((a & mask) << shift); a = a >> 4; shift -= 4; } return ret; } void print(int a) { for (int i = 0; i <= 15; i++) { int tmp = a; cout << ((tmp >> i) & 1) << " "; if (i % 4 == 3) cout << endl; } cout << endl; } void flip(int* a, int pos) { int row = pos / 4; int col = pos % 4; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { if (i < 0 || i > 3 || j < 0 || j > 3) continue; if (((i == row - 1) && (j == col - 1)) || ((i == row - 1) && (j == col + 1)) || ((i == row + 1) && (j == col - 1)) || ((i == row + 1) && (j == col + 1))) continue; int shift = i * 4 + j; int mask = 1 << shift; if (mask & *a) *a = (~mask) & *a; else *a = mask | *a; } } int flip(int a, int pos) { int row = pos / 4; int col = pos % 4; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { if (i < 0 || i > 3 || j < 0 || j > 3) continue; if (((i == row - 1) && (j == col - 1)) || ((i == row - 1) && (j == col + 1)) || ((i == row + 1) && (j == col - 1)) || ((i == row + 1) && (j == col + 1))) continue; int shift = i * 4 + j; int mask = 1 << shift; if (mask & a) a = (~mask) & a; else a = mask | a; } return a; } int solve(int a, int tgt) { int step = 0; for (int i = 0; i < 16; i++) { int tmp = a; int bit = (tmp >> i) & 1; if (bit == tgt) continue; int pos = i + 4; if (pos >= 16) return INT_MAX; flip(&a, pos); //print(a); step++; } return step; } <commit_msg>p1753b<commit_after>#include <iostream> #include <climits> using namespace std; int flip(int a, int pos); void flip(int* a, int pos); void print(int a); int solve(int a, int tgt); int topDown2LeftRight(int a); int reverseDirection(int a); int main() { int a = 0; for (int i = 0; i < 4; i++) { string line; cin >> line; for (int j = 0; j < 4; j++) { char c = line[j]; int tmp = (c == 'b') ? 1 : 0; int shift = i * 4 + j; a = a | (tmp << shift); } } int arr[4]; arr[0] = a; /* print(arr[0]); arr[2] = reverseDirection(a); print(arr[2]); */ arr[1] = reverseDirection(a); arr[2] = topDown2LeftRight(a); arr[3] = reverseDirection(arr[2]); int minFlip = INT_MAX; for (int i = 0; i < 2; i++) for (int j = 0; j < 4; j++) { int tmp = solve(arr[j], i); cout << tmp << endl; if (tmp < minFlip) minFlip = tmp; } if (minFlip == INT_MAX) cout << "Impossible" << endl; else cout << minFlip << endl; } int topDown2LeftRight(int a) { int ret = 0; int shift = 0; for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int pos = row * 4 + col; int tmp = a; ret = ret | (((tmp >> pos) & 1) << shift); shift++; } } return ret; } int reverseDirection(int a) { int ret = 0; int mask = 0xf; int shift = 12; while (a) { ret = ret | ((a & mask) << shift); a = a >> 4; shift -= 4; } return ret; } void print(int a) { for (int i = 0; i <= 15; i++) { int tmp = a; cout << ((tmp >> i) & 1) << " "; if (i % 4 == 3) cout << endl; } cout << endl; } void flip(int* a, int pos) { int row = pos / 4; int col = pos % 4; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { if (i < 0 || i > 3 || j < 0 || j > 3) continue; if (((i == row - 1) && (j == col - 1)) || ((i == row - 1) && (j == col + 1)) || ((i == row + 1) && (j == col - 1)) || ((i == row + 1) && (j == col + 1))) continue; int shift = i * 4 + j; int mask = 1 << shift; if (mask & *a) *a = (~mask) & *a; else *a = mask | *a; } } int flip(int a, int pos) { int row = pos / 4; int col = pos % 4; for (int i = row - 1; i <= row + 1; i++) for (int j = col - 1; j <= col + 1; j++) { if (i < 0 || i > 3 || j < 0 || j > 3) continue; if (((i == row - 1) && (j == col - 1)) || ((i == row - 1) && (j == col + 1)) || ((i == row + 1) && (j == col - 1)) || ((i == row + 1) && (j == col + 1))) continue; int shift = i * 4 + j; int mask = 1 << shift; if (mask & a) a = (~mask) & a; else a = mask | a; } return a; } int solve(int a, int tgt) { int step = 0; for (int i = 0; i < 16; i++) { int tmp = a; int bit = (tmp >> i) & 1; if (bit == tgt) continue; int pos = i + 4; if (pos >= 16) return INT_MAX; flip(&a, pos); print(a); step++; } return step; } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <ox/std/bstring.hpp> #include <ox/std/strops.hpp> #include <ox/std/types.hpp> #include <ox/std/typetraits.hpp> namespace ox { class SerStr { protected: int m_cap = 0; char *m_str = nullptr; char **m_tgt = nullptr; public: template<std::size_t sz> constexpr SerStr(BString<sz> *str) noexcept { m_str = str->data(); m_cap = str->cap(); } constexpr SerStr(char *str, int cap) noexcept { m_str = str; m_cap = cap; } constexpr SerStr(char **tgt, int cap = -1) noexcept { m_tgt = tgt; m_str = const_cast<char*>(*tgt); m_cap = cap; } template<std::size_t cap> constexpr SerStr(char (&str)[cap]) noexcept { m_str = str; m_cap = cap; } constexpr const char *c_str() noexcept { return m_str; } constexpr char *data(std::size_t sz = 0) noexcept { if (m_tgt && sz) { *m_tgt = new char[sz]; m_str = *m_tgt; m_cap = sz; } return m_str; } constexpr int len() noexcept { return m_str ? ox_strlen(m_str) : 0; } constexpr int cap() noexcept { return m_cap; } }; template<typename Union> class UnionView { protected: int m_idx = -1; typename enable_if<is_union_v<Union>, Union>::type *m_union = nullptr; public: constexpr explicit UnionView(Union *u, int idx) noexcept: m_idx(idx), m_union(u) { } constexpr auto idx() noexcept { return m_idx; } constexpr Union *get() noexcept { return m_union; } }; } <commit_msg>[ox/model] Removes some unnecessary type conversions<commit_after>/* * Copyright 2015 - 2021 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <ox/std/bstring.hpp> #include <ox/std/strops.hpp> #include <ox/std/types.hpp> #include <ox/std/typetraits.hpp> namespace ox { class SerStr { protected: int m_cap = 0; char *m_str = nullptr; char **m_tgt = nullptr; public: template<std::size_t sz> constexpr SerStr(BString<sz> *str) noexcept { m_str = str->data(); m_cap = str->cap(); } constexpr SerStr(char *str, int cap) noexcept { m_str = str; m_cap = cap; } constexpr SerStr(char **tgt, int cap = -1) noexcept { m_tgt = tgt; m_str = const_cast<char*>(*tgt); m_cap = cap; } template<std::size_t cap> constexpr SerStr(char (&str)[cap]) noexcept { m_str = str; m_cap = cap; } constexpr const char *c_str() noexcept { return m_str; } constexpr char *data(std::size_t sz = 0) noexcept { if (m_tgt && sz) { *m_tgt = new char[sz]; m_str = *m_tgt; m_cap = static_cast<int>(sz); } return m_str; } constexpr int len() noexcept { return static_cast<int>(m_str ? ox_strlen(m_str) : 0); } constexpr int cap() noexcept { return m_cap; } }; template<typename Union> class UnionView { protected: int m_idx = -1; typename enable_if<is_union_v<Union>, Union>::type *m_union = nullptr; public: constexpr explicit UnionView(Union *u, int idx) noexcept: m_idx(idx), m_union(u) { } constexpr auto idx() noexcept { return m_idx; } constexpr Union *get() noexcept { return m_union; } }; } <|endoftext|>
<commit_before>#pragma once #include "gl_test_widget.hpp" #include "../../gui/controller.hpp" #include "../../base/strings_bundle.hpp" #include <QMouseEvent> template <class T, void (T::*)(gui::Controller*)> struct init_with_controller_fn_bind { typedef T type; }; template <class T, class U> struct has_init_with_controller { static bool const value = false; }; template <class T> struct has_init_with_controller<T, typename init_with_controller_fn_bind<T, &T::Init>::type> { static bool const value = true; }; template <typename TTest> class GUITestWidget : public GLTestWidget<TTest> { private: typedef GLTestWidget<TTest> base_t; shared_ptr<gui::Controller> m_controller; shared_ptr<graphics::Screen> m_cacheScreen; shared_ptr<StringsBundle> m_stringBundle; public: void invalidate() { base_t::updateGL(); } void initializeGL() { base_t::initializeGL(); m_controller.reset(new gui::Controller()); gui::Controller::RenderParams rp; graphics::Screen::Params cp; cp.m_doUnbindRT = false; cp.m_threadSlot = 0; cp.m_storageType = graphics::ETinyStorage; cp.m_textureType = graphics::ESmallTexture; cp.m_isSynchronized = false; cp.m_resourceManager = base_t::m_resourceManager; cp.m_renderContext = base_t::m_primaryContext; m_cacheScreen = make_shared_ptr(new graphics::Screen(cp)); rp.m_CacheScreen = m_cacheScreen.get(); rp.m_GlyphCache = base_t::m_resourceManager->glyphCache(0); rp.m_InvalidateFn = bind(&GUITestWidget<TTest>::invalidate, this); rp.m_Density = graphics::EDensityMDPI; m_stringBundle.reset(new StringsBundle()); m_stringBundle->SetDefaultString("country_status_download", "Download^"); m_controller->SetStringsBundle(m_stringBundle.get()); InitImpl(m_controller, bool_tag<has_init_with_controller<TTest, TTest>::value >()); m_controller->SetRenderParams(rp); } void InitImpl(shared_ptr<gui::Controller> const & c, bool_tag<true> const &) { base_t::test.Init(c.get()); } void InitImpl(shared_ptr<gui::Controller> const & c, bool_tag<false> const &) {} void DoDraw(shared_ptr<graphics::Screen> const & s) { base_t::DoDraw(s); m_controller->UpdateElements(); m_controller->DrawFrame(s.get()); } void mousePressEvent(QMouseEvent * e) { base_t::mousePressEvent(e); if (e->button() == Qt::LeftButton) m_controller->OnTapStarted(m2::PointU(e->pos().x(), e->pos().y())); } void mouseReleaseEvent(QMouseEvent * e) { base_t::mouseReleaseEvent(e); if (e->button() == Qt::LeftButton) m_controller->OnTapEnded(m2::PointU(e->pos().x(), e->pos().y())); } void mouseMoveEvent(QMouseEvent * e) { base_t::mouseMoveEvent(e); m_controller->OnTapMoved(m2::PointU(e->pos().x(), e->pos().y())); } }; template <class Test> QWidget * create_gui_test_widget() { GUITestWidget<Test> * w = new GUITestWidget<Test>(); w->Init(); return w; } #define UNIT_TEST_GUI(name)\ void UnitTestGUI_##name();\ TestRegister g_TestRegisterGUI_##name("Test::"#name, __FILE__, &UnitTestGUI_##name);\ void UnitTestGUI_##name()\ {\ char * argv[] = { const_cast<char *>(#name) };\ int argc = 1;\ QApplication app(argc, argv);\ QWidget * w = create_gui_test_widget<name>();\ w->show();\ app.exec();\ } <commit_msg>Looped drawing in tests<commit_after>#pragma once #include "gl_test_widget.hpp" #include "../../gui/controller.hpp" #include "../../base/strings_bundle.hpp" #include <QMouseEvent> #include <QObject> #include <QTimerEvent> template <class T, void (T::*)(gui::Controller*)> struct init_with_controller_fn_bind { typedef T type; }; template <class T, class U> struct has_init_with_controller { static bool const value = false; }; template <class T> struct has_init_with_controller<T, typename init_with_controller_fn_bind<T, &T::Init>::type> { static bool const value = true; }; template <typename TTest> class GUITestWidget : public GLTestWidget<TTest> { private: typedef GLTestWidget<TTest> base_t; shared_ptr<gui::Controller> m_controller; shared_ptr<graphics::Screen> m_cacheScreen; shared_ptr<StringsBundle> m_stringBundle; shared_ptr<QObject> m_timerObj; int m_timerID; public: void invalidate() { base_t::updateGL(); } void initializeGL() { m_timerObj.reset(new QObject()); m_timerObj->installEventFilter(this); m_timerID = m_timerObj->startTimer(1000 / 60); base_t::initializeGL(); m_controller.reset(new gui::Controller()); gui::Controller::RenderParams rp; graphics::Screen::Params cp; cp.m_doUnbindRT = false; cp.m_threadSlot = 0; cp.m_storageType = graphics::ETinyStorage; cp.m_textureType = graphics::ESmallTexture; cp.m_isSynchronized = false; cp.m_resourceManager = base_t::m_resourceManager; cp.m_renderContext = base_t::m_primaryContext; m_cacheScreen = make_shared_ptr(new graphics::Screen(cp)); rp.m_CacheScreen = m_cacheScreen.get(); rp.m_GlyphCache = base_t::m_resourceManager->glyphCache(0); rp.m_InvalidateFn = bind(&GUITestWidget<TTest>::invalidate, this); rp.m_Density = graphics::EDensityMDPI; m_stringBundle.reset(new StringsBundle()); m_stringBundle->SetDefaultString("country_status_download", "Download^"); m_controller->SetStringsBundle(m_stringBundle.get()); InitImpl(m_controller, bool_tag<has_init_with_controller<TTest, TTest>::value >()); m_controller->SetRenderParams(rp); } void InitImpl(shared_ptr<gui::Controller> const & c, bool_tag<true> const &) { base_t::test.Init(c.get()); } void InitImpl(shared_ptr<gui::Controller> const & c, bool_tag<false> const &) {} void DoDraw(shared_ptr<graphics::Screen> const & s) { base_t::DoDraw(s); m_controller->UpdateElements(); m_controller->DrawFrame(s.get()); } void mousePressEvent(QMouseEvent * e) { base_t::mousePressEvent(e); if (e->button() == Qt::LeftButton) m_controller->OnTapStarted(m2::PointU(e->pos().x(), e->pos().y())); } void mouseReleaseEvent(QMouseEvent * e) { base_t::mouseReleaseEvent(e); if (e->button() == Qt::LeftButton) m_controller->OnTapEnded(m2::PointU(e->pos().x(), e->pos().y())); } void mouseMoveEvent(QMouseEvent * e) { base_t::mouseMoveEvent(e); m_controller->OnTapMoved(m2::PointU(e->pos().x(), e->pos().y())); } bool eventFilter(QObject * obj, QEvent *event) { if (obj == m_timerObj.get() && event->type() == QEvent::Timer) { if (((QTimerEvent *)event)->timerId() == m_timerID) { invalidate(); return true; } } return false; } }; template <class Test> QWidget * create_gui_test_widget() { GUITestWidget<Test> * w = new GUITestWidget<Test>(); w->Init(); return w; } #define UNIT_TEST_GUI(name)\ void UnitTestGUI_##name();\ TestRegister g_TestRegisterGUI_##name("Test::"#name, __FILE__, &UnitTestGUI_##name);\ void UnitTestGUI_##name()\ {\ char * argv[] = { const_cast<char *>(#name) };\ int argc = 1;\ QApplication app(argc, argv);\ QWidget * w = create_gui_test_widget<name>();\ w->show();\ app.exec();\ } <|endoftext|>
<commit_before>// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/quartc/quartc_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/core/tls_client_handshaker.h" #include "net/third_party/quiche/src/quic/core/tls_server_handshaker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_storage.h" #include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h" #include "net/third_party/quiche/src/quic/quartc/quartc_crypto_helpers.h" namespace quic { namespace { // Arbitrary server port number for net::QuicCryptoClientConfig. const int kQuicServerPort = 0; } // namespace QuartcSession::QuartcSession(std::unique_ptr<QuicConnection> connection, Visitor* visitor, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock) : QuicSession(connection.get(), visitor, config, supported_versions), connection_(std::move(connection)), clock_(clock), per_packet_options_(QuicMakeUnique<QuartcPerPacketOptions>()) { per_packet_options_->connection = connection_.get(); connection_->set_per_packet_options(per_packet_options_.get()); } QuartcSession::~QuartcSession() {} QuartcStream* QuartcSession::CreateOutgoingBidirectionalStream() { // Use default priority for incoming QUIC streams. // TODO(zhihuang): Determine if this value is correct. return ActivateDataStream(CreateDataStream( GetNextOutgoingBidirectionalStreamId(), QuicStream::kDefaultPriority)); } bool QuartcSession::SendOrQueueMessage(std::string message) { if (!CanSendMessage()) { QUIC_LOG(ERROR) << "Quic session does not support SendMessage"; return false; } if (message.size() > GetCurrentLargestMessagePayload()) { QUIC_LOG(ERROR) << "Message is too big, message_size=" << message.size() << ", GetCurrentLargestMessagePayload=" << GetCurrentLargestMessagePayload(); return false; } // There may be other messages in send queue, so we have to add message // to the queue and call queue processing helper. send_message_queue_.emplace_back(std::move(message)); ProcessSendMessageQueue(); return true; } void QuartcSession::ProcessSendMessageQueue() { QuicConnection::ScopedPacketFlusher flusher( connection(), QuicConnection::AckBundling::NO_ACK); while (!send_message_queue_.empty()) { struct iovec iov = {const_cast<char*>(send_message_queue_.front().data()), send_message_queue_.front().length()}; QuicMemSliceStorage storage( &iov, 1, connection()->helper()->GetStreamSendBufferAllocator(), send_message_queue_.front().length()); MessageResult result = SendMessage(storage.ToSpan()); const size_t message_size = send_message_queue_.front().size(); // Handle errors. switch (result.status) { case MESSAGE_STATUS_SUCCESS: QUIC_VLOG(1) << "Quartc message sent, message_id=" << result.message_id << ", message_size=" << message_size; break; // If connection is congestion controlled or not writable yet, stop // send loop and we'll retry again when we get OnCanWrite notification. case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED: case MESSAGE_STATUS_BLOCKED: QUIC_VLOG(1) << "Quartc message not sent because connection is blocked" << ", message will be retried later, status=" << result.status << ", message_size=" << message_size; return; // Other errors are unexpected. We do not propagate error to Quartc, // because writes can be delayed. case MESSAGE_STATUS_UNSUPPORTED: case MESSAGE_STATUS_TOO_LARGE: case MESSAGE_STATUS_INTERNAL_ERROR: QUIC_DLOG(DFATAL) << "Failed to send quartc message due to unexpected error" << ", message will not be retried, status=" << result.status << ", message_size=" << message_size; break; } send_message_queue_.pop_front(); } } void QuartcSession::OnCanWrite() { // TODO(b/119640244): Since we currently use messages for audio and streams // for video, it makes sense to process queued messages first, then call quic // core OnCanWrite, which will resend queued streams. Long term we may need // better solution especially if quic connection is used for both data and // media. // Process quartc messages that were previously blocked. ProcessSendMessageQueue(); QuicSession::OnCanWrite(); } bool QuartcSession::SendProbingData() { if (QuicSession::SendProbingData()) { return true; } SetTransmissionType(PROBING_RETRANSMISSION); SendPing(); WriteControlFrame(QuicFrame(QuicPaddingFrame())); return true; } void QuartcSession::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) { QuicSession::OnCryptoHandshakeEvent(event); switch (event) { case ENCRYPTION_FIRST_ESTABLISHED: case ENCRYPTION_REESTABLISHED: // 1-rtt setup triggers 'ENCRYPTION_REESTABLISHED' (after REJ, when the // CHLO is sent). DCHECK(IsEncryptionEstablished()); DCHECK(session_delegate_); session_delegate_->OnConnectionWritable(); break; case HANDSHAKE_CONFIRMED: // On the server, handshake confirmed is the first time when you can start // writing packets. DCHECK(IsEncryptionEstablished()); DCHECK(IsCryptoHandshakeConfirmed()); DCHECK(session_delegate_); session_delegate_->OnConnectionWritable(); session_delegate_->OnCryptoHandshakeComplete(); break; } } void QuartcSession::CancelStream(QuicStreamId stream_id) { ResetStream(stream_id, QuicRstStreamErrorCode::QUIC_STREAM_CANCELLED); } void QuartcSession::ResetStream(QuicStreamId stream_id, QuicRstStreamErrorCode error) { if (!IsOpenStream(stream_id)) { return; } QuicStream* stream = QuicSession::GetOrCreateStream(stream_id); if (stream) { stream->Reset(error); } } void QuartcSession::OnCongestionWindowChange(QuicTime now) { DCHECK(session_delegate_); const RttStats* rtt_stats = connection_->sent_packet_manager().GetRttStats(); QuicBandwidth bandwidth_estimate = connection_->sent_packet_manager().BandwidthEstimate(); QuicByteCount in_flight = connection_->sent_packet_manager().GetBytesInFlight(); QuicBandwidth pacing_rate = connection_->sent_packet_manager().GetSendAlgorithm()->PacingRate( in_flight); session_delegate_->OnCongestionControlChange(bandwidth_estimate, pacing_rate, rtt_stats->latest_rtt()); } bool QuartcSession::ShouldKeepConnectionAlive() const { // TODO(mellem): Quartc may want different keepalive logic than HTTP. return GetNumOpenDynamicStreams() > 0; } void QuartcSession::OnConnectionClosed(QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) { QuicSession::OnConnectionClosed(error, error_details, source); DCHECK(session_delegate_); session_delegate_->OnConnectionClosed(error, error_details, source); } void QuartcSession::CloseConnection(const std::string& details) { connection_->CloseConnection( QuicErrorCode::QUIC_CONNECTION_CANCELLED, details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET_WITH_NO_ACK); } void QuartcSession::SetDelegate(Delegate* session_delegate) { if (session_delegate_) { QUIC_LOG(WARNING) << "The delegate for the session has already been set."; } session_delegate_ = session_delegate; DCHECK(session_delegate_); } void QuartcSession::OnTransportCanWrite() { connection()->writer()->SetWritable(); if (HasDataToWrite()) { connection()->OnCanWrite(); } } void QuartcSession::OnTransportReceived(const char* data, size_t data_len) { QuicReceivedPacket packet(data, data_len, clock_->Now()); ProcessUdpPacket(connection()->self_address(), connection()->peer_address(), packet); } void QuartcSession::OnMessageReceived(QuicStringPiece message) { session_delegate_->OnMessageReceived(message); } QuicStream* QuartcSession::CreateIncomingStream(QuicStreamId id) { return ActivateDataStream(CreateDataStream(id, QuicStream::kDefaultPriority)); } QuicStream* QuartcSession::CreateIncomingStream(PendingStream pending) { return ActivateDataStream( CreateDataStream(std::move(pending), QuicStream::kDefaultPriority)); } std::unique_ptr<QuartcStream> QuartcSession::CreateDataStream( QuicStreamId id, spdy::SpdyPriority priority) { if (GetCryptoStream() == nullptr || !GetCryptoStream()->encryption_established()) { // Encryption not active so no stream created return nullptr; } return InitializeDataStream(QuicMakeUnique<QuartcStream>(id, this), priority); } std::unique_ptr<QuartcStream> QuartcSession::CreateDataStream( PendingStream pending, spdy::SpdyPriority priority) { return InitializeDataStream(QuicMakeUnique<QuartcStream>(std::move(pending)), priority); } std::unique_ptr<QuartcStream> QuartcSession::InitializeDataStream( std::unique_ptr<QuartcStream> stream, spdy::SpdyPriority priority) { // Register the stream to the QuicWriteBlockedList. |priority| is clamped // between 0 and 7, with 0 being the highest priority and 7 the lowest // priority. write_blocked_streams()->UpdateStreamPriority(stream->id(), priority); if (IsIncomingStream(stream->id())) { DCHECK(session_delegate_); // Incoming streams need to be registered with the session_delegate_. session_delegate_->OnIncomingStream(stream.get()); } return stream; } QuartcStream* QuartcSession::ActivateDataStream( std::unique_ptr<QuartcStream> stream) { // Transfer ownership of the data stream to the session via ActivateStream(). QuartcStream* raw = stream.release(); if (raw) { // Make QuicSession take ownership of the stream. ActivateStream(std::unique_ptr<QuicStream>(raw)); } return raw; } QuartcClientSession::QuartcClientSession( std::unique_ptr<QuicConnection> connection, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, std::unique_ptr<QuartcPacketWriter> packet_writer, std::unique_ptr<QuicCryptoClientConfig> client_crypto_config, QuicStringPiece server_crypto_config) : QuartcSession(std::move(connection), /*visitor=*/nullptr, config, supported_versions, clock), packet_writer_(std::move(packet_writer)), client_crypto_config_(std::move(client_crypto_config)), server_config_(server_crypto_config) { DCHECK_EQ(QuartcSession::connection()->perspective(), Perspective::IS_CLIENT); } QuartcClientSession::~QuartcClientSession() { // The client session is the packet transport delegate, so it must be unset // before the session is deleted. packet_writer_->SetPacketTransportDelegate(nullptr); } void QuartcClientSession::Initialize() { DCHECK(crypto_stream_) << "Do not call QuartcSession::Initialize(), call " "StartCryptoHandshake() instead."; QuartcSession::Initialize(); // QUIC is ready to process incoming packets after Initialize(). // Set the packet transport delegate to begin receiving packets. packet_writer_->SetPacketTransportDelegate(this); } const QuicCryptoStream* QuartcClientSession::GetCryptoStream() const { return crypto_stream_.get(); } QuicCryptoStream* QuartcClientSession::GetMutableCryptoStream() { return crypto_stream_.get(); } void QuartcClientSession::StartCryptoHandshake() { QuicServerId server_id(/*host=*/"", kQuicServerPort, /*privacy_mode_enabled=*/false); if (!server_config_.empty()) { QuicCryptoServerConfig::ConfigOptions options; std::string error; QuicWallTime now = clock()->WallNow(); QuicCryptoClientConfig::CachedState::ServerConfigState result = client_crypto_config_->LookupOrCreate(server_id)->SetServerConfig( server_config_, now, /*expiry_time=*/now.Add(QuicTime::Delta::Infinite()), &error); if (result == QuicCryptoClientConfig::CachedState::SERVER_CONFIG_VALID) { DCHECK_EQ(error, ""); client_crypto_config_->LookupOrCreate(server_id)->SetProof( std::vector<std::string>{kDummyCertName}, /*cert_sct=*/"", /*chlo_hash=*/"", /*signature=*/"anything"); } else { QUIC_LOG(DFATAL) << "Unable to set server config, error=" << error; } } crypto_stream_ = QuicMakeUnique<QuicCryptoClientStream>( server_id, this, client_crypto_config_->proof_verifier()->CreateDefaultContext(), client_crypto_config_.get(), this); Initialize(); crypto_stream_->CryptoConnect(); } void QuartcClientSession::OnProofValid( const QuicCryptoClientConfig::CachedState& cached) { // TODO(zhihuang): Handle the proof verification. } void QuartcClientSession::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) { // TODO(zhihuang): Handle the proof verification. } QuartcServerSession::QuartcServerSession( std::unique_ptr<QuicConnection> connection, Visitor* visitor, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, const QuicCryptoServerConfig* server_crypto_config, QuicCompressedCertsCache* const compressed_certs_cache, QuicCryptoServerStream::Helper* const stream_helper) : QuartcSession(std::move(connection), visitor, config, supported_versions, clock), server_crypto_config_(server_crypto_config), compressed_certs_cache_(compressed_certs_cache), stream_helper_(stream_helper) { DCHECK_EQ(QuartcSession::connection()->perspective(), Perspective::IS_SERVER); } const QuicCryptoStream* QuartcServerSession::GetCryptoStream() const { return crypto_stream_.get(); } QuicCryptoStream* QuartcServerSession::GetMutableCryptoStream() { return crypto_stream_.get(); } void QuartcServerSession::StartCryptoHandshake() { crypto_stream_ = QuicMakeUnique<QuicCryptoServerStream>( server_crypto_config_, compressed_certs_cache_, /*use_stateless_rejects_if_peer_supported=*/false, this, stream_helper_); Initialize(); } } // namespace quic <commit_msg>Remove the call to write padding when send probing data.<commit_after>// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/quartc/quartc_session.h" #include "net/third_party/quiche/src/quic/core/quic_utils.h" #include "net/third_party/quiche/src/quic/core/tls_client_handshaker.h" #include "net/third_party/quiche/src/quic/core/tls_server_handshaker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_storage.h" #include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h" #include "net/third_party/quiche/src/quic/quartc/quartc_crypto_helpers.h" namespace quic { namespace { // Arbitrary server port number for net::QuicCryptoClientConfig. const int kQuicServerPort = 0; } // namespace QuartcSession::QuartcSession(std::unique_ptr<QuicConnection> connection, Visitor* visitor, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock) : QuicSession(connection.get(), visitor, config, supported_versions), connection_(std::move(connection)), clock_(clock), per_packet_options_(QuicMakeUnique<QuartcPerPacketOptions>()) { per_packet_options_->connection = connection_.get(); connection_->set_per_packet_options(per_packet_options_.get()); } QuartcSession::~QuartcSession() {} QuartcStream* QuartcSession::CreateOutgoingBidirectionalStream() { // Use default priority for incoming QUIC streams. // TODO(zhihuang): Determine if this value is correct. return ActivateDataStream(CreateDataStream( GetNextOutgoingBidirectionalStreamId(), QuicStream::kDefaultPriority)); } bool QuartcSession::SendOrQueueMessage(std::string message) { if (!CanSendMessage()) { QUIC_LOG(ERROR) << "Quic session does not support SendMessage"; return false; } if (message.size() > GetCurrentLargestMessagePayload()) { QUIC_LOG(ERROR) << "Message is too big, message_size=" << message.size() << ", GetCurrentLargestMessagePayload=" << GetCurrentLargestMessagePayload(); return false; } // There may be other messages in send queue, so we have to add message // to the queue and call queue processing helper. send_message_queue_.emplace_back(std::move(message)); ProcessSendMessageQueue(); return true; } void QuartcSession::ProcessSendMessageQueue() { QuicConnection::ScopedPacketFlusher flusher( connection(), QuicConnection::AckBundling::NO_ACK); while (!send_message_queue_.empty()) { struct iovec iov = {const_cast<char*>(send_message_queue_.front().data()), send_message_queue_.front().length()}; QuicMemSliceStorage storage( &iov, 1, connection()->helper()->GetStreamSendBufferAllocator(), send_message_queue_.front().length()); MessageResult result = SendMessage(storage.ToSpan()); const size_t message_size = send_message_queue_.front().size(); // Handle errors. switch (result.status) { case MESSAGE_STATUS_SUCCESS: QUIC_VLOG(1) << "Quartc message sent, message_id=" << result.message_id << ", message_size=" << message_size; break; // If connection is congestion controlled or not writable yet, stop // send loop and we'll retry again when we get OnCanWrite notification. case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED: case MESSAGE_STATUS_BLOCKED: QUIC_VLOG(1) << "Quartc message not sent because connection is blocked" << ", message will be retried later, status=" << result.status << ", message_size=" << message_size; return; // Other errors are unexpected. We do not propagate error to Quartc, // because writes can be delayed. case MESSAGE_STATUS_UNSUPPORTED: case MESSAGE_STATUS_TOO_LARGE: case MESSAGE_STATUS_INTERNAL_ERROR: QUIC_DLOG(DFATAL) << "Failed to send quartc message due to unexpected error" << ", message will not be retried, status=" << result.status << ", message_size=" << message_size; break; } send_message_queue_.pop_front(); } } void QuartcSession::OnCanWrite() { // TODO(b/119640244): Since we currently use messages for audio and streams // for video, it makes sense to process queued messages first, then call quic // core OnCanWrite, which will resend queued streams. Long term we may need // better solution especially if quic connection is used for both data and // media. // Process quartc messages that were previously blocked. ProcessSendMessageQueue(); QuicSession::OnCanWrite(); } bool QuartcSession::SendProbingData() { if (QuicSession::SendProbingData()) { return true; } // Set transmission type to PROBING_RETRANSMISSION such that the packets will // be padded to full. SetTransmissionType(PROBING_RETRANSMISSION); // TODO(mellem): this sent PING will be retransmitted if it is lost which is // not ideal. Consider to send stream data as probing data instead. SendPing(); return true; } void QuartcSession::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) { QuicSession::OnCryptoHandshakeEvent(event); switch (event) { case ENCRYPTION_FIRST_ESTABLISHED: case ENCRYPTION_REESTABLISHED: // 1-rtt setup triggers 'ENCRYPTION_REESTABLISHED' (after REJ, when the // CHLO is sent). DCHECK(IsEncryptionEstablished()); DCHECK(session_delegate_); session_delegate_->OnConnectionWritable(); break; case HANDSHAKE_CONFIRMED: // On the server, handshake confirmed is the first time when you can start // writing packets. DCHECK(IsEncryptionEstablished()); DCHECK(IsCryptoHandshakeConfirmed()); DCHECK(session_delegate_); session_delegate_->OnConnectionWritable(); session_delegate_->OnCryptoHandshakeComplete(); break; } } void QuartcSession::CancelStream(QuicStreamId stream_id) { ResetStream(stream_id, QuicRstStreamErrorCode::QUIC_STREAM_CANCELLED); } void QuartcSession::ResetStream(QuicStreamId stream_id, QuicRstStreamErrorCode error) { if (!IsOpenStream(stream_id)) { return; } QuicStream* stream = QuicSession::GetOrCreateStream(stream_id); if (stream) { stream->Reset(error); } } void QuartcSession::OnCongestionWindowChange(QuicTime now) { DCHECK(session_delegate_); const RttStats* rtt_stats = connection_->sent_packet_manager().GetRttStats(); QuicBandwidth bandwidth_estimate = connection_->sent_packet_manager().BandwidthEstimate(); QuicByteCount in_flight = connection_->sent_packet_manager().GetBytesInFlight(); QuicBandwidth pacing_rate = connection_->sent_packet_manager().GetSendAlgorithm()->PacingRate( in_flight); session_delegate_->OnCongestionControlChange(bandwidth_estimate, pacing_rate, rtt_stats->latest_rtt()); } bool QuartcSession::ShouldKeepConnectionAlive() const { // TODO(mellem): Quartc may want different keepalive logic than HTTP. return GetNumOpenDynamicStreams() > 0; } void QuartcSession::OnConnectionClosed(QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) { QuicSession::OnConnectionClosed(error, error_details, source); DCHECK(session_delegate_); session_delegate_->OnConnectionClosed(error, error_details, source); } void QuartcSession::CloseConnection(const std::string& details) { connection_->CloseConnection( QuicErrorCode::QUIC_CONNECTION_CANCELLED, details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET_WITH_NO_ACK); } void QuartcSession::SetDelegate(Delegate* session_delegate) { if (session_delegate_) { QUIC_LOG(WARNING) << "The delegate for the session has already been set."; } session_delegate_ = session_delegate; DCHECK(session_delegate_); } void QuartcSession::OnTransportCanWrite() { connection()->writer()->SetWritable(); if (HasDataToWrite()) { connection()->OnCanWrite(); } } void QuartcSession::OnTransportReceived(const char* data, size_t data_len) { QuicReceivedPacket packet(data, data_len, clock_->Now()); ProcessUdpPacket(connection()->self_address(), connection()->peer_address(), packet); } void QuartcSession::OnMessageReceived(QuicStringPiece message) { session_delegate_->OnMessageReceived(message); } QuicStream* QuartcSession::CreateIncomingStream(QuicStreamId id) { return ActivateDataStream(CreateDataStream(id, QuicStream::kDefaultPriority)); } QuicStream* QuartcSession::CreateIncomingStream(PendingStream pending) { return ActivateDataStream( CreateDataStream(std::move(pending), QuicStream::kDefaultPriority)); } std::unique_ptr<QuartcStream> QuartcSession::CreateDataStream( QuicStreamId id, spdy::SpdyPriority priority) { if (GetCryptoStream() == nullptr || !GetCryptoStream()->encryption_established()) { // Encryption not active so no stream created return nullptr; } return InitializeDataStream(QuicMakeUnique<QuartcStream>(id, this), priority); } std::unique_ptr<QuartcStream> QuartcSession::CreateDataStream( PendingStream pending, spdy::SpdyPriority priority) { return InitializeDataStream(QuicMakeUnique<QuartcStream>(std::move(pending)), priority); } std::unique_ptr<QuartcStream> QuartcSession::InitializeDataStream( std::unique_ptr<QuartcStream> stream, spdy::SpdyPriority priority) { // Register the stream to the QuicWriteBlockedList. |priority| is clamped // between 0 and 7, with 0 being the highest priority and 7 the lowest // priority. write_blocked_streams()->UpdateStreamPriority(stream->id(), priority); if (IsIncomingStream(stream->id())) { DCHECK(session_delegate_); // Incoming streams need to be registered with the session_delegate_. session_delegate_->OnIncomingStream(stream.get()); } return stream; } QuartcStream* QuartcSession::ActivateDataStream( std::unique_ptr<QuartcStream> stream) { // Transfer ownership of the data stream to the session via ActivateStream(). QuartcStream* raw = stream.release(); if (raw) { // Make QuicSession take ownership of the stream. ActivateStream(std::unique_ptr<QuicStream>(raw)); } return raw; } QuartcClientSession::QuartcClientSession( std::unique_ptr<QuicConnection> connection, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, std::unique_ptr<QuartcPacketWriter> packet_writer, std::unique_ptr<QuicCryptoClientConfig> client_crypto_config, QuicStringPiece server_crypto_config) : QuartcSession(std::move(connection), /*visitor=*/nullptr, config, supported_versions, clock), packet_writer_(std::move(packet_writer)), client_crypto_config_(std::move(client_crypto_config)), server_config_(server_crypto_config) { DCHECK_EQ(QuartcSession::connection()->perspective(), Perspective::IS_CLIENT); } QuartcClientSession::~QuartcClientSession() { // The client session is the packet transport delegate, so it must be unset // before the session is deleted. packet_writer_->SetPacketTransportDelegate(nullptr); } void QuartcClientSession::Initialize() { DCHECK(crypto_stream_) << "Do not call QuartcSession::Initialize(), call " "StartCryptoHandshake() instead."; QuartcSession::Initialize(); // QUIC is ready to process incoming packets after Initialize(). // Set the packet transport delegate to begin receiving packets. packet_writer_->SetPacketTransportDelegate(this); } const QuicCryptoStream* QuartcClientSession::GetCryptoStream() const { return crypto_stream_.get(); } QuicCryptoStream* QuartcClientSession::GetMutableCryptoStream() { return crypto_stream_.get(); } void QuartcClientSession::StartCryptoHandshake() { QuicServerId server_id(/*host=*/"", kQuicServerPort, /*privacy_mode_enabled=*/false); if (!server_config_.empty()) { QuicCryptoServerConfig::ConfigOptions options; std::string error; QuicWallTime now = clock()->WallNow(); QuicCryptoClientConfig::CachedState::ServerConfigState result = client_crypto_config_->LookupOrCreate(server_id)->SetServerConfig( server_config_, now, /*expiry_time=*/now.Add(QuicTime::Delta::Infinite()), &error); if (result == QuicCryptoClientConfig::CachedState::SERVER_CONFIG_VALID) { DCHECK_EQ(error, ""); client_crypto_config_->LookupOrCreate(server_id)->SetProof( std::vector<std::string>{kDummyCertName}, /*cert_sct=*/"", /*chlo_hash=*/"", /*signature=*/"anything"); } else { QUIC_LOG(DFATAL) << "Unable to set server config, error=" << error; } } crypto_stream_ = QuicMakeUnique<QuicCryptoClientStream>( server_id, this, client_crypto_config_->proof_verifier()->CreateDefaultContext(), client_crypto_config_.get(), this); Initialize(); crypto_stream_->CryptoConnect(); } void QuartcClientSession::OnProofValid( const QuicCryptoClientConfig::CachedState& cached) { // TODO(zhihuang): Handle the proof verification. } void QuartcClientSession::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) { // TODO(zhihuang): Handle the proof verification. } QuartcServerSession::QuartcServerSession( std::unique_ptr<QuicConnection> connection, Visitor* visitor, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, const QuicCryptoServerConfig* server_crypto_config, QuicCompressedCertsCache* const compressed_certs_cache, QuicCryptoServerStream::Helper* const stream_helper) : QuartcSession(std::move(connection), visitor, config, supported_versions, clock), server_crypto_config_(server_crypto_config), compressed_certs_cache_(compressed_certs_cache), stream_helper_(stream_helper) { DCHECK_EQ(QuartcSession::connection()->perspective(), Perspective::IS_SERVER); } const QuicCryptoStream* QuartcServerSession::GetCryptoStream() const { return crypto_stream_.get(); } QuicCryptoStream* QuartcServerSession::GetMutableCryptoStream() { return crypto_stream_.get(); } void QuartcServerSession::StartCryptoHandshake() { crypto_stream_ = QuicMakeUnique<QuicCryptoServerStream>( server_crypto_config_, compressed_certs_cache_, /*use_stateless_rejects_if_peer_supported=*/false, this, stream_helper_); Initialize(); } } // namespace quic <|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_METALRENDERTARGET_HPP #define OUZEL_GRAPHICS_METALRENDERTARGET_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_METAL #if defined(__OBJC__) # import <Metal/Metal.h> typedef MTLRenderPassDescriptor* MTLRenderPassDescriptorPtr; #else # include <objc/objc.h> typedef id MTLRenderPassDescriptorPtr; typedef NSUInteger MTLLoadAction; typedef struct { double red; double green; double blue; double alpha; } MTLClearColor; #endif #include <set> #include "MetalRenderResource.hpp" #include "MetalPointer.hpp" #include "../../math/Color.hpp" namespace ouzel::graphics::metal { class RenderDevice; class Texture; class RenderTarget final: public RenderResource { public: RenderTarget(RenderDevice& initRenderDevice, const std::set<Texture*>& initColorTextures, Texture* initDepthTexture); auto& getColorTextures() const noexcept { return colorTextures; } auto getDepthTexture() const noexcept { return depthTexture; } auto getSampleCount() const noexcept { return sampleCount; } auto& getColorFormats() const noexcept { return colorFormats; } auto getDepthFormat() const noexcept { return depthFormat; } auto getStencilFormat() const noexcept { return stencilFormat; } auto& getRenderPassDescriptor() const noexcept { return renderPassDescriptor; } private: std::set<Texture*> colorTextures; Texture* depthTexture = nullptr; NSUInteger sampleCount = 0; std::vector<MTLPixelFormat> colorFormats; MTLPixelFormat depthFormat; MTLPixelFormat stencilFormat; Pointer<MTLRenderPassDescriptorPtr> renderPassDescriptor; }; } #endif #endif // OUZEL_GRAPHICS_METALRENDERTARGET_HPP <commit_msg>Remove the unneeded declaration of MTLClearColor<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_METALRENDERTARGET_HPP #define OUZEL_GRAPHICS_METALRENDERTARGET_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_METAL #if defined(__OBJC__) # import <Metal/Metal.h> typedef MTLRenderPassDescriptor* MTLRenderPassDescriptorPtr; #else # include <objc/objc.h> typedef id MTLRenderPassDescriptorPtr; typedef NSUInteger MTLLoadAction; #endif #include <set> #include "MetalRenderResource.hpp" #include "MetalPointer.hpp" #include "../../math/Color.hpp" namespace ouzel::graphics::metal { class RenderDevice; class Texture; class RenderTarget final: public RenderResource { public: RenderTarget(RenderDevice& initRenderDevice, const std::set<Texture*>& initColorTextures, Texture* initDepthTexture); auto& getColorTextures() const noexcept { return colorTextures; } auto getDepthTexture() const noexcept { return depthTexture; } auto getSampleCount() const noexcept { return sampleCount; } auto& getColorFormats() const noexcept { return colorFormats; } auto getDepthFormat() const noexcept { return depthFormat; } auto getStencilFormat() const noexcept { return stencilFormat; } auto& getRenderPassDescriptor() const noexcept { return renderPassDescriptor; } private: std::set<Texture*> colorTextures; Texture* depthTexture = nullptr; NSUInteger sampleCount = 0; std::vector<MTLPixelFormat> colorFormats; MTLPixelFormat depthFormat; MTLPixelFormat stencilFormat; Pointer<MTLRenderPassDescriptorPtr> renderPassDescriptor; }; } #endif #endif // OUZEL_GRAPHICS_METALRENDERTARGET_HPP <|endoftext|>
<commit_before><commit_msg>VclPtr: presumably these also leak<commit_after><|endoftext|>
<commit_before>#include <vector> #include <forward_list> #include <algorithm> namespace algorithm { template< class ValueType, /**< vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< weight type */ WeightType WeightDefaultValue = 0 /**< default value of weight */ > class Graph { public: typedef size_t SizeType; typedef unsigned int KeyType; /**< key type, used to access an array */ /** \brief Test if two keys are equal Test if two keys are equal. \return return true if two keys are equal; otherwise return false \param key_first first key to compare \param key_second second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) { return key_first == key_second; } /** \brief Vertex class Vertex class. Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< key of vertex; same with index in graph_ */ ValueType value; /**< value of vertex */ std::forward_list< std::pair<const KeyType, WeightType> > edges; /**< edges of vertex \param const KeyType key_dest \param WeightType weight */ SizeType edges_size; /**< count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) , edges_size(0) { } /** \brief Test if two values are equal Test if two values are equal. \return return true if two values are equal; otherwise return false \param value value to compare */ bool IsValueEqual(const ValueType & value) { return this.value == value; } }; private: std::vector<VertexNode> graph_; /**< graph */ public: /** \brief Test whether there is an edge from the vertices src to dest Test whether there is an edge from the vertices depart to dest. \return return true if the edge exists; otherwise return false \param key_src key of source (src) \param key_dest key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** \brief Add a vertex Add a vertex, if a graph not have the vertex with specified value already. \return return the key of vertex if added successfully; otherwise return -1 \param value_of_vertex value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** \brief Add an edge Add an edge connects two vertices. \param key_src key of source (src) \param key_dest key of destination (dest) \param weight weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.push_front( std::make_pair<const KeyType, WeightType> (key_dest, weight) ); ++graph_.at(key_src).edges_size; } /** \brief Get a key of the vertex with specified value Get a key of the vertex with specified value from a graph. If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return return the key of vertex if added successfully; otherwise return the size of graph \param value_of_vertex value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** \brief Get a value of the vertex with specified key Get a value of the vertex with specified key from a graph. \return return the value \param key_of_vertex key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) { return graph_.at(key_of_vertex).value; } /** \brief Set a value of the vertex with specified key Set a value of the vertex with specified key from a graph. \param key_of_vertex key of vertex \param value_of_vertex value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** \brief Get a count of vertices Get a count of vertices \return count of vertices */ inline SizeType GetVertexCount(void) { return graph_.size(); } /** \brief Get a count of edges Get a count of edges \return count of edges \param key_of_vertex key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) { return graph_.at(key_of_vertex).edges_size; } }; } /** ns:algorithm */ <commit_msg>Add header comments<commit_after>/** * * Graph * * Undirected, weighted graph * https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016 * */ /** Includes */ #include <cstddef> /** To define size_t */ /** STL containers */ #include <vector> #include <forward_list> namespace algorithm { template< class ValueType, /**< vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< weight type */ WeightType WeightDefaultValue = 0 /**< default value of weight */ > class Graph { public: typedef size_t SizeType; typedef unsigned int KeyType; /**< key type, used to access an array */ /** \brief Test if two keys are equal Test if two keys are equal. \return return true if two keys are equal; otherwise return false \param key_first first key to compare \param key_second second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) { return key_first == key_second; } /** \brief Vertex class Vertex class. Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< key of vertex; same with index in graph_ */ ValueType value; /**< value of vertex */ std::forward_list< std::pair<const KeyType, WeightType> > edges; /**< edges of vertex \param const KeyType key_dest \param WeightType weight */ SizeType edges_size; /**< count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) , edges_size(0) { } /** \brief Test if two values are equal Test if two values are equal. \return return true if two values are equal; otherwise return false \param value value to compare */ bool IsValueEqual(const ValueType & value) { return this.value == value; } }; private: std::vector<VertexNode> graph_; /**< graph */ public: /** \brief Test whether there is an edge from the vertices src to dest Test whether there is an edge from the vertices depart to dest. \return return true if the edge exists; otherwise return false \param key_src key of source (src) \param key_dest key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** \brief Add a vertex Add a vertex, if a graph not have the vertex with specified value already. \return return the key of vertex if added successfully; otherwise return -1 \param value_of_vertex value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** \brief Add an edge Add an edge connects two vertices. \param key_src key of source (src) \param key_dest key of destination (dest) \param weight weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.push_front( std::make_pair<const KeyType, WeightType> (key_dest, weight) ); ++graph_.at(key_src).edges_size; } /** \brief Get a key of the vertex with specified value Get a key of the vertex with specified value from a graph. If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return return the key of vertex if added successfully; otherwise return the size of graph \param value_of_vertex value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** \brief Get a value of the vertex with specified key Get a value of the vertex with specified key from a graph. \return return the value \param key_of_vertex key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) { return graph_.at(key_of_vertex).value; } /** \brief Set a value of the vertex with specified key Set a value of the vertex with specified key from a graph. \param key_of_vertex key of vertex \param value_of_vertex value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** \brief Get a count of vertices Get a count of vertices \return count of vertices */ inline SizeType GetVertexCount(void) { return graph_.size(); } /** \brief Get a count of edges Get a count of edges \return count of edges \param key_of_vertex key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) { return graph_.at(key_of_vertex).edges_size; } }; } /** ns: algorithm */ <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkMapper.h" #include "mitkDataTreeNode.h" //##ModelId=3E3C337E0162 mitk::Mapper::Mapper() { } //##ModelId=3E3C337E019E mitk::Mapper::~Mapper() { } //##ModelId=3E860B9A0378 mitk::BaseData* mitk::Mapper::GetData() const { return m_DataTreeNode->GetData(); } //##ModelId=3EF17276014B bool mitk::Mapper::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetColor(rgb, renderer, name); } //##ModelId=3EF17795006A bool mitk::Mapper::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetVisibility(visible, renderer, name); } //##ModelId=3EF1781F0285 bool mitk::Mapper::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetOpacity(opacity, renderer, name); } //##ModelId=3EF179660018 bool mitk::Mapper::GetLevelWindow(mitk::LevelWindow& levelWindow, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetLevelWindow(levelWindow, renderer, name); } //##ModelId=3EF18B340008 bool mitk::Mapper::IsVisible(mitk::BaseRenderer* renderer, const char* name) const { bool visible=true; GetVisibility(visible, renderer, name); return visible; } void mitk::Mapper::GenerateData() { } void mitk::Mapper::GenerateData(mitk::BaseRenderer* renderer) { } //##ModelId=3EF1A43C01D9 void mitk::Mapper::Update(mitk::BaseRenderer* renderer) { const DataTreeNode* node = GetDataTreeNode(); //safty cause there are datatreenodes, that have no defined data (video-nodes and root) unsigned int dataMTime = 0; mitk::BaseData::Pointer data = dynamic_cast<mitk::BaseData *>(node->GetData()); if (data.IsNotNull()) { dataMTime = data->GetMTime(); } if( (m_LastUpdateTime < GetMTime()) || (m_LastUpdateTime < node->GetDataReferenceChangedTime()) || (m_LastUpdateTime < dataMTime) ) { GenerateData(); m_LastUpdateTime.Modified(); } GenerateData(renderer); } <commit_msg>ENH: assert(node!=NULL), static_cast instead of dynamic_cast<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkMapper.h" #include "mitkDataTreeNode.h" //##ModelId=3E3C337E0162 mitk::Mapper::Mapper() { } //##ModelId=3E3C337E019E mitk::Mapper::~Mapper() { } //##ModelId=3E860B9A0378 mitk::BaseData* mitk::Mapper::GetData() const { return m_DataTreeNode->GetData(); } //##ModelId=3EF17276014B bool mitk::Mapper::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetColor(rgb, renderer, name); } //##ModelId=3EF17795006A bool mitk::Mapper::GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetVisibility(visible, renderer, name); } //##ModelId=3EF1781F0285 bool mitk::Mapper::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetOpacity(opacity, renderer, name); } //##ModelId=3EF179660018 bool mitk::Mapper::GetLevelWindow(mitk::LevelWindow& levelWindow, mitk::BaseRenderer* renderer, const char* name) const { const mitk::DataTreeNode* node=GetDataTreeNode(); if(node==NULL) return false; return node->GetLevelWindow(levelWindow, renderer, name); } //##ModelId=3EF18B340008 bool mitk::Mapper::IsVisible(mitk::BaseRenderer* renderer, const char* name) const { bool visible=true; GetVisibility(visible, renderer, name); return visible; } void mitk::Mapper::GenerateData() { } void mitk::Mapper::GenerateData(mitk::BaseRenderer* renderer) { } //##ModelId=3EF1A43C01D9 void mitk::Mapper::Update(mitk::BaseRenderer* renderer) { const DataTreeNode* node = GetDataTreeNode(); assert(node!=NULL); //safty cause there are datatreenodes, that have no defined data (video-nodes and root) unsigned int dataMTime = 0; mitk::BaseData::Pointer data = static_cast<mitk::BaseData *>(node->GetData()); if (data.IsNotNull()) { dataMTime = data->GetMTime(); } if( (m_LastUpdateTime < GetMTime()) || (m_LastUpdateTime < node->GetDataReferenceChangedTime()) || (m_LastUpdateTime < dataMTime) ) { GenerateData(); m_LastUpdateTime.Modified(); } GenerateData(renderer); } <|endoftext|>
<commit_before>/* * This file is part of vaporpp. * * vaporpp is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * vaporpp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with vaporpp. If not, see <http://www.gnu.org/licenses/>. */ #include "client.hpp" #include <cassert> #include <boost/asio.hpp> #include <array> using boost::asio::io_service; using boost::asio::ip::tcp; //pimpl-class (private members of client): class vlpp::client::client_impl { public: client_impl(const std::string& servername, const std::string& token, uint16_t port); void authenticate(const std::string& token); void set_led(uint16_t led, rgba_color col); void execute(); io_service _io_service; tcp::socket _socket; std::vector<char> cmd_buffer; }; //opcodes: enum: uint8_t { OP_SET_LED = 0x01, OP_AUTHENTICATE = 0x02, OP_STROBE = 0xFF }; enum { TOKEN_SIZE = 16 }; /////////// vlpp::client::client(const std::string &server, const std::string &token, uint16_t port): _impl(new vlpp::client::client_impl(server, token, port)) { } vlpp::client::~client() { } void vlpp::client::set_led(uint16_t led_id, const rgba_color &col) { _impl->set_led(led_id, col); } void vlpp::client::set_leds(const std::vector<uint16_t> &led_ids, const rgba_color &col) { for (auto led: led_ids) { set_led(led, col); } } void vlpp::client::execute() { _impl->execute(); } ///////// now: the private stuff vlpp::client::client_impl::client_impl(const std::string &servername, const std::string &token, uint16_t port): _socket(_io_service) { //first check the token: if (token.length() != TOKEN_SIZE) { throw std::invalid_argument("invalid token (wrong size)"); } tcp::resolver _resolver(_io_service); tcp::resolver::query q(servername, std::to_string(port)); auto endpoints = _resolver.resolve(q); boost::asio::connect(_socket, endpoints); if (!_socket.is_open()) { throw std::runtime_error("cannot open socket"); } authenticate(token); } void vlpp::client::client_impl::authenticate(const std::string &token) { assert(token.length() == TOKEN_SIZE); std::array<char,TOKEN_SIZE> auth_data; auth_data[0] = OP_AUTHENTICATE; for (size_t i = 0; i < TOKEN_SIZE; ++i) { auth_data[i+1] = (char)token[i]; } boost::system::error_code e; boost::asio::write(_socket, boost::asio::buffer(&(auth_data[0]), auth_data.size()) , e); if (e) { throw std::runtime_error("write failed"); } } void vlpp::client::client_impl::set_led(uint16_t led, rgba_color col) { cmd_buffer.push_back((char)OP_SET_LED); cmd_buffer.push_back((char)(led >> 8)); cmd_buffer.push_back((char)(led & 0xff)); cmd_buffer.push_back((char)col.r); cmd_buffer.push_back((char)col.g); cmd_buffer.push_back((char)col.b); cmd_buffer.push_back((char)col.alpha); } void vlpp::client::client_impl::execute() { cmd_buffer.push_back((char)OP_STROBE); boost::system::error_code e; boost::asio::write(_socket, boost::asio::buffer(&(cmd_buffer[0]), cmd_buffer.size()), e); if (e) { throw std::runtime_error("write failed"); } } <commit_msg>bugfix<commit_after>/* * This file is part of vaporpp. * * vaporpp is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * vaporpp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with vaporpp. If not, see <http://www.gnu.org/licenses/>. */ #include "client.hpp" #include <cassert> #include <boost/asio.hpp> #include <array> using boost::asio::io_service; using boost::asio::ip::tcp; //pimpl-class (private members of client): class vlpp::client::client_impl { public: client_impl(const std::string& servername, const std::string& token, uint16_t port); void authenticate(const std::string& token); void set_led(uint16_t led, rgba_color col); void execute(); io_service _io_service; tcp::socket _socket; std::vector<char> cmd_buffer; }; //opcodes: enum: uint8_t { OP_SET_LED = 0x01, OP_AUTHENTICATE = 0x02, OP_STROBE = 0xFF }; enum { TOKEN_SIZE = 16 }; /////////// vlpp::client::client(const std::string &server, const std::string &token, uint16_t port): _impl(new vlpp::client::client_impl(server, token, port)) { } vlpp::client::~client() { } void vlpp::client::set_led(uint16_t led_id, const rgba_color &col) { _impl->set_led(led_id, col); } void vlpp::client::set_leds(const std::vector<uint16_t> &led_ids, const rgba_color &col) { for (auto led: led_ids) { set_led(led, col); } } void vlpp::client::execute() { _impl->execute(); } ///////// now: the private stuff vlpp::client::client_impl::client_impl(const std::string &servername, const std::string &token, uint16_t port): _socket(_io_service) { //first check the token: if (token.length() != TOKEN_SIZE) { throw std::invalid_argument("invalid token (wrong size)"); } tcp::resolver _resolver(_io_service); tcp::resolver::query q(servername, std::to_string(port)); auto endpoints = _resolver.resolve(q); boost::asio::connect(_socket, endpoints); if (!_socket.is_open()) { throw std::runtime_error("cannot open socket"); } authenticate(token); } void vlpp::client::client_impl::authenticate(const std::string &token) { assert(token.length() == TOKEN_SIZE); std::array<char,TOKEN_SIZE> auth_data; auth_data[0] = OP_AUTHENTICATE; for (size_t i = 0; i < TOKEN_SIZE; ++i) { auth_data[i+1] = (char)token[i]; } boost::system::error_code e; boost::asio::write(_socket, boost::asio::buffer(&(auth_data[0]), auth_data.size()) , e); if (e) { throw std::runtime_error("write failed"); } } void vlpp::client::client_impl::set_led(uint16_t led, rgba_color col) { cmd_buffer.push_back((char)OP_SET_LED); cmd_buffer.push_back((char)(led >> 8)); cmd_buffer.push_back((char)(led & 0xff)); cmd_buffer.push_back((char)col.r); cmd_buffer.push_back((char)col.g); cmd_buffer.push_back((char)col.b); cmd_buffer.push_back((char)col.alpha); } void vlpp::client::client_impl::execute() { cmd_buffer.push_back((char)OP_STROBE); boost::system::error_code e; boost::asio::write(_socket, boost::asio::buffer(&(cmd_buffer[0]), cmd_buffer.size()), e); cmd_buffer.clear(); if (e) { throw std::runtime_error("write failed"); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <climits> struct Data { int x; //d::string word; double val; //Data() : x(0), word("Empty"), val(0.0) {} //Data(int x_, std::string word_, double val_) : x(x_), word(word_), val(val_) {} }; int main() { Data d, load; std::cout << "Please enter an integer." << std::endl; std::cin >> d.x; std::cin.clear(); std::cin.ignore(INT_MAX,'\n'); //std::cout << "Please enter a word of your choice." << std::endl; //std::getline(std::cin, d.word); std::cout << "Please enter a real number." << std::endl; std::cin >> d.val; std::ofstream out; out.open("Data.DAT", std::ofstream::binary); out.write(reinterpret_cast<char*>(&d), sizeof(Data)); out.close(); std::cout << "\nData saved!" << std::endl; std::ifstream in; in.open("Data.DAT", std::ifstream::binary); in.read(reinterpret_cast<char*>(&load), sizeof(Data)); in.close(); std::cout << "Data loaded!\n" << std::endl; std::cout << "The integer entered was " << load.x << "." << std::endl; //std::cout << "The string entered was " << load.word << "." << std::endl; std::cout << "The real no. entered was " << load.val << "." << std::endl; std::cout << "Check!" << std::endl; return 0; }<commit_msg>Update<commit_after>#include <iostream> #include <fstream> #include <string> #include <climits> struct Data { int x; //d::string word; // this code segfaults for string variables double val; //Data() : x(0), word("Empty"), val(0.0) {} //Data(int x_, std::string word_, double val_) : x(x_), word(word_), val(val_) {} }; int main() { Data d, load; std::cout << "Please enter an integer." << std::endl; std::cin >> d.x; std::cin.clear(); std::cin.ignore(INT_MAX,'\n'); //std::cout << "Please enter a word of your choice." << std::endl; //std::getline(std::cin, d.word); std::cout << "Please enter a real number." << std::endl; std::cin >> d.val; std::ofstream out; out.open("Data.DAT", std::ofstream::binary); out.write(reinterpret_cast<char*>(&d), sizeof(Data)); out.close(); std::cout << "\nData saved!" << std::endl; std::ifstream in; in.open("Data.DAT", std::ifstream::binary); in.read(reinterpret_cast<char*>(&load), sizeof(Data)); in.close(); std::cout << "Data loaded!\n" << std::endl; std::cout << "The integer entered was " << load.x << "." << std::endl; //std::cout << "The string entered was " << load.word << "." << std::endl; std::cout << "The real no. entered was " << load.val << "." << std::endl; std::cout << "Check!" << std::endl; return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/clipboard/clipboard.h" #include <gtk/gtk.h> #include <map> #include <set> #include <string> #include <utility> #include "base/file_path.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gtk_util.h" #include "base/utf_string_conversions.h" #include "gfx/size.h" namespace { const char kMimeBmp[] = "image/bmp"; const char kMimeHtml[] = "text/html"; const char kMimeText[] = "text/plain"; const char kMimeURI[] = "text/uri-list"; const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste"; std::string GdkAtomToString(const GdkAtom& atom) { gchar* name = gdk_atom_name(atom); std::string rv(name); g_free(name); return rv; } GdkAtom StringToGdkAtom(const std::string& str) { return gdk_atom_intern(str.c_str(), FALSE); } // GtkClipboardGetFunc callback. // GTK will call this when an application wants data we copied to the clipboard. void GetData(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer user_data) { Clipboard::TargetMap* data_map = reinterpret_cast<Clipboard::TargetMap*>(user_data); std::string target_string = GdkAtomToString(selection_data->target); Clipboard::TargetMap::iterator iter = data_map->find(target_string); if (iter == data_map->end()) return; if (target_string == kMimeBmp) { gtk_selection_data_set_pixbuf(selection_data, reinterpret_cast<GdkPixbuf*>(iter->second.first)); } else if (target_string == kMimeURI) { gchar* uri_list[2]; uri_list[0] = reinterpret_cast<gchar*>(iter->second.first); uri_list[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_list); } else { gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(iter->second.first), iter->second.second); } } // GtkClipboardClearFunc callback. // We are guaranteed this will be called exactly once for each call to // gtk_clipboard_set_with_data. void ClearData(GtkClipboard* clipboard, gpointer user_data) { Clipboard::TargetMap* map = reinterpret_cast<Clipboard::TargetMap*>(user_data); // The same data may be inserted under multiple keys, so use a set to // uniq them. std::set<char*> ptrs; for (Clipboard::TargetMap::iterator iter = map->begin(); iter != map->end(); ++iter) { if (iter->first == kMimeBmp) g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first)); else ptrs.insert(iter->second.first); } for (std::set<char*>::iterator iter = ptrs.begin(); iter != ptrs.end(); ++iter) { delete[] *iter; } delete map; } // Called on GdkPixbuf destruction; see WriteBitmap(). void GdkPixbufFree(guchar* pixels, gpointer data) { free(pixels); } } // namespace Clipboard::Clipboard() { clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY); } Clipboard::~Clipboard() { // TODO(estade): do we want to save clipboard data after we exit? // gtk_clipboard_set_can_store and gtk_clipboard_store work // but have strangely awful performance. } void Clipboard::WriteObjects(const ObjectMap& objects) { clipboard_data_ = new TargetMap(); for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { DispatchObject(static_cast<ObjectType>(iter->first), iter->second); } SetGtkClipboard(); } // When a URL is copied from a render view context menu (via "copy link // location", for example), we additionally stick it in the X clipboard. This // matches other linux browsers. void Clipboard::DidWriteURL(const std::string& utf8_text) { gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(), utf8_text.length()); } // Take ownership of the GTK clipboard and inform it of the targets we support. void Clipboard::SetGtkClipboard() { scoped_array<GtkTargetEntry> targets( new GtkTargetEntry[clipboard_data_->size()]); int i = 0; for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin(); iter != clipboard_data_->end(); ++iter, ++i) { targets[i].target = const_cast<char*>(iter->first.c_str()); targets[i].flags = 0; targets[i].info = 0; } gtk_clipboard_set_with_data(clipboard_, targets.get(), clipboard_data_->size(), GetData, ClearData, clipboard_data_); // clipboard_data_ now owned by the GtkClipboard. clipboard_data_ = NULL; } void Clipboard::WriteText(const char* text_data, size_t text_len) { char* data = new char[text_len + 1]; memcpy(data, text_data, text_len); data[text_len] = '\0'; InsertMapping(kMimeText, data, text_len); InsertMapping("TEXT", data, text_len); InsertMapping("STRING", data, text_len); InsertMapping("UTF8_STRING", data, text_len); InsertMapping("COMPOUND_TEXT", data, text_len); } void Clipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { // TODO(estade): We need to expand relative links with |url_data|. static const char* html_prefix = "<meta http-equiv=\"content-type\" " "content=\"text/html; charset=utf-8\">"; size_t html_prefix_len = strlen(html_prefix); size_t total_len = html_prefix_len + markup_len + 1; char* data = new char[total_len]; snprintf(data, total_len, "%s", html_prefix); memcpy(data + html_prefix_len, markup_data, markup_len); data[total_len - 1] = '\0'; InsertMapping(kMimeHtml, data, total_len); } // Write an extra flavor that signifies WebKit was the last to modify the // pasteboard. This flavor has no data. void Clipboard::WriteWebSmartPaste() { InsertMapping(kMimeWebkitSmartPaste, NULL, 0); } void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) { const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data); guchar* data = gtk_util::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data), size->width(), size->height(), 0); GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE, 8, size->width(), size->height(), size->width() * 4, GdkPixbufFree, NULL); // We store the GdkPixbuf*, and the size_t half of the pair is meaningless. // Note that this contrasts with the vast majority of entries in our target // map, which directly store the data and its length. InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0); } void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { // Write as a URI. char* data = new char[url_len + 1]; memcpy(data, url_data, url_len); data[url_len] = '\0'; InsertMapping(kMimeURI, data, url_len + 1); } void Clipboard::WriteData(const char* format_name, size_t format_len, const char* data_data, size_t data_len) { char* data = new char[data_len]; memcpy(data, data_data, data_len); std::string format(format_name, format_len); // We assume that certain mapping types are only written by trusted code. // Therefore we must upkeep their integrity. if (format == kMimeBmp || format == kMimeURI) return; InsertMapping(format.c_str(), data, data_len); } // We do not use gtk_clipboard_wait_is_target_available because of // a bug with the gtk clipboard. It caches the available targets // and does not always refresh the cache when it is appropriate. bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format, Clipboard::Buffer buffer) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return false; bool format_is_plain_text = GetPlainTextFormatType() == format; if (format_is_plain_text) { // This tries a number of common text targets. if (gtk_clipboard_wait_is_text_available(clipboard)) return true; } bool retval = false; GdkAtom* targets = NULL; GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, gdk_atom_intern("TARGETS", false)); if (!data) return false; int num = 0; gtk_selection_data_get_targets(data, &targets, &num); // Some programs post data to the clipboard without any targets. If this is // the case we attempt to make sense of the contents as text. This is pretty // unfortunate since it means we have to actually copy the data to see if it // is available, but at least this path shouldn't be hit for conforming // programs. if (num <= 0) { if (format_is_plain_text) { gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text) { g_free(text); retval = true; } } } GdkAtom format_atom = StringToGdkAtom(format); for (int i = 0; i < num; i++) { if (targets[i] == format_atom) { retval = true; break; } } g_free(targets); gtk_selection_data_free(data); return retval; } bool Clipboard::IsFormatAvailableByString(const std::string& format, Clipboard::Buffer buffer) const { return IsFormatAvailable(format, buffer); } void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; // TODO(estade): do we want to handle the possible error here? UTF8ToUTF16(text, strlen(text), result); g_free(text); } void Clipboard::ReadAsciiText(Clipboard::Buffer buffer, std::string* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; result->assign(text); g_free(text); } void Clipboard::ReadFile(FilePath* file) const { *file = FilePath(); } // TODO(estade): handle different charsets. // TODO(port): set *src_url. void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup, std::string* src_url) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; markup->clear(); GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, StringToGdkAtom(GetHtmlFormatType())); if (!data) return; // If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is // UTF-16, otherwise assume UTF-8. if (data->length >= 2 && reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) { markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1, (data->length / 2) - 1); } else { UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup); } gtk_selection_data_free(data); } void Clipboard::ReadBookmark(string16* title, std::string* url) const { // TODO(estade): implement this. NOTIMPLEMENTED(); } void Clipboard::ReadData(const std::string& format, std::string* result) { GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format)); if (!data) return; result->assign(reinterpret_cast<char*>(data->data), data->length); gtk_selection_data_free(data); } // static Clipboard::FormatType Clipboard::GetPlainTextFormatType() { return GdkAtomToString(GDK_TARGET_STRING); } // static Clipboard::FormatType Clipboard::GetPlainTextWFormatType() { return GetPlainTextFormatType(); } // static Clipboard::FormatType Clipboard::GetHtmlFormatType() { return std::string(kMimeHtml); } // static Clipboard::FormatType Clipboard::GetBitmapFormatType() { return std::string(kMimeBmp); } // static Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() { return std::string(kMimeWebkitSmartPaste); } void Clipboard::InsertMapping(const char* key, char* data, size_t data_len) { DCHECK(clipboard_data_->find(key) == clipboard_data_->end()); (*clipboard_data_)[key] = std::make_pair(data, data_len); } GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const { switch (clipboard) { case BUFFER_STANDARD: return clipboard_; case BUFFER_SELECTION: return primary_selection_; default: NOTREACHED(); return NULL; } } <commit_msg>GTK - don't paste a garbage text/html character.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/clipboard/clipboard.h" #include <gtk/gtk.h> #include <map> #include <set> #include <string> #include <utility> #include "base/file_path.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gtk_util.h" #include "base/utf_string_conversions.h" #include "gfx/size.h" namespace { const char kMimeBmp[] = "image/bmp"; const char kMimeHtml[] = "text/html"; const char kMimeText[] = "text/plain"; const char kMimeURI[] = "text/uri-list"; const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste"; std::string GdkAtomToString(const GdkAtom& atom) { gchar* name = gdk_atom_name(atom); std::string rv(name); g_free(name); return rv; } GdkAtom StringToGdkAtom(const std::string& str) { return gdk_atom_intern(str.c_str(), FALSE); } // GtkClipboardGetFunc callback. // GTK will call this when an application wants data we copied to the clipboard. void GetData(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer user_data) { Clipboard::TargetMap* data_map = reinterpret_cast<Clipboard::TargetMap*>(user_data); std::string target_string = GdkAtomToString(selection_data->target); Clipboard::TargetMap::iterator iter = data_map->find(target_string); if (iter == data_map->end()) return; if (target_string == kMimeBmp) { gtk_selection_data_set_pixbuf(selection_data, reinterpret_cast<GdkPixbuf*>(iter->second.first)); } else if (target_string == kMimeURI) { gchar* uri_list[2]; uri_list[0] = reinterpret_cast<gchar*>(iter->second.first); uri_list[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_list); } else { gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(iter->second.first), iter->second.second); } } // GtkClipboardClearFunc callback. // We are guaranteed this will be called exactly once for each call to // gtk_clipboard_set_with_data. void ClearData(GtkClipboard* clipboard, gpointer user_data) { Clipboard::TargetMap* map = reinterpret_cast<Clipboard::TargetMap*>(user_data); // The same data may be inserted under multiple keys, so use a set to // uniq them. std::set<char*> ptrs; for (Clipboard::TargetMap::iterator iter = map->begin(); iter != map->end(); ++iter) { if (iter->first == kMimeBmp) g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first)); else ptrs.insert(iter->second.first); } for (std::set<char*>::iterator iter = ptrs.begin(); iter != ptrs.end(); ++iter) { delete[] *iter; } delete map; } // Called on GdkPixbuf destruction; see WriteBitmap(). void GdkPixbufFree(guchar* pixels, gpointer data) { free(pixels); } } // namespace Clipboard::Clipboard() { clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY); } Clipboard::~Clipboard() { // TODO(estade): do we want to save clipboard data after we exit? // gtk_clipboard_set_can_store and gtk_clipboard_store work // but have strangely awful performance. } void Clipboard::WriteObjects(const ObjectMap& objects) { clipboard_data_ = new TargetMap(); for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { DispatchObject(static_cast<ObjectType>(iter->first), iter->second); } SetGtkClipboard(); } // When a URL is copied from a render view context menu (via "copy link // location", for example), we additionally stick it in the X clipboard. This // matches other linux browsers. void Clipboard::DidWriteURL(const std::string& utf8_text) { gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(), utf8_text.length()); } // Take ownership of the GTK clipboard and inform it of the targets we support. void Clipboard::SetGtkClipboard() { scoped_array<GtkTargetEntry> targets( new GtkTargetEntry[clipboard_data_->size()]); int i = 0; for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin(); iter != clipboard_data_->end(); ++iter, ++i) { targets[i].target = const_cast<char*>(iter->first.c_str()); targets[i].flags = 0; targets[i].info = 0; } gtk_clipboard_set_with_data(clipboard_, targets.get(), clipboard_data_->size(), GetData, ClearData, clipboard_data_); // clipboard_data_ now owned by the GtkClipboard. clipboard_data_ = NULL; } void Clipboard::WriteText(const char* text_data, size_t text_len) { char* data = new char[text_len]; memcpy(data, text_data, text_len); InsertMapping(kMimeText, data, text_len); InsertMapping("TEXT", data, text_len); InsertMapping("STRING", data, text_len); InsertMapping("UTF8_STRING", data, text_len); InsertMapping("COMPOUND_TEXT", data, text_len); } void Clipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { // TODO(estade): We need to expand relative links with |url_data|. static const char* html_prefix = "<meta http-equiv=\"content-type\" " "content=\"text/html; charset=utf-8\">"; size_t html_prefix_len = strlen(html_prefix); size_t total_len = html_prefix_len + markup_len + 1; char* data = new char[total_len]; snprintf(data, total_len, "%s", html_prefix); memcpy(data + html_prefix_len, markup_data, markup_len); // Some programs expect NULL-terminated data. See http://crbug.com/42624 data[total_len - 1] = '\0'; InsertMapping(kMimeHtml, data, total_len); } // Write an extra flavor that signifies WebKit was the last to modify the // pasteboard. This flavor has no data. void Clipboard::WriteWebSmartPaste() { InsertMapping(kMimeWebkitSmartPaste, NULL, 0); } void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) { const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data); guchar* data = gtk_util::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data), size->width(), size->height(), 0); GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE, 8, size->width(), size->height(), size->width() * 4, GdkPixbufFree, NULL); // We store the GdkPixbuf*, and the size_t half of the pair is meaningless. // Note that this contrasts with the vast majority of entries in our target // map, which directly store the data and its length. InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0); } void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { // Write as a URI. char* data = new char[url_len + 1]; memcpy(data, url_data, url_len); data[url_len] = '\0'; InsertMapping(kMimeURI, data, url_len + 1); } void Clipboard::WriteData(const char* format_name, size_t format_len, const char* data_data, size_t data_len) { char* data = new char[data_len]; memcpy(data, data_data, data_len); std::string format(format_name, format_len); // We assume that certain mapping types are only written by trusted code. // Therefore we must upkeep their integrity. if (format == kMimeBmp || format == kMimeURI) return; InsertMapping(format.c_str(), data, data_len); } // We do not use gtk_clipboard_wait_is_target_available because of // a bug with the gtk clipboard. It caches the available targets // and does not always refresh the cache when it is appropriate. bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format, Clipboard::Buffer buffer) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return false; bool format_is_plain_text = GetPlainTextFormatType() == format; if (format_is_plain_text) { // This tries a number of common text targets. if (gtk_clipboard_wait_is_text_available(clipboard)) return true; } bool retval = false; GdkAtom* targets = NULL; GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, gdk_atom_intern("TARGETS", false)); if (!data) return false; int num = 0; gtk_selection_data_get_targets(data, &targets, &num); // Some programs post data to the clipboard without any targets. If this is // the case we attempt to make sense of the contents as text. This is pretty // unfortunate since it means we have to actually copy the data to see if it // is available, but at least this path shouldn't be hit for conforming // programs. if (num <= 0) { if (format_is_plain_text) { gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text) { g_free(text); retval = true; } } } GdkAtom format_atom = StringToGdkAtom(format); for (int i = 0; i < num; i++) { if (targets[i] == format_atom) { retval = true; break; } } g_free(targets); gtk_selection_data_free(data); return retval; } bool Clipboard::IsFormatAvailableByString(const std::string& format, Clipboard::Buffer buffer) const { return IsFormatAvailable(format, buffer); } void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; // TODO(estade): do we want to handle the possible error here? UTF8ToUTF16(text, strlen(text), result); g_free(text); } void Clipboard::ReadAsciiText(Clipboard::Buffer buffer, std::string* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; result->assign(text); g_free(text); } void Clipboard::ReadFile(FilePath* file) const { *file = FilePath(); } // TODO(estade): handle different charsets. // TODO(port): set *src_url. void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup, std::string* src_url) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; markup->clear(); GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, StringToGdkAtom(GetHtmlFormatType())); if (!data) return; // If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is // UTF-16, otherwise assume UTF-8. if (data->length >= 2 && reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) { markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1, (data->length / 2) - 1); } else { UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup); } // If there is a terminating NULL, drop it. if (markup->at(markup->length() - 1) == '\0') markup->resize(markup->length() - 1); gtk_selection_data_free(data); } void Clipboard::ReadBookmark(string16* title, std::string* url) const { // TODO(estade): implement this. NOTIMPLEMENTED(); } void Clipboard::ReadData(const std::string& format, std::string* result) { GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format)); if (!data) return; result->assign(reinterpret_cast<char*>(data->data), data->length); gtk_selection_data_free(data); } // static Clipboard::FormatType Clipboard::GetPlainTextFormatType() { return GdkAtomToString(GDK_TARGET_STRING); } // static Clipboard::FormatType Clipboard::GetPlainTextWFormatType() { return GetPlainTextFormatType(); } // static Clipboard::FormatType Clipboard::GetHtmlFormatType() { return std::string(kMimeHtml); } // static Clipboard::FormatType Clipboard::GetBitmapFormatType() { return std::string(kMimeBmp); } // static Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() { return std::string(kMimeWebkitSmartPaste); } void Clipboard::InsertMapping(const char* key, char* data, size_t data_len) { DCHECK(clipboard_data_->find(key) == clipboard_data_->end()); (*clipboard_data_)[key] = std::make_pair(data, data_len); } GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const { switch (clipboard) { case BUFFER_STANDARD: return clipboard_; case BUFFER_SELECTION: return primary_selection_; default: NOTREACHED(); return NULL; } } <|endoftext|>
<commit_before>/** * TLS library. TLS wraps a (connected) socket. */ #include <v8.h> #include "macros.h" #include "common.h" #include <string> #include <openssl/ssl.h> #include <openssl/err.h> #define NOT_SOCKET JS_TYPE_ERROR("Invalid call format. Use 'new TLS(socket)'") #define LOAD_SOCKET LOAD_VALUE(0)->ToObject()->GetInternalField(0)->Int32Value() #define LOAD_SSL LOAD_PTR(1, SSL *) #define SSL_ERROR(ssl, ret) JS_ERROR(formatError(ssl, ret).c_str()) namespace { SSL_CTX * ctx; std::string formatError(SSL * ssl, int ret) { char string[120]; ERR_error_string_n(SSL_get_error(ssl, ret), string, sizeof(string)); return std::string(string); } void finalize(v8::Handle<v8::Object> obj) { obj->SetInternalField(0, v8::Handle<v8::Value>()); SSL * ssl = reinterpret_cast<SSL *>(obj->GetPointerFromInternalField(1)); SSL_free(ssl); } /** * TLS constructor * @param {Socket} socket */ JS_METHOD(_tls) { ASSERT_CONSTRUCTOR; if (args.Length() < 1 || !args[0]->IsObject()) { return NOT_SOCKET; } v8::Handle<v8::Value> socket = args[0]; try { v8::Handle<v8::Value> socketproto = socket->ToObject()->GetPrototype(); v8::Handle<v8::Object> socketmodule = APP_PTR->require("socket", ""); v8::Handle<v8::Value> prototype = socketmodule->Get(JS_STR("Socket"))->ToObject()->Get(JS_STR("prototype")); if (!prototype->Equals(socketproto)) { return NOT_SOCKET; } } catch (std::string e) { /* for some reasons, the socket module is not available */ return JS_ERROR("Socket module not available"); } SAVE_VALUE(0, socket); SSL * ssl = SSL_new(ctx); SSL_set_fd(ssl, LOAD_SOCKET); SAVE_PTR(1, ssl); GC * gc = GC_PTR; gc->add(args.This(), finalize); return args.This(); } JS_METHOD(_getSocket) { return LOAD_VALUE(0); } JS_METHOD(_verifyCertificate) { return JS_INT(SSL_get_verify_result(LOAD_SSL)); } JS_METHOD(_accept) { SSL * ssl = LOAD_SSL; int result = SSL_accept(ssl); if (result == 1) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_connect) { SSL * ssl = LOAD_SSL; int result = SSL_connect(ssl); if (result == 1) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_receive) { SSL * ssl = LOAD_SSL; int count = args[0]->Int32Value(); char * data = new char[count]; ssize_t result = SSL_read(ssl, data, count); if (result >= 0) { if (result == 0) { int ret = SSL_get_error(ssl, result); if (ret != SSL_ERROR_ZERO_RETURN) { delete[] data; return SSL_ERROR(ssl, result); } } v8::Handle<v8::Value> buffer = JS_BUFFER(data, result); delete[] data; return buffer; } else { delete[] data; return SSL_ERROR(ssl, result); } } JS_METHOD(_send) { if (args.Length() < 1) { return JS_TYPE_ERROR("Bad argument count. Use 'tls.send(data)'"); } SSL * ssl = LOAD_SSL; ssize_t result; if (IS_BUFFER(args[0])) { size_t size = 0; char * data = JS_BUFFER_TO_CHAR(args[0], &size); result = SSL_write(ssl, data, size); } else { v8::String::Utf8Value data(args[0]); result = SSL_write(ssl, *data, data.length()); } if (result > 0) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_close) { SSL * ssl = LOAD_SSL; int result = SSL_shutdown(ssl); if (result == 0) { return _close(args); } if (result > 0) { return args.This(); } else { return SSL_ERROR(ssl, result); } } } SHARED_INIT() { SSL_library_init(); SSL_load_error_strings(); ctx = SSL_CTX_new(TLSv1_method()); v8::HandleScope handle_scope; v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_tls); ft->SetClassName(JS_STR("TLS")); v8::Handle<v8::ObjectTemplate> it = ft->InstanceTemplate(); it->SetInternalFieldCount(2); /* socket, ssl */ v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate(); /** * Prototype methods (new TLS().*) */ pt->Set("getSocket", v8::FunctionTemplate::New(_getSocket)); pt->Set("verifyCertificate", v8::FunctionTemplate::New(_verifyCertificate)); pt->Set("accept", v8::FunctionTemplate::New(_accept)); pt->Set("connect", v8::FunctionTemplate::New(_connect)); pt->Set("receive", v8::FunctionTemplate::New(_receive)); pt->Set("send", v8::FunctionTemplate::New(_send)); pt->Set("close", v8::FunctionTemplate::New(_close)); exports->Set(JS_STR("TLS"), ft->GetFunction()); } <commit_msg>tls leak fix<commit_after>/** * TLS library. TLS wraps a (connected) socket. */ #include <v8.h> #include "macros.h" #include "common.h" #include <string> #include <openssl/ssl.h> #include <openssl/err.h> #define NOT_SOCKET JS_TYPE_ERROR("Invalid call format. Use 'new TLS(socket)'") #define LOAD_SOCKET LOAD_VALUE(0)->ToObject()->GetInternalField(0)->Int32Value() #define LOAD_SSL LOAD_PTR(1, SSL *) #define SSL_ERROR(ssl, ret) JS_ERROR(formatError(ssl, ret).c_str()) namespace { SSL_CTX * ctx; std::string formatError(SSL * ssl, int ret) { char string[120]; ERR_error_string_n(SSL_get_error(ssl, ret), string, sizeof(string)); return std::string(string); } void finalize(v8::Handle<v8::Object> obj) { SSL * ssl = reinterpret_cast<SSL *>(obj->GetPointerFromInternalField(1)); SSL_free(ssl); } /** * TLS constructor * @param {Socket} socket */ JS_METHOD(_tls) { ASSERT_CONSTRUCTOR; if (args.Length() < 1 || !args[0]->IsObject()) { return NOT_SOCKET; } v8::Handle<v8::Value> socket = args[0]; try { v8::Handle<v8::Value> socketproto = socket->ToObject()->GetPrototype(); v8::Handle<v8::Object> socketmodule = APP_PTR->require("socket", ""); v8::Handle<v8::Value> prototype = socketmodule->Get(JS_STR("Socket"))->ToObject()->Get(JS_STR("prototype")); if (!prototype->Equals(socketproto)) { return NOT_SOCKET; } } catch (std::string e) { /* for some reasons, the socket module is not available */ return JS_ERROR("Socket module not available"); } SAVE_VALUE(0, socket); SSL * ssl = SSL_new(ctx); SSL_set_fd(ssl, LOAD_SOCKET); SAVE_PTR(1, ssl); GC * gc = GC_PTR; gc->add(args.This(), finalize); return args.This(); } JS_METHOD(_getSocket) { return LOAD_VALUE(0); } JS_METHOD(_verifyCertificate) { return JS_INT(SSL_get_verify_result(LOAD_SSL)); } JS_METHOD(_accept) { SSL * ssl = LOAD_SSL; int result = SSL_accept(ssl); if (result == 1) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_connect) { SSL * ssl = LOAD_SSL; int result = SSL_connect(ssl); if (result == 1) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_receive) { SSL * ssl = LOAD_SSL; int count = args[0]->Int32Value(); char * data = new char[count]; ssize_t result = SSL_read(ssl, data, count); if (result >= 0) { if (result == 0) { int ret = SSL_get_error(ssl, result); if (ret != SSL_ERROR_ZERO_RETURN) { delete[] data; return SSL_ERROR(ssl, result); } } v8::Handle<v8::Value> buffer = JS_BUFFER(data, result); delete[] data; return buffer; } else { delete[] data; return SSL_ERROR(ssl, result); } } JS_METHOD(_send) { if (args.Length() < 1) { return JS_TYPE_ERROR("Bad argument count. Use 'tls.send(data)'"); } SSL * ssl = LOAD_SSL; ssize_t result; if (IS_BUFFER(args[0])) { size_t size = 0; char * data = JS_BUFFER_TO_CHAR(args[0], &size); result = SSL_write(ssl, data, size); } else { v8::String::Utf8Value data(args[0]); result = SSL_write(ssl, *data, data.length()); } if (result > 0) { return args.This(); } else { return SSL_ERROR(ssl, result); } } JS_METHOD(_close) { SSL * ssl = LOAD_SSL; int result = SSL_shutdown(ssl); if (result == 0) { return _close(args); } if (result > 0) { return args.This(); } else { return SSL_ERROR(ssl, result); } } } SHARED_INIT() { SSL_library_init(); SSL_load_error_strings(); ctx = SSL_CTX_new(TLSv1_method()); v8::HandleScope handle_scope; v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_tls); ft->SetClassName(JS_STR("TLS")); v8::Handle<v8::ObjectTemplate> it = ft->InstanceTemplate(); it->SetInternalFieldCount(2); /* socket, ssl */ v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate(); /** * Prototype methods (new TLS().*) */ pt->Set("getSocket", v8::FunctionTemplate::New(_getSocket)); pt->Set("verifyCertificate", v8::FunctionTemplate::New(_verifyCertificate)); pt->Set("accept", v8::FunctionTemplate::New(_accept)); pt->Set("connect", v8::FunctionTemplate::New(_connect)); pt->Set("receive", v8::FunctionTemplate::New(_receive)); pt->Set("send", v8::FunctionTemplate::New(_send)); pt->Set("close", v8::FunctionTemplate::New(_close)); exports->Set(JS_STR("TLS"), ft->GetFunction()); } <|endoftext|>
<commit_before>8e43e38c-2e4e-11e5-9284-b827eb9e62be<commit_msg>8e49411a-2e4e-11e5-9284-b827eb9e62be<commit_after>8e49411a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>413875b8-2e4d-11e5-9284-b827eb9e62be<commit_msg>413d78c4-2e4d-11e5-9284-b827eb9e62be<commit_after>413d78c4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ee053bc8-2e4d-11e5-9284-b827eb9e62be<commit_msg>ee0a8556-2e4d-11e5-9284-b827eb9e62be<commit_after>ee0a8556-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>39bb0738-2e4d-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before>2e45ae16-2e4e-11e5-9284-b827eb9e62be<commit_msg>2e4abe4c-2e4e-11e5-9284-b827eb9e62be<commit_after>2e4abe4c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>1ee08612-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before>10fa99a2-2e4e-11e5-9284-b827eb9e62be<commit_msg>10ff901a-2e4e-11e5-9284-b827eb9e62be<commit_after>10ff901a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>94d0b860-2e4e-11e5-9284-b827eb9e62be<commit_msg>94d5b0a4-2e4e-11e5-9284-b827eb9e62be<commit_after>94d5b0a4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f8848780-2e4c-11e5-9284-b827eb9e62be<commit_msg>f88996e4-2e4c-11e5-9284-b827eb9e62be<commit_after>f88996e4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>68699f6c-2e4e-11e5-9284-b827eb9e62be<commit_msg>686e9332-2e4e-11e5-9284-b827eb9e62be<commit_after>686e9332-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e89a1b3a-2e4e-11e5-9284-b827eb9e62be<commit_msg>e89f5eba-2e4e-11e5-9284-b827eb9e62be<commit_after>e89f5eba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1ee15e08-2e4d-11e5-9284-b827eb9e62be<commit_msg>1ee65570-2e4d-11e5-9284-b827eb9e62be<commit_after>1ee65570-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>036b7ac2-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before><commit_msg>9a68cb1e-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before>acd12d1e-2e4e-11e5-9284-b827eb9e62be<commit_msg>acd6283c-2e4e-11e5-9284-b827eb9e62be<commit_after>acd6283c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8b92fbd8-2e4d-11e5-9284-b827eb9e62be<commit_msg>8b97f7aa-2e4d-11e5-9284-b827eb9e62be<commit_after>8b97f7aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be85ad42-2e4d-11e5-9284-b827eb9e62be<commit_msg>be8abc2e-2e4d-11e5-9284-b827eb9e62be<commit_after>be8abc2e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eea27f60-2e4c-11e5-9284-b827eb9e62be<commit_msg>eeac2b78-2e4c-11e5-9284-b827eb9e62be<commit_after>eeac2b78-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e66a07bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>e66f330e-2e4e-11e5-9284-b827eb9e62be<commit_after>e66f330e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>17d3fade-2e4e-11e5-9284-b827eb9e62be<commit_msg>17d8eb48-2e4e-11e5-9284-b827eb9e62be<commit_after>17d8eb48-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>031b6042-2e4d-11e5-9284-b827eb9e62be<commit_msg>033047f0-2e4d-11e5-9284-b827eb9e62be<commit_after>033047f0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>20c6e01c-2e4d-11e5-9284-b827eb9e62be<commit_msg>20cbecf6-2e4d-11e5-9284-b827eb9e62be<commit_after>20cbecf6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e0617e6e-2e4d-11e5-9284-b827eb9e62be<commit_msg>e0668ec2-2e4d-11e5-9284-b827eb9e62be<commit_after>e0668ec2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>201a282a-2e4f-11e5-9284-b827eb9e62be<commit_msg>201f25fa-2e4f-11e5-9284-b827eb9e62be<commit_after>201f25fa-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f18b1ae2-2e4d-11e5-9284-b827eb9e62be<commit_msg>f190294c-2e4d-11e5-9284-b827eb9e62be<commit_after>f190294c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>69c5ccf0-2e4e-11e5-9284-b827eb9e62be<commit_msg>69cabfda-2e4e-11e5-9284-b827eb9e62be<commit_after>69cabfda-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1f2f8f42-2e4d-11e5-9284-b827eb9e62be<commit_msg>1f348b50-2e4d-11e5-9284-b827eb9e62be<commit_after>1f348b50-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>36b01a2e-2e4d-11e5-9284-b827eb9e62be<commit_msg>36b528a2-2e4d-11e5-9284-b827eb9e62be<commit_after>36b528a2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>88544eb2-2e4e-11e5-9284-b827eb9e62be<commit_msg>88595be6-2e4e-11e5-9284-b827eb9e62be<commit_after>88595be6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ba6ac670-2e4d-11e5-9284-b827eb9e62be<commit_msg>ba6fbf18-2e4d-11e5-9284-b827eb9e62be<commit_after>ba6fbf18-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>27b515ba-2e4d-11e5-9284-b827eb9e62be<commit_msg>27ba0b7e-2e4d-11e5-9284-b827eb9e62be<commit_after>27ba0b7e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>984d1e2a-2e4e-11e5-9284-b827eb9e62be<commit_msg>985256ba-2e4e-11e5-9284-b827eb9e62be<commit_after>985256ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1d87b2da-2e4f-11e5-9284-b827eb9e62be<commit_msg>1d8cb0b4-2e4f-11e5-9284-b827eb9e62be<commit_after>1d8cb0b4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fdc6835e-2e4e-11e5-9284-b827eb9e62be<commit_msg>fdcb9bb4-2e4e-11e5-9284-b827eb9e62be<commit_after>fdcb9bb4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fb820276-2e4e-11e5-9284-b827eb9e62be<commit_msg>fb8716bc-2e4e-11e5-9284-b827eb9e62be<commit_after>fb8716bc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ef3d3a08-2e4e-11e5-9284-b827eb9e62be<commit_msg>ef4232c4-2e4e-11e5-9284-b827eb9e62be<commit_after>ef4232c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c0c39354-2e4c-11e5-9284-b827eb9e62be<commit_msg>c0c8961a-2e4c-11e5-9284-b827eb9e62be<commit_after>c0c8961a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9b02c314-2e4d-11e5-9284-b827eb9e62be<commit_msg>9b080c7a-2e4d-11e5-9284-b827eb9e62be<commit_after>9b080c7a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0b921198-2e4e-11e5-9284-b827eb9e62be<commit_msg>0b970b12-2e4e-11e5-9284-b827eb9e62be<commit_after>0b970b12-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8fb37652-2e4d-11e5-9284-b827eb9e62be<commit_msg>8fb87ad0-2e4d-11e5-9284-b827eb9e62be<commit_after>8fb87ad0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>152ebe26-2e4f-11e5-9284-b827eb9e62be<commit_msg>1533ce70-2e4f-11e5-9284-b827eb9e62be<commit_after>1533ce70-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aed0c18e-2e4d-11e5-9284-b827eb9e62be<commit_msg>aed5b4f0-2e4d-11e5-9284-b827eb9e62be<commit_after>aed5b4f0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dc84b5d2-2e4c-11e5-9284-b827eb9e62be<commit_msg>dc89a9b6-2e4c-11e5-9284-b827eb9e62be<commit_after>dc89a9b6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5430801a-2e4e-11e5-9284-b827eb9e62be<commit_msg>5435946a-2e4e-11e5-9284-b827eb9e62be<commit_after>5435946a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>