<commit_before>//
//  FileManager.hpp
//  CatchLib
//
//  Created by John Barbero Unenge on 9/17/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#if __APPLE__
#include <OpenGLES/ES2/gl.h>
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#endif

#ifndef CatchiOS_FileManager_h
#define CatchiOS_FileManager_h
struct Texture{
	GLint           internalFormat;
    GLsizei         width;
    GLsizei         height;
    GLenum          format;
    GLenum          type;
    const GLvoid*   data;
};

class GLRenderer {
public:
	GLRenderer();
	~GLRenderer();

	void init(int width, int height);
	void createFrameBuffer();
	void render();

private:
    GLuint BuildShader(const char* source, GLenum shaderType) const;
    GLuint BuildProgram(const char* vShader, const char* fShader) const;
    void ApplyOrtho(float maxX, float maxY) const;
    void ApplyRotation(float degrees) const;

    GLuint m_simpleProgram;
    GLuint m_framebuffer;
    GLuint m_renderbuffer;
};

#endif
<commit_msg>Moved the CLTexture out to SCLTexture.hpp.<commit_after>//
//  FileManager.hpp
//  CatchLib
//
//  Created by John Barbero Unenge on 9/17/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#if __APPLE__
#include <OpenGLES/ES2/gl.h>
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#endif

#include "SCLTexture.hpp"

#ifndef CatchiOS_FileManager_h
#define CatchiOS_FileManager_h

class GLRenderer {
public:
	GLRenderer();
	~GLRenderer();

	void init(int width, int height);
	void createFrameBuffer();
	void render();

private:
    GLuint BuildShader(const char* source, GLenum shaderType) const;
    GLuint BuildProgram(const char* vShader, const char* fShader) const;
    void ApplyOrtho(float maxX, float maxY) const;
    void ApplyRotation(float degrees) const;

    GLuint m_simpleProgram;
    GLuint m_framebuffer;
    GLuint m_renderbuffer;
};

#endif
<|endoftext|>


<commit_before>#include <memory>
#include <wx/progdlg.h>
#include <wx/window.h>

#include "Plater.hpp"
#include "ProgressStatusBar.hpp"
#include "Log.hpp"
#include "MainFrame.hpp"

namespace Slic3r { namespace GUI {

const auto PROGRESS_BAR_EVENT = wxNewEventType();

Plater::Plater(wxWindow* parent, const wxString& title, std::shared_ptr<Settings> _settings) :
    wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, title), settings(_settings)
{

    // Set callback for status event for worker threads
    /*
    this->print->set_status_cb([=](std::string percent percent, std::wstring message) {
        wxPostEvent(this, new wxPlThreadEvent(-1, PROGRESS_BAR_EVENT,
    });
    */
    auto on_select_object { [=](size_t& obj_idx) {
       this->select_object(obj_idx);
    } };
    /*
   # Initialize handlers for canvases
    my $on_select_object = sub {
        my ($obj_idx) = @_;
        $self->select_object($obj_idx);
    };
    my $on_double_click = sub {
        $self->object_settings_dialog if $self->selected_object;
    };
    my $on_right_click = sub {
        my ($canvas, $click_pos) = @_;

        my ($obj_idx, $object) = $self->selected_object;
        return if !defined $obj_idx;

        my $menu = $self->object_menu;
        $canvas->PopupMenu($menu, $click_pos);
        $menu->Destroy;
    };
    my $on_instances_moved = sub {
        $self->on_model_change;
    };
    # Initialize 3D plater
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{config});
        $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D');
        $self->{canvas3D}->set_on_select_object($on_select_object);
        $self->{canvas3D}->set_on_double_click($on_double_click);
        $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); });
        $self->{canvas3D}->set_on_instances_moved($on_instances_moved);
        $self->{canvas3D}->on_viewport_changed(sub {
            $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
        });
    }
    */
    canvas2D = new Plate2D(preview_notebook, wxDefaultSize, objects, model, config, settings);
    preview_notebook->AddPage(canvas2D, _("2D"));

    /*
    # Initialize 2D preview canvas
    $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config});
    $self->{preview_notebook}->AddPage($self->{canvas}, '2D');
    $self->{canvas}->on_select_object($on_select_object);
    $self->{canvas}->on_double_click($on_double_click);
    $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); });
    $self->{canvas}->on_instances_moved($on_instances_moved);
    # Initialize 3D toolpaths preview
    $self->{preview3D_page_idx} = -1;
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print});
        $self->{preview3D}->canvas->on_viewport_changed(sub {
            $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
        });
        $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview');
        $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
    }

    # Initialize toolpaths preview
    $self->{toolpaths2D_page_idx} = -1;
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print});
        $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers');
        $self->{toolpaths2D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
    }

    EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub {
        wxTheApp->CallAfter(sub {
            my $sel = $self->{preview_notebook}->GetSelection;
            if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) {
                if (!$Slic3r::GUI::Settings->{_}{background_processing} && !$self->{processed}) {
                    $self->statusbar->SetCancelCallback(sub {
                        $self->stop_background_process;
                        $self->statusbar->SetStatusText("Slicing cancelled");
                        $self->{preview_notebook}->SetSelection(0);

                    });
                    $self->start_background_process;
                } else {
                    $self->{preview3D}->load_print
                        if $sel == $self->{preview3D_page_idx};
                }
            }
        });
    });
    */

}
void Plater::add() {
    Log::info(LogChannel, L"Called Add function");

    auto& start_object_id = this->object_identifier;
    const auto& input_files{open_model(this, *(this->settings), wxTheApp->GetTopWindow())};
    for (const auto& f : input_files) {
        Log::info(LogChannel, (wxString(L"Calling Load File for ") + f).ToStdWstring());
        this->load_file(f);
    }

    // abort if no objects actually added.
    if (start_object_id == this->object_identifier) return;

    // save the added objects
    auto new_model {this->model};

    // get newly added objects count
    auto new_objects_count = this->object_identifier - start_object_id;

    Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring());
    for (auto i = start_object_id; i < new_objects_count + start_object_id; i++) {
        const auto& obj_idx {this->get_object_index(i)};
        new_model->add_object(*(this->model->objects.at(obj_idx)));
    }
    Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring());

    // Prepare for undo
    //this->add_undo_operation("ADD", nullptr, new_model, start_object_id);

}

