<commit_before>#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;

  // TOOD(hamaji): Use signal instead of sigaction?
  if (google::glog_internal_namespace_::IsFailureSignalHandlerInstalled()) {
// Set the default signal handler for SIGABRT, to avoid invoking our
// own signal handler installed by InstallFailureSignalHandler().
#ifdef HAVE_SIGACTION
    struct sigaction sig_action;
    memset(&sig_action, 0, sizeof(sig_action));
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_handler = SIG_DFL;
    sigaction(SIGABRT, &sig_action, NULL);
#elif defined(OS_WINDOWS)
    signal(SIGABRT, SIG_DFL);
#endif  // HAVE_SIGACTION
  }

  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et
<commit_msg>Remove logic that isn't supported on Ubuntu/Debian<commit_after>#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;
  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// peer example program
//
// main.cpp
//
// Copyright (c) 2012-2014 Eric Lombrozo
//
// All Rights Reserved.

#include <CoinCore/CoinNodeData.h>
#include <CoinCore/MerkleTree.h>
#include <CoinCore/typedefs.h>

#include <CoinQ/CoinQ_peer_io.h>
#include <CoinQ/CoinQ_coinparams.h>

#include <stdutils/stringutils.h>

#include <signal.h>

bool g_bShutdown = false;

void finish(int sig)
{
    std::cout << "Stopping..." << std::endl;
    g_bShutdown = true;
}

using namespace CoinQ;
using namespace std;

void onOpen(Peer& peer)
{
    cout << "Peer " << peer.name() << " open." << endl;
}

void onClose(Peer& peer, int code, const std::string& message)
{
    cout << "Peer " << peer.name() << " closed with code " << code << ": " << message << "." << endl;

    g_bShutdown = true;
}

void onInv(Peer& peer, const Coin::Inventory& inv)
{
    cout << endl << "Received inventory from " << peer.name() << endl << inv.toIndentedString() << endl;

    Coin::GetDataMessage getData;

    for (auto& item: inv.getItems()) {
        if (item.getType() == MSG_BLOCK || item.getType() == MSG_FILTERED_BLOCK) {
            getData.addItem(MSG_BLOCK, item.getItemHash());
        }
        else if (item.getType() == MSG_TX) {
            getData.addItem(MSG_TX, item.getItemHash());
        }
    }

    if (getData.getCount() > 0) peer.send(getData);
}

void onHeaders(Peer& peer, const Coin::HeadersMessage& headers)
{
    cout << endl << "Received headers message from peer " << peer.name() << endl << headers.toIndentedString() << endl;
}

void onTx(Peer& peer, const Coin::Transaction& tx)
{
    cout << endl << "Received transaction " << tx.getHashLittleEndian().getHex() << " from peer " << peer.name() << endl;// << tx.toIndentedString() << endl;
}

void onBlock(Peer& peer, const Coin::CoinBlock& block)
{
    cout << endl << "Received block from peer " << peer.name() << endl << block.toRedactedIndentedString() << endl;
}

void onMerkleBlock(Peer& peer, const Coin::MerkleBlock& merkleBlock)
{
    cout << endl << "Received merkle block from peer " << peer.name() << endl << merkleBlock.toIndentedString() << endl;

    Coin::MerkleTree tree;
    for (auto& hash: merkleBlock.hashes) { tree.addHash(hash); }
    cout << "Merkle root: " << tree.getRootLittleEndian().getHex() << endl;
}

