<commit_before>//============================================================================//
// File:          qcan_network.hpp                                            //
// Description:   QCAN classes - CAN network                                  //
//                                                                            //
// Copyright (C) MicroControl GmbH & Co. KG                                   //
// 53844 Troisdorf - Germany                                                  //
// www.microcontrol.net                                                       //
//                                                                            //
//----------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without         //
// modification, are permitted provided that the following conditions         //
// are met:                                                                   //
// 1. Redistributions of source code must retain the above copyright          //
//    notice, this list of conditions, the following disclaimer and           //
//    the referenced file 'LICENSE'.                                          //
// 2. Redistributions in binary form must reproduce the above copyright       //
//    notice, this list of conditions and the following disclaimer in the     //
//    documentation and/or other materials provided with the distribution.    //
// 3. Neither the name of MicroControl nor the names of its contributors      //
//    may be used to endorse or promote products derived from this software   //
//    without specific prior written permission.                              //
//                                                                            //
// Provided that this notice is retained in full, this software may be        //
// distributed under the terms of the GNU Lesser General Public License       //
// ("LGPL") version 3 as distributed in the 'LICENSE' file.                   //
//                                                                            //
//============================================================================//

#ifndef QCAN_NETWORK_HPP_
#define QCAN_NETWORK_HPP_

/*----------------------------------------------------------------------------*\
** Include files                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/
#include <QTcpServer>
#include <QTcpSocket>
#include <QMutex>
#include <QPointer>
#include <QTimer>

#include "qcan_frame.hpp"
#include "qcan_frame_api.hpp"
#include "qcan_frame_error.hpp"

using namespace CANpie;

/*----------------------------------------------------------------------------*\
** Referenced classes                                                         **
**                                                                            **
\*----------------------------------------------------------------------------*/
class QCanInterface;

//-----------------------------------------------------------------------------
/*!
** \class QCanNetwork
** \brief CAN network representation
**
** This class represents a CAN network with a unique bit-rate.
** It supports one physical CAN interface (QCanInterface), which can be
** assigned during run-time to the CAN network and a limited number of
** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork
** via the QCanSocket class.
**
*/
class QCanNetwork : public QObject
{
   Q_OBJECT
public:

   /*!
   ** \param[in]  pclParentV     Pointer to QObject parent class
   ** \param[in]  uwPortV        Port number
   **
   ** Create new CAN network with unique channel number.
   */
   QCanNetwork(QObject * pclParentV = Q_NULLPTR,
               uint16_t  uwPortV = QCAN_TCP_DEFAULT_PORT);

	~QCanNetwork();

	/*!
   ** \param[in]  pclCanIfV     Pointer to CAN interface class
   ** \return     \c true if CAN interface added successfully
	** \see        removeInterface()
	**
	** The function adds a physical CAN interface to the CAN network.
	** Each CAN network supports only one physical CAN interface.
	** The CAN interface is removed from the network by calling
	** the removeInterface() method. The parameter \c pclCanIfV is a pointer
	** to an instance of a QCanInterface class.
	**

	** The function returns \c true if the CAN interface is added, otherwise
	** it will return \c false.
	*/
	bool addInterface(QCanInterface * pclCanIfV);

   /*!
   ** \return     Bit-rate value for Nominal Bit Timing
   ** \see        setBitrate()
   **
   ** This function returns the current bit-rate of the CAN network.
   ** For classic CAN, the return value defines the bit-rate for the
   ** complete frame.
   ** For CAN FD the return value defines the bit-rate for
   ** the arbitration phase.
   **

   ** If no bit-rate is configured, the function will return
   ** CANpie::eCAN_BITRATE_NONE.
   */
	inline int32_t  bitrate(void)          {  return (slNomBitRateP);    };

	inline int32_t  nominalBitrate(void)   {  return (slNomBitRateP);    };

	inline int32_t  dataBitrate(void)      {  return (slDatBitRateP);    };

   /*!
   ** \return     Current dispatcher time
   ** \see        setDispatcherTime()
   **
   ** This function returns the current dispatcher time for the
   ** internal CAN frame handler in milliseconds.
   */
	uint32_t dispatcherTime(void)    {return (ulDispatchTimeP); };

   bool hasErrorFramesSupport(void);

   bool hasFastDataSupport(void);

   bool hasListenOnlySupport(void);

   bool isErrorFramesEnabled(void)  {return (btErrorFramesEnabledP); };

   bool isFastDataEnabled(void)     {return (btFastDataEnabledP);    };

   bool isListenOnlyEnabled(void)   {return (btListenOnlyEnabledP);  };

   /*!
   ** \return     \c true if CAN is enabled
   ** \see        setNetworkEnabled()
   **
   ** This function returns \c true if the network is enabled,
   ** otherwise it returns \c false.
   */
   bool isNetworkEnabled(void)      {return (btNetworkEnabledP);     };

	QString  name()   { return(clNetNameP); };

	void reset(void);

   /*!
   ** \see     addInterface()
   **
   ** Remove a physical CAN interface from the CAN network.
   */
	void removeInterface(void);

   QHostAddress serverAddress(void);

   /*!
   ** \param[in]  slNomBitRateV  Nominal Bit-rate value
   ** \param[in]  slDatBitRateV  Data Bit-rate value
   ** \see        bitrate()
   **
   ** This function sets the bit-rate for the CAN network. For classic CAN,
   ** the parameter \c slBitrateV defines the bit-rate for the complete frame,
   ** the parameter \c slBrsClockV is not evaluated in that case.
   ** For CAN FD the parameter \c slBitrateV defines the bit-rate for
   ** the arbitration phase, the parameter \c slBrsClockV defines the
   ** bit-rate for the data phase.
   **

   ** For selection of predefined bit-rates the value can be taken from
   ** the enumeration CANpie::CAN_Bitrate_e.
   */
	void setBitrate(int32_t slNomBitRateV,
	                int32_t slDatBitRateV = eCAN_BITRATE_NONE);

   /*!
   ** \param[in]  ulTimeV        Dispatcher time
   ** \see        dispatcherTime()
   **
   ** This function sets the dispatcher time for the internal CAN frame
   ** handler in milliseconds.
   */
	void setDispatcherTime(uint32_t ulTimeV);

   /*!
   ** \param[in]  btEnableV      Enable / disable error frames
   ** \see        isErrorFramesEnabled()
   **
   ** This function enables the dispatching of CAN error frames if \a btEnable
   ** is \c true, it is disabled on \c false.
   */
   void setErrorFramesEnabled(bool btEnableV = true);

   void setFastDataEnabled(bool btEnableV = true);

   void setListenOnlyEnabled(bool btEnableV = true);

   /*!
   ** \param[in]  btEnableV      Enable / disable network
   ** \see        isNetworkEnabled()
   **
   ** This function enables the dispatching of CAN frames if \a btEnable is
   ** \c true, it is disabled on \c false.
   */
   void setNetworkEnabled(bool btEnableV = true);

   bool setServerAddress(QHostAddress clHostAddressV);

signals:
   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of API frames.
   */
   void  showApiFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of CAN frames.
   */
   void  showCanFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of CAN error frames.
   */
   void  showErrFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ubLoadV        Bus load in percent
   ** \param[in]  ulMsgPerSecV   Messages per second
   **
   **
   ** This signal is emitted every second. The parameter \a ubLoadV
   ** denotes the bus load in percent (value range 0 .. 100).
   */
   void  showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV);

private slots:
   /*!
   ** This function is called upon socket connection.
   */
   void onSocketConnect(void);

   /*!
   ** This function is called upon socket disconnection.
   */
   void onSocketDisconnect(void);

   void onTimerEvent(void);

protected:

private:

   bool  handleApiFrame(int32_t & slSockSrcR, QCanFrameApi & clApiFrameR);
   bool  handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);
   bool  handleErrFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);

   //----------------------------------------------------------------
   // unique network ID
   //
   static uint8_t          ubNetIdP;

   //----------------------------------------------------------------
   // unique network name
   //
   QString                 clNetNameP;

   QPointer<QCanInterface> pclInterfaceP;
   QPointer<QTcpServer>    pclTcpSrvP;
   QVector<QTcpSocket *> * pclTcpSockListP;
   QHostAddress            clTcpHostAddrP;
   uint16_t                uwTcpPortP;
   QMutex                  clTcpSockMutexP;

   //----------------------------------------------------------------
   // Frame dispatcher time
   //
   QTimer                  clDispatchTmrP;
   uint32_t                ulDispatchTimeP;

   //----------------------------------------------------------------
   // bit-rate settings
   //
   int32_t                 slNomBitRateP;
   int32_t                 slDatBitRateP;

   //----------------------------------------------------------------
   // statistic frame counter
   //
   uint32_t                ulCntFrameApiP;
   uint32_t                ulCntFrameCanP;
   uint32_t                ulCntFrameErrP;

   //----------------------------------------------------------------
   // statistic bit counter
   //
   uint32_t                ulCntBitMaxP;
   uint32_t                ulCntBitCurP;

   //----------------------------------------------------------------
   // statistic timing
   //
   uint32_t                ulStatisticTickP;
   uint32_t                ulStatisticTimeP;
   uint32_t                ulFramePerSecMaxP;
   uint32_t                ulFrameCntSaveP;

   bool                    btErrorFramesEnabledP;
   bool                    btFastDataEnabledP;
   bool                    btListenOnlyEnabledP;
   bool                    btNetworkEnabledP;
};