std::vector<int> Plater::load_file(const wxString& file, const int obj_idx_to_load) {

    auto input_file {wxFileName(file)};
    settings->skein_directory = input_file.GetPath();
    settings->save_settings();

    Slic3r::Model model;
    bool valid_load {true};

    auto obj_idx {std::vector<int>()};
    auto progress_dialog {new wxProgressDialog(_(L"Loading…"), _(L"Processing input file…"), 100, this, 0)};
    progress_dialog->Pulse();
    //TODO: Add a std::wstring so we can handle non-roman characters as file names.
    try {
        model = Slic3r::Model::read_from_file(file.ToStdString());
    } catch (std::runtime_error& e) {
        show_error(this, e.what());
        Slic3r::Log::error(LogChannel, LOG_WSTRING(file << " failed to load: " << e.what()));
        valid_load = false;
    }
    Slic3r::Log::info(LogChannel, LOG_WSTRING("load_valid is " << valid_load));

    if (valid_load) {
        if (model.looks_like_multipart_object()) {
            auto dialog {new wxMessageDialog(this,
            _("This file contains several objects positioned at multiple heights. Instead of considering them as multiple objects, should I consider\n them this file as a single object having multiple parts?\n"), _("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO)};
            if (dialog->ShowModal() == wxID_YES) {
                model.convert_multipart_object();
            }
        }

        for (auto i = 0U; i < model.objects.size(); i++) {
            auto object {model.objects[i]};
            object->input_file = file.ToStdString();
            for (auto j = 0U; j < object->volumes.size(); j++) {
                auto volume {object->volumes.at(j)};
                volume->input_file = file.ToStdString();
                volume->input_file_obj_idx = i;
                volume->input_file_vol_idx = j;
            }
        }
        auto i {0U};
        if (obj_idx_to_load > 0) {
            Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load > 0");
            const size_t idx_load = obj_idx_to_load;
            if (idx_load >= model.objects.size()) return std::vector<int>();
            obj_idx = this->load_model_objects(model.objects.at(idx_load));
            i = idx_load;
        } else {
            Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load = 0");
            obj_idx = this->load_model_objects(model.objects);
            Slic3r::Log::info(LogChannel, LOG_WSTRING("obj_idx size: " << obj_idx.size()));
        }

        for (const auto &j : obj_idx) {
            this->objects[j].input_file = file;
            this->objects[j].input_file_obj_idx = i++;
        }
        GetFrame()->statusbar->SetStatusText(_("Loaded ") + input_file.GetName());

        if (this->scaled_down) {
            GetFrame()->statusbar->SetStatusText(_("Your object appears to be too large, so it was automatically scaled down to fit your print bed."));
        }
        if (this->outside_bounds) {
            GetFrame()->statusbar->SetStatusText(_("Some of your object(s) appear to be outside the print bed. Use the arrange button to correct this."));
        }
    }

    progress_dialog->Destroy();
    this->redo = std::stack<UndoOperation>();
    return obj_idx;
}

std::vector<int> Plater::load_model_objects(ModelObject* model_object) {
    ModelObjectPtrs tmp {model_object}; //  wrap in a std::vector
    return load_model_objects(tmp);
}
std::vector<int> Plater::load_model_objects(ModelObjectPtrs model_objects) {
    auto bed_center {this->bed_centerf()};

    auto bed_shape {Slic3r::Polygon::new_scale(this->config->get<ConfigOptionPoints>("bed_shape").values)};
    auto bed_size {bed_shape.bounding_box().size()};

    bool need_arrange {false};

    auto obj_idx {std::vector<int>()};
    Slic3r::Log::info(LogChannel, LOG_WSTRING("Objects: " << model_objects.size()));

    for (auto& obj : model_objects) {
        auto o {this->model->add_object(*obj)};
        o->repair();

        auto tmpobj {PlaterObject()};
        const auto objfile {wxFileName::FileName( obj->input_file )};
        tmpobj.name = wxString(std::string() == obj->name ? obj->name : objfile.GetName());
        tmpobj.identifier = (this->object_identifier)++;

        this->objects.push_back(tmpobj);
        obj_idx.push_back(this->objects.size());
        Slic3r::Log::info(LogChannel, LOG_WSTRING("Object array new size: " << this->objects.size()));
        Slic3r::Log::info(LogChannel, LOG_WSTRING("Instances: " << obj->instances.size()));

        if (obj->instances.size() == 0) {
            if (settings->autocenter) {
                need_arrange = true;
                o->center_around_origin();

                o->add_instance();
                o->instances.back()->offset = this->bed_centerf();
            } else {
                need_arrange = false;
                if (settings->autoalignz) {
                    o->align_to_ground();
                }
                o->add_instance();
            }
        } else {
            if (settings->autoalignz) {
                o->align_to_ground();
            }
        }
        {
            // If the object is too large (more than 5x the bed) scale it down.
            auto size {o->bounding_box().size()};
            double ratio {0.0f};
            if (ratio > 5) {
                for (auto& instance : o->instances) {
                    instance->scaling_factor = (1.0f/ratio);
                    this->scaled_down = true;
                }
            }
        }

        {
            // Provide a warning if downscaling by 5x still puts it over the bed size.

        }
    }
    return obj_idx;
}

MainFrame* Plater::GetFrame() { return dynamic_cast<MainFrame*>(wxGetTopLevelParent(this)); }

int Plater::get_object_index(size_t object_id) {
    for (size_t i = 0U; i < this->objects.size(); i++) {
        if (this->objects.at(i).identifier == object_id) return static_cast<int>(i);
    }
    return -1;
}

}} // Namespace Slic3r::GUI

<commit_msg>Remember that std::vector<>.size() needs to be offset by 1 if it's being used to find the last index.<commit_after>#include <memory>
#include <wx/progdlg.h>
#include <wx/window.h>

#include "Plater.hpp"
#include "ProgressStatusBar.hpp"
#include "Log.hpp"
#include "MainFrame.hpp"

namespace Slic3r { namespace GUI {

const auto PROGRESS_BAR_EVENT = wxNewEventType();

Plater::Plater(wxWindow* parent, const wxString& title, std::shared_ptr<Settings> _settings) :
    wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, title), settings(_settings)
{

    // Set callback for status event for worker threads
    /*
    this->print->set_status_cb([=](std::string percent percent, std::wstring message) {
        wxPostEvent(this, new wxPlThreadEvent(-1, PROGRESS_BAR_EVENT,
    });
    */
    auto on_select_object { [=](size_t& obj_idx) {
       this->select_object(obj_idx);
    } };
    /*
   # Initialize handlers for canvases
    my $on_select_object = sub {
        my ($obj_idx) = @_;
        $self->select_object($obj_idx);
    };
    my $on_double_click = sub {
        $self->object_settings_dialog if $self->selected_object;
    };
    my $on_right_click = sub {
        my ($canvas, $click_pos) = @_;

        my ($obj_idx, $object) = $self->selected_object;
        return if !defined $obj_idx;

        my $menu = $self->object_menu;
        $canvas->PopupMenu($menu, $click_pos);
        $menu->Destroy;
    };
    my $on_instances_moved = sub {
        $self->on_model_change;
    };
    # Initialize 3D plater
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{canvas3D} = Slic3r::GUI::Plater::3D->new($self->{preview_notebook}, $self->{objects}, $self->{model}, $self->{config});
        $self->{preview_notebook}->AddPage($self->{canvas3D}, '3D');
        $self->{canvas3D}->set_on_select_object($on_select_object);
        $self->{canvas3D}->set_on_double_click($on_double_click);
        $self->{canvas3D}->set_on_right_click(sub { $on_right_click->($self->{canvas3D}, @_); });
        $self->{canvas3D}->set_on_instances_moved($on_instances_moved);
        $self->{canvas3D}->on_viewport_changed(sub {
            $self->{preview3D}->canvas->set_viewport_from_scene($self->{canvas3D});
        });
    }
    */
    canvas2D = new Plate2D(preview_notebook, wxDefaultSize, objects, model, config, settings);
    preview_notebook->AddPage(canvas2D, _("2D"));

    /*
    # Initialize 2D preview canvas
    $self->{canvas} = Slic3r::GUI::Plater::2D->new($self->{preview_notebook}, wxDefaultSize, $self->{objects}, $self->{model}, $self->{config});
    $self->{preview_notebook}->AddPage($self->{canvas}, '2D');
    $self->{canvas}->on_select_object($on_select_object);
    $self->{canvas}->on_double_click($on_double_click);
    $self->{canvas}->on_right_click(sub { $on_right_click->($self->{canvas}, @_); });
    $self->{canvas}->on_instances_moved($on_instances_moved);
    # Initialize 3D toolpaths preview
    $self->{preview3D_page_idx} = -1;
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print});
        $self->{preview3D}->canvas->on_viewport_changed(sub {
            $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas);
        });
        $self->{preview_notebook}->AddPage($self->{preview3D}, 'Preview');
        $self->{preview3D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
    }

    # Initialize toolpaths preview
    $self->{toolpaths2D_page_idx} = -1;
    if ($Slic3r::GUI::have_OpenGL) {
        $self->{toolpaths2D} = Slic3r::GUI::Plater::2DToolpaths->new($self->{preview_notebook}, $self->{print});
        $self->{preview_notebook}->AddPage($self->{toolpaths2D}, 'Layers');
        $self->{toolpaths2D_page_idx} = $self->{preview_notebook}->GetPageCount-1;
    }

    EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub {
        wxTheApp->CallAfter(sub {
            my $sel = $self->{preview_notebook}->GetSelection;
            if ($sel == $self->{preview3D_page_idx} || $sel == $self->{toolpaths2D_page_idx}) {
                if (!$Slic3r::GUI::Settings->{_}{background_processing} && !$self->{processed}) {
                    $self->statusbar->SetCancelCallback(sub {
                        $self->stop_background_process;
                        $self->statusbar->SetStatusText("Slicing cancelled");
                        $self->{preview_notebook}->SetSelection(0);

                    });
                    $self->start_background_process;
                } else {
                    $self->{preview3D}->load_print
                        if $sel == $self->{preview3D_page_idx};
                }
            }
        });
    });
    */

}
void Plater::add() {
    Log::info(LogChannel, L"Called Add function");

    auto& start_object_id = this->object_identifier;
    const auto& input_files{open_model(this, *(this->settings), wxTheApp->GetTopWindow())};
    for (const auto& f : input_files) {
        Log::info(LogChannel, (wxString(L"Calling Load File for ") + f).ToStdWstring());
        this->load_file(f);
    }

    // abort if no objects actually added.
    if (start_object_id == this->object_identifier) return;

    // save the added objects
    auto new_model {this->model};

    // get newly added objects count
    auto new_objects_count = this->object_identifier - start_object_id;

    Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring());
    for (auto i = start_object_id; i < new_objects_count + start_object_id; i++) {
        const auto& obj_idx {this->get_object_index(i)};
        new_model->add_object(*(this->model->objects.at(obj_idx)));
    }
    Slic3r::Log::info(LogChannel, (wxString("Obj id:") << object_identifier).ToStdWstring());

    // Prepare for undo
    //this->add_undo_operation("ADD", nullptr, new_model, start_object_id);

}

std::vector<int> Plater::load_file(const wxString& file, const int obj_idx_to_load) {

    auto input_file {wxFileName(file)};
    settings->skein_directory = input_file.GetPath();
    settings->save_settings();

    Slic3r::Model model;
    bool valid_load {true};

    auto obj_idx {std::vector<int>()};
    auto progress_dialog {new wxProgressDialog(_(L"Loading…"), _(L"Processing input file…"), 100, this, 0)};
    progress_dialog->Pulse();
    //TODO: Add a std::wstring so we can handle non-roman characters as file names.
    try {
        model = Slic3r::Model::read_from_file(file.ToStdString());
    } catch (std::runtime_error& e) {
        show_error(this, e.what());
        Slic3r::Log::error(LogChannel, LOG_WSTRING(file << " failed to load: " << e.what()));
        valid_load = false;
    }
    Slic3r::Log::info(LogChannel, LOG_WSTRING("load_valid is " << valid_load));

    if (valid_load) {
        if (model.looks_like_multipart_object()) {
            auto dialog {new wxMessageDialog(this,
            _("This file contains several objects positioned at multiple heights. Instead of considering them as multiple objects, should I consider\n them this file as a single object having multiple parts?\n"), _("Multi-part object detected"), wxICON_WARNING | wxYES | wxNO)};
            if (dialog->ShowModal() == wxID_YES) {
                model.convert_multipart_object();
            }
        }

        for (auto i = 0U; i < model.objects.size(); i++) {
            auto object {model.objects[i]};
            object->input_file = file.ToStdString();
            for (auto j = 0U; j < object->volumes.size(); j++) {
                auto volume {object->volumes.at(j)};
                volume->input_file = file.ToStdString();
                volume->input_file_obj_idx = i;
                volume->input_file_vol_idx = j;
            }
        }
        auto i {0U};
        if (obj_idx_to_load > 0) {
            Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load > 0");
            const size_t idx_load = obj_idx_to_load;
            if (idx_load >= model.objects.size()) return std::vector<int>();
            obj_idx = this->load_model_objects(model.objects.at(idx_load));
            i = idx_load;
        } else {
            Slic3r::Log::info(LogChannel, L"Loading model objects, obj_idx_to_load = 0");
            obj_idx = this->load_model_objects(model.objects);
            Slic3r::Log::info(LogChannel, LOG_WSTRING("obj_idx size: " << obj_idx.size()));
        }

        for (const auto &j : obj_idx) {
            this->objects[j].input_file = file;
            this->objects[j].input_file_obj_idx = i++;
        }
        GetFrame()->statusbar->SetStatusText(_("Loaded ") + input_file.GetName());

        if (this->scaled_down) {
            GetFrame()->statusbar->SetStatusText(_("Your object appears to be too large, so it was automatically scaled down to fit your print bed."));
        }
        if (this->outside_bounds) {
            GetFrame()->statusbar->SetStatusText(_("Some of your object(s) appear to be outside the print bed. Use the arrange button to correct this."));
        }
    }

    progress_dialog->Destroy();
    this->redo = std::stack<UndoOperation>();
    return obj_idx;
}

std::vector<int> Plater::load_model_objects(ModelObject* model_object) {
    ModelObjectPtrs tmp {model_object}; //  wrap in a std::vector
    return load_model_objects(tmp);
}
std::vector<int> Plater::load_model_objects(ModelObjectPtrs model_objects) {
    auto bed_center {this->bed_centerf()};

    auto bed_shape {Slic3r::Polygon::new_scale(this->config->get<ConfigOptionPoints>("bed_shape").values)};
    auto bed_size {bed_shape.bounding_box().size()};

    bool need_arrange {false};

    auto obj_idx {std::vector<int>()};
    Slic3r::Log::info(LogChannel, LOG_WSTRING("Objects: " << model_objects.size()));

    for (auto& obj : model_objects) {
        auto o {this->model->add_object(*obj)};
        o->repair();

        auto tmpobj {PlaterObject()};
        const auto objfile {wxFileName::FileName( obj->input_file )};
        tmpobj.name = wxString(std::string() == obj->name ? obj->name : objfile.GetName());
        tmpobj.identifier = (this->object_identifier)++;

        this->objects.push_back(tmpobj);
        obj_idx.push_back(this->objects.size() - 1);
        Slic3r::Log::info(LogChannel, LOG_WSTRING("Object array new size: " << this->objects.size()));
        Slic3r::Log::info(LogChannel, LOG_WSTRING("Instances: " << obj->instances.size()));

        if (obj->instances.size() == 0) {
            if (settings->autocenter) {
                need_arrange = true;
                o->center_around_origin();

                o->add_instance();
                o->instances.back()->offset = this->bed_centerf();
            } else {
                need_arrange = false;
                if (settings->autoalignz) {
                    o->align_to_ground();
                }
                o->add_instance();
            }
        } else {
            if (settings->autoalignz) {
                o->align_to_ground();
            }
        }
        {
            // If the object is too large (more than 5x the bed) scale it down.
            auto size {o->bounding_box().size()};
            double ratio {0.0f};
            if (ratio > 5) {
                for (auto& instance : o->instances) {
                    instance->scaling_factor = (1.0f/ratio);
                    this->scaled_down = true;
                }
            }
        }

        {
            // Provide a warning if downscaling by 5x still puts it over the bed size.

        }
    }
    return obj_idx;
}

MainFrame* Plater::GetFrame() { return dynamic_cast<MainFrame*>(wxGetTopLevelParent(this)); }

int Plater::get_object_index(size_t object_id) {
    for (size_t i = 0U; i < this->objects.size(); i++) {
        if (this->objects.at(i).identifier == object_id) return static_cast<int>(i);
    }
    return -1;
}

}} // Namespace Slic3r::GUI

