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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSet2DEquation.h"
#include "itkLevelSetEquation.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRASlabIdentifier.h"
#include "itkMRFImageFilter.h"
#include "itkMRIBiasFieldCorrectionFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSimpleFuzzyConnectednessImageFilterBase.h"
#include "itkSphereSource.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSet2DEquation.h"
#include "itkLevelSetEquation.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRASlabIdentifier.h"
#include "itkMRFImageFilter.h"
#include "itkMRIBiasFieldCorrectionFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSimpleFuzzyConnectednessImageFilterBase.h"
#include "itkSphereSource.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationImageFilterBase.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowFunction.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkDeformableMesh3DFilter.h"
#include "itkDeformableMeshFilter.h"
#include "itkDemonsRegistrationFilter.h"
#include "itkDemonsRegistrationFunction.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKmeansUnsupervisedClassifier.h"
#include "itkLevelSet.h"
#include "itkLevelSet2DFunction.h"
#include "itkLevelSetFunction.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRASlabIdentifier.h"
#include "itkMRFImageFilter.h"
#include "itkMRIBiasFieldCorrectionFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinMaxCurvatureFlowFunction.h"
#include "itkMinMaxCurvatureFlowImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionPDEDeformableRegistration.h"
#include "itkMultiResolutionPyramidImageFilter.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPDEDeformableRegistrationFilter.h"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRecursiveMultiResolutionPyramidImageFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSimpleFuzzyConnectednessImageFilterBase.h"
#include "itkSphereMeshSource.h"
#include "itkSphereSource.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoiDiagram2D.h"
#include "itkVoronoiDiagram2DGenerator.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationImageFilterBase.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedBoundary.h"
#include "itkWatershedBoundaryResolver.h"
#include "itkWatershedEquivalenceRelabeler.h"
#include "itkWatershedEquivalencyTable.h"
#include "itkWatershedImageFilter.h"
#include "itkWatershedOneWayEquivalencyTable.h"
#include "itkWatershedRelabeler.h"
#include "itkWatershedSegmentTable.h"
#include "itkWatershedSegmentTree.h"
#include "itkWatershedSegmentTreeGenerator.h"
#include "itkWatershedSegmenter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>ENH: hand built.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowFunction.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkDeformableMesh3DFilter.h"
#include "itkDeformableMeshFilter.h"
#include "itkDemonsRegistrationFilter.h"
#include "itkDemonsRegistrationFunction.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKmeansUnsupervisedClassifier.h"
#include "itkLevelSet.h"
#include "itkLevelSet2DFunction.h"
#include "itkLevelSetFunction.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRASlabIdentifier.h"
#include "itkMRFImageFilter.h"
#include "itkMRIBiasFieldCorrectionFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinMaxCurvatureFlowFunction.h"
#include "itkMinMaxCurvatureFlowImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionPDEDeformableRegistration.h"
#include "itkMultiResolutionPyramidImageFilter.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPDEDeformableRegistrationFilter.h"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRecursiveMultiResolutionPyramidImageFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSimpleFuzzyConnectednessImageFilterBase.h"
#include "itkSphereMeshSource.h"
#include "itkSphereSource.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoiDiagram2D.h"
#include "itkVoronoiDiagram2DGenerator.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationImageFilterBase.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedBoundary.h"
#include "itkWatershedBoundaryResolver.h"
#include "itkWatershedEquivalenceRelabeler.h"
#include "itkWatershedEquivalencyTable.h"
#include "itkWatershedImageFilter.h"
#include "itkWatershedOneWayEquivalencyTable.h"
#include "itkWatershedRelabeler.h"
#include "itkWatershedSegmentTable.h"
#include "itkWatershedSegmentTree.h"
#include "itkWatershedSegmentTreeGenerator.h"
#include "itkWatershedSegmenter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


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

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

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

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

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

#include "mitkSurfaceToImageFilter.h"

#include <fstream>

#include "itkCommand.h"
class ReferenceCountWatcher : public itk::Object
{
public:
  typedef itk::SimpleMemberCommand<ReferenceCountWatcher> CommandType;

  mitkClassMacro(ReferenceCountWatcher, itk::Object);

protected:
  itk::Object* m_Object;
  std::string m_Comment;
  bool m_Deleted;
  CommandType::Pointer m_DeleteCommand;

public:
  ReferenceCountWatcher(itk::Object* o, const char *comment="") : m_Object(o), m_Comment(comment), m_Deleted(false)
  {
    m_DeleteCommand = CommandType::New();
    m_DeleteCommand->SetCallbackFunction(this, &ReferenceCountWatcher::DeleteObserver);
    if(m_Object!=NULL)
      m_Object->AddObserver(itk::DeleteEvent(), m_DeleteCommand);
  }
  int GetReferenceCount() const
  {
    if(m_Object == NULL) return -1;
    if(m_Deleted) return 0;
    return m_Object->GetReferenceCount();
  }
  itkGetStringMacro(Comment);
protected:
  void DeleteObserver()
  {
    m_Deleted = true;
  }
};

class TwoOutputsFilter : public mitk::SurfaceToImageFilter
{
public:
  mitkClassMacro(TwoOutputsFilter, SurfaceToImageFilter);
  itkNewMacro(Self);
protected:
  TwoOutputsFilter()
  {
    mitk::Image::Pointer output
      = static_cast<mitk::Image*>(this->MakeOutput(0).GetPointer());
    Superclass::SetNumberOfRequiredOutputs(2);
    Superclass::SetNthOutput(1, output.GetPointer());
  }

  virtual ~TwoOutputsFilter()
  {
  }
};

