<commit_before>/*  ----------------------------------------------------------------
 Copyright 2016 Cisco Systems

 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.
 ------------------------------------------------------------------*/

#include <string.h>
#include <iostream>

#include <ydk/netconf_provider.hpp>
#include <ydk/netconf_service.hpp>
#include <ydk_ydktest/ydktest_sanity.hpp>
#include <ydk_ydktest/openconfig_bgp.hpp>
#include <ydk_ydktest/openconfig_interfaces.hpp>
#include <ydk/types.hpp>
#include <ydk/common_utilities.hpp>

#include <spdlog/spdlog.h>

#include "config.hpp"
#include "catch.hpp"

using namespace ydk;
using namespace ydktest;
using namespace std;

void print_data_node(shared_ptr<ydk::path::DataNode> dn);
void print_entity(shared_ptr<ydk::Entity> entity, ydk::path::RootSchemaNode& root);

// cancel_commit -- issues in netsim
//TEST_CASE("cancel_commit")
//{
//    // session
//    path::Repository repo{TEST_HOME};
//    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
//    NetconfService ns{};
//
//    auto reply = ns.cancel_commit(session);
//    REQUIRE(reply);
//}

// close_session
TEST_CASE("close_session")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.close_session(provider);
    REQUIRE(reply);
}

// commit
TEST_CASE("commit")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.commit(provider);
    REQUIRE(reply);
}

// copy_config
TEST_CASE("copy_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::running;

    auto reply = ns.copy_config(provider, target, source);
    REQUIRE(reply);
}

// delete_config -- issues in netsim
TEST_CASE("delete_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::url;

//    auto reply = ns.delete_config(session, target, "http://test");
    CHECK_THROWS_AS(ns.delete_config(provider, target, "http://test"), YError);
}

// discard_changes
TEST_CASE("discard_changes")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

TEST_CASE("get_edit_copy_config")
{
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::running;

    // Build filter
    openconfig_interfaces::Interfaces interfaces_filter{};
    openconfig_bgp::Bgp bgp_filter{};
    vector<ydk::Entity*> filter_list{};
    filter_list.push_back(&interfaces_filter);
    filter_list.push_back(&bgp_filter);

    // Read running config
    auto get_config_list = ns.get_config(provider, source, filter_list);

    vector<Entity*> copy_config_list{};
    for (auto ent : get_config_list) {
    	//print_entity(ent, provider.get_session().get_root_schema());
        copy_config_list.push_back(ent.get());
    }

    // Copy config to candidate
    auto result = ns.copy_config(provider, target, copy_config_list);
    REQUIRE(result);

    // Discard changes
    result = ns.discard_changes(provider);
    REQUIRE(result);
}

// edit_config, get_config
TEST_CASE("edit_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::candidate;
    openconfig_bgp::Bgp filter = {};
    openconfig_bgp::Bgp bgp = {};
    bgp.global->config->as = 6500;

    auto reply = ns.edit_config(provider, target, bgp);
    REQUIRE(reply);

    auto data = ns.get_config(provider, source, filter);
    REQUIRE(data);

    auto data_ptr = dynamic_cast<openconfig_bgp::Bgp*>(data.get());
    REQUIRE(data_ptr != nullptr);
    REQUIRE(data_ptr->global->config->as == bgp.global->config->as);

    reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

TEST_CASE("edit_multiple_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::candidate;

    // Create 'native' configuration
    ydktest::ydktest_sanity::Native native{};
    native.hostname = "My Host";
    native.version = "0.1.2";

    // Set the Global AS
    openconfig_bgp::Bgp bgp{};
    bgp.global->config->as = 65051;
    bgp.global->config->router_id = "10.20.30.40";

    // Create entity list
    vector<ydk::Entity*> edit_list{};
    edit_list.push_back(&native);
    edit_list.push_back(&bgp);

    auto reply = ns.edit_config(provider, target, edit_list);
    REQUIRE(reply);

    // Build filter
    ydktest::ydktest_sanity::Native native_filter{};
    openconfig_bgp::Bgp bgp_filter{};
    vector<ydk::Entity*> filter_list{};
    filter_list.push_back(&native_filter);
    filter_list.push_back(&bgp_filter);

    // Read current configuration and print it
    auto read_list = ns.get_config(provider, source, filter_list);
    REQUIRE(read_list.size() == 2);
    for (auto item : read_list) {
        string path = item->get_segment_path();
        if (path.find("bgp") != string::npos) {
            auto data_ptr = dynamic_cast<openconfig_bgp::Bgp*>(item.get());
            REQUIRE(data_ptr != nullptr);
            REQUIRE(data_ptr->global->config->as == bgp.global->config->as);
            REQUIRE(data_ptr->global->config->router_id == bgp.global->config->router_id);
        }
        if (path.find("native") != string::npos) {
            auto data_ptr = dynamic_cast<ydktest::ydktest_sanity::Native*>(item.get());
            REQUIRE(data_ptr != nullptr);
            REQUIRE(data_ptr->hostname == native.hostname);
            REQUIRE(data_ptr->version == native.version);
        }
    }

    // Discard config changes
    reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

// get
TEST_CASE("get")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    openconfig_bgp::Bgp filter = {};

    auto reply = ns.get(provider, filter);
    REQUIRE(reply);
}

// kill_session
TEST_CASE("kill_session")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    int session_id = 3;

//    auto reply = ns.kill_session(session, session_id);
    CHECK_THROWS_AS(ns.kill_session(provider, session_id), YError);
}

// lock, unlock
TEST_CASE("lock")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;

    auto reply = ns.lock(provider, target);
    REQUIRE(reply);

    reply = ns.unlock(provider, target);
    REQUIRE(reply);
}

// validate
TEST_CASE("validate")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore source = DataStore::candidate;

    auto reply = ns.validate(provider, source);
    REQUIRE(reply);
}

// read device configuration (no filter)
TEST_CASE("ietf_get_config_rpc")
{
    path::Repository repo{TEST_HOME};
    ydk::path::NetconfSession session{repo, "127.0.0.1", "admin", "admin",  12022};
    ydk::path::RootSchemaNode& schema = session.get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get-config") };
    read_rpc->get_input_node().create_datanode("source/running");

    auto read_result = (*read_rpc)(session);
    REQUIRE(read_result != nullptr);

    // Print config
    vector<shared_ptr<ydk::path::DataNode>> data_nodes = read_result->get_children();
    for (auto dn : data_nodes) {
        print_data_node(dn);
    }
}

// read device configuration and state (no filter)
TEST_CASE("ietf_get_rpc")
{
    NetconfServiceProvider provider{"127.0.0.1", "admin", "admin", 12022};
    ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get") };

    REQUIRE_THROWS_AS((*read_rpc)(provider.get_session()), ydk::YModelError);
}

TEST_CASE("get_config_openconfig_interfaces_and_bgp")
{
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get") };

    // filter
    openconfig_interfaces::Interfaces interfaces_filter{};
    openconfig_bgp::Bgp bgp_filter{};

    std::string filter_string = get_xml_subtree_filter_payload(interfaces_filter, provider);
    filter_string += "\n" + get_xml_subtree_filter_payload(bgp_filter, provider);

    read_rpc->get_input_node().create_datanode("filter", filter_string);

    auto read_result = (*read_rpc)(provider.get_session());
    REQUIRE(read_result != nullptr);

    // Print config
    vector<shared_ptr<ydk::path::DataNode>> data_nodes = read_result->get_children();
    for (auto dn : data_nodes) {
        print_data_node(dn);
    }
}
<commit_msg>Fixed Travis c++ test<commit_after>/*  ----------------------------------------------------------------
 Copyright 2016 Cisco Systems

 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.
 ------------------------------------------------------------------*/

#include <string.h>
#include <iostream>

#include <ydk/netconf_provider.hpp>
#include <ydk/netconf_service.hpp>
#include <ydk_ydktest/ydktest_sanity.hpp>
#include <ydk_ydktest/openconfig_bgp.hpp>
#include <ydk_ydktest/openconfig_interfaces.hpp>
#include <ydk/types.hpp>
#include <ydk/common_utilities.hpp>

#include <spdlog/spdlog.h>

#include "config.hpp"
#include "catch.hpp"

using namespace ydk;
using namespace ydktest;
using namespace std;

void print_data_node(shared_ptr<ydk::path::DataNode> dn);
void print_entity(shared_ptr<ydk::Entity> entity, ydk::path::RootSchemaNode& root);

// cancel_commit -- issues in netsim
//TEST_CASE("cancel_commit")
//{
//    // session
//    path::Repository repo{TEST_HOME};
//    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
//    NetconfService ns{};
//
//    auto reply = ns.cancel_commit(session);
//    REQUIRE(reply);
//}

// close_session
TEST_CASE("close_session")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.close_session(provider);
    REQUIRE(reply);
}

// commit
TEST_CASE("commit")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.commit(provider);
    REQUIRE(reply);
}

// copy_config
TEST_CASE("copy_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::running;

    auto reply = ns.copy_config(provider, target, source);
    REQUIRE(reply);
}

// delete_config -- issues in netsim
TEST_CASE("delete_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::url;

//    auto reply = ns.delete_config(session, target, "http://test");
    CHECK_THROWS_AS(ns.delete_config(provider, target, "http://test"), YError);
}

// discard_changes
TEST_CASE("discard_changes")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    auto reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

TEST_CASE("get_edit_copy_config")
{
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::running;

    // Build filter
    openconfig_interfaces::Interfaces interfaces_filter{};
    openconfig_bgp::Bgp bgp_filter{};
    vector<ydk::Entity*> filter_list{};
    filter_list.push_back(&interfaces_filter);
    filter_list.push_back(&bgp_filter);

    // Read running config
    auto get_config_list = ns.get_config(provider, source, filter_list);

    vector<Entity*> copy_config_list{};
    for (auto ent : get_config_list) {
    	//print_entity(ent, provider.get_session().get_root_schema());
        copy_config_list.push_back(ent.get());
    }

    // Copy config to candidate
    auto result = ns.copy_config(provider, target, copy_config_list);
    REQUIRE(result);

    // Discard changes
    result = ns.discard_changes(provider);
    REQUIRE(result);
}

