<commit_before>#include "Game.h"

Game::Game()
{
    //Set default variables
    width = 800;
    height = 600;
    vsync = false;
    fullscreen = false;
    fog = true;
    mazeSize = 40;

    //Try to load configuration
    loadConfig();

    //If user set wrong size, correct it
    if(mazeSize > MAZE_MAXSIZE)
        mazeSize = MAZE_MAXSIZE;

    if(mazeSize < MAZE_MINSIZE)
        mazeSize = MAZE_MINSIZE;

    cout << "\nStarting mode " << width << "x" << height << ", vsync=" << vsync << ", fullscreen=" << fullscreen << ", maze size=" << mazeSize << ", fog=" << fog << endl;
}

void Game::loadConfig()
{
    vector <std::string> options;
    std::string option, value;
    bool isOption = true;

    ifstream fin("config.cfg");

    if(!fin.is_open())
    {
        cout << "Failed to load config file. Setting default variables." << endl;
        return;
    }

    while(!fin.eof())
    {
        std::string tmp;
        fin >> tmp;
        options.push_back(tmp);
    }

    fin.close();

    for(unsigned int i = 0; i < options.size(); i++)
    {
        for(unsigned int j = 0; j < options[i].size(); j++)
        {
            //'=' catched, so now we picking value, not option
            if(options[i][j] == '=')
            {
                isOption = false;
                continue;
            }

            if(isOption)
                option += options[i][j];

            if(!isOption)
                value += options[i][j];
        }

        //Save game options
        if(option.compare("width") == 0)
            width = atoi(value.c_str());

        if(option.compare("height") == 0)
            height = atoi(value.c_str());

        if(option.compare("mazeSize") == 0)
            mazeSize = atoi(value.c_str());

        if(option.compare("vsync") == 0)
        {
            if(value.compare("true") == 0)
                vsync = true;
            else if (value.compare("false") == 0)
                vsync = false;
        }

        if(option.compare("fullscreen") == 0)
        {
            if(value.compare("true") == 0)
                fullscreen = true;
            else if (value.compare("false") == 0)
                fullscreen = false;
        }

        if(option.compare("fog") == 0)
        {
            if(value.compare("true") == 0)
                fog = true;
            else if (value.compare("false") == 0)
                fog = false;
        }

        //Clear variables to use it in next loop step
        option="";
        value="";
        isOption = true;
    }
}

void Game::startGame()
{
    //Create Irrlicht device and get pointer to driver and scene manager
    device = createDevice(EDT_OPENGL, dimension2d<u32>(width, height), 32, fullscreen, false, vsync, 0);

    srand(time(0));

    driver = device->getVideoDriver();
    scenemgr = device->getSceneManager();

    device->setWindowCaption(L"3D Maze");

    //Create map
    Map map(mazeSize);
    map.createMap(driver, scenemgr);

    IMeshSceneNode *mapNode = scenemgr->addMeshSceneNode(map.getMapMesh());
    mapNode->setMaterialFlag(EMF_LIGHTING, true);
    mapNode->getMaterial(0).FogEnable = false;

    ICameraSceneNode *camera = scenemgr->addCameraSceneNodeFPS();
    camera->setTarget(vector3df(90,4,45));
    camera->setFarValue(1000);
    device->getCursorControl()->setVisible(false);

    scenemgr->setAmbientLight(SColorf(1, 1, 1, 255));

    //Main loop
    while(device->run())
    {
        if(device->isWindowActive())
        {
            driver->beginScene(true, true, SColor(255,0,0,0));

            scenemgr->drawAll();

            driver->endScene();
        }
        else
            device->yield();
    }

    device->drop();
}

<commit_msg>Add fog<commit_after>#include "Game.h"

Game::Game()
{
    //Set default variables
    width = 800;
    height = 600;
    vsync = false;
    fullscreen = false;
    fog = false;
    mazeSize = 40;

    //Try to load configuration
    loadConfig();

    //If user set wrong size, correct it
    if(mazeSize > MAZE_MAXSIZE)
        mazeSize = MAZE_MAXSIZE;

    if(mazeSize < MAZE_MINSIZE)
        mazeSize = MAZE_MINSIZE;

    cout << "\nStarting mode " << width << "x" << height << ", vsync=" << vsync << ", fullscreen=" << fullscreen << ", maze size=" << mazeSize << ", fog=" << fog << endl;
}

void Game::loadConfig()
{
    vector <std::string> options;
    std::string option, value;
    bool isOption = true;

    ifstream fin("config.cfg");

    if(!fin.is_open())
    {
        cout << "Failed to load config file. Setting default variables." << endl;
        return;
    }

    while(!fin.eof())
    {
        std::string tmp;
        fin >> tmp;
        options.push_back(tmp);
    }

    fin.close();

    for(unsigned int i = 0; i < options.size(); i++)
    {
        for(unsigned int j = 0; j < options[i].size(); j++)
        {
            //'=' catched, so now we picking value, not option
            if(options[i][j] == '=')
            {
                isOption = false;
                continue;
            }

            if(isOption)
                option += options[i][j];

            if(!isOption)
                value += options[i][j];
        }

        //Save game options
        if(option.compare("width") == 0)
            width = atoi(value.c_str());

        if(option.compare("height") == 0)
            height = atoi(value.c_str());

        if(option.compare("mazeSize") == 0)
            mazeSize = atoi(value.c_str());

        if(option.compare("vsync") == 0)
        {
            if(value.compare("true") == 0)
                vsync = true;
            else if (value.compare("false") == 0)
                vsync = false;
        }

        if(option.compare("fullscreen") == 0)
        {
            if(value.compare("true") == 0)
                fullscreen = true;
            else if (value.compare("false") == 0)
                fullscreen = false;
        }

        if(option.compare("fog") == 0)
        {
            if(value.compare("true") == 0)
                fog = true;
            else if (value.compare("false") == 0)
                fog = false;
        }

        //Clear variables to use it in next loop step
        option="";
        value="";
        isOption = true;
    }
}

void Game::startGame()
{
    //Create Irrlicht device and get pointer to driver and scene manager
    device = createDevice(EDT_OPENGL, dimension2d<u32>(width, height), 32, fullscreen, false, vsync, 0);

    srand(time(0));

    driver = device->getVideoDriver();
    scenemgr = device->getSceneManager();

    device->setWindowCaption(L"3D Maze");

    //Create map
    Map map(mazeSize);
    map.createMap(driver, scenemgr);

    IMeshSceneNode *mapNode = scenemgr->addMeshSceneNode(map.getMapMesh());
    mapNode->setMaterialFlag(EMF_LIGHTING, true);

    if(!fog)
        mapNode->getMaterial(0).FogEnable = false;
    else
        mapNode->getMaterial(0).FogEnable = true;

    ICameraSceneNode *camera = scenemgr->addCameraSceneNodeFPS();
    camera->setTarget(vector3df(90,4,45));
    camera->setFarValue(1000);
    device->getCursorControl()->setVisible(false);

    scenemgr->setAmbientLight(SColorf(1, 1, 1, 255));

    //Enable fog when it is set in configuration
    if(fog)
        driver->setFog(SColor(0, 0, 0, 0), EFT_FOG_EXP2, 5, 100, 0.017, false, true);

    //Main loop
    while(device->run())
    {
        if(device->isWindowActive())
        {
            driver->beginScene(true, true, SColor(255,0,0,0));

            scenemgr->drawAll();

            driver->endScene();
        }
        else
            device->yield();
    }

    device->drop();
}

<|endoftext|>


<commit_before>#ifdef HAVE_PYTHON

#include "../script.h"
#include "python.h"
#include <string>
#include "../globals.h"
#include "../util/funcs.h"
#include <sstream>

#include <Python.h>

using namespace std;

PythonEngine::PythonEngine(const string & path):
Script::Engine(),
path(path){
    Global::debug(1) << "Loading python.." << endl;
    Py_Initialize();
    Global::debug(1) << "Load module " << path << endl;
    ostringstream python_string;
    python_string << "x = \"" << (Util::getDataPath() + path) << "\"; import sys; sys.path.append(x[0:x.rfind('/')])";
    Global::debug(1) << "Executing '" << python_string.str() << "'" << endl;
    Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl;
    int from = path.rfind("/")+1;
    int to = path.rfind(".");
    string module = path.substr(from, to - from);
    Global::debug(1) << "Loading module " << module << endl;
    PyObject * python_module = PyImport_ImportModule(module.c_str());
    Global::debug(1) << "Loaded " << python_module << endl;
    if (python_module == NULL){
        PyErr_Print();
    }
}

void PythonEngine::init(){
}

void PythonEngine::shutdown(){
}

PythonEngine::~PythonEngine(){
    Py_Finalize();
}

#endif
<commit_msg>add todo<commit_after>#ifdef HAVE_PYTHON

#include "../script.h"
#include "python.h"
#include <string>
#include "../globals.h"
#include "../util/funcs.h"
#include <sstream>

#include <Python.h>

using namespace std;

PythonEngine::PythonEngine(const string & path):
Script::Engine(),
path(path){
    Global::debug(1) << "Loading python.." << endl;
    Py_Initialize();
    Global::debug(1) << "Load module " << path << endl;

    /* TODO: Use PySys_GetObject() to get sys.path and then use
     * PyString_FromStringAndSize() and PyList_Append()
     */
    ostringstream python_string;
    python_string << "x = \"" << (Util::getDataPath() + path) << "\"; import sys; sys.path.append(x[0:x.rfind('/')])";
    Global::debug(1) << "Executing '" << python_string.str() << "'" << endl;
    Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl;
    int from = path.rfind("/")+1;
    int to = path.rfind(".");
    string module = path.substr(from, to - from);
    Global::debug(1) << "Loading module " << module << endl;
    PyObject * python_module = PyImport_ImportModule(module.c_str());
    Global::debug(1) << "Loaded " << python_module << endl;
    if (python_module == NULL){
        PyErr_Print();
    }
}

void PythonEngine::init(){
}

void PythonEngine::shutdown(){
}

PythonEngine::~PythonEngine(){
    Py_Finalize();
}

#endif
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMLBER_LOCAL_HH
#define DUNE_GDT_ASSEMLBER_LOCAL_HH

#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker/apply-on.hh>
#include <dune/stuff/grid/walker/wrapper.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/localoperator/interfaces.hh>
#include <dune/gdt/localfunctional/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class LocalVolumeTwoFormType>
class LocalVolumeTwoFormAssembler
{
  static_assert(is_local_volume_twoform<LocalVolumeTwoFormType>::value,
                "LocalVolumeTwoFormType has to be derived from LocalVolumeTwoFormInterface!");

public:
  explicit LocalVolumeTwoFormAssembler(const LocalVolumeTwoFormType& local_twoform)
    : local_volume_twoform_(local_twoform)
  {
  }