#endif   // QCAN_NETWORK_HPP_
<commit_msg>The private method handleApiFrame() has the same parameter types like all other frame handlers<commit_after>//============================================================================//
// File:          qcan_network.hpp                                            //
// Description:   QCAN classes - CAN network                                  //
//                                                                            //
// Copyright (C) MicroControl GmbH & Co. KG                                   //
// 53844 Troisdorf - Germany                                                  //
// www.microcontrol.net                                                       //
//                                                                            //
//----------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without         //
// modification, are permitted provided that the following conditions         //
// are met:                                                                   //
// 1. Redistributions of source code must retain the above copyright          //
//    notice, this list of conditions, the following disclaimer and           //
//    the referenced file 'LICENSE'.                                          //
// 2. Redistributions in binary form must reproduce the above copyright       //
//    notice, this list of conditions and the following disclaimer in the     //
//    documentation and/or other materials provided with the distribution.    //
// 3. Neither the name of MicroControl nor the names of its contributors      //
//    may be used to endorse or promote products derived from this software   //
//    without specific prior written permission.                              //
//                                                                            //
// Provided that this notice is retained in full, this software may be        //
// distributed under the terms of the GNU Lesser General Public License       //
// ("LGPL") version 3 as distributed in the 'LICENSE' file.                   //
//                                                                            //
//============================================================================//

#ifndef QCAN_NETWORK_HPP_
#define QCAN_NETWORK_HPP_

/*----------------------------------------------------------------------------*\
** Include files                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/
#include <QTcpServer>
#include <QTcpSocket>
#include <QMutex>
#include <QPointer>
#include <QTimer>

#include "qcan_frame.hpp"
#include "qcan_frame_api.hpp"
#include "qcan_frame_error.hpp"

using namespace CANpie;

/*----------------------------------------------------------------------------*\
** Referenced classes                                                         **
**                                                                            **
\*----------------------------------------------------------------------------*/
class QCanInterface;

//-----------------------------------------------------------------------------
/*!
** \class QCanNetwork
** \brief CAN network representation
**
** This class represents a CAN network with a unique bit-rate.
** It supports one physical CAN interface (QCanInterface), which can be
** assigned during run-time to the CAN network and a limited number of
** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork
** via the QCanSocket class.
**
*/
class QCanNetwork : public QObject
{
   Q_OBJECT
public:

   /*!
   ** \param[in]  pclParentV     Pointer to QObject parent class
   ** \param[in]  uwPortV        Port number
   **
   ** Create new CAN network with unique channel number.
   */
   QCanNetwork(QObject * pclParentV = Q_NULLPTR,
               uint16_t  uwPortV = QCAN_TCP_DEFAULT_PORT);

	~QCanNetwork();

	/*!
   ** \param[in]  pclCanIfV     Pointer to CAN interface class
   ** \return     \c true if CAN interface added successfully
	** \see        removeInterface()
	**
	** The function adds a physical CAN interface to the CAN network.
	** Each CAN network supports only one physical CAN interface.
	** The CAN interface is removed from the network by calling
	** the removeInterface() method. The parameter \c pclCanIfV is a pointer
	** to an instance of a QCanInterface class.
	**

	** The function returns \c true if the CAN interface is added, otherwise
	** it will return \c false.
	*/
	bool addInterface(QCanInterface * pclCanIfV);

   /*!
   ** \return     Bit-rate value for Nominal Bit Timing
   ** \see        setBitrate()
   **
   ** This function returns the current bit-rate of the CAN network.
   ** For classic CAN, the return value defines the bit-rate for the
   ** complete frame.
   ** For CAN FD the return value defines the bit-rate for
   ** the arbitration phase.
   **

   ** If no bit-rate is configured, the function will return
   ** CANpie::eCAN_BITRATE_NONE.
   */
	inline int32_t  bitrate(void)          {  return (slNomBitRateP);    };

	inline int32_t  nominalBitrate(void)   {  return (slNomBitRateP);    };

	inline int32_t  dataBitrate(void)      {  return (slDatBitRateP);    };

   /*!
   ** \return     Current dispatcher time
   ** \see        setDispatcherTime()
   **
   ** This function returns the current dispatcher time for the
   ** internal CAN frame handler in milliseconds.
   */
	uint32_t dispatcherTime(void)    {return (ulDispatchTimeP); };

   bool hasErrorFramesSupport(void);

   bool hasFastDataSupport(void);

   bool hasListenOnlySupport(void);

   bool isErrorFramesEnabled(void)  {return (btErrorFramesEnabledP); };

   bool isFastDataEnabled(void)     {return (btFastDataEnabledP);    };

   bool isListenOnlyEnabled(void)   {return (btListenOnlyEnabledP);  };

   /*!
   ** \return     \c true if CAN is enabled
   ** \see        setNetworkEnabled()
   **
   ** This function returns \c true if the network is enabled,
   ** otherwise it returns \c false.
   */
   bool isNetworkEnabled(void)      {return (btNetworkEnabledP);     };

	QString  name()   { return(clNetNameP); };

	void reset(void);

   /*!
   ** \see     addInterface()
   **
   ** Remove a physical CAN interface from the CAN network.
   */
	void removeInterface(void);

   QHostAddress serverAddress(void);

   /*!
   ** \param[in]  slNomBitRateV  Nominal Bit-rate value
   ** \param[in]  slDatBitRateV  Data Bit-rate value
   ** \see        bitrate()
   **
   ** This function sets the bit-rate for the CAN network. For classic CAN,
   ** the parameter \c slBitrateV defines the bit-rate for the complete frame,
   ** the parameter \c slBrsClockV is not evaluated in that case.
   ** For CAN FD the parameter \c slBitrateV defines the bit-rate for
   ** the arbitration phase, the parameter \c slBrsClockV defines the
   ** bit-rate for the data phase.
   **

   ** For selection of predefined bit-rates the value can be taken from
   ** the enumeration CANpie::CAN_Bitrate_e.
   */
	void setBitrate(int32_t slNomBitRateV,
	                int32_t slDatBitRateV = eCAN_BITRATE_NONE);

   /*!
   ** \param[in]  ulTimeV        Dispatcher time
   ** \see        dispatcherTime()
   **
   ** This function sets the dispatcher time for the internal CAN frame
   ** handler in milliseconds.
   */
	void setDispatcherTime(uint32_t ulTimeV);

   /*!
   ** \param[in]  btEnableV      Enable / disable error frames
   ** \see        isErrorFramesEnabled()
   **
   ** This function enables the dispatching of CAN error frames if \a btEnable
   ** is \c true, it is disabled on \c false.
   */
   void setErrorFramesEnabled(bool btEnableV = true);

   void setFastDataEnabled(bool btEnableV = true);

   void setListenOnlyEnabled(bool btEnableV = true);

   /*!
   ** \param[in]  btEnableV      Enable / disable network
   ** \see        isNetworkEnabled()
   **
   ** This function enables the dispatching of CAN frames if \a btEnable is
   ** \c true, it is disabled on \c false.
   */
   void setNetworkEnabled(bool btEnableV = true);

   bool setServerAddress(QHostAddress clHostAddressV);

signals:
   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of API frames.
   */
   void  showApiFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of CAN frames.
   */
   void  showCanFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ulFrameTotalV  Total number of frames
   **
   ** This signal is emitted every second. The parameter \a ulFrameTotalV
   ** denotes the total number of CAN error frames.
   */
   void  showErrFrames(uint32_t ulFrameTotalV);

   /*!
   ** \param[in]  ubLoadV        Bus load in percent
   ** \param[in]  ulMsgPerSecV   Messages per second
   **
   **
   ** This signal is emitted every second. The parameter \a ubLoadV
   ** denotes the bus load in percent (value range 0 .. 100).
   */
   void  showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV);

private slots:
   /*!
   ** This function is called upon socket connection.
   */
   void onSocketConnect(void);

   /*!
   ** This function is called upon socket disconnection.
   */
   void onSocketDisconnect(void);

   void onTimerEvent(void);

protected:

private:

   bool  handleApiFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);
   bool  handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);
   bool  handleErrFrame(int32_t & slSockSrcR, QByteArray & clSockDataR);

   //----------------------------------------------------------------
   // unique network ID
   //
   static uint8_t          ubNetIdP;

   //----------------------------------------------------------------
   // unique network name
   //
   QString                 clNetNameP;

   QPointer<QCanInterface> pclInterfaceP;
   QPointer<QTcpServer>    pclTcpSrvP;
   QVector<QTcpSocket *> * pclTcpSockListP;
   QHostAddress            clTcpHostAddrP;
   uint16_t                uwTcpPortP;
   QMutex                  clTcpSockMutexP;

   //----------------------------------------------------------------
   // Frame dispatcher time
   //
   QTimer                  clDispatchTmrP;
   uint32_t                ulDispatchTimeP;

   //----------------------------------------------------------------
   // bit-rate settings
   //
   int32_t                 slNomBitRateP;
   int32_t                 slDatBitRateP;

   //----------------------------------------------------------------
   // statistic frame counter
   //
   uint32_t                ulCntFrameApiP;
   uint32_t                ulCntFrameCanP;
   uint32_t                ulCntFrameErrP;

   //----------------------------------------------------------------
   // statistic bit counter
   //
   uint32_t                ulCntBitMaxP;
   uint32_t                ulCntBitCurP;

   //----------------------------------------------------------------
   // statistic timing
   //
   uint32_t                ulStatisticTickP;
   uint32_t                ulStatisticTimeP;
   uint32_t                ulFramePerSecMaxP;
   uint32_t                ulFrameCntSaveP;

   bool                    btErrorFramesEnabledP;
   bool                    btFastDataEnabledP;
   bool                    btListenOnlyEnabledP;
   bool                    btNetworkEnabledP;
};

