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

  Library:   CTK

  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.txt

  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 <QMap>
#include <QSettings>
#include <QTableWidgetItem>
#include <QVariant>

/// CTK includes
#include <ctkCheckableHeaderView.h>
#include <ctkCheckableModelHelper.h>

// ctkDICOMWidgets includes
#include "ctkDICOMServerNodeWidget.h"
#include "ui_ctkDICOMServerNodeWidget.h"

// STD includes
#include <iostream>
//----------------------------------------------------------------------------
class ctkDICOMServerNodeWidgetPrivate: public Ui_ctkDICOMServerNodeWidget
{
public:
  ctkDICOMServerNodeWidgetPrivate(){}
};

//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidgetPrivate methods

//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidget methods

//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::ctkDICOMServerNodeWidget(QWidget* parentWidget)
  : Superclass(parentWidget)
  , d_ptr(new ctkDICOMServerNodeWidgetPrivate)
{
  Q_D(ctkDICOMServerNodeWidget);

  d->setupUi(this);

  // checkable headers.
  d->NodeTable->model()->setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
  QHeaderView* previousHeaderView = d->NodeTable->horizontalHeader();
  ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->NodeTable);
  headerView->setClickable(previousHeaderView->isClickable());
  headerView->setMovable(previousHeaderView->isMovable());
  headerView->setHighlightSections(previousHeaderView->highlightSections());
  headerView->checkableModelHelper()->setPropagateDepth(-1);
  d->NodeTable->setHorizontalHeader(headerView);

  d->RemoveButton->setEnabled(false);

  this->readSettings();

  connect(d->CallingAETitle, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));
  connect(d->StorageAETitle, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));
  connect(d->StoragePort, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));

  connect(d->AddButton, SIGNAL(clicked()),
    this, SLOT(addServerNode()));
  connect(d->RemoveButton, SIGNAL(clicked()),
    this, SLOT(removeCurrentServerNode()));

  connect(d->NodeTable, SIGNAL(cellChanged(int,int)),
    this, SLOT(saveSettings()));
  connect(d->NodeTable, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
    this, SLOT(updateRemoveButtonEnableState()));
}

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

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode()
{
  Q_D(ctkDICOMServerNodeWidget);
  const int rowCount = d->NodeTable->rowCount();
  d->NodeTable->setRowCount( rowCount + 1 );

  QTableWidgetItem* newItem = new QTableWidgetItem;
  newItem->setCheckState( Qt::Unchecked );
  d->NodeTable->setItem(rowCount, NameColumn, newItem);

  d->NodeTable->setCurrentCell(rowCount, NameColumn);
  // The old rowCount becomes the added row index
  return rowCount;
}

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode(const QMap<QString, QVariant>& node)
{
  Q_D(ctkDICOMServerNodeWidget);
  const int row = this->addServerNode();

  QTableWidgetItem *newItem;
  newItem = new QTableWidgetItem( node["Name"].toString() );
  newItem->setCheckState( Qt::CheckState(node["CheckState"].toInt()) );
  d->NodeTable->setItem(row, NameColumn, newItem);
  newItem = new QTableWidgetItem( node["AETitle"].toString() );
  d->NodeTable->setItem(row, AETitleColumn, newItem);
  newItem = new QTableWidgetItem( node["Address"].toString() );
  d->NodeTable->setItem(row, AddressColumn, newItem);
  newItem = new QTableWidgetItem( node["Port"].toString() );
  d->NodeTable->setItem(row, PortColumn, newItem);
  return row;
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::removeCurrentServerNode()
{
  Q_D(ctkDICOMServerNodeWidget);

  d->NodeTable->removeRow( d->NodeTable->currentRow() );

  this->saveSettings();
  this->updateRemoveButtonEnableState();
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::updateRemoveButtonEnableState()
{
  Q_D(ctkDICOMServerNodeWidget);
  d->RemoveButton->setEnabled(d->NodeTable->rowCount() > 0);
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::saveSettings()
{
  Q_D(ctkDICOMServerNodeWidget);

  QSettings settings;
  const int rowCount = d->NodeTable->rowCount();

  settings.setValue("ServerNodeCount", rowCount);
  for (int row = 0; row < rowCount; ++row)
    {
    QMap<QString, QVariant> node = this->serverNodeParameters(row);
    settings.setValue(QString("ServerNodes/%1").arg(row), QVariant(node));
    }
  settings.setValue("CallingAETitle", this->callingAETitle());
  settings.setValue("StorageAETitle", this->storageAETitle());
  settings.setValue("StoragePort", this->storagePort());
  settings.sync();
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::readSettings()
{
  Q_D(ctkDICOMServerNodeWidget);

  d->NodeTable->setRowCount(0);

  QSettings settings;

  QMap<QString, QVariant> node;
  if (settings.status() == QSettings::AccessError ||
      settings.value("ServerNodeCount").toInt() == 0)
    {
    d->StorageAETitle->setText("CTKSTORE");
    d->StoragePort->setText("11113");
    d->CallingAETitle->setText("FINDSCU");

    QMap<QString, QVariant> defaultServerNode;
    defaultServerNode["Name"] = QString("ExampleHost");
    defaultServerNode["CheckState"] = Qt::Checked;
    defaultServerNode["AETitle"] = QString("ANY-SCP");
    defaultServerNode["Address"] = QString("localhost");
    defaultServerNode["Port"] = QString("11112");
    this->addServerNode(defaultServerNode);
    return;
    }

  d->StorageAETitle->setText(settings.value("StorageAETitle").toString());
  d->StoragePort->setText(settings.value("StoragePort").toString());
  d->CallingAETitle->setText(settings.value("CallingAETitle").toString());

  const int count = settings.value("ServerNodeCount").toInt();
  for (int row = 0; row < count; ++row)
    {
    node = settings.value(QString("ServerNodes/%1").arg(row)).toMap();
    this->addServerNode(node);
    }
}

//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::callingAETitle()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  return d->CallingAETitle->text();
}

//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::storageAETitle()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  return d->StorageAETitle->text();
}

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::storagePort()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  bool ok = false;
  int port = d->StoragePort->text().toInt(&ok);
  Q_ASSERT(ok);
  return port;
}

//----------------------------------------------------------------------------
QMap<QString,QVariant> ctkDICOMServerNodeWidget::parameters()const
{
  QMap<QString, QVariant> parameters;

  parameters["CallingAETitle"] = this->callingAETitle();
  parameters["StorageAETitle"] = this->storageAETitle();
  parameters["StoragePort"] = this->storagePort();

  return parameters;
}

//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::serverNodes()const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QStringList nodes;
  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; ++row)
    {
    QTableWidgetItem* item = d->NodeTable->item(row,NameColumn);
    nodes << (item ? item->text() : QString(""));
    }
  // If there are duplicates, serverNodeParameters(QString) will behave
  // strangely
  Q_ASSERT(nodes.removeDuplicates() == 0);
  return nodes;
}

//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::selectedServerNodes()const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QStringList nodes;
  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; ++row)
    {
    QTableWidgetItem* item = d->NodeTable->item(row, NameColumn);
    if (item && item->checkState() == Qt::Checked)
      {
      nodes << item->text();
      }
    }
  // If there are duplicates, serverNodeParameters(QString) will behave
  // strangely
  Q_ASSERT(nodes.removeDuplicates() == 0);
  return nodes;
}

//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(const QString &node)const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QMap<QString, QVariant> parameters;

  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; row++)
    {
    if ( d->NodeTable->item(row,0)->text() == node )
      {
      // TBD: not sure what it means to merge parameters
      parameters.unite(this->serverNodeParameters(row));
      }
    }

  return parameters;
}