  /**
   *  \tparam T           Traits of the SpaceInterface implementation, representing the type of test_space
   *  \tparam A           Traits of the SpaceInterface implementation, representing the type of ansatz_space
   *  \tparam *d          dimDomain of test_space (* == T) or ansatz_space (* == A)
   *  \tparam *r          dimRange of test_space (* == T) or ansatz_space (* == A)
   *  \tparam *rC         dimRangeCols of test_space (* == T) or ansatz_space (* == A)
   *  \tparam EntityType  A model of Dune::Entity< 0 >
   *  \tparam M           Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the
   * type of global_matrix
   *  \tparam R           RangeFieldType, i.e. double
   */
  template <class T, size_t Td, size_t Tr, size_t TrC, class A, size_t Ad, size_t Ar, size_t ArC, class EntityType,
            class M, class R>
  void assemble(const SpaceInterface<T, Td, Tr, TrC>& test_space, const SpaceInterface<A, Ad, Ar, ArC>& ansatz_space,
                const EntityType& entity, Stuff::LA::MatrixInterface<M, R>& global_matrix) const
  {
    // prepare
    const size_t rows = test_space.mapper().numDofs(entity);
    const size_t cols = ansatz_space.mapper().numDofs(entity);
    Dune::DynamicMatrix<R> local_matrix(rows, cols, 0.); // \todo: make mutable member, after SMP refactor
    // apply local two-form
    const auto test_base   = test_space.base_function_set(entity);
    const auto ansatz_base = ansatz_space.base_function_set(entity);
    assert(test_base.size() == rows);
    assert(ansatz_base.size() == cols);
    local_volume_twoform_.apply2(test_base, ansatz_base, local_matrix);
    // write local matrix to global
    const auto global_row_indices =
        test_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    const auto global_col_indices =
        ansatz_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    assert(global_row_indices.size() == rows);
    assert(global_col_indices.size() == cols);
    for (size_t ii = 0; ii < rows; ++ii) {
      const auto& local_matrix_row = local_matrix[ii];
      const size_t global_ii = global_row_indices[ii];
      for (size_t jj = 0; jj < cols; ++jj) {
        const size_t global_jj = global_col_indices[jj];
        global_matrix.add_to_entry(global_ii, global_jj, local_matrix_row[jj]);
      }
    } // write local matrix to global
  } // ... assemble(...)

private:
  const LocalVolumeTwoFormType& local_volume_twoform_;
}; // class LocalVolumeTwoFormAssembler

template <class GridViewImp, class LocalVolumeTwoFormType, class TestFunctionType, class AnsatzFunctionType,
          class FieldType>
class LocalVolumeTwoFormAccumulator : public Stuff::Grid::internal::Codim0ReturnObject<GridViewImp, FieldType>
{
  static_assert(std::is_base_of<LocalVolumeTwoFormInterface<typename LocalVolumeTwoFormType::Traits>,
                                LocalVolumeTwoFormType>::value,
                "LocalVolumeTwoFormType has to be derived from LocalVolumeTwoFormInterface!");
  static_assert(Stuff::is_localizable_function<TestFunctionType>::value,
                "TestFunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(Stuff::is_localizable_function<AnsatzFunctionType>::value,
                "AnsatzFunctionType has to be derived from Stuff::LocalizableFunctionInterface!");

  typedef LocalVolumeTwoFormAccumulator<GridViewImp, LocalVolumeTwoFormType, TestFunctionType, AnsatzFunctionType,
                                        FieldType> ThisType;
  typedef Stuff::Grid::internal::Codim0ReturnObject<GridViewImp, FieldType> BaseType;

public:
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::EntityType EntityType;

  LocalVolumeTwoFormAccumulator(const GridViewType& grd_vw, const LocalVolumeTwoFormType& local_op,
                                const TestFunctionType& test_function, const AnsatzFunctionType& ansatz_function,
                                const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where)
    : grid_view_(grd_vw)
    , local_operator_(local_op)
    , test_function_(test_function)
    , ansatz_function_(ansatz_function)
    , result_(0)
    , finalized_(false)
    , where_(where)
  {
  }

  LocalVolumeTwoFormAccumulator(const ThisType& other) = default;
  virtual ~LocalVolumeTwoFormAccumulator() = default;

  virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const override final
  {
    return where_.apply_on(grid_view, entity);
  }

  virtual FieldType compute_locally(const EntityType& entity) override final
  {
    DynamicMatrix<FieldType> local_twoform_result(1, 1, 0.); // \todo: make mutable member, after SMP refactor
    this->local_operator_.apply2(
        *test_function_.local_function(entity), *ansatz_function_.local_function(entity), local_twoform_result);
    return local_twoform_result[0][0];
  } // ... compute_locally(...)

  virtual void apply_local(const EntityType& entity) override
  {
    *result_ += compute_locally(entity);
  }

  virtual void finalize() override
  {
    if (!finalized_) {
      finalized_result_ = result_.sum();
      finalized_result_ = grid_view_.comm().sum(finalized_result_);
      finalized_        = true;
    }
  } // ... finalize(...)

  virtual FieldType result() const override final
  {
    if (!finalized_)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Call finalize() first!");
    return finalized_result_;
  }

private:
  const GridViewType& grid_view_;
  const LocalVolumeTwoFormType& local_operator_;
  const TestFunctionType& test_function_;
  const AnsatzFunctionType& ansatz_function_;
  DS::PerThreadValue<FieldType> result_;
  bool finalized_;
  const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where_;
  FieldType finalized_result_;
}; // class LocalVolumeTwoFormAccumulator

template <class GridViewType, class LocalOperatorType, class SourceType, class RangeType>
class LocalOperatorApplicator : public Stuff::Grid::internal::Codim0Object<GridViewType>
{
  static_assert(is_local_operator<LocalOperatorType>::value,
                "LocalOperatorType has to be derived from LocalOperatorInterface!");
  static_assert(Stuff::is_localizable_function<SourceType>::value,
                "SourceType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_discrete_function<RangeType>::value, "RangeType has to be a DiscreteFunctionDefault!");
  typedef Stuff::Grid::internal::Codim0Object<GridViewType> BaseType;

public:
  using typename BaseType::EntityType;

  LocalOperatorApplicator(const GridViewType& grid_view, const LocalOperatorType& local_operator,
                          const SourceType& source, RangeType& range,
                          const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where)
    : grid_view_(grid_view)
    , local_operator_(local_operator)
    , source_(source)
    , range_(range)
    , where_(where)
  {
  }

  virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
  {
    return where_.apply_on(grid_view, entity);
  }

  virtual void apply_local(const EntityType& entity)
  {
    local_operator_.apply(source_, *range_.local_discrete_function(entity));
  }

private:
  const GridViewType& grid_view_;
  const LocalOperatorType& local_operator_;
  const SourceType& source_;
  RangeType& range_;
  const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where_;
}; // class LocalOperatorApplicator

template <class LocalVolumeFunctionalType>
class LocalVolumeFunctionalAssembler
{
  static_assert(is_local_volume_functional<LocalVolumeFunctionalType>::value,
                "LocalVolumeFunctionalType has to be derived from LocalVolumeFunctionalInterface!");

public:
  explicit LocalVolumeFunctionalAssembler(const LocalVolumeFunctionalType& local_volume_functional)
    : local_volume_functional_(local_volume_functional)
  {
  }

  /**
   *  \tparam S          Traits of the SpaceInterface implementation, representing the type of test_space
   *  \tparam d          dimDomain of test_space
   *  \tparam r          dimRange of test_space
   *  \tparam rC         dimRangeCols of test_space
   *  \tparam EntityType A model of Dune::Entity< 0 >
   *  \tparam V          Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the type
   * of global_vector
   *  \tparam R          RangeFieldType, i.e. double
   */
  template <class S, size_t d, size_t r, size_t rC, class EntityType, class V, class R>
  void assemble(const SpaceInterface<S, d, r, rC>& test_space, const EntityType& entity,
                Stuff::LA::VectorInterface<V, R>& global_vector) const
  {
    // prepare
    const size_t size = test_space.mapper().numDofs(entity);
    Dune::DynamicVector<R> local_vector(size, 0.); // \todo: make mutable member, after SMP refactor
    // apply local functional
    const auto test_basis = test_space.base_function_set(entity);
    assert(test_basis.size() == size);
    local_volume_functional_.apply(test_basis, local_vector);
    // write local vector to global
    const auto global_indices =
        test_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    assert(global_indices.size() == size);
    for (size_t jj = 0; jj < size; ++jj)
      global_vector.add_to_entry(global_indices[jj], local_vector[jj]);
  } // ... assemble(...)

private:
  const LocalVolumeFunctionalType& local_volume_functional_;
}; // class LocalVolumeFunctionalAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMLBER_LOCAL_HH
<commit_msg>[assembler.local] add LocalFaceFunctionalAssembler<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMLBER_LOCAL_HH
#define DUNE_GDT_ASSEMLBER_LOCAL_HH

#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker/apply-on.hh>
#include <dune/stuff/grid/walker/wrapper.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/localoperator/interfaces.hh>
#include <dune/gdt/localfunctional/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class LocalVolumeTwoFormType>
class LocalVolumeTwoFormAssembler
{
  static_assert(is_local_volume_twoform<LocalVolumeTwoFormType>::value,
                "LocalVolumeTwoFormType has to be derived from LocalVolumeTwoFormInterface!");

public:
  explicit LocalVolumeTwoFormAssembler(const LocalVolumeTwoFormType& local_twoform)
    : local_volume_twoform_(local_twoform)
  {
  }

  /**
   *  \tparam T           Traits of the SpaceInterface implementation, representing the type of test_space
   *  \tparam A           Traits of the SpaceInterface implementation, representing the type of ansatz_space
   *  \tparam *d          dimDomain of test_space (* == T) or ansatz_space (* == A)
   *  \tparam *r          dimRange of test_space (* == T) or ansatz_space (* == A)
   *  \tparam *rC         dimRangeCols of test_space (* == T) or ansatz_space (* == A)
   *  \tparam EntityType  A model of Dune::Entity< 0 >
   *  \tparam M           Traits of the Dune::Stuff::LA::Container::MatrixInterface implementation, representing the
   * type of global_matrix
   *  \tparam R           RangeFieldType, i.e. double
   */
  template <class T, size_t Td, size_t Tr, size_t TrC, class A, size_t Ad, size_t Ar, size_t ArC, class EntityType,
            class M, class R>
  void assemble(const SpaceInterface<T, Td, Tr, TrC>& test_space, const SpaceInterface<A, Ad, Ar, ArC>& ansatz_space,
                const EntityType& entity, Stuff::LA::MatrixInterface<M, R>& global_matrix) const
  {
    // prepare
    const size_t rows = test_space.mapper().numDofs(entity);
    const size_t cols = ansatz_space.mapper().numDofs(entity);
    Dune::DynamicMatrix<R> local_matrix(rows, cols, 0.); // \todo: make mutable member, after SMP refactor
    // apply local two-form
    const auto test_base   = test_space.base_function_set(entity);
    const auto ansatz_base = ansatz_space.base_function_set(entity);
    assert(test_base.size() == rows);
    assert(ansatz_base.size() == cols);
    local_volume_twoform_.apply2(test_base, ansatz_base, local_matrix);
    // write local matrix to global
    const auto global_row_indices =
        test_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    const auto global_col_indices =
        ansatz_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    assert(global_row_indices.size() == rows);
    assert(global_col_indices.size() == cols);
    for (size_t ii = 0; ii < rows; ++ii) {
      const auto& local_matrix_row = local_matrix[ii];
      const size_t global_ii = global_row_indices[ii];
      for (size_t jj = 0; jj < cols; ++jj) {
        const size_t global_jj = global_col_indices[jj];
        global_matrix.add_to_entry(global_ii, global_jj, local_matrix_row[jj]);
      }
    } // write local matrix to global
  } // ... assemble(...)

private:
  const LocalVolumeTwoFormType& local_volume_twoform_;
}; // class LocalVolumeTwoFormAssembler

template <class GridViewImp, class LocalVolumeTwoFormType, class TestFunctionType, class AnsatzFunctionType,
          class FieldType>
class LocalVolumeTwoFormAccumulator : public Stuff::Grid::internal::Codim0ReturnObject<GridViewImp, FieldType>
{
  static_assert(std::is_base_of<LocalVolumeTwoFormInterface<typename LocalVolumeTwoFormType::Traits>,
                                LocalVolumeTwoFormType>::value,
                "LocalVolumeTwoFormType has to be derived from LocalVolumeTwoFormInterface!");
  static_assert(Stuff::is_localizable_function<TestFunctionType>::value,
                "TestFunctionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(Stuff::is_localizable_function<AnsatzFunctionType>::value,
                "AnsatzFunctionType has to be derived from Stuff::LocalizableFunctionInterface!");