#endif   // QCAN_NETWORK_HPP_
<|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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbStreamingShrinkImageFilter.h"

namespace otb
{
namespace Wrapper
{

class Quicklook : public Application
{
public:
  /** Standard class typedefs. */
  typedef Quicklook                     Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(Quicklook, otb::Application);

  /** Typedefs */
  typedef float InputPixelType;
  typedef float OutputPixelType;
  typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType >   ExtractROIFilterType;
  typedef ExtractROIFilterType::InputImageType InputImageType;
  typedef ExtractROIFilterType::OutputImageType OutputImageType;
  typedef otb::StreamingShrinkImageFilter
        <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("Quicklook");
    SetDescription("Generates a subsampled version of an image extract");
    SetDocName("Quick Look");
    SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n "
                          "This extract is subsampled using the ratio OR the output image Size.");
    SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n"
                      "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",   "Input Image");
    SetParameterDescription( "in", "The image to read" );

    AddParameter(ParameterType_OutputImage, "out",  "Output Image");
    SetParameterDescription( "out" , "The subsampled image" );

    AddParameter(ParameterType_ListView, "cl", "Channel List");
    SetParameterDescription( "cl" , "Selected channels" );
    MandatoryOff("cl");

    AddParameter(ParameterType_Int, "rox",  "ROI Origin X");
    SetParameterDescription( "rox" , "first point of ROI in x-direction" );
    MandatoryOff("rox");

    AddParameter(ParameterType_Int, "roy",  "ROI Origin Y");
    SetParameterDescription( "roy" , "first point of ROI in y-direction" );
    MandatoryOff("roy");

    AddParameter(ParameterType_Int, "rsx",  "ROI Size X");
    SetParameterDescription( "rsx" , "size of ROI in x-direction" );
    MandatoryOff("rsx");

    AddParameter(ParameterType_Int, "rsy",  "ROI Size Y");
    SetParameterDescription( "rsy" , "size of ROI in y-direction" );
    MandatoryOff("rsy");

    AddParameter(ParameterType_Int, "sr",  "Sampling ratio");
    SetParameterDescription( "sr" , "Sampling Ratio, default is 2" );
    SetDefaultParameterInt("sr", 2);
    SetMinimumParameterIntValue("sr", 1);
    MandatoryOff("sr");

    AddParameter(ParameterType_Int, "sx",  "Size X");
    SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" );
    MandatoryOff("sx");
    DisableParameter("sx");

    AddParameter(ParameterType_Int, "sy",  "Size Y");
    SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" );
    MandatoryOff("sy");
    DisableParameter("sy");

    SetDefaultParameterInt("rox", 0);
    SetDefaultParameterInt("roy", 0);
    SetDefaultParameterInt("rsx", 0);
    SetDefaultParameterInt("rsy", 0);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "qb_RoadExtract.tif");
    SetDocExampleParameterValue("out", "quicklookImage.tif");
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    // Update the sizes only if the user does not defined a size
    if ( HasValue("in") )
      {
      InputImageType::Pointer inImage = GetParameterImage("in");

      InputImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      if (nbComponents != GetChoiceKeys("cl").size())
        {
        ClearChoices("cl");
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          std::ostringstream key, item;
          key<<"cl.channel"<<idx+1;
          item<<"Channel"<<idx+1;
          AddChoice(key.str(), item.str());
          }
        }

      if (!HasUserValue("rsx")  && !HasUserValue("rsy") )
        {
        SetParameterInt("rsx",largestRegion.GetSize()[0], false);
        SetParameterInt("rsy",largestRegion.GetSize()[1], false);
        }

      // Put the limit of the index and the size relative the image
      SetMinimumParameterIntValue("rsx", 0);
      SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0));

      SetMinimumParameterIntValue("rsy", 0);
      SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1));

      SetMinimumParameterIntValue("rox", 0);
      SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1);

      SetMinimumParameterIntValue("roy", 0);
      SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1);

      // Crop the roi region to be included in the largest possible
      // region
      if(!this->CropRegionOfInterest())
        {
        // Put the index of the ROI to origin and try to crop again
        SetParameterInt("rox",0, false);
        SetParameterInt("roy",0, false);
        this->CropRegionOfInterest();
        }
      }

  }

bool CropRegionOfInterest()
  {
    FloatVectorImageType::RegionType region;
    region.SetSize(0,  GetParameterInt("rsx"));
    region.SetSize(1,  GetParameterInt("rsy"));
    region.SetIndex(0, GetParameterInt("rox"));
    region.SetIndex(1, GetParameterInt("roy"));

    if ( HasValue("in") )
      {
        if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
          {
            SetParameterInt("rsx",region.GetSize(0), false);
            SetParameterInt("rsy",region.GetSize(1), false);
            SetParameterInt("rox",region.GetIndex(0), false);
            SetParameterInt("roy",region.GetIndex(1), false);
            return true;
          }
      }
    return false;
  }

  void DoExecute() ITK_OVERRIDE
  {
    InputImageType::Pointer inImage = GetParameterImage("in");

    m_ExtractROIFilter = ExtractROIFilterType::New();
    m_ResamplingFilter = ShrinkImageFilterType::New();

    // The image on which the quicklook will be generated
    // Will eventually be the m_ExtractROIFilter output

    if (HasUserValue("rox") || HasUserValue("roy")
        || HasUserValue("rsx") || HasUserValue("rsy")
        || (GetSelectedItems("cl").size() > 0))
      {
      m_ExtractROIFilter->SetInput(inImage);
      m_ExtractROIFilter->SetStartX(GetParameterInt("rox"));
      m_ExtractROIFilter->SetStartY(GetParameterInt("roy"));
      m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx"));
      m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy"));

      if ((GetSelectedItems("cl").size() > 0))
        {
        for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
          {
          m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
          }
        }
      else
        {
        unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          m_ExtractROIFilter->SetChannel(idx + 1);
          }
        }
      m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );
      }
    else
      {
      m_ResamplingFilter->SetInput(inImage);
      }

    unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr"));
    unsigned int SamplingRatioX = 1;
    unsigned int SamplingRatioY = 1;

    if ( !HasUserValue("sr") )
      {
      if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") )
        {
        SamplingRatioX =  GetParameterInt("rsx") / GetParameterInt("sx");
        SamplingRatioY =  GetParameterInt("rsy") / GetParameterInt("sy");
        if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;
        if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;
        }
      else
        {
        if ( IsParameterEnabled("sx") )
          {
          Ratio =  GetParameterInt("rsx") / GetParameterInt("sx");
          }
        if ( IsParameterEnabled("sy") )
          {
          Ratio =  GetParameterInt("rsy") / GetParameterInt("sy");
          }
        }
      }

    if ( Ratio < 1)
      {
      otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1.");
      return;
      }
    otbAppLogINFO( << "Ratio used: "<<Ratio << ".");

    m_ResamplingFilter->SetShrinkFactor( Ratio );
    m_ResamplingFilter->Update();

    SetParameterOutputImage("out", m_ResamplingFilter->GetOutput());
  }

  ExtractROIFilterType::Pointer m_ExtractROIFilter;
  ShrinkImageFilterType::Pointer m_ResamplingFilter;

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook)
<commit_msg>BUG: Correct Quicklook application behavior for python binding.<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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbStreamingShrinkImageFilter.h"

namespace otb
{
namespace Wrapper
{

class Quicklook : public Application
{
public:
  /** Standard class typedefs. */
  typedef Quicklook                     Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(Quicklook, otb::Application);

  /** Typedefs */
  typedef float InputPixelType;
  typedef float OutputPixelType;
  typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType >   ExtractROIFilterType;
  typedef ExtractROIFilterType::InputImageType InputImageType;
  typedef ExtractROIFilterType::OutputImageType OutputImageType;
  typedef otb::StreamingShrinkImageFilter
        <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("Quicklook");
    SetDescription("Generates a subsampled version of an image extract");
    SetDocName("Quick Look");
    SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n "
                          "This extract is subsampled using the ratio OR the output image Size.");
    SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n"
                      "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",   "Input Image");
    SetParameterDescription( "in", "The image to read" );

    AddParameter(ParameterType_OutputImage, "out",  "Output Image");
    SetParameterDescription( "out" , "The subsampled image" );

    AddParameter(ParameterType_ListView, "cl", "Channel List");
    SetParameterDescription( "cl" , "Selected channels" );
    MandatoryOff("cl");

    AddParameter(ParameterType_Int, "rox",  "ROI Origin X");
    SetParameterDescription( "rox" , "first point of ROI in x-direction" );
    MandatoryOff("rox");

    AddParameter(ParameterType_Int, "roy",  "ROI Origin Y");
    SetParameterDescription( "roy" , "first point of ROI in y-direction" );
    MandatoryOff("roy");

    AddParameter(ParameterType_Int, "rsx",  "ROI Size X");
    SetParameterDescription( "rsx" , "size of ROI in x-direction" );
    MandatoryOff("rsx");

    AddParameter(ParameterType_Int, "rsy",  "ROI Size Y");
    SetParameterDescription( "rsy" , "size of ROI in y-direction" );
    MandatoryOff("rsy");

    AddParameter(ParameterType_Int, "sr",  "Sampling ratio");
    SetParameterDescription( "sr" , "Sampling Ratio, default is 2" );
    SetDefaultParameterInt("sr", 2);
    SetMinimumParameterIntValue("sr", 1);
    MandatoryOff("sr");

    AddParameter(ParameterType_Int, "sx",  "Size X");
    SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" );
    MandatoryOff("sx");
    DisableParameter("sx");