//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(int row)const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QMap<QString, QVariant> node;
  if (row < 0 || row >= d->NodeTable->rowCount())
    {
    return node;
    }
  const int columnCount = d->NodeTable->columnCount();
  for (int column = 0; column < columnCount; ++column)
    {
    if (!d->NodeTable->item(row, column))
      {
      continue;
      }
    QString label = d->NodeTable->horizontalHeaderItem(column)->text();
    node[label] = d->NodeTable->item(row, column)->data(Qt::DisplayRole);
    }
  node["CheckState"] = d->NodeTable->item(row, NameColumn) ?
    d->NodeTable->item(row,0)->checkState() : Qt::Unchecked;
  return node;
}
<commit_msg>Change defaults for first use of ctkDICOM<commit_after>/*=========================================================================

  Library:   CTK

  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.txt

  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 <QMap>
#include <QSettings>
#include <QTableWidgetItem>
#include <QVariant>

/// CTK includes
#include <ctkCheckableHeaderView.h>
#include <ctkCheckableModelHelper.h>

// ctkDICOMWidgets includes
#include "ctkDICOMServerNodeWidget.h"
#include "ui_ctkDICOMServerNodeWidget.h"

// STD includes
#include <iostream>
//----------------------------------------------------------------------------
class ctkDICOMServerNodeWidgetPrivate: public Ui_ctkDICOMServerNodeWidget
{
public:
  ctkDICOMServerNodeWidgetPrivate(){}
};

//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidgetPrivate methods

//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidget methods

//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::ctkDICOMServerNodeWidget(QWidget* parentWidget)
  : Superclass(parentWidget)
  , d_ptr(new ctkDICOMServerNodeWidgetPrivate)
{
  Q_D(ctkDICOMServerNodeWidget);

  d->setupUi(this);

  // checkable headers.
  d->NodeTable->model()->setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
  QHeaderView* previousHeaderView = d->NodeTable->horizontalHeader();
  ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->NodeTable);
  headerView->setClickable(previousHeaderView->isClickable());
  headerView->setMovable(previousHeaderView->isMovable());
  headerView->setHighlightSections(previousHeaderView->highlightSections());
  headerView->checkableModelHelper()->setPropagateDepth(-1);
  d->NodeTable->setHorizontalHeader(headerView);

  d->RemoveButton->setEnabled(false);

  this->readSettings();

  connect(d->CallingAETitle, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));
  connect(d->StorageAETitle, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));
  connect(d->StoragePort, SIGNAL(textChanged(QString)),
    this, SLOT(saveSettings()));

  connect(d->AddButton, SIGNAL(clicked()),
    this, SLOT(addServerNode()));
  connect(d->RemoveButton, SIGNAL(clicked()),
    this, SLOT(removeCurrentServerNode()));

  connect(d->NodeTable, SIGNAL(cellChanged(int,int)),
    this, SLOT(saveSettings()));
  connect(d->NodeTable, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
    this, SLOT(updateRemoveButtonEnableState()));
}

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

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode()
{
  Q_D(ctkDICOMServerNodeWidget);
  const int rowCount = d->NodeTable->rowCount();
  d->NodeTable->setRowCount( rowCount + 1 );

  QTableWidgetItem* newItem = new QTableWidgetItem;
  newItem->setCheckState( Qt::Unchecked );
  d->NodeTable->setItem(rowCount, NameColumn, newItem);

  d->NodeTable->setCurrentCell(rowCount, NameColumn);
  // The old rowCount becomes the added row index
  return rowCount;
}

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode(const QMap<QString, QVariant>& node)
{
  Q_D(ctkDICOMServerNodeWidget);
  const int row = this->addServerNode();

  QTableWidgetItem *newItem;
  newItem = new QTableWidgetItem( node["Name"].toString() );
  newItem->setCheckState( Qt::CheckState(node["CheckState"].toInt()) );
  d->NodeTable->setItem(row, NameColumn, newItem);
  newItem = new QTableWidgetItem( node["AETitle"].toString() );
  d->NodeTable->setItem(row, AETitleColumn, newItem);
  newItem = new QTableWidgetItem( node["Address"].toString() );
  d->NodeTable->setItem(row, AddressColumn, newItem);
  newItem = new QTableWidgetItem( node["Port"].toString() );
  d->NodeTable->setItem(row, PortColumn, newItem);
  return row;
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::removeCurrentServerNode()
{
  Q_D(ctkDICOMServerNodeWidget);

  d->NodeTable->removeRow( d->NodeTable->currentRow() );

  this->saveSettings();
  this->updateRemoveButtonEnableState();
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::updateRemoveButtonEnableState()
{
  Q_D(ctkDICOMServerNodeWidget);
  d->RemoveButton->setEnabled(d->NodeTable->rowCount() > 0);
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::saveSettings()
{
  Q_D(ctkDICOMServerNodeWidget);

  QSettings settings;
  const int rowCount = d->NodeTable->rowCount();

  settings.setValue("ServerNodeCount", rowCount);
  for (int row = 0; row < rowCount; ++row)
    {
    QMap<QString, QVariant> node = this->serverNodeParameters(row);
    settings.setValue(QString("ServerNodes/%1").arg(row), QVariant(node));
    }
  settings.setValue("CallingAETitle", this->callingAETitle());
  settings.setValue("StorageAETitle", this->storageAETitle());
  settings.setValue("StoragePort", this->storagePort());
  settings.sync();
}

//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::readSettings()
{
  Q_D(ctkDICOMServerNodeWidget);

  d->NodeTable->setRowCount(0);

  QSettings settings;

  QMap<QString, QVariant> node;
  if (settings.status() == QSettings::AccessError ||
      settings.value("ServerNodeCount").toInt() == 0)
    {
    d->StorageAETitle->setText("CTKSTORE");
    d->StoragePort->setText("11112");
    d->CallingAETitle->setText("CTKSTORE");

    // a dummy example
    QMap<QString, QVariant> defaultServerNode;
    defaultServerNode["Name"] = QString("ExampleHost");
    defaultServerNode["CheckState"] = Qt::Unchecked;
    defaultServerNode["AETitle"] = QString("AETITLE");
    defaultServerNode["Address"] = QString("dicom.example.com");
    defaultServerNode["Port"] = QString("11112");
    this->addServerNode(defaultServerNode);

    // the uk example - see http://www.dicomserver.co.uk/
    // and http://www.medicalconnections.co.uk/
    defaultServerNode["Name"] = QString("MedicalConnections");
    defaultServerNode["CheckState"] = Qt::Unchecked;
    defaultServerNode["AETitle"] = QString("ANYAE");
    defaultServerNode["Address"] = QString("dicomserver.co.uk");
    defaultServerNode["Port"] = QString("11112");
    this->addServerNode(defaultServerNode);

    return;
    }

  d->StorageAETitle->setText(settings.value("StorageAETitle").toString());
  d->StoragePort->setText(settings.value("StoragePort").toString());
  d->CallingAETitle->setText(settings.value("CallingAETitle").toString());

  const int count = settings.value("ServerNodeCount").toInt();
  for (int row = 0; row < count; ++row)
    {
    node = settings.value(QString("ServerNodes/%1").arg(row)).toMap();
    this->addServerNode(node);
    }
}

//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::callingAETitle()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  return d->CallingAETitle->text();
}

//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::storageAETitle()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  return d->StorageAETitle->text();
}

//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::storagePort()const
{
  Q_D(const ctkDICOMServerNodeWidget);
  bool ok = false;
  int port = d->StoragePort->text().toInt(&ok);
  Q_ASSERT(ok);
  return port;
}

//----------------------------------------------------------------------------
QMap<QString,QVariant> ctkDICOMServerNodeWidget::parameters()const
{
  QMap<QString, QVariant> parameters;

  parameters["CallingAETitle"] = this->callingAETitle();
  parameters["StorageAETitle"] = this->storageAETitle();
  parameters["StoragePort"] = this->storagePort();

  return parameters;
}

//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::serverNodes()const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QStringList nodes;
  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; ++row)
    {
    QTableWidgetItem* item = d->NodeTable->item(row,NameColumn);
    nodes << (item ? item->text() : QString(""));
    }
  // If there are duplicates, serverNodeParameters(QString) will behave
  // strangely
  Q_ASSERT(nodes.removeDuplicates() == 0);
  return nodes;
}

//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::selectedServerNodes()const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QStringList nodes;
  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; ++row)
    {
    QTableWidgetItem* item = d->NodeTable->item(row, NameColumn);
    if (item && item->checkState() == Qt::Checked)
      {
      nodes << item->text();
      }
    }
  // If there are duplicates, serverNodeParameters(QString) will behave
  // strangely
  Q_ASSERT(nodes.removeDuplicates() == 0);
  return nodes;
}

//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(const QString &node)const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QMap<QString, QVariant> parameters;

  const int count = d->NodeTable->rowCount();
  for (int row = 0; row < count; row++)
    {
    if ( d->NodeTable->item(row,0)->text() == node )
      {
      // TBD: not sure what it means to merge parameters
      parameters.unite(this->serverNodeParameters(row));
      }
    }

  return parameters;
}

//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(int row)const
{
  Q_D(const ctkDICOMServerNodeWidget);

  QMap<QString, QVariant> node;
  if (row < 0 || row >= d->NodeTable->rowCount())
    {
    return node;
    }
  const int columnCount = d->NodeTable->columnCount();
  for (int column = 0; column < columnCount; ++column)
    {
    if (!d->NodeTable->item(row, column))
      {
      continue;
      }
    QString label = d->NodeTable->horizontalHeaderItem(column)->text();
    node[label] = d->NodeTable->item(row, column)->data(Qt::DisplayRole);
    }
  node["CheckState"] = d->NodeTable->item(row, NameColumn) ?
    d->NodeTable->item(row,0)->checkState() : Qt::Unchecked;
  return node;
}
<|endoftext|>


<commit_before>//
// Copyright "Renga Software" LLC, 2016. All rights reserved.
//
// "Renga Software" LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// "Renga Software" LLC  DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//

#include "stdafx.h"

#include "PropertyViewBuilderBase.h"
#include "PropertyManager.h"
#include "GuidUtils.h"
#include "ScopeGuard.h"

#include <Renga/QuantityIds.h>

PropertyViewBuilderBase::PropertyViewBuilderBase(bool disableProperties) : m_disableProperties(disableProperties)
{
}

void PropertyViewBuilderBase::createParametersInternal(
    PropertyManager& mngr,
    Renga::IParameterContainer& container)
{
  // block signals before filling properties
  mngr.blockSignals(true);

  auto unblockSignalsGuard = makeGuard([&mngr] {mngr.blockSignals(false); });

  auto pIds = container.GetIds();
  for (int i = 0; i < pIds->Count; ++i)
  {
    const auto id = pIds->Get(i);

    auto pParameter = container.Get(id);
    auto pDefinition = pParameter->Definition;

    QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());

    switch (pDefinition->GetParameterType())
    {
    case Renga::ParameterType::ParameterType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      break;
    case Renga::ParameterType::ParameterType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      break;
    }

    QtProperty* pQtProperty(nullptr);
    switch (pParameter->GetValueType())
    {
    case Renga::ParameterValueType::ParameterValueType_Bool:
      pQtProperty = mngr.addValue(name, static_cast<bool>(pParameter->GetBoolValue()));
      break;
    case Renga::ParameterValueType::ParameterValueType_Int:
      pQtProperty = mngr.addValue(name, pParameter->GetIntValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_Double:
      pQtProperty = mngr.addValue(name, pParameter->GetDoubleValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_String:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pParameter->GetStringValue()));
      break;
    }

    if (pQtProperty)
    {
      if (!pParameter->HasValue())
        pQtProperty->setEnabled(false);

      const auto parameterIdString = QString::fromStdString((GuidToString(id)));
      pQtProperty->setData(parameterIdString);
    }
  }
}

void PropertyViewBuilderBase::createPropertiesInternal(
    PropertyManager& mngr,
    Renga::IPropertyContainer& container)
{
  // block signals before filling properties
  mngr.blockSignals(true);

  auto ids = container.GetIds();

  for (int i = 0; i < ids->Count; ++i)
  {
    auto id = ids->Get(i);
    auto pProperty = container.Get(id);

    if (!pProperty)
      continue;

    auto name = QString::fromWCharArray(pProperty->Name);
    const auto propertyIdString = QString::fromStdString((GuidToString(id)));

    // TODO: add support for all property types
    QtProperty* pQtProperty(nullptr);
    switch (pProperty->Type)
    {
    case Renga::PropertyType::PropertyType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetAngleValue(Renga::AngleUnit::AngleUnit_Degrees));
      break;
    case Renga::PropertyType::PropertyType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetLengthValue(Renga::LengthUnit::LengthUnit_Meters));
      break;
    case Renga::PropertyType::PropertyType_Area:
      name += ", " + QApplication::translate("me_mo", "area_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetAreaValue(Renga::AreaUnit::AreaUnit_Meters2));
      break;
    case Renga::PropertyType::PropertyType_Volume:
      name += ", " + QApplication::translate("me_mo", "volume_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetVolumeValue(Renga::VolumeUnit::VolumeUnit_Meters3));
      break;
    case Renga::PropertyType::PropertyType_Mass:
      name += ", " + QApplication::translate("me_mo", "mass_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetMassValue(Renga::MassUnit::MassUnit_Kilograms));
      break;
    case Renga::PropertyType::PropertyType_Double:
      pQtProperty = mngr.addValue(name, pProperty->GetDoubleValue());
      break;
    case Renga::PropertyType::PropertyType_String:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pProperty->GetStringValue()));
      break;
    case Renga::PropertyType::PropertyType_Boolean:
      pQtProperty = mngr.addValue(name, pProperty->GetBooleanValue());
      break;
    case Renga::PropertyType::PropertyType_Logical:
      pQtProperty = mngr.addValue(name, QString(pProperty->GetLogicalValue()));
      break;
    case Renga::PropertyType::PropertyType_Integer:
      pQtProperty = mngr.addValue(name, pProperty->GetIntegerValue());
      break;
    case Renga::PropertyType::PropertyType_Enumeration:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pProperty->GetEnumerationValue()));
      break;
    default:
      continue;
    }

    pQtProperty->setEnabled(!m_disableProperties);
    pQtProperty->setData(propertyIdString);
  }

  // unblock signals
  mngr.blockSignals(false);
}

void PropertyViewBuilderBase::createQuantitiesInternal(
    PropertyManager& mngr,
    Renga::IQuantityContainer& container)
{
  using namespace Renga;

  auto addValue = [&mngr, &container](QString name, GUID id)
  {
    auto pQuantity = container.Get(id);

    if (!pQuantity)
      return;

    switch (pQuantity->GetType())
    {
    case Renga::QuantityType::QuantityType_Length:
      mngr.addValue(name, pQuantity->AsLength(Renga::LengthUnit::LengthUnit_Millimeters));
      break;
    case Renga::QuantityType::QuantityType_Area:
      mngr.addValue(name, pQuantity->AsArea(Renga::AreaUnit::AreaUnit_Meters2));
      break;
    case Renga::QuantityType::QuantityType_Volume:
      mngr.addValue(name, pQuantity->AsVolume(Renga::VolumeUnit::VolumeUnit_Meters3));
      break;
    case Renga::QuantityType::QuantityType_Mass:
      mngr.addValue(name, pQuantity->AsMass(Renga::MassUnit::MassUnit_Kilograms));
      break;
    case Renga::QuantityType::QuantityType_Count:
      mngr.addValue(name, pQuantity->AsCount());
      break;
    }
  };

  addValue(QApplication::translate("me_mo", "overallWidth"), QuantityIds::OverallWidth);
  addValue(QApplication::translate("me_mo", "overallHeight"), QuantityIds::OverallHeight);
  addValue(QApplication::translate("me_mo", "overallLength"), QuantityIds::OverallLength);
  addValue(QApplication::translate("me_mo", "thickness"), QuantityIds::NominalThickness);
  addValue(QApplication::translate("me_mo", "length"), QuantityIds::NominalLength);
  addValue(QApplication::translate("me_mo", "width"), QuantityIds::NominalWidth);
  addValue(QApplication::translate("me_mo", "height"), QuantityIds::NominalHeight);
  addValue(QApplication::translate("me_mo", "perimeter"), QuantityIds::Perimeter);
  addValue(QApplication::translate("me_mo", "volume"), QuantityIds::Volume);
  addValue(QApplication::translate("me_mo", "netVolume"), QuantityIds::NetVolume);
  addValue(QApplication::translate("me_mo", "mass"), QuantityIds::NetMass);
  addValue(QApplication::translate("me_mo", "crossSectionOverallWidth"), QuantityIds::CrossSectionOverallWidth);
  addValue(QApplication::translate("me_mo", "crossSectionOverallHeight"), QuantityIds::CrossSectionOverallHeight);
  addValue(QApplication::translate("me_mo", "crossSectionArea"), QuantityIds::CrossSectionArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceArea"), QuantityIds::InnerSurfaceArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceInternalArea"), QuantityIds::InnerSurfaceInternalArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceExternalArea"), QuantityIds::InnerSurfaceExternalArea);
  addValue(QApplication::translate("me_mo", "outerSurfaceArea"), QuantityIds::OuterSurfaceArea);
  addValue(QApplication::translate("me_mo", "area"), QuantityIds::Area);
  addValue(QApplication::translate("me_mo", "nominalArea"), QuantityIds::NominalArea);
  addValue(QApplication::translate("me_mo", "netArea"), QuantityIds::NetArea);
  addValue(QApplication::translate("me_mo", "netFloorArea"), QuantityIds::NetFloorArea);
  addValue(QApplication::translate("me_mo", "netFootprintArea"), QuantityIds::NetFootprintArea);
  addValue(QApplication::translate("me_mo", "netSideArea"), QuantityIds::NetSideArea);
  addValue(QApplication::translate("me_mo", "totalSurfaceArea"), QuantityIds::TotalSurfaceArea);
  addValue(QApplication::translate("me_mo", "grossVolume"), QuantityIds::GrossVolume);
  addValue(QApplication::translate("me_mo", "grossFloorArea"), QuantityIds::GrossFloorArea);
  addValue(QApplication::translate("me_mo", "grossPerimeter"), QuantityIds::GrossPerimeter);
  addValue(QApplication::translate("me_mo", "numberOfRiser"), QuantityIds::NumberOfRiser);
  addValue(QApplication::translate("me_mo", "numberOfTreads"), QuantityIds::NumberOfTreads);
  addValue(QApplication::translate("me_mo", "riserHeight"), QuantityIds::RiserHeight);
  addValue(QApplication::translate("me_mo", "treadLength"), QuantityIds::TreadLength);
  addValue(QApplication::translate("me_reinforcement", "totalRebarLength"), QuantityIds::TotalRebarLength);
  addValue(QApplication::translate("me_reinforcement", "totalRebarMass"), QuantityIds::TotalRebarMass);
}
<commit_msg>Fix text color for editable controls<commit_after>//
// Copyright "Renga Software" LLC, 2016. All rights reserved.
//
// "Renga Software" LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// "Renga Software" LLC  DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//

#include "stdafx.h"

#include "PropertyViewBuilderBase.h"
#include "PropertyManager.h"
#include "GuidUtils.h"
#include "ScopeGuard.h"

#include <Renga/QuantityIds.h>

PropertyViewBuilderBase::PropertyViewBuilderBase(bool disableProperties) : m_disableProperties(disableProperties)
{
}

void PropertyViewBuilderBase::createParametersInternal(
    PropertyManager& mngr,
    Renga::IParameterContainer& container)
{
  // block signals before filling properties
  mngr.blockSignals(true);

  auto unblockSignalsGuard = makeGuard([&mngr] {mngr.blockSignals(false); });

  auto pIds = container.GetIds();
  for (int i = 0; i < pIds->Count; ++i)
  {
    const auto id = pIds->Get(i);

    auto pParameter = container.Get(id);
    auto pDefinition = pParameter->Definition;

    QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());

    switch (pDefinition->GetParameterType())
    {
    case Renga::ParameterType::ParameterType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      break;
    case Renga::ParameterType::ParameterType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      break;
    }

    QtProperty* pQtProperty(nullptr);
    switch (pParameter->GetValueType())
    {
    case Renga::ParameterValueType::ParameterValueType_Bool:
      pQtProperty = mngr.addValue(name, static_cast<bool>(pParameter->GetBoolValue()));
      break;
    case Renga::ParameterValueType::ParameterValueType_Int:
      pQtProperty = mngr.addValue(name, pParameter->GetIntValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_Double:
      pQtProperty = mngr.addValue(name, pParameter->GetDoubleValue());
      break;
    case Renga::ParameterValueType::ParameterValueType_String:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pParameter->GetStringValue()));
      break;
    }

    if (pQtProperty)
    {
      if (!pParameter->HasValue())
        pQtProperty->setEnabled(false);

      const auto parameterIdString = QString::fromStdString((GuidToString(id)));
      pQtProperty->setData(parameterIdString);
    }
  }
}

void PropertyViewBuilderBase::createPropertiesInternal(
    PropertyManager& mngr,
    Renga::IPropertyContainer& container)
{
  // block signals before filling properties
  mngr.blockSignals(true);

  auto ids = container.GetIds();

  for (int i = 0; i < ids->Count; ++i)
  {
    auto id = ids->Get(i);
    auto pProperty = container.Get(id);

    if (!pProperty)
      continue;

    auto name = QString::fromWCharArray(pProperty->Name);
    const auto propertyIdString = QString::fromStdString((GuidToString(id)));

    // TODO: add support for all property types
    QtProperty* pQtProperty(nullptr);
    switch (pProperty->Type)
    {
    case Renga::PropertyType::PropertyType_Angle:
      name += ", " + QApplication::translate("me_mo", "angle_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetAngleValue(Renga::AngleUnit::AngleUnit_Degrees));
      break;
    case Renga::PropertyType::PropertyType_Length:
      name += ", " + QApplication::translate("me_mo", "length_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetLengthValue(Renga::LengthUnit::LengthUnit_Meters));
      break;
    case Renga::PropertyType::PropertyType_Area:
      name += ", " + QApplication::translate("me_mo", "area_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetAreaValue(Renga::AreaUnit::AreaUnit_Meters2));
      break;
    case Renga::PropertyType::PropertyType_Volume:
      name += ", " + QApplication::translate("me_mo", "volume_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetVolumeValue(Renga::VolumeUnit::VolumeUnit_Meters3));
      break;
    case Renga::PropertyType::PropertyType_Mass:
      name += ", " + QApplication::translate("me_mo", "mass_dimension");
      pQtProperty = mngr.addValue(name, pProperty->GetMassValue(Renga::MassUnit::MassUnit_Kilograms));
      break;
    case Renga::PropertyType::PropertyType_Double:
      pQtProperty = mngr.addValue(name, pProperty->GetDoubleValue());
      break;
    case Renga::PropertyType::PropertyType_String:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pProperty->GetStringValue()));
      break;
    case Renga::PropertyType::PropertyType_Boolean:
      pQtProperty = mngr.addValue(name, pProperty->GetBooleanValue());
      break;
    case Renga::PropertyType::PropertyType_Logical:
      pQtProperty = mngr.addValue(name, QString(pProperty->GetLogicalValue()));
      break;
    case Renga::PropertyType::PropertyType_Integer:
      pQtProperty = mngr.addValue(name, pProperty->GetIntegerValue());
      break;
    case Renga::PropertyType::PropertyType_Enumeration:
      pQtProperty = mngr.addValue(name, QString::fromWCharArray(pProperty->GetEnumerationValue()));
      break;
    default:
      continue;
    }

    pQtProperty->setEnabled(!m_disableProperties);
    // TODO: text color should depend on control enable state, for now we use "modified" flag to ungrey text in edit box
    pQtProperty->setModified(true);
    pQtProperty->setData(propertyIdString);
  }

  // unblock signals
  mngr.blockSignals(false);
}

void PropertyViewBuilderBase::createQuantitiesInternal(
    PropertyManager& mngr,
    Renga::IQuantityContainer& container)
{
  using namespace Renga;

  auto addValue = [&mngr, &container](QString name, GUID id)
  {
    auto pQuantity = container.Get(id);

    if (!pQuantity)
      return;

    switch (pQuantity->GetType())
    {
    case Renga::QuantityType::QuantityType_Length:
      mngr.addValue(name, pQuantity->AsLength(Renga::LengthUnit::LengthUnit_Millimeters));
      break;
    case Renga::QuantityType::QuantityType_Area:
      mngr.addValue(name, pQuantity->AsArea(Renga::AreaUnit::AreaUnit_Meters2));
      break;
    case Renga::QuantityType::QuantityType_Volume:
      mngr.addValue(name, pQuantity->AsVolume(Renga::VolumeUnit::VolumeUnit_Meters3));
      break;
    case Renga::QuantityType::QuantityType_Mass:
      mngr.addValue(name, pQuantity->AsMass(Renga::MassUnit::MassUnit_Kilograms));
      break;
    case Renga::QuantityType::QuantityType_Count:
      mngr.addValue(name, pQuantity->AsCount());
      break;
    }
  };

  addValue(QApplication::translate("me_mo", "overallWidth"), QuantityIds::OverallWidth);
  addValue(QApplication::translate("me_mo", "overallHeight"), QuantityIds::OverallHeight);
  addValue(QApplication::translate("me_mo", "overallLength"), QuantityIds::OverallLength);
  addValue(QApplication::translate("me_mo", "thickness"), QuantityIds::NominalThickness);
  addValue(QApplication::translate("me_mo", "length"), QuantityIds::NominalLength);
  addValue(QApplication::translate("me_mo", "width"), QuantityIds::NominalWidth);
  addValue(QApplication::translate("me_mo", "height"), QuantityIds::NominalHeight);
  addValue(QApplication::translate("me_mo", "perimeter"), QuantityIds::Perimeter);
  addValue(QApplication::translate("me_mo", "volume"), QuantityIds::Volume);
  addValue(QApplication::translate("me_mo", "netVolume"), QuantityIds::NetVolume);
  addValue(QApplication::translate("me_mo", "mass"), QuantityIds::NetMass);
  addValue(QApplication::translate("me_mo", "crossSectionOverallWidth"), QuantityIds::CrossSectionOverallWidth);
  addValue(QApplication::translate("me_mo", "crossSectionOverallHeight"), QuantityIds::CrossSectionOverallHeight);
  addValue(QApplication::translate("me_mo", "crossSectionArea"), QuantityIds::CrossSectionArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceArea"), QuantityIds::InnerSurfaceArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceInternalArea"), QuantityIds::InnerSurfaceInternalArea);
  addValue(QApplication::translate("me_mo", "innerSurfaceExternalArea"), QuantityIds::InnerSurfaceExternalArea);
  addValue(QApplication::translate("me_mo", "outerSurfaceArea"), QuantityIds::OuterSurfaceArea);
  addValue(QApplication::translate("me_mo", "area"), QuantityIds::Area);
  addValue(QApplication::translate("me_mo", "nominalArea"), QuantityIds::NominalArea);
  addValue(QApplication::translate("me_mo", "netArea"), QuantityIds::NetArea);
  addValue(QApplication::translate("me_mo", "netFloorArea"), QuantityIds::NetFloorArea);
  addValue(QApplication::translate("me_mo", "netFootprintArea"), QuantityIds::NetFootprintArea);
  addValue(QApplication::translate("me_mo", "netSideArea"), QuantityIds::NetSideArea);
  addValue(QApplication::translate("me_mo", "totalSurfaceArea"), QuantityIds::TotalSurfaceArea);
  addValue(QApplication::translate("me_mo", "grossVolume"), QuantityIds::GrossVolume);
  addValue(QApplication::translate("me_mo", "grossFloorArea"), QuantityIds::GrossFloorArea);
  addValue(QApplication::translate("me_mo", "grossPerimeter"), QuantityIds::GrossPerimeter);
  addValue(QApplication::translate("me_mo", "numberOfRiser"), QuantityIds::NumberOfRiser);
  addValue(QApplication::translate("me_mo", "numberOfTreads"), QuantityIds::NumberOfTreads);
  addValue(QApplication::translate("me_mo", "riserHeight"), QuantityIds::RiserHeight);
  addValue(QApplication::translate("me_mo", "treadLength"), QuantityIds::TreadLength);
  addValue(QApplication::translate("me_reinforcement", "totalRebarLength"), QuantityIds::TotalRebarLength);
  addValue(QApplication::translate("me_reinforcement", "totalRebarMass"), QuantityIds::TotalRebarMass);
}
<|endoftext|>


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

   Program:   ORFEO Toolbox
   Language:  C++
   Date:      $Date$
   Version:   $Revision$

   Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
   See OTBCopyright.txt 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 "otbMPIConfig.h"
#include <iostream>
#include "itkMultiThreader.h"

int otbMPIConfigTest(int argc, char* argv[]) {

  // Mono-thread execution
  itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);
  itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);

  // MPI Configuration
  typedef otb::MPIConfig    MPIConfigType;
  MPIConfigType::Pointer config = MPIConfigType::Instance();
  config->Init(argc,argv,true);

  // Test
  std::cout<<"OTB MPI config test. I am process "<<config->GetMyRank()<<" among "<<config->GetNbProcs()<<"."<<std::endl;

  return EXIT_SUCCESS;
}

<commit_msg>TEST: Remove number of threads limitation<commit_after>/*=========================================================================

   Program:   ORFEO Toolbox
   Language:  C++
   Date:      $Date$
   Version:   $Revision$

   Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
   See OTBCopyright.txt 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 "otbMPIConfig.h"
#include <iostream>
#include "itkMultiThreader.h"

int otbMPIConfigTest(int argc, char* argv[]) {

  // MPI Configuration
  typedef otb::MPIConfig    MPIConfigType;
  MPIConfigType::Pointer config = MPIConfigType::Instance();
  config->Init(argc,argv,true);

  // Test
  std::cout<<"OTB MPI config test. I am process "<<config->GetMyRank()<<" among "<<config->GetNbProcs()<<"."<<std::endl;

  return EXIT_SUCCESS;
}

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

// MITK HEADER
#include "mitkUSImageVideoSource.h"
#include "mitkImage.h"

//OpenCV HEADER
#include <cv.h>
#include <highgui.h>

//Other
#include <stdio.h>

mitk::USImageVideoSource::USImageVideoSource()
  : m_VideoCapture(new cv::VideoCapture()),
  m_IsVideoReady(false),
  m_IsGreyscale(false),
  m_IsCropped(false),
  m_ResolutionOverrideWidth(0),
  m_ResolutionOverrideHeight(0),
  m_ResolutionOverride(false),
  m_GrayscaleFilter(mitk::ConvertGrayscaleOpenCVImageFilter::New()),
  m_CropFilter(mitk::CropOpenCVImageFilter::New())
{
}

mitk::USImageVideoSource::~USImageVideoSource()
{
  m_VideoCapture->release();
  delete m_VideoCapture;
}

void mitk::USImageVideoSource::SetVideoFileInput(std::string path)
{
  m_VideoCapture->open(path.c_str());

  // check if we succeeded
  if(!m_VideoCapture->isOpened()) { m_IsVideoReady = false; }
  else { m_IsVideoReady = true; }

  // if Override is enabled, use it
  if (m_ResolutionOverride)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, this->m_ResolutionOverrideWidth);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, this->m_ResolutionOverrideHeight);
  }
}

void mitk::USImageVideoSource::SetCameraInput(int deviceID)
{
  m_VideoCapture->open(deviceID);
  if(!m_VideoCapture->isOpened())  // check if we succeeded
    m_IsVideoReady = false;
  else
    m_IsVideoReady = true;

  // if Override is enabled, use it
  if (m_ResolutionOverride)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, this->m_ResolutionOverrideWidth);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, this->m_ResolutionOverrideHeight);
  }
}

void mitk::USImageVideoSource::ReleaseInput()
{
  m_VideoCapture->release();
  delete m_VideoCapture;
  m_VideoCapture = new cv::VideoCapture();
}

void mitk::USImageVideoSource::SetColorOutput(bool isColor){
  if ( ! isColor && ! m_IsGreyscale )
  {
    this->PushFilter(m_GrayscaleFilter.GetPointer());
  }
  else if ( isColor && m_IsGreyscale )
  {
    this->RemoveFilter(m_GrayscaleFilter.GetPointer());
  }

  m_IsGreyscale = !isColor;
}

int mitk::USImageVideoSource::GetImageHeight()
{
  if (m_VideoCapture) { return m_VideoCapture->get(CV_CAP_PROP_FRAME_HEIGHT); }
  else { return 0; }
}

int mitk::USImageVideoSource::GetImageWidth()
{
  if (m_VideoCapture) { return m_VideoCapture->get(CV_CAP_PROP_FRAME_WIDTH); }
  else { return 0; }
}

bool mitk::USImageVideoSource::GetIsReady()
{
  if (!m_VideoCapture) { return false; }

  return m_VideoCapture->isOpened();
}

void mitk::USImageVideoSource::SetRegionOfInterest(int topLeftX, int topLeftY, int bottomRightX, int bottomRightY)
{
  m_CropFilter->SetCropRegion(topLeftX, topLeftY, bottomRightX, bottomRightY);

  if (! m_IsCropped && ! m_CropFilter->GetIsCropRegionEmpty())
  {
    this->PushFilter(m_CropFilter.GetPointer());
    m_IsCropped = true;
  }
}

void mitk::USImageVideoSource::SetRegionOfInterest(USImageRoi roi)
{
  this->SetRegionOfInterest(roi.topLeftX, roi.topLeftY, roi.bottomRightX, roi.bottomRightY);
}

void mitk::USImageVideoSource::SetCropping(USImageCropping cropping)
{
  int width = this->GetImageWidth();
  int height = this->GetImageHeight();

  this->SetRegionOfInterest(cropping.left, cropping.top, width - cropping.right, height - cropping.bottom);
}

mitk::USImageVideoSource::USImageCropping mitk::USImageVideoSource::GetCropping()
{
  cv::Rect cropRect = m_CropFilter->GetCropRegion();

  USImageCropping cropping;
  cropping.left = cropRect.x;
  cropping.top = cropRect.y;

  if ( cropRect.height == 0 )
  {
    cropping.bottom = 0;
  }
  else
  {
    cropping.bottom = this->GetImageHeight() - (cropRect.y + cropRect.height);
  }

  if ( cropRect.width == 0 )
  {
    cropping.right = 0;
  }
  else
  {
    cropping.right = this->GetImageWidth() - (cropRect.x + cropRect.width);
  }

  return cropping;
}

mitk::USImageVideoSource::USImageRoi  mitk::USImageVideoSource::GetRegionOfInterest()
{
  cv::Rect cropRect = m_CropFilter->GetCropRegion();

  return USImageRoi(cropRect.x, cropRect.y, cropRect.x + cropRect.width, cropRect.y + cropRect.height);
}

void mitk::USImageVideoSource::RemoveRegionOfInterest()
{
  this->RemoveFilter(m_CropFilter.GetPointer());
  m_IsCropped = false;
}

void mitk::USImageVideoSource::GetNextRawImage( cv::Mat& image )
{
  // loop video if necessary
  if (m_VideoCapture->get(CV_CAP_PROP_POS_AVI_RATIO) >= 0.99 )
  {
    m_VideoCapture->set(CV_CAP_PROP_POS_AVI_RATIO, 0);
  }

  // retrieve image
  *m_VideoCapture >> image; // get a new frame from camera
}

void mitk::USImageVideoSource::GetNextRawImage( mitk::Image::Pointer& image )
{
  cv::Mat cv_img;

  this->GetNextRawImage(cv_img);

  // convert to MITK-Image
  IplImage ipl_img = cv_img;

  this->m_OpenCVToMitkFilter->SetOpenCVImage(&ipl_img);
  this->m_OpenCVToMitkFilter->Update();

  // OpenCVToMitkImageFilter returns a standard mitk::image. We then transform it into an USImage
  image = this->m_OpenCVToMitkFilter->GetOutput();

  // clean up
  cv_img.release();
}

void mitk::USImageVideoSource::OverrideResolution(int width, int height)
{
  this->m_ResolutionOverrideHeight = height;
  this->m_ResolutionOverrideWidth = width;

  if (m_VideoCapture != 0)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, width);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, height);
  }
}
<commit_msg>Changed end reached condition to use the frames count instead of the avi ratio.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

// MITK HEADER
#include "mitkUSImageVideoSource.h"
#include "mitkImage.h"

//OpenCV HEADER
#include <cv.h>
#include <highgui.h>

//Other
#include <stdio.h>

mitk::USImageVideoSource::USImageVideoSource()
  : m_VideoCapture(new cv::VideoCapture()),
  m_IsVideoReady(false),
  m_IsGreyscale(false),
  m_IsCropped(false),
  m_ResolutionOverrideWidth(0),
  m_ResolutionOverrideHeight(0),
  m_ResolutionOverride(false),
  m_GrayscaleFilter(mitk::ConvertGrayscaleOpenCVImageFilter::New()),
  m_CropFilter(mitk::CropOpenCVImageFilter::New())
{
}

mitk::USImageVideoSource::~USImageVideoSource()
{
  m_VideoCapture->release();
  delete m_VideoCapture;
}

void mitk::USImageVideoSource::SetVideoFileInput(std::string path)
{
  m_VideoCapture->open(path.c_str());

  // check if we succeeded
  if(!m_VideoCapture->isOpened()) { m_IsVideoReady = false; }
  else { m_IsVideoReady = true; }

  // if Override is enabled, use it
  if (m_ResolutionOverride)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, this->m_ResolutionOverrideWidth);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, this->m_ResolutionOverrideHeight);
  }
}

void mitk::USImageVideoSource::SetCameraInput(int deviceID)
{
  m_VideoCapture->open(deviceID);
  if(!m_VideoCapture->isOpened())  // check if we succeeded
    m_IsVideoReady = false;
  else
    m_IsVideoReady = true;

  // if Override is enabled, use it
  if (m_ResolutionOverride)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, this->m_ResolutionOverrideWidth);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, this->m_ResolutionOverrideHeight);
  }
}

void mitk::USImageVideoSource::ReleaseInput()
{
  m_VideoCapture->release();
  delete m_VideoCapture;
  m_VideoCapture = new cv::VideoCapture();
}

void mitk::USImageVideoSource::SetColorOutput(bool isColor){
  if ( ! isColor && ! m_IsGreyscale )
  {
    this->PushFilter(m_GrayscaleFilter.GetPointer());
  }
  else if ( isColor && m_IsGreyscale )
  {
    this->RemoveFilter(m_GrayscaleFilter.GetPointer());
  }

  m_IsGreyscale = !isColor;
}

int mitk::USImageVideoSource::GetImageHeight()
{
  if (m_VideoCapture) { return m_VideoCapture->get(CV_CAP_PROP_FRAME_HEIGHT); }
  else { return 0; }
}

int mitk::USImageVideoSource::GetImageWidth()
{
  if (m_VideoCapture) { return m_VideoCapture->get(CV_CAP_PROP_FRAME_WIDTH); }
  else { return 0; }
}

bool mitk::USImageVideoSource::GetIsReady()
{
  if (!m_VideoCapture) { return false; }

  return m_VideoCapture->isOpened();
}

void mitk::USImageVideoSource::SetRegionOfInterest(int topLeftX, int topLeftY, int bottomRightX, int bottomRightY)
{
  m_CropFilter->SetCropRegion(topLeftX, topLeftY, bottomRightX, bottomRightY);

  if (! m_IsCropped && ! m_CropFilter->GetIsCropRegionEmpty())
  {
    this->PushFilter(m_CropFilter.GetPointer());
    m_IsCropped = true;
  }
}

void mitk::USImageVideoSource::SetRegionOfInterest(USImageRoi roi)
{
  this->SetRegionOfInterest(roi.topLeftX, roi.topLeftY, roi.bottomRightX, roi.bottomRightY);
}

void mitk::USImageVideoSource::SetCropping(USImageCropping cropping)
{
  int width = this->GetImageWidth();
  int height = this->GetImageHeight();

  this->SetRegionOfInterest(cropping.left, cropping.top, width - cropping.right, height - cropping.bottom);
}

mitk::USImageVideoSource::USImageCropping mitk::USImageVideoSource::GetCropping()
{
  cv::Rect cropRect = m_CropFilter->GetCropRegion();

  USImageCropping cropping;
  cropping.left = cropRect.x;
  cropping.top = cropRect.y;

  if ( cropRect.height == 0 )
  {
    cropping.bottom = 0;
  }
  else
  {
    cropping.bottom = this->GetImageHeight() - (cropRect.y + cropRect.height);
  }

  if ( cropRect.width == 0 )
  {
    cropping.right = 0;
  }
  else
  {
    cropping.right = this->GetImageWidth() - (cropRect.x + cropRect.width);
  }

  return cropping;
}

mitk::USImageVideoSource::USImageRoi  mitk::USImageVideoSource::GetRegionOfInterest()
{
  cv::Rect cropRect = m_CropFilter->GetCropRegion();

  return USImageRoi(cropRect.x, cropRect.y, cropRect.x + cropRect.width, cropRect.y + cropRect.height);
}

void mitk::USImageVideoSource::RemoveRegionOfInterest()
{
  this->RemoveFilter(m_CropFilter.GetPointer());
  m_IsCropped = false;
}

void mitk::USImageVideoSource::GetNextRawImage( cv::Mat& image )
{
  // loop video if necessary
  if (m_VideoCapture->get(CV_CAP_PROP_POS_FRAMES) == m_VideoCapture->get(CV_CAP_PROP_FRAME_COUNT))
  {
    m_VideoCapture->set(CV_CAP_PROP_POS_FRAMES, 0);
  }

  // retrieve image
  *m_VideoCapture >> image; // get a new frame from camera
}

void mitk::USImageVideoSource::GetNextRawImage( mitk::Image::Pointer& image )
{
  cv::Mat cv_img;

  this->GetNextRawImage(cv_img);

  // convert to MITK-Image
  IplImage ipl_img = cv_img;

  this->m_OpenCVToMitkFilter->SetOpenCVImage(&ipl_img);
  this->m_OpenCVToMitkFilter->Update();

  // OpenCVToMitkImageFilter returns a standard mitk::image. We then transform it into an USImage
  image = this->m_OpenCVToMitkFilter->GetOutput();

  // clean up
  cv_img.release();
}

void mitk::USImageVideoSource::OverrideResolution(int width, int height)
{
  this->m_ResolutionOverrideHeight = height;
  this->m_ResolutionOverrideWidth = width;

  if (m_VideoCapture != 0)
  {
    m_VideoCapture->set(CV_CAP_PROP_FRAME_WIDTH, width);
    m_VideoCapture->set(CV_CAP_PROP_FRAME_HEIGHT, height);
  }
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCLuaScriptModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLuaScriptModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCLuaScriptModule.h"
#include "NFLuaScriptPlugin.h"
#include <assert.h>

#define TRY_RUN_GLOBAL_SCRIPT_FUN0(strFuncName)  try{luacpp::call<void>(lw, strFuncName);} catch (string &err){printf("%s\n", err.c_str());}
#define TRY_RUN_GLOBAL_SCRIPT_FUN1(strFuncName, arg1)  try{luacpp::call<void>(lw, strFuncName, arg1);} catch (string &err){printf("%s\n", err.c_str());}

#define TRY_LOAD_SCRIPT_FLE(strFileName)  try{lw.dofile(strFileName);} catch (string &err){printf("%s\n", err.c_str());}
#define TRY_ADD_PACKAGE_PATH(strFilePath)  try{lw.addPackagePath(strFilePath);} catch (string &err){printf("%s\n", err.c_str());}

bool NFCLuaScriptModule::Init()
{
	mnTime = pPluginManager->GetNowTime();

	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>("NFCKernelModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");

	assert(NULL != m_pKernelModule);
	assert(NULL != m_pLogicClassModule);
	assert(NULL != m_pElementInfoModule);

	Regisger();
	TRY_ADD_PACKAGE_PATH("../../NFDataCfg/ScriptModule");
	TRY_LOAD_SCRIPT_FLE("script_init.lua");
	TRY_RUN_GLOBAL_SCRIPT_FUN1("init_script_system", m_pKernelModule);
	TRY_LOAD_SCRIPT_FLE("script_list.lua");

	TRY_RUN_GLOBAL_SCRIPT_FUN0("Init");

	return true;
}

bool NFCLuaScriptModule::AfterInit()
{
	//add all callback
	m_pKernelModule->ResgisterCommonPropertyEvent(this, &NFCLuaScriptModule::OnPropertyCommEvent);
	m_pKernelModule->ResgisterCommonRecordEvent(this, &NFCLuaScriptModule::OnRecordCommonEvent);
	m_pKernelModule->ResgisterCommonClassEvent(this, &NFCLuaScriptModule::OnClassCommonEvent);

	TRY_RUN_GLOBAL_SCRIPT_FUN0("AfterInit");

	return true;
}

bool NFCLuaScriptModule::Shut()
{
	TRY_RUN_GLOBAL_SCRIPT_FUN0("Shut");

	return true;
}

bool NFCLuaScriptModule::Execute()
{
	//10秒钟reload一次
	if (pPluginManager->GetNowTime() - mnTime > 5)
	{
		mnTime = pPluginManager->GetNowTime();

		TRY_RUN_GLOBAL_SCRIPT_FUN0("Execute");

		TRY_LOAD_SCRIPT_FLE("script_reload.lua")

	}

	return true;
}

bool NFCLuaScriptModule::BeforeShut()
{
	TRY_RUN_GLOBAL_SCRIPT_FUN0("BeforeShut");

	return true;
}

int NFCLuaScriptModule::OnPropertyCommEvent(const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoPropertyCommEvent(self, strPropertyName, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnRecordCommonEvent(const NFGUID& self, const RECORD_EVENT_DATA& xEventData, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoRecordCommonEvent(self, xEventData, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnClassCommonEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
	DoClassCommonEvent(m_pLogicClassModule, self, strClassName, eClassEvent, var);

	return 0;
}

int NFCLuaScriptModule::DoScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}

	return 1;
}

int NFCLuaScriptModule::DoEventScript(const NFGUID& self, const int nEventID, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, nEventID, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, nEventID, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoHeartBeatScript(const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount, std::string& strComponentName, const std::string& strFunction)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strHeartBeat.c_str(), fTime, nCount);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strHeartBeat.c_str(), fTime, nCount);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptPropertyCallBack(const NFGUID& self, const std::string& strPropertyName, const std::string& strComponentName, const std::string& strFunction, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strPropertyName.c_str(), &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strPropertyName.c_str(), oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptRecordCallBack(const NFGUID& self, const std::string& strRecordName, const std::string& strComponentName, const std::string& strFunction, const int nOpType, const int nRow, const int nCol, const NFCDataList::TData& oldVar, const NFCDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strRecordName.c_str(), nOpType, nRow, nCol, &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strRecordName.c_str(), nOpType, nRow, nCol, oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

bool NFCLuaScriptModule::Regisger()
{
	luacpp::reg_cclass<NFGUID>::_reg(lw, "NFGUID")
		.constructor<void>()//ÎÞ²Î¹¹Ôì
		//.constructor<const test_class_A&>()//Ò»¸ö²ÎÊý¹¹Ôì
		.method("GetData", &NFGUID::GetData)
		.method("SetData", &NFGUID::SetData)
		.method("GetHead", &NFGUID::GetHead)
		.method("SetHead", &NFGUID::SetHead);
	luacpp::reg_cclass<NFIKernelModule>::_reg(lw, "NFIKernelModule")
		.property("strName", &NFIKernelModule::strName);

	luacpp::reg_cclass<NFIDataList>::_reg(lw, "NFIDataList");

	luacpp::reg_cclass<NFCDataList>::_reg(lw, "NFCDataList")
		.constructor<void>()
		.method("IsEmpty", &NFCDataList::IsEmpty)
		.method("GetCount", &NFCDataList::GetCount)
		.method("Type", &NFCDataList::Type)
		.method("AddInt", &NFCDataList::AddInt)
		.method("AddFloat", &NFCDataList::AddFloat)
		.method("AddString", &NFCDataList::AddStringFromChar)
		.method("AddObject", &NFCDataList::AddObject)
		.method("SetInt", &NFCDataList::SetInt)
		.method("SetFloat", &NFCDataList::SetFloat)
		.method("SetString", &NFCDataList::SetString)
		.method("SetObject", &NFCDataList::SetObject)
		.method("Int", &NFCDataList::Int)
		.method("Float", &NFCDataList::Float)
		.method("String", &NFCDataList::String)
		.method("Object", &NFCDataList::Object);

	luacpp::reg_cclass<NFCDataList::TData>::_reg(lw, "TData")
		.constructor<void>()//ÎÞ²Î¹¹Ôì
		.method("GetFloat", &NFCDataList::TData::GetFloat)
		.method("GetInt", &NFCDataList::TData::GetInt)
		.method("GetObjectA", &NFCDataList::TData::GetObjectA)
		.method("GetString", &NFCDataList::TData::GetCharArr)
		.method("GetType", &NFCDataList::TData::GetType)
		.method("IsNullValue", &NFCDataList::TData::IsNullValue)
		.method("SetFloat", &NFCDataList::TData::SetFloat)
		.method("SetInt", &NFCDataList::TData::SetInt)
		.method("SetObject", &NFCDataList::TData::SetObject)
		.method("SetString", &NFCDataList::TData::SetString)
		.method("StringValEx", &NFCDataList::TData::StringValEx)
		.property("GetData", &NFCDataList::TData::variantData);

	luacpp::reg_cfun(lw, "DoEvent", &KernelModule_DoEvent);
	luacpp::reg_cfun(lw, "ExistElement", &KernelModule_ExistElement);
	luacpp::reg_cfun(lw, "GetElementPropertyInt", &KernelModule_GetElementPropertyInt);
	luacpp::reg_cfun(lw, "GetElementPropertyFloat", &KernelModule_GetElementPropertyFloat);
	luacpp::reg_cfun(lw, "GetElementPropertyString", &KernelModule_GetElementPropertyString);
	luacpp::reg_cfun(lw, "AddPropertyCallBack", &KernelModule_AddPropertyCallBack);
	luacpp::reg_cfun(lw, "AddRecordCallBack", &KernelModule_AddRecordCallBack);
	luacpp::reg_cfun(lw, "AddEventCallBack", &KernelModule_AddEventCallBack);
	luacpp::reg_cfun(lw, "AddHeartBeat", &KernelModule_AddHeartBeat);
	luacpp::reg_cfun(lw, "FindHeartBeat", &KernelModule_FindHeartBeat);
	luacpp::reg_cfun(lw, "RemoveHeartBeat", &KernelModule_RemoveHeartBeat);
	luacpp::reg_cfun(lw, "ExistContainer", &KernelModule_ExistContainer);
	luacpp::reg_cfun(lw, "SetPropertyInt", &KernelModule_SetPropertyInt);
	luacpp::reg_cfun(lw, "SetPropertyFloat", &KernelModule_SetPropertyFloat);
	luacpp::reg_cfun(lw, "SetPropertyString", &KernelModule_SetPropertyString);
	luacpp::reg_cfun(lw, "SetPropertyObject", &KernelModule_SetPropertyObject);
	luacpp::reg_cfun(lw, "GetPropertyInt", &KernelModule_GetPropertyInt);
	luacpp::reg_cfun(lw, "GetPropertyFloat", &KernelModule_GetPropertyFloat);
	luacpp::reg_cfun(lw, "GetPropertyString", &KernelModule_GetPropertyString);
	luacpp::reg_cfun(lw, "GetPropertyObject", &KernelModule_GetPropertyObject);
	luacpp::reg_cfun(lw, "SetRecordInt", &KernelModule_SetRecordInt);
	luacpp::reg_cfun(lw, "SetRecordFloat", &KernelModule_SetRecordFloat);
	luacpp::reg_cfun(lw, "SetRecordString", &KernelModule_SetRecordString);
	luacpp::reg_cfun(lw, "SetRecordObject", &KernelModule_SetRecordObject);
	luacpp::reg_cfun(lw, "GetRecordInt", &KernelModule_GetRecordInt);
	luacpp::reg_cfun(lw, "GetRecordFloat", &KernelModule_GetRecordFloat);
	luacpp::reg_cfun(lw, "GetRecordString", &KernelModule_GetRecordString);
	luacpp::reg_cfun(lw, "GetRecordObject", &KernelModule_GetRecordObject);
	luacpp::reg_cfun(lw, "AddRow", &KernelModule_AddRow);

	return true;
}

int NFCLuaScriptModule::DoClassCommonScript(const NFGUID& self, const std::string& strComponentName, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule);
		luacpp::call<void>(lw, "onClassCommonEvent", (NFINT64)m_pKernelModule, self, strComponentName, strClassName, (int)eClassEvent);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 0;
}
<commit_msg>Update NFCLuaScriptModule.cpp<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCLuaScriptModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLuaScriptModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCLuaScriptModule.h"
#include "NFLuaScriptPlugin.h"
#include <assert.h>

#define TRY_RUN_GLOBAL_SCRIPT_FUN0(strFuncName)  try{luacpp::call<void>(lw, strFuncName);} catch (string &err){printf("%s\n", err.c_str());}
#define TRY_RUN_GLOBAL_SCRIPT_FUN1(strFuncName, arg1)  try{luacpp::call<void>(lw, strFuncName, arg1);} catch (string &err){printf("%s\n", err.c_str());}

#define TRY_LOAD_SCRIPT_FLE(strFileName)  try{lw.dofile(strFileName);} catch (string &err){printf("%s\n", err.c_str());}
#define TRY_ADD_PACKAGE_PATH(strFilePath)  try{lw.addPackagePath(strFilePath);} catch (string &err){printf("%s\n", err.c_str());}

bool NFCLuaScriptModule::Init()
{
	mnTime = pPluginManager->GetNowTime();

	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>("NFCKernelModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");

	assert(NULL != m_pKernelModule);
	assert(NULL != m_pLogicClassModule);
	assert(NULL != m_pElementInfoModule);

	Regisger();
	TRY_ADD_PACKAGE_PATH("../../NFDataCfg/ScriptModule");
	TRY_LOAD_SCRIPT_FLE("script_init.lua");
	TRY_RUN_GLOBAL_SCRIPT_FUN1("init_script_system", m_pKernelModule);
	TRY_LOAD_SCRIPT_FLE("script_list.lua");

	TRY_RUN_GLOBAL_SCRIPT_FUN0("Init");

	return true;
}

bool NFCLuaScriptModule::AfterInit()
{
	//add all callback
	m_pKernelModule->ResgisterCommonPropertyEvent(this, &NFCLuaScriptModule::OnPropertyCommEvent);
	m_pKernelModule->ResgisterCommonRecordEvent(this, &NFCLuaScriptModule::OnRecordCommonEvent);
	m_pKernelModule->ResgisterCommonClassEvent(this, &NFCLuaScriptModule::OnClassCommonEvent);

	TRY_RUN_GLOBAL_SCRIPT_FUN0("AfterInit");

	return true;
}

bool NFCLuaScriptModule::Shut()
{
	TRY_RUN_GLOBAL_SCRIPT_FUN0("Shut");

	return true;
}

bool NFCLuaScriptModule::Execute()
{
	//10秒钟reload一次
	if (pPluginManager->GetNowTime() - mnTime > 5)
	{
		mnTime = pPluginManager->GetNowTime();

		TRY_RUN_GLOBAL_SCRIPT_FUN0("Execute");

		TRY_LOAD_SCRIPT_FLE("script_reload.lua")

	}

	return true;
}

bool NFCLuaScriptModule::BeforeShut()
{
	TRY_RUN_GLOBAL_SCRIPT_FUN0("BeforeShut");

	return true;
}

int NFCLuaScriptModule::OnPropertyCommEvent(const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoPropertyCommEvent(self, strPropertyName, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnRecordCommonEvent(const NFGUID& self, const RECORD_EVENT_DATA& xEventData, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	DoRecordCommonEvent(self, xEventData, oldVar, newVar);

	return 0;
}

int NFCLuaScriptModule::OnClassCommonEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var)
{
	DoClassCommonEvent(m_pLogicClassModule, self, strClassName, eClassEvent, var);

	return 0;
}

int NFCLuaScriptModule::DoScript(const NFGUID& self, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}

	return 1;
}

int NFCLuaScriptModule::DoEventScript(const NFGUID& self, const int nEventID, const std::string& strComponentName, const std::string& strFunction, const NFCDataList& arg)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, nEventID, &arg);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, nEventID, arg);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoHeartBeatScript(const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount, std::string& strComponentName, const std::string& strFunction)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strHeartBeat.c_str(), fTime, nCount);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strHeartBeat.c_str(), fTime, nCount);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptPropertyCallBack(const NFGUID& self, const std::string& strPropertyName, const std::string& strComponentName, const std::string& strFunction, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strPropertyName.c_str(), &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strPropertyName.c_str(), oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

int NFCLuaScriptModule::DoScriptRecordCallBack(const NFGUID& self, const std::string& strRecordName, const std::string& strComponentName, const std::string& strFunction, const int nOpType, const int nRow, const int nCol, const NFCDataList::TData& oldVar, const NFCDataList::TData& newVar)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule, &self, strRecordName.c_str(), nOpType, nRow, nCol, &oldVar, &newVar);
		luacpp::call<void>(lw, strFunction.c_str(), (NFINT64)m_pKernelModule, self, strRecordName.c_str(), nOpType, nRow, nCol, oldVar, newVar);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 1;
}

bool NFCLuaScriptModule::Regisger()
{
	luacpp::reg_cclass<NFGUID>::_reg(lw, "NFGUID")
		.constructor<void>()//ÎÞ²Î¹¹Ôì
		//.constructor<const test_class_A&>()//Ò»¸ö²ÎÊý¹¹Ôì
		.method("GetData", &NFGUID::GetData)
		.method("SetData", &NFGUID::SetData)
		.method("GetHead", &NFGUID::GetHead)
		.method("SetHead", &NFGUID::SetHead);
	luacpp::reg_cclass<NFIKernelModule>::_reg(lw, "NFIKernelModule")
		.property("strName", &NFIKernelModule::strName);

	luacpp::reg_cclass<NFIDataList>::_reg(lw, "NFIDataList");

	luacpp::reg_cclass<NFCDataList>::_reg(lw, "NFCDataList")
		.constructor<void>()
		.method("IsEmpty", &NFCDataList::IsEmpty)
		.method("GetCount", &NFCDataList::GetCount)
		.method("Type", &NFCDataList::Type)
		.method("AddInt", &NFCDataList::AddInt)
		.method("AddFloat", &NFCDataList::AddFloat)
		.method("AddString", &NFCDataList::AddStringFromChar)
		.method("AddObject", &NFCDataList::AddObject)
		.method("SetInt", &NFCDataList::SetInt)
		.method("SetFloat", &NFCDataList::SetFloat)
		.method("SetString", &NFCDataList::SetString)
		.method("SetObject", &NFCDataList::SetObject)
		.method("Int", &NFCDataList::Int)
		.method("Float", &NFCDataList::Float)
		.method("String", &NFCDataList::String)
		.method("Object", &NFCDataList::Object);

	luacpp::reg_cclass<NFCDataList::TData>::_reg(lw, "TData")
		.constructor<void>()//ÎÞ²Î¹¹Ôì
		.method("GetFloat", &NFCDataList::TData::GetFloat)
		.method("GetInt", &NFCDataList::TData::GetInt)
		.method("GetObjectA", &NFCDataList::TData::GetObjectA)
		.method("GetString", &NFCDataList::TData::GetCharArr)
		.method("GetType", &NFCDataList::TData::GetType)
		.method("IsNullValue", &NFCDataList::TData::IsNullValue)
		.method("SetFloat", &NFCDataList::TData::SetFloat)
		.method("SetInt", &NFCDataList::TData::SetInt)
		.method("SetObject", &NFCDataList::TData::SetObject)
		.method("SetString", &NFCDataList::TData::SetString)
		.method("StringValEx", &NFCDataList::TData::StringValEx)
		.property("GetData", &NFCDataList::TData::variantData);

	luacpp::reg_cfun(lw, "DoEvent", &KernelModule_DoEvent);
	luacpp::reg_cfun(lw, "ExistElement", &KernelModule_ExistElement);
	luacpp::reg_cfun(lw, "GetElementPropertyInt", &KernelModule_GetElementPropertyInt);
	luacpp::reg_cfun(lw, "GetElementPropertyFloat", &KernelModule_GetElementPropertyFloat);
	luacpp::reg_cfun(lw, "GetElementPropertyString", &KernelModule_GetElementPropertyString);
	luacpp::reg_cfun(lw, "AddPropertyCallBack", &KernelModule_AddPropertyCallBack);
	luacpp::reg_cfun(lw, "AddRecordCallBack", &KernelModule_AddRecordCallBack);
	luacpp::reg_cfun(lw, "AddEventCallBack", &KernelModule_AddEventCallBack);
	luacpp::reg_cfun(lw, "AddHeartBeat", &KernelModule_AddHeartBeat);
	luacpp::reg_cfun(lw, "FindHeartBeat", &KernelModule_FindHeartBeat);
	luacpp::reg_cfun(lw, "RemoveHeartBeat", &KernelModule_RemoveHeartBeat);
	luacpp::reg_cfun(lw, "ExistContainer", &KernelModule_ExistContainer);
	luacpp::reg_cfun(lw, "SetPropertyInt", &KernelModule_SetPropertyInt);
	luacpp::reg_cfun(lw, "SetPropertyFloat", &KernelModule_SetPropertyFloat);
	luacpp::reg_cfun(lw, "SetPropertyString", &KernelModule_SetPropertyString);
	luacpp::reg_cfun(lw, "SetPropertyObject", &KernelModule_SetPropertyObject);
	luacpp::reg_cfun(lw, "GetPropertyInt", &KernelModule_GetPropertyInt);
	luacpp::reg_cfun(lw, "GetPropertyFloat", &KernelModule_GetPropertyFloat);
	luacpp::reg_cfun(lw, "GetPropertyString", &KernelModule_GetPropertyString);
	luacpp::reg_cfun(lw, "GetPropertyObject", &KernelModule_GetPropertyObject);
	luacpp::reg_cfun(lw, "SetRecordInt", &KernelModule_SetRecordInt);
	luacpp::reg_cfun(lw, "SetRecordFloat", &KernelModule_SetRecordFloat);
	luacpp::reg_cfun(lw, "SetRecordString", &KernelModule_SetRecordString);
	luacpp::reg_cfun(lw, "SetRecordObject", &KernelModule_SetRecordObject);
	luacpp::reg_cfun(lw, "GetRecordInt", &KernelModule_GetRecordInt);
	luacpp::reg_cfun(lw, "GetRecordFloat", &KernelModule_GetRecordFloat);
	luacpp::reg_cfun(lw, "GetRecordString", &KernelModule_GetRecordString);
	luacpp::reg_cfun(lw, "GetRecordObject", &KernelModule_GetRecordObject);
	luacpp::reg_cfun(lw, "AddRow", &KernelModule_AddRow);

	return true;
}

int NFCLuaScriptModule::DoClassCommonScript(const NFGUID& self, const std::string& strComponentName, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent)
{
	try
	{
		//fflua.call<void>(strFunction.c_str(), (NFINT64)m_pKernelModule);
		luacpp::call<void>(lw, "OnClassCommonEvent", (NFINT64)m_pKernelModule, self, strComponentName, strClassName, (int)eClassEvent);
	}
	catch (string &err)
	{
		printf("%s\n", err.c_str());
		return 0;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "style.h"

#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"

#include "csscolorparser.hpp"

#include <sstream>

std::unordered_map<std::bitset<MAX_LAYERS>, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;

using namespace Tangram;

Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}

Style::~Style() {
    m_layers.clear();
}

uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
    uint32_t color = 0;

    if (_colorPropStr.find(',') != std::string::npos) { // try to parse as comma-separated rgba components
        std::istringstream stream(_colorPropStr);
        std::string token;
        unsigned char i = 0;
        while (std::getline(stream, token, ',') && i < 4) {
            color += (uint32_t(std::stod(token) * 255.)) << (8 * i++);
        }
    } else { // parse as css color or #hex-num
        color = CSSColorParser::parse(_colorPropStr).getInt();
    }
    return color;
}

void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {

    constructVertexLayout();
    constructShaderProgram();

    switch (m_lightingType) {
        case LightingType::vertex:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
            break;
        case LightingType::fragment:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
            break;
        default:
            break;
    }

    m_material->injectOnProgram(m_shaderProgram);

    for (auto& light : _lights) {
        light->injectOnProgram(m_shaderProgram);
    }

}

void Style::setMaterial(const std::shared_ptr<Material>& _material) {

    m_material = _material;

}

void Style::setLightingType(LightingType _type){

    m_lightingType = _type;

}

void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {

    m_layers.push_back(std::move(_layer));

}

void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, std::bitset<MAX_LAYERS>& _uniqueID,
                                   StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {

    std::vector<std::shared_ptr<SceneLayer>> sLayers;
    sLayers.reserve(_uberLayer->getSublayers().size() + 1);
    sLayers.push_back(_uberLayer);

    auto sLayerItr = sLayers.begin();

    //A BFS traversal of the SceneLayer graph
    while (sLayerItr != sLayers.end()) {

        auto sceneLyr = *sLayerItr;

        if (sceneLyr->getFilter().eval(_feature, _ctx)) { // filter matches

            _uniqueID.set(sceneLyr->getID());

            {
                std::lock_guard<std::mutex> lock(s_cacheMutex);

                if(s_styleParamMapCache.find(_uniqueID) != s_styleParamMapCache.end()) {

                    _styleParamMapMix = s_styleParamMapCache.at(_uniqueID);

                } else {

                    /* update StyleParam with subLayer parameters */
                    auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
                    for(auto& styleParam : layerStyleParamMap) {
                        _styleParamMapMix[styleParam.first] = styleParam.second;
                    }

                    s_styleParamMapCache.emplace(_uniqueID, _styleParamMapMix);
                }
            }

            /* append sLayers with sublayers of this layer */
            auto& ssLayers = sceneLyr->getSublayers();
            sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
        } else {
            sLayerItr++;
        }
    }
}