// edit_config, get_config
TEST_CASE("edit_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::candidate;
    openconfig_bgp::Bgp filter = {};
    openconfig_bgp::Bgp bgp = {};
    bgp.global->config->as = 6500;

    auto reply = ns.edit_config(provider, target, bgp);
    REQUIRE(reply);

    auto data = ns.get_config(provider, source, filter);
    REQUIRE(data);

    auto data_ptr = dynamic_cast<openconfig_bgp::Bgp*>(data.get());
    REQUIRE(data_ptr != nullptr);
    REQUIRE(data_ptr->global->config->as == bgp.global->config->as);

    reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

TEST_CASE("edit_multiple_config")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;
    DataStore source = DataStore::candidate;

    // Create 'native' configuration
    ydktest::ydktest_sanity::Native native{};
    native.hostname = "My Host";
    native.version = "0.1.2";

    // Set the Global AS
    openconfig_bgp::Bgp bgp{};
    bgp.global->config->as = 65051;
    bgp.global->config->router_id = "10.20.30.40";

    // Create entity list
    vector<ydk::Entity*> edit_list{};
    edit_list.push_back(&native);
    edit_list.push_back(&bgp);

    auto reply = ns.edit_config(provider, target, edit_list);
    REQUIRE(reply);

    // Build filter
    ydktest::ydktest_sanity::Native native_filter{};
    openconfig_bgp::Bgp bgp_filter{};
    vector<ydk::Entity*> filter_list{};
    filter_list.push_back(&native_filter);
    filter_list.push_back(&bgp_filter);

    // Read current configuration and print it
    auto read_list = ns.get_config(provider, source, filter_list);
    REQUIRE(read_list.size() == 2);
    for (auto item : read_list) {
        string path = item->get_segment_path();
        if (path.find("bgp") != string::npos) {
            auto data_ptr = dynamic_cast<openconfig_bgp::Bgp*>(item.get());
            REQUIRE(data_ptr != nullptr);
            REQUIRE(data_ptr->global->config->as == bgp.global->config->as);
            REQUIRE(data_ptr->global->config->router_id == bgp.global->config->router_id);
        }
        if (path.find("native") != string::npos) {
            auto data_ptr = dynamic_cast<ydktest::ydktest_sanity::Native*>(item.get());
            REQUIRE(data_ptr != nullptr);
            REQUIRE(data_ptr->hostname == native.hostname);
            REQUIRE(data_ptr->version == native.version);
        }
    }

    // Discard config changes
    reply = ns.discard_changes(provider);
    REQUIRE(reply);
}

// get
TEST_CASE("get")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    openconfig_bgp::Bgp filter = {};

    auto reply = ns.get(provider, filter);
    REQUIRE(reply);
}

// kill_session
TEST_CASE("kill_session")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    int session_id = 3;

//    auto reply = ns.kill_session(session, session_id);
    CHECK_THROWS_AS(ns.kill_session(provider, session_id), YError);
}

// lock, unlock
TEST_CASE("lock")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore target = DataStore::candidate;

    auto reply = ns.lock(provider, target);
    REQUIRE(reply);

    reply = ns.unlock(provider, target);
    REQUIRE(reply);
}

// validate
TEST_CASE("validate")
{
    // session
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    NetconfService ns{};

    DataStore source = DataStore::candidate;

    auto reply = ns.validate(provider, source);
    REQUIRE(reply);
}

// read device configuration (no filter)
TEST_CASE("ietf_get_config_rpc")
{
    path::Repository repo{TEST_HOME};
    ydk::path::NetconfSession session{repo, "127.0.0.1", "admin", "admin",  12022};
    ydk::path::RootSchemaNode& schema = session.get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get-config") };
    read_rpc->get_input_node().create_datanode("source/running");

    auto read_result = (*read_rpc)(session);
    REQUIRE(read_result != nullptr);

    // Print config
    vector<shared_ptr<ydk::path::DataNode>> data_nodes = read_result->get_children();
    for (auto dn : data_nodes) {
        print_data_node(dn);
    }
}

// read device configuration and state (no filter)
TEST_CASE("ietf_get_rpc")
{
    NetconfServiceProvider provider{"127.0.0.1", "admin", "admin", 12022};
    ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get") };
    try {
        (*read_rpc)(provider.get_session());
    }
    catch (YModelError ex) {
        cout << "Exception while executing RPC: " << ex.what() << endl;
    }
}

TEST_CASE("get_config_openconfig_interfaces_and_bgp")
{
    path::Repository repo{TEST_HOME};
    NetconfServiceProvider provider{repo, "127.0.0.1", "admin", "admin", 12022};
    ydk::path::RootSchemaNode& schema = provider.get_session().get_root_schema();

    std::shared_ptr<ydk::path::Rpc> read_rpc { schema.create_rpc("ietf-netconf:get") };

    // filter
    openconfig_interfaces::Interfaces interfaces_filter{};
    openconfig_bgp::Bgp bgp_filter{};

    std::string filter_string = get_xml_subtree_filter_payload(interfaces_filter, provider);
    filter_string += "\n" + get_xml_subtree_filter_payload(bgp_filter, provider);

    read_rpc->get_input_node().create_datanode("filter", filter_string);

    auto read_result = (*read_rpc)(provider.get_session());
    REQUIRE(read_result != nullptr);

    // Print config
    vector<shared_ptr<ydk::path::DataNode>> data_nodes = read_result->get_children();
    for (auto dn : data_nodes) {
        print_data_node(dn);
    }
}
<|endoftext|>


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

  Program: Visomics

  Copyright (c) Kitware, Inc.

  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.

=========================================================================*/

// Qt includes
#include <QDebug>
#include <QList>
#include <QScriptEngine>
#include <QScriptValue>

// Visomics includes
#include "voDataObject.h"
#include "voKMeansClusteringDynView.h"
#include "voUtils.h"

// VTK includes
#include <vtkIntArray.h>
#include <vtkTable.h>

// --------------------------------------------------------------------------
class voKMeansClusteringDynViewPrivate
{
public:
  voKMeansClusteringDynViewPrivate();
};

// --------------------------------------------------------------------------
// voKMeansClusteringDynViewPrivate methods

// --------------------------------------------------------------------------
voKMeansClusteringDynViewPrivate::voKMeansClusteringDynViewPrivate()
{
}

// --------------------------------------------------------------------------
// voKMeansClusteringDynView methods

// --------------------------------------------------------------------------
voKMeansClusteringDynView::voKMeansClusteringDynView(QWidget * newParent):
    Superclass(newParent), d_ptr(new voKMeansClusteringDynViewPrivate)
{
}

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

namespace
{

// --------------------------------------------------------------------------
QScriptValue scriptValueFromCluster(QScriptEngine* scriptEngine, vtkTable * clusterTable, int clusterId)
{
  QScriptValue clusterChildren = scriptEngine->newArray();
  quint32 childCount = 0;
  for(vtkIdType cid = 1; cid < clusterTable->GetNumberOfColumns() ; ++cid)
    {
    vtkIntArray * currentColumn = vtkIntArray::SafeDownCast(clusterTable->GetColumn(cid));
    int currentValue = currentColumn->GetValue(0);
    if (currentValue == clusterId)
      {
      QScriptValue clusterChild = scriptEngine->newObject();
      clusterChild.setProperty("name", QScriptValue(currentColumn->GetName()));
      clusterChildren.setProperty(childCount, clusterChild);
      ++childCount;
      }
    }
  return clusterChildren;
}

// --------------------------------------------------------------------------
QScriptValue scriptValueFromClusters(QScriptEngine* scriptEngine, vtkTable * clusterTable, quint32 kmeansCenters)
{
  QScriptValue array = scriptEngine->newArray();
  QScriptValueList::const_iterator it;
  for (quint32 i = 0; i < kmeansCenters; ++i)
    {
    QScriptValue cluster = scriptEngine->newObject();
    cluster.setProperty("name", QScriptValue(QString("Cluster %1").arg(i + 1)));
    cluster.setProperty("children", scriptValueFromCluster(scriptEngine, clusterTable, i + 1));
    array.setProperty(i, cluster);
    }
  return array;
}

} // end of anonymous namespace

// --------------------------------------------------------------------------
QString voKMeansClusteringDynView::stringify(const voDataObject& dataObject)
{
  vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());
  if (!table)
    {
    qCritical() << "voKMeansClusteringDynView - Failed to setDataObject - vtkTable data is expected !";
    return QString();
    }

  bool ok = false;
  int kmeansCenters = dataObject.property("kmeans_centers").toInt(&ok);
  if (!ok)
    {
    qCritical() << "voKMeansClusteringDynView - Failed to setDataObject - 'kmeans_center' property is expected !";
    return QString();
    }

  QScriptEngine scriptEngine;
  QScriptValue object = scriptEngine.newObject();
  object.setProperty("name", QScriptValue("Clusters"));
  object.setProperty("children", scriptValueFromClusters(&scriptEngine, table, kmeansCenters));

  return voUtils::stringify(&scriptEngine, object);
}
<commit_msg>Cast to vtkAbstractArray rather than vtkIntArray<commit_after>/*=========================================================================

  Program: Visomics

  Copyright (c) Kitware, Inc.

  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.

=========================================================================*/

// Qt includes
#include <QDebug>
#include <QList>
#include <QScriptEngine>
#include <QScriptValue>

// Visomics includes
#include "voDataObject.h"
#include "voKMeansClusteringDynView.h"
#include "voUtils.h"

// VTK includes
#include <vtkAbstractArray.h>
#include <vtkTable.h>

// --------------------------------------------------------------------------
class voKMeansClusteringDynViewPrivate
{
public:
  voKMeansClusteringDynViewPrivate();
};

