<commit_before>/// HEADER
#include "apex_ros_interface.h"

/// PROJECT
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ros/ros_handler.h>
#include "import_ros.h"
#include <csapex/model/graph.h>
#include <csapex/model/node_state.h>
#include <csapex/factory/message_factory.h>
#include <csapex_ros/ros_message_conversion.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex_ros/yaml_io.hpp>
#include <csapex/model/graph_facade.h>
#include <csapex/model/node_handle.h>
#include <csapex/model/node.h>
#include <csapex/signal/event.h>
#include <csapex/msg/no_message.h>
#include <csapex/model/token.h>
#include <csapex/msg/any_message.h>

/// SYSTEM
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <std_msgs/Int32.h>
#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <std_msgs/Float64.h>
#include <QMimeData>

CSAPEX_REGISTER_CLASS(csapex::APEXRosInterface, csapex::CorePlugin)

using namespace csapex;

template <typename RosType, typename ApexType>
struct ConvertIntegral
{
    static typename connection_types::GenericValueMessage<ApexType>::Ptr ros2apex(const typename RosType::ConstPtr &ros_msg) {
        typename connection_types::GenericValueMessage<ApexType>::Ptr out(new connection_types::GenericValueMessage<ApexType>);
        out->value = ros_msg->data;
        return out;
    }
    static typename RosType::Ptr apex2ros(const typename connection_types::GenericValueMessage<ApexType>::ConstPtr& apex_msg) {
        typename RosType::Ptr out(new RosType);
        out->data = apex_msg->value;
        return out;
    }
};

APEXRosInterface::APEXRosInterface()
    : core_(nullptr), disabled_(false)
{
    last_clock_ = ros::Time(0);
}

APEXRosInterface::~APEXRosInterface()
{
}

void APEXRosInterface::prepare(Settings &settings)
{
    ROSHandler::createInstance(settings);
}

void APEXRosInterface::init(CsApexCore &core)
{
    core_ = &core;

    ROSHandler::instance().registerConnectionCallback([this]() {
        registerCommandListener();
        registerClockWatchdog();
    });

    RosMessageConversion::registerConversion<std_msgs::Bool, connection_types::GenericValueMessage<bool>, ConvertIntegral<std_msgs::Bool, bool> >();
    RosMessageConversion::registerConversion<std_msgs::Int32, connection_types::GenericValueMessage<int>, ConvertIntegral<std_msgs::Int32, int> >();
    RosMessageConversion::registerConversion<std_msgs::Float64, connection_types::GenericValueMessage<double>, ConvertIntegral<std_msgs::Float64, double> >();
    RosMessageConversion::registerConversion<std_msgs::String, connection_types::GenericValueMessage<std::string>, ConvertIntegral<std_msgs::String, std::string> >();

    core_->loaded.connect([this](){
        if(ROSHandler::instance().isConnected()) {
            XmlRpc::XmlRpcValue params, result, payload;
            params[0] = ros::this_node::getName();

            std::string prefix = ros::this_node::getName();

            if (ros::master::execute("getParamNames", params, result, payload, true)) {
                if(result.getType() != XmlRpc::XmlRpcValue::TypeArray) {
                    return;
                }

                std::string name = result[1];
                if(name != "Parameter names") {
                    return;
                }

                XmlRpc::XmlRpcValue data = result[2];
                for(std::size_t i = 0, total = data.size(); i < total; ++i) {
                    std::string parameter_name = data[i];

                    if(parameter_name.substr(0, prefix.size()) != prefix) {
                        continue;
                    }

                    try {
                        XmlRpc::XmlRpcValue parameter_value;
                        ros::param::getCached(parameter_name, parameter_value);

                        loadParameterValue(prefix, parameter_name, parameter_value);
                    } catch (std::exception e) {
                        // silence
                    }
                }
            }
        }
    });
}

void APEXRosInterface::setupGraph(Graph *graph)
{
    clock_reset_event_ = graph->createInternalEvent(connection_types::makeEmpty<connection_types::AnyMessage>(), graph->makeUUID("event_ros_time_reset"), "ros time reset");
}