int main(int argc, char* argv[])
{
    try
    {
        NetworkSelector networkSelector;

        if (argc < 3)
        {
            cerr << "# Usage: " << argv[0] << " <network> <host> [port]" << endl
                 << "# Supported networks: " << stdutils::delimited_list(networkSelector.getNetworkNames(), ", ") << endl;
            return -1;
        }

        CoinParams coinParams = networkSelector.getCoinParams(argv[1]);
        string host = argv[2];
        string port = (argc > 3) ? argv[3] : coinParams.default_port();

        CoinQ::io_service_t io_service;
        CoinQ::io_service_t::work work(io_service);
        boost::thread thread(boost::bind(&CoinQ::io_service_t::run, &io_service));

        cout << endl << "Connecting to " << coinParams.network_name() << " peer" << endl
             << "-------------------------------------------" << endl
             << "  host:             " << host << endl
             << "  port:             " << port << endl
             << "  magic bytes:      " << hex << coinParams.magic_bytes() << endl
             << "  protocol version: " << dec << coinParams.protocol_version() << endl
             << endl;

        Peer peer(io_service);
        peer.set(host, port, coinParams.magic_bytes(), coinParams.protocol_version(), "peer v1.0", 0, true);

        peer.subscribeStart([&](Peer& peer) { cout << "Peer " << peer.name() << " started." << endl; });
        peer.subscribeStop([&](Peer& peer) { cout << "Peer " << peer.name() << " stopped." << endl; });
        peer.subscribeOpen(&onOpen);
        peer.subscribeClose(&onClose);

        peer.subscribeTimeout([&](Peer& peer) { cout << "Peer " << peer.name() << " timed out." << endl; });

        peer.subscribeInv(&onInv);
        peer.subscribeHeaders(&onHeaders);
        peer.subscribeTx(&onTx);
        peer.subscribeBlock(&onBlock);
        peer.subscribeMerkleBlock(&onMerkleBlock);

        signal(SIGINT, &finish);
        signal(SIGTERM, &finish);

        peer.start();
        while (!g_bShutdown) { usleep(200); }
        peer.stop();
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<commit_msg>Added onError handler to CoinQ peer example.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// peer example program
//
// main.cpp
//
// Copyright (c) 2012-2014 Eric Lombrozo
//
// All Rights Reserved.

#include <CoinCore/CoinNodeData.h>
#include <CoinCore/MerkleTree.h>
#include <CoinCore/typedefs.h>

#include <CoinQ/CoinQ_peer_io.h>
#include <CoinQ/CoinQ_coinparams.h>

#include <stdutils/stringutils.h>

#include <signal.h>

bool g_bShutdown = false;

void finish(int sig)
{
    std::cout << "Stopping..." << std::endl;
    g_bShutdown = true;
}

using namespace CoinQ;
using namespace std;

void onOpen(Peer& peer)
{
    cout << "Peer " << peer.name() << " open." << endl;
}

void onClose(Peer& peer, int code, const std::string& message)
{
    cout << "Peer " << peer.name() << " closed with code " << code << ": " << message << "." << endl;

    g_bShutdown = true;
}

void onError(Peer& peer, const std::string& message)
{
    cout << "Peer " << peer.name() << " error - " << message << "." << endl;

    g_bShutdown = true;
}

void onInv(Peer& peer, const Coin::Inventory& inv)
{
    cout << endl << "Received inventory from " << peer.name() << endl << inv.toIndentedString() << endl;

    Coin::GetDataMessage getData;

    for (auto& item: inv.getItems()) {
        if (item.getType() == MSG_BLOCK || item.getType() == MSG_FILTERED_BLOCK) {
            getData.addItem(MSG_BLOCK, item.getItemHash());
        }
        else if (item.getType() == MSG_TX) {
            getData.addItem(MSG_TX, item.getItemHash());
        }
    }

    if (getData.getCount() > 0) peer.send(getData);
}

void onHeaders(Peer& peer, const Coin::HeadersMessage& headers)
{
    cout << endl << "Received headers message from peer " << peer.name() << endl << headers.toIndentedString() << endl;
}

void onTx(Peer& peer, const Coin::Transaction& tx)
{
    cout << endl << "Received transaction " << tx.getHashLittleEndian().getHex() << " from peer " << peer.name() << endl;// << tx.toIndentedString() << endl;
}

void onBlock(Peer& peer, const Coin::CoinBlock& block)
{
    cout << endl << "Received block from peer " << peer.name() << endl << block.toRedactedIndentedString() << endl;
}

void onMerkleBlock(Peer& peer, const Coin::MerkleBlock& merkleBlock)
{
    cout << endl << "Received merkle block from peer " << peer.name() << endl << merkleBlock.toIndentedString() << endl;

    Coin::MerkleTree tree;
    for (auto& hash: merkleBlock.hashes) { tree.addHash(hash); }
    cout << "Merkle root: " << tree.getRootLittleEndian().getHex() << endl;
}

int main(int argc, char* argv[])
{
    try
    {
        NetworkSelector networkSelector;

        if (argc < 3)
        {
            cerr << "# Usage: " << argv[0] << " <network> <host> [port]" << endl
                 << "# Supported networks: " << stdutils::delimited_list(networkSelector.getNetworkNames(), ", ") << endl;
            return -1;
        }

        CoinParams coinParams = networkSelector.getCoinParams(argv[1]);
        string host = argv[2];
        string port = (argc > 3) ? argv[3] : coinParams.default_port();

        CoinQ::io_service_t io_service;
        CoinQ::io_service_t::work work(io_service);
        boost::thread thread(boost::bind(&CoinQ::io_service_t::run, &io_service));

        cout << endl << "Connecting to " << coinParams.network_name() << " peer" << endl
             << "-------------------------------------------" << endl
             << "  host:             " << host << endl
             << "  port:             " << port << endl
             << "  magic bytes:      " << hex << coinParams.magic_bytes() << endl
             << "  protocol version: " << dec << coinParams.protocol_version() << endl
             << endl;

        Peer peer(io_service);
        peer.set(host, port, coinParams.magic_bytes(), coinParams.protocol_version(), "peer v1.0", 0, true);

        peer.subscribeStart([&](Peer& peer) { cout << "Peer " << peer.name() << " started." << endl; });
        peer.subscribeStop([&](Peer& peer) { cout << "Peer " << peer.name() << " stopped." << endl; });
        peer.subscribeOpen(&onOpen);
        peer.subscribeClose(&onClose);
        peer.subscribeError(&onError);

        peer.subscribeTimeout([&](Peer& peer) { cout << "Peer " << peer.name() << " timed out." << endl; });

        peer.subscribeInv(&onInv);
        peer.subscribeHeaders(&onHeaders);
        peer.subscribeTx(&onTx);
        peer.subscribeBlock(&onBlock);
        peer.subscribeMerkleBlock(&onMerkleBlock);

        signal(SIGINT, &finish);
        signal(SIGTERM, &finish);

        peer.start();
        while (!g_bShutdown) { usleep(200); }
        peer.stop();
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <cmath>

using namespace std;

vector<string> solvePuzzle(string state);
vector<string> reconstructPath(map<string, string> cameFrom, string current);
vector<string> findNeighbors(string state);
float calcfScore(string state);
bool isSolved(string state, string finalState);

int main() {

    // For Testing Purposes, otherwise we don't need this function
    string state;
    getline(cin, state);

    vector<string> neighbors = findNeighbors(state);
    for (int index = 0; index < neighbors.size(); index++) cout << neighbors[index] << endl;

    vector<string> solution = solvePuzzle(state);
    cout << "Solution: *****" << endl;
    for (int index = 0; index < solution.size(); index++) cout << solution[index] << endl;

    return 0;
}

vector<string> solvePuzzle(string state) {

    vector<string> frontier;
    vector<string> visited;
    map<string, string> cameFrom;

    frontier.push_back(state);

    map<string, float> fScore;
    map<string, int> gScore;
    gScore[state] = 0;

    while (frontier.size() > 0) {

        int best_choice = 0;
        float minimum = 100;

        for (int index = 0; index < frontier.size(); index++) {
            if (fScore[frontier[index]] > minimum) best_choice = index;
        }

        string curr_state = frontier[best_choice];
        frontier.erase(frontier.begin() + best_choice);
        visited.push_back(curr_state);

        // DEBUGGING
        /*
        cout << endl << curr_state << endl;// << "Visited: ";
        //for (int index = 0; index < visited.size(); index++) cout << visited[index];
        cout << endl << "Frontier: ";
        for (int index = 0; index < frontier.size(); index++) cout << frontier[index];
        cout << endl;
        */

        string final = "12345678 ";

        if (curr_state == final) {
            vector<string> path = reconstructPath(cameFrom, curr_state);
            return path;
        }

        vector<string> neighbors = findNeighbors(curr_state);

        for (unsigned int index = 0; index < neighbors.size(); index++) {

            string neighbor = neighbors[index];
            //cout << neighbor;
            if (find(visited.begin(), visited.end(), neighbor) != visited.end()) {
                    //cout << " terminated in visited." << endl;
                    continue;
            }

            if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) {
                //cout << " " << "State not yet Visited. State inserted in Frontier." << endl;
                frontier.push_back(neighbor);

            } else if ((gScore[curr_state] + 1) >= gScore[neighbor]) {
                    //cout << " terminated due to idiotic reasons." << endl;
                    continue;
            }

            // This path is the best until now. Record it!
            cameFrom[neighbor] = curr_state;
            fScore[neighbor] = calcfScore(neighbor);
            gScore[neighbor] = gScore[curr_state] + 1;

        }

        // mapping >>>>>>>>>>>>>>>>>>>>>>>>>>>
        //for (std::map<string,float>::iterator it=fScore.begin(); it!=fScore.end(); ++it) {
        //    std::cout << it->first << " => " << it->second << '\n';}

    }

    return vector<string>();

}

vector<string> reconstructPath(map<string, string> cameFrom, string current) {

    vector<string> totalPath;
    totalPath.push_back(current);

    while (cameFrom.find(current) != cameFrom.end()) {

        current = cameFrom[current];
        totalPath.insert(totalPath.begin(), current);
    }

    return totalPath;

}

float calcfScore(string state) {

    float fScore = 0;
    string final = "12345678 ";

    for (int index = 1; index < 9; index++) {
        int loc = state.find(final[index - 1]);

        fScore += abs(loc - (index - 1));

    }

    return fScore;

}

vector<string> findNeighbors(string state) {

    vector<string> neighbors;
    int index = state.find(' ');

    if (index % 3 < 2) {
        string temp_state = state;
        temp_state[index] = state[index + 1];
        temp_state[index + 1] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index % 3 > 0) {
        string temp_state = state;
        temp_state[index] = state[index - 1];
        temp_state[index - 1] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index > 2) {
        string temp_state = state;
        temp_state[index] = state[index - 3];
        temp_state[index - 3] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index < 6) {
        string temp_state = state;
        temp_state[index] = state[index + 3];
        temp_state[index + 3] = ' ';
        neighbors.push_back(temp_state);
    }

    return neighbors;

}

bool isSolved(string state, string finalState) {

    if (state == finalState) return true;
    else return false;

}
<commit_msg>Updated algorithm.cpp<commit_after>#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <cmath>

using namespace std;

vector<string> solvePuzzle(string state);
vector<string> reconstructPath(map<string, string> cameFrom, string current);
vector<string> findNeighbors(string state);
float calcfScore(string state);
bool isSolved(string state, string finalState);

int main() {

    // For Testing Purposes, otherwise we don't need this function
    string state;
    getline(cin, state);

    vector<string> solution = solvePuzzle(state);
    cout << "Solution:" << endl;
    for (int index = 0; index < solution.size(); index++) cout << solution[index] << endl;

    return 0;
}

vector<string> solvePuzzle(string state) {

    vector<string> frontier;
    vector<string> visited;
    map<string, string> cameFrom;

    frontier.push_back(state);

    map<string, float> fScore;
    map<string, int> gScore;
    gScore[state] = 0;

    while (frontier.size() > 0) {

        int best_choice = 0;
        float minimum = 100;

        for (int index = 0; index < frontier.size(); index++) {
            if (fScore[frontier[index]] > minimum) best_choice = index;
        }

        string curr_state = frontier[best_choice];
        frontier.erase(frontier.begin() + best_choice);
        visited.push_back(curr_state);

        // DEBUGGING
        /*
        cout << endl << curr_state << endl;// << "Visited: ";
        //for (int index = 0; index < visited.size(); index++) cout << visited[index];
        cout << endl << "Frontier: ";
        for (int index = 0; index < frontier.size(); index++) cout << frontier[index];
        cout << endl;
        */

        string final = "12345678 ";

        if (curr_state == final) {
            vector<string> path = reconstructPath(cameFrom, curr_state);
            return path;
        }

        vector<string> neighbors = findNeighbors(curr_state);

        for (unsigned int index = 0; index < neighbors.size(); index++) {

            string neighbor = neighbors[index];
            //cout << neighbor;
            if (find(visited.begin(), visited.end(), neighbor) != visited.end()) {
                    //cout << " terminated in visited." << endl;
                    continue;
            }

            if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) {
                //cout << " " << "State not yet Visited. State inserted in Frontier." << endl;
                frontier.push_back(neighbor);

            } else if ((gScore[curr_state] + 1) >= gScore[neighbor]) {
                    //cout << " terminated due to idiotic reasons." << endl;
                    continue;
            }

            // This path is the best until now. Record it!
            cameFrom[neighbor] = curr_state;
            fScore[neighbor] = calcfScore(neighbor);
            gScore[neighbor] = gScore[curr_state] + 1;

        }

        // mapping >>>>>>>>>>>>>>>>>>>>>>>>>>>
        //for (std::map<string,float>::iterator it=fScore.begin(); it!=fScore.end(); ++it) {
        //    std::cout << it->first << " => " << it->second << '\n';}

    }

    return vector<string>();

}

vector<string> reconstructPath(map<string, string> cameFrom, string current) {

    vector<string> totalPath;
    totalPath.push_back(current);

    while (cameFrom.find(current) != cameFrom.end()) {

        current = cameFrom[current];
        totalPath.insert(totalPath.begin(), current);
    }

    return totalPath;

}

float calcfScore(string state) {

    float fScore = 0;
    string final = "12345678 ";

    for (int index = 1; index < 9; index++) {
        int loc = state.find(final[index - 1]);

        fScore += abs(loc - (index - 1));

    }

    return fScore;

}

vector<string> findNeighbors(string state) {

    vector<string> neighbors;
    int index = state.find(' ');

    if (index % 3 < 2) {
        string temp_state = state;
        temp_state[index] = state[index + 1];
        temp_state[index + 1] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index % 3 > 0) {
        string temp_state = state;
        temp_state[index] = state[index - 1];
        temp_state[index - 1] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index > 2) {
        string temp_state = state;
        temp_state[index] = state[index - 3];
        temp_state[index - 3] = ' ';
        neighbors.push_back(temp_state);
    }

    if (index < 6) {
        string temp_state = state;
        temp_state[index] = state[index + 3];
        temp_state[index + 3] = ' ';
        neighbors.push_back(temp_state);
    }

    return neighbors;

}

bool isSolved(string state, string finalState) {

    if (state == finalState) return true;
    else return false;

}
<|endoftext|>


<commit_before><commit_msg>Hanlde TopDown -> BottomUp conversion in basebmp DirectCopy logic<commit_after><|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commercial and non commercial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osgDB/ReadFile>

#include <osgGA/StateSetManipulator>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <iostream>

bool readShaderArguments(osg::ArgumentParser& arguments, const std::string& option, osg::Program* program, const std::string& fallbackShaderFilename)
{
    bool shaderAssigned = false;
    std::string shaderFilename;
    while(arguments.read(option, shaderFilename))
    {
        osg::ref_ptr<osg::Shader> shader = osgDB::readRefShaderFile(shaderFilename);
        if (shader)
        {
            shaderAssigned = true;
            program->addShader(shader);
        }
        else
        {
            OSG_NOTICE<<"Unable to load shader file : "<<shaderFilename<<std::endl;
        }
    }

    if (shaderAssigned) return true;

    osg::ref_ptr<osg::Shader> shader = osgDB::readRefShaderFile(fallbackShaderFilename);
    if (shader)
    {
        shaderAssigned = true;
        program->addShader(shader);
        return true;
    }
    else
    {
        OSG_NOTICE<<"Unable to load shader file : "<<fallbackShaderFilename<<std::endl;
        return false;
    }
}

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    osgViewer::Viewer viewer(arguments);

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    osg::ref_ptr<osg::Program> program = new osg::Program;

    if (!readShaderArguments(arguments, "--vert", program, "shaders/shaderpipeline.vert"))
    {
        return 1;
    }

    if (!readShaderArguments(arguments, "--frag", program, "shaders/shaderpipeline.frag"))
    {
        return 1;
    }

    // assign program to topmost StateSet
    viewer.getCamera()->getOrCreateStateSet()->setAttribute(program);

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    viewer.setSceneData(loadedModel);

    viewer.realize();

    return viewer.run();

}
<commit_msg>Added setup of uniform arrays for passing in texture modes<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commercial and non commercial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osg/TexGen>
#include <osgDB/ReadFile>

#include <osgGA/StateSetManipulator>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <iostream>

bool readShaderArguments(osg::ArgumentParser& arguments, const std::string& option, osg::Program* program, const std::string& fallbackShaderFilename)
{
    bool shaderAssigned = false;
    std::string shaderFilename;
    while(arguments.read(option, shaderFilename))
    {
        osg::ref_ptr<osg::Shader> shader = osgDB::readRefShaderFile(shaderFilename);
        if (shader)
        {
            shaderAssigned = true;
            program->addShader(shader);
        }
        else
        {
            OSG_NOTICE<<"Unable to load shader file : "<<shaderFilename<<std::endl;
        }
    }

    if (shaderAssigned) return true;

    osg::ref_ptr<osg::Shader> shader = osgDB::readRefShaderFile(fallbackShaderFilename);
    if (shader)
    {
        shaderAssigned = true;
        program->addShader(shader);
        return true;
    }
    else
    {
        OSG_NOTICE<<"Unable to load shader file : "<<fallbackShaderFilename<<std::endl;
        return false;
    }
}

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    osgViewer::Viewer viewer(arguments);

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    osg::ref_ptr<osg::Program> program = new osg::Program;

    if (!readShaderArguments(arguments, "--vert", program, "shaders/shaderpipeline.vert"))
    {
        return 1;
    }

    if (!readShaderArguments(arguments, "--frag", program, "shaders/shaderpipeline.frag"))
    {
        return 1;
    }

    // assign program to topmost StateSet
    viewer.getCamera()->getOrCreateStateSet()->setAttribute(program);

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    viewer.setSceneData(loadedModel);

    osg::ref_ptr<osg::StateSet> stateset = viewer.getCamera()->getOrCreateStateSet();

    unsigned int maxTextureUnits = 1;
    std::stringstream sstream;
    sstream<<maxTextureUnits;
    stateset->setDefine("GL_MAX_TEXTURE_UNITS", sstream.str());

    #define ADD_DEFINE(DEF) \
        sstream.str(""); \
        sstream<<DEF; \
        stateset->setDefine(#DEF, sstream.str());

    if (maxTextureUnits>0)
    {
        ADD_DEFINE(GL_EYE_LINEAR);
        ADD_DEFINE(GL_OBJECT_LINEAR);
        ADD_DEFINE(GL_SPHERE_MAP);
        ADD_DEFINE(GL_NORMAL_MAP);
        ADD_DEFINE(GL_REFLECTION_MAP);
        ADD_DEFINE(GL_MODULATE);
        ADD_DEFINE(GL_REPLACE);
        ADD_DEFINE(GL_DECAL);
        ADD_DEFINE(GL_BLEND);
        ADD_DEFINE(GL_ADD);

        osg::ref_ptr<osg::Uniform> ACTIVE_TEXTURE = new osg::Uniform(osg::Uniform::BOOL, "GL_ACTIVE_TEXTURE", maxTextureUnits);
        osg::ref_ptr<osg::Uniform> TEXTURE_GEN_S = new osg::Uniform(osg::Uniform::BOOL, "GL_TEXTURE_GEN_S", maxTextureUnits);
        osg::ref_ptr<osg::Uniform> TEXTURE_GEN_T = new osg::Uniform(osg::Uniform::BOOL, "GL_TEXTURE_GEN_T", maxTextureUnits);

        osg::ref_ptr<osg::Uniform> TEXTURE_GEN_MODE = new osg::Uniform(osg::Uniform::INT, "GL_TEXTURE_GEN_MODE", maxTextureUnits);
        osg::ref_ptr<osg::Uniform> TEXTURE_ENV_MODE = new osg::Uniform(osg::Uniform::INT, "GL_TEXTURE_ENV_MODE", maxTextureUnits);

        for(unsigned int i=0; i<maxTextureUnits;++i)
        {
            ACTIVE_TEXTURE->setElement(i, false);
            TEXTURE_GEN_MODE->setElement(i, 0);
            TEXTURE_GEN_S->setElement(i, false);
            TEXTURE_GEN_T->setElement(i, false);
        }

        ACTIVE_TEXTURE->setElement(0, true);
        //TEXTURE_GEN_MODE->setElement(0, 0);
        TEXTURE_GEN_MODE->setElement(0, GL_SPHERE_MAP);
        TEXTURE_GEN_S->setElement(0, true);
        TEXTURE_GEN_T->setElement(0, true);

        stateset->addUniform(ACTIVE_TEXTURE.get());
        stateset->addUniform(TEXTURE_GEN_S.get());
        stateset->addUniform(TEXTURE_GEN_T.get());
        stateset->addUniform(TEXTURE_GEN_MODE.get());
        stateset->addUniform(TEXTURE_ENV_MODE.get());
    }

    viewer.realize();

    return viewer.run();

}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------ -
//    @FileName			:    NFCRankModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-12-18
//    @Module           :    NFCRankModule
//
// -------------------------------------------------------------------------

#include "NFCRankModule.h"

bool NFCRankModule::Init()
{
    return true;
}

bool NFCRankModule::Shut()
{
    return true;
}

bool NFCRankModule::Execute()
{
    return true;
}

bool NFCRankModule::AfterInit()
{
    m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();

    return true;
}<commit_msg>fixed<commit_after>//------------------------------------------------------------------------ -
//    @FileName			:    NFCRankModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-12-18
//    @Module           :    NFCRankModule
//
// -------------------------------------------------------------------------

#include "NFCRankModule.h"

bool NFCRankModule::Init()
{
    return true;
}

bool NFCRankModule::Shut()
{
    return true;
}

bool NFCRankModule::Execute()
{
    return true;
}

bool NFCRankModule::AfterInit()
{

    return true;
}<|endoftext|>


<commit_before>/*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/

#include "stdafx.h"
#include "dNewtonBody.h"
#include "dNewtonWorld.h"
#include "dNewtonCollision.h"

dNewtonBody::ScopeLock::ScopeLock (unsigned int* const lock)
	:m_atomicLock(lock)
{
	const int maxCount = 1024 * 32;
	for (int i = 0; (i < maxCount) && NewtonAtomicSwap((int*)m_atomicLock, 1); i++) {
		NewtonYield();
	}
}

dNewtonBody::ScopeLock::~ScopeLock()
{
	NewtonAtomicSwap((int*)m_atomicLock, 0);
}

dNewtonBody::dNewtonBody(const dMatrix& matrix)
	:dAlloc()
	,m_body(NULL)
	,m_posit0(matrix.m_posit)
	,m_posit1(matrix.m_posit)
	,m_interpolatedPosit(matrix.m_posit)
	,m_rotation0(matrix)
	,m_rotation1(m_rotation0)
	,m_interpolatedRotation(m_rotation0)
	,m_lock(0)
{
}

dNewtonBody::~dNewtonBody()
{
	Destroy();
}

void* dNewtonBody::GetBody() const
{
	return m_body;
}

bool dNewtonBody::GetSleepState() const
{
	return NewtonBodyGetSleepState(m_body) ? true : false;
}

void dNewtonBody::SetSleepState(bool state) const
{
	NewtonBodySetSleepState(m_body, state ? 1 : 0);
}

void* dNewtonBody::GetInterpolatedPosition()
{
	const dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));
	ScopeLock scopelock(&m_lock);
	m_interpolatedPosit = m_posit0 + (m_posit1 - m_posit0).Scale(world->m_interpotationParam);
	return &m_interpolatedPosit.m_x;
}

void* dNewtonBody::GetInterpolatedRotation()
{
	const dNewtonWorld* const world = (dNewtonWorld*) NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));
	ScopeLock scopelock(&m_lock);
	m_interpolatedRotation = m_rotation0.Slerp(m_rotation1, world->m_interpotationParam);
	return &m_interpolatedRotation.m_x;
}

void* dNewtonBody::GetPosition()
{
	return &m_posit1.m_x;
}

void* dNewtonBody::GetRotation()
{
	return &m_rotation1.m_x;
}

void dNewtonBody::SetPosition(dFloat x, dFloat y, dFloat z)
{
	dQuaternion rot;
	NewtonBodyGetRotation(m_body, &rot.m_x);
	dMatrix mat(rot, dVector(x, y, z));
	NewtonBodySetMatrix(m_body, &mat[0][0]);
}

void dNewtonBody::SetRotation(dFloat x, dFloat y, dFloat z, dFloat w)
{
	dVector pos(0, 0, 0);
	NewtonBodyGetPosition(m_body, &pos.m_x);
	dMatrix mat(dQuaternion(w, x, y, z), pos);
	NewtonBodySetMatrix(m_body, &mat[0][0]);
}

void dNewtonBody::SetUserData(void* userData)
{
	m_userData = userData;
}

void* dNewtonBody::GetUserData()
{
	return m_userData;
}

void* dNewtonBody::GetVelocity()
{
	NewtonBodyGetVelocity(m_body, &m_velocity.m_x);
	return &m_velocity;
}

void* dNewtonBody::GetOmega()
{
	NewtonBodyGetOmega(m_body, &m_omega.m_x);
	return &m_omega;
}

void dNewtonBody::SetVelocity(dFloat x, dFloat y, dFloat z)
{
	dVector vel(x,y,z);
	NewtonBodySetVelocity(m_body, &vel.m_x);
}

void dNewtonBody::SetOmega(dFloat x, dFloat y, dFloat z)
{
	dVector omg(x, y, z);
	NewtonBodySetOmega(m_body, &omg.m_x);
}

float dNewtonBody::GetLinearDamping()
{
	return NewtonBodyGetLinearDamping(m_body);
}

void dNewtonBody::SetLinearDamping(dFloat x)
{
	NewtonBodySetLinearDamping(m_body, x);
}

void* dNewtonBody::GetAngularDamping()
{
	NewtonBodyGetAngularDamping(m_body, &m_angulardamping.m_x);
	return &m_angulardamping;
}

void dNewtonBody::SetAngularDamping(dFloat x, dFloat y, dFloat z)
{
	dVector damp(x, y, z);
	NewtonBodySetAngularDamping(m_body, &damp.m_x);
}

void* dNewtonBody::GetCenterOfMass()
{
	NewtonBodyGetCentreOfMass(m_body, &m_com.m_x);
	return &m_com;
}

void dNewtonBody::SetCenterOfMass(float com_x, float com_y, float com_z, float Ixx, float Iyy, float Izz, bool Calc_inertia)
{
	dVector com;
	dFloat tmp_Ixx;
	dFloat tmp_Iyy;
	dFloat tmp_Izz;
	dFloat mass;

	NewtonBodyGetMass(m_body, &mass, &tmp_Ixx, &tmp_Iyy, &tmp_Izz);
	NewtonCollision* const collision = NewtonBodyGetCollision(m_body);
	if (Calc_inertia) {
		NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));
		NewtonBodyGetCentreOfMass(m_body, &com[0]);
	}
	else {
		NewtonBodySetMassMatrix(m_body, mass, Ixx, Iyy, Izz);
		com.m_x = 0;
		com.m_y = 0;
		com.m_z = 0;
	}

	com.m_x += com_x;
	com.m_y += com_y;
	com.m_z += com_z;
	NewtonBodySetCentreOfMass(m_body, &com[0]);
}

void dNewtonBody::CalculateBuoyancyForces(const void* plane, void* force, void* torque, float bodyDensity)
{
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	dFloat mass;

	NewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);

	if (mass > 0.0f) {
		dMatrix matrix;
		dVector cog(0.0f);
		dVector accelPerUnitMass(0.0f);
		dVector torquePerUnitMass(0.0f);
		const dVector gravity(0.0f, -9.8f, 0.0f, 0.0f);

		NewtonBodyGetMatrix(m_body, &matrix[0][0]);
		NewtonBodyGetCentreOfMass(m_body, &cog[0]);
		cog = matrix.TransformVector(cog);
		NewtonCollision* const collision = NewtonBodyGetCollision(m_body);

		dFloat shapeVolume = NewtonConvexCollisionCalculateVolume(collision);
		dFloat fluidDensity = 1.0f / (bodyDensity * shapeVolume);
		dFloat viscosity = 0.995f;

		NewtonConvexCollisionCalculateBuoyancyAcceleration(collision, &matrix[0][0], &cog[0], &gravity[0], (float*)plane, fluidDensity, viscosity, &accelPerUnitMass[0], &torquePerUnitMass[0]);

		dVector finalForce(accelPerUnitMass.Scale(mass));
		dVector finalTorque(torquePerUnitMass.Scale(mass));

		dVector omega(0.0f);
		NewtonBodyGetOmega(m_body, &omega[0]);
		omega = omega.Scale(viscosity);
		NewtonBodySetOmega(m_body, &omega[0]);

		((float*)force)[0] = finalForce.m_x ;
		((float*)force)[1] = finalForce.m_y ;
		((float*)force)[2] = finalForce.m_z ;
		((float*)torque)[0] = finalTorque.m_x;
		((float*)torque)[1] = finalTorque.m_y;
		((float*)torque)[2] = finalTorque.m_z;
	}
}

void dNewtonBody::OnBodyTransform(const dFloat* const matrixPtr, int threadIndex)
{
	dMatrix matrix(matrixPtr);

	ScopeLock scopelock(&m_lock);
	m_posit0 = m_posit1;
	m_rotation0 = m_rotation1;
	m_posit1 = matrix.m_posit;
	m_rotation1 = dQuaternion(matrix);
	dFloat angle = m_rotation0.DotProduct(m_rotation1);
	if (angle < 0.0f) {
		m_rotation1.Scale(-1.0f);
	}
}

void dNewtonBody::OnForceAndTorque(dFloat timestep, int threadIndex)
{
}

void dNewtonBody::OnForceAndTorqueCallback (const NewtonBody* body, dFloat timestep, int threadIndex)
{
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	dAssert(me);
	me->OnForceAndTorque(timestep, threadIndex);
}

void dNewtonBody::OnBodyTransformCallback (const NewtonBody* const body, const dFloat* const matrix, int threadIndex)
{
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	dAssert(me);
	me->OnBodyTransform(matrix, threadIndex);
}

void dNewtonBody::Destroy()
{
	if (m_body) {
		NewtonWaitForUpdateToFinish(NewtonBodyGetWorld(m_body));
		NewtonBodySetDestructorCallback(m_body, NULL);
		NewtonDestroyBody(m_body);
		m_body = NULL;
	}
}

void dNewtonBody::OnBodyDestroy(const NewtonBody* const body)
{
	dAssert(0);
/*
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	if (me) {
		NewtonBodySetDestructorCallback(me->m_body, NULL);
		delete me;
	}
*/
}