  typedef LocalVolumeTwoFormAccumulator<GridViewImp, LocalVolumeTwoFormType, TestFunctionType, AnsatzFunctionType,
                                        FieldType> ThisType;
  typedef Stuff::Grid::internal::Codim0ReturnObject<GridViewImp, FieldType> BaseType;

public:
  typedef typename BaseType::GridViewType GridViewType;
  typedef typename BaseType::EntityType EntityType;

  LocalVolumeTwoFormAccumulator(const GridViewType& grd_vw, const LocalVolumeTwoFormType& local_op,
                                const TestFunctionType& test_function, const AnsatzFunctionType& ansatz_function,
                                const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where)
    : grid_view_(grd_vw)
    , local_operator_(local_op)
    , test_function_(test_function)
    , ansatz_function_(ansatz_function)
    , result_(0)
    , finalized_(false)
    , where_(where)
  {
  }

  LocalVolumeTwoFormAccumulator(const ThisType& other) = default;
  virtual ~LocalVolumeTwoFormAccumulator() = default;

  virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const override final
  {
    return where_.apply_on(grid_view, entity);
  }

  virtual FieldType compute_locally(const EntityType& entity) override final
  {
    DynamicMatrix<FieldType> local_twoform_result(1, 1, 0.); // \todo: make mutable member, after SMP refactor
    this->local_operator_.apply2(
        *test_function_.local_function(entity), *ansatz_function_.local_function(entity), local_twoform_result);
    return local_twoform_result[0][0];
  } // ... compute_locally(...)

  virtual void apply_local(const EntityType& entity) override
  {
    *result_ += compute_locally(entity);
  }

  virtual void finalize() override
  {
    if (!finalized_) {
      finalized_result_ = result_.sum();
      finalized_result_ = grid_view_.comm().sum(finalized_result_);
      finalized_        = true;
    }
  } // ... finalize(...)

  virtual FieldType result() const override final
  {
    if (!finalized_)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Call finalize() first!");
    return finalized_result_;
  }

private:
  const GridViewType& grid_view_;
  const LocalVolumeTwoFormType& local_operator_;
  const TestFunctionType& test_function_;
  const AnsatzFunctionType& ansatz_function_;
  DS::PerThreadValue<FieldType> result_;
  bool finalized_;
  const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where_;
  FieldType finalized_result_;
}; // class LocalVolumeTwoFormAccumulator

template <class GridViewType, class LocalOperatorType, class SourceType, class RangeType>
class LocalOperatorApplicator : public Stuff::Grid::internal::Codim0Object<GridViewType>
{
  static_assert(is_local_operator<LocalOperatorType>::value,
                "LocalOperatorType has to be derived from LocalOperatorInterface!");
  static_assert(Stuff::is_localizable_function<SourceType>::value,
                "SourceType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(is_discrete_function<RangeType>::value, "RangeType has to be a DiscreteFunctionDefault!");
  typedef Stuff::Grid::internal::Codim0Object<GridViewType> BaseType;

public:
  using typename BaseType::EntityType;

  LocalOperatorApplicator(const GridViewType& grid_view, const LocalOperatorType& local_operator,
                          const SourceType& source, RangeType& range,
                          const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where)
    : grid_view_(grid_view)
    , local_operator_(local_operator)
    , source_(source)
    , range_(range)
    , where_(where)
  {
  }

  virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
  {
    return where_.apply_on(grid_view, entity);
  }

  virtual void apply_local(const EntityType& entity)
  {
    local_operator_.apply(source_, *range_.local_discrete_function(entity));
  }

private:
  const GridViewType& grid_view_;
  const LocalOperatorType& local_operator_;
  const SourceType& source_;
  RangeType& range_;
  const Stuff::Grid::ApplyOn::WhichEntity<GridViewType>& where_;
}; // class LocalOperatorApplicator

template <class LocalVolumeFunctionalType>
class LocalVolumeFunctionalAssembler
{
  static_assert(is_local_volume_functional<LocalVolumeFunctionalType>::value,
                "LocalVolumeFunctionalType has to be derived from LocalVolumeFunctionalInterface!");

public:
  explicit LocalVolumeFunctionalAssembler(const LocalVolumeFunctionalType& local_volume_functional)
    : local_volume_functional_(local_volume_functional)
  {
  }

  /**
   *  \tparam S          Traits of the SpaceInterface implementation, representing the type of test_space
   *  \tparam d          dimDomain of test_space
   *  \tparam r          dimRange of test_space
   *  \tparam rC         dimRangeCols of test_space
   *  \tparam EntityType A model of Dune::Entity< 0 >
   *  \tparam V          Traits of the Dune::Stuff::LA::Container::VectorInterface implementation, representing the type
   * of global_vector
   *  \tparam R          RangeFieldType, i.e. double
   */
  template <class S, size_t d, size_t r, size_t rC, class EntityType, class V, class R>
  void assemble(const SpaceInterface<S, d, r, rC>& test_space, const EntityType& entity,
                Stuff::LA::VectorInterface<V, R>& global_vector) const
  {
    // prepare
    const size_t size = test_space.mapper().numDofs(entity);
    Dune::DynamicVector<R> local_vector(size, 0.); // \todo: make mutable member, after SMP refactor
    // apply local functional
    const auto test_basis = test_space.base_function_set(entity);
    assert(test_basis.size() == size);
    local_volume_functional_.apply(test_basis, local_vector);
    // write local vector to global
    const auto global_indices =
        test_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    assert(global_indices.size() == size);
    for (size_t jj = 0; jj < size; ++jj)
      global_vector.add_to_entry(global_indices[jj], local_vector[jj]);
  } // ... assemble(...)

private:
  const LocalVolumeFunctionalType& local_volume_functional_;
}; // class LocalVolumeFunctionalAssembler

template <class LocalFunctionalType>
class LocalFaceFunctionalAssembler
{
  static_assert(
      std::is_base_of<LocalFaceFunctionalInterface<typename LocalFunctionalType::Traits>, LocalFunctionalType>::value,
      "LocalFunctionalType has to be derived from LocalFaceFunctionalInterface!");

public:
  explicit LocalFaceFunctionalAssembler(const LocalFunctionalType& local_face_functional)
    : local_face_functional_(local_face_functional)
  {
  }

