<commit_before>
#include "PipelineManager.h"

#include "tis_logging.h"

#include <ctime>
#include <cstring>
#include <algorithm>
#include <tis_utils.h>

using namespace tis_imaging;

PipelineManager::PipelineManager ()
    : status(PIPELINE_UNDEFINED), filter_loader(), frame_count(0)
{
    filter_loader.index_possible_filter();
    filter_loader.open_possible_filter();
    available_filter = filter_loader.get_all_filter();

}

PipelineManager::~PipelineManager ()
{
    if (status == PIPELINE_PLAYING)
    {
        stop_playing();
    }

    available_filter.clear();
    filter_pipeline.clear();
    filter_properties.clear();
    filter_loader.drop_all_filter();
}

std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties ()
{
    return filter_properties;
}

std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const
{
    return available_output_formats;
}

bool PipelineManager::setVideoFormat(const VideoFormat& f)
{
    this->format = f;
}

bool PipelineManager::setStatus (PIPELINE_STATUS s)
{
    if (status == s)
        return true;

    this->status = s;

    if (status == PIPELINE_PLAYING)
    {
        frame_count = 0;
        second_count = time(0);
        if (create_pipeline())
        {
            start_playing();
            tis_log(TIS_LOG_INFO, "All pipeline elements set to PLAYING.");
        }
        else
        {
            status = PIPELINE_ERROR;
            // TODO: error
            return false;
        }
    }
    else if (status == PIPELINE_STOPPED)
    {
      stop_playing();
    }

    return true;
}

PIPELINE_STATUS PipelineManager::getStatus () const
{
    return status;
}

bool PipelineManager::destroyPipeline ()
{
    setStatus(PIPELINE_STOPPED);

    source = nullptr;
    sink = nullptr;

    return true;
}

void PipelineManager::index_output_formats ()
{
    if (available_input_formats.empty() || available_filter.empty())
    {

        return ;
    }

    uint32_t fourcc = 0;
    auto dev_formats = [&fourcc] (const VideoFormatDescription& vfd)
        {
            tis_log(TIS_LOG_DEBUG,
                    "Testing %s against %s",
                    fourcc2description(fourcc),
                    fourcc2description(vfd.getFormatDescription().fourcc));

            return vfd.getFormatDescription().fourcc == fourcc;
        };

    for (auto f : available_filter)
    {
        if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {

            auto output = f->getDescription().output_fourcc;
            auto input = f->getDescription().input_fourcc;

            bool match = false;
            for (const uint32_t& fi : input)
            {
                fourcc = fi;
                auto format_match = std::find_if (available_input_formats.begin(),
                                                  available_input_formats.end(),
                                                  dev_formats);

                if (format_match != available_input_formats.end())
                {
                    for (uint32_t fcc : output)
                    {
                        auto desc = format_match->getFormatDescription();
                        auto rf   = format_match-> getResolutionsFramesrates();

                        desc.fourcc = fcc;
                        memcpy(desc.description, fourcc2description(fcc), sizeof(desc.description));

                        VideoFormatDescription v (desc, rf);
                        available_output_formats.push_back (v);
                    }
                }
            }

            if (match == false) // does not allow for input format
            {
                continue;
            }
        }
    }

    // to finalize iterate input formats and select those that shall be passed through

    std::vector<uint32_t> pass_through = {FOURCC_Y800, FOURCC_Y16, FOURCC_UYVY};

    for (auto f : pass_through)
    {
        fourcc = f;
        auto match = std::find_if(available_input_formats.begin(), available_input_formats.end(), dev_formats);

        if (match != available_input_formats.end())
        {
            tis_log(TIS_LOG_ERROR, "Passing format through %s", fourcc2description(f));
            available_output_formats.push_back(*match);
        }
        else
        {
            tis_log(TIS_LOG_DEBUG, "Device format '%s' will not be passed to user.", fourcc2description(f));
        }
    }
}

bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device)
{
    if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
    {
        return false;
    }

    properties = device->getProperties();
    available_input_formats = device->getAvailableVideoFormats();

    distributeProperties();

    this->source = std::make_shared<ImageSource>();
    source->setSink(shared_from_this());

    source->setDevice(device);

    for (const auto& f : available_filter)
    {
        auto p = f->getFilterProperties();

        if (!p.empty())
        {
            filter_properties.insert(filter_properties.end(), p.begin(), p.end());
        }
    }

    index_output_formats();

    return true;
}

std::shared_ptr<ImageSource> PipelineManager::getSource ()
{
    return source;
}

bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s)
{
    if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
    {
        return false;
    }

    this->sink = s;

    return true;
}

std::shared_ptr<SinkInterface> PipelineManager::getSink ()
{
    return sink;
}

void PipelineManager::distributeProperties ()
{
    for (auto& f : available_filter)
    {
        f->setDeviceProperties(properties);
    }
}

static bool isFilterApplicable (uint32_t fourcc,
                                const std::vector<uint32_t>& vec)
{
    if (std::find(vec.begin(), vec.end(), fourcc) == vec.end())
    {
        return false;
    }
    return true;
}

void PipelineManager::create_input_format (uint32_t fourcc)
{
    input_format = format;
    input_format.setFourcc(fourcc);
}

std::vector<uint32_t> PipelineManager::getDeviceFourcc ()
{
    // for easy usage we create a vector<fourcc> for avail. inputs
    std::vector<uint32_t> device_fourcc;

    for (const auto& v : available_input_formats)
    {
        tis_log(TIS_LOG_DEBUG,
                "Found device fourcc '%s' - %d",
                fourcc2description(v.getFormatDescription().fourcc),
                v.getFormatDescription().fourcc);

        device_fourcc.push_back(v.getFormatDescription().fourcc);
    }
    return device_fourcc;
}

bool PipelineManager::validate_pipeline ()
{
    // check if pipeline is valid
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    // check source format
    auto in_format = source->getVideoFormat();

    if (in_format != this->input_format)
    {
        tis_log(TIS_LOG_DEBUG,
                "Video format in source does not match pipeline: '%s' != '%s'",
                in_format.toString().c_str(),
                input_format.toString().c_str());
        return false;
    }

    VideoFormat in;
    VideoFormat out;
    for (auto f : filter_pipeline)
    {

        f->getVideoFormat(in, out);

        if (in != in_format)
        {
            tis_log(TIS_LOG_ERROR,
                    "Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'",
                    f->getDescription().name.c_str(),
                    in_format.toString().c_str(),
                    in.toString().c_str());
            // TODO: error
            return false;
        }
        else
        {
            tis_log(TIS_LOG_DEBUG, "Filter %s connected to pipeline -- %s",
                    f->getDescription().name.c_str(),
                    out.toString().c_str());
            // save output for next comparison
            in_format = out;
        }
    }

    if (in_format != this->format)
    {
        tis_log(TIS_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'",
                in_format.toString().c_str(),
                format.toString().c_str());
        return false;
    }

    return true;
}

bool PipelineManager::create_conversion_pipeline ()
{
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    auto device_fourcc = getDeviceFourcc();

    for (auto f : available_filter)
    {
        std::string s = f->getDescription().name;

        if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {

            if (isFilterApplicable(format.getFourcc(), f->getDescription().output_fourcc))
            {
                bool filter_valid = false;
                uint32_t fourcc_to_use = 0;
                for (const auto& cc : device_fourcc)
                {
                    if (isFilterApplicable(cc, f->getDescription().input_fourcc))
                    {
                        filter_valid = true;
                        fourcc_to_use = cc;
                        break;
                    }
                }

                // set device format to use correct fourcc
                create_input_format(fourcc_to_use);

                if (filter_valid)
                {
                    if (f->setVideoFormat(input_format, format))
                    {
                        tis_log(TIS_LOG_DEBUG,
                                "Added filter \"%s\" to pipeline",
                                s.c_str());
                        filter_pipeline.push_back(f);
                    }
                    else
                    {
                        tis_log(TIS_LOG_DEBUG,
                                "Filter %s did not accept format settings",
                                s.c_str());
                    }
                }
                else
                {
                    tis_log(TIS_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str());
                }
            }
            else
            {
                tis_log(TIS_LOG_DEBUG, "Filter %s is not applicable", s.c_str());

            }
        }
    }
    return true;
}

bool PipelineManager::add_interpretation_filter ()
{

    // if a valid pipeline can be created insert additional filter (e.g. autoexposure)
    // interpretations should be done as early as possible in the pipeline

    for (auto& f : available_filter)
    {
        if (f->getDescription().type == FILTER_TYPE_INTERPRET)
        {
            std::string s  = f->getDescription().name;
            // applicable to sink
            bool all_formats = false;
            if (f->getDescription().input_fourcc.size() == 1)
            {
                if (f->getDescription().input_fourcc.at(0) == 0)
                {
                    all_formats = true;
                }
            }

            if (all_formats ||isFilterApplicable(input_format.getFourcc(), f->getDescription().input_fourcc))
            {
                tis_log(TIS_LOG_DEBUG, "Adding filter '%s' after source", s.c_str());
                f->setVideoFormat(input_format, input_format);
                filter_pipeline.insert(filter_pipeline.begin(), f);
                continue;
            }
            else
            {
                tis_log(TIS_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str());
            }

            for (auto& filter : filter_pipeline)
            {
                if (f->setVideoFormat(input_format, input_format))
                {

                    continue;
                }
            }
        }
    }
    return true;
}

bool PipelineManager::allocate_conversion_buffer ()
{

    for (int i = 0; i < 5; ++i)
    {
        image_buffer b = {};
        b.pitch = format.getSize().width * img::getBitsPerPixel(format.getFourcc()) / 8;
        b.length = b.pitch * format.getSize().height;

        b.pData = (unsigned char*)malloc(b.length);

        b.format.fourcc = format.getFourcc();
        b.format.width = format.getSize().width;
        b.format.height = format.getSize().height;
        b.format.binning = format.getBinning();
        b.format.framerate = format.getFramerate();

        this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b));
    }
    return true;
}

