<commit_before>#include "regressionloglinearbayesianform.h"
#include "ui_regressionloglinearbayesianForm.h"

RegressionLogLinearBayesianForm::RegressionLogLinearBayesianForm(QWidget *parent) :
	AnalysisForm("RegressionLogLinearBayesianForm", parent),
	ui(new Ui::RegressionLogLinearBayesianForm)
{
	ui->setupUi(this);

	_availableVariablesModel.setVariableTypesSuggested(Column::ColumnTypeScale);
	ui->listAvailableFields->setModel(&_availableVariablesModel);

	_dependentListModel = new TableModelVariablesAssigned(this);
	_dependentListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
	_dependentListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeOrdinal | Column::ColumnTypeNominal);
	_dependentListModel->setSource(&_availableVariablesModel);
	ui->counts->setModel(_dependentListModel);

	_covariatesListModel = new TableModelVariablesAssigned(this);
	_covariatesListModel->setSource(&_availableVariablesModel);
	_covariatesListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
	_covariatesListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
	ui->factors->setModel(_covariatesListModel);

	ui->buttonAssignCounts->setSourceAndTarget(ui->listAvailableFields, ui->counts);
	ui->buttonAssignFactors->setSourceAndTarget(ui->listAvailableFields, ui->factors);

	_model = new TableModelAnovaModel(this);
	ui->modelTerms->setModel(_model);
	ui->modelTerms->hide();

	connect(_covariatesListModel, SIGNAL(assignmentsChanging()), this, SLOT(factorsChanging()));
	connect(_covariatesListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
	connect(_covariatesListModel, SIGNAL(assignedTo(Terms)), _model, SLOT(addCovariates(Terms)));
	connect(_covariatesListModel, SIGNAL(unassigned(Terms)), _model, SLOT(removeVariables(Terms)));
}

RegressionLogLinearBayesianForm::~RegressionLogLinearBayesianForm()
{
	delete ui;
}

void RegressionLogLinearBayesianForm:: bindTo(Options *options, DataSet *dataSet)
{
	AnalysisForm::bindTo(options, dataSet);

	factorsChanging();

	_model->setVariables(Terms(), Terms(), _covariatesListModel->assigned());

	factorsChanged();
}

void RegressionLogLinearBayesianForm::factorsChanging()
{
	if (_options != NULL)
		_options->blockSignals(true);
}

void RegressionLogLinearBayesianForm::factorsChanged()
{
	if (_options != NULL)
		_options->blockSignals(false);
}
<commit_msg>Fix to .h capitalization<commit_after>#include "regressionloglinearbayesianform.h"
#include "ui_regressionloglinearbayesianform.h"

RegressionLogLinearBayesianForm::RegressionLogLinearBayesianForm(QWidget *parent) :
	AnalysisForm("RegressionLogLinearBayesianForm", parent),
	ui(new Ui::RegressionLogLinearBayesianForm)
{
	ui->setupUi(this);

	_availableVariablesModel.setVariableTypesSuggested(Column::ColumnTypeScale);
	ui->listAvailableFields->setModel(&_availableVariablesModel);

	_dependentListModel = new TableModelVariablesAssigned(this);
	_dependentListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
	_dependentListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeOrdinal | Column::ColumnTypeNominal);
	_dependentListModel->setSource(&_availableVariablesModel);
	ui->counts->setModel(_dependentListModel);

	_covariatesListModel = new TableModelVariablesAssigned(this);
	_covariatesListModel->setSource(&_availableVariablesModel);
	_covariatesListModel->setVariableTypesSuggested(Column::ColumnTypeScale);
	_covariatesListModel->setVariableTypesAllowed(Column::ColumnTypeScale | Column::ColumnTypeNominal | Column::ColumnTypeOrdinal);
	ui->factors->setModel(_covariatesListModel);

	ui->buttonAssignCounts->setSourceAndTarget(ui->listAvailableFields, ui->counts);
	ui->buttonAssignFactors->setSourceAndTarget(ui->listAvailableFields, ui->factors);

	_model = new TableModelAnovaModel(this);
	ui->modelTerms->setModel(_model);
	ui->modelTerms->hide();

	connect(_covariatesListModel, SIGNAL(assignmentsChanging()), this, SLOT(factorsChanging()));
	connect(_covariatesListModel, SIGNAL(assignmentsChanged()), this, SLOT(factorsChanged()));
	connect(_covariatesListModel, SIGNAL(assignedTo(Terms)), _model, SLOT(addCovariates(Terms)));
	connect(_covariatesListModel, SIGNAL(unassigned(Terms)), _model, SLOT(removeVariables(Terms)));
}

RegressionLogLinearBayesianForm::~RegressionLogLinearBayesianForm()
{
	delete ui;
}

void RegressionLogLinearBayesianForm:: bindTo(Options *options, DataSet *dataSet)
{
	AnalysisForm::bindTo(options, dataSet);

	factorsChanging();

	_model->setVariables(Terms(), Terms(), _covariatesListModel->assigned());

	factorsChanged();
}

void RegressionLogLinearBayesianForm::factorsChanging()
{
	if (_options != NULL)
		_options->blockSignals(true);
}

void RegressionLogLinearBayesianForm::factorsChanged()
{
	if (_options != NULL)
		_options->blockSignals(false);
}
<|endoftext|>


<commit_before>#include <librealsense/rs.hpp>
#include "example.hpp"

#include <cstdarg>
#include <thread>
#include <iostream>
#include <algorithm>
#pragma comment(lib, "opengl32.lib")

struct int2 { int x,y; };
struct rect
{
    int x0,y0,x1,y1;
    bool contains(const int2 & p) const { return x0 <= p.x && y0 <= p.y && p.x < x1 && p.y < y1; }
    rect shrink(int amt) const { return {x0+amt, y0+amt, x1-amt, y1-amt}; }
};
struct color { float r,g,b; };

struct gui
{
    int2 cursor, clicked_offset, scroll_vec;
    bool click, mouse_down;
    int clicked_id;

    gui() : scroll_vec({0,0}), click(), mouse_down(), clicked_id() {}

    void label(const int2 & p, const color & c, const char * format, ...)
    {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, sizeof(buffer), format, args);
        va_end(args);
        glColor3f(c.r, c.g, c.b);
        draw_text(p.x, p.y, buffer);
    }

    void fill_rect(const rect & r, const color & c)
    {
        glBegin(GL_QUADS);
        glColor3f(c.r, c.g, c.b);
        glVertex2i(r.x0, r.y0);
        glVertex2i(r.x0, r.y1);
        glVertex2i(r.x1, r.y1);
        glVertex2i(r.x1, r.y0);
        glEnd();
    }

    bool button(const rect & r, const std::string & label)
    {
        fill_rect(r, {1,1,1});
        fill_rect(r.shrink(2), r.contains(cursor) ? (mouse_down ? color{0.3f,0.3f,0.3f} : color{0.4f,0.4f,0.4f}) : color{0.5f,0.5f,0.5f});
        glColor3f(1,1,1);
        draw_text(r.x0 + 4, r.y1 - 8, label.c_str());
        return click && r.contains(cursor);
    }

    bool checkbox(const rect & r, bool & value)
    {
        bool changed = false;
        if(click && r.contains(cursor))
        {
            value = !value;
            changed = true;
        }
        fill_rect(r, {1,1,1});
        fill_rect(r.shrink(1), {0.5,0.5,0.5});
        if(value) fill_rect(r.shrink(3), {1,1,1});
        return changed;
    }

    bool slider(int id, const rect & r, double min, double max, double step, double & value)
    {
        bool changed = false;
        const int w = r.x1 - r.x0, h = r.y1 - r.y0;
        double p = (w - h) * (value - min) / (max - min);
        if(mouse_down && clicked_id == id)
        {
            p = std::max(0.0, std::min<double>(cursor.x - clicked_offset.x - r.x0, w-h));
            double new_value = min + p * (max - min) / (w - h);
            if(step) new_value = std::round((new_value - min) / step) * step + min;
            changed = new_value != value;
            value = new_value;
            p = (w - h) * (value - min) / (max - min);
        }
        const rect dragger = {int(r.x0+p), int(r.y0), int(r.x0+p+h), int(r.y1)};
        if(click && dragger.contains(cursor))
        {
            clicked_offset = {cursor.x - dragger.x0, cursor.y - dragger.y0};
            clicked_id = id;
        }
        fill_rect(r, {0.5,0.5,0.5});
        fill_rect(dragger, {1,1,1});
        return changed;
    }

    void vscroll(const rect & r, int client_height, int & offset)
    {
        if(r.contains(cursor)) offset -= scroll_vec.y * 20;
        offset = std::min(offset, client_height - (r.y1 - r.y0));
        offset = std::max(offset, 0);
        if(client_height <= r.y1 - r.y0) return;
        auto bar = r; bar.x0 = bar.x1 - 10;
        auto dragger = bar;
        dragger.y0 = bar.y0 + offset * (r.y1 - r.y0) / client_height;
        dragger.y1 = bar.y0 + (offset + r.y1 - r.y0) * (r.y1 - r.y0) / client_height;
        fill_rect(bar, {0.5,0.5,0.5});
        fill_rect(dragger, {1,1,1});
    }
};

texture_buffer buffers[4];