// --------------------------------------------------------------------------
// voKMeansClusteringDynViewPrivate methods

// --------------------------------------------------------------------------
voKMeansClusteringDynViewPrivate::voKMeansClusteringDynViewPrivate()
{
}

// --------------------------------------------------------------------------
// voKMeansClusteringDynView methods

// --------------------------------------------------------------------------
voKMeansClusteringDynView::voKMeansClusteringDynView(QWidget * newParent):
    Superclass(newParent), d_ptr(new voKMeansClusteringDynViewPrivate)
{
}

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

namespace
{

// --------------------------------------------------------------------------
QScriptValue scriptValueFromCluster(QScriptEngine* scriptEngine, vtkTable * clusterTable, int clusterId)
{
  QScriptValue clusterChildren = scriptEngine->newArray();
  quint32 childCount = 0;

  for(vtkIdType cid = 1; cid < clusterTable->GetNumberOfColumns() ; ++cid)
    {

    vtkAbstractArray * currentColumn = vtkAbstractArray::SafeDownCast(clusterTable->GetColumn(cid));
    int currentValue = currentColumn->GetVariantValue(0).ToInt();
    if (currentValue == clusterId)
      {
      QScriptValue clusterChild = scriptEngine->newObject();
      clusterChild.setProperty("name", QScriptValue(currentColumn->GetName()));
      clusterChildren.setProperty(childCount, clusterChild);
      ++childCount;
      }
    }
  return clusterChildren;
}

// --------------------------------------------------------------------------
QScriptValue scriptValueFromClusters(QScriptEngine* scriptEngine, vtkTable * clusterTable, quint32 kmeansCenters)
{
  QScriptValue array = scriptEngine->newArray();
  QScriptValueList::const_iterator it;
  for (quint32 i = 0; i < kmeansCenters; ++i)
    {
    QScriptValue cluster = scriptEngine->newObject();
    cluster.setProperty("name", QScriptValue(QString("Cluster %1").arg(i + 1)));
    cluster.setProperty("children", scriptValueFromCluster(scriptEngine, clusterTable, i + 1));
    array.setProperty(i, cluster);
    }
  return array;
}

} // end of anonymous namespace

// --------------------------------------------------------------------------
QString voKMeansClusteringDynView::stringify(const voDataObject& dataObject)
{
  vtkTable * table = vtkTable::SafeDownCast(dataObject.dataAsVTKDataObject());
  if (!table)
    {
    qCritical() << "voKMeansClusteringDynView - Failed to setDataObject - vtkTable data is expected !";
    return QString();
    }

  bool ok = false;
  int kmeansCenters = dataObject.property("kmeans_centers").toInt(&ok);
  if (!ok)
    {
    qCritical() << "voKMeansClusteringDynView - Failed to setDataObject - 'kmeans_center' property is expected !";
    return QString();
    }

  QScriptEngine scriptEngine;
  QScriptValue object = scriptEngine.newObject();
  object.setProperty("name", QScriptValue("Clusters"));
  object.setProperty("children", scriptValueFromClusters(&scriptEngine, table, kmeansCenters));

  return voUtils::stringify(&scriptEngine, object);
}
<|endoftext|>


<commit_before>#include "chs.hpp"

CHS::CHS()
{
cylinder=0,head=0,sector=0,
spt=63,tpc=255;
}

CHS::CHS(int c,int h,int s)
{
cylinder=c,head=h,sector=s,

spt=63,tpc=255;
}

CHS::CHS(long long lba)
{
spt=63,tpc=255;
calc(lba);

}

void CHS::calc(long long lba)
{
long long temp;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

}

bool CHS::SetCylinder(long long cylinder)
{
   this->cylinder=cylinder;
   return true;
}

bool CHS::SetHead(unsigned int head)
{
   if(head>tpc) return false;
   this->head=head;
   return true;
}

bool CHS::SetSector(unsigned int sector)
{
   if(head>spt) return false;
   this->sector=sector;
   return true;
}

unsigned long CHS::GetCylinder()
{
  return this->cylinder;
}
unsigned int CHS::GetHead()
{
  return this->head;
}
unsigned int CHS::GetSector()
{
   return this->sector;
}

bool CHS::SetGeometry(int spt,int tpc)
{
  this->spt=spt;
  this->tpc=tpc;
return true;
}

int CHS::GetSPT() { return spt; }
int CHS::GetTPC() { return tpc; }

void CHS::SetSPT(int spt)
{
long long old_lba=ToLBA();
this->spt=spt;
calc(old_lba);
}
void CHS::SetTPC(int tpc)
{
long long old_lba=ToLBA();
this->tpc=tpc;
 calc(old_lba);

}

long long CHS::ToLBA()
{
 return ( ( cylinder * tpc + head ) * spt ) + sector - 1;
}

CHS &CHS::operator =(long long lba)
{
unsigned long temp;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return *this;
}

bool CHS::operator ==(CHS &chs)
{
if(this->ToLBA()==chs.ToLBA())
    return true;

return false;
}

CHS &CHS::operator ++()
{
unsigned long temp;
long long lba=this->ToLBA()+1;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return *this;
}

CHS &CHS::operator ++(int)
{
CHS ret=*this;

unsigned long temp;
long long lba=this->ToLBA()+1;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return ret;
}

<commit_msg>Added MBR_CHS CHS::ToMbrChs() function<commit_after>#include "chs.hpp"
#include "definitions.h"

CHS::CHS()
{
cylinder=0,head=0,sector=0,
spt=63,tpc=255;
}

CHS::CHS(int c,int h,int s)
{
cylinder=c,head=h,sector=s,

spt=63,tpc=255;
}

CHS::CHS(long long lba)
{
spt=63,tpc=255;
calc(lba);

}

void CHS::calc(long long lba)
{
long long temp;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

}

bool CHS::SetCylinder(long long cylinder)
{
   this->cylinder=cylinder;
   return true;
}

bool CHS::SetHead(unsigned int head)
{
   if(head>tpc) return false;
   this->head=head;
   return true;
}

bool CHS::SetSector(unsigned int sector)
{
   if(head>spt) return false;
   this->sector=sector;
   return true;
}

unsigned long CHS::GetCylinder()
{
  return this->cylinder;
}
unsigned int CHS::GetHead()
{
  return this->head;
}
unsigned int CHS::GetSector()
{
   return this->sector;
}

bool CHS::SetGeometry(int spt,int tpc)
{
  this->spt=spt;
  this->tpc=tpc;
return true;
}

int CHS::GetSPT() { return spt; }
int CHS::GetTPC() { return tpc; }

void CHS::SetSPT(int spt)
{
long long old_lba=ToLBA();
this->spt=spt;
calc(old_lba);
}
void CHS::SetTPC(int tpc)
{
long long old_lba=ToLBA();
this->tpc=tpc;
 calc(old_lba);

}

long long CHS::ToLBA()
{
 return ( ( cylinder * tpc + head ) * spt ) + sector - 1;
}

MBR_CHS CHS::ToMbrChs()
{
  MBR_CHS chs= {0};

  if(ToLBA()>=CHS_LIMIT)
  {
    chs.cylinder_bits=1023>>8;
    chs.cylinder=1023&0xFF;

    chs.head=254;
    chs.sector=63;
    return chs;
  }

  unsigned cylinder,head,sector,temp=0;

  cylinder =ToLBA()/ (tpc * spt);
  temp     = ToLBA() % (tpc * spt);
  head     = temp / spt;
  sector   = temp % spt + 1;

  chs.cylinder_bits=cylinder>>8;
  chs.cylinder=cylinder&0xFF;

  chs.head=head;
  chs.sector=sector;

  return chs;
}

CHS &CHS::operator =(long long lba)
{
unsigned long temp;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return *this;
}

bool CHS::operator ==(CHS &chs)
{
if(this->ToLBA()==chs.ToLBA())
    return true;

return false;
}

CHS &CHS::operator ++()
{
unsigned long temp;
long long lba=this->ToLBA()+1;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return *this;
}

CHS &CHS::operator ++(int)
{
CHS ret=*this;

unsigned long temp;
long long lba=this->ToLBA()+1;

cylinder =lba / (tpc * spt);
temp     = lba % (tpc * spt);
head     = temp / spt;
sector   = temp % spt + 1;

return ret;
}

<|endoftext|>


<commit_before>/*
* This file is part of PyMesh.
*
* PyMesh is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PyMesh is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*
*/

#ifndef PYMESHPLUGIN_HH
#define PYMESHPLUGIN_HH

#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/pytypes.h>

#include <QObject>

#include <OpenFlipper/BasePlugin/BaseInterface.hh>
#include <OpenFlipper/BasePlugin/LoggingInterface.hh>
#include <OpenFlipper/BasePlugin/ToolboxInterface.hh>
#include <OpenFlipper/BasePlugin/LoadSaveInterface.hh>
#include <OpenFlipper/BasePlugin/BackupInterface.hh>
#include <OpenFlipper/BasePlugin/ProcessInterface.hh>
#include <OpenFlipper/BasePlugin/ScriptInterface.hh>
#include <OpenFlipper/BasePlugin/RPCInterface.hh>

#include <ObjectTypes/PolyMesh/PolyMesh.hh>
#include <ObjectTypes/TriangleMesh/TriangleMesh.hh>

#include <vector>

#include "PyMeshToolbox.hh"

class PyMeshPlugin : public QObject, BaseInterface, ToolboxInterface, LoadSaveInterface, LoggingInterface, BackupInterface, ProcessInterface, ScriptInterface, RPCInterface
{
  Q_OBJECT
  Q_INTERFACES(BaseInterface)
  Q_INTERFACES(ToolboxInterface)
  Q_INTERFACES(LoadSaveInterface)
  Q_INTERFACES(LoggingInterface)
  Q_INTERFACES(BackupInterface)
  Q_INTERFACES(ProcessInterface)
  Q_INTERFACES(ScriptInterface)
  Q_INTERFACES(RPCInterface)
  Q_PLUGIN_METADATA(IID "org.OpenFlipper.Plugins.Plugin-PyMesh")

Q_SIGNALS:

  // Base Interface
  void updatedObject(int _identifier, const UpdateType& _type);

  // Toolbox Interface
  void addToolbox(QString  _name, QWidget* _widget , QIcon* _icon);

  // Load-Save Interface
  void addEmptyObject(DataType _type, int& _id);
  void deleteObject(int _id);

  // Logging Interface
  void log(Logtype _type, QString _message);
  void log(QString _message);

  // Process Interface
  void setJobDescription(QString _jobId, QString _text);
  void startJob(QString _jobId, QString _description, int _min, int _max, bool _blocking = false);
  void finishJob(QString _jobId);

  // Script Interface
  void getAvailableFunctions(QStringList& _functions);
  void getDescription(QString _function, QString& _description, QStringList& _parameters, QStringList& _descriptions);

  // Backup Interface
  void createBackup(int _objectid, QString _name, UpdateType _type = UPDATE_ALL);

public Q_SLOTS:

  bool runPyScriptFile(const QString& _filename, bool _clearPrevious);
  void runPyScriptFileAsync(const QString& _filename, bool _clearPrevious);

  bool runPyScript(const QString& _script, bool _clearPrevious);
  void runPyScriptAsync(const QString& _script, bool _clearPrevious);

  void convertPropsPyToCpp(const IdList& _list);

  void resetInterpreter();

public:

  // Python callback functions
  void pyOutput(const char* w);
  void pyError(const char* w);
  void* createTriMesh();
  void* createPolyMesh();

  PyMeshPlugin();
  ~PyMeshPlugin();

  QString name(){return QString("PyMesh");}
  QString description(){return QString("Run OpenMesh Python Scripts and shows the resulting mesh.");}

private:

    pybind11::module main_module_;
    PyObject* global_dict_clean_ = nullptr; //clean global dict. used for reset. do not change

    PyMeshToolbox* toolbox_ = nullptr;
    std::vector<int> createdObjects_;

    QWidget* scriptingFunctionsPresenter_ = nullptr;

    void initPython();
    /// Run Python Script. Does not update any object. save to call from another thread
    bool runPyScript_internal(const QString& _script, bool _clearPrevious);
    /// Does not update all objects, save to call from another thread
    void convertPropsPyToCpp_internal(const IdList& _list);

private Q_SLOTS:

  void initializePlugin();

  void pluginsInitialized();

  void slotRunScript();

  void slotSelectFile();

  void canceledJob(QString _job);

  void runPyScriptFinished();

  void noguiSupported() {};

  void showScriptingFunctions();

public Q_SLOTS:
  QString version(){ return QString("1.0"); }
};

#endif //PYMESHPLUGIN_HH
<commit_msg>increased version number<commit_after>/*
* This file is part of PyMesh.
*
* PyMesh is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PyMesh is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*
*/

#ifndef PYMESHPLUGIN_HH
#define PYMESHPLUGIN_HH

#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/pytypes.h>

#include <QObject>

#include <OpenFlipper/BasePlugin/BaseInterface.hh>
#include <OpenFlipper/BasePlugin/LoggingInterface.hh>
#include <OpenFlipper/BasePlugin/ToolboxInterface.hh>
#include <OpenFlipper/BasePlugin/LoadSaveInterface.hh>
#include <OpenFlipper/BasePlugin/BackupInterface.hh>
#include <OpenFlipper/BasePlugin/ProcessInterface.hh>
#include <OpenFlipper/BasePlugin/ScriptInterface.hh>
#include <OpenFlipper/BasePlugin/RPCInterface.hh>

#include <ObjectTypes/PolyMesh/PolyMesh.hh>
#include <ObjectTypes/TriangleMesh/TriangleMesh.hh>

#include <vector>

#include "PyMeshToolbox.hh"

class PyMeshPlugin : public QObject, BaseInterface, ToolboxInterface, LoadSaveInterface, LoggingInterface, BackupInterface, ProcessInterface, ScriptInterface, RPCInterface
{
  Q_OBJECT
  Q_INTERFACES(BaseInterface)
  Q_INTERFACES(ToolboxInterface)
  Q_INTERFACES(LoadSaveInterface)
  Q_INTERFACES(LoggingInterface)
  Q_INTERFACES(BackupInterface)
  Q_INTERFACES(ProcessInterface)
  Q_INTERFACES(ScriptInterface)
  Q_INTERFACES(RPCInterface)
  Q_PLUGIN_METADATA(IID "org.OpenFlipper.Plugins.Plugin-PyMesh")

Q_SIGNALS:

  // Base Interface
  void updatedObject(int _identifier, const UpdateType& _type);

  // Toolbox Interface
  void addToolbox(QString  _name, QWidget* _widget , QIcon* _icon);

  // Load-Save Interface
  void addEmptyObject(DataType _type, int& _id);
  void deleteObject(int _id);

  // Logging Interface
  void log(Logtype _type, QString _message);
  void log(QString _message);

  // Process Interface
  void setJobDescription(QString _jobId, QString _text);
  void startJob(QString _jobId, QString _description, int _min, int _max, bool _blocking = false);
  void finishJob(QString _jobId);

  // Script Interface
  void getAvailableFunctions(QStringList& _functions);
  void getDescription(QString _function, QString& _description, QStringList& _parameters, QStringList& _descriptions);

  // Backup Interface
  void createBackup(int _objectid, QString _name, UpdateType _type = UPDATE_ALL);

public Q_SLOTS:

  bool runPyScriptFile(const QString& _filename, bool _clearPrevious);
  void runPyScriptFileAsync(const QString& _filename, bool _clearPrevious);

  bool runPyScript(const QString& _script, bool _clearPrevious);
  void runPyScriptAsync(const QString& _script, bool _clearPrevious);

  void convertPropsPyToCpp(const IdList& _list);

  void resetInterpreter();

public:

  // Python callback functions
  void pyOutput(const char* w);
  void pyError(const char* w);
  void* createTriMesh();
  void* createPolyMesh();

  PyMeshPlugin();
  ~PyMeshPlugin();

  QString name(){return QString("PyMesh");}
  QString description(){return QString("Run OpenMesh Python Scripts and shows the resulting mesh.");}

private:

    pybind11::module main_module_;
    PyObject* global_dict_clean_ = nullptr; //clean global dict. used for reset. do not change

    PyMeshToolbox* toolbox_ = nullptr;
    std::vector<int> createdObjects_;

    QWidget* scriptingFunctionsPresenter_ = nullptr;

    void initPython();
    /// Run Python Script. Does not update any object. save to call from another thread
    bool runPyScript_internal(const QString& _script, bool _clearPrevious);
    /// Does not update all objects, save to call from another thread
    void convertPropsPyToCpp_internal(const IdList& _list);

private Q_SLOTS:

  void initializePlugin();

  void pluginsInitialized();

  void slotRunScript();

  void slotSelectFile();

  void canceledJob(QString _job);

  void runPyScriptFinished();

  void noguiSupported() {};

  void showScriptingFunctions();

public Q_SLOTS:
  QString version(){ return QString("2.0"); }
};

#endif //PYMESHPLUGIN_HH
<|endoftext|>


<commit_before>#include "Scene.h"

Scene::Scene(void)
{
	view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));
	memset(&KeyStates, 0, sizeof(KeyStates));
	bbo = new BulletBufferObject(this, 50);
	this->debug = false;
	this->game = true;
	this->score = 0;
}

Scene::~Scene(void)
{
	if (player != 0) delete player;
	for (unsigned int i = 0; i < objects.size(); i++){
		if (objects[i] != 0) delete objects[i];
	}

}
void Scene::Init(GLuint *texture){
	this->texture = texture;

	// Init Player
	this->player = new Player(this, this->texture[0], 0.0f, 0.0f);

	// Init Objects
	AddObstacle(new Obstacle(this, this->texture[2], 15.0, 15.0, 7.00));
	AddObstacle(new Obstacle(this, this->texture[2], -12.0, -17.0, 9.00));
	AddObstacle(new Obstacle(this, this->texture[2], 12.0, -6.0, 5.00));
	AddObstacle(new Obstacle(this, this->texture[2], -16.0, 15.0, 6.00));

	// Init Zombies
	for (unsigned int i = 0; i < ZOMBIE_AMOUNT; ++i) AddZombie(new Zombie(this, this->texture[1]));

	//Init PowerUps
	for (unsigned int i = 0; i < POWERUP_AMOUNT; ++i) AddPowerUp(new PowerUp(this));

	PrintPlayerData();

}

void Scene::PrintResult()
{
	system("cls");
	cout << "---------- RESULT ----------" << endl;
	cout << "Score: " << player->score << endl << endl;
	cout << "Type [R] to restart game" << endl << endl;
}

void Scene::PrintPlayerData()
{

}
string Scene::GetPlayerData()
{
	return player->GetPlayerData();
}

void Scene::Update(double delta_time)
{
	DisplayData();
	if (this->game){
		CheckVictoryCondition();
		bbo->Update(delta_time);
		for (unsigned int i = 0; i < objects.size(); i++)
		{
			objects[i]->Update(delta_time);
		}

		if (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);
		if (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);
		if (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);
		if (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);

		player->Update(delta_time);
	}
	if ((KeyStates['r'] || KeyStates['R']) && !game) Restart();
	if (KeyStates[27]) exit(0); //ESC key quits the game
}

bool Scene::CheckVictoryCondition(void)
{
	if(player->immortality_duration > 0)
		return game;

	for (unsigned int i = 0; i<zombies.size(); ++i)
	{
		if (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)
		{
			if(player->lifes > 0)
			{
				player->Respawn();
			}
			else
			{
				this->game = false;
				PrintResult();
			}
		}
	}

	return game;
}