<|endoftext|>


<commit_before>/*
 * For licensing please refer to the LICENSE.md file
 */

#pragma once

#include <string>
#include <vector>
#include <valarray>
#include <array>
#include <fstream>
#include <map>

namespace neon
{
struct ElementData
{
    ElementData(int numberOfNodes, int numberOfTags, int elementType, int id) :
        tags(numberOfTags, 0),
        nodalConnectivity(numberOfNodes, 0),
        elementType(elementType),
        id(id)
    {
    }
    std::vector<int> tags;
    std::vector<int> nodalConnectivity;
    int elementType;
    int id;
};

struct NodeData
{
    int id;
    std::array<double, 3> coordinates;
};

/*!
 * \class GmshReader
 * \brief Parses Gmsh format and returns the data structures of the mesh
 * in a format for neon to process
 */
class GmshReader
{
public:

    using StringKey = std::string;
    using Value     = std::vector<ElementData>;

public:

    GmshReader(const std::string& fileName);

    ~GmshReader() = default;

    /** Gmsh element numbering scheme */
    enum { LINE2 = 1, TRI3, QUAD4, TETRA4, HEX8, PRISM6, TRI6 = 9, TETRA10 = 11};

    const std::map<StringKey, Value>& mesh() const {return gmshMesh;}

private:

    /**
     * Parse the gmsh file as provided by the filename with the appended file
     * extension (.msh)
     * @param file name of the mesh to open
     * @return true if the read was successful
     */
     bool parse(const std::string& fileName);

    /**
     * Provide a reference to the nodes and dimensions that will be populated
     * with the correct data based on the elementType
     * @param Gmsh element number
     * @return number of nodes per element
     */
    short mapElementData(int elementType);

    /**
     * Check the version of gmsh is support otherwise print out a warning
     * @param gmshVersion
     */
    void checkSupportedGmsh(float gmshVersion);

    void fillMesh();

private:

    std::map<StringKey, Value> gmshMesh;
    std::map<int, std::string> physicalGroupMap;

    std::vector<NodeData> nodeList;

    std::string fileName;   //!< File name of gmsh file
    std::fstream gmshFile;  //!< Hold an object to the file stream

};
}
<commit_msg>Added enumerations for each available element type<commit_after>/*
 * For licensing please refer to the LICENSE.md file
 */

#pragma once

#include <string>
#include <vector>
#include <valarray>
#include <array>
#include <fstream>
#include <map>

namespace neon
{
struct ElementData
{
    ElementData(int numberOfNodes, int numberOfTags, int elementType, int id) :
        tags(numberOfTags, 0),
        nodalConnectivity(numberOfNodes, 0),
        elementType(elementType),
        id(id)
    {
    }
    std::vector<int> tags;
    std::vector<int> nodalConnectivity;
    int elementType;
    int id;
};

struct NodeData
{
    int id;
    std::array<double, 3> coordinates;
};

/*!
 * \class GmshReader
 * \brief Parses Gmsh format and returns the data structures of the mesh
 * in a format for neon to process
 */
class GmshReader
{
public:

    using StringKey = std::string;
    using Value     = std::vector<ElementData>;

public:

    GmshReader(const std::string& fileName);

    ~GmshReader() = default;