  template <class T, size_t d, size_t r, size_t rC, class IntersectionType, class V, class R>
  void assemble(const SpaceInterface<T, d, r, rC>& test_space, const IntersectionType& intersection,
                Stuff::LA::VectorInterface<V, R>& global_vector) const
  {
    // prepare
    const auto entity_ptr = intersection.inside();
    const auto& entity    = *entity_ptr;
    const size_t size = test_space.mapper().numDofs(entity);
    Dune::DynamicVector<R> local_vector(size, 0.); // \todo: make mutable member, after SMP refactor
    // apply local functional
    const auto test_basis = test_space.base_function_set(entity);
    assert(test_basis.size() == size);
    local_face_functional_.apply(test_basis, intersection, local_vector);
    // write local vector to global
    const auto global_indices =
        test_space.mapper().globalIndices(entity); // \todo: make mutable member, after SMP refactor
    assert(global_indices.size() == size);
    for (size_t jj = 0; jj < size; ++jj)
      global_vector.add_to_entry(global_indices[jj], local_vector[jj]);
  } // ... assemble(...)

private:
  const LocalFunctionalType& local_face_functional_;
}; // class LocalFaceFunctionalAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMLBER_LOCAL_HH
<|endoftext|>


<commit_before>#include "compiler.hh"
#include "parsers/assignmentparser.hh"
#include "parsers/constparser.hh"
#include "parsers/importparser.hh"
#include "parsers/methodparser.hh"
#include "parsers/methodcallparser.hh"
#include "parsers/namespacedefparser.hh"
#include "parsers/numberparser.hh"
#include "parsers/structparser.hh"
#include "parsers/typeidentparser.hh"

#include <iostream>

using namespace nolang;

Compiler::Compiler()
{
    parent = this;
}

Compiler::Compiler(Compiler *pt, mpc_ast_t *t, PureMethod *m, int l, bool p) :
    tree(t),
    method(m),
    level(l),
    parameters(p)
{
    Compiler *cp = pt;
    while (cp->parent != cp) {
        cp = cp->parent;
    }
    parent = cp;
    item = tree;
}

std::vector<Statement*> Compiler::appendStatement(std::vector<Statement*> rdata3, Statement *s)
{
    rdata3.push_back(s);
    return rdata3;
}

std::vector<Statement*> Compiler::appendBlock(std::vector<Statement*> rdata3)
{
    parent->m_blocks.push_back(rdata3);
    return std::vector<Statement*>();
}

std::vector<Statement*> Compiler::codegenRecurse(int lvl)
{
    std::vector<Statement*> rdata2;
    iterateTree(tree, [&] (mpc_ast_t *sub) {
        std::vector<Statement*> st = codegen(sub, method, lvl, parameters);
        for (auto s : st) {
            rdata2 = appendStatement(rdata2, s);
            if (isEOS(s)) rdata2 = appendBlock(rdata2);
        }
    });
    return rdata2;
}

void Compiler::parseMethodDef()
{
    PureMethod *new_method = MethodParser(this, item).parse();
    if (new_method == nullptr) throw "Invalid method!";
    parent->m_methods[new_method->name()] = new_method;
    recurse = false;
    level = 0;
}

void Compiler::parseStruct()
{
    parent->m_structs.push_back(StructParser(item).parse());
    recurse = false;
}

void Compiler::parseIndent()
{
    int new_level = std::string(item->contents).length();
    if (!method || new_level == level) return;
    if (parent->m_blocks.empty()) return;

    method->addBlock(parent->m_blocks);
    parent->m_blocks = std::vector<std::vector<Statement*>>();
}

void Compiler::parseMethodCall()
{
    rdata.push_back(MethodCallParser(this, item).parse());
    recurse = false;
}

void Compiler::parseAssignment()
{
    rdata.push_back(AssignmentParser(this, item, method).parse());
    recurse = false;
}

void Compiler::parseNumber()
{
    rdata.push_back(NumberParser(item).parse());
}

void Compiler::parseTermOp()
{
    rdata.push_back(new Op(item->contents));
}

void Compiler::parseFactorOp()
{
    rdata.push_back(new Op(item->contents));
}

void Compiler::parseString()
{
    rdata.push_back(new StringValue(item->contents));
}

void Compiler::parseTypeIdent()
{
    TypeIdent *ident = TypeIdentParser(item).parse();
    if (parameters) {
        rdata.push_back(ident);
    } else if (method != nullptr) {
        method->addVariable(ident);
    } else {
        rdata.push_back(ident);
    }
    recurse = false;
}

void Compiler::parseNamespace()
{
    std::string cnts = item->contents;
    NamespaceDef *def = NamespaceDefParser(item).parse();
    if (def != nullptr) rdata.push_back(def);
    else if (!cnts.empty()) rdata.push_back(new Identifier(cnts));
}

void Compiler::parseNamespaceDef()
{
    if (isBooleanDef()) rdata.push_back(new Boolean(item->contents));
    else parseNamespace();
    recurse = false;
}

void Compiler::parseIdentifier()
{
    std::string cnts = item->contents;
    // FIXME Some identifiers are special/reserved words
    if (cnts == "false" || cnts == "true") {
        rdata.push_back(new Boolean(cnts));
    } else {
        rdata.push_back(new Identifier(cnts));
    }
}

void Compiler::parseImport()
{
    parent->m_imports.push_back(ImportParser(item).parse());
    recurse = false;
}

void Compiler::parseConst()
{
    parent->m_consts.push_back(ConstParser(this, item).parse());
    recurse = false;
}

void Compiler::parseNewLine()
{
    rdata.push_back(new EOS());
}

void Compiler::parseComparator()
{
    rdata.push_back(new Comparator(item->contents));
}

void Compiler::parseBrace()
{
    rdata.push_back(new Braces(item->contents));
}

void Compiler::doRecurse()
{
    if (recurse) {
        Compiler g(parent, item, method, level, parameters);
        rdata = applyToVector<Statement*>(rdata, g.codegenRecurse(level));
    }
}

std::vector<Statement*> Compiler::gen()
{
    item = tree;
    std::string cnts = tree->contents;
    if (isRoot());
    else if (isComment()) recurse = false;
    else if (isMethodDef()) parseMethodDef();
    else if (isStruct()) parseStruct();
    else if (isIndent()) parseIndent();
    else if (isMethodCall()) parseMethodCall();
    else if (isAssignment()) parseAssignment();
    else if (isNumber()) parseNumber();
    else if (isTermOp()) parseTermOp();
    else if (isFactorOp()) parseFactorOp();
    else if (isString()) parseString();
    else if (isTypeIdent()) parseTypeIdent();
    else if (isNamespaceDef()) parseNamespaceDef();
    else if (isIdentifier()) parseIdentifier();
    else if (isImport()) parseImport();
    else if (isConst()) parseConst();
    else if (isNewLine()) parseNewLine();
    else if (isComparator()) parseComparator();
    else if (isBrace()) parseBrace();
    else if (isWhitespace());
    else printError("Unknown node in statement", tree);

    doRecurse();

    return rdata;
}

std::vector<Statement*> Compiler::codegen(mpc_ast_t *tree, PureMethod *m, int lvl, bool parameters)
{
    return Compiler(parent, tree, m, lvl, parameters).gen();
}
<commit_msg>Default recurse<commit_after>#include "compiler.hh"
#include "parsers/assignmentparser.hh"
#include "parsers/constparser.hh"
#include "parsers/importparser.hh"
#include "parsers/methodparser.hh"
#include "parsers/methodcallparser.hh"
#include "parsers/namespacedefparser.hh"
#include "parsers/numberparser.hh"
#include "parsers/structparser.hh"
#include "parsers/typeidentparser.hh"

#include <iostream>

using namespace nolang;

Compiler::Compiler()
{
    parent = this;
    recurse = true;
}

Compiler::Compiler(Compiler *pt, mpc_ast_t *t, PureMethod *m, int l, bool p) :
    tree(t),
    method(m),
    level(l),
    parameters(p)
{
    Compiler *cp = pt;
    while (cp->parent != cp) {
        cp = cp->parent;
    }
    parent = cp;
    item = tree;
    recurse = true;
}

std::vector<Statement*> Compiler::appendStatement(std::vector<Statement*> rdata3, Statement *s)
{
    rdata3.push_back(s);
    return rdata3;
}

std::vector<Statement*> Compiler::appendBlock(std::vector<Statement*> rdata3)
{
    parent->m_blocks.push_back(rdata3);
    return std::vector<Statement*>();
}

std::vector<Statement*> Compiler::codegenRecurse(int lvl)
{
    std::vector<Statement*> rdata2;
    iterateTree(tree, [&] (mpc_ast_t *sub) {
        std::vector<Statement*> st = codegen(sub, method, lvl, parameters);
        for (auto s : st) {
            rdata2 = appendStatement(rdata2, s);
            if (isEOS(s)) rdata2 = appendBlock(rdata2);
        }
    });
    return rdata2;
}

void Compiler::parseMethodDef()
{
    PureMethod *new_method = MethodParser(this, item).parse();
    if (new_method == nullptr) throw "Invalid method!";
    parent->m_methods[new_method->name()] = new_method;
    recurse = false;
    level = 0;
}

void Compiler::parseStruct()
{
    parent->m_structs.push_back(StructParser(item).parse());
    recurse = false;
}

void Compiler::parseIndent()
{
    int new_level = std::string(item->contents).length();
    if (!method || new_level == level) return;
    if (parent->m_blocks.empty()) return;

    method->addBlock(parent->m_blocks);
    parent->m_blocks = std::vector<std::vector<Statement*>>();
}

void Compiler::parseMethodCall()
{
    rdata.push_back(MethodCallParser(this, item).parse());
    recurse = false;
}

void Compiler::parseAssignment()
{
    rdata.push_back(AssignmentParser(this, item, method).parse());
    recurse = false;
}

void Compiler::parseNumber()
{
    rdata.push_back(NumberParser(item).parse());
}

void Compiler::parseTermOp()
{
    rdata.push_back(new Op(item->contents));
}

void Compiler::parseFactorOp()
{
    rdata.push_back(new Op(item->contents));
}

void Compiler::parseString()
{
    rdata.push_back(new StringValue(item->contents));
}

void Compiler::parseTypeIdent()
{
    TypeIdent *ident = TypeIdentParser(item).parse();
    if (parameters) {
        rdata.push_back(ident);
    } else if (method != nullptr) {
        method->addVariable(ident);
    } else {
        rdata.push_back(ident);
    }
    recurse = false;
}

void Compiler::parseNamespace()
{
    std::string cnts = item->contents;
    NamespaceDef *def = NamespaceDefParser(item).parse();
    if (def != nullptr) rdata.push_back(def);
    else if (!cnts.empty()) rdata.push_back(new Identifier(cnts));
}

void Compiler::parseNamespaceDef()
{
    if (isBooleanDef()) rdata.push_back(new Boolean(item->contents));
    else parseNamespace();
    recurse = false;
}

void Compiler::parseIdentifier()
{
    std::string cnts = item->contents;
    // FIXME Some identifiers are special/reserved words
    if (cnts == "false" || cnts == "true") {
        rdata.push_back(new Boolean(cnts));
    } else {
        rdata.push_back(new Identifier(cnts));
    }
}

void Compiler::parseImport()
{
    parent->m_imports.push_back(ImportParser(item).parse());
    recurse = false;
}

void Compiler::parseConst()
{
    parent->m_consts.push_back(ConstParser(this, item).parse());
    recurse = false;
}

void Compiler::parseNewLine()
{
    rdata.push_back(new EOS());
}

void Compiler::parseComparator()
{
    rdata.push_back(new Comparator(item->contents));
}

void Compiler::parseBrace()
{
    rdata.push_back(new Braces(item->contents));
}

void Compiler::doRecurse()
{
    if (recurse) {
        Compiler g(parent, item, method, level, parameters);
        rdata = applyToVector<Statement*>(rdata, g.codegenRecurse(level));
    }
}

std::vector<Statement*> Compiler::gen()
{
    item = tree;
    std::string cnts = tree->contents;
    if (isRoot());
    else if (isComment()) recurse = false;
    else if (isMethodDef()) parseMethodDef();
    else if (isStruct()) parseStruct();
    else if (isIndent()) parseIndent();
    else if (isMethodCall()) parseMethodCall();
    else if (isAssignment()) parseAssignment();
    else if (isNumber()) parseNumber();
    else if (isTermOp()) parseTermOp();
    else if (isFactorOp()) parseFactorOp();
    else if (isString()) parseString();
    else if (isTypeIdent()) parseTypeIdent();
    else if (isNamespaceDef()) parseNamespaceDef();
    else if (isIdentifier()) parseIdentifier();
    else if (isImport()) parseImport();
    else if (isConst()) parseConst();
    else if (isNewLine()) parseNewLine();
    else if (isComparator()) parseComparator();
    else if (isBrace()) parseBrace();
    else if (isWhitespace());
    else printError("Unknown node in statement", tree);

    doRecurse();

    return rdata;
}

std::vector<Statement*> Compiler::codegen(mpc_ast_t *tree, PureMethod *m, int lvl, bool parameters)
{
    return Compiler(parent, tree, m, lvl, parameters).gen();
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M グループ・ポート・マッピング @n
			・ペリフェラル型に従って、ポートの設定をグループ化
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX600/port.hpp"
#include "RX64M/mpc.hpp"
#include "RX64M/peripheral.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ポート・マッピング・ユーティリティー
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class port_map {

		static bool sub_(peripheral t, bool enable) {
			bool ret = true;
			switch(t) {
			// ※シリアルポートの MPC 設定では、PDR を制御する必要は無いが、
			// 出力ポートのインピーダンス制御の一環として入れてある。
			case peripheral::SCI0:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT2::PDR.B0 = enable; // TXD0
					PORT2::PDR.B1 = 0;  	// RXD0
					MPC::P20PFS.PSEL = sel;
					MPC::P21PFS.PSEL = sel;
					PORT2::PMR.B0 = enable;
					PORT2::PMR.B1 = enable;
				}
				break;
			case peripheral::SCI1:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTF::PDR.B0 = enable; // TXD1
					PORTF::PDR.B2 = 0;  	// RXD1
					MPC::PF0PFS.PSEL = sel;
					MPC::PF2PFS.PSEL = sel;
					PORTF::PMR.B0 = enable;
					PORTF::PMR.B2 = enable;
				}
				break;
			case peripheral::SCI2:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT1::PDR.B3 = enable; // TXD2
					PORT1::PDR.B2 = 0;  	// RXD2
					MPC::P13PFS.PSEL = sel;
					MPC::P12PFS.PSEL = sel;
					PORT1::PMR.B3 = enable;
					PORT1::PMR.B2 = enable;
				}
				break;
			case peripheral::SCI3:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT2::PDR.B3 = enable; // TXD3
					PORT2::PDR.B5 = 0;  	// RXD3
					MPC::P23PFS.PSEL = sel;
					MPC::P25PFS.PSEL = sel;
					PORT2::PMR.B3 = enable;
					PORT2::PMR.B5 = enable;
				}
				break;
			case peripheral::SCI4:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTB::PDR.B1 = enable; // TXD4
					PORTB::PDR.B0 = 0;  	// RXD4
					MPC::PB1PFS.PSEL = sel;
					MPC::PB0PFS.PSEL = sel;
					PORTB::PMR.B1 = enable;
					PORTB::PMR.B0 = enable;
				}
				break;
			case peripheral::SCI5:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTA::PDR.B4 = enable; // TXD5
					PORTA::PDR.B3 = 0;  	// RXD5
					MPC::PA4PFS.PSEL = sel;
					MPC::PA3PFS.PSEL = sel;
					PORTA::PMR.B4 = enable;
					PORTA::PMR.B3 = enable;
				}
				break;
			case peripheral::SCI6:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT0::PDR.B0 = enable; // TXD6
					PORT0::PDR.B1 = 0;  	// RXD6
					MPC::P00PFS.PSEL = sel;
					MPC::P01PFS.PSEL = sel;
					PORT0::PMR.B0 = enable;
					PORT0::PMR.B1 = enable;
				}
				break;
			case peripheral::SCI7:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT9::PDR.B0 = enable; // TXD7
					PORT9::PDR.B2 = 0;  	// RXD7
					MPC::P90PFS.PSEL = sel;
					MPC::P92PFS.PSEL = sel;
					PORT9::PMR.B0 = enable;
					PORT9::PMR.B2 = enable;
				}
				break;

			case peripheral::SCI12:
				{
					uint8_t sel = enable ? 0b001100 : 0;
					PORTE::PDR.B2 = enable; // TXD12
					PORTE::PDR.B1 = 0;  	// RXD12
					MPC::PE2PFS.PSEL = sel;
					MPC::PE1PFS.PSEL = sel;
					PORTE::PMR.B2 = enable;
					PORTE::PMR.B1 = enable;
				}
				break;

			case peripheral::RSPI:
				{
					uint8_t sel = enable ? 0b001101 : 0;
//					PORTC::PCR.B7 = 1;		// pull-up
//					PORTC::PDR.B7 = 0;		// MISOA
//					PORTC::PDR.B6 = 1;		// MOSIA
//					PORTC::PDR.B5 = 1;		// RSPCKA
					MPC::PC7PFS.PSEL = sel;  // MISOA
					MPC::PC6PFS.PSEL = sel;  // MOSIA
					MPC::PC5PFS.PSEL = sel;  // RSPCKA
					PORTC::PMR.B7 = enable;
					PORTC::PMR.B6 = enable;
					PORTC::PMR.B5 = enable;
				}
				break;

			case peripheral::SDHI:
				{
					uint8_t sel = enable ? 0b011010 : 0;
					MPC::P80PFS.PSEL = sel;  // SDHI_WP
					MPC::P81PFS.PSEL = sel;  // SDHI_CD
					PORT8::PMR.B0 = enable;
					PORT8::PMR.B1 = enable;
					MPC::PC2PFS.PSEL = sel;  // SDHI_D3
					MPC::PC3PFS.PSEL = sel;  // SDHI_D0
					MPC::PC4PFS.PSEL = sel;  // SDHI_D1
					PORTC::PMR.B2 = enable;
					PORTC::PMR.B3 = enable;
					PORTC::PMR.B4 = enable;
   					MPC::P75PFS.PSEL = sel;  // SDHI_D2
					MPC::P76PFS.PSEL = sel;  // SDHI_CMD
					MPC::P77PFS.PSEL = sel;  // SDHI_CLK
					PORT7::PMR.B5 = enable;
					PORT7::PMR.B6 = enable;
					PORT7::PMR.B7 = enable;
				}
				break;

			case peripheral::ETHERC0:  // only RMII mode, not use link status interrupt
				{
					uint8_t  mii = enable ? 0b010001 : 0;
					uint8_t rmii = enable ? 0b010010 : 0;
//					MPC::P34PFS.PSEL = mii;   // ET0_LINKSTA
//					PORT3::PMR.B4 = enable;
					MPC::P71PFS.PSEL = mii;   // ET0_MDIO
					MPC::P72PFS.PSEL = mii;   // ET0_MDC
//					MPC::P73PFS.PSEL = mii;   // ET0_WOL
					MPC::P74PFS.PSEL = rmii;  // RMII0_RXD1
					MPC::P75PFS.PSEL = rmii;  // RMII0_RXD0
					MPC::P76PFS.PSEL = rmii;  // REF50CK0
					MPC::P77PFS.PSEL = rmii;  // RMII0_RX_ER
					PORT7::PMR.B1 = enable;
					PORT7::PMR.B2 = enable;
//					PORT7::PMR.B3 = enable;
					PORT7::PMR.B4 = enable;
					PORT7::PMR.B5 = enable;
					PORT7::PMR.B6 = enable;
					PORT7::PMR.B7 = enable;
					MPC::P80PFS.PSEL = rmii;  // RMII0_TXD_EN
					MPC::P81PFS.PSEL = rmii;  // RMII0_TXD0
					MPC::P82PFS.PSEL = rmii;  // RMII0_TXD1
					MPC::P83PFS.PSEL = rmii;  // RMII0_CRS_DV
					PORT8::PMR.B0 = enable;
					PORT8::PMR.B1 = enable;
					PORT8::PMR.B2 = enable;
					PORT8::PMR.B3 = enable;
					MPC::PFENET.PHYMODE0 = 0;  // for RMII mode chanel 0
				}
				break;

			case peripheral::ETHERCA:  // only RMII mode, not use link status interrupt
				{
					uint8_t  mii = enable ? 0b010001 : 0;
					uint8_t rmii = enable ? 0b010010 : 0;
///					MPC::P73PFS.PSEL = mii;   // ET0_WOL  (144LQFP: 77)
					MPC::P72PFS.PSEL = mii;   // ET0_MDC  (144LQFP: 85)
					MPC::P71PFS.PSEL = mii;   // ET0_MDIO (144LQFP: 86)
///					PORT7::PMR.B3 = enable;
					PORT7::PMR.B2 = enable;
					PORT7::PMR.B1 = enable;
					MPC::PB7PFS.PSEL = rmii;  // RMII0_CRS_DV (144LQFP: 78)
					MPC::PB6PFS.PSEL = rmii;  // RMII0_TXD1   (144LQFP: 79)
					MPC::PB5PFS.PSEL = rmii;  // RMII0_TXD0   (144LQFP: 80)
					MPC::PB4PFS.PSEL = rmii;  // RMII0_TXD_EN (144LQFP: 81)
					MPC::PB3PFS.PSEL = rmii;  // RMII0_RX_ER  (144LQFP: 82)
					MPC::PB2PFS.PSEL = rmii;  // REF50CK0     (144LQFP: 83)
					MPC::PB1PFS.PSEL = rmii;  // RMII0_RXD0   (144LQFP: 84)
					MPC::PB0PFS.PSEL = rmii;  // RMII0_RXD1   (144LQFP: 87)
					PORTB::PMR.B7 = enable;
					PORTB::PMR.B6 = enable;
					PORTB::PMR.B5 = enable;
					PORTB::PMR.B4 = enable;
					PORTB::PMR.B3 = enable;
					PORTB::PMR.B2 = enable;
					PORTB::PMR.B1 = enable;
					PORTB::PMR.B0 = enable;
					MPC::PFENET.PHYMODE0 = 0;  // for RMII mode chanel 0
				}
				break;

			default:
				ret = false;
				break;
			}
			return ret;
		}

	public:

		//-----------------------------------------------------------------//
		/*!
			@brief  周辺機器に切り替える
			@param[in]	t	周辺機器タイプ
			@param[in]	ena	無効にする場合「false」
		*/
		//-----------------------------------------------------------------//
		static bool turn(peripheral t, bool ena = true) noexcept
		{
			MPC::PWPR.B0WI = 0;		// PWPR 書き込み許可
			MPC::PWPR.PFSWE = 1;	// PxxPFS 書き込み許可

			auto ret = sub_(t, ena);

			MPC::PWPR = device::MPC::PWPR.B0WI.b();

			return ret;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  SDHI クロック端子のソフト制御
			@param[in]	t	周辺機器タイプ
		*/
		//-----------------------------------------------------------------//
		static bool turn_sdhi_clk(peripheral t)
		{
			MPC::PWPR.B0WI = 0;		// PWPR 書き込み許可
			MPC::PWPR.PFSWE = 1;	// PxxPFS 書き込み許可

			bool ret = false;
			if(t == peripheral::SDHI) {
				MPC::P77PFS.PSEL = 0;  // SDHI_CLK
				PORT7::PMR.B7 = 0;
				ret = true;
			}
			MPC::PWPR = device::MPC::PWPR.B0WI.b();

			return ret;
		}
	};
}