void dNewtonBody::InitForceAccumulators()
{
}

void dNewtonBody::AddForce(dFloat x, dFloat y, dFloat z)
{
}

void dNewtonBody::AddTorque(dFloat x, dFloat y, dFloat z)
{
}

dNewtonKinematicBody::dNewtonKinematicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)
	:dNewtonBody(matrix)
{
	NewtonWorld* const newton = world->m_world;
	NewtonWaitForUpdateToFinish(newton);

	m_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);
	collision->DeleteShape();
	collision->SetShape(NewtonBodyGetCollision(m_body));

	NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));

	NewtonBodySetUserData(m_body, this);
	NewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);
	NewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);
}

dNewtonDynamicBody::dNewtonDynamicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)
	:dNewtonBody(matrix)
{
	NewtonWorld* const newton = world->m_world;

	NewtonWaitForUpdateToFinish(newton);
	m_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);
	//collision->DeleteShape();
	//collision->SetShape(NewtonBodyGetCollision(m_body));

	NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));

	NewtonBodySetUserData(m_body, this);
	NewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);
	NewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);
}

void dNewtonDynamicBody::InitForceAccumulators()
{
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;

	NewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);
	const dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));

	m_externalForce = world->GetGravity().Scale(mass);
	m_externalTorque = dVector(0.0f);
}