void Scene::Restart(void){
	this->game = true;
	this->debug = true;
	for (unsigned int i = 0; i < zombies.size(); i++)
	{
		zombies[i]->RandomPosition();
		zombies[i]->aggressive = false;
	}
	this->debug = false;
	player->Reset();
	for(unsigned int i = 0; i < powerups.size(); i++)
	{
		powerups[i]->Respawn();
	}
	PrintPlayerData();
}

string NumberWithSpaces(int n, int m)
{
	stringstream ss;
	ss << n;

	string s = ss.str();

	while(s.size() < m)
		s = " " + s;

	return s;
}

void Scene::Draw(void)
{
	player->Draw();
	bbo->Draw();
	for(unsigned int i = 0; i < objects.size(); i++)
	{
		objects[i]->Draw();
	}

	string rail_info = (player->current_weapon == Player::WEAPON_TYPE::RAIL ? "-> " : "   ");
	rail_info += "Railgun     [" + NumberWithSpaces(player->rail_lvl, 1) +  "] [" + NumberWithSpaces(player->rail_ammo, 4) + "]";

	if(player->current_weapon == Player::WEAPON_TYPE::RAIL)
		glColor3f(1.0f, 1.0f, 1.0f);
	else
		glColor3f(0.2f, 0.2f, 1.0f);
	glRasterPos2f(0.35f, -0.94f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)rail_info.c_str());

	string machine_info = (player->current_weapon == Player::WEAPON_TYPE::MACHINE ? "-> " : "   ");
	machine_info += "Machine gun [" + NumberWithSpaces(player->machine_lvl, 1) +  "] [" + NumberWithSpaces(player->machine_ammo, 4) + "]";

	if(player->current_weapon == Player::WEAPON_TYPE::MACHINE)
		glColor3f(1.0f, 1.0f, 1.0f);
	else
		glColor3f(0.2f, 0.2f, 1.0f);
	glRasterPos2f(0.35f, -0.98f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)machine_info.c_str());

	string lifes_info = "Lifes: " + NumberWithSpaces(player->lifes, 3);
	glColor3f(1.0f, 0.1f, 0.1f);
	glRasterPos2f(-0.99f, -0.90f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)lifes_info.c_str());

	string score_info = "Score: " + NumberWithSpaces(player->score, 3);
	glColor3f(0.3f, 0.8f, 0.8f);
	glRasterPos2f(-0.99f, -0.94f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)score_info.c_str());

	string cash_info = "Cash:  " + NumberWithSpaces(player->cash, 3);
	glColor3f(0.2f, 1.0f, 0.2f);
	glRasterPos2f(-0.99f, -0.98f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)cash_info.c_str());

	string info = "Press [q] to switch weapon";
	glColor3f(0.5f, 0.5f, 0.5f);
	glRasterPos2f(0.30f, 0.96f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());

	info = "Press [e] to upgrade weapon";
	glColor3f(0.5f, 0.5f, 0.5f);
	glRasterPos2f(0.30f, 0.92f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());
}

void Scene::PlayerRotate(glm::vec2 heading)
{
	player->Rotate(heading);

}

void Scene::PlayerShoot(glm::vec2 aim)
{
	player->Shoot(aim);
}

void Scene::KeyState(unsigned char key, bool tf)
{
	KeyStates[key] = tf;

	if(key == 'q' && tf)
	{
		if(player->current_weapon == Player::WEAPON_TYPE::RAIL)
			player->current_weapon = Player::WEAPON_TYPE::MACHINE;
		else
			player->current_weapon = Player::WEAPON_TYPE::RAIL;

		PrintPlayerData();
	}
	else if(key == 'e' && tf)
	{
		if(player->current_weapon == Player::WEAPON_TYPE::MACHINE)
			player->UpgradeWeapon(Player::WEAPON_TYPE::MACHINE);
		else
			player->UpgradeWeapon(Player::WEAPON_TYPE::RAIL);
	}
}

void Scene::AddObject(GameEntity *entity)
{
	objects.push_back(entity);
}
void Scene::AddZombie(Zombie *entity)
{
	zombies.push_back(entity);
	objects.push_back(entity);
}
void Scene::AddObstacle(Obstacle *entity)
{
	obstacles.push_back(entity);
	objects.push_back(entity);
}

void Scene::AddPowerUp(PowerUp *entity)
{
	powerups.push_back(entity);
	objects.push_back(entity);
}

ostream& operator<<(ostream &o, const Scene &gw)
{
	o << "---------------- SCENE ---------------" << "\n";

	o << "--------------------------------------" << endl;
	return o;
}

void Scene::DisplayData()
{
	string str;
	stringstream ss;

	ss << "Lifes: " << player->lifes << endl;
	str = "";
	ss >> str;

	//glRasterPos2i(0, 0);
	//glColor3f(1, 0, 0);
	//glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, (const unsigned char*)"Dzialaj");

}
<commit_msg>Instruction for Quitting the game<commit_after>#include "Scene.h"

Scene::Scene(void)
{
	view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));
	memset(&KeyStates, 0, sizeof(KeyStates));
	bbo = new BulletBufferObject(this, 50);
	this->debug = false;
	this->game = true;
	this->score = 0;
}

Scene::~Scene(void)
{
	if (player != 0) delete player;
	for (unsigned int i = 0; i < objects.size(); i++){
		if (objects[i] != 0) delete objects[i];
	}

}
void Scene::Init(GLuint *texture){
	this->texture = texture;

	// Init Player
	this->player = new Player(this, this->texture[0], 0.0f, 0.0f);

	// Init Objects
	AddObstacle(new Obstacle(this, this->texture[2], 15.0, 15.0, 7.00));
	AddObstacle(new Obstacle(this, this->texture[2], -12.0, -17.0, 9.00));
	AddObstacle(new Obstacle(this, this->texture[2], 12.0, -6.0, 5.00));
	AddObstacle(new Obstacle(this, this->texture[2], -16.0, 15.0, 6.00));

	// Init Zombies
	for (unsigned int i = 0; i < ZOMBIE_AMOUNT; ++i) AddZombie(new Zombie(this, this->texture[1]));

	//Init PowerUps
	for (unsigned int i = 0; i < POWERUP_AMOUNT; ++i) AddPowerUp(new PowerUp(this));

	PrintPlayerData();

}

void Scene::PrintResult()
{
	system("cls");
	cout << "---------- RESULT ----------" << endl;
	cout << "Score: " << player->score << endl << endl;
	cout << "Type [R] to restart game" << endl << endl;
}

void Scene::PrintPlayerData()
{

}
string Scene::GetPlayerData()
{
	return player->GetPlayerData();
}

void Scene::Update(double delta_time)
{
	DisplayData();
	if (this->game){
		CheckVictoryCondition();
		bbo->Update(delta_time);
		for (unsigned int i = 0; i < objects.size(); i++)
		{
			objects[i]->Update(delta_time);
		}

		if (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);
		if (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);
		if (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);
		if (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);

		player->Update(delta_time);
	}
	if ((KeyStates['r'] || KeyStates['R']) && !game) Restart();
	if (KeyStates[27]) exit(0); //ESC key quits the game
}

bool Scene::CheckVictoryCondition(void)
{
	if(player->immortality_duration > 0)
		return game;

	for (unsigned int i = 0; i<zombies.size(); ++i)
	{
		if (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)
		{
			if(player->lifes > 0)
			{
				player->Respawn();
			}
			else
			{
				this->game = false;
				PrintResult();
			}
		}
	}

	return game;
}

void Scene::Restart(void){
	this->game = true;
	this->debug = true;
	for (unsigned int i = 0; i < zombies.size(); i++)
	{
		zombies[i]->RandomPosition();
		zombies[i]->aggressive = false;
	}
	this->debug = false;
	player->Reset();
	for(unsigned int i = 0; i < powerups.size(); i++)
	{
		powerups[i]->Respawn();
	}
	PrintPlayerData();
}

string NumberWithSpaces(int n, int m)
{
	stringstream ss;
	ss << n;

	string s = ss.str();

	while(s.size() < m)
		s = " " + s;

	return s;
}

void Scene::Draw(void)
{
	player->Draw();
	bbo->Draw();
	for(unsigned int i = 0; i < objects.size(); i++)
	{
		objects[i]->Draw();
	}

	string rail_info = (player->current_weapon == Player::WEAPON_TYPE::RAIL ? "-> " : "   ");
	rail_info += "Railgun     [" + NumberWithSpaces(player->rail_lvl, 1) +  "] [" + NumberWithSpaces(player->rail_ammo, 4) + "]";

	if(player->current_weapon == Player::WEAPON_TYPE::RAIL)
		glColor3f(1.0f, 1.0f, 1.0f);
	else
		glColor3f(0.2f, 0.2f, 1.0f);
	glRasterPos2f(0.35f, -0.94f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)rail_info.c_str());

	string machine_info = (player->current_weapon == Player::WEAPON_TYPE::MACHINE ? "-> " : "   ");
	machine_info += "Machine gun [" + NumberWithSpaces(player->machine_lvl, 1) +  "] [" + NumberWithSpaces(player->machine_ammo, 4) + "]";

	if(player->current_weapon == Player::WEAPON_TYPE::MACHINE)
		glColor3f(1.0f, 1.0f, 1.0f);
	else
		glColor3f(0.2f, 0.2f, 1.0f);
	glRasterPos2f(0.35f, -0.98f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)machine_info.c_str());

	string lifes_info = "Lifes: " + NumberWithSpaces(player->lifes, 3);
	glColor3f(1.0f, 0.1f, 0.1f);
	glRasterPos2f(-0.99f, -0.90f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)lifes_info.c_str());

	string score_info = "Score: " + NumberWithSpaces(player->score, 3);
	glColor3f(0.3f, 0.8f, 0.8f);
	glRasterPos2f(-0.99f, -0.94f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)score_info.c_str());

	string cash_info = "Cash:  " + NumberWithSpaces(player->cash, 3);
	glColor3f(0.2f, 1.0f, 0.2f);
	glRasterPos2f(-0.99f, -0.98f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)cash_info.c_str());

	string info = "Press [ESC] to quit";
	glColor3f(0.5f, 0.5f, 0.5f);
	glRasterPos2f(-0.95f, 0.96f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());

	info = "Press [q] to switch weapon";
	glColor3f(0.5f, 0.5f, 0.5f);
	glRasterPos2f(0.30f, 0.96f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());

	info = "Press [e] to upgrade weapon";
	glColor3f(0.5f, 0.5f, 0.5f);
	glRasterPos2f(0.30f, 0.92f);
	glutBitmapString(GLUT_BITMAP_9_BY_15, (const unsigned char*)info.c_str());
}