<commit_msg>cleanup<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX64M グループ・ポート・マッピング @n
			・ペリフェラル型に従って、ポートの設定をグループ化
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX600/port.hpp"
#include "RX64M/mpc.hpp"
#include "RX64M/peripheral.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ポート・マッピング・ユーティリティー
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class port_map {

		static bool sub_(peripheral t, bool enable) {
			bool ret = true;
			switch(t) {
			// ※シリアルポートの MPC 設定では、PDR を制御する必要は無いが、
			// 出力ポートのインピーダンス制御の一環として入れてある。
			case peripheral::SCI0:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT2::PDR.B0 = enable; // TXD0
					PORT2::PDR.B1 = 0;  	// RXD0
					MPC::P20PFS.PSEL = sel;
					MPC::P21PFS.PSEL = sel;
					PORT2::PMR.B0 = enable;
					PORT2::PMR.B1 = enable;
				}
				break;
			case peripheral::SCI1:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTF::PDR.B0 = enable; // TXD1
					PORTF::PDR.B2 = 0;  	// RXD1
					MPC::PF0PFS.PSEL = sel;
					MPC::PF2PFS.PSEL = sel;
					PORTF::PMR.B0 = enable;
					PORTF::PMR.B2 = enable;
				}
				break;
			case peripheral::SCI2:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT1::PDR.B3 = enable; // TXD2
					PORT1::PDR.B2 = 0;  	// RXD2
					MPC::P13PFS.PSEL = sel;
					MPC::P12PFS.PSEL = sel;
					PORT1::PMR.B3 = enable;
					PORT1::PMR.B2 = enable;
				}
				break;
			case peripheral::SCI3:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT2::PDR.B3 = enable; // TXD3
					PORT2::PDR.B5 = 0;  	// RXD3
					MPC::P23PFS.PSEL = sel;
					MPC::P25PFS.PSEL = sel;
					PORT2::PMR.B3 = enable;
					PORT2::PMR.B5 = enable;
				}
				break;
			case peripheral::SCI4:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTB::PDR.B1 = enable; // TXD4
					PORTB::PDR.B0 = 0;  	// RXD4
					MPC::PB1PFS.PSEL = sel;
					MPC::PB0PFS.PSEL = sel;
					PORTB::PMR.B1 = enable;
					PORTB::PMR.B0 = enable;
				}
				break;
			case peripheral::SCI5:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORTA::PDR.B4 = enable; // TXD5
					PORTA::PDR.B3 = 0;  	// RXD5
					MPC::PA4PFS.PSEL = sel;
					MPC::PA3PFS.PSEL = sel;
					PORTA::PMR.B4 = enable;
					PORTA::PMR.B3 = enable;
				}
				break;
			case peripheral::SCI6:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT0::PDR.B0 = enable; // TXD6
					PORT0::PDR.B1 = 0;  	// RXD6
					MPC::P00PFS.PSEL = sel;
					MPC::P01PFS.PSEL = sel;
					PORT0::PMR.B0 = enable;
					PORT0::PMR.B1 = enable;
				}
				break;
			case peripheral::SCI7:
				{
					uint8_t sel = enable ? 0b001010 : 0;
					PORT9::PDR.B0 = enable; // TXD7
					PORT9::PDR.B2 = 0;  	// RXD7
					MPC::P90PFS.PSEL = sel;
					MPC::P92PFS.PSEL = sel;
					PORT9::PMR.B0 = enable;
					PORT9::PMR.B2 = enable;
				}
				break;

			case peripheral::SCI12:
				{
					uint8_t sel = enable ? 0b001100 : 0;
					PORTE::PDR.B2 = enable; // TXD12
					PORTE::PDR.B1 = 0;  	// RXD12
					MPC::PE2PFS.PSEL = sel;
					MPC::PE1PFS.PSEL = sel;
					PORTE::PMR.B2 = enable;
					PORTE::PMR.B1 = enable;
				}
				break;

			case peripheral::RSPI:
				{
					uint8_t sel = enable ? 0b001101 : 0;
//					PORTC::PCR.B7 = 1;		// pull-up
//					PORTC::PDR.B7 = 0;		// MISOA
//					PORTC::PDR.B6 = 1;		// MOSIA
//					PORTC::PDR.B5 = 1;		// RSPCKA
					MPC::PC7PFS.PSEL = sel;  // MISOA
					MPC::PC6PFS.PSEL = sel;  // MOSIA
					MPC::PC5PFS.PSEL = sel;  // RSPCKA
					PORTC::PMR.B7 = enable;
					PORTC::PMR.B6 = enable;
					PORTC::PMR.B5 = enable;
				}
				break;

			case peripheral::SDHI:
				{
					uint8_t sel = enable ? 0b011010 : 0;
					MPC::P80PFS.PSEL = sel;  // SDHI_WP (81)
					PORT8::PMR.B0 = enable;
//					PORT8::PCR.B0 = 1;
					MPC::P81PFS.PSEL = sel;  // SDHI_CD (80)
					PORT8::PMR.B1 = enable;
//					PORT8::PCR.B1 = 1;
					MPC::PC2PFS.PSEL = sel;  // SDHI_D3 (86)
					PORTC::PMR.B2 = enable;
//					PORTC::PCR.B2 = 1;
					MPC::PC3PFS.PSEL = sel;  // SDHI_D0 (83)
					PORTC::PMR.B3 = enable;
//					PORTC::PCR.B3 = 1;
					MPC::PC4PFS.PSEL = sel;  // SDHI_D1 (82)
					PORTC::PMR.B4 = enable;
//					PORTC::PCR.B4 = 1;
   					MPC::P75PFS.PSEL = sel;  // SDHI_D2 (87)
					PORT7::PMR.B5 = enable;
//					PORT7::PCR.B5 = 1;
					MPC::P76PFS.PSEL = sel;  // SDHI_CMD (85)
					PORT7::PMR.B6 = enable;
//					PORT7::PCR.B6 = 1;
					MPC::P77PFS.PSEL = sel;  // SDHI_CLK (84)
					PORT7::PMR.B7 = enable;
//					PORT7::PCR.B7 = 1;
				}
				break;

			case peripheral::ETHERC0:  // only RMII mode, not use link status interrupt
				{
					uint8_t  mii = enable ? 0b010001 : 0;
					uint8_t rmii = enable ? 0b010010 : 0;
//					MPC::P34PFS.PSEL = mii;   // ET0_LINKSTA
//					PORT3::PMR.B4 = enable;
					MPC::P71PFS.PSEL = mii;   // ET0_MDIO
					MPC::P72PFS.PSEL = mii;   // ET0_MDC
//					MPC::P73PFS.PSEL = mii;   // ET0_WOL
					MPC::P74PFS.PSEL = rmii;  // RMII0_RXD1
					MPC::P75PFS.PSEL = rmii;  // RMII0_RXD0
					MPC::P76PFS.PSEL = rmii;  // REF50CK0
					MPC::P77PFS.PSEL = rmii;  // RMII0_RX_ER
					PORT7::PMR.B1 = enable;
					PORT7::PMR.B2 = enable;
//					PORT7::PMR.B3 = enable;
					PORT7::PMR.B4 = enable;
					PORT7::PMR.B5 = enable;
					PORT7::PMR.B6 = enable;
					PORT7::PMR.B7 = enable;
					MPC::P80PFS.PSEL = rmii;  // RMII0_TXD_EN
					MPC::P81PFS.PSEL = rmii;  // RMII0_TXD0
					MPC::P82PFS.PSEL = rmii;  // RMII0_TXD1
					MPC::P83PFS.PSEL = rmii;  // RMII0_CRS_DV
					PORT8::PMR.B0 = enable;
					PORT8::PMR.B1 = enable;
					PORT8::PMR.B2 = enable;
					PORT8::PMR.B3 = enable;
					MPC::PFENET.PHYMODE0 = 0;  // for RMII mode chanel 0
				}
				break;

			case peripheral::ETHERCA:  // only RMII mode, not use link status interrupt
				{
					uint8_t  mii = enable ? 0b010001 : 0;
					uint8_t rmii = enable ? 0b010010 : 0;
///					MPC::P73PFS.PSEL = mii;   // ET0_WOL  (144LQFP: 77)
					MPC::P72PFS.PSEL = mii;   // ET0_MDC  (144LQFP: 85)
					MPC::P71PFS.PSEL = mii;   // ET0_MDIO (144LQFP: 86)
///					PORT7::PMR.B3 = enable;
					PORT7::PMR.B2 = enable;
					PORT7::PMR.B1 = enable;
					MPC::PB7PFS.PSEL = rmii;  // RMII0_CRS_DV (144LQFP: 78)
					MPC::PB6PFS.PSEL = rmii;  // RMII0_TXD1   (144LQFP: 79)
					MPC::PB5PFS.PSEL = rmii;  // RMII0_TXD0   (144LQFP: 80)
					MPC::PB4PFS.PSEL = rmii;  // RMII0_TXD_EN (144LQFP: 81)
					MPC::PB3PFS.PSEL = rmii;  // RMII0_RX_ER  (144LQFP: 82)
					MPC::PB2PFS.PSEL = rmii;  // REF50CK0     (144LQFP: 83)
					MPC::PB1PFS.PSEL = rmii;  // RMII0_RXD0   (144LQFP: 84)
					MPC::PB0PFS.PSEL = rmii;  // RMII0_RXD1   (144LQFP: 87)
					PORTB::PMR.B7 = enable;
					PORTB::PMR.B6 = enable;
					PORTB::PMR.B5 = enable;
					PORTB::PMR.B4 = enable;
					PORTB::PMR.B3 = enable;
					PORTB::PMR.B2 = enable;
					PORTB::PMR.B1 = enable;
					PORTB::PMR.B0 = enable;
					MPC::PFENET.PHYMODE0 = 0;  // for RMII mode chanel 0
				}
				break;

			default:
				ret = false;
				break;
			}
			return ret;
		}

	public:

		//-----------------------------------------------------------------//
		/*!
			@brief  周辺機器に切り替える
			@param[in]	t	周辺機器タイプ
			@param[in]	ena	無効にする場合「false」
		*/
		//-----------------------------------------------------------------//
		static bool turn(peripheral t, bool ena = true) noexcept
		{
			MPC::PWPR.B0WI = 0;		// PWPR 書き込み許可
			MPC::PWPR.PFSWE = 1;	// PxxPFS 書き込み許可

			auto ret = sub_(t, ena);

			MPC::PWPR = device::MPC::PWPR.B0WI.b();

			return ret;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  SDHI クロック端子のソフト制御
			@param[in]	t	周辺機器タイプ
			@param[in]	ena	SDHI のクロック端子にする場合「true」
			@param[in]	out	SDHI クロック出力設定
			@return 周辺機器型が異なる場合「false」
		*/
		//-----------------------------------------------------------------//
		static bool turn_sdhi_clk(peripheral t, bool ena, bool out)
		{
			MPC::PWPR.B0WI = 0;		// PWPR 書き込み許可
			MPC::PWPR.PFSWE = 1;	// PxxPFS 書き込み許可

			bool ret = false;
			if(t == peripheral::SDHI) {
				if(ena) {
					MPC::P77PFS.PSEL = 0b011010;  // enable SDHI_CLK
					PORT7::PMR.B7 = 1;
				} else {
					MPC::P77PFS.PSEL = 0;  		  // disable SDHI_CLK
					PORT7::PMR.B7 = 0;
					PORT7::PCR.B7 = 0;  // pullup offline
					PORT7::PDR.B7 = 1;  // output
					PORT7::PODR.B7 = out;
				}
				ret = true;
			}

			MPC::PWPR = device::MPC::PWPR.B0WI.b();

			return ret;
		}
	};
}