    /** Gmsh element numbering scheme */
    enum ELEMENT_TYPE_ID {// Standard linear elements
                          LINE2=1,
                          TRIANGLE3,
                          QUADRILATERAL4,
                          TETRAHEDRON4,
                          HEXAHEDRON8,
                          PRISM6,
                          PYRAMID5,
                          // Quadratic elements
                          LINE3,
                          TRIANGLE6,
                          QUADRILATERAL9,  // 4 vertex, 4 edges and 1 face node
                          TETRAHEDRON10,
                          HEXAHEDRON27,
                          PRISM18,
                          PYRAMID14,
                          POINT = 15,
                          QUADRILATERAL8,
                          HEXAHEDRON20,
                          PRISM15,
                          PYRAMID13,
                          TRIANGLE9 = 20,
                          TRIANGLE10,
                          TRIANGLE12,
                          TRIANGLE15,
                          TRIANGLE15_IC,  // Incomplete 15 node triangle
                          TRIANGLE21 = 25,
                          EDGE4,
                          EDGE5,
                          EDGE6,
                          TETRAHEDRON20,
                          TETRAHEDRON35,
                          TETRAHEDRON56,
                          HEXAHEDRON64 = 92,
                          HEXAHEDRON125};

    const std::map<StringKey, Value>& mesh() const {return gmshMesh;}

private:

    /**
     * Parse the gmsh file as provided by the filename with the appended file
     * extension (.msh)
     * @param file name of the mesh to open
     * @return true if the read was successful
     */
     bool parse(const std::string& fileName);

    /**
     * Provide a reference to the nodes and dimensions that will be populated
     * with the correct data based on the elementType
     * @param Gmsh element number
     * @return number of nodes per element
     */
    short mapElementData(int elementType);

    /**
     * Check the version of gmsh is support otherwise print out a warning
     * @param gmshVersion
     */
    void checkSupportedGmsh(float gmshVersion);

    void fillMesh();

private:

    std::map<StringKey, Value> gmshMesh;
    std::map<int, std::string> physicalGroupMap;

    std::vector<NodeData> nodeList;

    std::string fileName;   //!< File name of gmsh file
    std::fstream gmshFile;  //!< Hold an object to the file stream

};
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <uxtheme.h>
#include <vsstyle.h>
#include <vssym32.h>

#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_ptr.h"
#include "base/resource_util.h"
#include "grit/gfx_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/brush.h"
#include "ui/gfx/canvas_direct2d.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/native_theme_win.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/win_util.h"

namespace {

const char kVisibleModeFlag[] = "d2d-canvas-visible";
const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass";

class TestWindow {
 public:
  static const int kWindowSize = 500;
  static const int kWindowPosition = 10;

  TestWindow() : hwnd_(NULL) {
    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      Sleep(1000);

    RegisterMyClass();

    hwnd_ = CreateWindowEx(0, kWindowClassName, NULL,
                           WS_OVERLAPPEDWINDOW,
                           kWindowPosition, kWindowPosition,
                           kWindowSize, kWindowSize,
                           NULL, NULL, NULL, this);
    DCHECK(hwnd_);

    // Initialize the RenderTarget for the window.
    rt_ = MakeHWNDRenderTarget();

    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      ShowWindow(hwnd(), SW_SHOW);
  }
  virtual ~TestWindow() {
    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      Sleep(1000);
    DestroyWindow(hwnd());
    UnregisterMyClass();
  }

  HWND hwnd() const { return hwnd_; }

  ID2D1RenderTarget* rt() const { return rt_.get(); }

 private:
  ID2D1RenderTarget* MakeHWNDRenderTarget() {
    D2D1_RENDER_TARGET_PROPERTIES rt_properties =
        D2D1::RenderTargetProperties();
    rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;

    ID2D1HwndRenderTarget* rt = NULL;
    gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget(
        rt_properties,
        D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)),
        &rt);
    return rt;
  }

  void RegisterMyClass() {
    WNDCLASSEX class_ex;
    class_ex.cbSize = sizeof(WNDCLASSEX);
    class_ex.style = CS_DBLCLKS;
    class_ex.lpfnWndProc = &DefWindowProc;
    class_ex.cbClsExtra = 0;
    class_ex.cbWndExtra = 0;
    class_ex.hInstance = NULL;
    class_ex.hIcon = NULL;
    class_ex.hCursor = LoadCursor(NULL, IDC_ARROW);
    class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
    class_ex.lpszMenuName = NULL;
    class_ex.lpszClassName = kWindowClassName;
    class_ex.hIconSm = class_ex.hIcon;
    ATOM atom = RegisterClassEx(&class_ex);
    DCHECK(atom);
  }

  void UnregisterMyClass() {
    ::UnregisterClass(kWindowClassName, NULL);
  }

  HWND hwnd_;

  ScopedComPtr<ID2D1RenderTarget> rt_;

  DISALLOW_COPY_AND_ASSIGN(TestWindow);
};

// Loads a png data blob from the data resources associated with this
// executable, decodes it and returns a SkBitmap.
SkBitmap LoadBitmapFromResources(int resource_id) {
  SkBitmap bitmap;

  HINSTANCE resource_instance = GetModuleHandle(NULL);
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr,
                                      &data_size)) {
    scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory(
        reinterpret_cast<const unsigned char*>(data_ptr), data_size));
    if (!memory)
      return bitmap;

    if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap))
      NOTREACHED() << "Unable to decode theme image resource " << resource_id;
  }
  return bitmap;
}

bool CheckForD2DCompatibility() {
  if (!gfx::Direct2dIsAvailable()) {
    LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " <<
                    "Vista with Platform Update KB971644";
    return false;
  }
  return true;
}

}  // namespace

TEST(CanvasDirect2D, CreateCanvas) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());
}

TEST(CanvasDirect2D, SaveRestoreNesting) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Simple.
  canvas.Save();
  canvas.Restore();

  // Nested.
  canvas.Save();
  canvas.Save();
  canvas.Restore();
  canvas.Restore();

  // Simple alpha.
  canvas.SaveLayerAlpha(127);
  canvas.Restore();

  // Alpha with sub-rect.
  canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100));
  canvas.Restore();

  // Nested alpha.
  canvas.Save();
  canvas.SaveLayerAlpha(127);
  canvas.Save();
  canvas.Restore();
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, SaveLayerAlpha) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100);
  canvas.SaveLayerAlpha(127);
  canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100);
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100);
  canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50));
  canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100);
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, FillRect) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100);
}

TEST(CanvasDirect2D, PlatformPainting) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  gfx::NativeDrawingContext dc = canvas.BeginPlatformPaint();

  // Use the system theme engine to draw a native button. This only works on a
  // GDI device context.
  RECT r = { 20, 20, 220, 80 };
  gfx::NativeThemeWin::instance()->PaintButton(
      dc, BP_PUSHBUTTON, PBS_NORMAL, DFCS_BUTTONPUSH, &r);

  canvas.EndPlatformPaint();
}

TEST(CanvasDirect2D, ClipRect) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
}

TEST(CanvasDirect2D, ClipRectWithTranslate) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Repeat the same rendering as in ClipRect...
  canvas.Save();
  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
  canvas.Restore();

  // ... then translate, clip and fill again relative to the new origin.
  canvas.Save();
  canvas.TranslateInt(150, 150);
  canvas.ClipRectInt(10, 10, 110, 110);
  canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500);
  canvas.Restore();
}

TEST(CanvasDirect2D, ClipRectWithScale) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Repeat the same rendering as in ClipRect...
  canvas.Save();
  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
  canvas.Restore();

  // ... then translate and scale, clip and fill again relative to the new
  // origin.
  canvas.Save();
  canvas.TranslateInt(150, 150);
  canvas.ScaleInt(2, 2);
  canvas.ClipRectInt(10, 10, 110, 110);
  canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawRectInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawLineInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawBitmapInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.DrawBitmapInt(bitmap, 100, 100);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawBitmapInt2) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false);
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true);
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false);
  canvas.Restore();
}

TEST(CanvasDirect2D, TileImageInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.TileImageInt(bitmap, 10, 10, 300, 300);
  canvas.Restore();
}
<commit_msg>Removing uneeded test.  Because of the native theme cleanup, the method being called here is going away anyway.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <uxtheme.h>
#include <vsstyle.h>
#include <vssym32.h>

#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_ptr.h"
#include "base/resource_util.h"
#include "grit/gfx_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/brush.h"
#include "ui/gfx/canvas_direct2d.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/win_util.h"

namespace {

const char kVisibleModeFlag[] = "d2d-canvas-visible";
const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass";

class TestWindow {
 public:
  static const int kWindowSize = 500;
  static const int kWindowPosition = 10;