void dNewtonDynamicBody::OnForceAndTorque(dFloat timestep, int threadIndex)
{
	NewtonBodySetForce(m_body, &m_externalForce[0]);
	NewtonBodySetTorque(m_body, &m_externalTorque[0]);
}

void dNewtonDynamicBody::AddForce(dFloat x, dFloat y, dFloat z)
{
	m_externalForce += dVector (x, y, z);
}

void dNewtonDynamicBody::AddTorque(dFloat x, dFloat y, dFloat z)
{
	m_externalTorque += dVector(x, y, z);
}

<commit_msg>updated unity wrapper.<commit_after>/*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/

#include "stdafx.h"
#include "dNewtonBody.h"
#include "dNewtonWorld.h"
#include "dNewtonCollision.h"

dNewtonBody::ScopeLock::ScopeLock (unsigned int* const lock)
	:m_atomicLock(lock)
{
	const int maxCount = 1024 * 32;
	for (int i = 0; (i < maxCount) && NewtonAtomicSwap((int*)m_atomicLock, 1); i++) {
		NewtonYield();
	}
}

dNewtonBody::ScopeLock::~ScopeLock()
{
	NewtonAtomicSwap((int*)m_atomicLock, 0);
}

dNewtonBody::dNewtonBody(const dMatrix& matrix)
	:dAlloc()
	,m_body(NULL)
	,m_posit0(matrix.m_posit)
	,m_posit1(matrix.m_posit)
	,m_interpolatedPosit(matrix.m_posit)
	,m_rotation0(matrix)
	,m_rotation1(m_rotation0)
	,m_interpolatedRotation(m_rotation0)
	,m_lock(0)
{
}

dNewtonBody::~dNewtonBody()
{
	Destroy();
}

void* dNewtonBody::GetBody() const
{
	return m_body;
}

bool dNewtonBody::GetSleepState() const
{
	return NewtonBodyGetSleepState(m_body) ? true : false;
}

void dNewtonBody::SetSleepState(bool state) const
{
	NewtonBodySetSleepState(m_body, state ? 1 : 0);
}

void* dNewtonBody::GetInterpolatedPosition()
{
	const dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));
	ScopeLock scopelock(&m_lock);
	m_interpolatedPosit = m_posit0 + (m_posit1 - m_posit0).Scale(world->m_interpotationParam);
	return &m_interpolatedPosit.m_x;
}

void* dNewtonBody::GetInterpolatedRotation()
{
	const dNewtonWorld* const world = (dNewtonWorld*) NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));
	ScopeLock scopelock(&m_lock);
	m_interpolatedRotation = m_rotation0.Slerp(m_rotation1, world->m_interpotationParam);
	return &m_interpolatedRotation.m_x;
}

void* dNewtonBody::GetPosition()
{
	return &m_posit1.m_x;
}

void* dNewtonBody::GetRotation()
{
	return &m_rotation1.m_x;
}

void dNewtonBody::SetPosition(dFloat x, dFloat y, dFloat z)
{
	dQuaternion rot;
	NewtonBodyGetRotation(m_body, &rot.m_x);
	dMatrix mat(rot, dVector(x, y, z));
	NewtonBodySetMatrix(m_body, &mat[0][0]);
}

void dNewtonBody::SetRotation(dFloat x, dFloat y, dFloat z, dFloat w)
{
	dVector pos(0, 0, 0);
	NewtonBodyGetPosition(m_body, &pos.m_x);
	dMatrix mat(dQuaternion(w, x, y, z), pos);
	NewtonBodySetMatrix(m_body, &mat[0][0]);
}

void dNewtonBody::SetUserData(void* userData)
{
	m_userData = userData;
}

void* dNewtonBody::GetUserData()
{
	return m_userData;
}

void* dNewtonBody::GetVelocity()
{
	NewtonBodyGetVelocity(m_body, &m_velocity.m_x);
	return &m_velocity;
}

void* dNewtonBody::GetOmega()
{
	NewtonBodyGetOmega(m_body, &m_omega.m_x);
	return &m_omega;
}

void dNewtonBody::SetVelocity(dFloat x, dFloat y, dFloat z)
{
	dVector vel(x,y,z);
	NewtonBodySetVelocity(m_body, &vel.m_x);
}

void dNewtonBody::SetOmega(dFloat x, dFloat y, dFloat z)
{
	dVector omg(x, y, z);
	NewtonBodySetOmega(m_body, &omg.m_x);
}

float dNewtonBody::GetLinearDamping()
{
	return NewtonBodyGetLinearDamping(m_body);
}

void dNewtonBody::SetLinearDamping(dFloat x)
{
	NewtonBodySetLinearDamping(m_body, x);
}

void* dNewtonBody::GetAngularDamping()
{
	NewtonBodyGetAngularDamping(m_body, &m_angulardamping.m_x);
	return &m_angulardamping;
}

void dNewtonBody::SetAngularDamping(dFloat x, dFloat y, dFloat z)
{
	dVector damp(x, y, z);
	NewtonBodySetAngularDamping(m_body, &damp.m_x);
}

void* dNewtonBody::GetCenterOfMass()
{
	NewtonBodyGetCentreOfMass(m_body, &m_com.m_x);
	return &m_com;
}

void dNewtonBody::SetCenterOfMass(float com_x, float com_y, float com_z, float Ixx, float Iyy, float Izz, bool Calc_inertia)
{
	dVector com;
	dFloat tmp_Ixx;
	dFloat tmp_Iyy;
	dFloat tmp_Izz;
	dFloat mass;

	NewtonBodyGetMass(m_body, &mass, &tmp_Ixx, &tmp_Iyy, &tmp_Izz);
	NewtonCollision* const collision = NewtonBodyGetCollision(m_body);
	if (Calc_inertia) {
		NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));
		NewtonBodyGetCentreOfMass(m_body, &com[0]);
	}
	else {
		NewtonBodySetMassMatrix(m_body, mass, Ixx, Iyy, Izz);
		com.m_x = 0;
		com.m_y = 0;
		com.m_z = 0;
	}

	com.m_x += com_x;
	com.m_y += com_y;
	com.m_z += com_z;
	NewtonBodySetCentreOfMass(m_body, &com[0]);
}

void dNewtonBody::CalculateBuoyancyForces(const void* plane, void* force, void* torque, float bodyDensity)
{
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	dFloat mass;

	NewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);

	if (mass > 0.0f) {
		dMatrix matrix;
		dVector cenyterOfPreasure(0.0f);

		NewtonBodyGetMatrix(m_body, &matrix[0][0]);
		NewtonCollision* const collision = NewtonBodyGetCollision(m_body);

		// calculate the volume and center of mass of the shape under the water surface
		dFloat volume = NewtonConvexCollisionCalculateBuoyancyVolume(collision, &matrix[0][0], (dFloat*)plane, &cenyterOfPreasure[0]);
		if (volume > 0.0f) {
			// if some part of the shape si under water, calculate the buoyancy force base on
			// Archimedes's buoyancy principle, which is the buoyancy force is equal to the
			// weight of the fluid displaced by the volume under water.
			dVector cog(0.0f);
			const dFloat viscousDrag = 0.997f;
			//const dFloat solidDentityFactor = 1.35f;

			// Get the body density form the collision material.
			NewtonCollisionMaterial collisionMaterial;
			NewtonCollisionGetMaterial(collision, &collisionMaterial);
			const dFloat solidDentityFactor = collisionMaterial.m_userParam[0];

			// calculate the ratio of volumes an use it calculate a density equivalent
			dFloat shapeVolume = NewtonConvexCollisionCalculateVolume(collision);
			dFloat density = mass * solidDentityFactor / shapeVolume;

			dFloat displacedMass = density * volume;
			NewtonBodyGetCentreOfMass(m_body, &cog[0]);
			cenyterOfPreasure -= matrix.TransformVector(cog);

			// now with the mass and center of mass of the volume under water, calculate buoyancy force and torque
			dFloat DEMO_GRAVITY = 9.8f;
			dVector finalForce(dFloat(0.0f), dFloat(-DEMO_GRAVITY * displacedMass), dFloat(0.0f), dFloat(0.0f));
			dVector finalTorque(cenyterOfPreasure.CrossProduct(finalForce));

			//NewtonBodyAddForce(visitor, &force[0]);
			//NewtonBodyAddTorque(visitor, &torque[0]);

			// apply a fake viscous drag to damp the under water motion
			dVector omega(0.0f);
			dVector veloc(0.0f);
			NewtonBodyGetOmega(m_body, &omega[0]);
			NewtonBodyGetVelocity(m_body, &veloc[0]);
			omega = omega.Scale(viscousDrag);
			veloc = veloc.Scale(viscousDrag);
			NewtonBodySetOmega(m_body, &omega[0]);
			NewtonBodySetVelocity(m_body, &veloc[0]);

			((float*)force)[0] = finalForce.m_x;
			((float*)force)[1] = finalForce.m_y;
			((float*)force)[2] = finalForce.m_z;
			((float*)torque)[0] = finalTorque.m_x;
			((float*)torque)[1] = finalTorque.m_y;
			((float*)torque)[2] = finalTorque.m_z;
		}
	}
}

void dNewtonBody::OnBodyTransform(const dFloat* const matrixPtr, int threadIndex)
{
	dMatrix matrix(matrixPtr);

	ScopeLock scopelock(&m_lock);
	m_posit0 = m_posit1;
	m_rotation0 = m_rotation1;
	m_posit1 = matrix.m_posit;
	m_rotation1 = dQuaternion(matrix);
	dFloat angle = m_rotation0.DotProduct(m_rotation1);
	if (angle < 0.0f) {
		m_rotation1.Scale(-1.0f);
	}
}

void dNewtonBody::OnForceAndTorque(dFloat timestep, int threadIndex)
{
}

void dNewtonBody::OnForceAndTorqueCallback (const NewtonBody* body, dFloat timestep, int threadIndex)
{
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	dAssert(me);
	me->OnForceAndTorque(timestep, threadIndex);
}

void dNewtonBody::OnBodyTransformCallback (const NewtonBody* const body, const dFloat* const matrix, int threadIndex)
{
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	dAssert(me);
	me->OnBodyTransform(matrix, threadIndex);
}

void dNewtonBody::Destroy()
{
	if (m_body) {
		NewtonWaitForUpdateToFinish(NewtonBodyGetWorld(m_body));
		NewtonBodySetDestructorCallback(m_body, NULL);
		NewtonDestroyBody(m_body);
		m_body = NULL;
	}
}

void dNewtonBody::OnBodyDestroy(const NewtonBody* const body)
{
	dAssert(0);
/*
	dNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);
	if (me) {
		NewtonBodySetDestructorCallback(me->m_body, NULL);
		delete me;
	}
*/
}