    AddParameter(ParameterType_Int, "sy",  "Size Y");
    SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" );
    MandatoryOff("sy");
    DisableParameter("sy");

    SetDefaultParameterInt("rox", 0);
    SetDefaultParameterInt("roy", 0);
    SetDefaultParameterInt("rsx", 0);
    SetDefaultParameterInt("rsy", 0);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "qb_RoadExtract.tif");
    SetDocExampleParameterValue("out", "quicklookImage.tif");
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    // Update the sizes only if the user does not defined a size
    if ( HasValue("in") )
      {
      InputImageType::Pointer inImage = GetParameterImage("in");

      InputImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      if (nbComponents != GetChoiceKeys("cl").size())
        {
        ClearChoices("cl");
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          std::ostringstream key, item;
          key<<"cl.channel"<<idx+1;
          item<<"Channel"<<idx+1;
          AddChoice(key.str(), item.str());
          }
        }

      if (!HasUserValue("rsx")  && !HasUserValue("rsy") )
        {
        SetParameterInt("rsx",largestRegion.GetSize()[0], false);
        SetParameterInt("rsy",largestRegion.GetSize()[1], false);
        }

      // Put the limit of the index and the size relative the image
      SetMinimumParameterIntValue("rsx", 0);
      SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0));

      SetMinimumParameterIntValue("rsy", 0);
      SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1));

      SetMinimumParameterIntValue("rox", 0);
      SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1);

      SetMinimumParameterIntValue("roy", 0);
      SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1);

      // Crop the roi region to be included in the largest possible
      // region
      if(!this->CropRegionOfInterest())
        {
        // Put the index of the ROI to origin and try to crop again
        SetParameterInt("rox",0, false);
        SetParameterInt("roy",0, false);
        this->CropRegionOfInterest();
        }
      }

  }

bool CropRegionOfInterest()
  {
    FloatVectorImageType::RegionType region;
    region.SetSize(0,  GetParameterInt("rsx"));
    region.SetSize(1,  GetParameterInt("rsy"));
    region.SetIndex(0, GetParameterInt("rox"));
    region.SetIndex(1, GetParameterInt("roy"));

    if ( HasValue("in") )
      {
        if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
          {
            SetParameterInt( "rsx", region.GetSize(0), HasUserValue("rsx") );
            SetParameterInt( "rsy", region.GetSize(1), HasUserValue("rsy") );
            SetParameterInt( "rox", region.GetIndex(0), HasUserValue("rox") );
            SetParameterInt( "roy", region.GetIndex(1), HasUserValue("roy") );
            return true;
          }
      }
    return false;
  }

  void DoExecute() ITK_OVERRIDE
  {
    InputImageType::Pointer inImage = GetParameterImage("in");

    m_ExtractROIFilter = ExtractROIFilterType::New();
    m_ResamplingFilter = ShrinkImageFilterType::New();

    // The image on which the quicklook will be generated
    // Will eventually be the m_ExtractROIFilter output

    if (HasUserValue("rox") || HasUserValue("roy")
        || HasUserValue("rsx") || HasUserValue("rsy")
        || (GetSelectedItems("cl").size() > 0))
      {
      m_ExtractROIFilter->SetInput(inImage);
      m_ExtractROIFilter->SetStartX(GetParameterInt("rox"));
      m_ExtractROIFilter->SetStartY(GetParameterInt("roy"));
      m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx"));
      m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy"));

      if ((GetSelectedItems("cl").size() > 0))
        {
        for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
          {
          m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
          }
        }
      else
        {
        unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          m_ExtractROIFilter->SetChannel(idx + 1);
          }
        }
      m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );
      }
    else
      {
      m_ResamplingFilter->SetInput(inImage);
      }

    unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr"));
    unsigned int SamplingRatioX = 1;
    unsigned int SamplingRatioY = 1;

    if ( !HasUserValue("sr") )
      {
      if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") )
        {
        SamplingRatioX =  GetParameterInt("rsx") / GetParameterInt("sx");
        SamplingRatioY =  GetParameterInt("rsy") / GetParameterInt("sy");
        if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;
        if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;
        }
      else
        {
        if ( IsParameterEnabled("sx") )
          {
          Ratio =  GetParameterInt("rsx") / GetParameterInt("sx");
          }
        if ( IsParameterEnabled("sy") )
          {
          Ratio =  GetParameterInt("rsy") / GetParameterInt("sy");
          }
        }
      }

    if ( Ratio < 1)
      {
      otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1.");
      return;
      }
    otbAppLogINFO( << "Ratio used: "<<Ratio << ".");

    m_ResamplingFilter->SetShrinkFactor( Ratio );
    m_ResamplingFilter->Update();

    SetParameterOutputImage("out", m_ResamplingFilter->GetOutput());
  }

  ExtractROIFilterType::Pointer m_ExtractROIFilter;
  ShrinkImageFilterType::Pointer m_ResamplingFilter;

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testapp.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:21:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TESTAPP_HXX
#define _TESTAPP_HXX

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

#include "editwin.hxx"

#define EXECUTE_NO                  0
#define EXECUTE_POSSIBLE            1
#define EXECUTE_YES                 2
#define EXECUTEMODE_ASYNCHRON       1
#define EXECUTEMODE_DIALOGASYNCHRON 2

class MyApp;
class MainWindow : public WorkWindow
{
    MyApp *pApp;

public:
    MainWindow(MyApp *pAppl);
    virtual BOOL Close(); // derived

    void FileExit();
    void FileOpen();
    void TestGross();
    void Tree(GHEditWindow *aEditWin, Window *pBase, int Indent);
    void WinTree();
    void SysDlg();
    DECL_LINK(MenuSelectHdl,MenuBar*);

};
#define PlugInDispatcher MyDispatcher
class MyDispatcher
{
    MainWindow  *pMainWin;

public:
    MyDispatcher(MainWindow  *MainWin) : pMainWin(MainWin) {};
    ~MyDispatcher() {};
    virtual USHORT ExecuteFunction( USHORT nSID, SfxPoolItem** ppArgs = 0, USHORT nMode = 0);
    virtual void SetExecuteMode( USHORT nMode ) {}; // Ist hier sowieso egal
};

class MyApp : public Application
{
    PopupMenu  *MyMenu;
    Timer aCommandTimer;
    PlugInDispatcher *pMyDispatcher;

public:
    MyApp();
    void Main();

    virtual void                Property( ApplicationProperty& );
    virtual PlugInDispatcher*   GetDispatcher();

    MainWindow  *pMainWin;
};

// -----------------------------------------------------------------------

extern MyApp aApp;

#endif

<commit_msg>INTEGRATION: CWS warnings01 (1.2.12); FILE MERGED 2006/03/02 08:08:43 gh 1.2.12.2: removing warnings for linux and solarisSparc and some windows 2006/02/02 09:19:56 gh 1.2.12.1: removed compiler warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testapp.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:21:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TESTAPP_HXX
#define _TESTAPP_HXX

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

#include "editwin.hxx"

#define EXECUTE_NO                  0
#define EXECUTE_POSSIBLE            1
#define EXECUTE_YES                 2
#define EXECUTEMODE_ASYNCHRON       1
#define EXECUTEMODE_DIALOGASYNCHRON 2

class MyApp;
class MainWindow : public WorkWindow
{
    MyApp *pApp;

public:
    MainWindow(MyApp *pAppl);
    virtual BOOL Close(); // derived

    void FileExit();
    void FileOpen();
    void TestGross();
    void Tree(GHEditWindow *aEditWin, Window *pBase, USHORT Indent);
    void WinTree();
    void SysDlg();
    DECL_LINK(MenuSelectHdl,MenuBar*);

};
#define PlugInDispatcher MyDispatcher
class MyDispatcher
{
    MainWindow  *pMainWin;

public:
    MyDispatcher(MainWindow  *MainWin) : pMainWin(MainWin) {};
    virtual ~MyDispatcher() {};
    virtual USHORT ExecuteFunction( USHORT nSID, SfxPoolItem** ppArgs = 0, USHORT nMode = 0);
    virtual void SetExecuteMode( USHORT nMode )
    {
        (void) nMode; /* avoid warning about unused parameter */
    };  // Ist hier sowieso egal
};

class MyApp : public Application
{
    PopupMenu  *MyMenu;
    Timer aCommandTimer;
    PlugInDispatcher *pMyDispatcher;

public:
    MyApp();
    void Main();

    virtual void                Property( ApplicationProperty& );
    virtual PlugInDispatcher*   GetDispatcher();

    MainWindow  *pMainWin;
};

// -----------------------------------------------------------------------

extern MyApp aApp;

#endif

<|endoftext|>


<commit_before>#include <Kernel/Process.hh>
#include <Kernel/Thread.hh>

using namespace Kernel;

Process::Process()
{
}

Process::~Process()
{
}
<commit_msg>Init pd to 0<commit_after>#include <Kernel/Process.hh>
#include <Kernel/Thread.hh>

using namespace Kernel;

Process::Process()
   : pageDirectoryM(0)
{
}

Process::~Process()
{
}
<|endoftext|>


<commit_before>#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CWizard.h"

namespace WizardOfGalicia {
  CWizard::CWizard() : CActor() {
    view = '^';
    team = Team::HEROES;
    hp = 5;
    attack = 4;
    defence = 1;
    magicEnergy = 20;
  }

  void CWizard::update(std::shared_ptr<CMap> map) {
    magicEnergy += ( magicEnergy / abs( magicEnergy ) );
  }