void APEXRosInterface::loadParameterValue(const std::string& prefix, const std::string& parameter_name, const XmlRpc::XmlRpcValue& parameter_value)
{
    std::string apex_name = parameter_name.substr(prefix.size());

    Graph* graph = core_->getRoot()->getGraph();

    std::vector<std::string> levels;

    std::size_t delim = 0;
    while(delim != std::string::npos) {
        delim = apex_name.find('/');
        std::string subname = apex_name.substr(0, delim);
        if(!subname.empty()) {
            levels.push_back(subname);
        }
        apex_name = apex_name.substr(delim+1);
    }

    if(levels.empty()) {
        return;
    }

    NodeHandle* nh = nullptr;
    std::string param_name;
    for(std::size_t i = 0, n = levels.size(); i < n - 1; ++i) {
        const std::string subname = levels.at(i);
        std::cerr << "searching for " << subname << std::endl;
        nh = graph->findNodeHandleWithLabel(subname);
        if(!nh) {
            std::cerr << "no parameter for " << parameter_name << ", label " << subname << " non-existent" << std::endl;
            return;
        }

        if (NodePtr node = nh->getNode().lock()) {
            std::ostringstream param_name_builder;
            std::copy(std::next(levels.begin(), i + 1), levels.end(), std::ostream_iterator<std::string>(param_name_builder, "/"));
            param_name = param_name_builder.str();
            param_name = param_name.substr(0, param_name.size() - 1);
            std::cerr << "searching for param " << param_name << std::endl;
            if (node->hasParameter(param_name))
                break;
            boost::algorithm::replace_all(param_name, " ", "_");
            std::cerr << "searching for param " << param_name << " (fallback)" << std::endl;
            if (node->hasParameter(param_name))
                break;
        }
        if(i < n - 2) {
            graph = dynamic_cast<Graph*>(nh->getNode().lock().get());
            if(!graph) {
                std::cerr << "no parameter for " << parameter_name << ", child " << subname << " is not a graph" << std::endl;
                return;
            }
        }

    }
    if(!nh) {
        return;
    }

    NodePtr node = nh->getNode().lock();
    if(!node) {
        return;
    }

    if(!node->hasParameter(param_name)) {
        std::cerr << "node " << nh->getUUID() << " doesn't have a parameter called " << param_name << std::endl;
        return;
    }

    param::ParameterPtr p = node->getParameter(param_name);

    switch(parameter_value.getType()) {
    case XmlRpc::XmlRpcValue::TypeInt: {
        int val;
        ros::param::get(parameter_name, val);
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeDouble: {
        double val;
        ros::param::get(parameter_name, val);
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeBoolean: {
        bool val;
        ros::param::get(parameter_name, val);
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeString: {
        std::string val;
        ros::param::get(parameter_name, val);
        p->set(val);
    }
        break;

    default:
        break;
    }
}

void APEXRosInterface::registerCommandListener()
{
    assert(ROSHandler::instance().isConnected());
    global_command_sub_ = ROSHandler::instance().nh()->subscribe
            <std_msgs::String>("/syscommand", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, true));
    private_command_sub_ = ROSHandler::instance().nh()->subscribe
            <std_msgs::String>("command", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, false));

    ros::spinOnce();
}

void APEXRosInterface::command(const std_msgs::StringConstPtr& cmd, bool global_cmd)
{
    std::string command = cmd->data;
    bool local_cmd = !global_cmd;

    /*
     * pause / unpause:
     *   - temporary disable everything to conserve computational power
     *   - globally accepted, if this node is not disabled
     *
     * stop / resume
     *   - completely disable / enable this subsystem, when it is not needed
     *   - only locally accepted
     *   - overwrites pause -> a disabled instance cannot be unpaused
     */

    if(!disabled_) {
        // disabled state is stronger than pause / unpause
        if(command == "pause") {
            core_->setPause(true);

        } else if(command == "unpause"){
            core_->setPause(false);
        }
    }

    if(local_cmd) {
        if(command == "stop") {
            disabled_ = true;
            core_->setPause(true);
        } else if(command == "resume") {
            disabled_ = false;
            core_->setPause(false);
        }
    }
}

void APEXRosInterface::registerClockWatchdog()
{
    clock_sub_ = ROSHandler::instance().nh()->subscribe
            <rosgraph_msgs::Clock>("/clock", 10, std::bind(&APEXRosInterface::clock, this, std::placeholders::_1));
}

void APEXRosInterface::clock(const rosgraph_msgs::ClockConstPtr &clock)
{
    ros::Time now = clock->clock;
    if(now < last_clock_) {
        std::cerr << "time reset" << std::endl;

        TokenDataConstPtr data(new connection_types::AnyMessage);
        TokenPtr token = std::make_shared<Token>(data);
        token->setActive(true);
        clock_reset_event_->triggerWith(token);
    }

    last_clock_ = now;
}

void APEXRosInterface::shutdown()
{
    ROSHandler::instance().stop();

    RosMessageConversion::instance().shutdown();
}
<commit_msg>using mapped parameters for roslaunch support<commit_after>/// HEADER
#include "apex_ros_interface.h"

/// PROJECT
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ros/ros_handler.h>
#include "import_ros.h"
#include <csapex/model/graph.h>
#include <csapex/model/node_state.h>
#include <csapex/factory/message_factory.h>
#include <csapex_ros/ros_message_conversion.h>
#include <csapex/msg/generic_value_message.hpp>
#include <csapex_ros/yaml_io.hpp>
#include <csapex/model/graph_facade.h>
#include <csapex/model/node_handle.h>
#include <csapex/model/node.h>
#include <csapex/signal/event.h>
#include <csapex/msg/no_message.h>
#include <csapex/model/token.h>
#include <csapex/msg/any_message.h>

/// SYSTEM
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <std_msgs/Int32.h>
#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <std_msgs/Float64.h>
#include <QMimeData>

CSAPEX_REGISTER_CLASS(csapex::APEXRosInterface, csapex::CorePlugin)

using namespace csapex;

template <typename RosType, typename ApexType>
struct ConvertIntegral
{
    static typename connection_types::GenericValueMessage<ApexType>::Ptr ros2apex(const typename RosType::ConstPtr &ros_msg) {
        typename connection_types::GenericValueMessage<ApexType>::Ptr out(new connection_types::GenericValueMessage<ApexType>);
        out->value = ros_msg->data;
        return out;
    }
    static typename RosType::Ptr apex2ros(const typename connection_types::GenericValueMessage<ApexType>::ConstPtr& apex_msg) {
        typename RosType::Ptr out(new RosType);
        out->data = apex_msg->value;
        return out;
    }
};

APEXRosInterface::APEXRosInterface()
    : core_(nullptr), disabled_(false)
{
    last_clock_ = ros::Time(0);
}

APEXRosInterface::~APEXRosInterface()
{
}

void APEXRosInterface::prepare(Settings &settings)
{
    ROSHandler::createInstance(settings);
}

void APEXRosInterface::init(CsApexCore &core)
{
    core_ = &core;

    ROSHandler::instance().registerConnectionCallback([this]() {
        registerCommandListener();
        registerClockWatchdog();
    });

    RosMessageConversion::registerConversion<std_msgs::Bool, connection_types::GenericValueMessage<bool>, ConvertIntegral<std_msgs::Bool, bool> >();
    RosMessageConversion::registerConversion<std_msgs::Int32, connection_types::GenericValueMessage<int>, ConvertIntegral<std_msgs::Int32, int> >();
    RosMessageConversion::registerConversion<std_msgs::Float64, connection_types::GenericValueMessage<double>, ConvertIntegral<std_msgs::Float64, double> >();
    RosMessageConversion::registerConversion<std_msgs::String, connection_types::GenericValueMessage<std::string>, ConvertIntegral<std_msgs::String, std::string> >();

    core_->loaded.connect([this](){
        if(ROSHandler::instance().isConnected()) {
            XmlRpc::XmlRpcValue params, result, payload;
            params[0] = ros::this_node::getName();

            std::string prefix = ros::this_node::getName();

            if (ros::master::execute("getParamNames", params, result, payload, true)) {
                if(result.getType() != XmlRpc::XmlRpcValue::TypeArray) {
                    return;
                }

                std::string name = result[1];
                if(name != "Parameter names") {
                    return;
                }

                XmlRpc::XmlRpcValue data = result[2];
                for(std::size_t i = 0, total = data.size(); i < total; ++i) {
                    std::string parameter_name = data[i];

                    if(parameter_name.substr(0, prefix.size()) != prefix) {
                        continue;
                    }

                    try {
                        XmlRpc::XmlRpcValue parameter_value;
                        ros::param::getCached(parameter_name, parameter_value);

                        loadParameterValue(prefix, parameter_name, parameter_value);
                    } catch (std::exception e) {
                        // silence
                    }
                }
            }
        }
    });
}

void APEXRosInterface::setupGraph(Graph *graph)
{
    clock_reset_event_ = graph->createInternalEvent(connection_types::makeEmpty<connection_types::AnyMessage>(), graph->makeUUID("event_ros_time_reset"), "ros time reset");
}

void APEXRosInterface::loadParameterValue(const std::string& prefix, const std::string& parameter_name, const XmlRpc::XmlRpcValue& parameter_value)
{
    std::string apex_name = parameter_name.substr(prefix.size());

    Graph* graph = core_->getRoot()->getGraph();

    std::vector<std::string> levels;

    std::cerr << "analyzing parameter " << parameter_name << std::endl;

    std::size_t delim = 0;
    while(delim != std::string::npos) {
        delim = apex_name.find('/');
        std::string subname = apex_name.substr(0, delim);
        if(!subname.empty()) {
            levels.push_back(subname);
        }
        apex_name = apex_name.substr(delim+1);
    }

    if(levels.empty()) {
        return;
    }

    NodeHandle* nh = nullptr;
    std::string param_name;
    for(std::size_t i = 0, n = levels.size(); i < n - 1; ++i) {
        const std::string subname = levels.at(i);
        std::cerr << "searching for " << subname << std::endl;
        nh = graph->findNodeHandleWithLabel(subname);
        if(!nh) {
            std::cerr << "no parameter for " << parameter_name << ", label " << subname << " non-existent" << std::endl;
            return;
        }

        if (NodePtr node = nh->getNode().lock()) {
            std::ostringstream param_name_builder;
            std::copy(std::next(levels.begin(), i + 1), levels.end(), std::ostream_iterator<std::string>(param_name_builder, "/"));
            param_name = param_name_builder.str();
            param_name = param_name.substr(0, param_name.size() - 1);

            std::cerr << "searching for param " << param_name << " in node " << node->getUUID() << std::endl;
            if (node->hasParameter(param_name))
                break;
            boost::algorithm::replace_all(param_name, " ", "_");
            std::cerr << "searching for param " << param_name << " (fallback)" << std::endl;
            if (node->hasParameter(param_name))
                break;
        }
        if(i < n - 2) {
            graph = dynamic_cast<Graph*>(nh->getNode().lock().get());
            if(!graph) {
                std::cerr << "no parameter for " << parameter_name << ", child " << subname << " is not a graph" << std::endl;
                return;
            }
        }

    }
    std::cerr << "found parameter " << param_name << std::endl;
    if(!nh) {
        std::cerr << "cannot set parameter " << param_name << ", no node handle exists" << std::endl;
        return;
    }

    NodePtr node = nh->getNode().lock();
    if(!node) {
        std::cerr << "cannot set parameter " << param_name << ", no node exists" << std::endl;
        return;
    }

    if(!node->hasParameter(param_name)) {
        std::cerr << "node " << nh->getUUID() << " doesn't have a parameter called " << param_name << std::endl;
        return;
    }

    param::ParameterPtr p = node->getMappedParameter(param_name);

    switch(parameter_value.getType()) {
    case XmlRpc::XmlRpcValue::TypeInt: {
        int val;
        ros::param::get(parameter_name, val);
        std::cerr << "setting int parameter for " << nh->getUUID() << ":" << param_name << std::endl;
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeDouble: {
        double val;
        ros::param::get(parameter_name, val);
        std::cerr << "setting double parameter for " << nh->getUUID() << ":" << param_name << std::endl;
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeBoolean: {
        bool val;
        ros::param::get(parameter_name, val);
        std::cerr << "setting bool parameter for " << nh->getUUID() << ":" << param_name << std::endl;
        p->set(val);
    }
        break;
    case XmlRpc::XmlRpcValue::TypeString: {
        std::string val;
        ros::param::get(parameter_name, val);
        std::cerr << "setting string parameter for " << nh->getUUID() << ":" << param_name << std::endl;
        p->set(val);
    }
        break;

    default:
        std::cerr << "cannot set parameter for " << nh->getUUID() << ":" << param_name  << " is of unknown type " << (int) parameter_value.getType() << std::endl;
        break;
    }
}

void APEXRosInterface::registerCommandListener()
{
    assert(ROSHandler::instance().isConnected());
    global_command_sub_ = ROSHandler::instance().nh()->subscribe
            <std_msgs::String>("/syscommand", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, true));
    private_command_sub_ = ROSHandler::instance().nh()->subscribe
            <std_msgs::String>("command", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, false));

    ros::spinOnce();
}

void APEXRosInterface::command(const std_msgs::StringConstPtr& cmd, bool global_cmd)
{
    std::string command = cmd->data;
    bool local_cmd = !global_cmd;

    /*
     * pause / unpause:
     *   - temporary disable everything to conserve computational power
     *   - globally accepted, if this node is not disabled
     *
     * stop / resume
     *   - completely disable / enable this subsystem, when it is not needed
     *   - only locally accepted
     *   - overwrites pause -> a disabled instance cannot be unpaused
     */

    if(!disabled_) {
        // disabled state is stronger than pause / unpause
        if(command == "pause") {
            core_->setPause(true);

        } else if(command == "unpause"){
            core_->setPause(false);
        }
    }

    if(local_cmd) {
        if(command == "stop") {
            disabled_ = true;
            core_->setPause(true);
        } else if(command == "resume") {
            disabled_ = false;
            core_->setPause(false);
        }
    }
}

void APEXRosInterface::registerClockWatchdog()
{
    clock_sub_ = ROSHandler::instance().nh()->subscribe
            <rosgraph_msgs::Clock>("/clock", 10, std::bind(&APEXRosInterface::clock, this, std::placeholders::_1));
}

void APEXRosInterface::clock(const rosgraph_msgs::ClockConstPtr &clock)
{
    ros::Time now = clock->clock;
    if(now < last_clock_) {
        std::cerr << "time reset" << std::endl;

        TokenDataConstPtr data(new connection_types::AnyMessage);
        TokenPtr token = std::make_shared<Token>(data);
        token->setActive(true);
        clock_reset_event_->triggerWith(token);
    }

    last_clock_ = now;
}

void APEXRosInterface::shutdown()
{
    ROSHandler::instance().stop();

    RosMessageConversion::instance().shutdown();
}
<|endoftext|>


<commit_before> /*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
 */

#include "pcl/gpu/containers/device_memory.hpp"
#include "cuda_runtime_api.h"
#include "assert.h"

//temporary dependence, should eliminated in future
//Replace with THROW_PCL_EXCEPTION from PCL2.0 API
#include "pcl/gpu/utils/safe_call.hpp"

#define HAVE_CUDA
//#include "pcl_config.h"

#if !defined(HAVE_CUDA)

void throw_nogpu() { throw "PCL 2.0 exception"; }

pcl::gpu::DeviceMemory::DeviceMemory() { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(void *, size_t) { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(size_t) { throw_nogpu(); }
pcl::gpu::DeviceMemory::~DeviceMemory() { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& ) { throw_nogpu(); }
pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator=(const pcl::gpu::DeviceMemory&) { throw_nogpu(); return *this;}
void pcl::gpu::DeviceMemory::create(size_t) { throw_nogpu(); }
void pcl::gpu::DeviceMemory::release() { throw_nogpu(); }
void pcl::gpu::DeviceMemory::copyTo(DeviceMemory&) const { throw_nogpu(); }
void pcl::gpu::DeviceMemory::upload(const void*, size_t) { throw_nogpu(); }
void pcl::gpu::DeviceMemory::download(void*) const { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D() { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int, void*, size_t)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D&)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator=(const pcl::gpu::DeviceMemory2D&) { throw_nogpu(); return *this;}
void pcl::gpu::DeviceMemory2D::create(int, int )  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::release()  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D&) const  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::upload(const void *, size_t, int, int )  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::download(void *, size_t ) const  { throw_nogpu(); }

#else

//////////////////////////    XADD    ///////////////////////////////

#ifdef __GNUC__

    #if __GNUC__*10 + __GNUC_MINOR__ >= 42

        #if !defined WIN32 && (defined __i486__ || defined __i586__ || defined __i686__ || defined __MMX__ || defined __SSE__  || defined __ppc__)
            #define CV_XADD __sync_fetch_and_add
        #else
            #include <ext/atomicity.h>
            #define CV_XADD __gnu_cxx::__exchange_and_add
        #endif
    #else
        #include <bits/atomicity.h>
        #if __GNUC__*10 + __GNUC_MINOR__ >= 34
            #define CV_XADD __gnu_cxx::__exchange_and_add
        #else
            #define CV_XADD __exchange_and_add
        #endif
  #endif

#elif defined WIN32 || defined _WIN32
    #include <intrin.h>
    #define CV_XADD(addr,delta) _InterlockedExchangeAdd((long volatile*)(addr), (delta))
#else

    template<typename _Tp> static inline _Tp CV_XADD(_Tp* addr, _Tp delta)
    { int tmp = *addr; *addr += delta; return tmp; }

#endif

////////////////////////    DeviceArray    /////////////////////////////

pcl::gpu::DeviceMemory::DeviceMemory() : data(0), sizeBytes(0), refcount(0) {}
pcl::gpu::DeviceMemory::DeviceMemory(void *ptr_arg, size_t sizeBytes_arg) : data((char*)ptr_arg), sizeBytes(sizeBytes_arg), refcount(0){}
pcl::gpu::DeviceMemory::DeviceMemory(size_t sizeBtes_arg)  : data(0), sizeBytes(0), refcount(0) { create(sizeBtes_arg); }
pcl::gpu::DeviceMemory::~DeviceMemory() { release(); }

pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& other_arg)
    : data(other_arg.data), sizeBytes(other_arg.sizeBytes), refcount(other_arg.refcount)
{
    if( refcount )
        CV_XADD(refcount, 1);
}

pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator = (const pcl::gpu::DeviceMemory& other_arg)
{
    if( this != &other_arg )
    {
        if( other_arg.refcount )
            CV_XADD(other_arg.refcount, 1);
        release();

        data      = other_arg.data;
        sizeBytes = other_arg.sizeBytes;
        refcount  = other_arg.refcount;
    }
    return *this;
}

void pcl::gpu::DeviceMemory::create(size_t sizeBytes_arg)
{
    if (sizeBytes_arg == sizeBytes)
        return;

    if( sizeBytes_arg > 0)
    {
        if( data )
            release();

        sizeBytes = sizeBytes_arg;

        cudaSafeCall( cudaMalloc((void**)&data, sizeBytes) );

        //refcount_ = (int*)cv::fastMalloc(sizeof(*refcount_));
        refcount = new int;
        *refcount = 1;
    }
}

void pcl::gpu::DeviceMemory::copyTo(DeviceMemory& other) const
{
    assert(!this.data);

    other.create(sizeBytes);
    cudaSafeCall( cudaMemcpy(other.data, data, sizeBytes, cudaMemcpyDeviceToDevice) );
    cudaSafeCall( cudaDeviceSynchronize() );
}

void pcl::gpu::DeviceMemory::release()
{
    if( refcount && CV_XADD(refcount, -1) == 1 )
    {
        //cv::fastFree(refcount);
        delete refcount;
        cudaSafeCall( cudaFree(data) );
    }
    data = 0;
    sizeBytes = 0;
    refcount = 0;
}

void pcl::gpu::DeviceMemory::upload(const void *host_ptr_arg, size_t sizeBytes_arg)
{
    create(sizeBytes_arg);
    cudaSafeCall( cudaMemcpy(data, host_ptr_arg, sizeBytes, cudaMemcpyHostToDevice) );
}

void pcl::gpu::DeviceMemory::download(void *host_ptr_arg) const
{
    cudaSafeCall( cudaMemcpy(host_ptr_arg, data, sizeBytes, cudaMemcpyDeviceToHost) );
}

////////////////////////    DeviceArray2D    /////////////////////////////

pcl::gpu::DeviceMemory2D::DeviceMemory2D() : colsBytes(0), rows(0), data(0), step(0), refcount(0) {}

pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg)
    : colsBytes(0), rows(0), data(0), step(0), refcount(0)
{
    create(rows_arg, colsBytes_arg);
}

pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg, void *data_arg, size_t step_arg)
    : colsBytes(colsBytes_arg), rows(rows_arg), data((char*)data_arg), step(step_arg), refcount(0) {}

pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { release(); }

pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D& other_arg) :
    colsBytes(other_arg.colsBytes), rows(other_arg.rows), data(other_arg.data), step(other_arg.step), refcount(other_arg.refcount)
{
    if( refcount )
        CV_XADD(refcount, 1);
}

pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator = (const pcl::gpu::DeviceMemory2D& other_arg)
{
    if( this != &other_arg )
    {
        if( other_arg.refcount )
            CV_XADD(other_arg.refcount, 1);
        release();

        colsBytes = other_arg.colsBytes;
        rows = other_arg.rows;
        data = other_arg.data;
        step = other_arg.step;

        refcount = other_arg.refcount;
    }
    return *this;
}

void pcl::gpu::DeviceMemory2D::create(int rows_arg, int colsBytes_arg)
{
    if (colsBytes == colsBytes_arg && rows == rows_arg)
        return;

    if( rows_arg > 0 && colsBytes_arg > 0)
    {
        if( data )
            release();

        colsBytes = colsBytes_arg;
        rows = rows_arg;

        cudaSafeCall( cudaMallocPitch( (void**)&data, &step, colsBytes, rows) );

        //refcount = (int*)cv::fastMalloc(sizeof(*refcount));
        refcount = new int;
        *refcount = 1;
    }
}