bool PipelineManager::create_pipeline ()
{
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    // assure everything is in a defined state
    filter_pipeline.clear();

    format.setFramerate(10.0);
    format.setBinning(0);

    if (!create_conversion_pipeline())
    {
        return false;
    }

    if (source->setVideoFormat(input_format))
    {
        tis_log(TIS_LOG_ERROR, "Unable to set video format in source.");
        //return false;
    }

    if (!add_interpretation_filter())
    {
        return false;
    }

    if (!allocate_conversion_buffer())
    {
        return false;
    }

    if (!validate_pipeline())
    {
        return false;
    }

    tis_log(TIS_LOG_INFO, "Pipeline creation successful.");

    std::string ppl = "source -> ";

    for (const auto& f : filter_pipeline)
    {
        ppl += f->getDescription().name;
        ppl += " -> ";
    }
    ppl += " sink";
    tis_log(TIS_LOG_INFO, "%s" , ppl.c_str());

    return true;
}

bool PipelineManager::start_playing ()
{

    if (!sink->setStatus(PIPELINE_PLAYING))
    {
        tis_log(TIS_LOG_ERROR, "Sink refused to change to state PLAYING");
        goto error;
    }

    for (auto& f : filter_pipeline)
    {
        if (!f->setStatus(PIPELINE_PLAYING))
        {
            tis_log(TIS_LOG_ERROR,
                    "Filter %s refused to change to state PLAYING",
                    f->getDescription().name.c_str());
            goto error;
        }
    }

    if (!source->setStatus(PIPELINE_PLAYING))
    {
        tis_log(TIS_LOG_ERROR, "Source refused to change to state PLAYING");
        goto error;
    }

    status = PIPELINE_PLAYING;

    return true;

error:

    stop_playing();
    return false;
}

bool PipelineManager::stop_playing ()
{
    status = PIPELINE_STOPPED;

    if (!source->setStatus(PIPELINE_STOPPED))
    {
        tis_log(TIS_LOG_ERROR, "Source refused to change to state STOP");
        return false;
    }

    for (auto& f : filter_pipeline)
    {
        if (!f->setStatus(PIPELINE_STOPPED))
        {
            tis_log(TIS_LOG_ERROR,
                    "Filter %s refused to change to state STOP",
                    f->getDescription().name.c_str());
            return false;
        }
    }

    if (!sink->setStatus(PIPELINE_STOPPED))
    {
        tis_log(TIS_LOG_ERROR, "Sink refused to change to state STOP");
        return false;
    }

    return true;
}

void PipelineManager::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
    if (status == PIPELINE_STOPPED)
    {
        return;
    }

    frame_count++;
    buffer->lock();

    auto current_buffer = buffer;

    for (auto& f : filter_pipeline)
    {
        if (f->getDescription().type == FILTER_TYPE_INTERPRET)
        {
            f->apply(current_buffer);
        }
        else if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {
            auto next_buffer = pipeline_buffer.at(0);

            f->transform(*current_buffer, *next_buffer);

            current_buffer = next_buffer;
        }
    }

    if (sink != nullptr)
    {
      sink->pushImage(current_buffer);
    }
    else
    {
      tis_log(TIS_LOG_ERROR, "Sink is NULL");
    }
    buffer->unlock();
}
<commit_msg>Simplified format distribution for interpretation filter<commit_after>
#include "PipelineManager.h"

#include "tis_logging.h"

#include <ctime>
#include <cstring>
#include <algorithm>
#include <tis_utils.h>

using namespace tis_imaging;

PipelineManager::PipelineManager ()
    : status(PIPELINE_UNDEFINED), filter_loader(), frame_count(0)
{
    filter_loader.index_possible_filter();
    filter_loader.open_possible_filter();
    available_filter = filter_loader.get_all_filter();

}

PipelineManager::~PipelineManager ()
{
    if (status == PIPELINE_PLAYING)
    {
        stop_playing();
    }

    available_filter.clear();
    filter_pipeline.clear();
    filter_properties.clear();
    filter_loader.drop_all_filter();
}

std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties ()
{
    return filter_properties;
}

std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const
{
    return available_output_formats;
}

bool PipelineManager::setVideoFormat(const VideoFormat& f)
{
    this->format = f;
}

bool PipelineManager::setStatus (PIPELINE_STATUS s)
{
    if (status == s)
        return true;

    this->status = s;

    if (status == PIPELINE_PLAYING)
    {
        frame_count = 0;
        second_count = time(0);
        if (create_pipeline())
        {
            start_playing();
            tis_log(TIS_LOG_INFO, "All pipeline elements set to PLAYING.");
        }
        else
        {
            status = PIPELINE_ERROR;
            // TODO: error
            return false;
        }
    }
    else if (status == PIPELINE_STOPPED)
    {
      stop_playing();
    }

    return true;
}

PIPELINE_STATUS PipelineManager::getStatus () const
{
    return status;
}

bool PipelineManager::destroyPipeline ()
{
    setStatus(PIPELINE_STOPPED);

    source = nullptr;
    sink = nullptr;

    return true;
}

void PipelineManager::index_output_formats ()
{
    if (available_input_formats.empty() || available_filter.empty())
    {

        return ;
    }

    uint32_t fourcc = 0;
    auto dev_formats = [&fourcc] (const VideoFormatDescription& vfd)
        {
            tis_log(TIS_LOG_DEBUG,
                    "Testing %s against %s",
                    fourcc2description(fourcc),
                    fourcc2description(vfd.getFormatDescription().fourcc));

            return vfd.getFormatDescription().fourcc == fourcc;
        };

    for (auto f : available_filter)
    {
        if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {

            auto output = f->getDescription().output_fourcc;
            auto input = f->getDescription().input_fourcc;

            bool match = false;
            for (const uint32_t& fi : input)
            {
                fourcc = fi;
                auto format_match = std::find_if (available_input_formats.begin(),
                                                  available_input_formats.end(),
                                                  dev_formats);

                if (format_match != available_input_formats.end())
                {
                    for (uint32_t fcc : output)
                    {
                        auto desc = format_match->getFormatDescription();
                        auto rf   = format_match-> getResolutionsFramesrates();

                        desc.fourcc = fcc;
                        memcpy(desc.description, fourcc2description(fcc), sizeof(desc.description));

                        VideoFormatDescription v (desc, rf);
                        available_output_formats.push_back (v);
                    }
                }
            }

            if (match == false) // does not allow for input format
            {
                continue;
            }
        }
    }

    // to finalize iterate input formats and select those that shall be passed through

    std::vector<uint32_t> pass_through = {FOURCC_Y800, FOURCC_Y16, FOURCC_UYVY};

    for (auto f : pass_through)
    {
        fourcc = f;
        auto match = std::find_if(available_input_formats.begin(), available_input_formats.end(), dev_formats);

        if (match != available_input_formats.end())
        {
            tis_log(TIS_LOG_ERROR, "Passing format through %s", fourcc2description(f));
            available_output_formats.push_back(*match);
        }
        else
        {
            tis_log(TIS_LOG_DEBUG, "Device format '%s' will not be passed to user.", fourcc2description(f));
        }
    }
}

bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device)
{
    if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
    {
        return false;
    }

    properties = device->getProperties();
    available_input_formats = device->getAvailableVideoFormats();

    distributeProperties();

    this->source = std::make_shared<ImageSource>();
    source->setSink(shared_from_this());

    source->setDevice(device);

    for (const auto& f : available_filter)
    {
        auto p = f->getFilterProperties();

        if (!p.empty())
        {
            filter_properties.insert(filter_properties.end(), p.begin(), p.end());
        }
    }

    index_output_formats();

    return true;
}

std::shared_ptr<ImageSource> PipelineManager::getSource ()
{
    return source;
}

bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s)
{
    if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
    {
        return false;
    }

    this->sink = s;

    return true;
}

std::shared_ptr<SinkInterface> PipelineManager::getSink ()
{
    return sink;
}

void PipelineManager::distributeProperties ()
{
    for (auto& f : available_filter)
    {
        f->setDeviceProperties(properties);
    }
}

static bool isFilterApplicable (uint32_t fourcc,
                                const std::vector<uint32_t>& vec)
{
    if (std::find(vec.begin(), vec.end(), fourcc) == vec.end())
    {
        return false;
    }
    return true;
}

void PipelineManager::create_input_format (uint32_t fourcc)
{
    input_format = format;
    input_format.setFourcc(fourcc);
}

std::vector<uint32_t> PipelineManager::getDeviceFourcc ()
{
    // for easy usage we create a vector<fourcc> for avail. inputs
    std::vector<uint32_t> device_fourcc;

    for (const auto& v : available_input_formats)
    {
        tis_log(TIS_LOG_DEBUG,
                "Found device fourcc '%s' - %d",
                fourcc2description(v.getFormatDescription().fourcc),
                v.getFormatDescription().fourcc);

        device_fourcc.push_back(v.getFormatDescription().fourcc);
    }
    return device_fourcc;
}