void Scene::PlayerRotate(glm::vec2 heading)
{
	player->Rotate(heading);

}

void Scene::PlayerShoot(glm::vec2 aim)
{
	player->Shoot(aim);
}

void Scene::KeyState(unsigned char key, bool tf)
{
	KeyStates[key] = tf;

	if(key == 'q' && tf)
	{
		if(player->current_weapon == Player::WEAPON_TYPE::RAIL)
			player->current_weapon = Player::WEAPON_TYPE::MACHINE;
		else
			player->current_weapon = Player::WEAPON_TYPE::RAIL;

		PrintPlayerData();
	}
	else if(key == 'e' && tf)
	{
		if(player->current_weapon == Player::WEAPON_TYPE::MACHINE)
			player->UpgradeWeapon(Player::WEAPON_TYPE::MACHINE);
		else
			player->UpgradeWeapon(Player::WEAPON_TYPE::RAIL);
	}
}

void Scene::AddObject(GameEntity *entity)
{
	objects.push_back(entity);
}
void Scene::AddZombie(Zombie *entity)
{
	zombies.push_back(entity);
	objects.push_back(entity);
}
void Scene::AddObstacle(Obstacle *entity)
{
	obstacles.push_back(entity);
	objects.push_back(entity);
}

void Scene::AddPowerUp(PowerUp *entity)
{
	powerups.push_back(entity);
	objects.push_back(entity);
}

ostream& operator<<(ostream &o, const Scene &gw)
{
	o << "---------------- SCENE ---------------" << "\n";

	o << "--------------------------------------" << endl;
	return o;
}

void Scene::DisplayData()
{
	string str;
	stringstream ss;

	ss << "Lifes: " << player->lifes << endl;
	str = "";
	ss >> str;

	//glRasterPos2i(0, 0);
	//glColor3f(1, 0, 0);
	//glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24, (const unsigned char*)"Dzialaj");

}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkManualSegmentationToSurfaceFilter.h"
#include <itksys/SystemTools.hxx>
#include "mitkDataTreeNodeFactory.h"
#include <mitkSurfaceVtkWriter.h>
#include <vtkSTLWriter.h>

#include <fstream>
/**
* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface
* 1. Read an image
* 2. Create a surface
* 3. Create a Surface with all image processing facillities
*/
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{

  if(argc==0)
  {
    std::cout<<"no file specified [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::string path = argv[1];
  itksys::SystemTools::ConvertToUnixSlashes(path);
  std::string fileIn = path;
  std::string fileOut = "BallBinary30x30x30.stl";

  fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str());
  fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str());
  std::cout<<"Eingabe Datei: "<<fileIn<<std::endl;
  std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl;
  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    std::cout << "Loading file: "<<std::flush;
    factory->SetFileName( fileIn.c_str() );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      std::cout<<"file could not be loaded [FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch ( itk::ExceptionObject & ex )
  {
    std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
  std::cout << "Instantiat mitk::ManualSegmentationToSurfaceFilter - implicit: mitk::ImageToSurface: ";
  filter = mitk::ManualSegmentationToSurfaceFilter::New();

  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //Wirter instance
  mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New();
  if (filter.IsNull())
  {
    std::cout<<"Instantiat SurfaceVtkWirter: [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
    writer->GlobalWarningDisplayOn();
    writer->SetFileName(fileOut.c_str());
    writer->GetVtkWriter()->SetFileTypeToBinary();

  }

  std::cout << "Create surface with default settings: ";
  if (image->GetDimension()==3)
  {
    filter->SetInput(image);
    filter->Update();
    writer->SetInput(filter->GetOutput());
    writer->Write();

    if( writer->GetNumberOfInputs() < 1 )
    {
      std::cout<<"[FAILED]"<<std::endl;
      writer->Delete();
      return EXIT_FAILURE;
    }
    else
    {
      std::cout<<"[PASSED]"<<std::endl;
    }

    std::cout << "Create surface all optimised settings: ";
    //configure ImageToSurfaceFilter
    filter->MedianFilter3DOn();
    filter->SetGaussianStandardDeviation(1.5);
    filter->InterpolationOn();
    filter->UseGaussianImageSmoothOn();
    filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube
    filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );
    filter->SetTargetReduction(0.05f);
    filter->SmoothOn();

    //filter->Update();
    writer->SetInput( filter->GetOutput() );
    if( writer->GetNumberOfInputs() < 1 )
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
    {
      std::cout<<"[PASSED]"<<std::endl;
      writer->Write();
    }
  }
  else
  {
    std::cout<<"Image not suitable for filter: Dimension!=3"<<std::endl;
  }

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}

<commit_msg>COMP: exception handling for writing<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkManualSegmentationToSurfaceFilter.h"
#include <itksys/SystemTools.hxx>
#include "mitkDataTreeNodeFactory.h"
#include <mitkSurfaceVtkWriter.h>
#include <vtkSTLWriter.h>

#include <fstream>
/**
* Test class for ManualSegmentationToSurfaceFilter and ImageToSurface
* 1. Read an image
* 2. Create a surface
* 3. Create a Surface with all image processing facillities
*/
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{

  if(argc==0)
  {
    std::cout<<"no file specified [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::string path = argv[1];
  itksys::SystemTools::ConvertToUnixSlashes(path);
  std::string fileIn = path;
  std::string fileOut = "BallBinary30x30x30.stl";

  fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str());
  fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str());
  std::cout<<"Eingabe Datei: "<<fileIn<<std::endl;
  std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl;
  mitk::Image::Pointer image = NULL;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    std::cout << "Loading file: "<<std::flush;
    factory->SetFileName( fileIn.c_str() );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      std::cout<<"file could not be loaded [FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    image = dynamic_cast<mitk::Image*>(node->GetData());
    if(image.IsNull())
    {
      std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl;
      std::cout<<"[TEST DONE]"<<std::endl;
      return EXIT_SUCCESS;
    }
  }
  catch ( itk::ExceptionObject & ex )
  {
    std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
    return EXIT_FAILURE;
  }

  mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
  std::cout << "Instantiat mitk::ManualSegmentationToSurfaceFilter - implicit: mitk::ImageToSurface: ";
  filter = mitk::ManualSegmentationToSurfaceFilter::New();

  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //Wirter instance
  mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New();
  if (filter.IsNull())
  {
    std::cout<<"Instantiat SurfaceVtkWirter: [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
    writer->GlobalWarningDisplayOn();
    writer->SetFileName(fileOut.c_str());
    writer->GetVtkWriter()->SetFileTypeToBinary();

  }

  std::cout << "Create surface with default settings: ";
  if (image->GetDimension()==3)
  {
    filter->SetInput(image);
    filter->Update();
    writer->SetInput(filter->GetOutput());
    writer->Write();

    if( writer->GetNumberOfInputs() < 1 )
    {
      std::cout<<"[FAILED]"<<std::endl;
      writer->Delete();
      return EXIT_FAILURE;
    }
    else
    {
      std::cout<<"[PASSED]"<<std::endl;
    }

    std::cout << "Create surface all optimised settings: ";
    //configure ImageToSurfaceFilter
    filter->MedianFilter3DOn();
    filter->SetGaussianStandardDeviation(1.5);
    filter->InterpolationOn();
    filter->UseGaussianImageSmoothOn();
    filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube
    filter->SetDecimate( mitk::ImageToSurfaceFilter::DecimatePro );
    filter->SetTargetReduction(0.05f);
    filter->SmoothOn();

    //filter->Update();
    writer->SetInput( filter->GetOutput() );
    if( writer->GetNumberOfInputs() < 1 )
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
    {
      std::cout<<"[PASSED]"<<std::endl;
      try {
        writer->Write();
      }
      catch( itk::ExceptionObject e)
      {
        std::cout<<"caught exception: "<<e<<std::endl;
      }
    }
  }
  else
  {
    std::cout<<"Image not suitable for filter: Dimension!=3"<<std::endl;
  }

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Tasks/SimpleTasks/DamageTask.hpp>

using namespace RosettaStone;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(DamageTask, GetTaskID)
{
    const DamageTask damage(EntityType::ENEMIES, 2);
    EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);
}

TEST(DamageTask, Run)
{
    GameConfig config;
    config.startPlayer = PlayerType::PLAYER1;
    Game game(config);

    Player& player1 = game.GetPlayer1();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (std::size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
    }

    DamageTask damage(EntityType::FRIENDS, 1);
    TaskStatus result = damage.Run(player1);

    EXPECT_EQ(result, TaskStatus::COMPLETE);
    EXPECT_EQ(player1.GetField().GetNumOfMinions(), 0u);
}
<commit_msg>test: Add code to test spell power<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Tasks/PlayerTasks/PlayCardTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/DamageTask.hpp>

using namespace RosettaStone;
using namespace SimpleTasks;
using namespace TestUtils;

TEST(DamageTask, GetTaskID)
{
    const DamageTask damage(EntityType::ENEMIES, 2);
    EXPECT_EQ(damage.GetTaskID(), +TaskID::DAMAGE);
}