void pcl::gpu::DeviceMemory2D::release()
{
    if( refcount && CV_XADD(refcount, -1) == 1 )
    {
        //cv::fastFree(refcount);
        delete refcount;
        cudaSafeCall( cudaFree(data) );
    }

    colsBytes = 0;
    rows = 0;
    data = 0;
    step = 0;
    refcount = 0;
}

void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D& other) const
{
    assert(!this.data);
    other.create(rows, colsBytes);
    cudaSafeCall( cudaMemcpy2D(other.data, other.step, data, step, colsBytes, rows, cudaMemcpyDeviceToDevice) );
    cudaSafeCall( cudaDeviceSynchronize() );
}

void pcl::gpu::DeviceMemory2D::upload(const void *host_ptr_arg, size_t host_step_arg, int rows_arg, int colsBytes_arg)
{
    create(rows_arg, colsBytes_arg);
    cudaSafeCall( cudaMemcpy2D(data, step, host_ptr_arg, host_step_arg, colsBytes, rows, cudaMemcpyHostToDevice) );
}

void pcl::gpu::DeviceMemory2D::download(void *host_ptr_arg, size_t host_step_arg) const
{
    cudaSafeCall( cudaMemcpy2D(host_ptr_arg, host_step_arg, data, step, colsBytes, rows, cudaMemcpyDeviceToHost) );
}

#endif<commit_msg>misprint(compilation)<commit_after> /*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
 */

#include "pcl/gpu/containers/device_memory.hpp"
#include "cuda_runtime_api.h"
#include "assert.h"

//temporary dependence, should eliminated in future
//Replace with THROW_PCL_EXCEPTION from PCL2.0 API
#include "pcl/gpu/utils/safe_call.hpp"

#define HAVE_CUDA
//#include "pcl_config.h"

#if !defined(HAVE_CUDA)

void throw_nogpu() { throw "PCL 2.0 exception"; }

pcl::gpu::DeviceMemory::DeviceMemory() { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(void *, size_t) { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(size_t) { throw_nogpu(); }
pcl::gpu::DeviceMemory::~DeviceMemory() { throw_nogpu(); }
pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& ) { throw_nogpu(); }
pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator=(const pcl::gpu::DeviceMemory&) { throw_nogpu(); return *this;}
void pcl::gpu::DeviceMemory::create(size_t) { throw_nogpu(); }
void pcl::gpu::DeviceMemory::release() { throw_nogpu(); }
void pcl::gpu::DeviceMemory::copyTo(DeviceMemory&) const { throw_nogpu(); }
void pcl::gpu::DeviceMemory::upload(const void*, size_t) { throw_nogpu(); }
void pcl::gpu::DeviceMemory::download(void*) const { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D() { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int, void*, size_t)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { throw_nogpu(); }
pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D&)  { throw_nogpu(); }
pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator=(const pcl::gpu::DeviceMemory2D&) { throw_nogpu(); return *this;}
void pcl::gpu::DeviceMemory2D::create(int, int )  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::release()  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D&) const  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::upload(const void *, size_t, int, int )  { throw_nogpu(); }
void pcl::gpu::DeviceMemory2D::download(void *, size_t ) const  { throw_nogpu(); }

#else

//////////////////////////    XADD    ///////////////////////////////

#ifdef __GNUC__

    #if __GNUC__*10 + __GNUC_MINOR__ >= 42

        #if !defined WIN32 && (defined __i486__ || defined __i586__ || defined __i686__ || defined __MMX__ || defined __SSE__  || defined __ppc__)
            #define CV_XADD __sync_fetch_and_add
        #else
            #include <ext/atomicity.h>
            #define CV_XADD __gnu_cxx::__exchange_and_add
        #endif
    #else
        #include <bits/atomicity.h>
        #if __GNUC__*10 + __GNUC_MINOR__ >= 34
            #define CV_XADD __gnu_cxx::__exchange_and_add
        #else
            #define CV_XADD __exchange_and_add
        #endif
  #endif

#elif defined WIN32 || defined _WIN32
    #include <intrin.h>
    #define CV_XADD(addr,delta) _InterlockedExchangeAdd((long volatile*)(addr), (delta))
#else

    template<typename _Tp> static inline _Tp CV_XADD(_Tp* addr, _Tp delta)
    { int tmp = *addr; *addr += delta; return tmp; }

#endif

////////////////////////    DeviceArray    /////////////////////////////

pcl::gpu::DeviceMemory::DeviceMemory() : data(0), sizeBytes(0), refcount(0) {}
pcl::gpu::DeviceMemory::DeviceMemory(void *ptr_arg, size_t sizeBytes_arg) : data((char*)ptr_arg), sizeBytes(sizeBytes_arg), refcount(0){}
pcl::gpu::DeviceMemory::DeviceMemory(size_t sizeBtes_arg)  : data(0), sizeBytes(0), refcount(0) { create(sizeBtes_arg); }
pcl::gpu::DeviceMemory::~DeviceMemory() { release(); }

pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& other_arg)
    : data(other_arg.data), sizeBytes(other_arg.sizeBytes), refcount(other_arg.refcount)
{
    if( refcount )
        CV_XADD(refcount, 1);
}

pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator = (const pcl::gpu::DeviceMemory& other_arg)
{
    if( this != &other_arg )
    {
        if( other_arg.refcount )
            CV_XADD(other_arg.refcount, 1);
        release();

        data      = other_arg.data;
        sizeBytes = other_arg.sizeBytes;
        refcount  = other_arg.refcount;
    }
    return *this;
}

void pcl::gpu::DeviceMemory::create(size_t sizeBytes_arg)
{
    if (sizeBytes_arg == sizeBytes)
        return;

    if( sizeBytes_arg > 0)
    {
        if( data )
            release();

        sizeBytes = sizeBytes_arg;

        cudaSafeCall( cudaMalloc((void**)&data, sizeBytes) );

        //refcount_ = (int*)cv::fastMalloc(sizeof(*refcount_));
        refcount = new int;
        *refcount = 1;
    }
}

void pcl::gpu::DeviceMemory::copyTo(DeviceMemory& other) const
{
    assert(data);

    other.create(sizeBytes);
    cudaSafeCall( cudaMemcpy(other.data, data, sizeBytes, cudaMemcpyDeviceToDevice) );
    cudaSafeCall( cudaDeviceSynchronize() );
}

void pcl::gpu::DeviceMemory::release()
{
    if( refcount && CV_XADD(refcount, -1) == 1 )
    {
        //cv::fastFree(refcount);
        delete refcount;
        cudaSafeCall( cudaFree(data) );
    }
    data = 0;
    sizeBytes = 0;
    refcount = 0;
}