  void CWizard::turnLeft() {
    CActor::turnLeft();
    updateView();
  }

  void CWizard::turnRight() {
    CActor::turnRight();
    updateView();
  }

  void CWizard::updateView() {
    switch (direction) {
    case Direction::N:
      view = '^';
      break;
    case Direction::W:
      view = '<';
      break;
    case Direction::E:
      view = '>';
      break;
    case Direction::S:
      view = 'V';
      break;
    }
  }
}
<commit_msg>Fix ugly division by zero on Wizard updates<commit_after>#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"
#include "CWizard.h"

namespace WizardOfGalicia {
  CWizard::CWizard() : CActor() {
    view = '^';
    team = Team::HEROES;
    hp = 5;
    attack = 4;
    defence = 1;
    magicEnergy = 20;
  }

  void CWizard::update(std::shared_ptr<CMap> map) {
    if ( abs( magicEnergy ) > 0.0f ) {
      magicEnergy += ( magicEnergy / abs( magicEnergy ) );
    }
  }

  void CWizard::turnLeft() {
    CActor::turnLeft();
    updateView();
  }

  void CWizard::turnRight() {
    CActor::turnRight();
    updateView();
  }

  void CWizard::updateView() {
    switch (direction) {
    case Direction::N:
      view = '^';
      break;
    case Direction::W:
      view = '<';
      break;
    case Direction::E:
      view = '>';
      break;
    case Direction::S:
      view = 'V';
      break;
    }
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"

#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

///
/// BuildSettingsPanelFactory
///

bool BuildSettingsPanelFactory::supports(Project *project)
{
    return project->hasBuildSettings();
}

PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
    return new BuildSettingsPanel(project);
}

///
/// BuildSettingsPanel
///

BuildSettingsPanel::BuildSettingsPanel(Project *project)
        : PropertiesPanel(),
          m_widget(new BuildSettingsWidget(project))
{
}

BuildSettingsPanel::~BuildSettingsPanel()
{
    delete m_widget;
}

QString BuildSettingsPanel::name() const
{
    return tr("Build Settings");
}

QWidget *BuildSettingsPanel::widget()
{
    return m_widget;
}

///
// BuildSettingsSubWidgets
///

BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
    clear();
}

void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
    QLabel *label = new QLabel(this);
    label->setText(name);
    QFont f = label->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() *1.2);
    label->setFont(f);

    layout()->addWidget(label);
    layout()->addWidget(widget);

    m_labels.append(label);
    m_widgets.append(widget);
}

void BuildSettingsSubWidgets::clear()
{
    qDeleteAll(m_widgets);
    qDeleteAll(m_labels);
}

QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
    return m_widgets;
}

BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
    : QGroupBox(parent)
{
    new QVBoxLayout(this);
}

///
/// BuildSettingsWidget
///

BuildSettingsWidget::~BuildSettingsWidget()
{
}

BuildSettingsWidget::BuildSettingsWidget(Project *project)
    : m_project(project)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(tr("Build Configuration:"), this));
    m_buildConfigurationComboBox = new QComboBox(this);
    hbox->addWidget(m_buildConfigurationComboBox);

    m_addButton = new QPushButton(this);
    m_addButton->setText("Add");
    m_addButton->setIcon(QIcon(Core::Constants::ICON_PLUS));
    m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_addButton);

    m_removeButton = new QPushButton(this);
    m_removeButton->setText("Remove");
    m_removeButton->setIcon(QIcon(Core::Constants::ICON_MINUS));
    m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_removeButton);
    hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
    vbox->addLayout(hbox);

    m_subWidgets = new BuildSettingsSubWidgets(this);
    vbox->addWidget(m_subWidgets);

    QMenu *addButtonMenu = new QMenu(this);
    addButtonMenu->addAction(tr("Create &New"),
                             this, SLOT(createConfiguration()));
    addButtonMenu->addAction(tr("&Clone Selected"),
                             this, SLOT(cloneConfiguration()));
    m_addButton->setMenu(addButtonMenu);

    connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentIndexChanged(int)));

    // TODO currentIndexChanged
    // needs to change active configuration
    // and set widgets

    connect(m_removeButton, SIGNAL(clicked()),
            this, SLOT(deleteConfiguration()));
    connect(m_project, SIGNAL(activeBuildConfigurationChanged()),
            this, SLOT(activeBuildConfigurationChanged()));
    connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
            this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));

    updateBuildSettings();
}

void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{

    for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
            m_buildConfigurationComboBox->setItemText(i, m_project->displayNameFor(buildConfiguration));
            break;
        }
    }
}

void BuildSettingsWidget::updateBuildSettings()
{

    // TODO save position, entry from combbox

    // Delete old tree items
    m_buildConfigurationComboBox->blockSignals(true); // TODO ...
    m_buildConfigurationComboBox->clear();
    m_subWidgets->clear();

    // update buttons
    m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);

    // Add pages
    BuildStepConfigWidget *generalConfigWidget = m_project->createConfigWidget();
    m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);

    m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
    m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));

    QList<BuildStepConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
    foreach (BuildStepConfigWidget *subConfigWidget, subConfigWidgets)
        m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);

    // Add tree items
    QString activeBuildConfiguration = m_project->activeBuildConfiguration();
    foreach (const QString &buildConfiguration, m_project->buildConfigurations()) {
        m_buildConfigurationComboBox->addItem(m_project->displayNameFor(buildConfiguration), buildConfiguration);
        if (buildConfiguration == activeBuildConfiguration)
            m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
    }

    // TODO ...
    m_buildConfigurationComboBox->blockSignals(false);

    // TODO Restore position, entry from combbox
    // TODO? select entry from combobox ?
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::currentIndexChanged(int index)
{
    QString buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
    m_project->setActiveBuildConfiguration(buildConfiguration);
}

void BuildSettingsWidget::activeBuildConfigurationChanged()
{
    const QString &activeBuildConfiguration = m_project->activeBuildConfiguration();
    for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == activeBuildConfiguration) {
            m_buildConfigurationComboBox->setCurrentIndex(i);
            break;
        }
    }
    foreach (QWidget *widget, m_subWidgets->widgets()) {
        if (BuildStepConfigWidget *buildStepWidget = qobject_cast<BuildStepConfigWidget*>(widget)) {
            buildStepWidget->init(activeBuildConfiguration);
        }
    }
}

void BuildSettingsWidget::createConfiguration()
{
    bool ok;
    QString newBuildConfiguration = QInputDialog::getText(this, tr("New configuration"), tr("New Configuration Name:"), QLineEdit::Normal, QString(), &ok);
    if (!ok || newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    // Check that the internal name is not taken and use a different one otherwise
    const QStringList &buildConfigurations = m_project->buildConfigurations();
    if (buildConfigurations.contains(newBuildConfiguration)) {
        int i = 2;
        while (buildConfigurations.contains(newBuildConfiguration + QString::number(i)))
            ++i;
        newBuildConfiguration += QString::number(i);
    }

    // Check that we don't have a configuration with the same displayName
    QStringList displayNames;
    foreach (const QString &bc, buildConfigurations)
        displayNames << m_project->displayNameFor(bc);

    if (displayNames.contains(newDisplayName)) {
        int i = 2;
        while (displayNames.contains(newDisplayName + QString::number(i)))
            ++i;
        newDisplayName += QString::number(i);
    }

    m_project->addBuildConfiguration(newBuildConfiguration);
    m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName);
    m_project->newBuildConfiguration(newBuildConfiguration);
    m_project->setActiveBuildConfiguration(newBuildConfiguration);

    updateBuildSettings();
}

void BuildSettingsWidget::cloneConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    cloneConfiguration(configuration);
}

void BuildSettingsWidget::deleteConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    deleteConfiguration(configuration);
}

void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
    if (sourceConfiguration.isEmpty())
        return;

    QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
    if (newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    // Check that the internal name is not taken and use a different one otherwise
    const QStringList &buildConfigurations = m_project->buildConfigurations();
    if (buildConfigurations.contains(newBuildConfiguration)) {
        int i = 2;
        while (buildConfigurations.contains(newBuildConfiguration + QString::number(i)))
            ++i;
        newBuildConfiguration += QString::number(i);
    }

    // Check that we don't have a configuration with the same displayName
    QStringList displayNames;
    foreach (const QString &bc, buildConfigurations)
        displayNames << m_project->displayNameFor(bc);

    if (displayNames.contains(newDisplayName)) {
        int i = 2;
        while (displayNames.contains(newDisplayName + QString::number(i)))
            ++i;
        newDisplayName += QString::number(i);
    }

    m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
    m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName);

    updateBuildSettings();

    m_project->setActiveBuildConfiguration(newBuildConfiguration);
}

void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
    if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
        return;

    if (m_project->activeBuildConfiguration() == deleteConfiguration) {
        foreach (const QString &otherConfiguration, m_project->buildConfigurations()) {
            if (otherConfiguration != deleteConfiguration) {
                m_project->setActiveBuildConfiguration(otherConfiguration);
                break;
            }
        }
    }

    m_project->removeBuildConfiguration(deleteConfiguration);

    updateBuildSettings();
}
<commit_msg>Fix crash on adding or deleting buildconfigurations.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/

#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"

#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

///
/// BuildSettingsPanelFactory
///

bool BuildSettingsPanelFactory::supports(Project *project)
{
    return project->hasBuildSettings();
}

PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
    return new BuildSettingsPanel(project);
}

///
/// BuildSettingsPanel
///

BuildSettingsPanel::BuildSettingsPanel(Project *project)
        : PropertiesPanel(),
          m_widget(new BuildSettingsWidget(project))
{
}