TEST(DamageTask, Run)
{
    GameConfig config;
    config.startPlayer = PlayerType::PLAYER1;
    Game game(config);

    Player& player1 = game.GetPlayer1();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (std::size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 1));
        PlayMinionCard(player1, cards[i]);
    }

    DamageTask damage(EntityType::FRIENDS, 1);
    TaskStatus result = damage.Run(player1);

    EXPECT_EQ(result, TaskStatus::COMPLETE);
    EXPECT_EQ(player1.GetField().GetNumOfMinions(), 0u);
}

TEST(DamageTask, SpellPower)
{
    GameConfig config;
    config.startPlayer = PlayerType::PLAYER1;
    Game game(config);

    Player& player1 = game.GetPlayer1();

    std::vector<Card> cards;
    cards.reserve(5);

    const std::string name = "test";
    for (std::size_t i = 0; i < 5; ++i)
    {
        const auto id = static_cast<char>(i + 0x30);
        cards.emplace_back(GenerateMinionCard(name + id, 1, 5));
        PlayMinionCard(player1, cards[i]);
    }

    DamageTask damage1(EntityType::FRIENDS, 1, true);
    damage1.SetSource(player1.GetField().GetMinion(0));
    TaskStatus result = damage1.Run(player1);

    EXPECT_EQ(result, TaskStatus::COMPLETE);
    for (std::size_t i = 0; i < 5; ++i)
    {
        EXPECT_EQ(player1.GetField().GetMinion(i)->health, 4);
    }

    player1.currentSpellPower = 1;

    DamageTask damage2(EntityType::FRIENDS, 1, true);
    damage2.SetSource(player1.GetField().GetMinion(0));
    result = damage2.Run(player1);

    EXPECT_EQ(result, TaskStatus::COMPLETE);
    for (std::size_t i = 0; i < 5; ++i)
    {
        EXPECT_EQ(player1.GetField().GetMinion(i)->health, 2);
    }
}<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include "serialDriver.c"
#include <sstream>      // std::stringstream

class serialListener{
	public:
	ros::NodeHandle handle;
	ros::Publisher arduino;
	std_msgs::String serialmsg;
	std::stringstream read;

	int checklastln(const char* toCheck , int maxLength){
		for(int i=0;i<maxLength;i++){
			if(toCheck[i]==10){
				return 1;
			}
			if(toCheck[i]==0){
				return 0;
			}
		}
	}
	int validatemsg(std::string msg){
		ROS_INFO("SerialListener: validatemsg: %c", msg[0]);
		if(msg[0]=='c'||msg[0]=='w'){
			return 1;
		}
		ROS_INFO("SerialListener: Invalid message received");
		return 0;
	}

	void writeSerial(std::string shit){
		ROS_INFO("SerialListener: Writing to serial line");
		std::stringstream sysCall;
	        sysCall<<"/home/ubuntu/robotica-minor-5/com/arduino-serial/arduino-serial --port=/dev/ttyACM0 --send="<<shit;
		std::string temp= sysCall.str();
		ROS_INFO("serialListener: syscall: %s", temp.c_str());
		system(temp.c_str());
	}

	void poll(){
		ROS_INFO("polling");
		read<<(char*)readline();

		if(read.str()[0]!=0&&read.str()[0]!=10){
			serialmsg.data=read.str();
			ROS_INFO("SerialListener:received data: %s" , read.str().c_str());
			if(checklastln(read.str().c_str(),255)){
				if(validatemsg(read.str())){
					writeSerial("conf");
					arduino.publish(serialmsg);
					read.str("");
				}
			}
		}
	}

	serialListener():handle("~"){
		arduino=handle.advertise<std_msgs::String>("/tawi/arduino/serial",100);
	}
};

int main (int argc, char **argv){
	ros::init(argc, argv, "serialListener");
	serialListener serial;
	ros::Rate hz(5);
	while(ros::ok()){
		serial.poll();
		ros::spinOnce();
		hz.sleep();
	}
}
<commit_msg>Trying to clarify serialListener.poll<commit_after>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include "serialDriver.c"
#include <sstream>      // std::stringstream

class serialListener{
	public:
	ros::NodeHandle handle;
	ros::Publisher arduino;
	std_msgs::String serialmsg;
	std::stringstream read;

	int checklastln(const char* toCheck , int maxLength){
		for(int i=0;i<maxLength;i++){
			if(toCheck[i]==10){
				return 1;
			}
			if(toCheck[i]==0){
				return 0;
			}
		}
	}
	int validatemsg(std::string msg){
		ROS_INFO("SerialListener: validatemsg: %c", msg[0]);
		if(msg[0]=='c'||msg[0]=='w'){
			return 1;
		}
		ROS_INFO("SerialListener: Invalid message received");
		return 0;
	}

	void writeSerial(std::string shit){
		ROS_INFO("SerialListener: Writing to serial line");
		std::stringstream sysCall;
	        sysCall<<"/home/ubuntu/robotica-minor-5/com/arduino-serial/arduino-serial --port=/dev/ttyACM0 --send="<<shit;
		std::string temp= sysCall.str();
		ROS_INFO("serialListener: syscall: %s", temp.c_str());
		system(temp.c_str());
	}

	void poll(){
		read<<(char*)readline();
		ROS_INFO("SerialListener: poll: Read some line");
		if(read.str()[0]!=0&&read.str()[0]!=10){ //what is even going on here
			ROS_INFO("SerialListener: poll: weird ass if statement fullfilled")
			serialmsg.data=read.str();
			ROS_INFO("SerialListener:received data: %s" , read.str().c_str());
			if(checklastln(read.str().c_str(),255)){
				if(validatemsg(read.str())){
					writeSerial("conf");
					arduino.publish(serialmsg);
					read.str("");
				}
			}
		}
	}

	serialListener():handle("~"){
		arduino=handle.advertise<std_msgs::String>("/tawi/arduino/serial",100);
	}
};

int main (int argc, char **argv){
	ros::init(argc, argv, "serialListener");
	serialListener serial;
	ros::Rate hz(5);
	while(ros::ok()){
		serial.poll();
		ros::spinOnce();
		hz.sleep();
	}
}
<|endoftext|>


<commit_before>#include "mitkImageBackground2D.h"
// MITK includes
#include "mitkVtkLayerController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"

// VTK includes
#include "vtkSystemIncludes.h"
#include "vtkRenderer.h"
#include "vtkMapper.h"
#include "vtkObjectFactory.h"
#include "vtkImageActor.h"
#include "vtkRenderWindow.h"
#include "vtkImageImport.h"
#include "vtkCommand.h"
#include "vtkCamera.h"

#include <iostream>

// VTK CALLBACK for automatic resize of the video
class vtkVideoSizeCallback : public vtkCommand
{
public:
  static vtkVideoSizeCallback *New(){ return new vtkVideoSizeCallback; }

  vtkRenderer * m_ImageRenderer;
  int m_ImageWidth, m_ImageHeight;

  void SetVtkVideoRenderer(vtkRenderer* r)
  {
    m_ImageRenderer = r;
  }
  void SetVideoDimensions(int x, int y)
  {
    m_ImageWidth = x; m_ImageHeight = y;
  }

  virtual void Execute(vtkObject* /*caller*/, unsigned long, void*)
  {
    //vtkRenderWindow * RenderWindow = reinterpret_cast<vtkRenderWindow*>(caller);
    //m_ImageRenderer->ResetCameraClippingRange();
  }
};

mitk::ImageBackground2D::ImageBackground2D()
{
  m_ImageWidth              = 720;
  m_ImageHeight             = 576;
  m_ImageScalarComponents   = 3;
  m_ParallelScale           = 0;
  m_RenderWindow = NULL;

  m_Actor             = vtkImageActor::New();
  m_ImageRenderer     = vtkRenderer::New();
  m_VtkImageImport    = vtkImageImport::New();

  m_ImageData         = 0;

  InitVtkImageImport();
}

void mitk::ImageBackground2D::InitVtkImageImport()
{
  m_VtkImageImport->SetDataScalarTypeToUnsignedChar();
  m_VtkImageImport->SetNumberOfScalarComponents(m_ImageScalarComponents);
  m_VtkImageImport->SetWholeExtent(0,m_ImageWidth-1,0,m_ImageHeight-1,0,1-1);
  m_VtkImageImport->SetDataExtentToWholeExtent();
}

mitk::ImageBackground2D::~ImageBackground2D()
{
  if ( m_RenderWindow != NULL )
    if ( this->IsEnabled() )
      this->Disable();
  if ( m_Actor!=NULL )
    m_Actor->Delete();
  if ( m_ImageRenderer != NULL )
    m_ImageRenderer->Delete();
  if ( m_VtkImageImport != NULL)
    m_VtkImageImport->Delete();
}
/**
 * Sets the renderwindow, in which the Video background
 * will be shown. Make sure, you have called this function
 * before calling Enable()
 */
void mitk::ImageBackground2D::SetRenderWindow( const mitk::RenderWindow* renderWindow )
{
  m_RenderWindow = renderWindow;

  /*m_SizeCallback = vtkVideoSizeCallback::New();
  m_RenderWindow->GetVtkRenderWindow()->AddObserver(vtkCommand::ModifiedEvent,m_SizeCallback);*/

}

void mitk::ImageBackground2D::SetParallelScale(int scale)
{
  m_ParallelScale = scale;
  m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ParallelScale);
}
int mitk::ImageBackground2D::GetParallelScale()
{
  // TODO someone who knows this, check if double->int could cause problems
  return static_cast<int>(m_ImageRenderer->GetActiveCamera()->GetParallelScale());
}
/**
 * Enables drawing of the color Video background.
 * If you want to disable it, call the Disable() function.
 */