void pcl::gpu::DeviceMemory::upload(const void *host_ptr_arg, size_t sizeBytes_arg)
{
    create(sizeBytes_arg);
    cudaSafeCall( cudaMemcpy(data, host_ptr_arg, sizeBytes, cudaMemcpyHostToDevice) );
}

void pcl::gpu::DeviceMemory::download(void *host_ptr_arg) const
{
    cudaSafeCall( cudaMemcpy(host_ptr_arg, data, sizeBytes, cudaMemcpyDeviceToHost) );
}

////////////////////////    DeviceArray2D    /////////////////////////////

pcl::gpu::DeviceMemory2D::DeviceMemory2D() : colsBytes(0), rows(0), data(0), step(0), refcount(0) {}

pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg)
    : colsBytes(0), rows(0), data(0), step(0), refcount(0)
{
    create(rows_arg, colsBytes_arg);
}

pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg, void *data_arg, size_t step_arg)
    : colsBytes(colsBytes_arg), rows(rows_arg), data((char*)data_arg), step(step_arg), refcount(0) {}

pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { release(); }

pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D& other_arg) :
    colsBytes(other_arg.colsBytes), rows(other_arg.rows), data(other_arg.data), step(other_arg.step), refcount(other_arg.refcount)
{
    if( refcount )
        CV_XADD(refcount, 1);
}

pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator = (const pcl::gpu::DeviceMemory2D& other_arg)
{
    if( this != &other_arg )
    {
        if( other_arg.refcount )
            CV_XADD(other_arg.refcount, 1);
        release();

        colsBytes = other_arg.colsBytes;
        rows = other_arg.rows;
        data = other_arg.data;
        step = other_arg.step;

        refcount = other_arg.refcount;
    }
    return *this;
}

void pcl::gpu::DeviceMemory2D::create(int rows_arg, int colsBytes_arg)
{
    if (colsBytes == colsBytes_arg && rows == rows_arg)
        return;

    if( rows_arg > 0 && colsBytes_arg > 0)
    {
        if( data )
            release();

        colsBytes = colsBytes_arg;
        rows = rows_arg;

        cudaSafeCall( cudaMallocPitch( (void**)&data, &step, colsBytes, rows) );

        //refcount = (int*)cv::fastMalloc(sizeof(*refcount));
        refcount = new int;
        *refcount = 1;
    }
}

void pcl::gpu::DeviceMemory2D::release()
{
    if( refcount && CV_XADD(refcount, -1) == 1 )
    {
        //cv::fastFree(refcount);
        delete refcount;
        cudaSafeCall( cudaFree(data) );
    }

    colsBytes = 0;
    rows = 0;
    data = 0;
    step = 0;
    refcount = 0;
}

void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D& other) const
{
    assert(data);
    other.create(rows, colsBytes);
    cudaSafeCall( cudaMemcpy2D(other.data, other.step, data, step, colsBytes, rows, cudaMemcpyDeviceToDevice) );
    cudaSafeCall( cudaDeviceSynchronize() );
}

void pcl::gpu::DeviceMemory2D::upload(const void *host_ptr_arg, size_t host_step_arg, int rows_arg, int colsBytes_arg)
{
    create(rows_arg, colsBytes_arg);
    cudaSafeCall( cudaMemcpy2D(data, step, host_ptr_arg, host_step_arg, colsBytes, rows, cudaMemcpyHostToDevice) );
}

void pcl::gpu::DeviceMemory2D::download(void *host_ptr_arg, size_t host_step_arg) const
{
    cudaSafeCall( cudaMemcpy2D(host_ptr_arg, host_step_arg, data, step, colsBytes, rows, cudaMemcpyDeviceToHost) );
}

#endif<|endoftext|>


<commit_before>#include <Salamandre-daemon/Daemon.hpp>

#include <iostream>
#include <csignal>

#define GUI_PORT 1
#define SERVER_PORT 2
#define NB_ARGS (SERVER_PORT + 1)

salamandre::Daemon* server = nullptr;

void stop_server_handler(int sig)
{
    std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl;
    if(server)
        server->stop();
}

int main(int argc,char* argv[])
{
    int gui_port = 3842;
    int server_port = 3843;

    if(argc < NB_ARGS)
    {
        std::cout<<"Usage is:\n\t"<<argv[0]<<"<gui port> <server port>"<<std::endl;
        if(argc <= GUI_PORT)
            std::cout<<"Use "<<gui_port<<"as default gui port"<<std::endl;
        if(argc <= SERVER_PORT)
            std::cout<<"Use "<<server_port<<"as default server port"<<std::endl;
    }
    if(argc > GUI_PORT)
        gui_port = atoi(argv[GUI_PORT]);
    if(argc > SERVER_PORT)
        server_port = atoi(argv[SERVER_PORT]);

    std::cout<<"Daemon start on:"
        <<"\n\tgui port : "<<gui_port
        <<"\n\tfile server port : "<<server_port
        <<"\nPress ^C to exit"
        <<std::endl;
    std::signal(SIGINT, stop_server_handler);

    try
    {

        ntw::Socket::init();

        server = new salamandre::Daemon(gui_port,server_port);
        server->start();
        server->wait();

        delete server;
        server = nullptr;

        ntw::Socket::close();
    }
    catch(ntw::SocketExeption& e)
    {
        std::cout<<e.what()<<std::endl;
    }

    std::cout<<"Daemon is now close. Good bye"<<std::endl;

    return 0;
}
<commit_msg>add base files<commit_after>#include <Salamandre-daemon/Daemon.hpp>

#include <iostream>
#include <csignal>

#define GUI_PORT 1
#define SERVER_PORT 2
#define NB_ARGS (SERVER_PORT + 1)

salamandre::Daemon* server = nullptr;

void stop_server_handler(int sig)
{
    std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl;
    if(server)
        server->stop();
}

int main(int argc,char* argv[])
{
    int gui_port = 3842;
    int server_port = 3843;

    if(argc < NB_ARGS)
    {
        std::cout<<"Usage is:\n\t"<<argv[0]<<"<gui port> <server port>"<<std::endl;
        if(argc <= GUI_PORT)
            std::cout<<"Use "<<gui_port<<"as default gui port"<<std::endl;
        if(argc <= SERVER_PORT)
            std::cout<<"Use "<<server_port<<"as default server port"<<std::endl;
    }
    if(argc > GUI_PORT)
        gui_port = atoi(argv[GUI_PORT]);
    if(argc > SERVER_PORT)
        server_port = atoi(argv[SERVER_PORT]);

    std::cout<<"Daemon start on:"
        <<"\n\tgui port : "<<gui_port
        <<"\n\tfile server port : "<<server_port
        <<"\nPress ^C to exit"
        <<std::endl<<std::endl;
    std::signal(SIGINT, stop_server_handler);

    try
    {

        ntw::Socket::init();

        server = new salamandre::Daemon(gui_port,server_port);
        server->start();
        server->wait();

        delete server;
        server = nullptr;

        ntw::Socket::close();
    }
    catch(ntw::SocketExeption& e)
    {
        std::cout<<e.what()<<std::endl;
    }

    std::cout<<"Daemon is now close. Good bye"<<std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 "Actor.h"
#include "Vector3.h"
#include "Quaternion.h"
#include "Matrix4x4.h"
#include "Unit.h"
#include "Device.h"
#include "Physics.h"
#include "Log.h"
#include "SceneGraph.h"
#include "PxPhysicsAPI.h"

using physx::PxRigidDynamicFlag;
using physx::PxMat44;
using physx::PxTransform;
using physx::PxActorFlag;
using physx::PxVec3;
using physx::PxReal;
using physx::PxRigidBody;
using physx::PxRigidDynamic;
using physx::PxPlaneGeometry;
using physx::PxSphereGeometry;
using physx::PxBoxGeometry;
using physx::PxRigidBodyExt;

using physx::PxD6Joint;
using physx::PxD6JointCreate;
using physx::PxD6Axis;
using physx::PxD6Motion;

namespace crown
{

//-----------------------------------------------------------------------------
Actor::Actor(PxScene* scene, SceneGraph& sg, int32_t node, ActorType::Enum type, const Vector3& pos, const Quaternion& rot)
	: m_scene(scene)
	, m_scene_graph(sg)
	, m_node(node)
	, m_type(type)
{
	Matrix4x4 m(rot, pos);
	m.transpose();
	PxMat44 pose((PxReal*)(m.to_float_ptr()));

	switch (type)
	{
		case ActorType::STATIC:
		{
			m_actor = device()->physx()->createRigidStatic(PxTransform(pose));
			break;
		}
		case ActorType::DYNAMIC_PHYSICAL:
		case ActorType::DYNAMIC_KINEMATIC:
		{
			m_actor = device()->physx()->createRigidDynamic(PxTransform(pose));

			if (type == ActorType::DYNAMIC_KINEMATIC)
			{
				static_cast<PxRigidDynamic*>(m_actor)->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);
			}
			break;
		}
		default:
		{
			CE_FATAL("Oops, unknown actor type");
			break;
		}
	}

	m_actor->userData = this;
	m_mat = device()->physx()->createMaterial(0.5f, 0.5f, 0.5f);

	create_box(Vector3(0, 0, 0), .5, .5, .5);

	PxRigidBodyExt::setMassAndUpdateInertia(*static_cast<PxRigidDynamic*>(m_actor), 500.0f);

	PxD6Joint* joint = PxD6JointCreate(*device()->physx(), m_actor, PxTransform(pose), NULL, PxTransform(pose));
	joint->setMotion(PxD6Axis::eX, PxD6Motion::eFREE);
	joint->setMotion(PxD6Axis::eY, PxD6Motion::eFREE);
	//joint->setMotion(PxD6Axis::eZ, PxD6Motion::eFREE);
	//joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE);
	joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE);

	m_scene->addActor(*m_actor);
}