int main(int argc, char * argv[]) try
{
    rs::log_to_console(rs::log_severity::warn);
    //rs::log_to_file(rs::log_severity::debug, "librealsense.log");

    glfwInit();
    auto win = glfwCreateWindow(1550, 960, "CPP Configuration Example", nullptr, nullptr);
    glfwMakeContextCurrent(win);
    gui g;
    glfwSetWindowUserPointer(win, &g);
    glfwSetCursorPosCallback(win, [](GLFWwindow * w, double cx, double cy) { reinterpret_cast<gui *>(glfwGetWindowUserPointer(w))->cursor = {(int)cx, (int)cy}; });
    glfwSetScrollCallback(win, [](GLFWwindow * w, double x, double y) { reinterpret_cast<gui *>(glfwGetWindowUserPointer(w))->scroll_vec = {(int)x, (int)y}; });
    glfwSetMouseButtonCallback(win, [](GLFWwindow * w, int button, int action, int mods)
    {
        auto g = reinterpret_cast<gui *>(glfwGetWindowUserPointer(w));
        if(action == GLFW_PRESS)
        {
            g->clicked_id = 0;
            g->click = true;
        }
        g->mouse_down = action != GLFW_RELEASE;
    });

    rs::context ctx;
    if(ctx.get_device_count() < 1) throw std::runtime_error("No device found. Is it plugged in?");

    rs::device * dev = ctx.get_device(0);
    dev->enable_stream(rs::stream::depth, rs::preset::best_quality);
    dev->enable_stream(rs::stream::color, rs::preset::best_quality);
    dev->enable_stream(rs::stream::infrared, rs::preset::best_quality);
    try { dev->enable_stream(rs::stream::infrared2, rs::preset::best_quality); } catch(...) {}

    //std::this_thread::sleep_for(std::chrono::seconds(1));

    struct option { rs::option opt; double min, max, step, value, def; };
    std::vector<option> options;
    for(int i=0; i<RS_OPTION_COUNT; ++i)
    {
        option o = {(rs::option)i};
        if(!dev->supports_option(o.opt)) continue;
        dev->get_option_range(o.opt, o.min, o.max, o.step, o.def);
        if(o.min == o.max) continue;
        try { o.value = dev->get_option(o.opt); } catch(...) {}
        options.push_back(o);
    }
    double dc_preset = 0, iv_preset = 0;

    int offset = 0, panel_height = 1;
    while(!glfwWindowShouldClose(win))
    {
        glfwPollEvents();
        if(dev->is_streaming()) dev->wait_for_frames();

        int w, h;
        glfwGetFramebufferSize(win, &w, &h);
        glViewport(0, 0, w, h);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwGetWindowSize(win, &w, &h);
        glLoadIdentity();
        glOrtho(0, w, h, 0, -1, +1);

        g.vscroll({w-270, 0, w, h}, panel_height, offset);
        int y = 10 - offset;

        if(dev->is_streaming())
        {
            if(g.button({w-260, y, w-20, y+24}, "Stop Capture")) dev->stop();
        }
        else
        {
            if(g.button({w-260, y, w-20, y+24}, "Start Capture")) dev->start();
        }
        y += 34;
        if(!dev->is_streaming())
        {
            for(int i=0; i<4; ++i)
            {
                auto s = (rs::stream)i;
                bool enable = dev->is_stream_enabled(s);
                if(g.checkbox({w-260, y, w-240, y+20}, enable))
                {
                    if(enable) dev->enable_stream(s, rs::preset::best_quality);
                    else dev->disable_stream(s);
                }
                g.label({w-234, y+13}, {1,1,1}, "Enable %s", rs_stream_to_string((rs_stream)i));
                y += 30;
            }
        }

        for(auto & o : options)
        {
            std::ostringstream ss; ss << o.opt << ": " << o.value;
            g.label({w-260,y+12}, {1,1,1}, ss.str().c_str());
            if(g.slider((int)o.opt + 1, {w-260,y+16,w-20,y+36}, o.min, o.max, o.step, o.value))
            {
                dev->set_option(o.opt, o.value);
            }
            y += 38;
        }
        g.label({w-260,y+12}, {1,1,1}, "Depth control parameters preset: %g", dc_preset);
        if(g.slider(100, {w-260,y+16,w-20,y+36}, 0, 5, 1, dc_preset)) rs_apply_depth_control_preset((rs_device *)dev, static_cast<int>(dc_preset));
        y += 38;
        g.label({w-260,y+12}, {1,1,1}, "IVCAM options preset: %g", iv_preset);
        if(g.slider(101, {w-260,y+16,w-20,y+36}, 0, 10, 1, iv_preset)) rs_apply_ivcam_preset((rs_device *)dev, static_cast<rs_ivcam_preset>((int)iv_preset));
        y += 38;

        panel_height = y + 10 + offset;

        if(dev->is_streaming())
        {
            w-=270;
            buffers[0].show(*dev, rs::stream::color, 0, 0, w/2, h/2);
            buffers[1].show(*dev, rs::stream::depth, w/2, 0, w-w/2, h/2);
            buffers[2].show(*dev, rs::stream::infrared, 0, h/2, w/2, h-h/2);
            buffers[3].show(*dev, rs::stream::infrared2, w/2, h/2, w-w/2, h-h/2);
        }

        glfwSwapBuffers(win);

        g.scroll_vec = {0,0};
        g.click = false;
        if(!g.mouse_down) g.clicked_id = 0;
    }

    glfwTerminate();
    return 0;
}
catch(const rs::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}
<commit_msg>Change cpp-config-ui.cpp for streaming with Fisheye<commit_after>#include <librealsense/rs.hpp>
#include "example.hpp"

#include <cstdarg>
#include <thread>
#include <iostream>
#include <algorithm>
#include <iomanip>

#pragma comment(lib, "opengl32.lib")

struct int2 { int x,y; };
struct rect
{
    int x0,y0,x1,y1;
    bool contains(const int2 & p) const { return x0 <= p.x && y0 <= p.y && p.x < x1 && p.y < y1; }
    rect shrink(int amt) const { return {x0+amt, y0+amt, x1-amt, y1-amt}; }
};
struct color { float r,g,b; };

struct gui
{
    int2 cursor, clicked_offset, scroll_vec;
    bool click, mouse_down;
    int clicked_id;

    gui() : scroll_vec({0,0}), click(), mouse_down(), clicked_id() {}

    void label(const int2 & p, const color & c, const char * format, ...)
    {
        va_list args;
        va_start(args, format);
        char buffer[1024];
        vsnprintf(buffer, sizeof(buffer), format, args);
        va_end(args);
        glColor3f(c.r, c.g, c.b);
        draw_text(p.x, p.y, buffer);
    }

    void fill_rect(const rect & r, const color & c)
    {
        glBegin(GL_QUADS);
        glColor3f(c.r, c.g, c.b);
        glVertex2i(r.x0, r.y0);
        glVertex2i(r.x0, r.y1);
        glVertex2i(r.x1, r.y1);
        glVertex2i(r.x1, r.y0);
        glEnd();
    }

    bool button(const rect & r, const std::string & label)
    {
        fill_rect(r, {1,1,1});
        fill_rect(r.shrink(2), r.contains(cursor) ? (mouse_down ? color{0.3f,0.3f,0.3f} : color{0.4f,0.4f,0.4f}) : color{0.5f,0.5f,0.5f});
        glColor3f(1,1,1);
        draw_text(r.x0 + 4, r.y1 - 8, label.c_str());
        return click && r.contains(cursor);
    }

    bool checkbox(const rect & r, bool & value)
    {
        bool changed = false;
        if(click && r.contains(cursor))
        {
            value = !value;
            changed = true;
        }
        fill_rect(r, {1,1,1});
        fill_rect(r.shrink(1), {0.5,0.5,0.5});
        if(value) fill_rect(r.shrink(3), {1,1,1});
        return changed;
    }

    bool slider(int id, const rect & r, double min, double max, double step, double & value)
    {
        bool changed = false;
        const int w = r.x1 - r.x0, h = r.y1 - r.y0;
        double p = (w - h) * (value - min) / (max - min);
        if(mouse_down && clicked_id == id)
        {
            p = std::max(0.0, std::min<double>(cursor.x - clicked_offset.x - r.x0, w-h));
            double new_value = min + p * (max - min) / (w - h);
            if(step) new_value = std::round((new_value - min) / step) * step + min;
            changed = new_value != value;
            value = new_value;
            p = (w - h) * (value - min) / (max - min);
        }
        const rect dragger = {int(r.x0+p), int(r.y0), int(r.x0+p+h), int(r.y1)};
        if(click && dragger.contains(cursor))
        {
            clicked_offset = {cursor.x - dragger.x0, cursor.y - dragger.y0};
            clicked_id = id;
        }
        fill_rect(r, {0.5,0.5,0.5});
        fill_rect(dragger, {1,1,1});
        return changed;
    }