bool PipelineManager::validate_pipeline ()
{
    // check if pipeline is valid
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    // check source format
    auto in_format = source->getVideoFormat();

    if (in_format != this->input_format)
    {
        tis_log(TIS_LOG_DEBUG,
                "Video format in source does not match pipeline: '%s' != '%s'",
                in_format.toString().c_str(),
                input_format.toString().c_str());
        return false;
    }

    VideoFormat in;
    VideoFormat out;
    for (auto f : filter_pipeline)
    {

        f->getVideoFormat(in, out);

        if (in != in_format)
        {
            tis_log(TIS_LOG_ERROR,
                    "Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'",
                    f->getDescription().name.c_str(),
                    in_format.toString().c_str(),
                    in.toString().c_str());
            // TODO: error
            return false;
        }
        else
        {
            tis_log(TIS_LOG_DEBUG, "Filter %s connected to pipeline -- %s",
                    f->getDescription().name.c_str(),
                    out.toString().c_str());
            // save output for next comparison
            in_format = out;
        }
    }

    if (in_format != this->format)
    {
        tis_log(TIS_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'",
                in_format.toString().c_str(),
                format.toString().c_str());
        return false;
    }

    return true;
}

bool PipelineManager::create_conversion_pipeline ()
{
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    auto device_fourcc = getDeviceFourcc();

    for (auto f : available_filter)
    {
        std::string s = f->getDescription().name;

        if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {

            if (isFilterApplicable(format.getFourcc(), f->getDescription().output_fourcc))
            {
                bool filter_valid = false;
                uint32_t fourcc_to_use = 0;
                for (const auto& cc : device_fourcc)
                {
                    if (isFilterApplicable(cc, f->getDescription().input_fourcc))
                    {
                        filter_valid = true;
                        fourcc_to_use = cc;
                        break;
                    }
                }

                // set device format to use correct fourcc
                create_input_format(fourcc_to_use);

                if (filter_valid)
                {
                    if (f->setVideoFormat(input_format, format))
                    {
                        tis_log(TIS_LOG_DEBUG,
                                "Added filter \"%s\" to pipeline",
                                s.c_str());
                        filter_pipeline.push_back(f);
                    }
                    else
                    {
                        tis_log(TIS_LOG_DEBUG,
                                "Filter %s did not accept format settings",
                                s.c_str());
                    }
                }
                else
                {
                    tis_log(TIS_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str());
                }
            }
            else
            {
                tis_log(TIS_LOG_DEBUG, "Filter %s is not applicable", s.c_str());

            }
        }
    }
    return true;
}

bool PipelineManager::add_interpretation_filter ()
{

    // if a valid pipeline can be created insert additional filter (e.g. autoexposure)
    // interpretations should be done as early as possible in the pipeline

    for (auto& f : available_filter)
    {
        if (f->getDescription().type == FILTER_TYPE_INTERPRET)
        {
            std::string s  = f->getDescription().name;
            // applicable to sink
            bool all_formats = false;
            if (f->getDescription().input_fourcc.size() == 1)
            {
                if (f->getDescription().input_fourcc.at(0) == 0)
                {
                    all_formats = true;
                }
            }

            if (all_formats ||isFilterApplicable(input_format.getFourcc(), f->getDescription().input_fourcc))
            {
                tis_log(TIS_LOG_DEBUG, "Adding filter '%s' after source", s.c_str());
                f->setVideoFormat(input_format, input_format);
                filter_pipeline.insert(filter_pipeline.begin(), f);
                continue;
            }
            else
            {
                tis_log(TIS_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str());
            }

            // for (auto& filter : filter_pipeline)
            // {
                if (f->setVideoFormat(input_format, input_format))
                {
                    continue;
                }
           // }
        }
    }
    return true;
}

bool PipelineManager::allocate_conversion_buffer ()
{

    for (int i = 0; i < 5; ++i)
    {
        image_buffer b = {};
        b.pitch = format.getSize().width * img::getBitsPerPixel(format.getFourcc()) / 8;
        b.length = b.pitch * format.getSize().height;

        b.pData = (unsigned char*)malloc(b.length);

        b.format.fourcc = format.getFourcc();
        b.format.width = format.getSize().width;
        b.format.height = format.getSize().height;
        b.format.binning = format.getBinning();
        b.format.framerate = format.getFramerate();

        this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b));
    }
    return true;
}

bool PipelineManager::create_pipeline ()
{
    if (source.get() == nullptr || sink.get() == nullptr)
    {
        // TODO: error
        return false;
    }

    // assure everything is in a defined state
    filter_pipeline.clear();

    format.setFramerate(10.0);
    format.setBinning(0);

    if (!create_conversion_pipeline())
    {
        return false;
    }

    if (source->setVideoFormat(input_format))
    {
        tis_log(TIS_LOG_ERROR, "Unable to set video format in source.");
        //return false;
    }

    if (!add_interpretation_filter())
    {
        return false;
    }

    if (!allocate_conversion_buffer())
    {
        return false;
    }

    if (!validate_pipeline())
    {
        return false;
    }

    tis_log(TIS_LOG_INFO, "Pipeline creation successful.");

    std::string ppl = "source -> ";

    for (const auto& f : filter_pipeline)
    {
        ppl += f->getDescription().name;
        ppl += " -> ";
    }
    ppl += " sink";
    tis_log(TIS_LOG_INFO, "%s" , ppl.c_str());

    return true;
}

bool PipelineManager::start_playing ()
{

    if (!sink->setStatus(PIPELINE_PLAYING))
    {
        tis_log(TIS_LOG_ERROR, "Sink refused to change to state PLAYING");
        goto error;
    }

    for (auto& f : filter_pipeline)
    {
        if (!f->setStatus(PIPELINE_PLAYING))
        {
            tis_log(TIS_LOG_ERROR,
                    "Filter %s refused to change to state PLAYING",
                    f->getDescription().name.c_str());
            goto error;
        }
    }

    if (!source->setStatus(PIPELINE_PLAYING))
    {
        tis_log(TIS_LOG_ERROR, "Source refused to change to state PLAYING");
        goto error;
    }

    status = PIPELINE_PLAYING;

    return true;

error:

    stop_playing();
    return false;
}

bool PipelineManager::stop_playing ()
{
    status = PIPELINE_STOPPED;

    if (!source->setStatus(PIPELINE_STOPPED))
    {
        tis_log(TIS_LOG_ERROR, "Source refused to change to state STOP");
        return false;
    }

    for (auto& f : filter_pipeline)
    {
        if (!f->setStatus(PIPELINE_STOPPED))
        {
            tis_log(TIS_LOG_ERROR,
                    "Filter %s refused to change to state STOP",
                    f->getDescription().name.c_str());
            return false;
        }
    }

    if (!sink->setStatus(PIPELINE_STOPPED))
    {
        tis_log(TIS_LOG_ERROR, "Sink refused to change to state STOP");
        return false;
    }

    return true;
}

void PipelineManager::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
    if (status == PIPELINE_STOPPED)
    {
        return;
    }

    frame_count++;
    buffer->lock();

    auto current_buffer = buffer;

    for (auto& f : filter_pipeline)
    {
        if (f->getDescription().type == FILTER_TYPE_INTERPRET)
        {
            f->apply(current_buffer);
        }
        else if (f->getDescription().type == FILTER_TYPE_CONVERSION)
        {
            auto next_buffer = pipeline_buffer.at(0);

            f->transform(*current_buffer, *next_buffer);

            current_buffer = next_buffer;
        }
    }

    if (sink != nullptr)
    {
      sink->pushImage(current_buffer);
    }
    else
    {
      tis_log(TIS_LOG_ERROR, "Sink is NULL");
    }
    buffer->unlock();
}
<|endoftext|>


<commit_before>#include "common.h"

using namespace details;

go_bandit([]{

    describe("draw::Renderer:", []{

        before_each([&]{

            mockGL();
        });

        it("should be created", [&]{

            auto ptr = makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().Not().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });

        it("should throw draw::InvalidArgument if context is invalid", [&]{

            auto ptr = draw::makeRenderer(nullptr);
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::InvalidArgument));
        });

        it("throw draw::OpenGLAbsentFeature if OpenGL 2.0 is not supported", [&]{

            Given(::glMocked(), glew_Init()).WillByDefault(Return(GLEW_ERROR_NO_GL_VERSION));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLAbsentFeature));
        });

        it("throw draw::OpenGLAbsentFeature if ARB_draw_instanced is not supported", [&]{

            Given(::glMocked(), glew_IsSupported(_)).WillByDefault(Return(false));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLAbsentFeature));
        });

        it("throw draw::OpenGLOutOfMemory if is not enough memory to create internal OpenGL resources", [&]{

            Given(::glMocked(), gl_GetError()).WillByDefault(Return(GL_OUT_OF_MEMORY));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLOutOfMemory));
        });

        it("should resize", [&]{

            draw::Size size;

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            ptr->resize(size);
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });

        it("should draw no objects", [&]{

            draw::Color color;

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr->draw(color), Is().EqualTo(0));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });
    });
});<commit_msg>fix clang compilation error<commit_after>#include "common.h"

using namespace details;

go_bandit([]{

    describe("draw::Renderer:", []{

        before_each([&]{

            mockGL();
        });

        it("should be created", [&]{

            auto ptr = makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().Not().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });

        it("should throw draw::InvalidArgument if context is invalid", [&]{

            auto ptr = draw::makeRenderer(nullptr);
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::InvalidArgument));
        });

        it("throw draw::OpenGLAbsentFeature if OpenGL 2.0 is not supported", [&]{

            Given(::glMocked(), glew_Init()).WillByDefault(Return(GLEW_ERROR_NO_GL_VERSION));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLAbsentFeature));
        });

        it("throw draw::OpenGLAbsentFeature if ARB_draw_instanced is not supported", [&]{

            Given(::glMocked(), glew_IsSupported(_)).WillByDefault(Return(false));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLAbsentFeature));
        });

        it("throw draw::OpenGLOutOfMemory if is not enough memory to create internal OpenGL resources", [&]{

            Given(::glMocked(), gl_GetError()).WillByDefault(Return(GL_OUT_OF_MEMORY));

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr, Is().EqualTo(draw::RendererPtr()));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::OpenGLOutOfMemory));
        });

        it("should resize", [&]{

            draw::Size size;

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            ptr->resize(size);
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });

        it("should draw no objects", [&]{

            draw::Color color = 0x00000000;

            auto ptr = draw::makeRenderer(std::unique_ptr<ContextImpl>(new ContextImpl()));
            AssertThat(ptr->draw(color), Is().EqualTo(0));
            AssertThat(draw::getLastError(), Is().EqualTo(draw::ErrorCode::NoError));
        });
    });
});<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_PRANDOM_HPP_
#define WTL_PRANDOM_HPP_