//-----------------------------------------------------------------------------
Actor::~Actor()
{
	if (m_actor)
	{
		m_scene->removeActor(*m_actor);
		m_actor->release();
	}
}

//-----------------------------------------------------------------------------
void Actor::create_sphere(const Vector3& position, float radius)
{
	m_actor->createShape(PxSphereGeometry(radius), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::create_box(const Vector3& position, float a, float b, float c)
{
	m_actor->createShape(PxBoxGeometry(a, b, c), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::create_plane(const Vector3& /*position*/, const Vector3& /*normal*/)
{
	m_actor->createShape(PxPlaneGeometry(), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::enable_gravity()
{
	m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, false);
}

//-----------------------------------------------------------------------------
void Actor::disable_gravity()
{
	m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
}

//-----------------------------------------------------------------------------
bool Actor::is_static() const
{
	return m_type == ActorType::STATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_dynamic() const
{
	return m_type == ActorType::DYNAMIC_PHYSICAL || m_type == ActorType::DYNAMIC_KINEMATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_kinematic() const
{
	return m_type == ActorType::DYNAMIC_KINEMATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_physical() const
{
	return m_type == ActorType::DYNAMIC_PHYSICAL;
}

//-----------------------------------------------------------------------------
float Actor::linear_damping() const
{
	return ((PxRigidDynamic*)m_actor)->getLinearDamping();
}

//-----------------------------------------------------------------------------
void Actor::set_linear_damping(float rate)
{
	((PxRigidDynamic*)m_actor)->setLinearDamping(rate);
}

//-----------------------------------------------------------------------------
float Actor::angular_damping() const
{
	return ((PxRigidDynamic*)m_actor)->getAngularDamping();
}

//-----------------------------------------------------------------------------
void Actor::set_angular_damping(float rate)
{
	((PxRigidDynamic*)m_actor)->setAngularDamping(rate);
}

//-----------------------------------------------------------------------------
Vector3 Actor::linear_velocity() const
{
	PxVec3 vel = ((PxRigidBody*)m_actor)->getLinearVelocity();
	Vector3 velocity(vel.x, vel.y, vel.z);
	return velocity;
}

//-----------------------------------------------------------------------------
void Actor::set_linear_velocity(const Vector3& vel)
{
	PxVec3 velocity(vel.x, vel.y, vel.z);
	((PxRigidBody*)m_actor)->setLinearVelocity(velocity);
}

//-----------------------------------------------------------------------------
Vector3 Actor::angular_velocity() const
{
	PxVec3 vel = ((PxRigidBody*)m_actor)->getAngularVelocity();
	Vector3 velocity(vel.x, vel.y, vel.z);
	return velocity;
}

//-----------------------------------------------------------------------------
void Actor::set_angular_velocity(const Vector3& vel)
{
	PxVec3 velocity(vel.x, vel.y, vel.z);
	((PxRigidBody*)m_actor)->setAngularVelocity(velocity);
}

//-----------------------------------------------------------------------------
bool Actor::is_sleeping()
{
	return ((PxRigidDynamic*)m_actor)->isSleeping();
}

//-----------------------------------------------------------------------------
void Actor::wake_up()
{
	((PxRigidDynamic*)m_actor)->wakeUp();
}

//-----------------------------------------------------------------------------
void Actor::update_pose()
{
	// Read world pose
	Matrix4x4 wp = m_scene_graph.world_pose(m_node);
	Matrix4x4 a = wp;
	const PxMat44 pose((PxReal*) (wp.to_float_ptr()));
	const PxTransform world_transform(pose);

	switch (m_type)
	{
		case ActorType::DYNAMIC_KINEMATIC:
		{
			static_cast<PxRigidDynamic*>(m_actor)->setKinematicTarget(world_transform);
			break;
		}
		default: break;
	}
}

//-----------------------------------------------------------------------------
void Actor::update(const Matrix4x4& pose)
{
	if (m_type == ActorType::DYNAMIC_PHYSICAL)
	{
		m_scene_graph.set_world_pose(m_node, pose);
	}
}

} // namespace crown<commit_msg>Remove unused variable<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 "Actor.h"
#include "Vector3.h"
#include "Quaternion.h"
#include "Matrix4x4.h"
#include "Unit.h"
#include "Device.h"
#include "Physics.h"
#include "Log.h"
#include "SceneGraph.h"
#include "PxPhysicsAPI.h"

using physx::PxRigidDynamicFlag;
using physx::PxMat44;
using physx::PxTransform;
using physx::PxActorFlag;
using physx::PxVec3;
using physx::PxReal;
using physx::PxRigidBody;
using physx::PxRigidDynamic;
using physx::PxPlaneGeometry;
using physx::PxSphereGeometry;
using physx::PxBoxGeometry;
using physx::PxRigidBodyExt;

using physx::PxD6Joint;
using physx::PxD6JointCreate;
using physx::PxD6Axis;
using physx::PxD6Motion;

namespace crown
{

//-----------------------------------------------------------------------------
Actor::Actor(PxScene* scene, SceneGraph& sg, int32_t node, ActorType::Enum type, const Vector3& pos, const Quaternion& rot)
	: m_scene(scene)
	, m_scene_graph(sg)
	, m_node(node)
	, m_type(type)
{
	Matrix4x4 m(rot, pos);
	m.transpose();
	PxMat44 pose((PxReal*)(m.to_float_ptr()));

	switch (type)
	{
		case ActorType::STATIC:
		{
			m_actor = device()->physx()->createRigidStatic(PxTransform(pose));
			break;
		}
		case ActorType::DYNAMIC_PHYSICAL:
		case ActorType::DYNAMIC_KINEMATIC:
		{
			m_actor = device()->physx()->createRigidDynamic(PxTransform(pose));

			if (type == ActorType::DYNAMIC_KINEMATIC)
			{
				static_cast<PxRigidDynamic*>(m_actor)->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true);
			}
			break;
		}
		default:
		{
			CE_FATAL("Oops, unknown actor type");
			break;
		}
	}

	m_actor->userData = this;
	m_mat = device()->physx()->createMaterial(0.5f, 0.5f, 0.5f);

	create_box(Vector3(0, 0, 0), .5, .5, .5);

	PxRigidBodyExt::setMassAndUpdateInertia(*static_cast<PxRigidDynamic*>(m_actor), 500.0f);

	PxD6Joint* joint = PxD6JointCreate(*device()->physx(), m_actor, PxTransform(pose), NULL, PxTransform(pose));
	joint->setMotion(PxD6Axis::eX, PxD6Motion::eFREE);
	joint->setMotion(PxD6Axis::eY, PxD6Motion::eFREE);
	//joint->setMotion(PxD6Axis::eZ, PxD6Motion::eFREE);
	//joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE);
	joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE);

	m_scene->addActor(*m_actor);
}

//-----------------------------------------------------------------------------
Actor::~Actor()
{
	if (m_actor)
	{
		m_scene->removeActor(*m_actor);
		m_actor->release();
	}
}

//-----------------------------------------------------------------------------
void Actor::create_sphere(const Vector3& position, float radius)
{
	m_actor->createShape(PxSphereGeometry(radius), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::create_box(const Vector3& position, float a, float b, float c)
{
	m_actor->createShape(PxBoxGeometry(a, b, c), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::create_plane(const Vector3& /*position*/, const Vector3& /*normal*/)
{
	m_actor->createShape(PxPlaneGeometry(), *m_mat);
}

//-----------------------------------------------------------------------------
void Actor::enable_gravity()
{
	m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, false);
}

//-----------------------------------------------------------------------------
void Actor::disable_gravity()
{
	m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true);
}

//-----------------------------------------------------------------------------
bool Actor::is_static() const
{
	return m_type == ActorType::STATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_dynamic() const
{
	return m_type == ActorType::DYNAMIC_PHYSICAL || m_type == ActorType::DYNAMIC_KINEMATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_kinematic() const
{
	return m_type == ActorType::DYNAMIC_KINEMATIC;
}

//-----------------------------------------------------------------------------
bool Actor::is_physical() const
{
	return m_type == ActorType::DYNAMIC_PHYSICAL;
}

//-----------------------------------------------------------------------------
float Actor::linear_damping() const
{
	return ((PxRigidDynamic*)m_actor)->getLinearDamping();
}

//-----------------------------------------------------------------------------
void Actor::set_linear_damping(float rate)
{
	((PxRigidDynamic*)m_actor)->setLinearDamping(rate);
}

//-----------------------------------------------------------------------------
float Actor::angular_damping() const
{
	return ((PxRigidDynamic*)m_actor)->getAngularDamping();
}

//-----------------------------------------------------------------------------
void Actor::set_angular_damping(float rate)
{
	((PxRigidDynamic*)m_actor)->setAngularDamping(rate);
}

//-----------------------------------------------------------------------------
Vector3 Actor::linear_velocity() const
{
	PxVec3 vel = ((PxRigidBody*)m_actor)->getLinearVelocity();
	Vector3 velocity(vel.x, vel.y, vel.z);
	return velocity;
}

//-----------------------------------------------------------------------------
void Actor::set_linear_velocity(const Vector3& vel)
{
	PxVec3 velocity(vel.x, vel.y, vel.z);
	((PxRigidBody*)m_actor)->setLinearVelocity(velocity);
}

//-----------------------------------------------------------------------------
Vector3 Actor::angular_velocity() const
{
	PxVec3 vel = ((PxRigidBody*)m_actor)->getAngularVelocity();
	Vector3 velocity(vel.x, vel.y, vel.z);
	return velocity;
}

//-----------------------------------------------------------------------------
void Actor::set_angular_velocity(const Vector3& vel)
{
	PxVec3 velocity(vel.x, vel.y, vel.z);
	((PxRigidBody*)m_actor)->setAngularVelocity(velocity);
}

//-----------------------------------------------------------------------------
bool Actor::is_sleeping()
{
	return ((PxRigidDynamic*)m_actor)->isSleeping();
}

//-----------------------------------------------------------------------------
void Actor::wake_up()
{
	((PxRigidDynamic*)m_actor)->wakeUp();
}

//-----------------------------------------------------------------------------
void Actor::update_pose()
{
	// Read world pose
	Matrix4x4 wp = m_scene_graph.world_pose(m_node);
	const PxMat44 pose((PxReal*) (wp.to_float_ptr()));
	const PxTransform world_transform(pose);

	switch (m_type)
	{
		case ActorType::DYNAMIC_KINEMATIC:
		{
			static_cast<PxRigidDynamic*>(m_actor)->setKinematicTarget(world_transform);
			break;
		}
		default: break;
	}
}

//-----------------------------------------------------------------------------
void Actor::update(const Matrix4x4& pose)
{
	if (m_type == ActorType::DYNAMIC_PHYSICAL)
	{
		m_scene_graph.set_world_pose(m_node, pose);
	}
}

} // namespace crown<|endoftext|>


<commit_before>#include "engine/Engine.hpp"

#include <SDL2/SDL.h>

using namespace std;
using namespace glm;

Engine::Engine(int argc, char** argv) : _wnd(nullptr)
{
	for(int i = 0; i < argc; ++i)
		_args.push_back(string{argv[i]});
}

Engine::~Engine()
{ }

int Engine::run(Application* app)
{
	_running = true;
	_exit_code = 0;
	SDL_Init(SDL_INIT_VIDEO);

	SDL_DisplayMode ask_mode;
	ask_mode.format = SDL_PIXELFORMAT_RGBA8888;
	ask_mode.w = 1920;
	ask_mode.h = 1080;
	ask_mode.refresh_rate = 60;
	SDL_DisplayMode mode;
	SDL_GetClosestDisplayMode(0, &ask_mode, &mode);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
	_wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN);
	SDL_SetWindowDisplayMode(_wnd, &mode);
	SDL_GLContext ctx = SDL_GL_CreateContext(_wnd);
	SDL_GL_MakeCurrent(_wnd, ctx);

	gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress);

	auto fb_size = framebuffer_size();
	glViewport(0, 0, fb_size.x, fb_size.y);
	glClearColor(0.2f, 0.2f, 0.2f, 1.f);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	SDL_GL_SetSwapInterval(1);
	SDL_GL_SwapWindow(_wnd);

	app->initialize();

	TimePoint last_time{};
	Duration accumulator{};
	while(_running)
	{
		TimePoint new_time = Clock::now();
		Duration dT = new_time - last_time;
		last_time = new_time;
		accumulator += dT;

		SDL_Event e;
		while(SDL_PollEvent(&e))
		{
			if(e.type == SDL_WINDOWEVENT_CLOSE)
				_running = false;
			if(e.type == SDL_KEYUP)
				app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), false);
			if(e.type == SDL_KEYDOWN)
				app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), true);
			if(e.type == SDL_TEXTINPUT)
				app->keyboard_character_event(e.text.text);
			if(e.type == SDL_MOUSEMOTION)
				app->mouse_move_event({e.motion.xrel, e.motion.yrel});
			if(e.type == SDL_MOUSEBUTTONUP)
				app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), false);
			if(e.type == SDL_MOUSEBUTTONDOWN)
				app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), true);
			if(e.type == SDL_MOUSEWHEEL)
				app->scroll_event({e.wheel.x, e.wheel.y});
			if(e.type == SDL_WINDOWEVENT_RESIZED)
				app->resize_event(e.window.data1, e.window.data2);
		}

		if(accumulator >= app->fixed_time_step())
		{
			app->update(accumulator);
			accumulator = Duration{};
		}

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		app->frame_start();
		app->frame();
		app->frame_end();

		SDL_GL_SwapWindow(_wnd);
	}

	delete app;

	SDL_GL_DeleteContext(ctx);
	SDL_DestroyWindow(_wnd);
	_wnd = nullptr;

	SDL_Quit();
	return _exit_code;
}