    void indicator(const rect & r, double min, double max, double value)
    {
        const int w = r.x1 - r.x0, h = r.y0 - r.y1;
        double p = (w) * (value - min) / (max - min);
        int Xdelta = 1;
        int Ydelta = -1;
        if (value == max)
        {
            int Xdelta =  0;
            int Ydelta = -2;
        }
        else if (value == min)
        {
            int Xdelta = 2;
            int Ydelta = 0;
        }

        const rect dragger = {int(r.x0+p+Xdelta), int(r.y0), int(r.x0+p+Ydelta), int(r.y1)};
        fill_rect(r, {0.5,0.5,0.5});
        fill_rect(dragger, {1,1,1});
        glColor3f(1,1,1);

        std::ostringstream oss;
        oss << std::setprecision(2) << std::fixed << min;
        draw_text(r.x0 - 22, r.y1 + abs(h/2) + 3, oss.str().c_str());

        oss.str("");
        oss << std::setprecision(2) << std::fixed << max;
        draw_text(r.x1 + 6, r.y1 + abs(h/2) + 3, oss.str().c_str());

        oss.str("");
        oss << std::setprecision(2) << std::fixed << value;
        draw_text(dragger.x0 - 1, dragger.y0 + 12, oss.str().c_str());
    }

    void vscroll(const rect & r, int client_height, int & offset)
    {
        if(r.contains(cursor)) offset -= scroll_vec.y * 20;
        offset = std::min(offset, client_height - (r.y1 - r.y0));
        offset = std::max(offset, 0);
        if(client_height <= r.y1 - r.y0) return;
        auto bar = r; bar.x0 = bar.x1 - 10;
        auto dragger = bar;
        dragger.y0 = bar.y0 + offset * (r.y1 - r.y0) / client_height;
        dragger.y1 = bar.y0 + (offset + r.y1 - r.y0) * (r.y1 - r.y0) / client_height;
        fill_rect(bar, {0.5,0.5,0.5});
        fill_rect(dragger, {1,1,1});
    }
};

texture_buffer buffers[6];

int main(int argc, char * argv[]) try
{
    rs::log_to_console(rs::log_severity::warn);
    //rs::log_to_file(rs::log_severity::debug, "librealsense.log");

    glfwInit();
    auto win = glfwCreateWindow(1100, 960, "CPP Configuration Example", nullptr, nullptr);
    glfwMakeContextCurrent(win);
    gui g;
    glfwSetWindowUserPointer(win, &g);
    glfwSetCursorPosCallback(win, [](GLFWwindow * w, double cx, double cy) { reinterpret_cast<gui *>(glfwGetWindowUserPointer(w))->cursor = {(int)cx, (int)cy}; });
    glfwSetScrollCallback(win, [](GLFWwindow * w, double x, double y) { reinterpret_cast<gui *>(glfwGetWindowUserPointer(w))->scroll_vec = {(int)x, (int)y}; });
    glfwSetMouseButtonCallback(win, [](GLFWwindow * w, int button, int action, int mods)
    {
        auto g = reinterpret_cast<gui *>(glfwGetWindowUserPointer(w));
        if(action == GLFW_PRESS)
        {
            g->clicked_id = 0;
            g->click = true;
        }
        g->mouse_down = action != GLFW_RELEASE;
    });

    rs::context ctx;
    if(ctx.get_device_count() < 1) throw std::runtime_error("No device found. Is it plugged in?");

    rs::device * dev = ctx.get_device(0);
    dev->enable_stream(rs::stream::depth, rs::preset::best_quality);
    dev->enable_stream(rs::stream::color, rs::preset::best_quality);
    dev->enable_stream(rs::stream::infrared, rs::preset::best_quality);
    try { dev->enable_stream(rs::stream::infrared2, rs::preset::best_quality); } catch(...) {}
    try { dev->enable_stream(rs::stream::fisheye, rs::preset::best_quality);} catch(...) {}

    //std::this_thread::sleep_for(std::chrono::seconds(1));

    struct option { rs::option opt; double min, max, step, value, def; };
    std::vector<option> options;
    for(int i=0; i<RS_OPTION_COUNT; ++i)
    {
        option o = {(rs::option)i};
        if(!dev->supports_option(o.opt)) continue;
        dev->get_option_range(o.opt, o.min, o.max, o.step, o.def);
        if(o.min == o.max) continue;
        try { o.value = dev->get_option(o.opt); } catch(...) {}
        options.push_back(o);
    }
    double dc_preset = 0, iv_preset = 0;

    int offset = 0, panel_height = 1;
    while(!glfwWindowShouldClose(win))
    {
        glfwPollEvents();
        if(dev->is_streaming()) dev->wait_for_frames();

        int w, h;
        glfwGetFramebufferSize(win, &w, &h);
        glViewport(0, 0, w, h);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwGetWindowSize(win, &w, &h);
        glLoadIdentity();
        glOrtho(0, w, h, 0, -1, +1);

        g.vscroll({w-270, 0, w, h}, panel_height, offset);
        int y = 10 - offset;

        if(dev->is_streaming())
        {
            if(g.button({w-260, y, w-20, y+24}, "Stop Capture")) dev->stop();
        }
        else
        {
            if(g.button({w-260, y, w-20, y+24}, "Start Capture")) dev->start();
        }
        y += 34;
        if(!dev->is_streaming())
        {
            for(int i=0; i<5; ++i)
            {
                auto s = (rs::stream)i;
                bool enable = dev->is_stream_enabled(s);
                if(g.checkbox({w-260, y, w-240, y+20}, enable))
                {
                    if(enable) dev->enable_stream(s, rs::preset::best_quality);
                    else dev->disable_stream(s);
                }
                g.label({w-234, y+13}, {1,1,1}, "Enable %s", rs_stream_to_string((rs_stream)i));
                y += 30;
            }
        }

        for(auto & o : options)
        {
            std::ostringstream ss; ss << o.opt << ": " << o.value;
            g.label({w-260,y+12}, {1,1,1}, ss.str().c_str());
            if(g.slider((int)o.opt + 1, {w-260,y+16,w-20,y+36}, o.min, o.max, o.step, o.value))
            {
                dev->set_option(o.opt, o.value);
            }
            y += 38;
        }
        g.label({w-260,y+12}, {1,1,1}, "Depth control parameters preset: %g", dc_preset);
        if(g.slider(100, {w-260,y+16,w-20,y+36}, 0, 5, 1, dc_preset)) rs_apply_depth_control_preset((rs_device *)dev, static_cast<int>(dc_preset));
        y += 38;
        g.label({w-260,y+12}, {1,1,1}, "IVCAM options preset: %g", iv_preset);
        if(g.slider(101, {w-260,y+16,w-20,y+36}, 0, 10, 1, iv_preset)) rs_apply_ivcam_preset((rs_device *)dev, static_cast<rs_ivcam_preset>((int)iv_preset));
        y += 38;

        panel_height = y + 10 + offset;

        if(dev->is_streaming())
        {
            w+=150;
            buffers[0].show(*dev, rs::stream::color, 0, 0, w/3, h/3);
            buffers[1].show(*dev, rs::stream::depth, w/3, 0, w/3, h/3);
            buffers[2].show(*dev, rs::stream::infrared, 0, h/3, w/3, h/3);
            buffers[3].show(*dev, rs::stream::infrared2, w/3, h/3, w/3, h/3);
            buffers[4].show(*dev, rs::stream::fisheye, 0, 2*h/3, w/3, h/3);

            int x = w/3 + 5;
            int y = 2*h/3 + 5;
            buffers[5].print(x, y, "MM (200 Hz)");
            buffers[5].print(x, y + 16, "Gyro: ");
            g.indicator({x + 100, y + 26 , x + 300, y + 18}, 0, 100, 40);
        }

        glfwSwapBuffers(win);

        g.scroll_vec = {0,0};
        g.click = false;
        if(!g.mouse_down) g.clicked_id = 0;
    }

    glfwTerminate();
    return 0;
}
catch(const rs::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexScriptol.cxx
 ** Lexer for Scriptol.
 **/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)
{
    char s[100] = "";
    bool wordIsNumber = isdigit(styler[start]) != 0;
    for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
     {
           s[i] = styler[start + i];
           s[i + 1] = '\0';
     }
    char chAttr = SCE_SCRIPTOL_IDENTIFIER;
    if (0 == strcmp(prevWord, "class"))       chAttr = SCE_SCRIPTOL_CLASSNAME;
    else if (wordIsNumber)                    chAttr = SCE_SCRIPTOL_NUMBER;
    else if (keywords.InList(s))              chAttr = SCE_SCRIPTOL_KEYWORD;
    else for (unsigned int i = 0; i < end - start + 1; i++)  // test dotted idents
    {
        if (styler[start + i] == '.')
        {
            styler.ColourTo(start + i - 1, chAttr);
            styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);
        }
    }
    styler.ColourTo(end, chAttr);
    strcpy(prevWord, s);
}

static bool IsSolComment(Accessor &styler, int pos, int len)
{
   if(len > 0)
   {
     char c = styler[pos];
     if(c == '`') return true;
     if(len > 1)
     {
        if(c == '/')
        {
          c = styler[pos + 1];
          if(c == '/') return true;
          if(c == '*') return true;
        }
     }
   }
   return false;
}

static bool IsSolStringStart(char ch)
{
    if (ch == '\'' || ch == '"')  return true;
    return false;
}

static bool IsSolWordStart(char ch)
{
    return (iswordchar(ch) && !IsSolStringStart(ch));
}