void dNewtonBody::InitForceAccumulators()
{
}

void dNewtonBody::AddForce(dFloat x, dFloat y, dFloat z)
{
}

void dNewtonBody::AddTorque(dFloat x, dFloat y, dFloat z)
{
}

dNewtonKinematicBody::dNewtonKinematicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)
	:dNewtonBody(matrix)
{
	NewtonWorld* const newton = world->m_world;
	NewtonWaitForUpdateToFinish(newton);

	m_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);
	collision->DeleteShape();
	collision->SetShape(NewtonBodyGetCollision(m_body));

	NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));

	NewtonBodySetUserData(m_body, this);
	NewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);
	NewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);
}

dNewtonDynamicBody::dNewtonDynamicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)
	:dNewtonBody(matrix)
{
	NewtonWorld* const newton = world->m_world;

	NewtonWaitForUpdateToFinish(newton);
	m_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);
	//collision->DeleteShape();
	//collision->SetShape(NewtonBodyGetCollision(m_body));

	NewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));

	NewtonBodySetUserData(m_body, this);
	NewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);
	NewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);
}

void dNewtonDynamicBody::InitForceAccumulators()
{
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;

	NewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);
	const dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));

	m_externalForce = world->GetGravity().Scale(mass);
	m_externalTorque = dVector(0.0f);
}

void dNewtonDynamicBody::OnForceAndTorque(dFloat timestep, int threadIndex)
{
	NewtonBodySetForce(m_body, &m_externalForce[0]);
	NewtonBodySetTorque(m_body, &m_externalTorque[0]);
}

void dNewtonDynamicBody::AddForce(dFloat x, dFloat y, dFloat z)
{
	m_externalForce += dVector (x, y, z);
}

void dNewtonDynamicBody::AddTorque(dFloat x, dFloat y, dFloat z)
{
	m_externalTorque += dVector(x, y, z);
}

<|endoftext|>


<commit_before>/* ****************************************************************************************************
Dak Washbrook
This program calculates the number of boxes required to ship X number of widgets to a customer.
Have your program prompt the user for the number of widgets ordered. The maximum number of widgets
that can be shipped in a box is 16.  Your program should then calculate the number of full boxes that
will be shipped to the customer and the number of widgets in the last box if the number of widgets
isn't evenly divisible by 16.  You can assume the user will enter in a value between 1 and 15,999.
**************************************************************************************************** */

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() {

	// Declare the variables for the number of widgets and boxes.
	int widgets, boxes, extra;

	// Prompt user for the number of widgets ordered and store it into the widgets variable.
	cout << "Number of widgets ordered? ";
	cin >> widgets;

	// Error handling if user inputs a number less than 1 or greater than 15999.
	while (widgets > 15999 || widgets < 1) {
		cout << endl << "You have entered an invalid amount of widgets! Please enter a number between 1 and 15,999." << endl << endl;
		cout << "Number of widgets ordered? ";
		cin >> widgets;
	}

	// Check if even amount, divisable by 16.
	if (widgets % 16 == 0) {
		// Find the number of boxes.
		boxes = widgets / 16;
		// Output the number of boxes in the correct format.
		cout << "Number of boxes shipped with " << setfill('0') << setw(2) << widgets << " widget(s): " << setw(3) << boxes << endl;
	}
	else {
		// Find the number of boxes.
		boxes = widgets / 16;

		if (boxes > 0) {
			// Output the number of boxes in the correct format.
			cout << "Number of boxes shipped with " << setfill('0') << setw(2) << "16 widget(s): " << setw(3) << boxes << endl;
		}

		// Find the number of extra widgets.
		extra = widgets % 16;

		// Output the number of extra widgets in the last box in the correct format.
		cout << "Number of boxes shipped with " << setfill('0') << setw(2) << extra << " widget(s): " << setw(3) << "001" << endl;
	}

	return 0;

}
<commit_msg>Delete Assignment-1.cpp<commit_after><|endoftext|>