void mitk::ImageBackground2D::Enable()
{
  m_ImageRenderer = vtkRenderer::New();

  unsigned char * c = 0;
  Update(c);
  m_Actor->SetInput(m_VtkImageImport->GetOutput());

  m_ImageRenderer->AddActor2D(m_Actor);
  m_ImageRenderer->ResetCamera();
  m_ImageRenderer->InteractiveOff();
  m_ImageRenderer->GetActiveCamera()->ParallelProjectionOn();
  if(m_ParallelScale == 0)
    m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ImageHeight/2);

  //m_SizeCallback->SetVtkVideoRenderer(m_ImageRenderer);
  //m_SizeCallback->SetVideoDimensions(m_ImageWidth, m_ImageHeight);
  m_RenderWindow->GetVtkLayerController()->InsertBackgroundRenderer(m_ImageRenderer,true);
}

/**
 * Disables drawing of the color Video background.
 * If you want to enable it, call the Enable() function.
 */
void mitk::ImageBackground2D::Disable()
{
  if ( this->IsEnabled() )
    m_RenderWindow->GetVtkLayerController()->RemoveRenderer(m_ImageRenderer);
}
/**
 * Checks, if the Video background is currently
 * enabled (visible)
 */
bool mitk::ImageBackground2D::IsEnabled()
{
  if ( m_RenderWindow->GetVtkLayerController()->IsRendererInserted(m_ImageRenderer) )
      return true;
  else
      return false;
}

void mitk::ImageBackground2D::Update(unsigned char * datapointer)
{
  if(!IsEnabled())
    return;

  if(!datapointer)
  {// no valid image pointer provided -> initialize black image
    m_ImageData = new unsigned char[m_ImageHeight*m_ImageWidth*m_ImageScalarComponents];
    unsigned char* b = m_ImageData;
    for ( int textCounter = 0; textCounter < (m_ImageHeight*m_ImageWidth*m_ImageScalarComponents); textCounter++ )
      *b++ = 0;
  }

  m_VtkImageImport->SetImportVoidPointer(m_ImageData);
  m_VtkImageImport->Modified();
  m_VtkImageImport->Update();
  m_RenderWindow->GetVtkRenderWindow()->Render();

}

#ifdef OPEN_CV

void mitk::ImageBackground2D::Update(IplImage * image)
{
  if(!image || !IsEnabled())
    return;

  if(image->roi == NULL)
  {
    if(image->height != m_ImageHeight || image->width != m_ImageWidth || image->nChannels != m_ImageScalarComponents)
    { // image parameters changed, update data array
      m_ImageHeight           = image->height;
      m_ImageWidth            = image->width;
      m_ImageScalarComponents = image->nChannels;

      if(m_ImageData != 0)
      {
        delete m_ImageData;
        m_ImageData = 0;
      }
    }
    if(m_ImageData == 0)
      m_ImageData = new unsigned char[m_ImageWidth*m_ImageHeight*m_ImageScalarComponents];

  }
  else
  {
    if(image->roi->height != m_ImageHeight|| image->roi->width != m_ImageWidth || image->nChannels != m_ImageScalarComponents)
    {

    }
  }

  InitVtkImageImport();

  int column, row;
  unsigned char* tex = m_ImageData;
  char* data = image->imageData;

  if(image->nChannels == 1 && image->origin == 1)
  { // flip image
    unsigned char g;
    for (column = 0; column < m_ImageHeight; column++)
    {
      for (row = 0; row < m_ImageWidth; row++)
      {
            g   = *data++;
        *tex++  = g;
      }
    }
  }
  else if(image->nChannels == 3 && image->origin == 1)
  { // flip image, change color channels
    unsigned char r, g, b;
    for (column = 0; column < m_ImageHeight; column++)
    {
      for (row = 0; row < m_ImageWidth; row++)
      {   //change r with b
          b = *data++;
          g = *data++;
          r = *data++;
          *tex++ = r;
          *tex++ = g;
          *tex++ = b;
      }
    }
  }
  else
    std::cout << "opencv image not supported in mitkimagebackround2d.cpp" << std::endl;

  m_VtkImageImport->SetImportVoidPointer(m_ImageData);
  m_VtkImageImport->Modified();
  m_VtkImageImport->Update();
  m_RenderWindow->GetVtkRenderWindow()->Render();
}
#endif
<commit_msg>CHG: removed opencv dependency<commit_after>#include "mitkImageBackground2D.h"
// MITK includes
#include "mitkVtkLayerController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"

// VTK includes
#include "vtkSystemIncludes.h"
#include "vtkRenderer.h"
#include "vtkMapper.h"
#include "vtkObjectFactory.h"
#include "vtkImageActor.h"
#include "vtkRenderWindow.h"
#include "vtkImageImport.h"
#include "vtkCommand.h"
#include "vtkCamera.h"

#include <iostream>

// VTK CALLBACK for automatic resize of the video
class vtkVideoSizeCallback : public vtkCommand
{
public:
  static vtkVideoSizeCallback *New(){ return new vtkVideoSizeCallback; }

  vtkRenderer * m_ImageRenderer;
  int m_ImageWidth, m_ImageHeight;

  void SetVtkVideoRenderer(vtkRenderer* r)
  {
    m_ImageRenderer = r;
  }
  void SetVideoDimensions(int x, int y)
  {
    m_ImageWidth = x; m_ImageHeight = y;
  }

  virtual void Execute(vtkObject* /*caller*/, unsigned long, void*)
  {
    //vtkRenderWindow * RenderWindow = reinterpret_cast<vtkRenderWindow*>(caller);
    //m_ImageRenderer->ResetCameraClippingRange();
  }
};

mitk::ImageBackground2D::ImageBackground2D()
{
  m_ImageWidth              = 720;
  m_ImageHeight             = 576;
  m_ImageScalarComponents   = 3;
  m_ParallelScale           = 0;
  m_RenderWindow = NULL;

  m_Actor             = vtkImageActor::New();
  m_ImageRenderer     = vtkRenderer::New();
  m_VtkImageImport    = vtkImageImport::New();

  m_ImageData         = 0;

  InitVtkImageImport();
}

void mitk::ImageBackground2D::InitVtkImageImport()
{
  m_VtkImageImport->SetDataScalarTypeToUnsignedChar();
  m_VtkImageImport->SetNumberOfScalarComponents(m_ImageScalarComponents);
  m_VtkImageImport->SetWholeExtent(0,m_ImageWidth-1,0,m_ImageHeight-1,0,1-1);
  m_VtkImageImport->SetDataExtentToWholeExtent();
}

mitk::ImageBackground2D::~ImageBackground2D()
{
  if ( m_RenderWindow != NULL )
    if ( this->IsEnabled() )
      this->Disable();
  if ( m_Actor!=NULL )
    m_Actor->Delete();
  if ( m_ImageRenderer != NULL )
    m_ImageRenderer->Delete();
  if ( m_VtkImageImport != NULL)
    m_VtkImageImport->Delete();
}
/**
 * Sets the renderwindow, in which the Video background
 * will be shown. Make sure, you have called this function
 * before calling Enable()
 */
void mitk::ImageBackground2D::SetRenderWindow( const mitk::RenderWindow* renderWindow )
{
  m_RenderWindow = renderWindow;

  /*m_SizeCallback = vtkVideoSizeCallback::New();
  m_RenderWindow->GetVtkRenderWindow()->AddObserver(vtkCommand::ModifiedEvent,m_SizeCallback);*/

}

void mitk::ImageBackground2D::SetParallelScale(int scale)
{
  m_ParallelScale = scale;
  m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ParallelScale);
}
int mitk::ImageBackground2D::GetParallelScale()
{
  // TODO someone who knows this, check if double->int could cause problems
  return static_cast<int>(m_ImageRenderer->GetActiveCamera()->GetParallelScale());
}
/**
 * Enables drawing of the color Video background.
 * If you want to disable it, call the Disable() function.
 */
void mitk::ImageBackground2D::Enable()
{
  m_ImageRenderer = vtkRenderer::New();

  unsigned char * c = 0;
  Update(c);
  m_Actor->SetInput(m_VtkImageImport->GetOutput());

  m_ImageRenderer->AddActor2D(m_Actor);
  m_ImageRenderer->ResetCamera();
  m_ImageRenderer->InteractiveOff();
  m_ImageRenderer->GetActiveCamera()->ParallelProjectionOn();
  if(m_ParallelScale == 0)
    m_ImageRenderer->GetActiveCamera()->SetParallelScale(m_ImageHeight/2);

  //m_SizeCallback->SetVtkVideoRenderer(m_ImageRenderer);
  //m_SizeCallback->SetVideoDimensions(m_ImageWidth, m_ImageHeight);
  m_RenderWindow->GetVtkLayerController()->InsertBackgroundRenderer(m_ImageRenderer,true);
}

/**
 * Disables drawing of the color Video background.
 * If you want to enable it, call the Enable() function.
 */
void mitk::ImageBackground2D::Disable()
{
  if ( this->IsEnabled() )
    m_RenderWindow->GetVtkLayerController()->RemoveRenderer(m_ImageRenderer);
}
/**
 * Checks, if the Video background is currently
 * enabled (visible)
 */
bool mitk::ImageBackground2D::IsEnabled()
{
  if ( m_RenderWindow->GetVtkLayerController()->IsRendererInserted(m_ImageRenderer) )
      return true;
  else
      return false;
}

void mitk::ImageBackground2D::Update(unsigned char * datapointer)
{
  if(!IsEnabled())
    return;

  if(!datapointer)
  {// no valid image pointer provided -> initialize black image
    m_ImageData = new unsigned char[m_ImageHeight*m_ImageWidth*m_ImageScalarComponents];
    unsigned char* b = m_ImageData;
    for ( int textCounter = 0; textCounter < (m_ImageHeight*m_ImageWidth*m_ImageScalarComponents); textCounter++ )
      *b++ = 0;
  }

  m_VtkImageImport->SetImportVoidPointer(m_ImageData);
  m_VtkImageImport->Modified();
  m_VtkImageImport->Update();
  m_RenderWindow->GetVtkRenderWindow()->Render();

}

<|endoftext|>


<commit_before><commit_msg>Implement tutorial 02<commit_after><|endoftext|>