static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
{
	char ch = styler.SafeGetCharAt(i);
	char chNext = styler.SafeGetCharAt(i + 1);

        if (ch != '\"' && ch != '\'')
        {
            *nextIndex = i + 1;
            return SCE_SCRIPTOL_DEFAULT;
	}
        // ch is either single or double quotes in string
        // code below seem non-sense but is here for future extensions
	if (ch == chNext && ch == styler.SafeGetCharAt(i + 2))
        {
          *nextIndex = i + 3;
          if(ch == '\"') return SCE_SCRIPTOL_TRIPLE;
          if(ch == '\'') return SCE_SCRIPTOL_TRIPLE;
          return SCE_SCRIPTOL_STRING;
	}
        else
        {
          *nextIndex = i + 1;
          if (ch == '"') return SCE_SCRIPTOL_STRING;
          else           return SCE_SCRIPTOL_STRING;
	}
}

static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
                            WordList *keywordlists[], Accessor &styler)
 {

	int lengthDoc = startPos + length;
        char stringType = '\"';

	if (startPos > 0)
        {
            int lineCurrent = styler.GetLine(startPos);
            if (lineCurrent > 0)
            {
              startPos = styler.LineStart(lineCurrent-1);
              if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;
              else               initStyle = styler.StyleAt(startPos-1);
            }
	}

	styler.StartAt(startPos, 127);

	WordList &keywords = *keywordlists[0];

	int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
	char prevWord[200];
	prevWord[0] = '\0';
        if (length == 0)  return;

	int state = initStyle & 31;

	int nextIndex = 0;
        char chPrev  = ' ';
        char chPrev2 = ' ';
        char chNext  = styler[startPos];
	styler.StartSegment(startPos);
	bool atStartLine = true;
	int spaceFlags = 0;
	for (int i = startPos; i < lengthDoc; i++)
        {

         if (atStartLine)
         {
         char chBad = static_cast<char>(64);
         char chGood = static_cast<char>(0);
         char chFlags = chGood;

         if (whingeLevel == 1)
         {
             chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;
         }
         else if (whingeLevel == 2)
         {
             chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;
         }
         else if (whingeLevel == 3)
         {
             chFlags = (spaceFlags & wsSpace) ? chBad : chGood;
         }
         else if (whingeLevel == 4)
         {
              chFlags = (spaceFlags & wsTab) ? chBad : chGood;
         }
         styler.SetFlags(chFlags, static_cast<char>(state));
         atStartLine = false;
       }

       char ch = chNext;
       chNext = styler.SafeGetCharAt(i + 1);

       if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
       {
          if ((state == SCE_SCRIPTOL_DEFAULT) ||
              (state == SCE_SCRIPTOL_TRIPLE) ||
              (state == SCE_SCRIPTOL_COMMENTBLOCK))
          {
              styler.ColourTo(i, state);
          }
          atStartLine = true;
        }

        if (styler.IsLeadByte(ch))
         {
             chNext = styler.SafeGetCharAt(i + 2);
             chPrev  = ' ';
             chPrev2 = ' ';
             i += 1;
             continue;
         }

        if (state == SCE_SCRIPTOL_STRINGEOL)
         {
             if (ch != '\r' && ch != '\n')
             {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_DEFAULT;
             }
         }

        if (state == SCE_SCRIPTOL_DEFAULT)
         {
            if (IsSolWordStart(ch))
            {
                 styler.ColourTo(i - 1, state);
                 state = SCE_SCRIPTOL_KEYWORD;
            }
            else if (ch == '`')
            {
                styler.ColourTo(i - 1, state);
                state = SCE_SCRIPTOL_COMMENTLINE;
            }
            else if (ch == '/')
            {
                styler.ColourTo(i - 1, state);
                if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE;
                if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;
            }

            else if (IsSolStringStart(ch))
            {
               styler.ColourTo(i - 1, state);
               state = GetSolStringState(styler, i, &nextIndex);
               if(state == SCE_SCRIPTOL_STRING)
               {
                 stringType = ch;
               }
               if (nextIndex != i + 1)
               {
                   i = nextIndex - 1;
                   ch = ' ';
                   chPrev = ' ';
                   chNext = styler.SafeGetCharAt(i + 1);
               }
           }
            else if (isoperator(ch))
            {
                 styler.ColourTo(i - 1, state);
                 styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
            }
          }
          else if (state == SCE_SCRIPTOL_KEYWORD)
          {
              if (!iswordchar(ch))
              {
                 ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);
                 state = SCE_SCRIPTOL_DEFAULT;
                 if (ch == '`')
                 {
                     state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;
                 }
                 else if (IsSolStringStart(ch))
                 {
                    styler.ColourTo(i - 1, state);
                    state = GetSolStringState(styler, i, &nextIndex);
                    if (nextIndex != i + 1)
                    {
                       i = nextIndex - 1;
                       ch = ' ';
                       chPrev = ' ';
                       chNext = styler.SafeGetCharAt(i + 1);
                     }
                 }
                 else if (isoperator(ch))
                 {
                     styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
                 }
             }
          }
          else
          {
            if (state == SCE_SCRIPTOL_COMMENTLINE ||
                state == SCE_SCRIPTOL_PERSISTENT ||
                state == SCE_SCRIPTOL_CSTYLE)
            {
                 if (ch == '\r' || ch == '\n')
                 {
                     styler.ColourTo(i - 1, state);
                     state = SCE_SCRIPTOL_DEFAULT;
                 }
            }
            else if(state == SCE_SCRIPTOL_COMMENTBLOCK)
            {
              if(chPrev == '*' && ch == '/')
              {
                styler.ColourTo(i, state);
                state = SCE_SCRIPTOL_DEFAULT;
              }
            }
            else if ((state == SCE_SCRIPTOL_STRING) ||
                     (state == SCE_SCRIPTOL_CHARACTER))
            {
               if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
                {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_STRINGEOL;
                }
                else if (ch == '\\')
                {
                   if (chNext == '\"' || chNext == '\'' || chNext == '\\')
                   {
                        i++;
                        ch = chNext;
                        chNext = styler.SafeGetCharAt(i + 1);
                   }
                 }
                else if ((ch == '\"') || (ch == '\''))
                {
                    // must match the entered quote type
                    if(ch == stringType)
                    {
                      styler.ColourTo(i, state);
                      state = SCE_SCRIPTOL_DEFAULT;
                    }
                 }
             }
             else if (state == SCE_SCRIPTOL_TRIPLE)
             {
                if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') ||
                    (ch == '\"' && chPrev == '\"' && chPrev2 == '\"'))
                 {
                    styler.ColourTo(i, state);
                    state = SCE_SCRIPTOL_DEFAULT;
                 }
             }

           }
          chPrev2 = chPrev;
          chPrev = ch;
	}
        if (state == SCE_SCRIPTOL_KEYWORD)
        {
            ClassifyWordSol(styler.GetStartSegment(),
                 lengthDoc-1, keywords, styler, prevWord);
	}
        else
        {
            styler.ColourTo(lengthDoc-1, state);
	}
}

static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
						   WordList *[], Accessor &styler)
 {
	int lengthDoc = startPos + length;

	int lineCurrent = styler.GetLine(startPos);
	if (startPos > 0)
        {
          if (lineCurrent > 0)
          {
               lineCurrent--;
               startPos = styler.LineStart(lineCurrent);
               if (startPos == 0)
                    initStyle = SCE_SCRIPTOL_DEFAULT;
               else
                    initStyle = styler.StyleAt(startPos-1);
           }
	}
	int state = initStyle & 31;
	int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);
        if (state == SCE_SCRIPTOL_TRIPLE)
             indentCurrent |= SC_FOLDLEVELWHITEFLAG;
	char chNext = styler[startPos];
	for (int i = startPos; i < lengthDoc; i++)
         {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i) & 31;

		if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
                {
                   int lev = indentCurrent;
                   int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);
                   if (style == SCE_SCRIPTOL_TRIPLE)
                        indentNext |= SC_FOLDLEVELWHITEFLAG;
                   if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))
                    {
                        // Only non whitespace lines can be headers
                        if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
                        {
                              lev |= SC_FOLDLEVELHEADERFLAG;
                        }
                        else if (indentNext & SC_FOLDLEVELWHITEFLAG)
                        {
                             // Line after is blank so check the next - maybe should continue further?
                             int spaceFlags2 = 0;
                             int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);
                             if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))
                             {
                                   lev |= SC_FOLDLEVELHEADERFLAG;
                              }
                        }
                    }
                   indentCurrent = indentNext;
                   styler.SetLevel(lineCurrent, lev);
                   lineCurrent++;
		}
	}
}

LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc);
<commit_msg>Removing use of style byte indicator in Scriptol lexer.<commit_after>// Scintilla source code edit control
/** @file LexScriptol.cxx
 ** Lexer for Scriptol.
 **/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)
{
    char s[100] = "";
    bool wordIsNumber = isdigit(styler[start]) != 0;
    for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
     {
           s[i] = styler[start + i];
           s[i + 1] = '\0';
     }
    char chAttr = SCE_SCRIPTOL_IDENTIFIER;
    if (0 == strcmp(prevWord, "class"))       chAttr = SCE_SCRIPTOL_CLASSNAME;
    else if (wordIsNumber)                    chAttr = SCE_SCRIPTOL_NUMBER;
    else if (keywords.InList(s))              chAttr = SCE_SCRIPTOL_KEYWORD;
    else for (unsigned int i = 0; i < end - start + 1; i++)  // test dotted idents
    {
        if (styler[start + i] == '.')
        {
            styler.ColourTo(start + i - 1, chAttr);
            styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);
        }
    }
    styler.ColourTo(end, chAttr);
    strcpy(prevWord, s);
}