<|endoftext|>


<commit_before>#include <iostream>

void PrintUsage() {
	std::cout<<
#ifndef HIDDEN
"Usage: SnK [settings_block|swith[:parametres][=argument]] ...\n"
"\n"
"This is a usage quick reference. Please check README.TXT for more information.\n"
	<<std::endl;
	std::cout<<
"Switches:"
	<<std::endl;
	std::cout<<
"/hlp                          Print this help and exit."
	<<std::endl;
	std::cout<<
"/ver                          Print version information and exit."
	<<std::endl;
	std::cout<<
"/bpp                          Make standart Windows 'informational beep' and\n"
"                              continue execution."
	<<std::endl;
	std::cout<<
"/sec                          Secured execution. Will exit program if there is\n"
"                              another instance already running that has\n"
"                              executed this switch."
	<<std::endl;
	std::cout<<
"/cpu                          Kill process with highest cpu load."
	<<std::endl;
	std::cout<<
"/d3d[:simple][:soft]          Kill process that uses Direct3D and has highest\n"
"                              cpu load."
	<<std::endl;
	std::cout<<
"/ogl[:simple][:soft]          Kill process that uses OpenGL and has highest cpu\n"
"                              load."
	<<std::endl;
	std::cout<<
"/d2d[:simple][:strict]        Kill process that uses DirectDraw and has highest\n"
"                              cpu load."
	<<std::endl;
	std::cout<<
"/gld[:simple][:strict]        Kill process that uses Glide and has highest cpu\n"
"                              load."
	<<std::endl;
	std::cout<<
"/inr[:manual|:ghost]          Kill process that is not responding and has\n"
"                              highest cpu load."
	<<std::endl;
	std::cout<<
"/fsc[:apps][:strict]          Kill process that is running in fullscreen and\n"
"                              has highest cpu load."
	<<std::endl;
	std::cout<<
"/pth[:full][:lcase]=NAME      Kill process whose name matches wildcard 'NAME'\n"
"                              and has highest cpu load."
	<<std::endl;
	std::cout<<
"Settings:"
	<<std::endl;
	std::cout<<
"+t|-t                         Will turn test mode on/off."
	<<std::endl;
	std::cout<<
"+v|-v                         Will turn verbose mode on/off."
	<<std::endl;
	std::cout<<
"+k|-k                         Will turn 'any key' mode on/off."
	<<std::endl;
	std::cout<<
"+a|-a                         Will turn 'query all processes' mode on/off."
#else
"Usage: SnKh [settings_block|swith[:parametres][=argument]] ...\n"
"\n"
"Please check README.TXT for more information.\n"
#endif
	<<std::endl;
}

void PrintVersion() {
	std::cout<<
#ifndef HIDDEN
"Search and Kill v 1.0\n"
#else
"Search and Kill (windowless) v 1.0\n"
#endif
"\n"
#ifndef HIDDEN
"Run with /hlp switch for usage information.\n"
#else
"Run with +v /hlp command for usage information.\n"
#endif
"\n"
"Copyright (c) 2012, Lcferrum <lcferrum@yandex.com>\n"
"Licensed under BSD license - see LICENSE.TXT file for details."
#ifdef HIDDEN
"\n"
#endif
	<<std::endl;
}
<commit_msg>Silly fixes<commit_after>#include <iostream>

void PrintUsage() {
	std::cout<<
#ifndef HIDDEN
"Usage: SnK [settings_block|swith[:parametres][=argument]] ...\n"
"\n"
"This is a usage quick reference. Please check README.TXT for more information.\n"
	<<std::endl;
	std::cout<<
"Switches:"
	<<std::endl;
	std::cout<<
"/hlp                          Print this help and exit."
	<<std::endl;
	std::cout<<
"/ver                          Print version information and exit."
	<<std::endl;
	std::cout<<
"/bpp                          Make standart Windows 'informational beep' and\n"
"                              continue execution."
	<<std::endl;
	std::cout<<
"/sec                          Secured execution. Will exit program if there is\n"
"                              another instance already running that has\n"
"                              executed this switch."
	<<std::endl;
	std::cout<<
"/cpu                          Kill process with highest cpu load."
	<<std::endl;
	std::cout<<
"/d3d[:simple][:soft]          Kill process that uses Direct3D and has highest\n"
"                              cpu load."
	<<std::endl;
	std::cout<<
"/ogl[:simple][:soft]          Kill process that uses OpenGL and has highest cpu\n"
"                              load."
	<<std::endl;
	std::cout<<
"/d2d[:simple][:strict]        Kill process that uses DirectDraw and has highest\n"
"                              cpu load."
	<<std::endl;
	std::cout<<
"/gld[:simple][:strict]        Kill process that uses Glide and has highest cpu\n"
"                              load."
	<<std::endl;
	std::cout<<
"/inr[:manual|:ghost]          Kill process that is not responding and has\n"
"                              highest cpu load."
	<<std::endl;
	std::cout<<
"/fsc[:apps][:strict]          Kill process that is running in fullscreen and\n"
"                              has highest cpu load."
	<<std::endl;
	std::cout<<
"/pth[:full][:lcase]=NAME      Kill process whose name matches wildcard 'NAME'\n"
"                              and has highest cpu load."
	<<std::endl;
	std::cout<<
"Settings:"
	<<std::endl;
	std::cout<<
"+t|-t                         Will turn test mode on/off."
	<<std::endl;
	std::cout<<
"+v|-v                         Will turn verbose mode on/off."
	<<std::endl;
	std::cout<<
"+k|-k                         Will turn 'any key' mode on/off."
	<<std::endl;
	std::cout<<
"+a|-a                         Will turn 'query all processes' mode on/off."
#else
"Usage: SnKh [settings_block|swith[:parametres][=argument]] ...\n"
"\n"
"Please check README.TXT for more information.\n"
#endif
	<<std::endl;
}