void Style::addData(TileData& _data, Tile& _tile) {

    std::shared_ptr<VboMesh> mesh(newMesh());

    onBeginBuildTile(*mesh);

    Context ctx;
    ctx["$zoom"] = Value(_tile.getID().z);

    for (auto& layer : _data.layers) {

        // Skip any layers that this style doesn't have a rule for
        auto it = m_layers.begin();
        while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
        if (it == m_layers.end()) { continue; }

        // Loop over all features
        for (auto& feature : layer.features) {

            std::bitset<MAX_LAYERS> uniqueID(0);
            StyleParamMap styleParamMapMix;
            applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));

            if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
                feature.props.numericProps["zoom"] = _tile.getID().z;

                switch (feature.geometryType) {
                    case GeometryType::points:
                        // Build points
                        for (auto& point : feature.points) {
                            buildPoint(point, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    case GeometryType::lines:
                        // Build lines
                        for (auto& line : feature.lines) {
                            buildLine(line, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    case GeometryType::polygons:
                        // Build polygons
                        for (auto& polygon : feature.polygons) {
                            buildPolygon(polygon, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    onEndBuildTile(*mesh);

    if (mesh->numVertices() == 0) {
        mesh.reset();
    } else {
        mesh->compileVertexBuffer();

        _tile.addGeometry(*this, mesh);
    }
}

void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {

    m_material->setupProgram(m_shaderProgram);

    // Set up lights
    for (const auto& light : _scene->getLights()) {
        light->setupProgram(_view, m_shaderProgram);
    }

    m_shaderProgram->setUniformf("u_zoom", _view->getZoom());

    // default capabilities
    RenderState::blending(GL_FALSE);
    RenderState::depthTest(GL_TRUE);
}

void Style::onBeginBuildTile(VboMesh& _mesh) const {
    // No-op by default
}

void Style::onEndBuildTile(VboMesh& _mesh) const {
    // No-op by default
}

void Style::buildPoint(Point& _point, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildLine(Line& _line, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildPolygon(Polygon& _polygon, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}
<commit_msg>use a single cache lookup per (sub)layer<commit_after>#include "style.h"

#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"

#include "csscolorparser.hpp"

#include <sstream>

std::unordered_map<std::bitset<MAX_LAYERS>, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;

using namespace Tangram;

Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}

Style::~Style() {
    m_layers.clear();
}

uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
    uint32_t color = 0;

    if (_colorPropStr.find(',') != std::string::npos) { // try to parse as comma-separated rgba components
        std::istringstream stream(_colorPropStr);
        std::string token;
        unsigned char i = 0;
        while (std::getline(stream, token, ',') && i < 4) {
            color += (uint32_t(std::stod(token) * 255.)) << (8 * i++);
        }
    } else { // parse as css color or #hex-num
        color = CSSColorParser::parse(_colorPropStr).getInt();
    }
    return color;
}

void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {

    constructVertexLayout();
    constructShaderProgram();

    switch (m_lightingType) {
        case LightingType::vertex:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
            break;
        case LightingType::fragment:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
            break;
        default:
            break;
    }

    m_material->injectOnProgram(m_shaderProgram);

    for (auto& light : _lights) {
        light->injectOnProgram(m_shaderProgram);
    }

}

void Style::setMaterial(const std::shared_ptr<Material>& _material) {

    m_material = _material;

}

void Style::setLightingType(LightingType _type){

    m_lightingType = _type;

}

void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {

    m_layers.push_back(std::move(_layer));

}

void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, std::bitset<MAX_LAYERS>& _uniqueID,
                                   StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {

    std::vector<std::shared_ptr<SceneLayer>> sLayers;
    sLayers.reserve(_uberLayer->getSublayers().size() + 1);
    sLayers.push_back(_uberLayer);

    auto sLayerItr = sLayers.begin();

    // A BFS traversal of the SceneLayer graph
    while (sLayerItr != sLayers.end()) {

        auto sceneLyr = *sLayerItr;

        if (sceneLyr->getFilter().eval(_feature, _ctx)) { // filter matches

            _uniqueID.set(sceneLyr->getID());
            {
                std::lock_guard<std::mutex> lock(s_cacheMutex);

                // Get or create cache entry
                auto& entry = s_styleParamMapCache[_uniqueID];

                if (!entry.empty()) {
                    _styleParamMapMix = entry;

                } else {
                    // Update StyleParam with subLayer parameters

                    auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
                    for(auto& styleParam : layerStyleParamMap) {
                        _styleParamMapMix[styleParam.first] = styleParam.second;
                    }
                    entry = _styleParamMapMix;
                }
            }

            // Append sLayers with sublayers of this layer
            auto& ssLayers = sceneLyr->getSublayers();
            sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
        } else {
            sLayerItr++;
        }
    }
}

void Style::addData(TileData& _data, Tile& _tile) {

    std::shared_ptr<VboMesh> mesh(newMesh());

    onBeginBuildTile(*mesh);

    Context ctx;
    ctx["$zoom"] = Value(_tile.getID().z);

    for (auto& layer : _data.layers) {

        // Skip any layers that this style doesn't have a rule for
        auto it = m_layers.begin();
        while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
        if (it == m_layers.end()) { continue; }

        // Loop over all features
        for (auto& feature : layer.features) {

            std::bitset<MAX_LAYERS> uniqueID(0);
            StyleParamMap styleParamMapMix;
            applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));

            if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
                feature.props.numericProps["zoom"] = _tile.getID().z;

                switch (feature.geometryType) {
                    case GeometryType::points:
                        // Build points
                        for (auto& point : feature.points) {
                            buildPoint(point, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    case GeometryType::lines:
                        // Build lines
                        for (auto& line : feature.lines) {
                            buildLine(line, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    case GeometryType::polygons:
                        // Build polygons
                        for (auto& polygon : feature.polygons) {
                            buildPolygon(polygon, styleParamMapMix, feature.props, *mesh, _tile);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    onEndBuildTile(*mesh);

    if (mesh->numVertices() == 0) {
        mesh.reset();
    } else {
        mesh->compileVertexBuffer();

        _tile.addGeometry(*this, mesh);
    }
}

void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {

    m_material->setupProgram(m_shaderProgram);

    // Set up lights
    for (const auto& light : _scene->getLights()) {
        light->setupProgram(_view, m_shaderProgram);
    }

    m_shaderProgram->setUniformf("u_zoom", _view->getZoom());

    // default capabilities
    RenderState::blending(GL_FALSE);
    RenderState::depthTest(GL_TRUE);
}

void Style::onBeginBuildTile(VboMesh& _mesh) const {
    // No-op by default
}

void Style::onEndBuildTile(VboMesh& _mesh) const {
    // No-op by default
}

void Style::buildPoint(Point& _point, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildLine(Line& _line, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildPolygon(Polygon& _polygon, const StyleParamMap& _styleParamMap, Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}
<|endoftext|>


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

#ifndef SKUI_CSS_LENGTH_H
#define SKUI_CSS_LENGTH_H

#include <iosfwd>

namespace skui::css
{
  enum class unit
  {
    // absolute
    cm, // centimeters
    mm, // millimeters
    in, // inches (1in = 96px = 2.54cm)
    px, // pixels (1px = 1/96th of 1in)
    pt, // points (1pt = 1/72 of 1in)
    pc, // picas (1pc = 12 pt)
    // relative
    em, // Relative to the font-size of the element (2em means 2 times the size of the current font)
    ex, // Relative to the x-height of the current font (rarely used)
    ch, // Relative to width of the "0" (zero)
    rem, // Relative to font-size of the root element
    vw, // Relative to 1% of the width of the viewport
    vh, // Relative to 1% of the height of the viewport
    vmin, // Relative to 1% of viewport's smaller dimension
    vmax, // Relative to 1% of viewport's larger dimension
    percentage, // Relative to the parent element
  };

  struct length
  {
    float value;

    css::unit unit;
  };

  std::ostream& operator<<(std::ostream& os, const css::unit unit);
  std::ostream& operator<<(std::ostream& os, const length& length);

  constexpr bool operator==(const length& left, const length& right)
  {
    return left.value == right.value && left.unit == right.unit;
  }
}

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

#ifndef SKUI_CSS_LENGTH_H
#define SKUI_CSS_LENGTH_H

#include <iosfwd>

namespace skui::css
{
  enum class unit
  {
    // absolute
    cm, // centimeters
    mm, // millimeters
    in, // inches (1in = 96px = 2.54cm)
    px, // pixels (1px = 1/96th of 1in)
    pt, // points (1pt = 1/72 of 1in)
    pc, // picas (1pc = 12 pt)
    // relative
    em, // Relative to the font-size of the element (2em means 2 times the size of the current font)
    ex, // Relative to the x-height of the current font (rarely used)
    ch, // Relative to width of the "0" (zero)
    rem, // Relative to font-size of the root element
    vw, // Relative to 1% of the width of the viewport
    vh, // Relative to 1% of the height of the viewport
    vmin, // Relative to 1% of viewport's smaller dimension
    vmax, // Relative to 1% of viewport's larger dimension
    percentage, // Relative to the parent element
  };

  struct length
  {
    float value;

    css::unit unit;
  };

  std::ostream& operator<<(std::ostream& os, const css::unit unit);
  std::ostream& operator<<(std::ostream& os, const length& length);

  constexpr bool operator==(const length& left, const length& right)
  {
    return left.value == right.value && left.unit == right.unit;
  }
  constexpr bool operator!=(const length& left, const length& right)
  {
    return !(left == right);
  }
}

#endif
<|endoftext|>