glm::ivec2 Engine::framebuffer_size() const
{
	ivec2 ret;
	SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y);
	return ret;
}

glm::ivec2 Engine::window_size() const
{
	ivec2 ret;
	SDL_GetWindowSize(_wnd, &ret.x, &ret.y);
	return ret;
}
<commit_msg>Removed an if statement<commit_after>#include "engine/Engine.hpp"

#include <SDL2/SDL.h>

using namespace std;
using namespace glm;

Engine::Engine(int argc, char** argv) : _wnd(nullptr)
{
	for(int i = 0; i < argc; ++i)
		_args.push_back(string{argv[i]});
}

Engine::~Engine()
{ }

int Engine::run(Application* app)
{
	_running = true;
	_exit_code = 0;
	SDL_Init(SDL_INIT_VIDEO);

	SDL_DisplayMode ask_mode;
	ask_mode.format = SDL_PIXELFORMAT_RGBA8888;
	ask_mode.w = 1920;
	ask_mode.h = 1080;
	ask_mode.refresh_rate = 60;
	SDL_DisplayMode mode;
	SDL_GetClosestDisplayMode(0, &ask_mode, &mode);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
	_wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN);
	SDL_SetWindowDisplayMode(_wnd, &mode);
	SDL_GLContext ctx = SDL_GL_CreateContext(_wnd);
	SDL_GL_MakeCurrent(_wnd, ctx);

	gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress);

	auto fb_size = framebuffer_size();
	glViewport(0, 0, fb_size.x, fb_size.y);
	glClearColor(0.2f, 0.2f, 0.2f, 1.f);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	SDL_GL_SetSwapInterval(1);
	SDL_GL_SwapWindow(_wnd);

	app->initialize();

	TimePoint last_time{};
	Duration accumulator{};
	while(_running)
	{
		TimePoint new_time = Clock::now();
		Duration dT = new_time - last_time;
		last_time = new_time;
		accumulator += dT;

		SDL_Event e;
		while(SDL_PollEvent(&e))
		{
			if(e.type == SDL_WINDOWEVENT_CLOSE)
				_running = false;
			if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
				app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), e.type == SDL_KEYDOWN);
			if(e.type == SDL_TEXTINPUT)
				app->keyboard_character_event(e.text.text);
			if(e.type == SDL_MOUSEMOTION)
				app->mouse_move_event({e.motion.xrel, e.motion.yrel});
			if(e.type == SDL_MOUSEBUTTONUP || e.type == SDL_MOUSEBUTTONDOWN)
				app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), e.type == SDL_MOUSEBUTTONDOWN);
			if(e.type == SDL_MOUSEWHEEL)
				app->scroll_event({e.wheel.x, e.wheel.y});
			if(e.type == SDL_WINDOWEVENT_RESIZED)
				app->resize_event(e.window.data1, e.window.data2);
		}

		if(accumulator >= app->fixed_time_step())
		{
			app->update(accumulator);
			accumulator = Duration{};
		}

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

		app->frame_start();
		app->frame();
		app->frame_end();

		SDL_GL_SwapWindow(_wnd);
	}

	delete app;

	SDL_GL_DeleteContext(ctx);
	SDL_DestroyWindow(_wnd);
	_wnd = nullptr;

	SDL_Quit();
	return _exit_code;
}