<commit_before>#include "Graphics/TextRenderer.h"

TextRenderer::TextRenderer()
{
	this->_texture = NULL;
	this->_program = NULL;
}

TextRenderer::~TextRenderer()
{
}

void TextRenderer::DrawStringAlpha(int x, int y, int textSize, const string &text, float rTop, float gTop, float bTop, float rBot, float gBot, float bBot, float alpha)
{
	GLFuncs* g = GLFuncs::GetInstance();
    int xPos;
    int charPos;
	char currentChar;

	charPos = 0;
	xPos = x;

	if (this->_texture == NULL) {
		this->_texture = TextureMgr::GetInstance()->LoadTexture("data/font.png");
	}

	if (g->CanUseShaders()) {
		if (this->_program == NULL) {
			vector<string> vertexShaders = { "data/shaders/Default.150.vertex" };
			vector<string> fragmentShaders = { "data/shaders/TexturedColored.150.fragment" };
			this->_program = new Program(vertexShaders, fragmentShaders);
			this->_program->Textures.push_back(this->_texture);
		}

		this->_program->Use();
		this->_program->BindTextures();
		this->_program->SetUniform("MVP", g->MVP);
	}
	else {
		g->SetTexture(0, this->_texture->texture);
	}

	GLfloat color_buffer_data[] = {
		rTop, gTop, bTop, alpha,
		rTop, gTop, bTop, alpha,
		rBot, gBot, bBot, alpha,
		rBot, gBot, bBot, alpha
	};

	while(text[charPos] != 0)
	{
		float tx1, tx2, ty1, ty2;

		currentChar = text[charPos++];

		updateTexCoords(currentChar, &tx1, &ty1, &tx2, &ty2);

		GLfloat vertex_buffer_data[] = {
			(float)xPos, (float)y, 0.0f,
			(float)xPos + textSize, (float)y, 0.0f,
			(float)xPos + textSize, (float)y + textSize, 0.0f,
			(float)xPos, (float)y + textSize, 0.0f
		};

		GLfloat uv_buffer_data[] = {
			tx1, ty1,
			tx2, ty1,
			tx2, ty2,
			tx1, ty2
		};

		g->BlitVerts(vertex_buffer_data, sizeof(vertex_buffer_data), uv_buffer_data, sizeof(uv_buffer_data), color_buffer_data, sizeof(color_buffer_data));

		xPos += textSize;
	}
}

void TextRenderer::updateTexCoords(char currentChar, float* tx1, float* ty1, float* tx2, float* ty2)
{
	const float factor = 0.0625f;
	char diff;

	if(currentChar >= 'a' && currentChar <= 'p')
	{
        diff = currentChar - 'a';
		*tx1 = diff * factor;
		*tx2 = (diff + 1) * factor;
		*ty1 = 0;
		*ty2 = factor;
	}
	else
	{
		if(currentChar >= 'q' && currentChar <= 'z')
		{
			diff = currentChar - 'q';
			*tx1 = diff * factor;
			*tx2 = (diff + 1) * factor;
			*ty1 = factor;
			*ty2 = 2 * factor;
		}
		else
		{
			if(currentChar >= 'A' && currentChar <= 'P')
			{
				diff = currentChar - 'A';
				*tx1 = diff * factor;
				*tx2 = (diff + 1) * factor;
				*ty1 = 2 * factor;
				*ty2 = 3 * factor;
			}
			else
			{
				if(currentChar >= 'Q' && currentChar <= 'Z')
				{
					diff = currentChar - 'Q';
					*tx1 = diff * factor;
					*tx2 = (diff + 1) * factor;
					*ty1 = 3 * factor;
					*ty2 = 4 * factor;
				}
				else
				{
					if(currentChar >= '0' && currentChar <= '9')
					{
						diff = currentChar - '0';
						*tx1 = diff * factor;
						*tx2 = (diff + 1) * factor;
						*ty1 = 4 * factor;
						*ty2 = 5 * factor;
					}
					else
					{
						*ty1 = 5 * factor;
						*ty2 = 6 * factor;
						switch(currentChar)
						{
							case '.':
								*tx1 = 0;
								*tx2 = factor;
								break;
							case ':':
								*tx1 = factor;
								*tx2 = 2 * factor;
								break;
							case ',':
								*tx1 = 2 * factor;
								*tx2 = 3 * factor;
								break;
							case ';':
								*tx1 = 3 * factor;
								*tx2 = 4 * factor;
								break;
							case '(':
								*tx1 = 4 * factor;
								*tx2 = 5 * factor;
								break;
							case '*':
								*tx1 = 6 * factor;
								*tx2 = 7 * factor;
								break;
							case '!':
								*tx1 = 7 * factor;
								*tx2 = 8 * factor;
								break;
							case '?':
								*tx1 = 8 * factor;
								*tx2 = 9 * factor;
								break;
							case '\'':
								*tx1 = 9 * factor;
								*tx2 = 10 * factor;
								break;
							case ')':
								*tx1 = 10 * factor;
								*tx2 = 11 * factor;
								break;
							case '&':
								*tx1 = 11 * factor;
								*tx2 = 12 * factor;
								break;
							case '-':
								*tx1 = 12 * factor;
								*tx2 = 13 * factor;
								break;
							case '@':
								*tx1 = 13 * factor;
								*tx2 = 14 * factor;
								break;
							default:
								*tx1 = 15 * factor;
								*tx2 = 16 * factor;
								break;
						}
					}
				}
			}
		}
	}
}<commit_msg>Solved minor bugs in OpenGL state management<commit_after>#include "Graphics/TextRenderer.h"

TextRenderer::TextRenderer()
{
	this->_texture = NULL;
	this->_program = NULL;
}

TextRenderer::~TextRenderer()
{
}

void TextRenderer::DrawStringAlpha(int x, int y, int textSize, const string &text, float rTop, float gTop, float bTop, float rBot, float gBot, float bBot, float alpha)
{
	GLFuncs* g = GLFuncs::GetInstance();
    int xPos;
    int charPos;
	char currentChar;

	charPos = 0;
	xPos = x;

	if (this->_texture == NULL) {
		this->_texture = TextureMgr::GetInstance()->LoadTexture("data/font.png");
		if(this->_texture == NULL) {
			Log::Out << "TextRenderer::DrawStringAlpha: Couldn't load font!" << endl;
			return;
		}
	}

	if (g->CanUseShaders()) {
		if (this->_program == NULL) {
			vector<string> vertexShaders = { "data/shaders/Default.150.vertex" };
			vector<string> fragmentShaders = { "data/shaders/TexturedColored.150.fragment" };
			this->_program = new Program(vertexShaders, fragmentShaders);
			this->_program->Textures.push_back(this->_texture);
		}

		this->_program->Use();
		this->_program->BindTextures();
		this->_program->SetUniform("MVP", g->MVP);
	}
	else {
		g->SetTexture(0, this->_texture->texture);
	}

	GLfloat color_buffer_data[] = {
		rTop, gTop, bTop, alpha,
		rTop, gTop, bTop, alpha,
		rBot, gBot, bBot, alpha,
		rBot, gBot, bBot, alpha
	};

	while(text[charPos] != 0)
	{
		float tx1, tx2, ty1, ty2;

		currentChar = text[charPos++];

		updateTexCoords(currentChar, &tx1, &ty1, &tx2, &ty2);

		GLfloat vertex_buffer_data[] = {
			(float)xPos, (float)y, 0.0f,
			(float)xPos + textSize, (float)y, 0.0f,
			(float)xPos + textSize, (float)y + textSize, 0.0f,
			(float)xPos, (float)y + textSize, 0.0f
		};

		GLfloat uv_buffer_data[] = {
			tx1, ty1,
			tx2, ty1,
			tx2, ty2,
			tx1, ty2
		};

		g->BlitVerts(vertex_buffer_data, sizeof(vertex_buffer_data), uv_buffer_data, sizeof(uv_buffer_data), color_buffer_data, sizeof(color_buffer_data));

		xPos += textSize;
	}
}

void TextRenderer::updateTexCoords(char currentChar, float* tx1, float* ty1, float* tx2, float* ty2)
{
	const float factor = 0.0625f;
	char diff;

	if(currentChar >= 'a' && currentChar <= 'p')
	{
        diff = currentChar - 'a';
		*tx1 = diff * factor;
		*tx2 = (diff + 1) * factor;
		*ty1 = 0;
		*ty2 = factor;
	}
	else
	{
		if(currentChar >= 'q' && currentChar <= 'z')
		{
			diff = currentChar - 'q';
			*tx1 = diff * factor;
			*tx2 = (diff + 1) * factor;
			*ty1 = factor;
			*ty2 = 2 * factor;
		}
		else
		{
			if(currentChar >= 'A' && currentChar <= 'P')
			{
				diff = currentChar - 'A';
				*tx1 = diff * factor;
				*tx2 = (diff + 1) * factor;
				*ty1 = 2 * factor;
				*ty2 = 3 * factor;
			}
			else
			{
				if(currentChar >= 'Q' && currentChar <= 'Z')
				{
					diff = currentChar - 'Q';
					*tx1 = diff * factor;
					*tx2 = (diff + 1) * factor;
					*ty1 = 3 * factor;
					*ty2 = 4 * factor;
				}
				else
				{
					if(currentChar >= '0' && currentChar <= '9')
					{
						diff = currentChar - '0';
						*tx1 = diff * factor;
						*tx2 = (diff + 1) * factor;
						*ty1 = 4 * factor;
						*ty2 = 5 * factor;
					}
					else
					{
						*ty1 = 5 * factor;
						*ty2 = 6 * factor;
						switch(currentChar)
						{
							case '.':
								*tx1 = 0;
								*tx2 = factor;
								break;
							case ':':
								*tx1 = factor;
								*tx2 = 2 * factor;
								break;
							case ',':
								*tx1 = 2 * factor;
								*tx2 = 3 * factor;
								break;
							case ';':
								*tx1 = 3 * factor;
								*tx2 = 4 * factor;
								break;
							case '(':
								*tx1 = 4 * factor;
								*tx2 = 5 * factor;
								break;
							case '*':
								*tx1 = 6 * factor;
								*tx2 = 7 * factor;
								break;
							case '!':
								*tx1 = 7 * factor;
								*tx2 = 8 * factor;
								break;
							case '?':
								*tx1 = 8 * factor;
								*tx2 = 9 * factor;
								break;
							case '\'':
								*tx1 = 9 * factor;
								*tx2 = 10 * factor;
								break;
							case ')':
								*tx1 = 10 * factor;
								*tx2 = 11 * factor;
								break;
							case '&':
								*tx1 = 11 * factor;
								*tx2 = 12 * factor;
								break;
							case '-':
								*tx1 = 12 * factor;
								*tx2 = 13 * factor;
								break;
							case '@':
								*tx1 = 13 * factor;
								*tx2 = 14 * factor;
								break;
							default:
								*tx1 = 15 * factor;
								*tx2 = 16 * factor;
								break;
						}
					}
				}
			}
		}
	}
}<|endoftext|>