static bool IsSolComment(Accessor &styler, int pos, int len)
{
   if(len > 0)
   {
     char c = styler[pos];
     if(c == '`') return true;
     if(len > 1)
     {
        if(c == '/')
        {
          c = styler[pos + 1];
          if(c == '/') return true;
          if(c == '*') return true;
        }
     }
   }
   return false;
}

static bool IsSolStringStart(char ch)
{
    if (ch == '\'' || ch == '"')  return true;
    return false;
}

static bool IsSolWordStart(char ch)
{
    return (iswordchar(ch) && !IsSolStringStart(ch));
}

static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
{
	char ch = styler.SafeGetCharAt(i);
	char chNext = styler.SafeGetCharAt(i + 1);

        if (ch != '\"' && ch != '\'')
        {
            *nextIndex = i + 1;
            return SCE_SCRIPTOL_DEFAULT;
	}
        // ch is either single or double quotes in string
        // code below seem non-sense but is here for future extensions
	if (ch == chNext && ch == styler.SafeGetCharAt(i + 2))
        {
          *nextIndex = i + 3;
          if(ch == '\"') return SCE_SCRIPTOL_TRIPLE;
          if(ch == '\'') return SCE_SCRIPTOL_TRIPLE;
          return SCE_SCRIPTOL_STRING;
	}
        else
        {
          *nextIndex = i + 1;
          if (ch == '"') return SCE_SCRIPTOL_STRING;
          else           return SCE_SCRIPTOL_STRING;
	}
}

static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
                            WordList *keywordlists[], Accessor &styler)
 {

	int lengthDoc = startPos + length;
        char stringType = '\"';

	if (startPos > 0)
        {
            int lineCurrent = styler.GetLine(startPos);
            if (lineCurrent > 0)
            {
              startPos = styler.LineStart(lineCurrent-1);
              if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;
              else               initStyle = styler.StyleAt(startPos-1);
            }
	}

	styler.StartAt(startPos);

	WordList &keywords = *keywordlists[0];

	char prevWord[200];
	prevWord[0] = '\0';
        if (length == 0)  return;

	int state = initStyle & 31;

	int nextIndex = 0;
        char chPrev  = ' ';
        char chPrev2 = ' ';
        char chNext  = styler[startPos];
	styler.StartSegment(startPos);
	for (int i = startPos; i < lengthDoc; i++)
        {

       char ch = chNext;
       chNext = styler.SafeGetCharAt(i + 1);

       if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
       {
          if ((state == SCE_SCRIPTOL_DEFAULT) ||
              (state == SCE_SCRIPTOL_TRIPLE) ||
              (state == SCE_SCRIPTOL_COMMENTBLOCK))
          {
              styler.ColourTo(i, state);
          }
        }

        if (styler.IsLeadByte(ch))
         {
             chNext = styler.SafeGetCharAt(i + 2);
             chPrev  = ' ';
             chPrev2 = ' ';
             i += 1;
             continue;
         }

        if (state == SCE_SCRIPTOL_STRINGEOL)
         {
             if (ch != '\r' && ch != '\n')
             {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_DEFAULT;
             }
         }

        if (state == SCE_SCRIPTOL_DEFAULT)
         {
            if (IsSolWordStart(ch))
            {
                 styler.ColourTo(i - 1, state);
                 state = SCE_SCRIPTOL_KEYWORD;
            }
            else if (ch == '`')
            {
                styler.ColourTo(i - 1, state);
                state = SCE_SCRIPTOL_COMMENTLINE;
            }
            else if (ch == '/')
            {
                styler.ColourTo(i - 1, state);
                if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE;
                if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;
            }

            else if (IsSolStringStart(ch))
            {
               styler.ColourTo(i - 1, state);
               state = GetSolStringState(styler, i, &nextIndex);
               if(state == SCE_SCRIPTOL_STRING)
               {
                 stringType = ch;
               }
               if (nextIndex != i + 1)
               {
                   i = nextIndex - 1;
                   ch = ' ';
                   chPrev = ' ';
                   chNext = styler.SafeGetCharAt(i + 1);
               }
           }
            else if (isoperator(ch))
            {
                 styler.ColourTo(i - 1, state);
                 styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
            }
          }
          else if (state == SCE_SCRIPTOL_KEYWORD)
          {
              if (!iswordchar(ch))
              {
                 ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);
                 state = SCE_SCRIPTOL_DEFAULT;
                 if (ch == '`')
                 {
                     state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;
                 }
                 else if (IsSolStringStart(ch))
                 {
                    styler.ColourTo(i - 1, state);
                    state = GetSolStringState(styler, i, &nextIndex);
                    if (nextIndex != i + 1)
                    {
                       i = nextIndex - 1;
                       ch = ' ';
                       chPrev = ' ';
                       chNext = styler.SafeGetCharAt(i + 1);
                     }
                 }
                 else if (isoperator(ch))
                 {
                     styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
                 }
             }
          }
          else
          {
            if (state == SCE_SCRIPTOL_COMMENTLINE ||
                state == SCE_SCRIPTOL_PERSISTENT ||
                state == SCE_SCRIPTOL_CSTYLE)
            {
                 if (ch == '\r' || ch == '\n')
                 {
                     styler.ColourTo(i - 1, state);
                     state = SCE_SCRIPTOL_DEFAULT;
                 }
            }
            else if(state == SCE_SCRIPTOL_COMMENTBLOCK)
            {
              if(chPrev == '*' && ch == '/')
              {
                styler.ColourTo(i, state);
                state = SCE_SCRIPTOL_DEFAULT;
              }
            }
            else if ((state == SCE_SCRIPTOL_STRING) ||
                     (state == SCE_SCRIPTOL_CHARACTER))
            {
               if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
                {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_STRINGEOL;
                }
                else if (ch == '\\')
                {
                   if (chNext == '\"' || chNext == '\'' || chNext == '\\')
                   {
                        i++;
                        ch = chNext;
                        chNext = styler.SafeGetCharAt(i + 1);
                   }
                 }
                else if ((ch == '\"') || (ch == '\''))
                {
                    // must match the entered quote type
                    if(ch == stringType)
                    {
                      styler.ColourTo(i, state);
                      state = SCE_SCRIPTOL_DEFAULT;
                    }
                 }
             }
             else if (state == SCE_SCRIPTOL_TRIPLE)
             {
                if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') ||
                    (ch == '\"' && chPrev == '\"' && chPrev2 == '\"'))
                 {
                    styler.ColourTo(i, state);
                    state = SCE_SCRIPTOL_DEFAULT;
                 }
             }

           }
          chPrev2 = chPrev;
          chPrev = ch;
	}
        if (state == SCE_SCRIPTOL_KEYWORD)
        {
            ClassifyWordSol(styler.GetStartSegment(),
                 lengthDoc-1, keywords, styler, prevWord);
	}
        else
        {
            styler.ColourTo(lengthDoc-1, state);
	}
}

static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
						   WordList *[], Accessor &styler)
 {
	int lengthDoc = startPos + length;

	int lineCurrent = styler.GetLine(startPos);
	if (startPos > 0)
        {
          if (lineCurrent > 0)
          {
               lineCurrent--;
               startPos = styler.LineStart(lineCurrent);
               if (startPos == 0)
                    initStyle = SCE_SCRIPTOL_DEFAULT;
               else
                    initStyle = styler.StyleAt(startPos-1);
           }
	}
	int state = initStyle & 31;
	int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);
        if (state == SCE_SCRIPTOL_TRIPLE)
             indentCurrent |= SC_FOLDLEVELWHITEFLAG;
	char chNext = styler[startPos];
	for (int i = startPos; i < lengthDoc; i++)
         {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i) & 31;

		if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
                {
                   int lev = indentCurrent;
                   int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);
                   if (style == SCE_SCRIPTOL_TRIPLE)
                        indentNext |= SC_FOLDLEVELWHITEFLAG;
                   if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))
                    {
                        // Only non whitespace lines can be headers
                        if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
                        {
                              lev |= SC_FOLDLEVELHEADERFLAG;
                        }
                        else if (indentNext & SC_FOLDLEVELWHITEFLAG)
                        {
                             // Line after is blank so check the next - maybe should continue further?
                             int spaceFlags2 = 0;
                             int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);
                             if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))
                             {
                                   lev |= SC_FOLDLEVELHEADERFLAG;
                              }
                        }
                    }
                   indentCurrent = indentNext;
                   styler.SetLevel(lineCurrent, lev);
                   lineCurrent++;
		}
	}
}

LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc);
<|endoftext|>


<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGGroundReactions.cpp
 Author:       Jon S. Berndt
 Date started: 09/13/00
 Purpose:      Encapsulates the ground reaction forces (gear and collision)

 ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
09/13/00   JSB   Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <sstream>
#include <iomanip>

#include "FGGroundReactions.h"
#include "FGLGear.h"
#include "FGAccelerations.h"
#include "input_output/FGPropertyManager.h"
#include "input_output/FGXMLFileRead.h"
#include "input_output/FGXMLElement.h"

using namespace std;