glm::ivec2 Engine::framebuffer_size() const
{
	ivec2 ret;
	SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y);
	return ret;
}

glm::ivec2 Engine::window_size() const
{
	ivec2 ret;
	SDL_GetWindowSize(_wnd, &ret.x, &ret.y);
	return ret;
}
<|endoftext|>


<commit_before>//===-- RegisterContextOpenBSD_x86_64.cpp ----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//

#include "RegisterContextOpenBSD_x86_64.h"
#include "RegisterContextPOSIX_x86.h"
#include <vector>

using namespace lldb_private;
using namespace lldb;

// /usr/include/machine/reg.h
typedef struct _GPR {
  uint64_t rdi;
  uint64_t rsi;
  uint64_t rdx;
  uint64_t rcx;
  uint64_t r8;
  uint64_t r9;
  uint64_t r10;
  uint64_t r11;
  uint64_t r12;
  uint64_t r13;
  uint64_t r14;
  uint64_t r15;
  uint64_t rbp;
  uint64_t rbx;
  uint64_t rax;
  uint64_t rsp;
  uint64_t rip;
  uint64_t rflags;
  uint64_t cs;
  uint64_t ss;
  uint64_t ds;
  uint64_t es;
  uint64_t fs;
  uint64_t gs;
} GPR;

struct DBG {
  uint64_t dr[16]; /* debug registers */
                   /* Index 0-3: debug address registers */
                   /* Index 4-5: reserved */
                   /* Index 6: debug status */
                   /* Index 7: debug control */
                   /* Index 8-15: reserved */
};

struct UserArea {
  GPR gpr;
  FPR fpr;
  DBG dbg;
};

#define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index]))

//---------------------------------------------------------------------------
// Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64
// structure.
//---------------------------------------------------------------------------
#define DECLARE_REGISTER_INFOS_X86_64_STRUCT
#include "RegisterInfos_x86_64.h"
#undef DECLARE_REGISTER_INFOS_X86_64_STRUCT

static std::vector<lldb_private::RegisterInfo> &GetSharedRegisterInfoVector() {
  static std::vector<lldb_private::RegisterInfo> register_infos;
  return register_infos;
}

static const RegisterInfo *
PrivateGetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::x86_64:
    return g_register_infos_x86_64;
  default:
    assert(false && "Unhandled target architecture.");
    return nullptr;
  }
}

static uint32_t
PrivateGetRegisterCount(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::x86_64:
    return static_cast<uint32_t>(sizeof(g_register_infos_x86_64) /
                                 sizeof(g_register_infos_x86_64[0]));
  default:
    assert(false && "Unhandled target architecture.");
    return 0;
  }
}

RegisterContextOpenBSD_x86_64::RegisterContextOpenBSD_x86_64(
    const ArchSpec &target_arch)
    : lldb_private::RegisterInfoInterface(target_arch),
      m_register_info_p(PrivateGetRegisterInfoPtr(target_arch)),
      m_register_count(PrivateGetRegisterCount(target_arch)) {}

size_t RegisterContextOpenBSD_x86_64::GetGPRSize() const { return sizeof(GPR); }

const RegisterInfo *RegisterContextOpenBSD_x86_64::GetRegisterInfo() const {
  return m_register_info_p;
}

uint32_t RegisterContextOpenBSD_x86_64::GetRegisterCount() const {
  return m_register_count;
}
<commit_msg>[Process/Utility] Remove dead code. NFCI.<commit_after>//===-- RegisterContextOpenBSD_x86_64.cpp ----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//

#include "RegisterContextOpenBSD_x86_64.h"
#include "RegisterContextPOSIX_x86.h"
#include <vector>

using namespace lldb_private;
using namespace lldb;

// /usr/include/machine/reg.h
typedef struct _GPR {
  uint64_t rdi;
  uint64_t rsi;
  uint64_t rdx;
  uint64_t rcx;
  uint64_t r8;
  uint64_t r9;
  uint64_t r10;
  uint64_t r11;
  uint64_t r12;
  uint64_t r13;
  uint64_t r14;
  uint64_t r15;
  uint64_t rbp;
  uint64_t rbx;
  uint64_t rax;
  uint64_t rsp;
  uint64_t rip;
  uint64_t rflags;
  uint64_t cs;
  uint64_t ss;
  uint64_t ds;
  uint64_t es;
  uint64_t fs;
  uint64_t gs;
} GPR;

struct DBG {
  uint64_t dr[16]; /* debug registers */
                   /* Index 0-3: debug address registers */
                   /* Index 4-5: reserved */
                   /* Index 6: debug status */
                   /* Index 7: debug control */
                   /* Index 8-15: reserved */
};

struct UserArea {
  GPR gpr;
  FPR fpr;
  DBG dbg;
};

#define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index]))

//---------------------------------------------------------------------------
// Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64
// structure.
//---------------------------------------------------------------------------
#define DECLARE_REGISTER_INFOS_X86_64_STRUCT
#include "RegisterInfos_x86_64.h"
#undef DECLARE_REGISTER_INFOS_X86_64_STRUCT

static const RegisterInfo *
PrivateGetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::x86_64:
    return g_register_infos_x86_64;
  default:
    assert(false && "Unhandled target architecture.");
    return nullptr;
  }
}

static uint32_t
PrivateGetRegisterCount(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::x86_64:
    return static_cast<uint32_t>(sizeof(g_register_infos_x86_64) /
                                 sizeof(g_register_infos_x86_64[0]));
  default:
    assert(false && "Unhandled target architecture.");
    return 0;
  }
}

RegisterContextOpenBSD_x86_64::RegisterContextOpenBSD_x86_64(
    const ArchSpec &target_arch)
    : lldb_private::RegisterInfoInterface(target_arch),
      m_register_info_p(PrivateGetRegisterInfoPtr(target_arch)),
      m_register_count(PrivateGetRegisterCount(target_arch)) {}

size_t RegisterContextOpenBSD_x86_64::GetGPRSize() const { return sizeof(GPR); }

const RegisterInfo *RegisterContextOpenBSD_x86_64::GetRegisterInfo() const {
  return m_register_info_p;
}

uint32_t RegisterContextOpenBSD_x86_64::GetRegisterCount() const {
  return m_register_count;
}
<|endoftext|>