<commit_before>// @(#)root/core/meta:$Id$
// Author: Paul Russo   30/07/2012

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TClingTypedefInfo                                                    //
//                                                                      //
// Emulation of the CINT TypedefInfo class.                             //
//                                                                      //
// The CINT C++ interpreter provides an interface to metadata about     //
// a typedef through the TypedefInfo class.  This class provides the    //
// same functionality, using an interface as close as possible to       //
// TypedefInfo but the typedef metadata comes from the Clang C++        //
// compiler, not CINT.                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TClingTypedefInfo.h"

#include "TDictionary.h"
#include "TError.h"
#include "TMetaUtils.h"
#include "Rtypes.h" // for gDebug

#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Attr.h"

using namespace clang;

//______________________________________________________________________________
TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,
                                     const char *name)
   : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle("")
{
   // Lookup named typedef and initialize the iterator to point to it.
   // Yields a non-iterable TClingTypedefInfo (fIter is invalid).
   Init(name);
}

TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,
                                     const clang::TypedefDecl *TdefD)
   : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD),
     fTitle("")
{
   // Initialize with a clang::TypedefDecl.
   // fIter is invalid; cannot call Next().
   if (gDebug > 0) {
      Info("TClingTypedefInfo::TClingTypedefInfo(interp,name)",
           "found typedef name: %s  decl: 0x%lx",
           TdefD->getNameAsString().c_str(), (long) fDecl);
   }
}

//______________________________________________________________________________
const clang::Decl *TClingTypedefInfo::GetDecl() const
{
   // Get the current typedef declaration.
   return fDecl;
}

//______________________________________________________________________________
void TClingTypedefInfo::Init(const char *name)
{
   // Lookup named typedef and reset the iterator to point to it.
   if (gDebug > 0) {
      Info("TClingTypedefInfo::Init(name)", "looking up typedef: %s", name);
   }
   // Reset the iterator to invalid.
   fFirstTime = true;
   fDescend = false;
   fIter = clang::DeclContext::decl_iterator();
   fIterStack.clear();
   // Ask the cling interpreter to lookup the name for us.
   const cling::LookupHelper& lh = fInterp->getLookupHelper();
   clang::QualType QT = lh.findType(name);
   if (QT.isNull()) {
      std::string buf = TClassEdit::InsertStd(name);
      QT = lh.findType(buf);

      if (QT.isNull()) {
         if (gDebug > 0) {
            Info("TClingTypedefInfo::Init(name)",
                 "type not found: %s", name);
         }
         fDecl = 0;
         return;
      }
   }
   const clang::TypedefType *td = QT->getAs<clang::TypedefType>();
   // if (fDecl && !llvm::isa<clang::TypedefDecl>(fDecl)) {
   if (!td) {
      // If what the lookup found is not a typedef, ignore it.
      if (gDebug > 0) {
         Info("TClingTypedefInfo::Init(name)",
              "type not a typedef: %s", name);
      }
      fDecl = 0;
      return;
   }
   fDecl = td->getDecl();
   if (!fDecl) {
      if (gDebug > 0) {
         Info("TClingTypedefInfo::Init(name)",
              "typedef decl not found name: %s", name);
      }
      return;
   }
   if (gDebug > 0) {
      Info("TClingTypedefInfo::Init(name)", "found typedef name: "
           "%s  decl: 0x%lx", name, (long) fDecl);
   }
}

//______________________________________________________________________________
bool TClingTypedefInfo::IsValid() const
{
   // Return true if the current iterator position is valid.
   return fDecl;
}

//______________________________________________________________________________
int TClingTypedefInfo::InternalNext()
{
   // Increment the iterator, return true if new position is valid.
   if (!*fIter) {
      // Iterator is already invalid.
      if (fFirstTime && fDecl) {
         std::string buf;
         clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());
         llvm::raw_string_ostream stream(buf);
         llvm::dyn_cast<clang::NamedDecl>(fDecl)
            ->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
         stream.flush();
         Error("TClingTypedefInfo::InternalNext","Next called but iteration not prepared for %s!",buf.c_str());
      }
      return 0;
   }
   while (true) {
      // Advance to next usable decl, or return if
      // there is no next usable decl.
      if (fFirstTime) {
         // The cint semantics are strange.
         fFirstTime = false;
      }
      else {
         // Advance the iterator one decl, descending into
         // the current decl context if necessary.
         if (!fDescend) {
            // Do not need to scan the decl context of the
            // current decl, move on to the next decl.
            ++fIter;
         }
         else {
            // Descend into the decl context of the current decl.
            fDescend = false;
            fIterStack.push_back(fIter);
            clang::DeclContext *dc = llvm::cast<clang::DeclContext>(*fIter);
            fIter = dc->decls_begin();
         }
         // Fix it if we went past the end.
         while (!*fIter && fIterStack.size()) {
            fIter = fIterStack.back();
            fIterStack.pop_back();
            ++fIter;
         }
         // Check for final termination.
         if (!*fIter) {
            // We have reached the end of the translation unit, all done.
            fDecl = 0;
            return 0;
         }
      }
      // Return if this decl is a typedef.
      if (llvm::isa<clang::TypedefDecl>(*fIter)) {
         fDecl = *fIter;
         return 1;
      }
      // Descend into namespaces and classes.
      clang::Decl::Kind dk = fIter->getKind();
      if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||
            (dk == clang::Decl::ClassTemplateSpecialization)) {
         fDescend = true;
      }
   }
}

//______________________________________________________________________________
int TClingTypedefInfo::Next()
{
   // Increment the iterator.
   return InternalNext();
}

//______________________________________________________________________________
long TClingTypedefInfo::Property() const
{
   // Return a bit mask of metadata about the current typedef.
   if (!IsValid()) {
      return 0L;
   }
   long property = 0L;
   property |= kIsTypedef;
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType qt = td->getUnderlyingType().getCanonicalType();
   if (qt.isConstQualified()) {
      property |= kIsConstant;
   }
   while (1) {
      if (qt->isArrayType()) {
         qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
         continue;
      }
      else if (qt->isReferenceType()) {
         property |= kIsReference;
         qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
         continue;
      }
      else if (qt->isPointerType()) {
         property |= kIsPointer;
         if (qt.isConstQualified()) {
            property |= kIsConstPointer;
         }
         qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
         continue;
      }
      else if (qt->isMemberPointerType()) {
         qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
         continue;
      }
      break;
   }
   if (qt->isBuiltinType()) {
      property |= kIsFundamental;
   }
   if (qt.isConstQualified()) {
      property |= kIsConstant;
   }
   return property;
}

//______________________________________________________________________________
int TClingTypedefInfo::Size() const
{
   // Return the size in bytes of the underlying type of the current typedef.
   if (!IsValid()) {
      return 1;
   }
   clang::ASTContext &context = fDecl->getASTContext();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType qt = td->getUnderlyingType();
   if (qt->isDependentType()) {
      // The underlying type is dependent on a template parameter,
      // we have no idea what it is yet.
      return 0;
   }
   if (const clang::RecordType *rt = qt->getAs<clang::RecordType>()) {
      if (!rt->getDecl()->getDefinition()) {
         // This is a typedef to a forward-declared type.
         return 0;
      }
   }
   // Note: This is an int64_t.
   clang::CharUnits::QuantityType quantity =
      context.getTypeSizeInChars(qt).getQuantity();
   // Truncate cast to fit the CINT interface.
   return static_cast<int>(quantity);
}

//______________________________________________________________________________
const char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
   // Get the name of the underlying type of the current typedef.
   if (!IsValid()) {
      return "(unknown)";
   }
   // Note: This must be static because we return a pointer to the internals.
   static std::string truename;
   truename.clear();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType underlyingType = td->getUnderlyingType();
   if (underlyingType->isBooleanType()) {
      return "bool";
   }
   const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();
   ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);

   return truename.c_str();
}

//______________________________________________________________________________
const char *TClingTypedefInfo::Name() const
{
   // Get the name of the current typedef.
   if (!IsValid()) {
      return "(unknown)";
   }
   // Note: This must be static because we return a pointer to the internals.
   static std::string fullname;
   fullname.clear();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   const clang::ASTContext &ctxt = fDecl->getASTContext();
   ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);
   return fullname.c_str();
}