template <class FilterType>
runPipelineSmartPointerCorrectnessTestForFilterType()
{
  typename FilterType::Pointer filter;
  std::cout << "Testing " << typeid(FilterType).name() << "::New(): ";
  filter = FilterType::New();
  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
     return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //std::cout << "Testing mitk::SurfaceToImageFilter::*TESTED_METHOD_DESCRIPTION: ";
  //// METHOD_TEST_CODE
  //if (filter.IsNull()) {
  //  std::cout<<"[FAILED]"<<std::endl;
  //  // return EXIT_FAILURE;
  //}
  //else {
  //std::cout<<"[PASSED]"<<std::endl;
  //}

//#ifdef MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED
  //MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED test
  std::cout << "Initializing ReferenceCountWatcher: ";
  ReferenceCountWatcher::Pointer filterWatcher, filterOutputWatcher;
  filterWatcher = new ReferenceCountWatcher(filter, "filter1");
  filterOutputWatcher = new ReferenceCountWatcher(filter->GetOutput(), "filter1Output");
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part1: "<<std::endl;
  try
  {
    mitk::Image::Pointer output = filter->GetOutput();
    std::cout << "Testing to set filter to NULL, keeping reference to output:";
    filter = NULL;
    std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing reference count of output: ";
    if(output->GetReferenceCount()!=2)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing external reference count of output: ";
    if(output->GetExternalReferenceCount()!=1)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing to set output to NULL:";
    //output->GetSource()->DebugOn();
    //output->DebugOn();
    output = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part2: "<<std::endl;
  filter = FilterType::New();
  filterWatcher = new ReferenceCountWatcher(filter, "filter2");
  filterOutputWatcher = new ReferenceCountWatcher(filter->GetOutput(), "filter2Output");
  try
  {
    std::cout << "Testing to set filter to NULL, keeping NO reference to output:";
    filter = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part3: "<<std::endl;
  try
  {
    mitk::Image::Pointer output;
    {
      typename FilterType::Pointer localFilter = FilterType::New();
      filterWatcher = new ReferenceCountWatcher(localFilter, "filter3");
      filterOutputWatcher = new ReferenceCountWatcher(localFilter->GetOutput(), "filter3Output");
      output = localFilter->GetOutput();
      std::cout << "Testing running out of scope of filter, keeping reference to output:";
    }
    std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing reference count of output: ";
    if(output->GetReferenceCount()!=2)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing external reference count of output: ";
    if(output->GetExternalReferenceCount()!=1)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing to set output to NULL:";
    output = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part4: "<<std::endl;
  try
  {
    {
      typename FilterType::Pointer localFilter = FilterType::New();
      filterWatcher = new ReferenceCountWatcher(localFilter, "filter4");
      filterOutputWatcher = new ReferenceCountWatcher(localFilter->GetOutput(), "filter4Output");
      std::cout << "Testing running out of scope of filter, keeping NO reference to output:";
    }
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
//#endif
}

int mitkPipelineSmartPointerCorrectnessTest(int argc, char* argv[])
{
  int result;
  result = runPipelineSmartPointerCorrectnessTestForFilterType<mitk::SurfaceToImageFilter>();
  if( result != EXIT_SUCCESS )
    return result;
  std::cout << std::endl;

  result = runPipelineSmartPointerCorrectnessTestForFilterType<TwoOutputsFilter>();
  if( result != EXIT_SUCCESS )
    return result;

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>FIX: missing return type<commit_after>/*=========================================================================

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

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

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

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

#include "mitkSurfaceToImageFilter.h"

#include <fstream>

#include "itkCommand.h"
class ReferenceCountWatcher : public itk::Object
{
public:
  typedef itk::SimpleMemberCommand<ReferenceCountWatcher> CommandType;

  mitkClassMacro(ReferenceCountWatcher, itk::Object);

protected:
  itk::Object* m_Object;
  std::string m_Comment;
  bool m_Deleted;
  CommandType::Pointer m_DeleteCommand;

public:
  ReferenceCountWatcher(itk::Object* o, const char *comment="") : m_Object(o), m_Comment(comment), m_Deleted(false)
  {
    m_DeleteCommand = CommandType::New();
    m_DeleteCommand->SetCallbackFunction(this, &ReferenceCountWatcher::DeleteObserver);
    if(m_Object!=NULL)
      m_Object->AddObserver(itk::DeleteEvent(), m_DeleteCommand);
  }
  int GetReferenceCount() const
  {
    if(m_Object == NULL) return -1;
    if(m_Deleted) return 0;
    return m_Object->GetReferenceCount();
  }
  itkGetStringMacro(Comment);
protected:
  void DeleteObserver()
  {
    m_Deleted = true;
  }
};

class TwoOutputsFilter : public mitk::SurfaceToImageFilter
{
public:
  mitkClassMacro(TwoOutputsFilter, SurfaceToImageFilter);
  itkNewMacro(Self);
protected:
  TwoOutputsFilter()
  {
    mitk::Image::Pointer output
      = static_cast<mitk::Image*>(this->MakeOutput(0).GetPointer());
    Superclass::SetNumberOfRequiredOutputs(2);
    Superclass::SetNthOutput(1, output.GetPointer());
  }

  virtual ~TwoOutputsFilter()
  {
  }
};

template <class FilterType>
int runPipelineSmartPointerCorrectnessTestForFilterType()
{
  typename FilterType::Pointer filter;
  std::cout << "Testing " << typeid(FilterType).name() << "::New(): ";
  filter = FilterType::New();
  if (filter.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
     return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  //std::cout << "Testing mitk::SurfaceToImageFilter::*TESTED_METHOD_DESCRIPTION: ";
  //// METHOD_TEST_CODE
  //if (filter.IsNull()) {
  //  std::cout<<"[FAILED]"<<std::endl;
  //  // return EXIT_FAILURE;
  //}
  //else {
  //std::cout<<"[PASSED]"<<std::endl;
  //}

//#ifdef MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED
  //MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED test
  std::cout << "Initializing ReferenceCountWatcher: ";
  ReferenceCountWatcher::Pointer filterWatcher, filterOutputWatcher;
  filterWatcher = new ReferenceCountWatcher(filter, "filter1");
  filterOutputWatcher = new ReferenceCountWatcher(filter->GetOutput(), "filter1Output");
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part1: "<<std::endl;
  try
  {
    mitk::Image::Pointer output = filter->GetOutput();
    std::cout << "Testing to set filter to NULL, keeping reference to output:";
    filter = NULL;
    std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing reference count of output: ";
    if(output->GetReferenceCount()!=2)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing external reference count of output: ";
    if(output->GetExternalReferenceCount()!=1)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing to set output to NULL:";
    //output->GetSource()->DebugOn();
    //output->DebugOn();
    output = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part2: "<<std::endl;
  filter = FilterType::New();
  filterWatcher = new ReferenceCountWatcher(filter, "filter2");
  filterOutputWatcher = new ReferenceCountWatcher(filter->GetOutput(), "filter2Output");
  try
  {
    std::cout << "Testing to set filter to NULL, keeping NO reference to output:";
    filter = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part3: "<<std::endl;
  try
  {
    mitk::Image::Pointer output;
    {
      typename FilterType::Pointer localFilter = FilterType::New();
      filterWatcher = new ReferenceCountWatcher(localFilter, "filter3");
      filterOutputWatcher = new ReferenceCountWatcher(localFilter->GetOutput(), "filter3Output");
      output = localFilter->GetOutput();
      std::cout << "Testing running out of scope of filter, keeping reference to output:";
    }
    std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing reference count of output: ";
    if(output->GetReferenceCount()!=2)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
    std::cout << "Testing external reference count of output: ";
    if(output->GetExternalReferenceCount()!=1)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing to set output to NULL:";
    output = NULL;
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Testing MITK_WEAKPOINTER_PROBLEM_WORKAROUND_ENABLED part4: "<<std::endl;
  try
  {
    {
      typename FilterType::Pointer localFilter = FilterType::New();
      filterWatcher = new ReferenceCountWatcher(localFilter, "filter4");
      filterOutputWatcher = new ReferenceCountWatcher(localFilter->GetOutput(), "filter4Output");
      std::cout << "Testing running out of scope of filter, keeping NO reference to output:";
    }
    std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter:";
    if(filterWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;

    std::cout << "Testing reference count of filter output:";
    if(filterOutputWatcher->GetReferenceCount()!=0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
    else
      std::cout<<"[PASSED]"<<std::endl;
  }
  catch(...)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
//#endif
}

int mitkPipelineSmartPointerCorrectnessTest(int argc, char* argv[])
{
  int result;
  result = runPipelineSmartPointerCorrectnessTestForFilterType<mitk::SurfaceToImageFilter>();
  if( result != EXIT_SUCCESS )
    return result;
  std::cout << std::endl;

  result = runPipelineSmartPointerCorrectnessTestForFilterType<TwoOutputsFilter>();
  if( result != EXIT_SUCCESS )
    return result;

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


<commit_before>/****************************************************************************
*
*   Copyright (c) 2015 PX4 Development Team. All rights reserved.
*      Author: Pavel Kirienko <pavel.kirienko@gmail.com>
*              David Sidrane <david_s5@usa.net>
*
****************************************************************************/

#ifndef UAVCAN_POSIX_DYNAMIC_NODE_ID_SERVER_FILE_EVENT_TRACER_HPP_INCLUDED
#define UAVCAN_POSIX_DYNAMIC_NODE_ID_SERVER_FILE_EVENT_TRACER_HPP_INCLUDED

#include <uavcan/protocol/dynamic_node_id_server/event.hpp>
#include <cstdio>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>

namespace uavcan_posix
{
namespace dynamic_node_id_server
{
/**
 * This interface implements a POSIX compliant file based IEventTracer interface
 */
class FileEventTracer : public uavcan::dynamic_node_id_server::IEventTracer
{
    /**
     * Maximum length of full path to log file
     */
    enum { MaxPathLength = 128 };

    enum { FilePermissions = 438 };     ///< 0o666

    /**
     * This type is used for the path
     */
    typedef uavcan::MakeString<MaxPathLength>::Type PathString;

    PathString path_;

protected:
    virtual void onEvent(uavcan::dynamic_node_id_server::TraceCode code, uavcan::int64_t argument)
    {
        using namespace std;

        timespec ts = timespec();               // If clock_gettime() fails, zero time will be used
        (void)clock_gettime(CLOCK_REALTIME, &ts);

        int fd = open(path_.c_str(), O_WRONLY | O_CREAT | O_APPEND, FilePermissions);
        if (fd >= 0)
        {
            const int FormatBufferLength = 63;
            char buffer[FormatBufferLength + 1];
            int n = snprintf(buffer, FormatBufferLength, "%ld.%06ld\t%d\t%lld\n",
                             static_cast<long>(ts.tv_sec), static_cast<long>(ts.tv_nsec / 1000L),
                             static_cast<int>(code), static_cast<long long>(argument));
            (void)write(fd, buffer, n); // TODO FIXME Write loop
            (void)close(fd);
        }
    }

public:
    /**
     * Initializes the file based event tracer.
     */
    int init(const PathString & path)
    {
        using namespace std;

        int rv = -uavcan::ErrInvalidParam;

        if (path.size() > 0)
        {
            rv = 0;
            path_ = path.c_str();
            int fd = open(path_.c_str(), O_RDWR | O_CREAT | O_TRUNC, FilePermissions);
            if (fd >= 0)
            {
                (void)close(fd);
            }
        }
        return rv;
    }
};

}
}

#endif // Include guard
<commit_msg>POSIX event tracer formatting<commit_after>/****************************************************************************
*
*   Copyright (c) 2015 PX4 Development Team. All rights reserved.
*      Author: Pavel Kirienko <pavel.kirienko@gmail.com>
*              David Sidrane <david_s5@usa.net>
*
****************************************************************************/

#ifndef UAVCAN_POSIX_DYNAMIC_NODE_ID_SERVER_FILE_EVENT_TRACER_HPP_INCLUDED
#define UAVCAN_POSIX_DYNAMIC_NODE_ID_SERVER_FILE_EVENT_TRACER_HPP_INCLUDED

#include <uavcan/protocol/dynamic_node_id_server/event.hpp>
#include <cstdio>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>

namespace uavcan_posix
{
namespace dynamic_node_id_server
{
/**
 * This interface implements a POSIX compliant file based IEventTracer interface
 */
class FileEventTracer : public uavcan::dynamic_node_id_server::IEventTracer
{
    /**
     * Maximum length of full path to log file
     */
    enum { MaxPathLength = 128 };

    enum { FilePermissions = 438 };     ///< 0o666

    /**
     * This type is used for the path
     */
    typedef uavcan::MakeString<MaxPathLength>::Type PathString;

    PathString path_;

protected:
    virtual void onEvent(uavcan::dynamic_node_id_server::TraceCode code, uavcan::int64_t argument)
    {
        using namespace std;

        timespec ts = timespec();               // If clock_gettime() fails, zero time will be used
        (void)clock_gettime(CLOCK_REALTIME, &ts);

        int fd = open(path_.c_str(), O_WRONLY | O_CREAT | O_APPEND, FilePermissions);
        if (fd >= 0)
        {
            const int FormatBufferLength = 63;
            char buffer[FormatBufferLength + 1];
            int n = snprintf(buffer, FormatBufferLength, "%ld.%06ld\t%d\t%lld\n",
                             static_cast<long>(ts.tv_sec), static_cast<long>(ts.tv_nsec / 1000L),
                             static_cast<int>(code), static_cast<long long>(argument));
            (void)write(fd, buffer, n); // TODO FIXME Write loop
            (void)close(fd);
        }
    }

public:
    /**
     * Initializes the file based event tracer.
     */
    int init(const PathString& path)
    {
        using namespace std;

        int rv = -uavcan::ErrInvalidParam;

        if (path.size() > 0)
        {
            rv = 0;
            path_ = path.c_str();
            int fd = open(path_.c_str(), O_RDWR | O_CREAT | O_TRUNC, FilePermissions);
            if (fd >= 0)
            {
                (void)close(fd);
            }
        }
        return rv;
    }
};

}
}

#endif // Include guard
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <unistd.h>

#include <tms_msg_rc/rc_robot_control.h>
#include <tms_msg_db/TmsdbStamped.h>
#include <boost/date_time/posix_time/posix_time.hpp>

#define SUCCESS                  1
#define FAILURE                 -1
#define SRV_UNIT_ERR            -112
#define SRV_CMD_ERR             -113

ros::Publisher pose_publisher;
// ロボット初期値----------------------------------------------------------------
double g_x = 2000.0;
double g_y = 500.0;
double g_t = -90.0; // -90
double g_r_state = 1;

//------------------------------------------------------------------------------
int8_t VehicleMoveLinearAbs(double x_mm, double y_mm, double theta_deg)
{
  bool ret = true;

  g_x = x_mm;
  g_y = y_mm;
  g_t = theta_deg;
  if (g_t < -180) g_t = g_t+360;

  printf("vehicleMoveLinearAbs(%0.1fmm, %0.1fmm, %0.1fdeg) result:",g_x, g_y, g_t);
  ret ? printf("Success\n") : printf("Failure\n");

  if(ret) return  SUCCESS;
  else    return  FAILURE;
}

//------------------------------------------------------------------------------
bool robotControl(tms_msg_rc::rc_robot_control::Request &req,
		tms_msg_rc::rc_robot_control::Response &res) {
	  switch(req.unit)
	  {
	  //----------------------------------------------------------------------------
	    case	1: // Vehivle
	        switch(req.cmd) {
	            case	15: res.result = VehicleMoveLinearAbs(req.arg[0],req.arg[1],req.arg[2]); break;
            default:   res.result = SRV_CMD_ERR; break;
	        }
	        break;

	    //--------------------------------------------------------------------------
	    default:res.result = SRV_UNIT_ERR; break;
		}
		return true;
}

//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
  //--------------------------------------------------------------------------
  ros::init(argc, argv, "mimamorukun_virtual_control");
  ros::NodeHandle nh;
  ros::ServiceServer service = nh.advertiseService("mimamorukun_virtual_control", robotControl);

  pose_publisher = nh.advertise<tms_msg_db::TmsdbStamped>("tms_db_data", 10);

  // kobuki initialize
  printf("Virtual MIMAMORUKUN initialization has been completed.\n\n");
  ros::Rate loop_rate(10); // 10Hz frequency (0.1 sec)

  //--------------------------------------------------------------------------
  while (ros::ok())
  {
	  ros::Time now = ros::Time::now() + ros::Duration(9*60*60); // GMT +9
	  double secs = now.toSec();
	  //ROS_INFO("r1|Time:%f,x:%f,y:%f,ry:%f", secs,g_x,g_y,g_t);

	  tms_msg_db::TmsdbStamped db_msg;
	  tms_msg_db::Tmsdb current_pos_data;

	  db_msg.header.frame_id  = "/world";
	  db_msg.header.stamp     = now;

	  current_pos_data.time    = boost::posix_time::to_iso_extended_string(now.toBoost());
	  current_pos_data.id      = 2007;
	  current_pos_data.x       = g_x;
	  current_pos_data.y       = g_y;
	  current_pos_data.z       = 0;
	  current_pos_data.rr      = 0.0;
	  current_pos_data.rp      = 0.0;
	  current_pos_data.ry      = g_t;
	  current_pos_data.place   = 5001;
	  current_pos_data.sensor  = 3005;
	  current_pos_data.state   = g_r_state;

	  db_msg.tmsdb.push_back(current_pos_data);
	  pose_publisher.publish(db_msg);

	  ros::spinOnce();
	  loop_rate.sleep();
  }
  return(0);
}
//------------------------------------------------------------------------------
<commit_msg>virtual_controlを整形<commit_after>#include <ros/ros.h>
#include <unistd.h>

#include <tms_msg_rc/rc_robot_control.h>
#include <tms_msg_db/TmsdbStamped.h>
#include <boost/date_time/posix_time/posix_time.hpp>

#define SUCCESS 1
#define FAILURE -1
#define SRV_UNIT_ERR -112
#define SRV_CMD_ERR -113

ros::Publisher pose_publisher;
// ロボット初期値----------------------------------------------------------------
double g_x = 2000.0;
double g_y = 500.0;
double g_t = -90.0;  // -90
double g_r_state = 1;

//------------------------------------------------------------------------------
int8_t VehicleMoveLinearAbs(double x_mm, double y_mm, double theta_deg) {
  bool ret = true;

  g_x = x_mm;
  g_y = y_mm;
  g_t = theta_deg;
  if (g_t < -180) g_t = g_t + 360;

  printf("vehicleMoveLinearAbs(%0.1fmm, %0.1fmm, %0.1fdeg) result:", g_x, g_y, g_t);
  ret ? printf("Success\n") : printf("Failure\n");

  if (ret)
    return SUCCESS;
  else
    return FAILURE;
}

//------------------------------------------------------------------------------
bool robotControl(tms_msg_rc::rc_robot_control::Request &req,
                  tms_msg_rc::rc_robot_control::Response &res) {
  switch (req.unit) {
    //----------------------------------------------------------------------------
    case 1:  // Vehivle
      switch (req.cmd) {
        case 15:
          res.result = VehicleMoveLinearAbs(req.arg[0], req.arg[1], req.arg[2]);
          break;
        default:
          res.result = SRV_CMD_ERR;
          break;
      }
      break;

    //--------------------------------------------------------------------------
    default:
      res.result = SRV_UNIT_ERR;
      break;
  }
  return true;
}

//------------------------------------------------------------------------------
int main(int argc, char **argv) {
  //--------------------------------------------------------------------------
  ros::init(argc, argv, "mimamorukun_virtual_control");
  ros::NodeHandle nh;
  ros::ServiceServer service = nh.advertiseService("mimamorukun_virtual_control", robotControl);

  pose_publisher = nh.advertise<tms_msg_db::TmsdbStamped>("tms_db_data", 10);

  // kobuki initialize
  printf("Virtual MIMAMORUKUN initialization has been completed.\n\n");
  ros::Rate loop_rate(10);  // 10Hz frequency (0.1 sec)

  //--------------------------------------------------------------------------
  while (ros::ok()) {
    ros::Time now = ros::Time::now() + ros::Duration(9 * 60 * 60);  // GMT +9
    double secs = now.toSec();
    // ROS_INFO("r1|Time:%f,x:%f,y:%f,ry:%f", secs,g_x,g_y,g_t);

    tms_msg_db::TmsdbStamped db_msg;
    tms_msg_db::Tmsdb current_pos_data;

    db_msg.header.frame_id = "/world";
    db_msg.header.stamp = now;

    current_pos_data.time = boost::posix_time::to_iso_extended_string(now.toBoost());
    current_pos_data.id = 2007;
    current_pos_data.x = g_x;
    current_pos_data.y = g_y;
    current_pos_data.z = 0;
    current_pos_data.rr = 0.0;
    current_pos_data.rp = 0.0;
    current_pos_data.ry = g_t;
    current_pos_data.place = 5001;
    current_pos_data.sensor = 3005;
    current_pos_data.state = g_r_state;

    db_msg.tmsdb.push_back(current_pos_data);
    pose_publisher.publish(db_msg);

    ros::spinOnce();
    loop_rate.sleep();
  }
  return (0);
}
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * OpenGL Conformance Test Suite
 * -----------------------------
 *
 * Copyright (c) 2017 The Khronos Group Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */ /*!
 * \file esextcTessellationShaderWinding.cpp
 * \brief Test winding order with tessellation shaders
 */ /*-------------------------------------------------------------------*/

#include "esextcTessellationShaderWinding.hpp"
#include "deSharedPtr.hpp"
#include "esextcTessellationShaderUtils.hpp"
#include "gluContextInfo.hpp"
#include "gluDefs.hpp"
#include "gluPixelTransfer.hpp"
#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include "tcuRGBA.hpp"
#include "tcuSurface.hpp"
#include "tcuTestLog.hpp"
#include <string>

namespace glcts
{

class WindingCase : public TestCaseBase
{
public:
	WindingCase(glcts::Context& context, const ExtParameters& extParams, std::string name, std::string primitiveType,
				std::string winding);

	void		  init(void);
	void		  deinit(void);
	IterateResult iterate(void);

private:
	static const int RENDER_SIZE = 64;

	de::SharedPtr<const glu::ShaderProgram> m_program;
};

WindingCase::WindingCase(glcts::Context& context, const ExtParameters& extParams, std::string name,
						 std::string primitiveType, std::string winding)
	: TestCaseBase(context, extParams, name.c_str(), "")
{
	DE_ASSERT((primitiveType.compare("triangles") == 0) || (primitiveType.compare("quads") == 0));
	DE_ASSERT((winding.compare("cw") == 0) || (winding.compare("ccw") == 0));

	m_specializationMap["PRIMITIVE_TYPE"] = primitiveType;
	m_specializationMap["WINDING"]		  = winding;
}

void WindingCase::init(void)
{
	TestCaseBase::init();
	if (!m_is_tessellation_shader_supported)
	{
		TCU_THROW(NotSupportedError, TESSELLATION_SHADER_EXTENSION_NOT_SUPPORTED);
	}

	TestCaseBase::init();

	const char* vs("${VERSION}\n"
				   "void main (void)\n"
				   "{\n"
				   "}\n");
	const char* tcs("${VERSION}\n"
					"${TESSELLATION_SHADER_REQUIRE}\n"
					"layout (vertices = 1) out;\n"
					"void main (void)\n"
					"{\n"
					"	gl_TessLevelInner[0] = 5.0;\n"
					"	gl_TessLevelInner[1] = 5.0;\n"
					"\n"
					"	gl_TessLevelOuter[0] = 5.0;\n"
					"	gl_TessLevelOuter[1] = 5.0;\n"
					"	gl_TessLevelOuter[2] = 5.0;\n"
					"	gl_TessLevelOuter[3] = 5.0;\n"
					"}\n");
	const char* tes("${VERSION}\n"
					"${TESSELLATION_SHADER_REQUIRE}\n"
					"layout (${PRIMITIVE_TYPE}, ${WINDING}) in;\n"
					"void main (void)\n"
					"{\n"
					"	gl_Position = vec4(gl_TessCoord.xy*2.0 - 1.0, 0.0, 1.0);\n"
					"}\n");
	const char* fs("${VERSION}\n"
				   "layout (location = 0) out mediump vec4 o_color;\n"
				   "void main (void)\n"
				   "{\n"
				   "	o_color = vec4(1.0);\n"
				   "}\n");

	m_program = de::SharedPtr<const glu::ShaderProgram>(
		new glu::ShaderProgram(m_context.getRenderContext(),
							   glu::ProgramSources() << glu::VertexSource(specializeShader(1, &vs))
													 << glu::TessellationControlSource(specializeShader(1, &tcs))
													 << glu::TessellationEvaluationSource(specializeShader(1, &tes))
													 << glu::FragmentSource(specializeShader(1, &fs))));

	m_testCtx.getLog() << *m_program;
	if (!m_program->isOk())
		TCU_FAIL("Program compilation failed");
}

void WindingCase::deinit(void)
{
	m_program.clear();
}

WindingCase::IterateResult WindingCase::iterate(void)
{
	const glu::RenderContext& renderCtx = m_context.getRenderContext();
	const deUint32			  programGL = m_program->getProgram();
	const glw::Functions&	 gl		= renderCtx.getFunctions();

	const unsigned int windingTaken[2]	 = { GL_CW, GL_CCW };
	const char*		   windingTakenName[2] = { "GL_CW", "GL_CCW" };

	const bool testPrimitiveTypeIsTriangles = (m_specializationMap["PRIMITIVE_TYPE"].compare("triangles") == 0);
	const bool testWindingIsCW				= (m_specializationMap["WINDING"].compare("cw") == 0);
	bool	   success						= true;

	gl.viewport(0, 0, RENDER_SIZE, RENDER_SIZE);
	gl.clearColor(1.0f, 0.0f, 0.0f, 1.0f);
	gl.useProgram(programGL);

	gl.patchParameteri(GL_PATCH_VERTICES, 1);

	gl.enable(GL_CULL_FACE);

	deUint32 vaoGL;
	gl.genVertexArrays(1, &vaoGL);
	gl.bindVertexArray(vaoGL);

	m_testCtx.getLog() << tcu::TestLog::Message << "Face culling enabled" << tcu::TestLog::EndMessage;

	for (int windingIndex = 0; windingIndex < 2; windingIndex++)
	{
		m_testCtx.getLog() << tcu::TestLog::Message << "Setting glFrontFace(" << windingTakenName[windingIndex] << ")"
						   << tcu::TestLog::EndMessage;

		gl.frontFace(windingTaken[windingIndex]);

		gl.clear(GL_COLOR_BUFFER_BIT);
		gl.drawArrays(GL_PATCHES, 0, 1);
		GLU_EXPECT_NO_ERROR(gl.getError(), "Draw failed");

		{
			tcu::Surface rendered(RENDER_SIZE, RENDER_SIZE);
			glu::readPixels(renderCtx, 0, 0, rendered.getAccess());
			m_testCtx.getLog() << tcu::TestLog::Image("RenderedImage", "Rendered Image", rendered);

			{
				const int badPixelTolerance =
					testPrimitiveTypeIsTriangles ? 5 * de::max(rendered.getWidth(), rendered.getHeight()) : 0;
				const int totalNumPixels = rendered.getWidth() * rendered.getHeight();

				int numWhitePixels = 0;
				int numRedPixels   = 0;
				for (int y = 0; y < rendered.getHeight(); y++)
					for (int x = 0; x < rendered.getWidth(); x++)
					{
						numWhitePixels += rendered.getPixel(x, y) == tcu::RGBA::white() ? 1 : 0;
						numRedPixels += rendered.getPixel(x, y) == tcu::RGBA::red() ? 1 : 0;
					}

				DE_ASSERT(numWhitePixels + numRedPixels <= totalNumPixels);

				m_testCtx.getLog() << tcu::TestLog::Message << "Note: got " << numWhitePixels << " white and "
								   << numRedPixels << " red pixels" << tcu::TestLog::EndMessage;

				if (totalNumPixels - numWhitePixels - numRedPixels > badPixelTolerance)
				{
					m_testCtx.getLog() << tcu::TestLog::Message << "Failure: Got "
									   << totalNumPixels - numWhitePixels - numRedPixels
									   << " other than white or red pixels (maximum tolerance " << badPixelTolerance
									   << ")" << tcu::TestLog::EndMessage;
					success = false;
					break;
				}

				bool frontFaceWindingIsCW = (windingIndex == 0);
				if (frontFaceWindingIsCW == testWindingIsCW)
				{
					if (testPrimitiveTypeIsTriangles)
					{
						if (de::abs(numWhitePixels - totalNumPixels / 2) > badPixelTolerance)
						{
							m_testCtx.getLog() << tcu::TestLog::Message
											   << "Failure: wrong number of white pixels; expected approximately "
											   << totalNumPixels / 2 << tcu::TestLog::EndMessage;
							success = false;
							break;
						}
					}
					else // test primitive type is quads
					{
						if (numWhitePixels != totalNumPixels)
						{
							m_testCtx.getLog()
								<< tcu::TestLog::Message << "Failure: expected only white pixels (full-viewport quad)"
								<< tcu::TestLog::EndMessage;
							success = false;
							break;
						}
					}
				}
				else
				{
					if (numWhitePixels != 0)
					{
						m_testCtx.getLog()
							<< tcu::TestLog::Message << "Failure: expected only red pixels (everything culled)"
							<< tcu::TestLog::EndMessage;
						success = false;
						break;
					}
				}
			}
		}
	}

	gl.bindVertexArray(0);
	gl.deleteVertexArrays(1, &vaoGL);

	m_testCtx.setTestResult(success ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL,
							success ? "Pass" : "Image verification failed");
	return STOP;
}

/** Constructor
 *
 * @param context Test context
 **/
TesselationShaderWindingTests::TesselationShaderWindingTests(glcts::Context& context, const ExtParameters& extParams)
	: TestCaseGroupBase(context, extParams, "winding", "Verifies winding order with tessellation shaders")
{
}

/**
 * Initializes test groups for winding tests
 **/
void TesselationShaderWindingTests::init(void)
{
	addChild(new WindingCase(m_context, m_extParams, "triangles_ccw", "triangles", "ccw"));
	addChild(new WindingCase(m_context, m_extParams, "triangles_cw", "triangles", "cw"));
	addChild(new WindingCase(m_context, m_extParams, "quads_ccw", "quads", "ccw"));
	addChild(new WindingCase(m_context, m_extParams, "quads_cw", "quads", "cw"));
}

} /* namespace glcts */
<commit_msg>Render to FBO in tessellation winding order tests<commit_after>/*-------------------------------------------------------------------------
 * OpenGL Conformance Test Suite
 * -----------------------------
 *
 * Copyright (c) 2017 The Khronos Group Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */ /*!
 * \file esextcTessellationShaderWinding.cpp
 * \brief Test winding order with tessellation shaders
 */ /*-------------------------------------------------------------------*/

#include "esextcTessellationShaderWinding.hpp"
#include "deSharedPtr.hpp"
#include "esextcTessellationShaderUtils.hpp"
#include "gluContextInfo.hpp"
#include "gluDefs.hpp"
#include "gluPixelTransfer.hpp"
#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include "tcuRGBA.hpp"
#include "tcuSurface.hpp"
#include "tcuTestLog.hpp"
#include <string>

namespace glcts
{

class WindingCase : public TestCaseBase
{
public:
	WindingCase(glcts::Context& context, const ExtParameters& extParams, std::string name, std::string primitiveType,
				std::string winding);

	void		  init(void);
	void		  deinit(void);
	IterateResult iterate(void);
	void prepareFramebuffer();

private:
	static const int RENDER_SIZE = 64;

	de::SharedPtr<const glu::ShaderProgram> m_program;
	glw::GLuint m_rbo;
	glw::GLuint m_fbo;
};

WindingCase::WindingCase(glcts::Context& context, const ExtParameters& extParams, std::string name,
						 std::string primitiveType, std::string winding)
	: TestCaseBase(context, extParams, name.c_str(), "")
{
	DE_ASSERT((primitiveType.compare("triangles") == 0) || (primitiveType.compare("quads") == 0));
	DE_ASSERT((winding.compare("cw") == 0) || (winding.compare("ccw") == 0));

	m_specializationMap["PRIMITIVE_TYPE"] = primitiveType;
	m_specializationMap["WINDING"]        = winding;
	m_rbo                                 = 0;
	m_fbo                                 = 0;
}

void WindingCase::init(void)
{
	TestCaseBase::init();
	if (!m_is_tessellation_shader_supported)
	{
		TCU_THROW(NotSupportedError, TESSELLATION_SHADER_EXTENSION_NOT_SUPPORTED);
	}

	TestCaseBase::init();

	const char* vs("${VERSION}\n"
				   "void main (void)\n"
				   "{\n"
				   "}\n");
	const char* tcs("${VERSION}\n"
					"${TESSELLATION_SHADER_REQUIRE}\n"
					"layout (vertices = 1) out;\n"
					"void main (void)\n"
					"{\n"
					"	gl_TessLevelInner[0] = 5.0;\n"
					"	gl_TessLevelInner[1] = 5.0;\n"
					"\n"
					"	gl_TessLevelOuter[0] = 5.0;\n"
					"	gl_TessLevelOuter[1] = 5.0;\n"
					"	gl_TessLevelOuter[2] = 5.0;\n"
					"	gl_TessLevelOuter[3] = 5.0;\n"
					"}\n");
	const char* tes("${VERSION}\n"
					"${TESSELLATION_SHADER_REQUIRE}\n"
					"layout (${PRIMITIVE_TYPE}, ${WINDING}) in;\n"
					"void main (void)\n"
					"{\n"
					"	gl_Position = vec4(gl_TessCoord.xy*2.0 - 1.0, 0.0, 1.0);\n"
					"}\n");
	const char* fs("${VERSION}\n"
				   "layout (location = 0) out mediump vec4 o_color;\n"
				   "void main (void)\n"
				   "{\n"
				   "	o_color = vec4(1.0);\n"
				   "}\n");

	m_program = de::SharedPtr<const glu::ShaderProgram>(
		new glu::ShaderProgram(m_context.getRenderContext(),
							   glu::ProgramSources() << glu::VertexSource(specializeShader(1, &vs))
													 << glu::TessellationControlSource(specializeShader(1, &tcs))
													 << glu::TessellationEvaluationSource(specializeShader(1, &tes))
													 << glu::FragmentSource(specializeShader(1, &fs))));

	m_testCtx.getLog() << *m_program;
	if (!m_program->isOk())
		TCU_FAIL("Program compilation failed");
}

void WindingCase::deinit(void)
{
	const glw::Functions& gl = m_context.getRenderContext().getFunctions();

	if (m_fbo)
	{
		gl.deleteFramebuffers(1, &m_fbo);
		m_fbo = 0;
	}

	if (m_rbo)
	{
		gl.deleteRenderbuffers(1, &m_rbo);
		m_rbo = 0;
	}

	m_program.clear();
}

/** @brief Bind default framebuffer object.
 *
 *  @note The function may throw if unexpected error has occured.
 */
void WindingCase::prepareFramebuffer()
{
	/* Shortcut for GL functionality */
	const glw::Functions& gl = m_context.getRenderContext().getFunctions();

	gl.genRenderbuffers(1, &m_rbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glGenRenderbuffers call failed.");

	gl.bindRenderbuffer(GL_RENDERBUFFER, m_rbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glBindRenderbuffer call failed.");

	gl.renderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, RENDER_SIZE, RENDER_SIZE);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glRenderbufferStorage call failed.");

	gl.genFramebuffers(1, &m_fbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glGenFramebuffers call failed.");

	gl.bindFramebuffer(GL_FRAMEBUFFER, m_fbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glBindFramebuffer call failed.");

	gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_rbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glFramebufferRenderbuffer call failed.");
}

WindingCase::IterateResult WindingCase::iterate(void)
{
	const glu::RenderContext& renderCtx = m_context.getRenderContext();
	const deUint32			  programGL = m_program->getProgram();
	const glw::Functions&	 gl		= renderCtx.getFunctions();

	const unsigned int windingTaken[2]	 = { GL_CW, GL_CCW };
	const char*		   windingTakenName[2] = { "GL_CW", "GL_CCW" };

	const bool testPrimitiveTypeIsTriangles = (m_specializationMap["PRIMITIVE_TYPE"].compare("triangles") == 0);
	const bool testWindingIsCW				= (m_specializationMap["WINDING"].compare("cw") == 0);
	bool	   success						= true;

	prepareFramebuffer();
	gl.viewport(0, 0, RENDER_SIZE, RENDER_SIZE);
	gl.clearColor(1.0f, 0.0f, 0.0f, 1.0f);
	gl.useProgram(programGL);

	gl.patchParameteri(GL_PATCH_VERTICES, 1);

	gl.enable(GL_CULL_FACE);

	deUint32 vaoGL;
	gl.genVertexArrays(1, &vaoGL);
	gl.bindVertexArray(vaoGL);

	m_testCtx.getLog() << tcu::TestLog::Message << "Face culling enabled" << tcu::TestLog::EndMessage;

	for (int windingIndex = 0; windingIndex < 2; windingIndex++)
	{
		m_testCtx.getLog() << tcu::TestLog::Message << "Setting glFrontFace(" << windingTakenName[windingIndex] << ")"
						   << tcu::TestLog::EndMessage;

		gl.frontFace(windingTaken[windingIndex]);

		gl.clear(GL_COLOR_BUFFER_BIT);
		gl.drawArrays(GL_PATCHES, 0, 1);
		GLU_EXPECT_NO_ERROR(gl.getError(), "Draw failed");

		{
			tcu::Surface rendered(RENDER_SIZE, RENDER_SIZE);
			glu::readPixels(renderCtx, 0, 0, rendered.getAccess());
			m_testCtx.getLog() << tcu::TestLog::Image("RenderedImage", "Rendered Image", rendered);

			{
				const int badPixelTolerance =
					testPrimitiveTypeIsTriangles ? 5 * de::max(rendered.getWidth(), rendered.getHeight()) : 0;
				const int totalNumPixels = rendered.getWidth() * rendered.getHeight();

				int numWhitePixels = 0;
				int numRedPixels   = 0;
				for (int y = 0; y < rendered.getHeight(); y++)
					for (int x = 0; x < rendered.getWidth(); x++)
					{
						numWhitePixels += rendered.getPixel(x, y) == tcu::RGBA::white() ? 1 : 0;
						numRedPixels += rendered.getPixel(x, y) == tcu::RGBA::red() ? 1 : 0;
					}

				DE_ASSERT(numWhitePixels + numRedPixels <= totalNumPixels);

				m_testCtx.getLog() << tcu::TestLog::Message << "Note: got " << numWhitePixels << " white and "
								   << numRedPixels << " red pixels" << tcu::TestLog::EndMessage;

				if (totalNumPixels - numWhitePixels - numRedPixels > badPixelTolerance)
				{
					m_testCtx.getLog() << tcu::TestLog::Message << "Failure: Got "
									   << totalNumPixels - numWhitePixels - numRedPixels
									   << " other than white or red pixels (maximum tolerance " << badPixelTolerance
									   << ")" << tcu::TestLog::EndMessage;
					success = false;
					break;
				}

				bool frontFaceWindingIsCW = (windingIndex == 0);
				if (frontFaceWindingIsCW == testWindingIsCW)
				{
					if (testPrimitiveTypeIsTriangles)
					{
						if (de::abs(numWhitePixels - totalNumPixels / 2) > badPixelTolerance)
						{
							m_testCtx.getLog() << tcu::TestLog::Message
											   << "Failure: wrong number of white pixels; expected approximately "
											   << totalNumPixels / 2 << tcu::TestLog::EndMessage;
							success = false;
							break;
						}
					}
					else // test primitive type is quads
					{
						if (numWhitePixels != totalNumPixels)
						{
							m_testCtx.getLog()
								<< tcu::TestLog::Message << "Failure: expected only white pixels (full-viewport quad)"
								<< tcu::TestLog::EndMessage;
							success = false;
							break;
						}
					}
				}
				else
				{
					if (numWhitePixels != 0)
					{
						m_testCtx.getLog()
							<< tcu::TestLog::Message << "Failure: expected only red pixels (everything culled)"
							<< tcu::TestLog::EndMessage;
						success = false;
						break;
					}
				}
			}
		}
	}

	gl.bindVertexArray(0);
	gl.deleteVertexArrays(1, &vaoGL);

	m_testCtx.setTestResult(success ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL,
							success ? "Pass" : "Image verification failed");
	return STOP;
}

/** Constructor
 *
 * @param context Test context
 **/
TesselationShaderWindingTests::TesselationShaderWindingTests(glcts::Context& context, const ExtParameters& extParams)
	: TestCaseGroupBase(context, extParams, "winding", "Verifies winding order with tessellation shaders")
{
}

/**
 * Initializes test groups for winding tests
 **/
void TesselationShaderWindingTests::init(void)
{
	addChild(new WindingCase(m_context, m_extParams, "triangles_ccw", "triangles", "ccw"));
	addChild(new WindingCase(m_context, m_extParams, "triangles_cw", "triangles", "cw"));
	addChild(new WindingCase(m_context, m_extParams, "quads_ccw", "quads", "ccw"));
	addChild(new WindingCase(m_context, m_extParams, "quads_cw", "quads", "cw"));
}

} /* namespace glcts */
<|endoftext|>


<commit_before>#ifndef NEW_AIO_H
#define NEW_AIO_H

/*Defines virtual AIO objects to be instantiated
by concrete implementation in the src/ file.
*/

#include<string>
#include<stdexcept>

#include<stdint.h>

#include<boost/shared_ptr.hpp>

class Process;
class Symbol;

/*
The AIO is based on event objects.  Event
objects are just passive requests; in order to
"arm" an event, it should be added to the global
event waiting set object.

Events are:
1.  Write-to-I/O event
2.  Read-from-I/O event
3.  Accept-from-I/O Socket event
4.  Sleep Event
5.  System Event (i.e. spawn child OS process)
*/

/*Details are handled by the AIO implementation
This include file deals only in abstractions;
we don't care how they are actually implemented.
*/

class Event;
class ProcessInvoker;

/*Errors in I/O should throw this class*/
/*Could use a Maybe T type I suppose though*/
class IOError : public std::runtime_error {
};
/*
Errors are caught only on:
1. opening a file
2. seeking
3. closing

In all other cases, errors are caught at the time
that events are triggered; they are reported by
sending messages to the process being informed.
*/

/*-----------------------------------------------------------------------------
Implementation-specific
-----------------------------------------------------------------------------*/

/*I/O Ports*/
class IOPort {
public:
	void close(void);

	virtual boost::shared_ptr<Event> read(
		boost::shared_ptr<ProcessInvoker>, size_t
	) =0;
	virtual boost::shared_ptr<Event> write(boost::shared_ptr<ProcessInvoker>,
		std::vector<unsigned char> const&
	) =0;
	virtual boost::shared_ptr<Event> accept(
		boost::shared_ptr<ProcessInvoker>
	) =0;

	virtual ~IOPort() { }
};

/*Will only be called once, at init*/
boost::shared_ptr<IOPort> ioport_stdin(void);
boost::shared_ptr<IOPort> ioport_stdout(void);
boost::shared_ptr<IOPort> ioport_stderr(void);

boost::shared_ptr<IOPort> infile(std::string);
boost::shared_ptr<IOPort> outfile(std::string);
boost::shared_ptr<IOPort> appendfile(std::string);

void close(boost::shared_ptr<IOPort>);

class Event {
public:
	virtual void seek(uint64_t) =0;

	virtual ~Event() { }
};

boost::shared_ptr<Event> system_event(boost::shared_ptr<ProcessInvoker>,std::string);
boost::shared_ptr<Event> sleep_event(boost::shared_ptr<ProcessInvoker>,size_t);

/*used as a Singleton, although we don't enforce it*/
class EventSetImpl;
class EventSet {
private:
	EventSetImpl* pimpl;

public:
	void add_event(boost::shared_ptr<Event>);
	void remove_event(boost::shared_ptr<Event>);

	EventSet(void);
	~EventSet();
};

/*-----------------------------------------------------------------------------
Shared across Implementations
-----------------------------------------------------------------------------*/

/*implementations in src/aio.cpp*/

class ProcessInvoker {
private:
	Process* P;
public:
	void read_respond(
		boost::shared_ptr<IOPort>, std::vector<unsigned char> const&
	);
	void write_respond(
		boost::shared_ptr<IOPort>, std::vector<unsigned char> const&
	);
	void accept_respond(
		boost::shared_ptr<IOPort> socket, boost::shared_ptr<IOPort> new_socket
	);
	void sleep_respond(
		boost::shared_ptr<Event>, size_t
	);
	void system_respond(
		boost::shared_ptr<Event>, int term_code
	);

	/*call for errors*/
	void io_error_respond(
		boost::shared_ptr<IOPort>, std::string
	);
	void other_error_respond(
		boost::shared_ptr<Event>, std::string
	);
};

#endif // NEW_AIO_H

<commit_msg>inc/aio.hpp: Added TODO<commit_after>#ifndef NEW_AIO_H
#define NEW_AIO_H

/*Defines virtual AIO objects to be instantiated
by concrete implementation in the src/ file.
*/

#include<string>
#include<stdexcept>

#include<stdint.h>

#include<boost/shared_ptr.hpp>

class Process;
class Symbol;

/*
The AIO is based on event objects.  Event
objects are just passive requests; in order to
"arm" an event, it should be added to the global
event waiting set object.

Events are:
1.  Write-to-I/O event
2.  Read-from-I/O event
3.  Accept-from-I/O Socket event
4.  Sleep Event
5.  System Event (i.e. spawn child OS process)
*/

/*Details are handled by the AIO implementation
This include file deals only in abstractions;
we don't care how they are actually implemented.
*/

class Event;
class ProcessInvoker;

/*Errors in I/O should throw this class*/
/*Could use a Maybe T type I suppose though*/
class IOError : public std::runtime_error {
};
/*
Errors are caught only on:
1. opening a file
2. seeking
3. closing

In all other cases, errors are caught at the time
that events are triggered; they are reported by
sending messages to the process being informed.
*/

/*-----------------------------------------------------------------------------
Implementation-specific
-----------------------------------------------------------------------------*/

/*I/O Ports*/
class IOPort {
public:
	void close(void);

	virtual boost::shared_ptr<Event> read(
		boost::shared_ptr<ProcessInvoker>, size_t
	) =0;
	virtual boost::shared_ptr<Event> write(boost::shared_ptr<ProcessInvoker>,
		std::vector<unsigned char> const&
	) =0;
	virtual boost::shared_ptr<Event> accept(
		boost::shared_ptr<ProcessInvoker>
	) =0;

	virtual ~IOPort() { }
};

/*Will only be called once, at init*/
boost::shared_ptr<IOPort> ioport_stdin(void);
boost::shared_ptr<IOPort> ioport_stdout(void);
boost::shared_ptr<IOPort> ioport_stderr(void);

boost::shared_ptr<IOPort> infile(std::string);
boost::shared_ptr<IOPort> outfile(std::string);
boost::shared_ptr<IOPort> appendfile(std::string);

void close(boost::shared_ptr<IOPort>);

class Event {
public:
	virtual void seek(uint64_t) =0;

	virtual ~Event() { }
};

boost::shared_ptr<Event> system_event(boost::shared_ptr<ProcessInvoker>,std::string);
boost::shared_ptr<Event> sleep_event(boost::shared_ptr<ProcessInvoker>,size_t);

/*used as a Singleton, although we don't enforce it*/
class EventSetImpl;
class EventSet {
private:
	EventSetImpl* pimpl;

public:
	void add_event(boost::shared_ptr<Event>);
	void remove_event(boost::shared_ptr<Event>);

	EventSet(void);
	~EventSet();
};

/*-----------------------------------------------------------------------------
Shared across Implementations
-----------------------------------------------------------------------------*/

/*implementations in src/aio.cpp*/

class ProcessInvoker {
private:
	Process* P;
public:
	void read_respond(
		boost::shared_ptr<IOPort>, std::vector<unsigned char> const&
	);
	void write_respond(
		boost::shared_ptr<IOPort>, std::vector<unsigned char> const&
	);
	void accept_respond(
		boost::shared_ptr<IOPort> socket, boost::shared_ptr<IOPort> new_socket
	);
	void sleep_respond(
		boost::shared_ptr<Event>, size_t
	);
	void system_respond(
		boost::shared_ptr<Event>, int term_code
	);

	/*call for errors*/
	void io_error_respond(
		boost::shared_ptr<IOPort>, std::string
	);
	void other_error_respond(
		boost::shared_ptr<Event>, std::string
	);

	/*TODO: integrate with workers.cpp so that existing ProcessInvoker's
	are part of the root set.
	*/
};

#endif // NEW_AIO_H

<|endoftext|>


<commit_before>/* Created by Darren Otgaar on 2016/10/28. http://www.github.com/otgaard/zap */

#include <apps/graphic_types.hpp>
#include <maths/rand_lcg.hpp>
#include "part_engine.hpp"

#include <tools/log.hpp>
#include <maths/io.hpp>

using namespace zap;
using namespace zap::maths;
using namespace zap::engine;
using namespace zap::effects;

using quad_vertex_t = vertex<pos2f_t, tex2f_t>;
using quad_vbuf_t = vertex_buffer<quad_vertex_t, buffer_usage::BU_STATIC_DRAW>;
using quad_mesh_t = mesh<vertex_stream<quad_vbuf_t>, primitive_type::PT_TRIANGLE_FAN>;

using vec3_pbuf_t = pixel_buffer<rgb32f_t, buffer_usage::BU_DYNAMIC_DRAW>;

using particle_vbuf_t = vertex_buffer<vertex<pos3f_t>, buffer_usage::BU_STREAM_COPY>;
using particle_mesh_t = mesh<vertex_stream<particle_vbuf_t>, primitive_type::PT_POINTS>;

extern const char* const particle_sim_vshdr;
extern const char* const particle_sim_fshdr;

extern const char* const particle_rndr_vshdr;
extern const char* const particle_rndr_fshdr;

struct particle_engine::state_t {
    const size_t particle_count = 250000;   // 1/4 million to start
    size_t dim;

    quad_vbuf_t quad_vbuf;
    quad_mesh_t quad_mesh;

    particle_vbuf_t particle_vbuf;          // Attributes...
    particle_mesh_t particle_mesh;          // Only need the mesh.  Poor design.  Adapter for pixel buffers? Any buffer?

    size_t allocated;                       // Number of active particles in simulation

    framebuffer buffers[2];                 // 3 targets (pos, vel, mae)
    int active_buffer;                      // Buffer switch

    vec3_pbuf_t copy_buffer;                // Used, for now, for copying data from the framebuffers and rendering the particles
                                            // Should be replaced by buffer textures to remove the copy so position_tex can be
                                            // bound directly as vertices in render pass (point sprites)

    program sim_pass;                       // Simulation Shader Pass
    program rndr_pass;                      // Render Shader Pass
};

particle_engine::particle_engine() : state_(new state_t()), s(*state_.get()) {
}

particle_engine::~particle_engine() {
}

bool particle_engine::setup_buffers() {
    for(auto& buf : s.buffers) {
        if(!buf.allocate() || !buf.initialise(3, s.dim, s.dim, pixel_format::PF_RGB, pixel_datatype::PD_FLOAT, false, false)) {
            LOG_ERR("Failure allocating/initialising framebuffers");
            return false;
        }
    }

    std::vector<rgb32f_t> initial_position;
    initial_position.reserve(s.dim*s.dim);
    rand_lcg rand;

    for(int i = 0, end = s.dim*s.dim; i != end; ++i) {
        auto P = vec3f(rand.random_s(), rand.random_s(), rand.random_s());
        while(P.length_sqr() > 1.) P.set(rand.random_s(), rand.random_s(), rand.random_s());

        initial_position.push_back(rgb32f_t(P.x, P.y, P.z));
    }

    if(!s.copy_buffer.allocate()) {
        LOG_ERR("Failed to allocate pixel copy buffer");
        return false;
    }

    s.copy_buffer.bind();
    if(!s.copy_buffer.initialise(s.dim, s.dim, initial_position.data())) {
        LOG_ERR("Failed to initialise pixel copy buffer");
        return false;
    }
    s.copy_buffer.release();

    if(!s.quad_vbuf.allocate() || !s.quad_mesh.allocate()) {
        LOG_ERR("Failed to initialise screen quad");
        return false;
    }

    s.quad_mesh.set_stream(&s.quad_vbuf);
    s.quad_mesh.bind(); s.quad_vbuf.bind();

    std::vector<quad_vertex_t> quad_vertices = {{
                                                        { { vec2f(-1.f, -1.f) }, { vec2f(0.f, 0.f) } },
                                                        { { vec2f(+1.f, -1.f) }, { vec2f(1.f, 0.f) } },
                                                        { { vec2f(+1.f, +1.f) }, { vec2f(1.f, 1.f) } },
                                                        { { vec2f(-1.f, +1.f) }, { vec2f(0.f, 1.f) } }
                                                }};

    s.quad_vbuf.initialise(quad_vertices);

    s.quad_mesh.release();

    if(!s.particle_vbuf.allocate() || !s.particle_mesh.allocate()) {
        LOG_ERR("Failed to initialise particle mesh");
        return false;
    }

    s.copy_buffer.bind();

    s.particle_mesh.set_stream(&s.particle_vbuf);
    s.particle_mesh.bind();
    s.particle_vbuf.bind();
    s.particle_vbuf.initialise(s.particle_count);
    s.particle_mesh.release();

    if(!s.buffers[0].write_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {
        LOG_ERR("Error during initialisation of particle system from pixel buffer");
        return false;
    }

    if(!s.buffers[0].write_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 1)) {
        LOG_ERR("Error during initialisation of particle system from pixel buffer");
        return false;
    }

    s.copy_buffer.release();
    s.active_buffer = 0;
    return true;
}

bool particle_engine::setup_shaders() {
    s.sim_pass.add_shader(shader_type::ST_VERTEX, particle_sim_vshdr);
    s.sim_pass.add_shader(shader_type::ST_FRAGMENT, particle_sim_fshdr);
    if(!s.sim_pass.link()) {
        LOG_ERR("Particle Simulation Pass shader failed to compile");
        return false;
    }

    s.rndr_pass.add_shader(shader_type::ST_VERTEX, particle_rndr_vshdr);
    s.rndr_pass.add_shader(shader_type::ST_FRAGMENT, particle_rndr_fshdr);
    if(!s.rndr_pass.link()) {
        LOG_ERR("Particle Render Pass shader failed to compile");
        return false;
    }

    // Set up shaders
    s.sim_pass.bind();
    s.sim_pass.bind_texture_unit(s.sim_pass.uniform_location("position_tex"), 0);
    s.sim_pass.bind_texture_unit(s.sim_pass.uniform_location("velocity_tex"), 1);
    s.sim_pass.release();
    return true;
}

bool particle_engine::initialise() {
    s.allocated = 0;
    s.dim = (size_t)std::pow(2, std::ceil(std::log2(std::sqrt(s.particle_count))));
    LOG("PARTICLE ENGINE DIMENSIONS:", s.dim, s.dim*s.dim, s.particle_count);

    if(!setup_buffers() || !setup_shaders()) {
        LOG_ERR("Failed to setup Particle Engine");
        return false;
    }

    return true;
}

void particle_engine::update(double t, float dt) {

}

void particle_engine::draw(const renderer::camera& cam) {
    if(s.active_buffer == 0) {   // Framebuffer 0 target was previously active (so we write to 1 & read from 0)
        s.buffers[1].bind();
        s.sim_pass.bind();
        s.buffers[0].get_attachment(0).bind(0);
        s.buffers[0].get_attachment(1).bind(1);

        s.quad_mesh.bind();
        s.quad_mesh.draw();
        s.quad_mesh.release();

        s.buffers[0].get_attachment(0).release();
        s.buffers[0].get_attachment(1).release();
        s.sim_pass.release();

        s.buffers[1].release();

        s.buffers[0].bind();
        if(!s.buffers[0].read_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {    // Read from 0
            LOG("Error reading framebuffer (0, 0)");
            return;
        }
        s.buffers[0].release();

        // TODO: This step is unnecessary - bind pixel_buffer as vertex buffer directly, refactor
        s.particle_vbuf.bind();
        s.copy_buffer.bind(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.copy_buffer(buffer_type::BT_PIXEL_UNPACK, buffer_type::BT_ARRAY, 0, 0, s.particle_count*sizeof(rgb32f_t));
        s.copy_buffer.release(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.release();

        s.active_buffer = 1;
    } else if(s.active_buffer == 1) {   // Framebuffer 1 target was previously active (so we write to 0 & read from 1)
        s.buffers[0].bind();
        s.sim_pass.bind();
        s.buffers[1].get_attachment(0).bind(0);
        s.buffers[1].get_attachment(1).bind(1);

        s.quad_mesh.bind();
        s.quad_mesh.draw();
        s.quad_mesh.release();

        s.buffers[1].get_attachment(0).release();
        s.buffers[1].get_attachment(1).release();
        s.sim_pass.release();

        s.buffers[0].release();

        s.buffers[1].bind();
        if(!s.buffers[1].read_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {    // Read from 1
            LOG("Error reading framebuffer (1, 0)");
            return;
        }
        s.buffers[1].release();

        s.particle_vbuf.bind();
        s.copy_buffer.bind(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.copy_buffer(buffer_type::BT_PIXEL_UNPACK, buffer_type::BT_ARRAY, 0, 0, s.particle_count*sizeof(rgb32f_t));
        s.copy_buffer.release(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.release();

        s.active_buffer = 0;
    }

    s.rndr_pass.bind();
    s.rndr_pass.bind_uniform("PVM", cam.proj_view());
    s.particle_mesh.bind();
    s.particle_mesh.draw();
    s.particle_mesh.release();
    s.rndr_pass.release();
}

const char* const particle_sim_vshdr = GLSL(
    in vec2 position;
    in vec2 texcoord1;

    out vec2 texcoord;

    void main() {
        texcoord = texcoord1;
        gl_Position = vec4(position.xy, 0.f, 1.f);
    }
);

const char* const particle_sim_fshdr = GLSL(
    uniform sampler2D position_tex;
    uniform sampler2D velocity_tex;

    in vec2 texcoord;

    out vec3 frag_colour[2];

    void main() {
        vec3 vel = texture(velocity_tex, texcoord).rgb;
        vec3 pos = texture(position_tex, texcoord).rgb + .01*vel;
        frag_colour[0] = length(pos) > 3.+(length(vel)) ? vec3(0., 0., 0.) : pos;
        frag_colour[1] = .99995*vel;
    }
);

const char* const particle_rndr_vshdr = GLSL(
    uniform mat4 PVM;

    in vec3 position;

    void main() {
        gl_Position = PVM * vec4(position, 1.f);
    }
);

const char* const particle_rndr_fshdr = GLSL(
    out vec4 frag_colour;

    void main() {
        frag_colour = vec4(1, 1, 1, 1);
    }
);
<commit_msg>- 3 framebuffer targets and render shader<commit_after>/* Created by Darren Otgaar on 2016/10/28. http://www.github.com/otgaard/zap */

#include <apps/graphic_types.hpp>
#include <maths/rand_lcg.hpp>
#include "part_engine.hpp"

#include <tools/log.hpp>
#include <maths/io.hpp>

using namespace zap;
using namespace zap::maths;
using namespace zap::engine;
using namespace zap::effects;

using quad_vertex_t = vertex<pos2f_t, tex2f_t>;
using quad_vbuf_t = vertex_buffer<quad_vertex_t, buffer_usage::BU_STATIC_DRAW>;
using quad_mesh_t = mesh<vertex_stream<quad_vbuf_t>, primitive_type::PT_TRIANGLE_FAN>;

using vec3_pbuf_t = pixel_buffer<rgb32f_t, buffer_usage::BU_DYNAMIC_DRAW>;

using particle_vbuf_t = vertex_buffer<vertex<pos3f_t>, buffer_usage::BU_STREAM_COPY>;
using particle_mesh_t = mesh<vertex_stream<particle_vbuf_t>, primitive_type::PT_POINTS>;

extern const char* const particle_sim_vshdr;
extern const char* const particle_sim_fshdr;

extern const char* const particle_rndr_vshdr;
extern const char* const particle_rndr_fshdr;

struct particle_engine::state_t {
    const size_t particle_count = 250000;   // 1/4 million to start
    size_t dim;

    quad_vbuf_t quad_vbuf;
    quad_mesh_t quad_mesh;

    particle_vbuf_t particle_vbuf;          // Attributes...
    particle_mesh_t particle_mesh;          // Only need the mesh.  Poor design.  Adapter for pixel buffers? Any buffer?

    size_t allocated;                       // Number of active particles in simulation

    framebuffer buffers[2];                 // 3 targets (pos, vel, mae)
    int active_buffer;                      // Buffer switch

    vec3_pbuf_t copy_buffer;                // Used, for now, for copying data from the framebuffers and rendering the particles
                                            // Should be replaced by buffer textures to remove the copy so position_tex can be
                                            // bound directly as vertices in render pass (point sprites)

    program sim_pass;                       // Simulation Shader Pass
    program rndr_pass;                      // Render Shader Pass

    // Temporary - Just for testing various concepts
    float angle;
};

particle_engine::particle_engine() : state_(new state_t()), s(*state_.get()) {
}

particle_engine::~particle_engine() {
}

bool particle_engine::setup_buffers() {
    for(auto& buf : s.buffers) {
        if(!buf.allocate() || !buf.initialise(3, s.dim, s.dim, pixel_format::PF_RGB, pixel_datatype::PD_FLOAT, false, false)) {
            LOG_ERR("Failure allocating/initialising framebuffers");
            return false;
        }
    }

    std::vector<rgb32f_t> initial_position;
    initial_position.reserve(s.dim*s.dim);
    rand_lcg rand;

    for(int i = 0, end = s.dim*s.dim; i != end; ++i) {
        auto P = vec3f(rand.random_s(), rand.random_s(), rand.random_s());
        while(P.length_sqr() > 1.) P.set(rand.random_s(), rand.random_s(), rand.random_s());

        initial_position.push_back(rgb32f_t(P.x, P.y, P.z));
    }

    if(!s.copy_buffer.allocate()) {
        LOG_ERR("Failed to allocate pixel copy buffer");
        return false;
    }

    s.copy_buffer.bind();
    if(!s.copy_buffer.initialise(s.dim, s.dim, initial_position.data())) {
        LOG_ERR("Failed to initialise pixel copy buffer");
        return false;
    }
    s.copy_buffer.release();

    if(!s.quad_vbuf.allocate() || !s.quad_mesh.allocate()) {
        LOG_ERR("Failed to initialise screen quad");
        return false;
    }

    s.quad_mesh.set_stream(&s.quad_vbuf);
    s.quad_mesh.bind(); s.quad_vbuf.bind();

    std::vector<quad_vertex_t> quad_vertices = {{
                                                        { { vec2f(-1.f, -1.f) }, { vec2f(0.f, 0.f) } },
                                                        { { vec2f(+1.f, -1.f) }, { vec2f(1.f, 0.f) } },
                                                        { { vec2f(+1.f, +1.f) }, { vec2f(1.f, 1.f) } },
                                                        { { vec2f(-1.f, +1.f) }, { vec2f(0.f, 1.f) } }
                                                }};

    s.quad_vbuf.initialise(quad_vertices);

    s.quad_mesh.release();

    if(!s.particle_vbuf.allocate() || !s.particle_mesh.allocate()) {
        LOG_ERR("Failed to initialise particle mesh");
        return false;
    }

    s.copy_buffer.bind();

    s.particle_mesh.set_stream(&s.particle_vbuf);
    s.particle_mesh.bind();
    s.particle_vbuf.bind();
    s.particle_vbuf.initialise(s.particle_count);
    s.particle_mesh.release();

    if(!s.buffers[0].write_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {
        LOG_ERR("Error during initialisation of particle system from pixel buffer");
        return false;
    }

    if(!s.buffers[0].write_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 1)) {
        LOG_ERR("Error during initialisation of particle system from pixel buffer");
        return false;
    }

    if(!s.buffers[0].write_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 2)) {
        LOG_ERR("Error during initialisation of particle system from pixel buffer");
        return false;
    }

    s.copy_buffer.release();
    s.active_buffer = 0;
    return true;
}

bool particle_engine::setup_shaders() {
    s.sim_pass.add_shader(shader_type::ST_VERTEX, particle_sim_vshdr);
    s.sim_pass.add_shader(shader_type::ST_FRAGMENT, particle_sim_fshdr);
    if(!s.sim_pass.link()) {
        LOG_ERR("Particle Simulation Pass shader failed to compile");
        return false;
    }

    s.rndr_pass.add_shader(shader_type::ST_VERTEX, particle_rndr_vshdr);
    s.rndr_pass.add_shader(shader_type::ST_FRAGMENT, particle_rndr_fshdr);
    if(!s.rndr_pass.link()) {
        LOG_ERR("Particle Render Pass shader failed to compile");
        return false;
    }

    // Set up shaders
    s.sim_pass.bind();
    s.sim_pass.bind_texture_unit(s.sim_pass.uniform_location("position_tex"), 0);
    s.sim_pass.bind_texture_unit(s.sim_pass.uniform_location("velocity_tex"), 1);
    s.sim_pass.bind_texture_unit(s.sim_pass.uniform_location("colour_tex"), 2);
    s.sim_pass.release();

    s.rndr_pass.bind();
    s.rndr_pass.bind_texture_unit(s.rndr_pass.uniform_location("colour_tex"), 0);
    s.rndr_pass.bind_uniform("dim", int(s.dim));
    s.rndr_pass.release();

    return true;
}

bool particle_engine::initialise() {
    s.allocated = 0;
    s.dim = (size_t)std::pow(2, std::ceil(std::log2(std::sqrt(s.particle_count))));
    LOG("PARTICLE ENGINE DIMENSIONS:", s.dim, s.dim*s.dim, s.particle_count);

    if(!setup_buffers() || !setup_shaders()) {
        LOG_ERR("Failed to setup Particle Engine");
        return false;
    }

    return true;
}

void particle_engine::update(double t, float dt) {

}

void particle_engine::draw(const renderer::camera& cam) {
    if(s.active_buffer == 0) {   // Framebuffer 0 target was previously active (so we write to 1 & read from 0)
        s.buffers[1].bind();
        s.sim_pass.bind();
        s.sim_pass.bind_uniform("angle", s.angle);
        s.buffers[0].get_attachment(0).bind(0);
        s.buffers[0].get_attachment(1).bind(1);
        s.buffers[0].get_attachment(2).bind(2);

        s.quad_mesh.bind();
        s.quad_mesh.draw();
        s.quad_mesh.release();

        s.buffers[0].get_attachment(0).release();
        s.buffers[0].get_attachment(1).release();
        s.buffers[0].get_attachment(2).release();

        s.sim_pass.release();

        s.buffers[1].release();

        s.buffers[0].bind();
        if(!s.buffers[0].read_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {    // Read from 0
            LOG("Error reading framebuffer (0, 0)");
            return;
        }
        s.buffers[0].release();

        // TODO: This step is unnecessary - bind pixel_buffer as vertex buffer directly, refactor
        s.particle_vbuf.bind();
        s.copy_buffer.bind(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.copy_buffer(buffer_type::BT_PIXEL_UNPACK, buffer_type::BT_ARRAY, 0, 0, s.particle_count*sizeof(rgb32f_t));
        s.copy_buffer.release(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.release();

        s.active_buffer = 1;
    } else if(s.active_buffer == 1) {   // Framebuffer 1 target was previously active (so we write to 0 & read from 1)
        s.buffers[0].bind();
        s.sim_pass.bind();
        s.sim_pass.bind_uniform("angle", s.angle);
        s.buffers[1].get_attachment(0).bind(0);
        s.buffers[1].get_attachment(1).bind(1);
        s.buffers[1].get_attachment(2).bind(2);

        s.quad_mesh.bind();
        s.quad_mesh.draw();
        s.quad_mesh.release();

        s.buffers[1].get_attachment(0).release();
        s.buffers[1].get_attachment(1).release();
        s.buffers[1].get_attachment(2).release();

        s.sim_pass.release();

        s.buffers[0].release();

        s.buffers[1].bind();
        if(!s.buffers[1].read_attachment(s.copy_buffer, vec4i(0, 0, s.dim, s.dim), 0)) {    // Read from 1
            LOG("Error reading framebuffer (1, 0)");
            return;
        }
        s.buffers[1].release();

        s.particle_vbuf.bind();
        s.copy_buffer.bind(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.copy_buffer(buffer_type::BT_PIXEL_UNPACK, buffer_type::BT_ARRAY, 0, 0, s.particle_count*sizeof(rgb32f_t));
        s.copy_buffer.release(buffer_type::BT_PIXEL_UNPACK);
        s.particle_vbuf.release();

        s.active_buffer = 0;
    }

    s.rndr_pass.bind();
    s.rndr_pass.bind_uniform("PVM", cam.proj_view());
    s.active_buffer == 0 ? s.buffers[1].get_attachment(2).bind(0) : s.buffers[0].get_attachment(2).bind(0);

    s.particle_mesh.bind();
    s.particle_mesh.draw();
    s.particle_mesh.release();

    s.active_buffer == 0 ? s.buffers[1].get_attachment(2).release() : s.buffers[0].get_attachment(2).release();
    s.rndr_pass.release();

    s.angle = maths::wrap(s.angle + 0.2f, float(-PI), float(PI));
}

const char* const particle_sim_vshdr = GLSL(
    in vec2 position;
    in vec2 texcoord1;

    out vec2 texcoord;

    void main() {
        texcoord = texcoord1;
        gl_Position = vec4(position.xy, 0.f, 1.f);
    }
);

const char* const particle_sim_fshdr = GLSL(
    uniform float angle;

    uniform sampler2D position_tex;
    uniform sampler2D velocity_tex;
    uniform sampler2D colour_tex;

    in vec2 texcoord;

    out vec3 frag_colour[3];

    void main() {
        vec3 vel = texture(velocity_tex, texcoord).rgb;
        vec3 pos = texture(position_tex, texcoord).rgb + .02*vel;
        bool renew = length(pos) > 3.+(length(vel));
        frag_colour[0] = renew ? vec3(0., 0., 0.) : pos;
        frag_colour[1] = .99995*vel;
        frag_colour[2] = renew ? max(dot(normalize(vel.xy), vec2(cos(angle), sin(angle))), 0.3)*vec3(1,0,0) : texture(colour_tex, texcoord).rgb;
    }
);

const char* const particle_rndr_vshdr = GLSL(
    uniform mat4 PVM;

    in vec3 position;
    flat out int vertex_id;

    void main() {
        vertex_id = gl_VertexID;
        gl_Position = PVM * vec4(position, 1.f);
    }
);

const char* const particle_rndr_fshdr = GLSL(
    uniform int dim;
    uniform sampler2D colour_tex;

    flat in int vertex_id;

    out vec4 frag_colour;

    void main() {
        frag_colour = vec4(texelFetch(colour_tex, ivec2(vertex_id%dim, vertex_id/dim), 0).rgb, 1.);
    }
);
<|endoftext|>