  TestWindow() : hwnd_(NULL) {
    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      Sleep(1000);

    RegisterMyClass();

    hwnd_ = CreateWindowEx(0, kWindowClassName, NULL,
                           WS_OVERLAPPEDWINDOW,
                           kWindowPosition, kWindowPosition,
                           kWindowSize, kWindowSize,
                           NULL, NULL, NULL, this);
    DCHECK(hwnd_);

    // Initialize the RenderTarget for the window.
    rt_ = MakeHWNDRenderTarget();

    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      ShowWindow(hwnd(), SW_SHOW);
  }
  virtual ~TestWindow() {
    if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag))
      Sleep(1000);
    DestroyWindow(hwnd());
    UnregisterMyClass();
  }

  HWND hwnd() const { return hwnd_; }

  ID2D1RenderTarget* rt() const { return rt_.get(); }

 private:
  ID2D1RenderTarget* MakeHWNDRenderTarget() {
    D2D1_RENDER_TARGET_PROPERTIES rt_properties =
        D2D1::RenderTargetProperties();
    rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;

    ID2D1HwndRenderTarget* rt = NULL;
    gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget(
        rt_properties,
        D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)),
        &rt);
    return rt;
  }

  void RegisterMyClass() {
    WNDCLASSEX class_ex;
    class_ex.cbSize = sizeof(WNDCLASSEX);
    class_ex.style = CS_DBLCLKS;
    class_ex.lpfnWndProc = &DefWindowProc;
    class_ex.cbClsExtra = 0;
    class_ex.cbWndExtra = 0;
    class_ex.hInstance = NULL;
    class_ex.hIcon = NULL;
    class_ex.hCursor = LoadCursor(NULL, IDC_ARROW);
    class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND);
    class_ex.lpszMenuName = NULL;
    class_ex.lpszClassName = kWindowClassName;
    class_ex.hIconSm = class_ex.hIcon;
    ATOM atom = RegisterClassEx(&class_ex);
    DCHECK(atom);
  }

  void UnregisterMyClass() {
    ::UnregisterClass(kWindowClassName, NULL);
  }

  HWND hwnd_;

  ScopedComPtr<ID2D1RenderTarget> rt_;

  DISALLOW_COPY_AND_ASSIGN(TestWindow);
};

// Loads a png data blob from the data resources associated with this
// executable, decodes it and returns a SkBitmap.
SkBitmap LoadBitmapFromResources(int resource_id) {
  SkBitmap bitmap;

  HINSTANCE resource_instance = GetModuleHandle(NULL);
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr,
                                      &data_size)) {
    scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory(
        reinterpret_cast<const unsigned char*>(data_ptr), data_size));
    if (!memory)
      return bitmap;

    if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap))
      NOTREACHED() << "Unable to decode theme image resource " << resource_id;
  }
  return bitmap;
}

bool CheckForD2DCompatibility() {
  if (!gfx::Direct2dIsAvailable()) {
    LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " <<
                    "Vista with Platform Update KB971644";
    return false;
  }
  return true;
}

}  // namespace

TEST(CanvasDirect2D, CreateCanvas) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());
}

TEST(CanvasDirect2D, SaveRestoreNesting) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Simple.
  canvas.Save();
  canvas.Restore();

  // Nested.
  canvas.Save();
  canvas.Save();
  canvas.Restore();
  canvas.Restore();

  // Simple alpha.
  canvas.SaveLayerAlpha(127);
  canvas.Restore();

  // Alpha with sub-rect.
  canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100));
  canvas.Restore();

  // Nested alpha.
  canvas.Save();
  canvas.SaveLayerAlpha(127);
  canvas.Save();
  canvas.Restore();
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, SaveLayerAlpha) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100);
  canvas.SaveLayerAlpha(127);
  canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100);
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100);
  canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50));
  canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100);
  canvas.Restore();
  canvas.Restore();
}

TEST(CanvasDirect2D, FillRect) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100);
}

TEST(CanvasDirect2D, ClipRect) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
}

TEST(CanvasDirect2D, ClipRectWithTranslate) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Repeat the same rendering as in ClipRect...
  canvas.Save();
  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
  canvas.Restore();

  // ... then translate, clip and fill again relative to the new origin.
  canvas.Save();
  canvas.TranslateInt(150, 150);
  canvas.ClipRectInt(10, 10, 110, 110);
  canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500);
  canvas.Restore();
}

TEST(CanvasDirect2D, ClipRectWithScale) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  // Repeat the same rendering as in ClipRect...
  canvas.Save();
  canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500);
  canvas.ClipRectInt(20, 20, 120, 120);
  canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500);
  canvas.Restore();

  // ... then translate and scale, clip and fill again relative to the new
  // origin.
  canvas.Save();
  canvas.TranslateInt(150, 150);
  canvas.ScaleInt(2, 2);
  canvas.ClipRectInt(10, 10, 110, 110);
  canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawRectInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawLineInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  canvas.Save();
  canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawBitmapInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.DrawBitmapInt(bitmap, 100, 100);
  canvas.Restore();
}

TEST(CanvasDirect2D, DrawBitmapInt2) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false);
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true);
  canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false);
  canvas.Restore();
}

TEST(CanvasDirect2D, TileImageInt) {
  if (!CheckForD2DCompatibility())
    return;
  TestWindow window;
  gfx::CanvasDirect2D canvas(window.rt());

  SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE);

  canvas.Save();
  canvas.TileImageInt(bitmap, 10, 10, 300, 300);
  canvas.Restore();
}
<|endoftext|>


<commit_before>#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include "thor/PrimitiveTypes.h"
#include "thor/lang/Language.h"
#include "thor/lang/String.h"
#include "thor/container/Vector.h"

using namespace thor;

namespace
{
void draw_background(SDL_Renderer *renderer, int w, int h)
{
    SDL_Color col[2] = {
        { 0x66, 0x66, 0x66, 0xff },
        { 0x99, 0x99, 0x99, 0xff },
    };
    int i, x, y;
    SDL_Rect rect;

    rect.w = 8;
    rect.h = 8;
    for (y = 0; y < h; y += rect.h) {
        for (x = 0; x < w; x += rect.w) {
            /* use an 8x8 checkerboard pattern */
            i = (((x ^ y) >> 3) & 1);
            SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a);

            rect.x = x;
            rect.y = y;
            SDL_RenderFillRect(renderer, &rect);
        }
    }
}

}

namespace imgutil
{

class Image : public thor::lang::Object
{
public:
    using PixCont = thor::container::Vector<int32>;

    Image();
    ~Image();

    bool load(thor::lang::String* filename);

    PixCont* getAllPixels();
       void  setAllPixels(PixCont* pixs);

    SDL_Surface *surface;
};

Image::Image() : surface(nullptr)
{
}

Image::~Image()
{
    SDL_FreeSurface(surface);
}

bool Image::load(thor::lang::String* filename)
{
    char cfilename[64];
    wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename));
    surface = IMG_Load(cfilename);

    return surface != nullptr;
}

auto Image::getAllPixels() -> PixCont*
{
    int         w = surface->w;
    int         h = surface->h;
    int     total = w*h;
    int* ori_pixs = reinterpret_cast<int*>(surface->pixels);

    // FIXME: instead of total, create() always get a UINT_MAX...WTF?
    // PixCont* pixs = PixCont::create(static_cast<int64>(total));

    PixCont* pixs = PixCont::create();

    for(int i = 0; i < total; ++i)
    {
        int val = *ori_pixs;
        // pixs->set(i, val);

        pixs->pushBack(val);
        ++ori_pixs;
    }

    return pixs;
}

void Image::setAllPixels(PixCont* pixs)
{
    int         w = surface->w;
    int         h = surface->h;
    int     total = w*h;
    int* ori_pixs = reinterpret_cast<int*>(surface->pixels);

    for(int i = 0; i < total; ++i)
    {
        int val = pixs->get(i);

        *ori_pixs = val;
        ++ori_pixs;
    }
}

class Window : public thor::lang::Object
{
public:
    Window(int32 x, int32 y);
    ~Window();

    bool isQuit();

    void handleEvent();

    void showImage(Image* img);

private:
    SDL_Window   *_window;
    SDL_Renderer *_render;
    SDL_Texture  *_texture;

    bool _quit;
};

Window::Window(int32 x, int32 y) :
    _window(nullptr),
    _render(nullptr),
    _texture(nullptr),
    _quit(false)
{
    SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render);
    SDL_SetWindowPosition(_window, 0, 0);
    SDL_SetWindowTitle(_window, "Thorlang Monochrome");

    std::assert(_window != nullptr && _render != nullptr && "Failed to create SDL_Window / SDL_Renderer.");
}

Window::~Window()
{
    SDL_DestroyRenderer(_render);
    SDL_DestroyWindow(_window);
}

bool Window::isQuit()
{
    return _quit;
}

void Window::handleEvent()
{
    SDL_Event event;

    while(SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_KEYUP:
                switch (event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        _quit = 1;
                    default:
                        break;
                }
                break;
            case SDL_QUIT:
                _quit = 1;
                break;
            default:
                break;
        }
    }
}

void Window::showImage(Image* img)
{
    int w, h;

    _texture = SDL_CreateTextureFromSurface(_render, img->surface);

    SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h);
    SDL_SetWindowSize(_window, w, h);

    draw_background(_render, w, h);

    SDL_RenderCopy(_render, _texture, nullptr, nullptr);
    SDL_RenderPresent(_render);

    SDL_ShowWindow(_window);
}