#include <cstddef> // ptrdiff_t
#include <random>
#include <limits> // numeric_limits
#include <functional> // bind
#include <unordered_set>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class Iter, class RNG> inline
Iter choice(Iter begin_, Iter end_, RNG& rng) {
    std::uniform_int_distribution<ptrdiff_t> uniform(0, std::distance(begin_, end_) - 1);
    std::advance(begin_, uniform(rng));
    return begin_;
}

template <class Container, class RNG> inline
Container sample(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (100 * k < n) {return sample_set(src, k, rng);}
    else if (5 * k < n) {return sample_fisher(src, k, rng);}
    else {return sample_knuth(src, k, rng);}
}

//! fast if k << n
template <class Container, class RNG> inline
Container sample_set(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    std::unordered_set<size_t> existing_indices;
    Container dst;
    dst.reserve(k);
    std::uniform_int_distribution<size_t> uniform(0, n - 1);
    size_t idx = 0;
    for (size_t i=0; i<k; ++i) {
        do {
            idx = uniform(rng);
        } while (!std::get<1>(existing_indices.insert(idx)));
        dst.push_back(src[idx]);
    }
    return dst;
}

//! Fisher-Yates algorithm; Durstenfeld; Knuth's P
//! consistently fast; note that whole src is copied first
template <class Container, class RNG> inline
Container sample_fisher(Container src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    const size_t last = n - 1;
    for (size_t i=0; i<k; ++i) {
        std::swap(src[std::uniform_int_distribution<size_t>(i, last)(rng)], src[i]);
    }
    src.resize(k);
    return src;
}