//______________________________________________________________________________
const char *TClingTypedefInfo::Title()
{
   if (!IsValid()) {
      return 0;
   }
   //NOTE: We can't use it as a cache due to the "thoughtful" self iterator
   //if (fTitle.size())
   //   return fTitle.c_str();

   // Try to get the comment either from the annotation or the header file if present

   // Iterate over the redeclarations, we can have muliple definitions in the
   // redecl chain (came from merging of pcms).
   if (const TypedefNameDecl *TND = llvm::dyn_cast<TypedefNameDecl>(GetDecl())) {
      if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {
         if (AnnotateAttr *A = TND->getAttr<AnnotateAttr>()) {
            fTitle = A->getAnnotation().str();
            return fTitle.c_str();
         }
      }
   }

   // Try to get the comment from the header file if present
   fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();
   return fTitle.c_str();
}

<commit_msg>Add missing transaction in TClingTypedefInfo.<commit_after>// @(#)root/core/meta:$Id$
// Author: Paul Russo   30/07/2012

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TClingTypedefInfo                                                    //
//                                                                      //
// Emulation of the CINT TypedefInfo class.                             //
//                                                                      //
// The CINT C++ interpreter provides an interface to metadata about     //
// a typedef through the TypedefInfo class.  This class provides the    //
// same functionality, using an interface as close as possible to       //
// TypedefInfo but the typedef metadata comes from the Clang C++        //
// compiler, not CINT.                                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TClingTypedefInfo.h"

#include "TDictionary.h"
#include "TError.h"
#include "TMetaUtils.h"
#include "Rtypes.h" // for gDebug

#include "cling/Interpreter/LookupHelper.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Attr.h"

using namespace clang;

//______________________________________________________________________________
TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,
                                     const char *name)
   : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle("")
{
   // Lookup named typedef and initialize the iterator to point to it.
   // Yields a non-iterable TClingTypedefInfo (fIter is invalid).
   Init(name);
}

TClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,
                                     const clang::TypedefDecl *TdefD)
   : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD),
     fTitle("")
{
   // Initialize with a clang::TypedefDecl.
   // fIter is invalid; cannot call Next().
   if (gDebug > 0) {
      Info("TClingTypedefInfo::TClingTypedefInfo(interp,name)",
           "found typedef name: %s  decl: 0x%lx",
           TdefD->getNameAsString().c_str(), (long) fDecl);
   }
}

//______________________________________________________________________________
const clang::Decl *TClingTypedefInfo::GetDecl() const
{
   // Get the current typedef declaration.
   return fDecl;
}

//______________________________________________________________________________
void TClingTypedefInfo::Init(const char *name)
{
   // Lookup named typedef and reset the iterator to point to it.
   if (gDebug > 0) {
      Info("TClingTypedefInfo::Init(name)", "looking up typedef: %s", name);
   }
   // Reset the iterator to invalid.
   fFirstTime = true;
   fDescend = false;
   fIter = clang::DeclContext::decl_iterator();
   fIterStack.clear();
   // Ask the cling interpreter to lookup the name for us.
   const cling::LookupHelper& lh = fInterp->getLookupHelper();
   clang::QualType QT = lh.findType(name);
   if (QT.isNull()) {
      std::string buf = TClassEdit::InsertStd(name);
      QT = lh.findType(buf);

      if (QT.isNull()) {
         if (gDebug > 0) {
            Info("TClingTypedefInfo::Init(name)",
                 "type not found: %s", name);
         }
         fDecl = 0;
         return;
      }
   }
   const clang::TypedefType *td = QT->getAs<clang::TypedefType>();
   // if (fDecl && !llvm::isa<clang::TypedefDecl>(fDecl)) {
   if (!td) {
      // If what the lookup found is not a typedef, ignore it.
      if (gDebug > 0) {
         Info("TClingTypedefInfo::Init(name)",
              "type not a typedef: %s", name);
      }
      fDecl = 0;
      return;
   }
   fDecl = td->getDecl();
   if (!fDecl) {
      if (gDebug > 0) {
         Info("TClingTypedefInfo::Init(name)",
              "typedef decl not found name: %s", name);
      }
      return;
   }
   if (gDebug > 0) {
      Info("TClingTypedefInfo::Init(name)", "found typedef name: "
           "%s  decl: 0x%lx", name, (long) fDecl);
   }
}

//______________________________________________________________________________
bool TClingTypedefInfo::IsValid() const
{
   // Return true if the current iterator position is valid.
   return fDecl;
}

//______________________________________________________________________________
int TClingTypedefInfo::InternalNext()
{
   // Increment the iterator, return true if new position is valid.
   if (!*fIter) {
      // Iterator is already invalid.
      if (fFirstTime && fDecl) {
         std::string buf;
         clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());
         llvm::raw_string_ostream stream(buf);
         llvm::dyn_cast<clang::NamedDecl>(fDecl)
            ->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
         stream.flush();
         Error("TClingTypedefInfo::InternalNext","Next called but iteration not prepared for %s!",buf.c_str());
      }
      return 0;
   }
   // Deserialization might happen during the iteration.
   cling::Interpreter::PushTransactionRAII pushedT(fInterp);
   while (true) {
      // Advance to next usable decl, or return if
      // there is no next usable decl.
      if (fFirstTime) {
         // The cint semantics are strange.
         fFirstTime = false;
      }
      else {
         // Advance the iterator one decl, descending into
         // the current decl context if necessary.
         if (!fDescend) {
            // Do not need to scan the decl context of the
            // current decl, move on to the next decl.
            ++fIter;
         }
         else {
            // Descend into the decl context of the current decl.
            fDescend = false;
            fIterStack.push_back(fIter);
            clang::DeclContext *dc = llvm::cast<clang::DeclContext>(*fIter);
            fIter = dc->decls_begin();
         }
         // Fix it if we went past the end.
         while (!*fIter && fIterStack.size()) {
            fIter = fIterStack.back();
            fIterStack.pop_back();
            ++fIter;
         }
         // Check for final termination.
         if (!*fIter) {
            // We have reached the end of the translation unit, all done.
            fDecl = 0;
            return 0;
         }
      }
      // Return if this decl is a typedef.
      if (llvm::isa<clang::TypedefDecl>(*fIter)) {
         fDecl = *fIter;
         return 1;
      }
      // Descend into namespaces and classes.
      clang::Decl::Kind dk = fIter->getKind();
      if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||
            (dk == clang::Decl::ClassTemplateSpecialization)) {
         fDescend = true;
      }
   }
}

//______________________________________________________________________________
int TClingTypedefInfo::Next()
{
   // Increment the iterator.
   return InternalNext();
}

//______________________________________________________________________________
long TClingTypedefInfo::Property() const
{
   // Return a bit mask of metadata about the current typedef.
   if (!IsValid()) {
      return 0L;
   }
   long property = 0L;
   property |= kIsTypedef;
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType qt = td->getUnderlyingType().getCanonicalType();
   if (qt.isConstQualified()) {
      property |= kIsConstant;
   }
   while (1) {
      if (qt->isArrayType()) {
         qt = llvm::cast<clang::ArrayType>(qt)->getElementType();
         continue;
      }
      else if (qt->isReferenceType()) {
         property |= kIsReference;
         qt = llvm::cast<clang::ReferenceType>(qt)->getPointeeType();
         continue;
      }
      else if (qt->isPointerType()) {
         property |= kIsPointer;
         if (qt.isConstQualified()) {
            property |= kIsConstPointer;
         }
         qt = llvm::cast<clang::PointerType>(qt)->getPointeeType();
         continue;
      }
      else if (qt->isMemberPointerType()) {
         qt = llvm::cast<clang::MemberPointerType>(qt)->getPointeeType();
         continue;
      }
      break;
   }
   if (qt->isBuiltinType()) {
      property |= kIsFundamental;
   }
   if (qt.isConstQualified()) {
      property |= kIsConstant;
   }
   return property;
}

//______________________________________________________________________________
int TClingTypedefInfo::Size() const
{
   // Return the size in bytes of the underlying type of the current typedef.
   if (!IsValid()) {
      return 1;
   }
   clang::ASTContext &context = fDecl->getASTContext();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType qt = td->getUnderlyingType();
   if (qt->isDependentType()) {
      // The underlying type is dependent on a template parameter,
      // we have no idea what it is yet.
      return 0;
   }
   if (const clang::RecordType *rt = qt->getAs<clang::RecordType>()) {
      if (!rt->getDecl()->getDefinition()) {
         // This is a typedef to a forward-declared type.
         return 0;
      }
   }
   // Note: This is an int64_t.
   clang::CharUnits::QuantityType quantity =
      context.getTypeSizeInChars(qt).getQuantity();
   // Truncate cast to fit the CINT interface.
   return static_cast<int>(quantity);
}

//______________________________________________________________________________
const char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
{
   // Get the name of the underlying type of the current typedef.
   if (!IsValid()) {
      return "(unknown)";
   }
   // Note: This must be static because we return a pointer to the internals.
   static std::string truename;
   truename.clear();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   clang::QualType underlyingType = td->getUnderlyingType();
   if (underlyingType->isBooleanType()) {
      return "bool";
   }
   const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();
   ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);

   return truename.c_str();
}

//______________________________________________________________________________
const char *TClingTypedefInfo::Name() const
{
   // Get the name of the current typedef.
   if (!IsValid()) {
      return "(unknown)";
   }
   // Note: This must be static because we return a pointer to the internals.
   static std::string fullname;
   fullname.clear();
   const clang::TypedefDecl *td = llvm::dyn_cast<clang::TypedefDecl>(fDecl);
   const clang::ASTContext &ctxt = fDecl->getASTContext();
   ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);
   return fullname.c_str();
}

//______________________________________________________________________________
const char *TClingTypedefInfo::Title()
{
   if (!IsValid()) {
      return 0;
   }
   //NOTE: We can't use it as a cache due to the "thoughtful" self iterator
   //if (fTitle.size())
   //   return fTitle.c_str();

   // Try to get the comment either from the annotation or the header file if present

   // Iterate over the redeclarations, we can have muliple definitions in the
   // redecl chain (came from merging of pcms).
   if (const TypedefNameDecl *TND = llvm::dyn_cast<TypedefNameDecl>(GetDecl())) {
      if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {
         if (AnnotateAttr *A = TND->getAttr<AnnotateAttr>()) {
            fTitle = A->getAnnotation().str();
            return fTitle.c_str();
         }
      }
   }

   // Try to get the comment from the header file if present
   fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();
   return fTitle.c_str();
}

<|endoftext|>