bool initialize()
{
    int result = SDL_Init(SDL_INIT_VIDEO);

    return result == 0;
}

void finalize()
{
    SDL_Quit();
}

}

<commit_msg>Fix: release texture if any<commit_after>#include <iostream>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include "thor/PrimitiveTypes.h"
#include "thor/lang/Language.h"
#include "thor/lang/String.h"
#include "thor/container/Vector.h"

using namespace thor;

namespace
{
void draw_background(SDL_Renderer *renderer, int w, int h)
{
    SDL_Color col[2] = {
        { 0x66, 0x66, 0x66, 0xff },
        { 0x99, 0x99, 0x99, 0xff },
    };
    int i, x, y;
    SDL_Rect rect;

    rect.w = 8;
    rect.h = 8;
    for (y = 0; y < h; y += rect.h) {
        for (x = 0; x < w; x += rect.w) {
            /* use an 8x8 checkerboard pattern */
            i = (((x ^ y) >> 3) & 1);
            SDL_SetRenderDrawColor(renderer, col[i].r, col[i].g, col[i].b, col[i].a);

            rect.x = x;
            rect.y = y;
            SDL_RenderFillRect(renderer, &rect);
        }
    }
}

}

namespace imgutil
{

class Image : public thor::lang::Object
{
public:
    using PixCont = thor::container::Vector<int32>;

    Image();
    ~Image();

    bool load(thor::lang::String* filename);

    PixCont* getAllPixels();
       void  setAllPixels(PixCont* pixs);

    SDL_Surface *surface;
};

Image::Image() : surface(nullptr)
{
}

Image::~Image()
{
    SDL_FreeSurface(surface);
}

bool Image::load(thor::lang::String* filename)
{
    char cfilename[64];
    wcstombs(cfilename, filename->data->c_str(), sizeof(cfilename));
    surface = IMG_Load(cfilename);

    return surface != nullptr;
}

auto Image::getAllPixels() -> PixCont*
{
    int         w = surface->w;
    int         h = surface->h;
    int     total = w*h;
    int* ori_pixs = reinterpret_cast<int*>(surface->pixels);

    // FIXME: instead of total, create() always get a UINT_MAX...WTF?
    // PixCont* pixs = PixCont::create(static_cast<int64>(total));

    PixCont* pixs = PixCont::create();

    for(int i = 0; i < total; ++i)
    {
        int val = *ori_pixs;
        // pixs->set(i, val);

        pixs->pushBack(val);
        ++ori_pixs;
    }

    return pixs;
}

void Image::setAllPixels(PixCont* pixs)
{
    int         w = surface->w;
    int         h = surface->h;
    int     total = w*h;
    int* ori_pixs = reinterpret_cast<int*>(surface->pixels);

    for(int i = 0; i < total; ++i)
    {
        int val = pixs->get(i);

        *ori_pixs = val;
        ++ori_pixs;
    }
}

class Window : public thor::lang::Object
{
public:
    Window(int32 x, int32 y);
    ~Window();

    bool isQuit();

    void handleEvent();

    void showImage(Image* img);

private:
    SDL_Window   *_window;
    SDL_Renderer *_render;
    SDL_Texture  *_texture;

    bool _quit;
};

Window::Window(int32 x, int32 y) :
    _window(nullptr),
    _render(nullptr),
    _texture(nullptr),
    _quit(false)
{
    SDL_CreateWindowAndRenderer(0, 0, 0, &_window, &_render);
    SDL_SetWindowPosition(_window, 0, 0);
    SDL_SetWindowTitle(_window, "Thorlang Monochrome");

    std::assert(_window != nullptr && _render != nullptr && "Failed to create SDL_Window / SDL_Renderer.");
}

Window::~Window()
{
    if(_texture != nullptr)
        SDL_DestroyTexture(_texture);

    SDL_DestroyRenderer(_render);
    SDL_DestroyWindow(_window);
}

bool Window::isQuit()
{
    return _quit;
}

void Window::handleEvent()
{
    SDL_Event event;

    while(SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_KEYUP:
                switch (event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        _quit = 1;
                    default:
                        break;
                }
                break;
            case SDL_QUIT:
                _quit = 1;
                break;
            default:
                break;
        }
    }
}

void Window::showImage(Image* img)
{
    int w, h;

    _texture = SDL_CreateTextureFromSurface(_render, img->surface);

    SDL_QueryTexture(_texture, nullptr, nullptr, &w, &h);
    SDL_SetWindowSize(_window, w, h);

    draw_background(_render, w, h);

    SDL_RenderCopy(_render, _texture, nullptr, nullptr);
    SDL_RenderPresent(_render);

    SDL_ShowWindow(_window);
}

bool initialize()
{
    int result = SDL_Init(SDL_INIT_VIDEO);

    return result == 0;
}

void finalize()
{
    SDL_Quit();
}

}

<|endoftext|>


<commit_before>/// @author Владимир Керимов

#pragma once

#include <data/bytes>
#include <data_head/object_data.hpp>

namespace data
{
    class bytes::data : public object::data
    {
    public:
        data();

    private:
    };
}

// sine qua non
<commit_msg>Saved change.<commit_after>/// @author Владимир Керимов

#pragma once

#include <data/bytes>
#include <data_head/object_data.hpp>

namespace data
{
    class bytes::data : public object::data
    {
    public:
        data();

    private:
        std::string m_array;
    };
}

// sine qua non
<|endoftext|>


<commit_before><commit_msg>BUG: removing items and adding again clears previous selection. mantis #1025<commit_after><|endoftext|>


<commit_before>/* A recursive C++ program to find Grundy Number for
   a game.
 Game Description :  The game starts with a number- 'n'
 and the player to move divides the number- 'n' with 2, 3
 or 6 and then takes the floor. If the integer becomes 0,
 it is removed. The last player to move wins.  */
#include<bits/stdc++.h>
using namespace std;

// A Function to calculate Mex of all the values in
// that set.
int calculateMex(unordered_set<int> Set)
{
    int Mex = 0;

    while (Set.find(Mex) != Set.end())
        Mex++;

    return (Mex);
}

// A function to Compute Grundy Number of 'n'
// Only this function varies according to the game
int calculateGrundy (int n)
{
    if (n == 0)
        return (0);

    unordered_set<int> Set; // A Hash Table

    Set.insert(calculateGrundy(n/2));
    Set.insert(calculateGrundy(n/3));
    Set.insert(calculateGrundy(n/6));

    return (calculateMex(Set));
}

// Driver program to test above functions
int main()
{
    int n = 10;
    printf("%d", calculateGrundy (n));
    return (0);
}
<commit_msg>Delete Combinatorial_Game_Theory_Nimbers_and_Mex.cpp<commit_after><|endoftext|>


<commit_before>/*
Copyright 2011, Jernej Kovacic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
@file NumericUtil.cpp

Implementation  of the class NumericUtil, a collection of some useful
numerical utilities. This is a templated class and must not be compiled.
Instead it must be included after the class declaration in the .h file

@author Jernej Kovacic
*/

// Deliberately there is no #include "NumericUtil.h"
#include "Rational.h"
#include "SqMatrixGeneric.h"
#include "PolynomialGeneric.h"

#include <complex>

// Note that the optimal EPS depends on application requirements
/*
 * Definition of EPS for type float
 */
template<>
float math::NumericUtil<float>::EPS = 1e-9f;

/*
 * Double is a more accurate type...
 */
template<>
double math::NumericUtil<double>::EPS = 1e-16;

/*
 * and long double is even more accurate
 */
template<>
long double math::NumericUtil<long double>::EPS = 1e-22L;

/*
 * In int and other types, EPS doesn't make sense, so set it to 0
 */
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);

/**
 * A constant value with the T's representation of zero (0)
 */
template<class T>
const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) );

/**
 * A constant value with the T's representation of one (1)
 */
template<class T>
const T math::NumericUtil<T>::ONE ( static_cast<T>(1) );

/**
 * Does the given value equal (or is close enough to) zero?
 * Implementation depends on the type T.
 * For floating point types (float, double, long double), it checks
 * whether its absolute value is less than a hardcoded constant 'eps'.
 *
 * @param value
 *
 @ @return true or false
 */
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
    /*
     * The implementation for integers et al. where the == operator
     * does make sense and no comparison to EPS is necessary.
     */
    bool retVal = ( ZERO==value ? true : false );

    return retVal;
}

/*
 * Float, double and long double require specialized implementations of isZero().
 * In case of these three types, the equality operator (==) is useless.
 * In numerical mathematics, two numbers are considered "equal", when
 * absolute value of their difference does not exceed a reasonably set EPS.
 * All specializations are very similar and only differ in types of an input value.
 * For easier maintainability, the specialization will be implemented
 * only once using a parameterized #define
 */