//! Knuth's algorithm S
//! fast if k / n is large
//! The order is not random
template <class Container, class RNG> inline
Container sample_knuth(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    Container samples;
    samples.reserve(k);
    size_t i = 0;
    for (; i<k; ++i) {
        samples.push_back(src[i]);
    }
    std::uniform_int_distribution<size_t> uniform(0, k - 1);
    while (i < n) {
        if (std::bernoulli_distribution((1.0 / ++i) * k)(rng)) {
            samples[uniform(rng)] = src[i - 1];
        }
    }
    return samples;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

//! Pythonic RNG object
template <class Generator>
class Prandom{
  public:
    // typedefs
    typedef unsigned int result_type;
    typedef result_type argument_type;

    static constexpr result_type min() {return Generator::min();}
    static constexpr result_type max() {return Generator::max();}

    // constructors
    explicit Prandom(const result_type s=std::random_device{}())
    : seed_(s), generator_(s) {seed(s);}

    Prandom(const Prandom&) = delete;

    ////////////////////////////////////////
    // methods

    void seed(const result_type s) {seed_ = s; generator_.seed(seed_);}
    void discard(unsigned long long n) {generator_.discard(n);}

    ////////////////////
    // integer

    // [0, 2^32-1]
    result_type operator()() {return generator_();}
    // [0, n-1]
    unsigned int randrange(unsigned int n) {
        return std::uniform_int_distribution<unsigned int>(0, --n)(generator_);
    }
    // [a, b-1]
    int randrange(const int a, int b) {
        return randint(a, --b);
    }
    // [a, b]
    int randint(const int a, const int b) {
        return std::uniform_int_distribution<int>(a, b)(generator_);
    }

    ////////////////////
    // uniform real

    // [0.0, 1.0)
    double random() {
        return std::uniform_real_distribution<double>()(generator_);
    }
    // (0.0, 1.0]
    double random_oc() {return 1.0 - random();}
    // [0.0, n)
    double uniform(double n) {
        return std::uniform_real_distribution<double>(0, n)(generator_);
    }
    // [a, b)
    double uniform(double a, double b) {
        return std::uniform_real_distribution<double>(a, b)(generator_);
    }

    ////////////////////
    // continuous

    // E = 1/lambda, V = 1/lambda^2
    double exponential(const double lambda=1.0) {
        return std::exponential_distribution<double>(lambda)(generator_);
    }

    // Scale-free: E = ?, V = ?
    double power(const double k=1.0, const double min=1.0) {
        return min * std::pow(random_oc(), -1.0 / k);
    }

    // E = mu, V = sigma^2
    double gauss(const double mu=0.0, const double sigma=1.0) {
        return std::normal_distribution<double>(mu, sigma)(generator_);
    }
    double normal(const double mu=0.0, const double sigma=1.0) {return gauss(mu, sigma);}

    ////////////////////
    // discrete

    // return true with probability p
    // E = p, V = p(1-p)
    bool bernoulli(const double p=0.5) {
        return std::bernoulli_distribution(p)(generator_);
    }

    // The number of true in n trials with probability p
    // E = np, V = np(1-p)
    unsigned int binomial(const unsigned int n, const double p=0.5) {
        return std::binomial_distribution<unsigned int>(n, p)(generator_);
    }

    // The expected number of occurrences in an unit of time/space
    // E = V = lambda
    unsigned int poisson(const double lambda) {
        return std::poisson_distribution<unsigned int>(lambda)(generator_);
    }

    // The number of trials needed to get first true
    // E = (1-p)/p, V = (1-p)/p^2
    unsigned int geometric(const double p) {
        return std::geometric_distribution<unsigned int>(p)(generator_);
    }

    ////////////////////
    // sequence
    template <class Iter>
    Iter choice(Iter begin_, Iter end_) {
        return wtl::choice(begin_, end_, generator_);
    }

    template <class Container>
    Container sample(Container src, const size_t k) {
        wtl::sample(&src, k, generator_);
        return src;
    }

  private:
    unsigned int seed_;
    Generator generator_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Global definition/declaration

inline std::mt19937& mt() {
    static std::mt19937 generator(std::random_device{}());
    return generator;
}

inline std::mt19937_64& mt64() {
    static std::mt19937_64 generator(std::random_device{}());
    return generator;
}

inline Prandom<std::mt19937>& prandom() {
    static Prandom<std::mt19937> generator;
    return generator;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_PRANDOM_HPP_ */
<commit_msg>Remove unused include<commit_after>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_PRANDOM_HPP_
#define WTL_PRANDOM_HPP_

#include <random>
#include <unordered_set>

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

template <class Iter, class RNG> inline
Iter choice(Iter begin_, Iter end_, RNG& rng) {
    using diff_t = decltype(std::distance(begin_, end_));
    std::uniform_int_distribution<diff_t> uniform(0, std::distance(begin_, end_) - 1);
    std::advance(begin_, uniform(rng));
    return begin_;
}

template <class Container, class RNG> inline
Container sample(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (100 * k < n) {return sample_set(src, k, rng);}
    else if (5 * k < n) {return sample_fisher(src, k, rng);}
    else {return sample_knuth(src, k, rng);}
}

//! fast if k << n
template <class Container, class RNG> inline
Container sample_set(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    std::unordered_set<size_t> existing_indices;
    Container dst;
    dst.reserve(k);
    std::uniform_int_distribution<size_t> uniform(0, n - 1);
    size_t idx = 0;
    for (size_t i=0; i<k; ++i) {
        do {
            idx = uniform(rng);
        } while (!std::get<1>(existing_indices.insert(idx)));
        dst.push_back(src[idx]);
    }
    return dst;
}

//! Fisher-Yates algorithm; Durstenfeld; Knuth's P
//! consistently fast; note that whole src is copied first
template <class Container, class RNG> inline
Container sample_fisher(Container src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    const size_t last = n - 1;
    for (size_t i=0; i<k; ++i) {
        std::swap(src[std::uniform_int_distribution<size_t>(i, last)(rng)], src[i]);
    }
    src.resize(k);
    return src;
}

//! Knuth's algorithm S
//! fast if k / n is large
//! The order is not random
template <class Container, class RNG> inline
Container sample_knuth(const Container& src, const size_t k, RNG& rng) {
    const size_t n = src.size();
    if (n < k) throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + ": n < k");
    Container samples;
    samples.reserve(k);
    size_t i = 0;
    for (; i<k; ++i) {
        samples.push_back(src[i]);
    }
    std::uniform_int_distribution<size_t> uniform(0, k - 1);
    while (i < n) {
        if (std::bernoulli_distribution((1.0 / ++i) * k)(rng)) {
            samples[uniform(rng)] = src[i - 1];
        }
    }
    return samples;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

//! Pythonic RNG object
template <class Generator>
class Prandom{
  public:
    // typedefs
    typedef unsigned int result_type;
    typedef result_type argument_type;

    static constexpr result_type min() {return Generator::min();}
    static constexpr result_type max() {return Generator::max();}

    // constructors
    explicit Prandom(const result_type s=std::random_device{}())
    : seed_(s), generator_(s) {seed(s);}

    Prandom(const Prandom&) = delete;

    ////////////////////////////////////////
    // methods

    void seed(const result_type s) {seed_ = s; generator_.seed(seed_);}
    void discard(unsigned long long n) {generator_.discard(n);}

    ////////////////////
    // integer

    // [0, 2^32-1]
    result_type operator()() {return generator_();}
    // [0, n-1]
    unsigned int randrange(unsigned int n) {
        return std::uniform_int_distribution<unsigned int>(0, --n)(generator_);
    }
    // [a, b-1]
    int randrange(const int a, int b) {
        return randint(a, --b);
    }
    // [a, b]
    int randint(const int a, const int b) {
        return std::uniform_int_distribution<int>(a, b)(generator_);
    }

    ////////////////////
    // uniform real

    // [0.0, 1.0)
    double random() {
        return std::uniform_real_distribution<double>()(generator_);
    }
    // (0.0, 1.0]
    double random_oc() {return 1.0 - random();}
    // [0.0, n)
    double uniform(double n) {
        return std::uniform_real_distribution<double>(0, n)(generator_);
    }
    // [a, b)
    double uniform(double a, double b) {
        return std::uniform_real_distribution<double>(a, b)(generator_);
    }

    ////////////////////
    // continuous

    // E = 1/lambda, V = 1/lambda^2
    double exponential(const double lambda=1.0) {
        return std::exponential_distribution<double>(lambda)(generator_);
    }

    // Scale-free: E = ?, V = ?
    double power(const double k=1.0, const double min=1.0) {
        return min * std::pow(random_oc(), -1.0 / k);
    }

    // E = mu, V = sigma^2
    double gauss(const double mu=0.0, const double sigma=1.0) {
        return std::normal_distribution<double>(mu, sigma)(generator_);
    }
    double normal(const double mu=0.0, const double sigma=1.0) {return gauss(mu, sigma);}

    ////////////////////
    // discrete

    // return true with probability p
    // E = p, V = p(1-p)
    bool bernoulli(const double p=0.5) {
        return std::bernoulli_distribution(p)(generator_);
    }

    // The number of true in n trials with probability p
    // E = np, V = np(1-p)
    unsigned int binomial(const unsigned int n, const double p=0.5) {
        return std::binomial_distribution<unsigned int>(n, p)(generator_);
    }

    // The expected number of occurrences in an unit of time/space
    // E = V = lambda
    unsigned int poisson(const double lambda) {
        return std::poisson_distribution<unsigned int>(lambda)(generator_);
    }

    // The number of trials needed to get first true
    // E = (1-p)/p, V = (1-p)/p^2
    unsigned int geometric(const double p) {
        return std::geometric_distribution<unsigned int>(p)(generator_);
    }

    ////////////////////
    // sequence
    template <class Iter>
    Iter choice(Iter begin_, Iter end_) {
        return wtl::choice(begin_, end_, generator_);
    }

    template <class Container>
    Container sample(Container src, const size_t k) {
        wtl::sample(&src, k, generator_);
        return src;
    }

  private:
    unsigned int seed_;
    Generator generator_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// Global definition/declaration

inline std::mt19937& mt() {
    static std::mt19937 generator(std::random_device{}());
    return generator;
}

inline std::mt19937_64& mt64() {
    static std::mt19937_64 generator(std::random_device{}());
    return generator;
}

inline Prandom<std::mt19937>& prandom() {
    static Prandom<std::mt19937> generator;
    return generator;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_PRANDOM_HPP_ */
<|endoftext|>


<commit_before>//************************************************************/
//
//	CrossSection Implementation
//
//	Implements the SPXCrossSection class, which performs the
//	convolution and all math required to calculate the cross-
//	section from a PDF and a grid file.
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		14.10.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include "SPXCrossSection.h"
#include "SPXUtilities.h"
#include "SPXException.h"

//Class name for debug statements
const std::string cn = "SPXCrossSection::";

//Must define the static debug variable in the implementation
bool SPXCrossSection::debug;

//Create the CrossSection
void SPXCrossSection::Create(void) {
	std::string m n = "Create: ";

	//Attempt to create the Grid
	try {
		grid = new SPXGrid(pci);
	} catch(const SPXException &e) {
		throw;
	}

	//Attempt to create the PDF object and perform convolution
	try {
		pdf = new SPXPDF(psf, grid->GetGridName());
	} catch(const SPXException &e) {
		throw;
	}

	//Set the name of the convolution graphs appropriately
	//Create name strings
	TString name;
	TString pdfName;
	TString alphaSName;
	TString scaleName;

	//Check if name exists
	if(!pci->gridSteeringFile.GetName().empty()) {
		name = TString(pci->gridSteeringFile.GetName());
		pdfName = name + "_pdf";
		alphaSName = name + "_alpha_s";
		scaleName = name + "_scale";
	}

	//Grid steering file has no [DESC]:name
	//Default to filename
	else {
		if(debug) std::cout << cn << mn << "Grid steering file has no name value: using filename instead" << std::endl;
		name = pci->gridSteeringFile.GetFilename();
		name.ReplaceAll(TString(".txt"), TString(""));
		pdfName = name + "_pdf";
		alphaSName = name + "_alpha_s";
		scaleName = name + "_scale";
	}

	//Set the graph names
	pdf->h_PDFBand_results->SetName(pdfName);
	pdf->h_AlphaS_results->SetName(alphaSName);
	pdf->h_Scale_results->SetName(scaleName);
}

void SPXCrossSection::ParseCorrections(void) {
	//Check if grid contains corrections
	if(pci->gridSteeringFile.GetNumberOfCorrectionFiles() != 0) {
		try {
			corrections = new SPXGridCorrections(*pci);
			corrections->Parse();
			corrections->Print();
		} catch(const SPXException &e) {
			throw;
		}
	}
}

void SPXCrossSection::ApplyCorrections(void) {
	std::string mn = "ApplyCorrections: ";

	if(pci->gridSteeringFile.GetNumberOfCorrectionFiles() == 0) {
		return;
	}

	std::cout << cn << mn << ">>>>>>>>>>>>>>>>> APPLY CORRECTIONS <<<<<<<<<<<<<<<<<" << std::endl;

	//Loop over the band bins and make sure they match, if not just do nothing

	unsigned int nBins = pdf->h_PDFBand_results->GetN();
	double *x = pdf->h_PDFBand_results->GetX();
	double *y = pdf->h_PDFBand_results->GetY();
	double *exl = pdf->h_PDFBand_results->GetEXlow();
	double *exh = pdf->h_PDFBand_results->GetEXhigh();
	double *eyl = pdf->h_PDFBand_results->GetEYlow();
	double *eyh = pdf->h_PDFBand_results->GetEYhigh();

	unsigned int nBinsCorr = corrections->GetNumberOfBins();
	double *c_x = &(corrections->GetTotalX().at(0));
	double *c_exl = &(corrections->GetTotalEXL().at(0));
	double *c_exh = &(corrections->GetTotalEXH().at(0));
	double *c_y = &(corrections->GetTotalYCorrections().at(0));
	double *c_eyl = &(corrections->GetTotalEYLCorrections().at(0));
	double *c_eyh = &(corrections->GetTotalEYHCorrections().at(0));

	//Loop over the smallest of the two
	unsigned int n = (nBins < nBinsCorr ? nBins : nBinsCorr);

	for(int i = 0; i < nBins; i++) {
		for(int j = 0; j < nBinsCorr; j++) {

			//Check for bin match
			if(((x[i] - exl[i]) == c_exl[j]) && ((x[i] + exh[i]) == c_exh[j])) {

				if(debug) std::cout << cn << mn << "Bins Match (i, j): (" << i << ", " << j << ")" << std::endl;

				//Bins match; Scale y, eyl, and eyh
				y[i] *= c_y[j];
				eyl[i] *= c_eyl[j];
				eyh[i] *= c_eyh[j];

				break;
			}
		}
	}

	//@TODO Do the same for Alpha S and Scale uncertainty bands
}
<commit_msg>Setting convolute name properly<commit_after>//************************************************************/
//
//	CrossSection Implementation
//
//	Implements the SPXCrossSection class, which performs the
//	convolution and all math required to calculate the cross-
//	section from a PDF and a grid file.
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		14.10.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include "SPXCrossSection.h"
#include "SPXUtilities.h"
#include "SPXException.h"

//Class name for debug statements
const std::string cn = "SPXCrossSection::";

//Must define the static debug variable in the implementation
bool SPXCrossSection::debug;

//Create the CrossSection
void SPXCrossSection::Create(void) {
	std::string mn = "Create: ";

	//Attempt to create the Grid
	try {
		grid = new SPXGrid(pci);
	} catch(const SPXException &e) {
		throw;
	}

	//Attempt to create the PDF object and perform convolution
	try {
		pdf = new SPXPDF(psf, grid->GetGridName());
	} catch(const SPXException &e) {
		throw;
	}

	//Set the name of the convolution graphs appropriately
	//Create name strings
	TString name;
	TString pdfName;
	TString alphaSName;
	TString scaleName;

	//Check if name exists
	if(!pci->gridSteeringFile.GetName().empty()) {
		name = TString(pci->gridSteeringFile.GetName());
		pdfName = name + "_pdf";
		alphaSName = name + "_alpha_s";
		scaleName = name + "_scale";
	}

	//Grid steering file has no [DESC]:name
	//Default to filename
	else {
		if(debug) std::cout << cn << mn << "Grid steering file has no name value: using filename instead" << std::endl;
		name = pci->gridSteeringFile.GetFilename();
		name.ReplaceAll(TString(".txt"), TString(""));
		pdfName = name + "_pdf";
		alphaSName = name + "_alpha_s";
		scaleName = name + "_scale";
	}

	//Set the graph names
	pdf->h_PDFBand_results->SetName(pdfName);
	pdf->h_AlphaS_results->SetName(alphaSName);
	pdf->h_Scale_results->SetName(scaleName);
}

void SPXCrossSection::ParseCorrections(void) {
	//Check if grid contains corrections
	if(pci->gridSteeringFile.GetNumberOfCorrectionFiles() != 0) {
		try {
			corrections = new SPXGridCorrections(*pci);
			corrections->Parse();
			corrections->Print();
		} catch(const SPXException &e) {
			throw;
		}
	}
}

void SPXCrossSection::ApplyCorrections(void) {
	std::string mn = "ApplyCorrections: ";

	if(pci->gridSteeringFile.GetNumberOfCorrectionFiles() == 0) {
		return;
	}

	std::cout << cn << mn << ">>>>>>>>>>>>>>>>> APPLY CORRECTIONS <<<<<<<<<<<<<<<<<" << std::endl;

	//Loop over the band bins and make sure they match, if not just do nothing

	unsigned int nBins = pdf->h_PDFBand_results->GetN();
	double *x = pdf->h_PDFBand_results->GetX();
	double *y = pdf->h_PDFBand_results->GetY();
	double *exl = pdf->h_PDFBand_results->GetEXlow();
	double *exh = pdf->h_PDFBand_results->GetEXhigh();
	double *eyl = pdf->h_PDFBand_results->GetEYlow();
	double *eyh = pdf->h_PDFBand_results->GetEYhigh();

	unsigned int nBinsCorr = corrections->GetNumberOfBins();
	double *c_x = &(corrections->GetTotalX().at(0));
	double *c_exl = &(corrections->GetTotalEXL().at(0));
	double *c_exh = &(corrections->GetTotalEXH().at(0));
	double *c_y = &(corrections->GetTotalYCorrections().at(0));
	double *c_eyl = &(corrections->GetTotalEYLCorrections().at(0));
	double *c_eyh = &(corrections->GetTotalEYHCorrections().at(0));

	//Loop over the smallest of the two
	unsigned int n = (nBins < nBinsCorr ? nBins : nBinsCorr);

	for(int i = 0; i < nBins; i++) {
		for(int j = 0; j < nBinsCorr; j++) {

			//Check for bin match
			if(((x[i] - exl[i]) == c_exl[j]) && ((x[i] + exh[i]) == c_exh[j])) {

				if(debug) std::cout << cn << mn << "Bins Match (i, j): (" << i << ", " << j << ")" << std::endl;

				//Bins match; Scale y, eyl, and eyh
				y[i] *= c_y[j];
				eyl[i] *= c_eyl[j];
				eyh[i] *= c_eyh[j];

				break;
			}
		}
	}

	//@TODO Do the same for Alpha S and Scale uncertainty bands
}
<|endoftext|>


<commit_before>#include "HOffsetManager.h"

#include <sstream>
#include <fstream>
#include <iomanip>

#include "../Utilis/HUtilis.h"
#include "../NetVarManager/HNetVarManager.h"

namespace Dumper
{
    namespace OffsetManager
    {
        void COffsetManager::Dump( void )
        {
            if( !pProcess->GetModuleByName( "client.dll" ) || !pProcess->GetModuleByName( "engine.dll" ) )
                return;

            std::stringstream ss;
            ss << "- - - - - - Tool by Y3t1y3t ( uc ) - - - - - - " << std::endl;
            ss << "| -> http://www.unknowncheats.me/forum/counterstrike-global-offensive/100856-cs-go-offset-dumper-small-one.html" << std::endl;
            ss << "| -> " << Utilis::GetTime();
            ss << "- -" << std::endl << std::endl;

            DumpNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty", 0x0, ss );

            DumpNetVar( "DT_BaseAnimating", "m_nForceBone", 0x0, ss );

            DumpNetVar( "DT_BaseCombatWeapon", "m_iState", 0x0, ss );
            DumpNetVar( "DT_BaseCombatWeapon", "m_iClip1", 0x0, ss );
            DumpNetVar( "DT_BaseCombatWeapon", "m_flNextPrimaryAttack", 0x0, ss );

            DumpPatternOffset( "DT_BaseCombatWeapon", "m_bCanReload", "client.dll",
                               "80 B9 ? ? ? ? ? 0F 85 ? ? ? ? A1",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpNetVar( "DT_BaseCombatWeapon", "m_iPrimaryAmmoType", 0x0, ss );

            LogToStringStream( "DT_BaseCombatWeapon", "m_iWeaponID",
                               pNetVarManager->GetNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty" ) + 0x2C, ss );

            DumpNetVar( "DT_WeaponCSBaseGun", "m_zoomLevel", 0x0, ss );

            DumpNetVar( "DT_BaseEntity", "m_bSpotted", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_bSpottedByMask", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_hOwnerEntity", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_vecOrigin", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_iTeamNum", 0x0, ss );

            DumpNetVar( "DT_CSPlayer", "m_flFlashMaxAlpha", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_flFlashDuration", 0x0, ss );

            LogToStringStream( "DT_CSPlayer", "m_iGlowIndex",
                               pNetVarManager->GetNetVar( "DT_CSPlayer", "m_flFlashDuration" ) + 0x18, ss );

            DumpNetVar( "DT_CSPlayer", "m_angEyeAngles", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_iAccount", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_ArmorValue", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_bGunGameImmunity", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_iShotsFired", 0x0, ss );

            DumpPatternOffset( "DT_CSPlayerResource", "CSPlayerResource", "client.dll",
                               "8B 3D ? ? ? ? 85 FF 0F 84 ? ? ? ? 81 C7",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveRanking", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveWins", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iKills", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iAssists", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iDeaths", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iPing", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iScore", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_szClan", 0x0, ss );

            DumpNetVar( "DT_BasePlayer", "m_lifeState", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_fFlags", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_iHealth", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hLastWeapon", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hMyWeapons", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hActiveWeapon", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_Local", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_vecViewOffset[0]", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_nTickBase", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_vecVelocity[0]", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_szLastPlaceName", 0x0, ss );

            LogToStringStream( "DT_Local", "m_vecPunch",
                               pNetVarManager->GetNetVar( "DT_BasePlayer", "m_Local" ) + 0x70, ss );
            LogToStringStream( "DT_Local", "m_iCrossHairID",
                               pNetVarManager->GetNetVar( "DT_CSPlayer", "m_bHasDefuser" ) + 0x4C, ss );

            LogToStringStream( "BaseEntity", "m_dwModel", 0x6C, ss );
            LogToStringStream( "BaseEntity", "m_dwIndex", 0x64, ss );
            LogToStringStream( "BaseEntity", "m_dwBoneMatrix",
                               pNetVarManager->GetNetVar( "DT_BaseAnimating", "m_nForceBone" ) + 0x1C, ss );
            LogToStringStream( "BaseEntity", "m_bMoveType", 0x258, ss );
            LogToStringStream( "BaseEntity", "m_bDormant", 0xE9, ss );

            DumpPatternOffset( "ClientState", "m_dwClientState", "engine.dll",
                               "A1 ? ? ? ? F3 0F 11 80 ? ? ? ? D9 46 04 D9 05",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwLocalPlayerIndex", "engine.dll",
                               "8B 80 ? ? ? ? 40 C3",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwInGame", "engine.dll",
                               "83 B9 ? ? ? ? 06 0F 94 C0 C3",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMaxPlayer", "engine.dll",
                               "A1 ? ? ? ? 8B 80 ? ? ? ? C3 CC CC CC CC 55 8B EC 8B 45 08",
                               Remote::SignatureType_t::READ, 0x7, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMapDirectory", "engine.dll",
                               "05 ? ? ? ? C3 CC CC CC CC CC CC CC 80 3D",
                               Remote::SignatureType_t::READ, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMapname", "engine.dll",
                               "05 ? ? ? ? C3 CC CC CC CC CC CC CC A1",
                               Remote::SignatureType_t::READ, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwPlayerInfo", "engine.dll",
                               "8B 88 ? ? ? ? 8B 01 8B 40 ? FF D0 8B F8",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwViewAngles", "engine.dll",
                               "F3 0F 11 80 ? ? ? ? D9 46 04 D9 05 ? ? ? ?",
                               Remote::SignatureType_t::READ, 0x4, 0x0, ss );

            DumpPatternOffset( "EngineRender", "m_dwViewMatrix", "client.dll",
                               "81 C6 ? ? ? ? 88 45 92 0F B6 C0",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x33C, 0xB0, ss );

            DumpPatternOffset( "EngineRender", "m_dwEnginePosition", "engine.dll",
                               "F3 0F 11 15 ? ? ? ? F3 0F 11 0D ? ? ? ? F3 0F 11 05 ? ? ? ? F3 0F 11 3D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss );

            DumpPatternOffset( "RadarBase", "m_dwRadarBase", "client.dll",
                               "A1 ? ? ? ? 8B 0C B0 8B 01 FF 50 ? 46 3B 35 ? ? ? ? 7C EA 8B 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpNetVar( "RadarBase", "m_dwRadarBasePointer", 0x50, ss );

            DumpPatternOffset( "LocalPlayer", "m_dwLocalPlayer", "client.dll",
                               "A3 ? ? ? ? C7 05 ? ? ? ? ? ? ? ? E8 ? ? ? ? 59 C3 6A",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x10, ss );

            DumpPatternOffset( "EntityList", "m_dwEntityList", "client.dll",
                               "BB ? ? ? ? 83 FF 01 0F 8C ? ? ? ? 3B F8",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "WeaponTable", "m_dwWeaponTable", "client.dll",
                               "A1 ? ? ? ? 0F B7 C9 03 C9 8B 44 ? 0C C3",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "WeaponTable", "m_dwWeaponTableIndex", "client.dll",
                               "66 8B 8E ? ? ? ? E8 ? ? ? ? 05 ? ? ? ? 50",
                               Remote::SignatureType_t::READ, 0x3, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwInput", "client.dll",
                               "B9 ? ? ? ? FF 75 08 E8 ? ? ? ? 8B 06",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwGlobalVars", "engine.dll",
                               "8B 0D ? ? ? ? 83 C4 04 8B 01 68 ? ? ? ? FF 35",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x12, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwGlowObject", "client.dll",
                               "A1 ? ? ? ? A8 01 75 ? 0F 57 C0 C7 05",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x58, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwForceJump", "client.dll",
                               "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 08",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwForceAttack", "client.dll"
                               , "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 04",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwSensitivity", "client.dll",
                               "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwMouseEnable", "client.dll",
                               "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x5C, ss );

            std::ofstream( "OffsetManager.txt" ) << ss.str();
        }

        void COffsetManager::DumpNetVar( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss )
        {
            LogToStringStream( tablename, varname, pNetVarManager->GetNetVar( tablename, varname ) + offset, ss );
        }

        void COffsetManager::DumpPatternOffset( const std::string& tablename, const std::string& varname, const std::string& module, const char* pattern, int type, uintptr_t pattern_offset, uintptr_t address_offset, std::stringstream& ss )
        {
            LogToStringStream( tablename, varname, pProcess->FindPattern( module, pattern, type, pattern_offset, address_offset ), ss );
        }

        void COffsetManager::LogToStringStream( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss )
        {
            ss << std::setw( 48 )
                << std::setfill( '_' )
                << std::left
                << tablename + " -> " + varname + ": "
                << std::right
                << std::hex
                << " 0x"
                << std::setw( 8 )
                << std::setfill( '0' )
                << std::uppercase
                << offset << std::endl;
        }

        COffsetManager* COffsetManager::Singleton( void )
        {
            static auto g_pOffsetManager = new COffsetManager();
            return g_pOffsetManager;
        }
    }
}

<commit_msg>Added pattern offset signature thanks to issue #9<commit_after>#include "HOffsetManager.h"

#include <sstream>
#include <fstream>
#include <iomanip>

#include "../Utilis/HUtilis.h"
#include "../NetVarManager/HNetVarManager.h"

namespace Dumper
{
    namespace OffsetManager
    {
        void COffsetManager::Dump( void )
        {
            if( !pProcess->GetModuleByName( "client.dll" ) || !pProcess->GetModuleByName( "engine.dll" ) )
                return;

            std::stringstream ss;
            ss << "- - - - - - Tool by Y3t1y3t ( uc ) - - - - - - " << std::endl;
            ss << "| -> http://www.unknowncheats.me/forum/counterstrike-global-offensive/100856-cs-go-offset-dumper-small-one.html" << std::endl;
            ss << "| -> " << Utilis::GetTime();
            ss << "- -" << std::endl << std::endl;

            DumpNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty", 0x0, ss );

            DumpNetVar( "DT_BaseAnimating", "m_nForceBone", 0x0, ss );

            DumpNetVar( "DT_BaseCombatWeapon", "m_iState", 0x0, ss );
            DumpNetVar( "DT_BaseCombatWeapon", "m_iClip1", 0x0, ss );
            DumpNetVar( "DT_BaseCombatWeapon", "m_flNextPrimaryAttack", 0x0, ss );

            DumpPatternOffset( "DT_BaseCombatWeapon", "m_bCanReload", "client.dll",
                               "80 B9 ? ? ? ? ? 0F 85 ? ? ? ? A1",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpNetVar( "DT_BaseCombatWeapon", "m_iPrimaryAmmoType", 0x0, ss );

            LogToStringStream( "DT_BaseCombatWeapon", "m_iWeaponID",
                               pNetVarManager->GetNetVar( "DT_WeaponCSBase", "m_fAccuracyPenalty" ) + 0x2C, ss );

            DumpNetVar( "DT_WeaponCSBaseGun", "m_zoomLevel", 0x0, ss );

            DumpNetVar( "DT_BaseEntity", "m_bSpotted", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_bSpottedByMask", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_hOwnerEntity", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_vecOrigin", 0x0, ss );
            DumpNetVar( "DT_BaseEntity", "m_iTeamNum", 0x0, ss );

            DumpNetVar( "DT_CSPlayer", "m_flFlashMaxAlpha", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_flFlashDuration", 0x0, ss );

            LogToStringStream( "DT_CSPlayer", "m_iGlowIndex",
                               pNetVarManager->GetNetVar( "DT_CSPlayer", "m_flFlashDuration" ) + 0x18, ss );

            DumpNetVar( "DT_CSPlayer", "m_angEyeAngles", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_iAccount", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_ArmorValue", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_bGunGameImmunity", 0x0, ss );
            DumpNetVar( "DT_CSPlayer", "m_iShotsFired", 0x0, ss );

            DumpPatternOffset( "DT_CSPlayerResource", "CSPlayerResource", "client.dll",
                               "8B 3D ? ? ? ? 85 FF 0F 84 ? ? ? ? 81 C7",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpPatternOffset( "BaseEntity", "m_bDormant", "client.dll",
                               "88 9E ? ? ? ? E8 ? ? ? ? 53 8D 8E ? ? ? ? E8 ? ? ? ? 8B 06 8B CE 53 FF 90 ? ? ? ? 8B 46 64 0F B6 CB 5E 5B 66 89 0C C5 ? ? ? ? 5D C2 04 00",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveRanking", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iCompetitiveWins", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iKills", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iAssists", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iDeaths", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iPing", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_iScore", 0x0, ss );
            DumpNetVar( "DT_CSPlayerResource", "m_szClan", 0x0, ss );

            DumpNetVar( "DT_BasePlayer", "m_lifeState", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_fFlags", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_iHealth", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hLastWeapon", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hMyWeapons", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_hActiveWeapon", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_Local", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_vecViewOffset[0]", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_nTickBase", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_vecVelocity[0]", 0x0, ss );
            DumpNetVar( "DT_BasePlayer", "m_szLastPlaceName", 0x0, ss );

            LogToStringStream( "DT_Local", "m_vecPunch",
                               pNetVarManager->GetNetVar( "DT_BasePlayer", "m_Local" ) + 0x70, ss );
            LogToStringStream( "DT_Local", "m_iCrossHairID",
                               pNetVarManager->GetNetVar( "DT_CSPlayer", "m_bHasDefuser" ) + 0x4C, ss );

            LogToStringStream( "BaseEntity", "m_dwModel", 0x6C, ss );
            LogToStringStream( "BaseEntity", "m_dwIndex", 0x64, ss );
            LogToStringStream( "BaseEntity", "m_dwBoneMatrix",
                               pNetVarManager->GetNetVar( "DT_BaseAnimating", "m_nForceBone" ) + 0x1C, ss );
            LogToStringStream( "BaseEntity", "m_bMoveType", 0x258, ss );

            DumpPatternOffset( "ClientState", "m_dwClientState", "engine.dll",
                               "A1 ? ? ? ? F3 0F 11 80 ? ? ? ? D9 46 04 D9 05",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwLocalPlayerIndex", "engine.dll",
                               "8B 80 ? ? ? ? 40 C3",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwInGame", "engine.dll",
                               "83 B9 ? ? ? ? 06 0F 94 C0 C3",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMaxPlayer", "engine.dll",
                               "A1 ? ? ? ? 8B 80 ? ? ? ? C3 CC CC CC CC 55 8B EC 8B 45 08",
                               Remote::SignatureType_t::READ, 0x7, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMapDirectory", "engine.dll",
                               "05 ? ? ? ? C3 CC CC CC CC CC CC CC 80 3D",
                               Remote::SignatureType_t::READ, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwMapname", "engine.dll",
                               "05 ? ? ? ? C3 CC CC CC CC CC CC CC A1",
                               Remote::SignatureType_t::READ, 0x1, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwPlayerInfo", "engine.dll",
                               "8B 88 ? ? ? ? 8B 01 8B 40 ? FF D0 8B F8",
                               Remote::SignatureType_t::READ, 0x2, 0x0, ss );

            DumpPatternOffset( "ClientState", "m_dwViewAngles", "engine.dll",
                               "F3 0F 11 80 ? ? ? ? D9 46 04 D9 05 ? ? ? ?",
                               Remote::SignatureType_t::READ, 0x4, 0x0, ss );

            DumpPatternOffset( "EngineRender", "m_dwViewMatrix", "client.dll",
                               "81 C6 ? ? ? ? 88 45 92 0F B6 C0",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x33C, 0xB0, ss );

            DumpPatternOffset( "EngineRender", "m_dwEnginePosition", "engine.dll",
                               "F3 0F 11 15 ? ? ? ? F3 0F 11 0D ? ? ? ? F3 0F 11 05 ? ? ? ? F3 0F 11 3D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss );

            DumpPatternOffset( "RadarBase", "m_dwRadarBase", "client.dll",
                               "A1 ? ? ? ? 8B 0C B0 8B 01 FF 50 ? 46 3B 35 ? ? ? ? 7C EA 8B 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpNetVar( "RadarBase", "m_dwRadarBasePointer", 0x50, ss );

            DumpPatternOffset( "LocalPlayer", "m_dwLocalPlayer", "client.dll",
                               "A3 ? ? ? ? C7 05 ? ? ? ? ? ? ? ? E8 ? ? ? ? 59 C3 6A",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x10, ss );

            DumpPatternOffset( "EntityList", "m_dwEntityList", "client.dll",
                               "BB ? ? ? ? 83 FF 01 0F 8C ? ? ? ? 3B F8",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "WeaponTable", "m_dwWeaponTable", "client.dll",
                               "A1 ? ? ? ? 0F B7 C9 03 C9 8B 44 ? 0C C3",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "WeaponTable", "m_dwWeaponTableIndex", "client.dll",
                               "66 8B 8E ? ? ? ? E8 ? ? ? ? 05 ? ? ? ? 50",
                               Remote::SignatureType_t::READ, 0x3, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwInput", "client.dll",
                               "B9 ? ? ? ? FF 75 08 E8 ? ? ? ? 8B 06",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x1, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwGlobalVars", "engine.dll",
                               "8B 0D ? ? ? ? 83 C4 04 8B 01 68 ? ? ? ? FF 35",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x12, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwGlowObject", "client.dll",
                               "A1 ? ? ? ? A8 01 75 ? 0F 57 C0 C7 05",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x58, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwForceJump", "client.dll",
                               "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 08",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwForceAttack", "client.dll"
                               , "89 15 ? ? ? ? 8B 15 ? ? ? ? F6 C2 03 74 03 83 CE 04",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x2, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwSensitivity", "client.dll",
                               "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x0, ss );

            DumpPatternOffset( "Extra", "m_dwMouseEnable", "client.dll",
                               "F3 0F 10 05 ? ? ? ? EB 17 8B 01 8B 40 30 FF D0 F3 0F 10 0D",
                               Remote::SignatureType_t::READ | Remote::SignatureType_t::SUBTRACT, 0x4, 0x5C, ss );

            std::ofstream( "OffsetManager.txt" ) << ss.str();
        }

        void COffsetManager::DumpNetVar( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss )
        {
            LogToStringStream( tablename, varname, pNetVarManager->GetNetVar( tablename, varname ) + offset, ss );
        }

        void COffsetManager::DumpPatternOffset( const std::string& tablename, const std::string& varname, const std::string& module, const char* pattern, int type, uintptr_t pattern_offset, uintptr_t address_offset, std::stringstream& ss )
        {
            LogToStringStream( tablename, varname, pProcess->FindPattern( module, pattern, type, pattern_offset, address_offset ), ss );
        }

        void COffsetManager::LogToStringStream( const std::string& tablename, const std::string& varname, uintptr_t offset, std::stringstream& ss )
        {
            ss << std::setw( 48 )
                << std::setfill( '_' )
                << std::left
                << tablename + " -> " + varname + ": "
                << std::right
                << std::hex
                << " 0x"
                << std::setw( 8 )
                << std::setfill( '0' )
                << std::uppercase
                << offset << std::endl;
        }

        COffsetManager* COffsetManager::Singleton( void )
        {
            static auto g_pOffsetManager = new COffsetManager();
            return g_pOffsetManager;
        }
    }
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractSelectedPolyDataIds.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkExtractSelectedPolyDataIds.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkSelection.h"

vtkCxxRevisionMacro(vtkExtractSelectedPolyDataIds, "1.4");
vtkStandardNewMacro(vtkExtractSelectedPolyDataIds);

//----------------------------------------------------------------------------
vtkExtractSelectedPolyDataIds::vtkExtractSelectedPolyDataIds()
{
  this->SetNumberOfInputPorts(2);
}

//----------------------------------------------------------------------------
vtkExtractSelectedPolyDataIds::~vtkExtractSelectedPolyDataIds()
{
}

//----------------------------------------------------------------------------
int vtkExtractSelectedPolyDataIds::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *selInfo = inputVector[1]->GetInformationObject(0);
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkPolyData *input = vtkPolyData::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkSelection *sel = vtkSelection::SafeDownCast(
    selInfo->Get(vtkDataObject::DATA_OBJECT()));
  if ( ! sel )
    {
    vtkErrorMacro(<<"No selection specified");
    return 1;
    }

  vtkPointData *pd = input->GetPointData();
  vtkCellData *cd = input->GetCellData();

  vtkPointData *outputPD = output->GetPointData();
  vtkCellData *outputCD = output->GetCellData();

  vtkDebugMacro(<< "Extracting poly data geometry");

  if (!sel->GetProperties()->Has(vtkSelection::CONTENT_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::INDICES ||
      !sel->GetProperties()->Has(vtkSelection::FIELD_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::FIELD_TYPE()) != vtkSelection::CELL)
    {
    return 1;
    }

  vtkIdTypeArray* idArray =
    vtkIdTypeArray::SafeDownCast(sel->GetSelectionList());

  if (!idArray)
    {
    return 1;
    }

  vtkIdType numCells =
    idArray->GetNumberOfComponents()*idArray->GetNumberOfTuples();

  if (numCells == 0)
    {
    return 1;
    }

  output->Allocate(numCells);
  output->SetPoints(input->GetPoints());
  outputPD->PassData(pd);

  // Now loop over all cells to see whether they are in the selection.
  // Copy if they are.

  vtkIdList* ids = vtkIdList::New();

  vtkIdType numInputCells = input->GetNumberOfCells();
  for (vtkIdType i=0; i < numCells; i++)
    {
    vtkIdType cellId = idArray->GetValue(i);
    if (cellId >= numInputCells)
      {
      continue;
      }
    input->GetCellPoints(cellId, ids);
    vtkIdType newId = output->InsertNextCell(
      input->GetCellType(cellId), ids);
    outputCD->CopyData(cd, cellId, newId);
    }
  ids->Delete();
  output->Squeeze();

  return 1;
}

//----------------------------------------------------------------------------
void vtkExtractSelectedPolyDataIds::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
int vtkExtractSelectedPolyDataIds::FillInputPortInformation(
  int port, vtkInformation* info)
{
  if (port==0)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
    }
  else
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
    }
  return 1;
}
<commit_msg><commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractSelectedPolyDataIds.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkExtractSelectedPolyDataIds.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkSelection.h"

vtkCxxRevisionMacro(vtkExtractSelectedPolyDataIds, "1.5");
vtkStandardNewMacro(vtkExtractSelectedPolyDataIds);

//----------------------------------------------------------------------------
vtkExtractSelectedPolyDataIds::vtkExtractSelectedPolyDataIds()
{
  this->SetNumberOfInputPorts(2);
}

//----------------------------------------------------------------------------
vtkExtractSelectedPolyDataIds::~vtkExtractSelectedPolyDataIds()
{
}

//----------------------------------------------------------------------------
int vtkExtractSelectedPolyDataIds::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *selInfo = inputVector[1]->GetInformationObject(0);
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkPolyData *input = vtkPolyData::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkSelection *sel = vtkSelection::SafeDownCast(
    selInfo->Get(vtkDataObject::DATA_OBJECT()));
  if ( ! sel )
    {
    vtkErrorMacro(<<"No selection specified");
    return 1;
    }

  vtkPointData *pd = input->GetPointData();
  vtkCellData *cd = input->GetCellData();

  vtkPointData *outputPD = output->GetPointData();
  vtkCellData *outputCD = output->GetCellData();

  vtkDebugMacro(<< "Extracting poly data geometry");

  if (!sel->GetProperties()->Has(vtkSelection::CONTENT_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::CONTENT_TYPE()) != vtkSelection::INDICES ||
      !sel->GetProperties()->Has(vtkSelection::FIELD_TYPE()) ||
      sel->GetProperties()->Get(vtkSelection::FIELD_TYPE()) != vtkSelection::CELL)
    {
    return 1;
    }

  vtkIdTypeArray* idArray =
    vtkIdTypeArray::SafeDownCast(sel->GetSelectionList());

  if (!idArray)
    {
    return 1;
    }

  vtkIdType numCells =
    idArray->GetNumberOfComponents()*idArray->GetNumberOfTuples();

  if (numCells == 0)
    {
    return 1;
    }

  output->Allocate(numCells);
  output->SetPoints(input->GetPoints());
  outputPD->PassData(pd);
  outputCD->CopyAllocate(cd);

  // Now loop over all cells to see whether they are in the selection.
  // Copy if they are.

  vtkIdList* ids = vtkIdList::New();

  vtkIdType numInputCells = input->GetNumberOfCells();
  for (vtkIdType i=0; i < numCells; i++)
    {
    vtkIdType cellId = idArray->GetValue(i);
    if (cellId >= numInputCells)
      {
      continue;
      }
    input->GetCellPoints(cellId, ids);
    vtkIdType newId = output->InsertNextCell(
      input->GetCellType(cellId), ids);
    outputCD->CopyData(cd, cellId, newId);
    }
  ids->Delete();
  output->Squeeze();

  return 1;
}

//----------------------------------------------------------------------------
void vtkExtractSelectedPolyDataIds::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
int vtkExtractSelectedPolyDataIds::FillInputPortInformation(
  int port, vtkInformation* info)
{
  if (port==0)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
    }
  else
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
    }
  return 1;
}
<|endoftext|>


<commit_before>#ifndef THREE_MOTOR_GROUP_HPP
#define THREE_MOTOR_GROUP_HPP

#include <WPILib.h>
#include <memory>

class ThreeMotorGroup : public SafePWM, public SpeedController
{
private:
	std::unique_ptr<Talon> one;
	std::unique_ptr<Talon> two;
	std::unique_ptr<Talon> three;
public:
	ThreeMotorGroup(int portOne, int portTwo, int portThree);
	ThreeMotorGroup (int portOne, int portTwo, int portThree);
	virtual ~ThreeMotorGroup();
	virtual void Set(float speed, uint8_t syncGroup = 0);
	virtual float Get();
	virtual void Disable();
	virtual void PIDWrite(float output);
};

#endif
<commit_msg>fix again<commit_after>#ifndef THREE_MOTOR_GROUP_HPP
#define THREE_MOTOR_GROUP_HPP

#include <WPILib.h>
#include <memory>

class ThreeMotorGroup : public SpeedController
{
private:
	std::unique_ptr<Talon> one;
	std::unique_ptr<Talon> two;
	std::unique_ptr<Talon> three;
public:
	ThreeMotorGroup(int portOne, int portTwo, int portThree);
	virtual ~ThreeMotorGroup();
	virtual void Set(float speed, uint8_t syncGroup);
	virtual float Get();
	virtual void Disable();
	virtual void PIDWrite(float output);
};

#endif
<|endoftext|>