BuildSettingsPanel::~BuildSettingsPanel()
{
    delete m_widget;
}

QString BuildSettingsPanel::name() const
{
    return tr("Build Settings");
}

QWidget *BuildSettingsPanel::widget()
{
    return m_widget;
}

///
// BuildSettingsSubWidgets
///

BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
    clear();
}

void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
    QLabel *label = new QLabel(this);
    label->setText(name);
    QFont f = label->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() *1.2);
    label->setFont(f);

    layout()->addWidget(label);
    layout()->addWidget(widget);

    m_labels.append(label);
    m_widgets.append(widget);
}

void BuildSettingsSubWidgets::clear()
{
    qDeleteAll(m_widgets);
    qDeleteAll(m_labels);
    m_widgets.clear();
    m_labels.clear();
}

QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
    return m_widgets;
}

BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
    : QGroupBox(parent)
{
    new QVBoxLayout(this);
}

///
/// BuildSettingsWidget
///

BuildSettingsWidget::~BuildSettingsWidget()
{
}

BuildSettingsWidget::BuildSettingsWidget(Project *project)
    : m_project(project)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(tr("Build Configuration:"), this));
    m_buildConfigurationComboBox = new QComboBox(this);
    hbox->addWidget(m_buildConfigurationComboBox);

    m_addButton = new QPushButton(this);
    m_addButton->setText("Add");
    m_addButton->setIcon(QIcon(Core::Constants::ICON_PLUS));
    m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_addButton);

    m_removeButton = new QPushButton(this);
    m_removeButton->setText("Remove");
    m_removeButton->setIcon(QIcon(Core::Constants::ICON_MINUS));
    m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    hbox->addWidget(m_removeButton);
    hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
    vbox->addLayout(hbox);

    m_subWidgets = new BuildSettingsSubWidgets(this);
    vbox->addWidget(m_subWidgets);

    QMenu *addButtonMenu = new QMenu(this);
    addButtonMenu->addAction(tr("Create &New"),
                             this, SLOT(createConfiguration()));
    addButtonMenu->addAction(tr("&Clone Selected"),
                             this, SLOT(cloneConfiguration()));
    m_addButton->setMenu(addButtonMenu);

    connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentIndexChanged(int)));

    // TODO currentIndexChanged
    // needs to change active configuration
    // and set widgets

    connect(m_removeButton, SIGNAL(clicked()),
            this, SLOT(deleteConfiguration()));
    connect(m_project, SIGNAL(activeBuildConfigurationChanged()),
            this, SLOT(activeBuildConfigurationChanged()));
    connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
            this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));

    updateBuildSettings();
}

void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{

    for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
            m_buildConfigurationComboBox->setItemText(i, m_project->displayNameFor(buildConfiguration));
            break;
        }
    }
}

void BuildSettingsWidget::updateBuildSettings()
{

    // TODO save position, entry from combbox

    // Delete old tree items
    m_buildConfigurationComboBox->blockSignals(true); // TODO ...
    m_buildConfigurationComboBox->clear();
    m_subWidgets->clear();

    // update buttons
    m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);

    // Add pages
    BuildStepConfigWidget *generalConfigWidget = m_project->createConfigWidget();
    m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);

    m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
    m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));

    QList<BuildStepConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
    foreach (BuildStepConfigWidget *subConfigWidget, subConfigWidgets)
        m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);

    // Add tree items
    QString activeBuildConfiguration = m_project->activeBuildConfiguration();
    foreach (const QString &buildConfiguration, m_project->buildConfigurations()) {
        m_buildConfigurationComboBox->addItem(m_project->displayNameFor(buildConfiguration), buildConfiguration);
        if (buildConfiguration == activeBuildConfiguration)
            m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
    }

    // TODO ...
    m_buildConfigurationComboBox->blockSignals(false);

    // TODO Restore position, entry from combbox
    // TODO? select entry from combobox ?
    activeBuildConfigurationChanged();
}

void BuildSettingsWidget::currentIndexChanged(int index)
{
    QString buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
    m_project->setActiveBuildConfiguration(buildConfiguration);
}

void BuildSettingsWidget::activeBuildConfigurationChanged()
{
    const QString &activeBuildConfiguration = m_project->activeBuildConfiguration();
    for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
        if (m_buildConfigurationComboBox->itemData(i).toString() == activeBuildConfiguration) {
            m_buildConfigurationComboBox->setCurrentIndex(i);
            break;
        }
    }
    foreach (QWidget *widget, m_subWidgets->widgets()) {
        if (BuildStepConfigWidget *buildStepWidget = qobject_cast<BuildStepConfigWidget*>(widget)) {
            buildStepWidget->init(activeBuildConfiguration);
        }
    }
}

void BuildSettingsWidget::createConfiguration()
{
    bool ok;
    QString newBuildConfiguration = QInputDialog::getText(this, tr("New configuration"), tr("New Configuration Name:"), QLineEdit::Normal, QString(), &ok);
    if (!ok || newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    // Check that the internal name is not taken and use a different one otherwise
    const QStringList &buildConfigurations = m_project->buildConfigurations();
    if (buildConfigurations.contains(newBuildConfiguration)) {
        int i = 2;
        while (buildConfigurations.contains(newBuildConfiguration + QString::number(i)))
            ++i;
        newBuildConfiguration += QString::number(i);
    }

    // Check that we don't have a configuration with the same displayName
    QStringList displayNames;
    foreach (const QString &bc, buildConfigurations)
        displayNames << m_project->displayNameFor(bc);

    if (displayNames.contains(newDisplayName)) {
        int i = 2;
        while (displayNames.contains(newDisplayName + QString::number(i)))
            ++i;
        newDisplayName += QString::number(i);
    }

    m_project->addBuildConfiguration(newBuildConfiguration);
    m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName);
    m_project->newBuildConfiguration(newBuildConfiguration);
    m_project->setActiveBuildConfiguration(newBuildConfiguration);

    updateBuildSettings();
}

void BuildSettingsWidget::cloneConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    cloneConfiguration(configuration);
}

void BuildSettingsWidget::deleteConfiguration()
{
    const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
    deleteConfiguration(configuration);
}

void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
    if (sourceConfiguration.isEmpty())
        return;

    QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
    if (newBuildConfiguration.isEmpty())
        return;

    QString newDisplayName = newBuildConfiguration;
    // Check that the internal name is not taken and use a different one otherwise
    const QStringList &buildConfigurations = m_project->buildConfigurations();
    if (buildConfigurations.contains(newBuildConfiguration)) {
        int i = 2;
        while (buildConfigurations.contains(newBuildConfiguration + QString::number(i)))
            ++i;
        newBuildConfiguration += QString::number(i);
    }

    // Check that we don't have a configuration with the same displayName
    QStringList displayNames;
    foreach (const QString &bc, buildConfigurations)
        displayNames << m_project->displayNameFor(bc);

    if (displayNames.contains(newDisplayName)) {
        int i = 2;
        while (displayNames.contains(newDisplayName + QString::number(i)))
            ++i;
        newDisplayName += QString::number(i);
    }

    m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
    m_project->setDisplayNameFor(newBuildConfiguration, newDisplayName);

    updateBuildSettings();

    m_project->setActiveBuildConfiguration(newBuildConfiguration);
}

void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
    if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
        return;

    if (m_project->activeBuildConfiguration() == deleteConfiguration) {
        foreach (const QString &otherConfiguration, m_project->buildConfigurations()) {
            if (otherConfiguration != deleteConfiguration) {
                m_project->setActiveBuildConfiguration(otherConfiguration);
                break;
            }
        }
    }

    m_project->removeBuildConfiguration(deleteConfiguration);

    updateBuildSettings();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <vector>
//#include <map>
//#include <set>
#include <unordered_set>
//#include <unordered_map>
#include <cmath>
#include <algorithm>

// #include <gnuplot-iostream.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "vector3d.hpp"
#include "swiss_to_lat_lon.hpp"
#include "height_map.hpp"

const int horizon_angles = 360;
const int tile_size = 40;

namespace po = boost::program_options;

struct pos_hoz {
    vector3d pos;
    vector3d norm;
    short elevation_angles[horizon_angles];
    pos_hoz() : pos(0,0,0), norm(0,0,0) {
        memset(elevation_angles, 0, sizeof(short) * horizon_angles);
    }
};

bool EQ_DBL(double a, double b){
    return std::abs(a-b)<EPS_DBL;
}