#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \
template<> \
bool math::NumericUtil<FDL>::isZero(const FDL& value) \
{ \
    bool retVal = false; \
    retVal = ( value>-EPS && value<EPS ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO

/*
 * Specialization for complex.
 * As complex is a templated class, again it must be implemented for each supported subtemplated
 * type. To facilitate this, a parameterized macro is introduced.
 * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare
 * it with EPS^2 than calculating its square root (the actual definition of complex abs. value).
 */
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \
template<> \
bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \
{ \
    bool retVal = false; \
    const FDL eps = math::NumericUtil<FDL>::getEPS(); \
    retVal = ( std::norm(value)<=eps*eps ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX
/*
 * Implementation for Rational
 */
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
    // Rational already contains its own isZero()...
    return value.isZero();
}

/**
 * @return value of 'eps' for the desired type
 */
template<class T>
T math::NumericUtil<T>::getEPS()
{
    return EPS;
}

/**
 * Sets the new value of 'eps' for the desired type if the default one does
 * not meet application's requirements.
 *
 * @note There is no check of input so make sure a sensible value
 *       (typically a very small positive number) is entered.
 *
 * @param eps - new value of EPS
 */
template<class T>
void math::NumericUtil<T>::setEPS(const T& eps)
{
    EPS = eps;
}

/*
 * In C++, it is not possible to specialize a function of a templated class
 * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>).
 * However it is possible if a single function is templated.
 * For more details, see the discussion at:
 * http://www.cplusplus.com/forum/general/68298/
 *
 * At the moment, getUnit() is only used by power(). Until it is changed,
 * getUnit() will be defined in this file as a templated standalone function.
 * Additionlly, implementations of the function are "hidden" in the namespace
 * math::getunit which is not supposed to be known to other members of math::
 */
namespace math
{
    namespace getunit
    {
        /*
         * @param t - an arbitrary instance of T, ignored by the generic implementation,
         *            at specializations it might be useful to determine unit's dimensions etc.
         *
         * @return an instance of T acting as a multiplication unit
         */
        template<class T>
        T getUnit(const T& t)
        {
            return T(math::NumericUtil<T>::ONE);
        }

        /*
         * Specialization for generic class math::SqMatrixGeneric<T>
         *
         * @param t - an arbitrary instance of a square matrix to determine
         *            dimensions of the returned unit matrix
         *
         * @return a unit nxn square matrix where n is a dimension of 't'
         */
        template<class T>
        math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t)
        {
            const unsigned int N = t.nrRows();
            math::SqMatrixGeneric<T> retVal(N);
            retVal.setUnit();
            return retVal;
        }

        /*
         * Specialization for generic class math::PolynomialGeneric<T>
         *
         * @param t - ignored
         *
         * @return a unit polynomial p(x) = (T)1
         */
        template<class T>
        math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t)
        {
            math::PolynomialGeneric<T> retVal(1);
            retVal.set(0, math::NumericUtil<T>::ONE);
            return retVal;
        }
    } // namespace units
} // namespace math

/**
 * Efficient calculation of positive integer power.
 * Complexity of the algorithm is O(log2 n).
 *
 * @note T must have implemented operator*=
 *
 * @param base - base of the exponentiation
 * @param n - exponent (a positive integer number)
 *
 * @return base^n
 */
template<class T>
T math::NumericUtil<T>::power(const T& base, unsigned int n)
{
    /*
     * "Exponentiation by squaring" algorithm will be applied.
     *
     * Exponentiation can be expanded into:
     *        n    n%2       n/2
     *       a  = a   * (a^2)
     *
     * where / and % are integer division and remainder operators.
     *
     * The expression above can be further recursively derived to:
     *  n    n%2    (n/2)%2     (n/2)/2
     * a  = a   (a^2)       (a^4)       =
     *
     *       n%2    (n/2)%2    (n/4)%2    ((n/2)/2)/2
     *    = a   (a^2)      (a^4)      (a^8)           = ....
     *
     * It is simple to develop an iterative algorithm where factor
     * is iteratively increased by squaring itself and coefficients
     * ai (i=0..n) are iteratively calculated by the remainder of
     * division by 2
     */

    // Note: it is safe to use bitwise operators for arithmetic operations
    // on unsigned int values as they do not depend on endianess:
    // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness

    T retVal = math::getunit::getUnit(base);
    T factor = base;

    // Obtain coefficients ai from the exponent's binary form.
    // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2"
    for ( unsigned int i=n; i>0; i>>=1 )
    {
        // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0)
        // Note: "i&1" is a bitwise equivalent of "i%2"
        if ( 0!=(i & static_cast<unsigned int>(1) ) )
        {
            retVal *= factor;
        }

        factor *= factor;
    }

    return retVal;
}
<commit_msg>Lib suggested values for default EPS<commit_after>/*
Copyright 2011, Jernej Kovacic

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * @file NumericUtil.cpp
 *
 * Implementation  of the class NumericUtil, a collection of some useful
 * numerical utilities. This is a templated class and must not be compiled.
 * Instead it must be included after the class declaration in the .h file
 *
 * @author Jernej Kovacic
 */

// Deliberately there is no #include "NumericUtil.h"
#include "Rational.h"
#include "SqMatrixGeneric.h"
#include "PolynomialGeneric.h"

#include <complex>
#include <limits>

// Note that the optimal EPS depends on application's requirements

// For float, double and long double, a suggested value for EPS can be
// obtained by std::numeric_limits<type>::epsilon().
#define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \
template<> \
FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon();
// end of #define

// definition of EPS for float:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(float)

// double is a more accurate type:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(double)

// ... and long double is even more accurate:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_EPS

/*
 * For int and other types, EPS doesn't make sense, so set it to 0
 */
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);

/**
 * A constant value with the T's representation of zero (0)
 */
template<class T>
const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) );

/**
 * A constant value with the T's representation of one (1)
 */
template<class T>
const T math::NumericUtil<T>::ONE ( static_cast<T>(1) );

/**
 * Does the given value equal (or is close enough to) zero?
 * Implementation depends on the type T.
 * For floating point types (float, double, long double), it checks
 * whether its absolute value is less than a hardcoded constant 'eps'.
 *
 * @param value
 *
 * @return true or false
 */
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
    /*
     * The implementation for integers et al. where the == operator
     * does make sense and no comparison to EPS is necessary.
     */
    bool retVal = ( ZERO==value ? true : false );

    return retVal;
}

/*
 * Float, double and long double require specialized implementations of isZero().
 * In case of these three types, the equality operator (==) is useless.
 * In numerical mathematics, two numbers are considered "equal", when
 * absolute value of their difference does not exceed a reasonably set EPS.
 * All specializations are very similar and only differ in types of an input value.
 * For easier maintainability, the specialization will be implemented
 * only once using a parameterized #define
 */