void PrintVersion() {
	std::cout<<
#ifndef HIDDEN
"Search and Kill v 1.0\n"
#else
"Search and Kill (windowless) v 1.0\n"
#endif
"\n"
#ifndef HIDDEN
"Run with /hlp switch for usage information.\n"
#else
"Run with +v /hlp command for usage information.\n"
#endif
"\n"
"Copyright (c) 2012 Lcferrum\n"
"Licensed under BSD license - see LICENSE.TXT file for details."
#ifdef HIDDEN
"\n"
#endif
	<<std::endl;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, elvman
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY elvman ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "RealisticWater.h"

RealisticWaterSceneNode::RealisticWaterSceneNode(scene::ISceneManager* sceneManager, f32 width, f32 height,
												 const irr::core::stringc& resourcePath, core::dimension2du renderTargetSize,
												 scene::ISceneNode* parent, s32 id):
	scene::ISceneNode(parent, sceneManager, id), _time(0),
	_size(width, height), _sceneManager(sceneManager), _refractionMap(NULL), _reflectionMap(NULL),
	_windForce(20.0f),_windDirection(0, 1),_waveHeight(0.3f), _waterColor(0.1f, 0.1f, 0.6f, 1.0f), _colorBlendFactor(0.2f), _camera(NULL)
{
	_videoDriver = sceneManager->getVideoDriver();

	//create new camera
	_camera = sceneManager->addCameraSceneNode(0, core::vector3df(0, 0, 0), core::vector3df(0, 0, 0), -1, false);

	_waterMesh = sceneManager->addHillPlaneMesh("RealisticWater", _size, core::dimension2d<u32>(1, 1));

	_waterSceneNode = sceneManager->addMeshSceneNode(_waterMesh->getMesh(0), this);

	video::IGPUProgrammingServices* GPUProgrammingServices = _videoDriver->getGPUProgrammingServices();

	core::stringc waterPixelShader;
	core::stringc waterVertexShader;

	if (_videoDriver->getDriverType() == video::EDT_DIRECT3D9)
	{
		waterPixelShader = resourcePath + "/shaders/Water_ps.hlsl";
		waterVertexShader = resourcePath + "/shaders/Water_vs.hlsl";
	}
	else if (_videoDriver->getDriverType() == video::EDT_OPENGL)
	{
		waterPixelShader = resourcePath + "/shaders/Water_ps.glsl";
		waterVertexShader = resourcePath + "/shaders/Water_vs.glsl";
	}

	_shaderMaterial = GPUProgrammingServices->addHighLevelShaderMaterialFromFiles(
		waterVertexShader.c_str(), "main", video::EVST_VS_1_1,
		waterPixelShader.c_str(), "main", video::EPST_PS_1_1,
		this);

	_waterSceneNode->setMaterialType((video::E_MATERIAL_TYPE)_shaderMaterial);

	irr::video::ITexture* bumpTexture = _videoDriver->getTexture(resourcePath + "/waterbump.png");
	_waterSceneNode->setMaterialTexture(0, bumpTexture);

	_refractionMap = _videoDriver->addRenderTargetTexture(renderTargetSize);
	_reflectionMap = _videoDriver->addRenderTargetTexture(renderTargetSize);

	_waterSceneNode->setMaterialTexture(1, _refractionMap);
	_waterSceneNode->setMaterialTexture(2, _reflectionMap);
}

RealisticWaterSceneNode::~RealisticWaterSceneNode()
{
	if (_camera)
	{
		_camera->drop();
		_camera = NULL;
	}

	if (_refractionMap)
	{
		_refractionMap->drop();
		_refractionMap = NULL;
	}

	if (_reflectionMap)
	{
		_reflectionMap->drop();
		_reflectionMap = NULL;
	}

	if (_waterSceneNode)
	{
		_waterSceneNode->drop();
		_waterSceneNode = NULL;
	}

	if (_waterMesh)
	{
		_waterMesh->drop();
		_waterMesh = NULL;
	}
}

// frame
void RealisticWaterSceneNode::OnRegisterSceneNode()
{
	ISceneNode::OnRegisterSceneNode();

	if (IsVisible)
	{
		_sceneManager->registerNodeForRendering(this);
	}
}

void RealisticWaterSceneNode::OnAnimate(u32 timeMs)
{
	ISceneNode::OnAnimate(timeMs);

	_time = timeMs;

	//fixes glitches with incomplete refraction
	const f32 CLIP_PLANE_OFFSET_Y = 5.0f;

	if (IsVisible)
	{
		setVisible(false); //hide the water

		//refraction
		_videoDriver->setRenderTarget(_refractionMap, true, true); //render to refraction

		//refraction clipping plane
		core::plane3d<f32> refractionClipPlane(0, RelativeTranslation.Y + CLIP_PLANE_OFFSET_Y, 0, 0, -1, 0); //refraction clip plane
		_videoDriver->setClipPlane(0, refractionClipPlane, true);

		_sceneManager->drawAll(); //draw the scene

		//reflection
		_videoDriver->setRenderTarget(_reflectionMap, true, true); //render to reflection

		//get current camera
		scene::ICameraSceneNode* currentCamera = _sceneManager->getActiveCamera();

		//set FOV anf far value from current camera
		_camera->setFarValue(currentCamera->getFarValue());
		_camera->setFOV(currentCamera->getFOV());

		core::vector3df position = currentCamera->getPosition();
		position.Y = -position.Y + 2 * RelativeTranslation.Y; //position of the water
		_camera->setPosition(position);

		core::vector3df target = currentCamera->getTarget();

		//invert Y position of current camera
		target.Y = -target.Y + 2 * RelativeTranslation.Y;
		_camera->setTarget(target);

		//set the reflection camera
		_sceneManager->setActiveCamera(_camera);

		//reflection clipping plane
		core::plane3d<f32> reflectionClipPlane(0, RelativeTranslation.Y - CLIP_PLANE_OFFSET_Y, 0, 0, 1, 0);
		_videoDriver->setClipPlane(0, reflectionClipPlane, true);

		_sceneManager->drawAll(); //draw the scene

		//disable clip plane
		_videoDriver->enableClipPlane(0, false);

		//set back old render target
		_videoDriver->setRenderTarget(0, false, true);

		//set back the active camera
		_sceneManager->setActiveCamera(currentCamera);

		setVisible(true); //show it again
	}
}

void RealisticWaterSceneNode::render()
{
	/*core::array<video::IRenderTarget> renderTargets;
	//renderTargets.push_back();
	renderTargets.push_back(_refractionMap);

	_videoDriver->setRenderTarget(renderTargets, true, true);*/
	//_videoDriver->draw2DImage(_reflectionMap,core::position2d<s32>(0,0));
}

// returns the axis aligned bounding box of terrain
const core::aabbox3d<f32>& RealisticWaterSceneNode::getBoundingBox() const
{
	return _waterSceneNode->getBoundingBox();
}

void RealisticWaterSceneNode::OnSetConstants(video::IMaterialRendererServices* services, s32 userData)
{
	video::IVideoDriver* driver = services->getVideoDriver();

	core::matrix4 projection = driver->getTransform(video::ETS_PROJECTION);
	core::matrix4 view = driver->getTransform(video::ETS_VIEW);
	core::matrix4 world = driver->getTransform(video::ETS_WORLD);

	core::matrix4 cameraView = _camera->getViewMatrix();

	//vertex shader constants
	//services->setVertexShaderConstant("View", view.pointer(), 16);

	core::matrix4 worldViewProj = projection;
	worldViewProj *= view;
	worldViewProj *= world;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("WorldViewProj"), worldViewProj.pointer(), 16);

	core::matrix4 worldReflectionViewProj = projection;
	worldReflectionViewProj *= cameraView;
	worldReflectionViewProj *= world;

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WorldReflectionViewProj"), worldReflectionViewProj.pointer(), 16);

	f32 waveLength = 0.1f;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("WaveLength"), &waveLength, 1);

	f32 time = _time / 100000.0f;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("Time"), &time, 1);

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WindForce"), &_windForce, 1);

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WindDirection"), &_windDirection.X, 2);

	//pixel shader constants
	core::vector3df cameraPosition = _sceneManager->getActiveCamera()->getPosition();
	services->setPixelShaderConstant(services->getVertexShaderConstantID("CameraPosition"), &cameraPosition.X, 3);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("WaveHeight"), &_waveHeight, 1);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("WaterColor"), &_waterColor.r, 4);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("ColorBlendFactor"), &_colorBlendFactor, 1);

	//texture constants for GLSL
	if (driver->getDriverType() == video::EDT_OPENGL)
	{
		int var0 = 0;
		int var1 = 1;
		int var2 = 2;
		services->setPixelShaderConstant(services->getVertexShaderConstantID("WaterBump"), &var0, 1); //the colormap
		services->setPixelShaderConstant(services->getVertexShaderConstantID("RefractionMap"), &var1, 1); //the colormap
		services->setPixelShaderConstant(services->getVertexShaderConstantID("ReflectionMap"), &var2, 1); //the colormap
	}
}

void RealisticWaterSceneNode::setWindForce(const f32 windForce)
{
	_windForce = windForce;
}

void RealisticWaterSceneNode::setWindDirection(const core::vector2df& windDirection)
{
	_windDirection = windDirection;
	_windDirection.normalize();
}

void RealisticWaterSceneNode::setWaveHeight(const f32 waveHeight)
{
	_waveHeight = waveHeight;
}

void RealisticWaterSceneNode::setWaterColor(const video::SColorf& waterColor)
{
	_waterColor = waterColor;
}

void RealisticWaterSceneNode::setColorBlendFactor(const f32 colorBlendFactor)
{
	_colorBlendFactor = colorBlendFactor;
}
<commit_msg>Using camera's absolute position<commit_after>/*
 * Copyright (c) 2013, elvman
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY elvman ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "RealisticWater.h"