namespace JSBSim {

IDENT(IdSrc,"$Id: FGGroundReactions.cpp,v 1.49 2014/01/28 09:42:21 ehofman Exp $");
IDENT(IdHdr,ID_GROUNDREACTIONS);

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGGroundReactions::FGGroundReactions(FGFDMExec* fgex) :
   FGModel(fgex),
   FGSurface(fgex)
{
  Name = "FGGroundReactions";

  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGGroundReactions::~FGGroundReactions(void)
{
  for (unsigned int i=0; i<lGear.size();i++) delete lGear[i];
  lGear.clear();

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::InitModel(void)
{
  if (!FGModel::InitModel()) return false;

  vForces.InitMatrix();
  vMoments.InitMatrix();

  multipliers.clear();

  for (unsigned int i=0; i<lGear.size(); i++)
    lGear[i]->ResetToIC();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::Run(bool Holding)
{
  if (FGModel::Run(Holding)) return true;
  if (Holding) return false;

  RunPreFunctions();

  vForces.InitMatrix();
  vMoments.InitMatrix();

  multipliers.clear();

  // Sum forces and moments for all gear, here.
  // Some optimizations may be made here - or rather in the gear code itself.
  // The gear ::Run() method is called several times - once for each gear.
  // Perhaps there is some commonality for things which only need to be
  // calculated once.
  for (unsigned int i=0; i<lGear.size(); i++) {
    vForces  += lGear[i]->GetBodyForces(this);
    vMoments += lGear[i]->GetMoments();
  }

  RunPostFunctions();

  return false;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::GetWOW(void) const
{
  bool result = false;
  for (unsigned int i=0; i<lGear.size(); i++) {
    if (lGear[i]->IsBogey() && lGear[i]->GetWOW()) {
      result = true;
      break;
    }
  }
  return result;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::Load(Element* elem)
{
  int num=0;
  string fname="", file="";
  string separator = "/";
  FGXMLFileRead XMLFileRead;
  Element* document;

  fname = elem->GetAttributeValue("file");
  if (!fname.empty()) {
    file = FDMExec->GetFullAircraftPath() + separator + fname;
    document = XMLFileRead.LoadXMLDocument(file);
    if (document == 0L) return false;
  } else {
    document = elem;
  }

  Debug(2);

  unsigned int numContacts = document->GetNumElements("contact");
  lGear.resize(numContacts);
  Element* contact_element = document->FindElement("contact");
  for (unsigned int idx=0; idx<numContacts; idx++) {
    lGear[idx] = new FGLGear(contact_element, FDMExec, num++, in);
    contact_element = document->FindNextElement("contact");
  }

  FGModel::Load(document); // Perform base class Load

  for (unsigned int i=0; i<lGear.size();i++) lGear[i]->bind();

  PostLoad(document, PropertyManager);

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGGroundReactions::GetGroundReactionStrings(string delimeter) const
{
  std::ostringstream buf;

  for (unsigned int i=0;i<lGear.size();i++) {
    if (lGear[i]->IsBogey()) {
      string name = lGear[i]->GetName();
      buf << name << " WOW" << delimeter
          << name << " stroke (ft)" << delimeter
          << name << " stroke velocity (ft/sec)" << delimeter
          << name << " compress force (lbs)" << delimeter
          << name << " wheel side force (lbs)" << delimeter
          << name << " wheel roll force (lbs)" << delimeter
          << name << " body X force (lbs)" << delimeter
          << name << " body Y force (lbs)" << delimeter
          << name << " wheel velocity vec X (ft/sec)" << delimeter
          << name << " wheel velocity vec Y (ft/sec)" << delimeter
          << name << " wheel rolling velocity (ft/sec)" << delimeter
          << name << " wheel side velocity (ft/sec)" << delimeter
          << name << " wheel slip (deg)" << delimeter;
    } else {
      string name = lGear[i]->GetName();
      buf << name << " WOW" << delimeter
          << name << " stroke (ft)" << delimeter
          << name << " stroke velocity (ft/sec)" << delimeter
          << name << " compress force (lbs)" << delimeter;
    }
  }

  buf << " Total Gear Force_X (lbs)" << delimeter
      << " Total Gear Force_Y (lbs)" << delimeter
      << " Total Gear Force_Z (lbs)" << delimeter
      << " Total Gear Moment_L (ft-lbs)" << delimeter
      << " Total Gear Moment_M (ft-lbs)" << delimeter
      << " Total Gear Moment_N (ft-lbs)";

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGGroundReactions::GetGroundReactionValues(string delimeter) const
{
  std::ostringstream buf;

  for (unsigned int i=0;i<lGear.size();i++) {
    if (lGear[i]->IsBogey()) {
      FGLGear *gear = lGear[i];
      buf << (gear->GetWOW() ? "1" : "0") << delimeter
          << setprecision(5) << gear->GetCompLen() << delimeter
          << setprecision(6) << gear->GetCompVel() << delimeter
          << setprecision(10) << gear->GetCompForce() << delimeter
          << gear->GetWheelSideForce() << delimeter
          << gear->GetWheelRollForce() << delimeter
          << gear->GetBodyXForce() << delimeter
          << gear->GetBodyYForce() << delimeter
          << setprecision(6) << gear->GetWheelVel(eX) << delimeter
          << gear->GetWheelVel(eY) << delimeter
          << gear->GetWheelRollVel() << delimeter
          << gear->GetWheelSideVel() << delimeter
          << gear->GetWheelSlipAngle() << delimeter;
    } else {
      FGLGear *gear = lGear[i];
      buf << (gear->GetWOW() ? "1" : "0") << delimeter
          << setprecision(5) << gear->GetCompLen() << delimeter
          << setprecision(6) << gear->GetCompVel() << delimeter
          << setprecision(10) << gear->GetCompForce() << delimeter;
    }
  }

  FGAccelerations* Accelerations = FDMExec->GetAccelerations();

  buf << Accelerations->GetGroundForces(eX) << delimeter
      << Accelerations->GetGroundForces(eY) << delimeter
      << Accelerations->GetGroundForces(eZ) << delimeter
      << Accelerations->GetGroundMoments(eX) << delimeter
      << Accelerations->GetGroundMoments(eY) << delimeter
      << Accelerations->GetGroundMoments(eZ);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGGroundReactions::bind(void)
{
  eSurfaceType = ctGROUND;
  FGSurface::bind();

  PropertyManager->Tie("gear/num-units", this, &FGGroundReactions::GetNumGearUnits);
  PropertyManager->Tie("gear/wow", this, &FGGroundReactions::GetWOW);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGGroundReactions::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 2) { // Loading
      cout << endl << "  Ground Reactions: " << endl;
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGGroundReactions" << endl;
    if (from == 1) cout << "Destroyed:    FGGroundReactions" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<commit_msg>Added support for naming of ground reactions model values<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGGroundReactions.cpp
 Author:       Jon S. Berndt
 Date started: 09/13/00
 Purpose:      Encapsulates the ground reaction forces (gear and collision)

 ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
 details.

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
09/13/00   JSB   Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <sstream>
#include <iomanip>

#include "FGGroundReactions.h"
#include "FGLGear.h"
#include "FGAccelerations.h"
#include "input_output/FGPropertyManager.h"
#include "input_output/FGXMLFileRead.h"
#include "input_output/FGXMLElement.h"

using namespace std;

namespace JSBSim {

IDENT(IdSrc,"$Id: FGGroundReactions.cpp,v 1.50 2014/05/17 15:25:20 jberndt Exp $");
IDENT(IdHdr,ID_GROUNDREACTIONS);

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGGroundReactions::FGGroundReactions(FGFDMExec* fgex) :
   FGModel(fgex),
   FGSurface(fgex)
{
  Name = "FGGroundReactions";

  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGGroundReactions::~FGGroundReactions(void)
{
  for (unsigned int i=0; i<lGear.size();i++) delete lGear[i];
  lGear.clear();

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::InitModel(void)
{
  if (!FGModel::InitModel()) return false;

  vForces.InitMatrix();
  vMoments.InitMatrix();

  multipliers.clear();

  for (unsigned int i=0; i<lGear.size(); i++)
    lGear[i]->ResetToIC();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::Run(bool Holding)
{
  if (FGModel::Run(Holding)) return true;
  if (Holding) return false;

  RunPreFunctions();

  vForces.InitMatrix();
  vMoments.InitMatrix();

  multipliers.clear();

  // Sum forces and moments for all gear, here.
  // Some optimizations may be made here - or rather in the gear code itself.
  // The gear ::Run() method is called several times - once for each gear.
  // Perhaps there is some commonality for things which only need to be
  // calculated once.
  for (unsigned int i=0; i<lGear.size(); i++) {
    vForces  += lGear[i]->GetBodyForces(this);
    vMoments += lGear[i]->GetMoments();
  }

  RunPostFunctions();

  return false;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::GetWOW(void) const
{
  bool result = false;
  for (unsigned int i=0; i<lGear.size(); i++) {
    if (lGear[i]->IsBogey() && lGear[i]->GetWOW()) {
      result = true;
      break;
    }
  }
  return result;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGGroundReactions::Load(Element* elem)
{
  int num=0;
  string fname="", file="";
  string separator = "/";
  FGXMLFileRead XMLFileRead;
  Element* document;

  fname = elem->GetAttributeValue("file");
  if (!fname.empty()) {
    file = FDMExec->GetFullAircraftPath() + separator + fname;
    document = XMLFileRead.LoadXMLDocument(file);
    if (document == 0L) return false;
  } else {
    document = elem;
  }

  Name = "Ground Reactions Model: " + document->GetAttributeValue("name");

  Debug(2);

  unsigned int numContacts = document->GetNumElements("contact");
  lGear.resize(numContacts);
  Element* contact_element = document->FindElement("contact");
  for (unsigned int idx=0; idx<numContacts; idx++) {
    lGear[idx] = new FGLGear(contact_element, FDMExec, num++, in);
    contact_element = document->FindNextElement("contact");
  }

  FGModel::Load(document); // Perform base class Load

  for (unsigned int i=0; i<lGear.size();i++) lGear[i]->bind();

  PostLoad(document, PropertyManager);

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGGroundReactions::GetGroundReactionStrings(string delimeter) const
{
  std::ostringstream buf;

  for (unsigned int i=0;i<lGear.size();i++) {
    if (lGear[i]->IsBogey()) {
      string name = lGear[i]->GetName();
      buf << name << " WOW" << delimeter
          << name << " stroke (ft)" << delimeter
          << name << " stroke velocity (ft/sec)" << delimeter
          << name << " compress force (lbs)" << delimeter
          << name << " wheel side force (lbs)" << delimeter
          << name << " wheel roll force (lbs)" << delimeter
          << name << " body X force (lbs)" << delimeter
          << name << " body Y force (lbs)" << delimeter
          << name << " wheel velocity vec X (ft/sec)" << delimeter
          << name << " wheel velocity vec Y (ft/sec)" << delimeter
          << name << " wheel rolling velocity (ft/sec)" << delimeter
          << name << " wheel side velocity (ft/sec)" << delimeter
          << name << " wheel slip (deg)" << delimeter;
    } else {
      string name = lGear[i]->GetName();
      buf << name << " WOW" << delimeter
          << name << " stroke (ft)" << delimeter
          << name << " stroke velocity (ft/sec)" << delimeter
          << name << " compress force (lbs)" << delimeter;
    }
  }

  buf << " Total Gear Force_X (lbs)" << delimeter
      << " Total Gear Force_Y (lbs)" << delimeter
      << " Total Gear Force_Z (lbs)" << delimeter
      << " Total Gear Moment_L (ft-lbs)" << delimeter
      << " Total Gear Moment_M (ft-lbs)" << delimeter
      << " Total Gear Moment_N (ft-lbs)";

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGGroundReactions::GetGroundReactionValues(string delimeter) const
{
  std::ostringstream buf;

  for (unsigned int i=0;i<lGear.size();i++) {
    if (lGear[i]->IsBogey()) {
      FGLGear *gear = lGear[i];
      buf << (gear->GetWOW() ? "1" : "0") << delimeter
          << setprecision(5) << gear->GetCompLen() << delimeter
          << setprecision(6) << gear->GetCompVel() << delimeter
          << setprecision(10) << gear->GetCompForce() << delimeter
          << gear->GetWheelSideForce() << delimeter
          << gear->GetWheelRollForce() << delimeter
          << gear->GetBodyXForce() << delimeter
          << gear->GetBodyYForce() << delimeter
          << setprecision(6) << gear->GetWheelVel(eX) << delimeter
          << gear->GetWheelVel(eY) << delimeter
          << gear->GetWheelRollVel() << delimeter
          << gear->GetWheelSideVel() << delimeter
          << gear->GetWheelSlipAngle() << delimeter;
    } else {
      FGLGear *gear = lGear[i];
      buf << (gear->GetWOW() ? "1" : "0") << delimeter
          << setprecision(5) << gear->GetCompLen() << delimeter
          << setprecision(6) << gear->GetCompVel() << delimeter
          << setprecision(10) << gear->GetCompForce() << delimeter;
    }
  }

  FGAccelerations* Accelerations = FDMExec->GetAccelerations();

  buf << Accelerations->GetGroundForces(eX) << delimeter
      << Accelerations->GetGroundForces(eY) << delimeter
      << Accelerations->GetGroundForces(eZ) << delimeter
      << Accelerations->GetGroundMoments(eX) << delimeter
      << Accelerations->GetGroundMoments(eY) << delimeter
      << Accelerations->GetGroundMoments(eZ);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGGroundReactions::bind(void)
{
  eSurfaceType = ctGROUND;
  FGSurface::bind();

  PropertyManager->Tie("gear/num-units", this, &FGGroundReactions::GetNumGearUnits);
  PropertyManager->Tie("gear/wow", this, &FGGroundReactions::GetWOW);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGGroundReactions::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 2) { // Loading
      cout << endl << "  Ground Reactions: " << endl;
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGGroundReactions" << endl;
    if (from == 1) cout << "Destroyed:    FGGroundReactions" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<|endoftext|>


<commit_before>#include "render/bufferbuilder2d.h"

Point::Point(float x, float y, float u, float v) : pos(x, y), vert(u, v) {}

Point::Point(const vec2f& apos, const vec2f& avert)
    : pos(apos), vert(avert) {}

BufferBuilder2d::BufferBuilder2d() {}

void BufferBuilder2d::AddVertex(const Point& p) {
  Assert(this);
  data.push_back(p.pos.x);
  data.push_back(p.pos.y);
  data.push_back(p.vert.x);
  data.push_back(p.vert.y);
}

void BufferBuilder2d::AddTriangle(unsigned int a, unsigned int b, unsigned int c) {
  Assert(this);
  tris.push_back(a);
  tris.push_back(b);
  tris.push_back(c);
}

void BufferBuilder2d::AddQuad(const Point& a, const Point& b, const Point& c,
             const Point& d) {
  Assert(this);
  AddVertex(a);
  AddVertex(b);
  AddVertex(c);
  AddVertex(d);

  const unsigned int ai = data.size() / 4;
  const unsigned int bi = ai + 1;
  const unsigned int ci = ai + 2;
  const unsigned int di = ai + 3;
  AddTriangle(ci, bi, ai);
  AddTriangle(ci, di, bi);
}

const std::vector<float>& BufferBuilder2d::GetVertexData() const {
  Assert(this);
  return data;
}

const std::vector<unsigned int>& BufferBuilder2d::GetTriangleIndices() const {
  Assert(this);
  return tris;
}
<commit_msg>fixed so that the index count was based on the current quad, and not the next quad<commit_after>#include "render/bufferbuilder2d.h"

Point::Point(float x, float y, float u, float v) : pos(x, y), vert(u, v) {}

Point::Point(const vec2f& apos, const vec2f& avert)
    : pos(apos), vert(avert) {}

BufferBuilder2d::BufferBuilder2d() {}

void BufferBuilder2d::AddVertex(const Point& p) {
  Assert(this);
  data.push_back(p.pos.x);
  data.push_back(p.pos.y);
  data.push_back(p.vert.x);
  data.push_back(p.vert.y);
}

void BufferBuilder2d::AddTriangle(unsigned int a, unsigned int b, unsigned int c) {
  Assert(this);
  tris.push_back(a);
  tris.push_back(b);
  tris.push_back(c);
}

void BufferBuilder2d::AddQuad(const Point& a, const Point& b, const Point& c,
             const Point& d) {
  Assert(this);

  const unsigned int ai = data.size() / 4;
  const unsigned int bi = ai + 1;
  const unsigned int ci = ai + 2;
  const unsigned int di = ai + 3;

  AddVertex(a);
  AddVertex(b);
  AddVertex(c);
  AddVertex(d);

  AddTriangle(ci, bi, ai);
  AddTriangle(ci, di, bi);
}

const std::vector<float>& BufferBuilder2d::GetVertexData() const {
  Assert(this);
  return data;
}

const std::vector<unsigned int>& BufferBuilder2d::GetTriangleIndices() const {
  Assert(this);
  return tris;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include <vector>
#include <list>
#include <type_traits>
#include <stdexcept>
#include "command_buffer.hpp"
#include "hash.hpp"
#include "enum_cast.hpp"
#include "intrusive_hash_map.hpp"
#include "math.hpp"

namespace Granite
{
class ShaderSuite;
class RenderContext;
class AbstractRenderable;
class PositionalLight;
struct RenderInfoComponent;

struct RenderableInfo
{
	AbstractRenderable *renderable;
	const RenderInfoComponent *transform;
};
using VisibilityList = std::vector<RenderableInfo>;
using PositionalLightList = std::vector<std::pair<PositionalLight *, const RenderInfoComponent *>>;

enum class Queue : unsigned
{
	Opaque = 0,
	OpaqueEmissive,
	Light, // Relevant only for classic deferred rendering
	Transparent,
	Count
};

enum class StaticLayer : unsigned
{
	Front,
	Default,
	Back,
	Last,
	Count
};

struct RenderInfo
{
	static uint64_t get_sort_key(const RenderContext &context, Queue queue_type,
	                             Util::Hash pipeline_hash, Util::Hash draw_hash,
	                             const vec3 &center,
	                             StaticLayer layer = StaticLayer::Default);
	static uint64_t get_sprite_sort_key(Queue queue_type,
	                                    Util::Hash pipeline_hash, Util::Hash draw_hash,
	                                    float layer, StaticLayer static_layer = StaticLayer::Default);
	static uint64_t get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash);

private:
	RenderInfo() = default;
};

struct RenderQueueData;
using RenderFunc = void (*)(Vulkan::CommandBuffer &, const RenderQueueData *, unsigned);

struct RenderQueueData
{
	// How to render an object.
	RenderFunc render;

	// Per-draw call specific data. Understood by the render callback.
	const void *render_info;

	// Per-instance specific data. Understood by the render callback.
	const void *instance_data;

	// Sorting key.
	// Lower sorting keys will appear earlier.
	uint64_t sorting_key;
};

struct QueueDataWrappedErased : Util::IntrusiveHashMapEnabled<QueueDataWrappedErased>
{
};

template <typename T>
struct QueueDataWrapped : QueueDataWrappedErased
{
	T data;
};

class RenderQueue
{
public:
	enum { BlockSize = 256 * 1024 };

	template <typename T>
	T *push(Queue queue, Util::Hash instance_key, uint64_t sorting_key,
	        RenderFunc render, void *instance_data)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Dispatchable type is not trivially destructible!");

		assert(instance_key != 0);
		assert(sorting_key != 0);

		Util::Hasher h(instance_key);
		h.pointer(render);

		using WrappedT = QueueDataWrapped<T>;

		auto *itr = render_infos.find(h.get());
		if (itr)
		{
			auto *t = static_cast<WrappedT *>(itr);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return nullptr;
		}
		else
		{
			void *buffer = allocate(sizeof(WrappedT), alignof(WrappedT));
			if (!buffer)
				throw std::bad_alloc();

			auto *t = new(buffer) WrappedT();
			t->set_hash(h.get());
			render_infos.insert_replace(t);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return &t->data;
		}
	}

	void *allocate(size_t size, size_t alignment = 64);

	template <typename T>
	T *allocate_one()
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T), alignof(T)));
	}

	template <typename T>
	T *allocate_many(size_t n)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T) * n, alignof(T)));
	}

	void combine_render_info(const RenderQueue &queue);
	void reset();
	void reset_and_reclaim();

	const std::vector<RenderQueueData> &get_queue_data(Queue queue) const
	{
		return queues[Util::ecast(queue)];
	}

	void sort();
	void dispatch(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state) const;
	void dispatch_range(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, size_t begin, size_t end) const;
	void dispatch_subset(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, unsigned index, unsigned num_indices) const;
	size_t get_dispatch_size(Queue queue) const;

	void set_shader_suites(ShaderSuite *suite)
	{
		shader_suites = suite;
	}

	ShaderSuite *get_shader_suites() const
	{
		return shader_suites;
	}

	void push_renderables(const RenderContext &context, const VisibilityList &visible);
	void push_depth_renderables(const RenderContext &context, const VisibilityList &visible);

private:
	void enqueue_queue_data(Queue queue, const RenderQueueData &data);

	struct Block
	{
		std::vector<uint8_t> buffer;
		uintptr_t ptr = 0;
		uintptr_t begin = 0;
		uintptr_t end = 0;

		explicit Block(size_t size)
		{
			buffer.resize(size);
			begin = reinterpret_cast<uintptr_t>(buffer.data());
			end = reinterpret_cast<uintptr_t>(buffer.data()) + size;
			reset();
		}

		void operator=(const Block &) = delete;
		Block(const Block &) = delete;
		Block(Block &&) = default;
		Block &operator=(Block &&) = default;

		void reset()
		{
			ptr = begin;
		}
	};

	using Chain = std::list<Block>;
	Chain blocks;
	Chain large_blocks;
	Chain::iterator current = std::end(blocks);

	std::vector<RenderQueueData> queues[static_cast<unsigned>(Queue::Count)];

	void *allocate_from_block(Block &block, size_t size, size_t alignment);
	Chain::iterator insert_block();
	Chain::iterator insert_large_block(size_t size, size_t alignment);

	ShaderSuite *shader_suites = nullptr;
	Util::IntrusiveHashMapHolder<QueueDataWrappedErased> render_infos;
};
}
<commit_msg>Avoid a lot of memset cost when adding a RenderQueue block.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include <vector>
#include <list>
#include <type_traits>
#include <stdexcept>
#include "command_buffer.hpp"
#include "hash.hpp"
#include "enum_cast.hpp"
#include "intrusive_hash_map.hpp"
#include "math.hpp"

namespace Granite
{
class ShaderSuite;
class RenderContext;
class AbstractRenderable;
class PositionalLight;
struct RenderInfoComponent;

struct RenderableInfo
{
	AbstractRenderable *renderable;
	const RenderInfoComponent *transform;
};
using VisibilityList = std::vector<RenderableInfo>;
using PositionalLightList = std::vector<std::pair<PositionalLight *, const RenderInfoComponent *>>;

enum class Queue : unsigned
{
	Opaque = 0,
	OpaqueEmissive,
	Light, // Relevant only for classic deferred rendering
	Transparent,
	Count
};

enum class StaticLayer : unsigned
{
	Front,
	Default,
	Back,
	Last,
	Count
};

struct RenderInfo
{
	static uint64_t get_sort_key(const RenderContext &context, Queue queue_type,
	                             Util::Hash pipeline_hash, Util::Hash draw_hash,
	                             const vec3 &center,
	                             StaticLayer layer = StaticLayer::Default);
	static uint64_t get_sprite_sort_key(Queue queue_type,
	                                    Util::Hash pipeline_hash, Util::Hash draw_hash,
	                                    float layer, StaticLayer static_layer = StaticLayer::Default);
	static uint64_t get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash);

private:
	RenderInfo() = default;
};

struct RenderQueueData;
using RenderFunc = void (*)(Vulkan::CommandBuffer &, const RenderQueueData *, unsigned);

struct RenderQueueData
{
	// How to render an object.
	RenderFunc render;

	// Per-draw call specific data. Understood by the render callback.
	const void *render_info;

	// Per-instance specific data. Understood by the render callback.
	const void *instance_data;

	// Sorting key.
	// Lower sorting keys will appear earlier.
	uint64_t sorting_key;
};

struct QueueDataWrappedErased : Util::IntrusiveHashMapEnabled<QueueDataWrappedErased>
{
};

template <typename T>
struct QueueDataWrapped : QueueDataWrappedErased
{
	T data;
};

class RenderQueue
{
public:
	enum { BlockSize = 256 * 1024 };

	template <typename T>
	T *push(Queue queue, Util::Hash instance_key, uint64_t sorting_key,
	        RenderFunc render, void *instance_data)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Dispatchable type is not trivially destructible!");

		assert(instance_key != 0);
		assert(sorting_key != 0);

		Util::Hasher h(instance_key);
		h.pointer(render);

		using WrappedT = QueueDataWrapped<T>;

		auto *itr = render_infos.find(h.get());
		if (itr)
		{
			auto *t = static_cast<WrappedT *>(itr);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return nullptr;
		}
		else
		{
			void *buffer = allocate(sizeof(WrappedT), alignof(WrappedT));
			if (!buffer)
				throw std::bad_alloc();

			auto *t = new(buffer) WrappedT();
			t->set_hash(h.get());
			render_infos.insert_replace(t);
			enqueue_queue_data(queue, { render, &t->data, instance_data, sorting_key });
			return &t->data;
		}
	}

	void *allocate(size_t size, size_t alignment = 64);

	template <typename T>
	T *allocate_one()
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T), alignof(T)));
	}

	template <typename T>
	T *allocate_many(size_t n)
	{
		static_assert(std::is_trivially_destructible<T>::value, "Type is not trivially destructible!");
		return static_cast<T *>(allocate(sizeof(T) * n, alignof(T)));
	}

	void combine_render_info(const RenderQueue &queue);
	void reset();
	void reset_and_reclaim();

	const std::vector<RenderQueueData> &get_queue_data(Queue queue) const
	{
		return queues[Util::ecast(queue)];
	}

	void sort();
	void dispatch(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state) const;
	void dispatch_range(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, size_t begin, size_t end) const;
	void dispatch_subset(Queue queue, Vulkan::CommandBuffer &cmd, const Vulkan::CommandBufferSavedState *state, unsigned index, unsigned num_indices) const;
	size_t get_dispatch_size(Queue queue) const;

	void set_shader_suites(ShaderSuite *suite)
	{
		shader_suites = suite;
	}

	ShaderSuite *get_shader_suites() const
	{
		return shader_suites;
	}

	void push_renderables(const RenderContext &context, const VisibilityList &visible);
	void push_depth_renderables(const RenderContext &context, const VisibilityList &visible);

private:
	void enqueue_queue_data(Queue queue, const RenderQueueData &data);

	struct Block
	{
		std::unique_ptr<uint8_t[]> buffer;
		uintptr_t ptr = 0;
		uintptr_t begin = 0;
		uintptr_t end = 0;

		explicit Block(size_t size)
		{
			buffer.reset(new uint8_t[size]);
			begin = reinterpret_cast<uintptr_t>(buffer.get());
			end = reinterpret_cast<uintptr_t>(buffer.get()) + size;
			reset();
		}

		void operator=(const Block &) = delete;
		Block(const Block &) = delete;
		Block(Block &&) = default;
		Block &operator=(Block &&) = default;

		void reset()
		{
			ptr = begin;
		}
	};

	using Chain = std::list<Block>;
	Chain blocks;
	Chain large_blocks;
	Chain::iterator current = std::end(blocks);

	std::vector<RenderQueueData> queues[static_cast<unsigned>(Queue::Count)];

	void *allocate_from_block(Block &block, size_t size, size_t alignment);
	Chain::iterator insert_block();
	Chain::iterator insert_large_block(size_t size, size_t alignment);

	ShaderSuite *shader_suites = nullptr;
	Util::IntrusiveHashMapHolder<QueueDataWrappedErased> render_infos;
};
}
<|endoftext|>