int main(int ac, char** av) {

    bool test = false;
    //Variables to be assigned by program options
    double height_map_resolution;
    double north_bound;
    double south_bound;
    double east_bound;
    double west_bound;

    std::string input_file;
    std::string output_dir;
    bool verbose = false;

    // Declare the supported options.
    po::options_description op_desc("Allowed options");
    op_desc.add_options()
    ("help", "print options table")
    ("input-file,i", po::value<std::string>(&input_file), "File containing height map data in x<space>y<space>z<newline> swiss coordinates format")
    ("output-dir,o", po::value<std::string>(&output_dir), "Directory for output files (default data_out_<date_time>)")
    ("resolution,R", po::value<double>(&height_map_resolution)->default_value(25.0), "resolution of data (default: 25.0)")
    ("nmax",po::value<double>(&north_bound)->default_value(1e100), "maximum north coordinate to be treated (default 1e100)")
    ("nmin",po::value<double>(&south_bound)->default_value(-1e100), "minimum north coordinate to be treated (default -1e100)")
    ("emax",po::value<double>(&east_bound)->default_value(1e100), "maximum east coordinate to be treated (default 1e100)")
    ("emin",po::value<double>(&west_bound)->default_value(-1e100), "minimum east coordinate to be treated (default -1e100)")
    ("verbose, v", "Verbose: output lots of text")
    ;

    po::positional_options_description pd;
    pd.add("input-file", 1).add("output-file", 1);

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, op_desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout <<"ComputeHorizons [options] [input file] [output base]"<<std::endl<< op_desc << std::endl;
        return 1;
    }

    if (vm.count("verbose")){
        verbose = true;
    }
    if(!vm.count("input-file")){
        std::cout << "Input file must be specified" << std::endl;
        exit(255);
    }
    if(!vm.count("output-dir")){
        std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        std::string time_string(30, 0);
        std::strftime(&time_string[0], time_string.size(), "%Yx%mx%dT%Hx%Mx%S", std::localtime(&now));
        output_dir = std::string("hoz_out_")+time_string;
        std::cout << "Output directory will be: "+output_dir << std::endl;
    }

    //create output directory
    boost::filesystem::path dir(output_dir);
    if(!boost::filesystem::create_directory(dir)) {
        std::cout << "Failed to creat output directory" << "\n";
        exit(255);
    }
    std::ifstream ifs(input_file);
    if (!ifs.is_open())
        throw std::runtime_error("could not open file : " + std::string(input_file));

    height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);

    //grid_points is a height_map, an unordered_set of all points in bounding box with
    //the maximum and minimum x,y,h of all values stored.

    std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);
    std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);

    std::cout << "NE: " << grid_points.xmax() <<", " << grid_points.ymax() << " SW: "<< grid_points.xmin() << " , " << grid_points.ymin() <<  std::endl;
    std::cout  << "NE: " << NE.first <<", " << NE.second << " SW: "<< SW.first << ", " << SW.second <<  std::endl;
    std::cout << "Maximum height: " << grid_points.hmax() << std::endl;
    std::cout << "Number of points in dataset: " << grid_points.size() << std::endl;

    if(test){
        double y_test = height_map_resolution*floor(601430.0/height_map_resolution);
        double x_test = height_map_resolution*floor(126243.0/height_map_resolution);
        auto it_v = grid_points.find_point(vector3d(x_test,y_test,0));      //get the gridpoint from the set
        std::cout << "Test point: " << x_test <<" "<< y_test << std::endl;
        std::cout << "Resolution: " << height_map_resolution << ", tile size: "<< tile_size << std::endl;
        vector3d v = *it_v;
        double elevation_angles[360];
        int theta_start = 0;
        int theta_end = 360;

        //        time_t start_time  = time(NULL);
        clock_t t = clock();
        for(int theta = theta_start;theta<theta_end;theta++){
            elevation_angles[theta] = grid_points.compute_elevation_angle(v, theta, height_map_resolution, 1.0);
        }
        double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;
        //        double run_time = difftime(time(NULL), start_time);
        std::cout << "phi = [";
        for(int theta = theta_start;theta<theta_end;theta++){
            std::cout << elevation_angles[theta] << ";";
        }
        std::cout << "];" << std::endl;
        std::cout << "runtime test point: " << run_time << std::endl;
        std::cout << "estimated runtime all points: " << run_time*grid_points.size() << std::endl;

        return 0;
    }

    std::string file_name;
    std::ofstream ofs;

    time_t start_time  = time(NULL);
    int N=0;
    int NT=0;

    int first_tile_y = (int) (grid_points.ymin()+10.0*height_map_resolution);
    int first_tile_x = (int) (grid_points.xmin()+10.0*height_map_resolution);
    int N_tiles_x = (int) ceil((grid_points.xmax()-grid_points.xmin()-20.0*height_map_resolution)/tile_size);
    int N_tiles_y = (int) ceil((grid_points.ymax()-grid_points.ymin()-20.0*height_map_resolution)/tile_size);

    pos_hoz tile_points[tile_size*tile_size];

    for(int x_tile = 0;x_tile<N_tiles_x; x_tile++){
        for(int y_tile = 0; y_tile<N_tiles_y;y_tile++){
            double coord_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
            double coord_x_end = coord_x+height_map_resolution*tile_size;
            int tile_point = 0;
            while(coord_x < coord_x_end){
                double coord_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
                double coord_y_end = coord_y+height_map_resolution*tile_size;
                while(coord_y < coord_y_end){

                    //get point and points to the north, west, south and east
                    vector3d v(coord_x, coord_y, 0.0);
                    vector3d vN(v.x+height_map_resolution,v.y,0);
                    vector3d vW(v.x,v.y+height_map_resolution,0);
                    vector3d vS(v.x-height_map_resolution,v.y,0);
                    vector3d vE(v.x,v.y-height_map_resolution,0);

                    auto itv=grid_points.find_point(v);
                    auto itE=grid_points.find_point(vE);
                    auto itN=grid_points.find_point(vN);
                    auto itW=grid_points.find_point(vW);
                    auto itS=grid_points.find_point(vS);

                    if (grid_points.is_end(itv) ||grid_points.is_end(itE) || grid_points.is_end(itN) || grid_points.is_end(itW) || grid_points.is_end(itS)){
                        coord_y = coord_y + height_map_resolution;
                        tile_points[tile_point].pos = vector3d(0,0,0);
                        tile_point++;
                        continue;
                        //if one of the neighboring points are not found we continue with the next point
                    }
                    v = *itv;
                    vE = *itE;
                    vN = *itN;
                    vW = *itW;
                    vS = *itS;
                    tile_points[tile_point].pos = v;

                    vector3d Normal = ((((vE-v)^(vN-v))+((vW-v)^(vS-v)))/2).norm();       //normal is the crossproduct of two prependicular differences. Avgd.

                    tile_points[tile_point].norm = Normal;

                    for(int theta=0;theta<horizon_angles;theta++){
                        double phi = grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles);
                        tile_points[tile_point].elevation_angles[theta] = (short)(phi / M_PI_2) * std::numeric_limits<short>::max();
                    }
                    N++;
                    coord_y = coord_y + height_map_resolution;
                    tile_point++;
                    if (N%10==0) {
                        double run_time = difftime(time(NULL), start_time);
                        int rdays = (int)floor(run_time/86400.0);
                        int rhours = (int)floor((run_time-rdays*86400)/3600.0);
                        int rminutes = (int)floor((run_time-rdays*86400.0-rhours*3600.0)/60.0);
                        int rseconds = (int)floor(run_time-rdays*86400.0-rhours*3600.0-rminutes*60.0);
                        double remaining_time = ((grid_points.size() - N)*1.0)*run_time/(N*1.0);
                        int days = (int)floor(remaining_time/86400.0);
                        int hours = (int)floor((remaining_time-days*86400)/3600.0);
                        int minutes = (int)floor((remaining_time-days*86400-hours*3600.0)/60.0);
                        int seconds = (int)floor(remaining_time-days*86400-hours*3600.0-minutes*60.0);
                        double progress = round(1000.0*100.0*(N*1.0)/(grid_points.size()*1.0))/1000.0;
                        if(N > 0){
                            std::cout <<"   Progress: "<< progress <<" %  ("<<N<<", "<<NT<<")  time: "<<rdays<<"d"<<rhours<<":"<<rminutes<<":"<<rseconds<<" time left: "<<days<<"d"<<hours<<":"<<minutes<<":"<<seconds<<"      \r";
                            std::cout.flush();
                        }
                    }

                }
                coord_x = coord_x + height_map_resolution;
            }
            std::string tile_name;
            int tile_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
            int tile_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
            tile_name = output_dir + std::string("/tile_") + std::to_string(tile_x) + std::string("_") + std::to_string(tile_y) + std::string(".hoz");
//            std::cout << std::endl << "tile_name " << tile_name << std::endl;
            ofs.open(tile_name, std::iostream::out | std::iostream::binary);
//            std::cout << "first point" << tile_points[0].pos << "norm: " << tile_points[0].norm<< std::endl;
            //open output file
            if (!ofs.is_open()){
                std::cout << "Can't open output file " << tile_name << std::endl;
            }
            ofs.write((char*)&tile_points[0], sizeof(pos_hoz)*tile_size*tile_size);
            ofs.flush();
            ofs.close();
            NT++;

        }
    }
    return 0;
}

<commit_msg>progress update frequency changed<commit_after>#include <iostream>
#include <stdio.h>
#include <fstream>
#include <vector>
//#include <map>
//#include <set>
#include <unordered_set>
//#include <unordered_map>
#include <cmath>
#include <algorithm>

// #include <gnuplot-iostream.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "vector3d.hpp"
#include "swiss_to_lat_lon.hpp"
#include "height_map.hpp"

const int horizon_angles = 360;
const int tile_size = 40;

namespace po = boost::program_options;

struct pos_hoz {
    vector3d pos;
    vector3d norm;
    short elevation_angles[horizon_angles];
    pos_hoz() : pos(0,0,0), norm(0,0,0) {
        memset(elevation_angles, 0, sizeof(short) * horizon_angles);
    }
};

bool EQ_DBL(double a, double b){
    return std::abs(a-b)<EPS_DBL;
}