RealisticWaterSceneNode::RealisticWaterSceneNode(scene::ISceneManager* sceneManager, f32 width, f32 height,
												 const irr::core::stringc& resourcePath, core::dimension2du renderTargetSize,
												 scene::ISceneNode* parent, s32 id):
	scene::ISceneNode(parent, sceneManager, id), _time(0),
	_size(width, height), _sceneManager(sceneManager), _refractionMap(NULL), _reflectionMap(NULL),
	_windForce(20.0f),_windDirection(0, 1),_waveHeight(0.3f), _waterColor(0.1f, 0.1f, 0.6f, 1.0f), _colorBlendFactor(0.2f), _camera(NULL)
{
	_videoDriver = sceneManager->getVideoDriver();

	//create new camera
	_camera = sceneManager->addCameraSceneNode(0, core::vector3df(0, 0, 0), core::vector3df(0, 0, 0), -1, false);

	_waterMesh = sceneManager->addHillPlaneMesh("RealisticWater", _size, core::dimension2d<u32>(1, 1));

	_waterSceneNode = sceneManager->addMeshSceneNode(_waterMesh->getMesh(0), this);

	video::IGPUProgrammingServices* GPUProgrammingServices = _videoDriver->getGPUProgrammingServices();

	core::stringc waterPixelShader;
	core::stringc waterVertexShader;

	if (_videoDriver->getDriverType() == video::EDT_DIRECT3D9)
	{
		waterPixelShader = resourcePath + "/shaders/Water_ps.hlsl";
		waterVertexShader = resourcePath + "/shaders/Water_vs.hlsl";
	}
	else if (_videoDriver->getDriverType() == video::EDT_OPENGL)
	{
		waterPixelShader = resourcePath + "/shaders/Water_ps.glsl";
		waterVertexShader = resourcePath + "/shaders/Water_vs.glsl";
	}

	_shaderMaterial = GPUProgrammingServices->addHighLevelShaderMaterialFromFiles(
		waterVertexShader.c_str(), "main", video::EVST_VS_1_1,
		waterPixelShader.c_str(), "main", video::EPST_PS_1_1,
		this);

	_waterSceneNode->setMaterialType((video::E_MATERIAL_TYPE)_shaderMaterial);

	irr::video::ITexture* bumpTexture = _videoDriver->getTexture(resourcePath + "/waterbump.png");
	_waterSceneNode->setMaterialTexture(0, bumpTexture);

	_refractionMap = _videoDriver->addRenderTargetTexture(renderTargetSize);
	_reflectionMap = _videoDriver->addRenderTargetTexture(renderTargetSize);

	_waterSceneNode->setMaterialTexture(1, _refractionMap);
	_waterSceneNode->setMaterialTexture(2, _reflectionMap);
}

RealisticWaterSceneNode::~RealisticWaterSceneNode()
{
	if (_camera)
	{
		_camera->drop();
		_camera = NULL;
	}

	if (_refractionMap)
	{
		_refractionMap->drop();
		_refractionMap = NULL;
	}

	if (_reflectionMap)
	{
		_reflectionMap->drop();
		_reflectionMap = NULL;
	}

	if (_waterSceneNode)
	{
		_waterSceneNode->drop();
		_waterSceneNode = NULL;
	}

	if (_waterMesh)
	{
		_waterMesh->drop();
		_waterMesh = NULL;
	}
}

// frame
void RealisticWaterSceneNode::OnRegisterSceneNode()
{
	ISceneNode::OnRegisterSceneNode();

	if (IsVisible)
	{
		_sceneManager->registerNodeForRendering(this);
	}
}

void RealisticWaterSceneNode::OnAnimate(u32 timeMs)
{
	ISceneNode::OnAnimate(timeMs);

	_time = timeMs;

	//fixes glitches with incomplete refraction
	const f32 CLIP_PLANE_OFFSET_Y = 5.0f;

	if (IsVisible)
	{
		setVisible(false); //hide the water

		//refraction
		_videoDriver->setRenderTarget(_refractionMap, true, true); //render to refraction

		//refraction clipping plane
		core::plane3d<f32> refractionClipPlane(0, RelativeTranslation.Y + CLIP_PLANE_OFFSET_Y, 0, 0, -1, 0); //refraction clip plane
		_videoDriver->setClipPlane(0, refractionClipPlane, true);

		_sceneManager->drawAll(); //draw the scene

		//reflection
		_videoDriver->setRenderTarget(_reflectionMap, true, true); //render to reflection

		//get current camera
		scene::ICameraSceneNode* currentCamera = _sceneManager->getActiveCamera();

		//set FOV anf far value from current camera
		_camera->setFarValue(currentCamera->getFarValue());
		_camera->setFOV(currentCamera->getFOV());

		core::vector3df position = currentCamera->getAbsolutePosition();
		position.Y = -position.Y + 2 * RelativeTranslation.Y; //position of the water
		_camera->setPosition(position);

		core::vector3df target = currentCamera->getTarget();

		//invert Y position of current camera
		target.Y = -target.Y + 2 * RelativeTranslation.Y;
		_camera->setTarget(target);

		//set the reflection camera
		_sceneManager->setActiveCamera(_camera);

		//reflection clipping plane
		core::plane3d<f32> reflectionClipPlane(0, RelativeTranslation.Y - CLIP_PLANE_OFFSET_Y, 0, 0, 1, 0);
		_videoDriver->setClipPlane(0, reflectionClipPlane, true);

		_sceneManager->drawAll(); //draw the scene

		//disable clip plane
		_videoDriver->enableClipPlane(0, false);

		//set back old render target
		_videoDriver->setRenderTarget(0, false, true);

		//set back the active camera
		_sceneManager->setActiveCamera(currentCamera);

		setVisible(true); //show it again
	}
}

void RealisticWaterSceneNode::render()
{
	/*core::array<video::IRenderTarget> renderTargets;
	//renderTargets.push_back();
	renderTargets.push_back(_refractionMap);

	_videoDriver->setRenderTarget(renderTargets, true, true);*/
	//_videoDriver->draw2DImage(_reflectionMap,core::position2d<s32>(0,0));
}

// returns the axis aligned bounding box of terrain
const core::aabbox3d<f32>& RealisticWaterSceneNode::getBoundingBox() const
{
	return _waterSceneNode->getBoundingBox();
}

void RealisticWaterSceneNode::OnSetConstants(video::IMaterialRendererServices* services, s32 userData)
{
	video::IVideoDriver* driver = services->getVideoDriver();

	core::matrix4 projection = driver->getTransform(video::ETS_PROJECTION);
	core::matrix4 view = driver->getTransform(video::ETS_VIEW);
	core::matrix4 world = driver->getTransform(video::ETS_WORLD);

	core::matrix4 cameraView = _camera->getViewMatrix();

	//vertex shader constants
	//services->setVertexShaderConstant("View", view.pointer(), 16);

	core::matrix4 worldViewProj = projection;
	worldViewProj *= view;
	worldViewProj *= world;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("WorldViewProj"), worldViewProj.pointer(), 16);

	core::matrix4 worldReflectionViewProj = projection;
	worldReflectionViewProj *= cameraView;
	worldReflectionViewProj *= world;

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WorldReflectionViewProj"), worldReflectionViewProj.pointer(), 16);

	f32 waveLength = 0.1f;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("WaveLength"), &waveLength, 1);

	f32 time = _time / 100000.0f;
	services->setVertexShaderConstant(services->getVertexShaderConstantID("Time"), &time, 1);

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WindForce"), &_windForce, 1);

	services->setVertexShaderConstant(services->getVertexShaderConstantID("WindDirection"), &_windDirection.X, 2);

	//pixel shader constants
	core::vector3df cameraPosition = _sceneManager->getActiveCamera()->getPosition();
	services->setPixelShaderConstant(services->getVertexShaderConstantID("CameraPosition"), &cameraPosition.X, 3);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("WaveHeight"), &_waveHeight, 1);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("WaterColor"), &_waterColor.r, 4);

	services->setPixelShaderConstant(services->getVertexShaderConstantID("ColorBlendFactor"), &_colorBlendFactor, 1);

	//texture constants for GLSL
	if (driver->getDriverType() == video::EDT_OPENGL)
	{
		int var0 = 0;
		int var1 = 1;
		int var2 = 2;
		services->setPixelShaderConstant(services->getVertexShaderConstantID("WaterBump"), &var0, 1); //the colormap
		services->setPixelShaderConstant(services->getVertexShaderConstantID("RefractionMap"), &var1, 1); //the colormap
		services->setPixelShaderConstant(services->getVertexShaderConstantID("ReflectionMap"), &var2, 1); //the colormap
	}
}

void RealisticWaterSceneNode::setWindForce(const f32 windForce)
{
	_windForce = windForce;
}

void RealisticWaterSceneNode::setWindDirection(const core::vector2df& windDirection)
{
	_windDirection = windDirection;
	_windDirection.normalize();
}

void RealisticWaterSceneNode::setWaveHeight(const f32 waveHeight)
{
	_waveHeight = waveHeight;
}

void RealisticWaterSceneNode::setWaterColor(const video::SColorf& waterColor)
{
	_waterColor = waterColor;
}

void RealisticWaterSceneNode::setColorBlendFactor(const f32 colorBlendFactor)
{
	_colorBlendFactor = colorBlendFactor;
}
<|endoftext|>


<commit_before><commit_msg>Roll up addGeometry into a for loop.<commit_after><|endoftext|>


<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "../ports/SkOSLibrary.h"

#include <EGL/egl.h>

namespace {
struct Libs {
    void* fGLLib;
    void* fEGLLib;
};
}

static GrGLFuncPtr angle_get_gl_proc(void* ctx, const char name[]) {
    const Libs* libs = reinterpret_cast<const Libs*>(ctx);
    GrGLFuncPtr proc = (GrGLFuncPtr) GetProcedureAddress(libs->fGLLib, name);
    if (proc) {
        return proc;
    }
    proc = (GrGLFuncPtr) GetProcedureAddress(libs->fEGLLib, name);
    if (proc) {
        return proc;
    }
    return eglGetProcAddress(name);
}

const GrGLInterface* GrGLCreateANGLEInterface() {
    static Libs gLibs = { nullptr, nullptr };

    if (nullptr == gLibs.fGLLib) {
        // We load the ANGLE library and never let it go
#if defined _WIN32
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dll");
        gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dll");
#elif defined SK_BUILD_FOR_MAC
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dylib");
        gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dylib");
#else
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.so");
        gLibs.fGLLib = DynamicLoadLibrary("libEGL.so");
#endif
    }

    if (nullptr == gLibs.fGLLib || nullptr == gLibs.fEGLLib) {
        // We can't setup the interface correctly w/o the so
        return nullptr;
    }

    return GrGLAssembleGLESInterface(&gLibs, angle_get_gl_proc);
}
<commit_msg>Load ANGLE EGL library correctly on Linux<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gl/GrGLInterface.h"
#include "gl/GrGLAssembleInterface.h"
#include "../ports/SkOSLibrary.h"

#include <EGL/egl.h>

namespace {
struct Libs {
    void* fGLLib;
    void* fEGLLib;
};
}

static GrGLFuncPtr angle_get_gl_proc(void* ctx, const char name[]) {
    const Libs* libs = reinterpret_cast<const Libs*>(ctx);
    GrGLFuncPtr proc = (GrGLFuncPtr) GetProcedureAddress(libs->fGLLib, name);
    if (proc) {
        return proc;
    }
    proc = (GrGLFuncPtr) GetProcedureAddress(libs->fEGLLib, name);
    if (proc) {
        return proc;
    }
    return eglGetProcAddress(name);
}

const GrGLInterface* GrGLCreateANGLEInterface() {
    static Libs gLibs = { nullptr, nullptr };

    if (nullptr == gLibs.fGLLib) {
        // We load the ANGLE library and never let it go
#if defined _WIN32
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dll");
        gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dll");
#elif defined SK_BUILD_FOR_MAC
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.dylib");
        gLibs.fEGLLib = DynamicLoadLibrary("libEGL.dylib");
#else
        gLibs.fGLLib = DynamicLoadLibrary("libGLESv2.so");
        gLibs.fEGLLib = DynamicLoadLibrary("libEGL.so");
#endif
    }

    if (nullptr == gLibs.fGLLib || nullptr == gLibs.fEGLLib) {
        // We can't setup the interface correctly w/o the so
        return nullptr;
    }

    return GrGLAssembleGLESInterface(&gLibs, angle_get_gl_proc);
}
<|endoftext|>