#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \
template<> \
bool math::NumericUtil<FDL>::isZero(const FDL& value) \
{ \
    bool retVal = false; \
    retVal = ( value>-EPS && value<EPS ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO

/*
 * Specialization for complex.
 * As complex is a templated class, again it must be implemented for each supported subtemplated
 * type. To facilitate this, a parameterized macro is introduced.
 * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare
 * it with EPS^2 than calculating its square root (the actual definition of complex abs. value).
 */
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \
template<> \
bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \
{ \
    bool retVal = false; \
    const FDL eps = math::NumericUtil<FDL>::getEPS(); \
    retVal = ( std::norm(value)<=eps*eps ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX
/*
 * Implementation for Rational
 */
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
    // Rational already contains its own isZero()...
    return value.isZero();
}

/**
 * @return value of 'eps' for the desired type
 */
template<class T>
T math::NumericUtil<T>::getEPS()
{
    return EPS;
}

/**
 * Sets the new value of 'eps' for the desired type if the default one does
 * not meet application's requirements.
 *
 * @note There is no check of input so make sure a sensible value
 *       (typically a very small positive number) is entered.
 *
 * @param eps - new value of EPS
 */
template<class T>
void math::NumericUtil<T>::setEPS(const T& eps)
{
    EPS = eps;
}

/*
 * In C++, it is not possible to specialize a function of a templated class
 * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>).
 * However it is possible if a single function is templated.
 * For more details, see the discussion at:
 * http://www.cplusplus.com/forum/general/68298/
 *
 * At the moment, getUnit() is only used by power(). Until it is changed,
 * getUnit() will be defined in this file as a templated standalone function.
 * Additionlly, implementations of the function are "hidden" in the namespace
 * math::getunit which is not supposed to be known to other members of math::
 */
namespace math
{
    namespace getunit
    {
        /*
         * @param t - an arbitrary instance of T, ignored by the generic implementation,
         *            at specializations it might be useful to determine unit's dimensions etc.
         *
         * @return an instance of T acting as a multiplication unit
         */
        template<class T>
        T getUnit(const T& t)
        {
            return T(math::NumericUtil<T>::ONE);
        }

        /*
         * Specialization for generic class math::SqMatrixGeneric<T>
         *
         * @param t - an arbitrary instance of a square matrix to determine
         *            dimensions of the returned unit matrix
         *
         * @return a unit nxn square matrix where n is a dimension of 't'
         */
        template<class T>
        math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t)
        {
            const unsigned int N = t.nrRows();
            math::SqMatrixGeneric<T> retVal(N);
            retVal.setUnit();
            return retVal;
        }

        /*
         * Specialization for generic class math::PolynomialGeneric<T>
         *
         * @param t - ignored
         *
         * @return a unit polynomial p(x) = (T)1
         */
        template<class T>
        math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t)
        {
            math::PolynomialGeneric<T> retVal(1);
            retVal.set(0, math::NumericUtil<T>::ONE);
            return retVal;
        }
    } // namespace units
} // namespace math

/**
 * Efficient calculation of positive integer power.
 * Complexity of the algorithm is O(log2 n).
 *
 * @note T must have implemented operator*=
 *
 * @param base - base of the exponentiation
 * @param n - exponent (a positive integer number)
 *
 * @return base^n
 */
template<class T>
T math::NumericUtil<T>::power(const T& base, unsigned int n)
{
    /*
     * "Exponentiation by squaring" algorithm will be applied.
     *
     * Exponentiation can be expanded into:
     *        n    n%2       n/2
     *       a  = a   * (a^2)
     *
     * where / and % are integer division and remainder operators.
     *
     * The expression above can be further recursively derived to:
     *  n    n%2    (n/2)%2     (n/2)/2
     * a  = a   (a^2)       (a^4)       =
     *
     *       n%2    (n/2)%2    (n/4)%2    ((n/2)/2)/2
     *    = a   (a^2)      (a^4)      (a^8)           = ....
     *
     * It is simple to develop an iterative algorithm where factor
     * is iteratively increased by squaring itself and coefficients
     * ai (i=0..n) are iteratively calculated by the remainder of
     * division by 2
     */

    // Note: it is safe to use bitwise operators for arithmetic operations
    // on unsigned int values as they do not depend on endianess:
    // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness

    T retVal = math::getunit::getUnit(base);
    T factor = base;

    // Obtain coefficients ai from the exponent's binary form.
    // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2"
    for ( unsigned int i=n; i>0; i>>=1 )
    {
        // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0)
        // Note: "i&1" is a bitwise equivalent of "i%2"
        if ( 0!=(i & static_cast<unsigned int>(1) ) )
        {
            retVal *= factor;
        }

        factor *= factor;
    }

    return retVal;
}
<|endoftext|>


<commit_before>#include <Vertica.h>
using Vertica::TransformFunction;
using Vertica::TransformFunctionFactory;

extern "C" {
#include <json/selector.h>
#include <json/slice.h>
}
#include "JsonCopyResult.hpp"

template<class D>
class AbstractJsonArrayUnnest : public TransformFunction {
public:

	virtual void processPartition(Vertica::ServerInterface &,
	                              Vertica::PartitionReader &argReader,
	                              Vertica::PartitionWriter &resWriter)
	{
		do {
			const Vertica::VString &jsonSrc = argReader.getStringRef(0);
			if (jsonSrc.isNull()) {
				continue;
			}

			json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length());
			json_slice_t jsonOut;
			json_array_iter_t iter;
			if (json_array_iter_init(&iter, &jsonIn) != JSON_ARRAY_ITER_OK) {
				continue;
			}

			for (;;) {
				json_array_iter_result_t result;
				result = json_array_iter_next(&iter, &jsonOut);
				if (result == JSON_ARRAY_ITER_OK) {
					D::copyResult(jsonOut, resWriter.getStringRef(0));
					resWriter.next();
				} else {
					break;
				}
			}
		} while (argReader.next());
	}
};

class JsonArrayUnnest :
	public JsonValueResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnest> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnest";
	}
};

class JsonArrayUnnestStrings :
	public JsonStringResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnestStrings> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnestStrings";
	}
};

class JsonArrayUnnestUnquoted :
	public JsonUnquotedResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnestUnquoted> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnestUnquoted";
	}
};

template<class T>
class AbstractJsonArrayUnnestFactory : public TransformFunctionFactory {
public:

	virtual void getPrototype(Vertica::ServerInterface &,
	                          Vertica::ColumnTypes &argTypes,
	                          Vertica::ColumnTypes &resTypes)
	{
		argTypes.addVarchar();
		resTypes.addVarchar();
	}

	virtual void getReturnType(Vertica::ServerInterface &,
	                           const Vertica::SizedColumnTypes &argTypes,
	                           Vertica::SizedColumnTypes &resTypes)
	{
		const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0);
		resTypes.addVarchar(jsonSrcType.getStringLength(), T::resultColumnName());
	}

	virtual TransformFunction *createTransformFunction(Vertica::ServerInterface &iface)
	{
		return vt_createFuncObj(iface.allocator, T);
	}

	virtual void getPerInstanceResources(Vertica::ServerInterface &,
	                                     Vertica::VResources &resources)
	{
		resources.nFileHandles = 0;
		resources.scratchMemory = 0;
	}
};

class JsonArrayUnnestFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnest> {
};

class JsonArrayUnnestStringsFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnestStrings> {
};

class JsonArrayUnnestUnquotedFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnestUnquoted> {
};

RegisterFactory(JsonArrayUnnestFactory);
RegisterFactory(JsonArrayUnnestStringsFactory);
RegisterFactory(JsonArrayUnnestUnquotedFactory);
<commit_msg>Get rid of trailing whitespace.<commit_after>#include <Vertica.h>
using Vertica::TransformFunction;
using Vertica::TransformFunctionFactory;

extern "C" {
#include <json/selector.h>
#include <json/slice.h>
}
#include "JsonCopyResult.hpp"

template<class D>
class AbstractJsonArrayUnnest : public TransformFunction {
public:

	virtual void processPartition(Vertica::ServerInterface &,
	                              Vertica::PartitionReader &argReader,
	                              Vertica::PartitionWriter &resWriter)
	{
		do {
			const Vertica::VString &jsonSrc = argReader.getStringRef(0);
			if (jsonSrc.isNull()) {
				continue;
			}

			json_slice_t jsonIn = json_slice_new(jsonSrc.data(), jsonSrc.length());
			json_slice_t jsonOut;
			json_array_iter_t iter;
			if (json_array_iter_init(&iter, &jsonIn) != JSON_ARRAY_ITER_OK) {
				continue;
			}

			for (;;) {
				json_array_iter_result_t result;
				result = json_array_iter_next(&iter, &jsonOut);
				if (result == JSON_ARRAY_ITER_OK) {
					D::copyResult(jsonOut, resWriter.getStringRef(0));
					resWriter.next();
				} else {
					break;
				}
			}
		} while (argReader.next());
	}
};

class JsonArrayUnnest :
	public JsonValueResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnest> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnest";
	}
};

class JsonArrayUnnestStrings :
	public JsonStringResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnestStrings> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnestStrings";
	}
};

class JsonArrayUnnestUnquoted :
	public JsonUnquotedResult,
	public AbstractJsonArrayUnnest<JsonArrayUnnestUnquoted> {
public:

	static const char *resultColumnName()
	{
		return "JsonArrayUnnestUnquoted";
	}
};

template<class T>
class AbstractJsonArrayUnnestFactory : public TransformFunctionFactory {
public:

	virtual void getPrototype(Vertica::ServerInterface &,
	                          Vertica::ColumnTypes &argTypes,
	                          Vertica::ColumnTypes &resTypes)
	{
		argTypes.addVarchar();
		resTypes.addVarchar();
	}

	virtual void getReturnType(Vertica::ServerInterface &,
	                           const Vertica::SizedColumnTypes &argTypes,
	                           Vertica::SizedColumnTypes &resTypes)
	{
		const Vertica::VerticaType &jsonSrcType = argTypes.getColumnType(0);
		resTypes.addVarchar(jsonSrcType.getStringLength(), T::resultColumnName());
	}

	virtual TransformFunction *createTransformFunction(Vertica::ServerInterface &iface)
	{
		return vt_createFuncObj(iface.allocator, T);
	}

	virtual void getPerInstanceResources(Vertica::ServerInterface &,
	                                     Vertica::VResources &resources)
	{
		resources.nFileHandles = 0;
		resources.scratchMemory = 0;
	}
};

class JsonArrayUnnestFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnest> {
};

class JsonArrayUnnestStringsFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnestStrings> {
};

class JsonArrayUnnestUnquotedFactory :
	public AbstractJsonArrayUnnestFactory<JsonArrayUnnestUnquoted> {
};

RegisterFactory(JsonArrayUnnestFactory);
RegisterFactory(JsonArrayUnnestStringsFactory);
RegisterFactory(JsonArrayUnnestUnquotedFactory);
<|endoftext|>