int main(int ac, char** av) {

    bool test = false;
    //Variables to be assigned by program options
    double height_map_resolution;
    double north_bound;
    double south_bound;
    double east_bound;
    double west_bound;

    std::string input_file;
    std::string output_dir;
    bool verbose = false;

    // Declare the supported options.
    po::options_description op_desc("Allowed options");
    op_desc.add_options()
    ("help", "print options table")
    ("input-file,i", po::value<std::string>(&input_file), "File containing height map data in x<space>y<space>z<newline> swiss coordinates format")
    ("output-dir,o", po::value<std::string>(&output_dir), "Directory for output files (default data_out_<date_time>)")
    ("resolution,R", po::value<double>(&height_map_resolution)->default_value(25.0), "resolution of data (default: 25.0)")
    ("nmax",po::value<double>(&north_bound)->default_value(1e100), "maximum north coordinate to be treated (default 1e100)")
    ("nmin",po::value<double>(&south_bound)->default_value(-1e100), "minimum north coordinate to be treated (default -1e100)")
    ("emax",po::value<double>(&east_bound)->default_value(1e100), "maximum east coordinate to be treated (default 1e100)")
    ("emin",po::value<double>(&west_bound)->default_value(-1e100), "minimum east coordinate to be treated (default -1e100)")
    ("verbose, v", "Verbose: output lots of text")
    ;

    po::positional_options_description pd;
    pd.add("input-file", 1).add("output-file", 1);

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, op_desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout <<"ComputeHorizons [options] [input file] [output base]"<<std::endl<< op_desc << std::endl;
        return 1;
    }

    if (vm.count("verbose")){
        verbose = true;
    }
    if(!vm.count("input-file")){
        std::cout << "Input file must be specified" << std::endl;
        exit(255);
    }
    if(!vm.count("output-dir")){
        std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        std::string time_string(30, 0);
        std::strftime(&time_string[0], time_string.size(), "%Yx%mx%dT%Hx%Mx%S", std::localtime(&now));
        output_dir = std::string("hoz_out_")+time_string;
        std::cout << "Output directory will be: "+output_dir << std::endl;
    }

    //create output directory
    boost::filesystem::path dir(output_dir);
    if(!boost::filesystem::create_directory(dir)) {
        std::cout << "Failed to creat output directory" << "\n";
        exit(255);
    }
    std::ifstream ifs(input_file);
    if (!ifs.is_open())
        throw std::runtime_error("could not open file : " + std::string(input_file));

    height_map grid_points(ifs, south_bound, north_bound, east_bound, west_bound);

    //grid_points is a height_map, an unordered_set of all points in bounding box with
    //the maximum and minimum x,y,h of all values stored.

    std::pair<double,double> NE = swiss_to_lat_lon(grid_points.xmax()+height_map_resolution/2.0, grid_points.ymax()+height_map_resolution/2.0);
    std::pair<double,double> SW = swiss_to_lat_lon(grid_points.xmin()-height_map_resolution/2.0, grid_points.ymin()-height_map_resolution/2.0);

    std::cout << "NE: " << grid_points.xmax() <<", " << grid_points.ymax() << " SW: "<< grid_points.xmin() << " , " << grid_points.ymin() <<  std::endl;
    std::cout  << "NE: " << NE.first <<", " << NE.second << " SW: "<< SW.first << ", " << SW.second <<  std::endl;
    std::cout << "Maximum height: " << grid_points.hmax() << std::endl;
    std::cout << "Number of points in dataset: " << grid_points.size() << std::endl;

    if(test){
        double y_test = height_map_resolution*floor(601430.0/height_map_resolution);
        double x_test = height_map_resolution*floor(126243.0/height_map_resolution);
        auto it_v = grid_points.find_point(vector3d(x_test,y_test,0));      //get the gridpoint from the set
        std::cout << "Test point: " << x_test <<" "<< y_test << std::endl;
        std::cout << "Resolution: " << height_map_resolution << ", tile size: "<< tile_size << std::endl;
        vector3d v = *it_v;
        double elevation_angles[360];
        int theta_start = 0;
        int theta_end = 360;

        //        time_t start_time  = time(NULL);
        clock_t t = clock();
        for(int theta = theta_start;theta<theta_end;theta++){
            elevation_angles[theta] = grid_points.compute_elevation_angle(v, theta, height_map_resolution, 1.0);
        }
        double run_time = ((double)(clock()-t))/CLOCKS_PER_SEC;
        //        double run_time = difftime(time(NULL), start_time);
        std::cout << "phi = [";
        for(int theta = theta_start;theta<theta_end;theta++){
            std::cout << elevation_angles[theta] << ";";
        }
        std::cout << "];" << std::endl;
        std::cout << "runtime test point: " << run_time << std::endl;
        std::cout << "estimated runtime all points: " << run_time*grid_points.size() << std::endl;

        return 0;
    }

    std::string file_name;
    std::ofstream ofs;

    time_t start_time  = time(NULL);
    int N=0;
    int NT=0;

    int first_tile_y = (int) (grid_points.ymin()+10.0*height_map_resolution);
    int first_tile_x = (int) (grid_points.xmin()+10.0*height_map_resolution);
    int N_tiles_x = (int) ceil((grid_points.xmax()-grid_points.xmin()-20.0*height_map_resolution)/tile_size);
    int N_tiles_y = (int) ceil((grid_points.ymax()-grid_points.ymin()-20.0*height_map_resolution)/tile_size);

    pos_hoz tile_points[tile_size*tile_size];

    for(int x_tile = 0;x_tile<N_tiles_x; x_tile++){
        for(int y_tile = 0; y_tile<N_tiles_y;y_tile++){
            double coord_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
            double coord_x_end = coord_x+height_map_resolution*tile_size;
            int tile_point = 0;
            while(coord_x < coord_x_end){
                double coord_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
                double coord_y_end = coord_y+height_map_resolution*tile_size;
                while(coord_y < coord_y_end){

                    //get point and points to the north, west, south and east
                    vector3d v(coord_x, coord_y, 0.0);
                    vector3d vN(v.x+height_map_resolution,v.y,0);
                    vector3d vW(v.x,v.y+height_map_resolution,0);
                    vector3d vS(v.x-height_map_resolution,v.y,0);
                    vector3d vE(v.x,v.y-height_map_resolution,0);

                    auto itv=grid_points.find_point(v);
                    auto itE=grid_points.find_point(vE);
                    auto itN=grid_points.find_point(vN);
                    auto itW=grid_points.find_point(vW);
                    auto itS=grid_points.find_point(vS);

                    if (grid_points.is_end(itv) ||grid_points.is_end(itE) || grid_points.is_end(itN) || grid_points.is_end(itW) || grid_points.is_end(itS)){
                        coord_y = coord_y + height_map_resolution;
                        tile_points[tile_point].pos = vector3d(0,0,0);
                        tile_point++;
                        continue;
                        //if one of the neighboring points are not found we continue with the next point
                    }
                    v = *itv;
                    vE = *itE;
                    vN = *itN;
                    vW = *itW;
                    vS = *itS;
                    tile_points[tile_point].pos = v;

                    vector3d Normal = ((((vE-v)^(vN-v))+((vW-v)^(vS-v)))/2).norm();       //normal is the crossproduct of two prependicular differences. Avgd.

                    tile_points[tile_point].norm = Normal;

                    for(int theta=0;theta<horizon_angles;theta++){
                        double phi = grid_points.compute_elevation_angle(v,theta, height_map_resolution, 360.0/horizon_angles);
                        tile_points[tile_point].elevation_angles[theta] = (short)(phi / M_PI_2) * std::numeric_limits<short>::max();
                    }
                    N++;
                    coord_y = coord_y + height_map_resolution;
                    tile_point++;
                    if (N%40==0) {
                        double run_time = difftime(time(NULL), start_time);
                        int rdays = (int)floor(run_time/86400.0);
                        int rhours = (int)floor((run_time-rdays*86400)/3600.0);
                        int rminutes = (int)floor((run_time-rdays*86400.0-rhours*3600.0)/60.0);
                        int rseconds = (int)floor(run_time-rdays*86400.0-rhours*3600.0-rminutes*60.0);
                        double remaining_time = ((grid_points.size() - N)*1.0)*run_time/(N*1.0);
                        int days = (int)floor(remaining_time/86400.0);
                        int hours = (int)floor((remaining_time-days*86400)/3600.0);
                        int minutes = (int)floor((remaining_time-days*86400-hours*3600.0)/60.0);
                        int seconds = (int)floor(remaining_time-days*86400-hours*3600.0-minutes*60.0);
                        double progress = round(1000.0*100.0*(N*1.0)/(grid_points.size()*1.0))/1000.0;
                        if(N > 0){
                            std::cout <<"   Progress: "<< progress <<" %  ("<<N<<", "<<NT<<")  time: "<<rdays<<"d"<<rhours<<":"<<rminutes<<":"<<rseconds<<" time left: "<<days<<"d"<<hours<<":"<<minutes<<":"<<seconds<<"      \r";
                            std::cout.flush();
                        }
                    }

                }
                coord_x = coord_x + height_map_resolution;
            }
            std::string tile_name;
            int tile_x = (first_tile_x + height_map_resolution*tile_size*x_tile);
            int tile_y = (first_tile_y + height_map_resolution*tile_size*y_tile);
            tile_name = output_dir + std::string("/tile_") + std::to_string(tile_x) + std::string("_") + std::to_string(tile_y) + std::string(".hoz");
//            std::cout << std::endl << "tile_name " << tile_name << std::endl;
            ofs.open(tile_name, std::iostream::out | std::iostream::binary);
//            std::cout << "first point" << tile_points[0].pos << "norm: " << tile_points[0].norm<< std::endl;
            //open output file
            if (!ofs.is_open()){
                std::cout << "Can't open output file " << tile_name << std::endl;
            }
            ofs.write((char*)&tile_points[0], sizeof(pos_hoz)*tile_size*tile_size);
            ofs.flush();
            ofs.close();
            NT++;

        }
    }
    return 0;
}

<|endoftext|>