<commit_before>/*************************************************************************/
/* Copyright (c) 2014,2018 Linas Vepstas                                 */
/* All rights reserved                                                   */
/*                                                                       */
/* Use of the link grammar parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software.    */
/* This license allows free redistribution and use in source and binary  */
/* forms, with or without modification, subject to certain conditions.   */
/*                                                                       */
/*************************************************************************/

// This implements a very simple-minded multi-threaded unit test.
// All it does is to make sure the system doesn't crash e.g. due to
// memory allocation conflicts.

#include <thread>
#include <vector>

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include "link-grammar/link-includes.h"

static void parse_one_sent(const char *sent_str)
{
	Parse_Options opts = parse_options_create();
	dictionary_set_data_dir(DICTIONARY_DIR "/data");
	// Dictionary dict = dictionary_create_lang("ru");
	Dictionary dict = dictionary_create_lang("en");
	if (!dict) {
		fprintf (stderr, "Fatal error: Unable to open the dictionary\n");
		exit(1);
	}

	Sentence sent = sentence_create(sent_str, dict);
	if (!sent) {
		fprintf (stderr, "Fatal error: Unable to create parser\n");
		exit(2);
	}

	sentence_split(sent, opts);
	int num_linkages = sentence_parse(sent, opts);
	if (num_linkages <= 0) {
		fprintf (stderr, "Fatal error: Unable to parse sentence\n");
		exit(3);
	}

	if (2 < num_linkages) num_linkages = 2;
	for (int li = 0; li<num_linkages; li++)
	{
		Linkage linkage = linkage_create(li, sent, opts);
		linkage_delete(linkage);
	}
	sentence_delete(sent);

	dictionary_delete(dict);
	parse_options_delete(opts);
}

static void parse_sents(int thread_id, int niter)
{
	const char *sents[] = {
		"Frank felt vindicated when his long time friend Bill revealed that he was the winner of the competition.",
		"Logorrhea, or excessive and often incoherent talkativeness or wordiness, is a social disease.",
		"It was covered with bites.",
		"I have no idea what that is.",
		"His shout had been involuntary, something anybody might have done.",
		"Trump, Ryan and McConnell are using the budget process to pay for the GOP’s $1.5 trillion tax scam.",
		"We ate popcorn and watched movies on TV for three days.",
		"Sweat stood on his brow, fury was bright in his one good eye.",
		"One of the things you do when you stop your bicycle is apply the brake.",
		"The line extends 10 miles offshore."
// "под броню боевого робота устремились потоки энергии.",
// "через четверть часа здесь будет полно полицейских."
	};

	int nsents = sizeof(sents) / sizeof(const char *);

	for (int j=0; j<niter; j += nsents)
	{
		for (int i=0; i < nsents; ++i)
		{
			parse_one_sent(sents[i]);
		}
	}
}

int main(int argc, char* argv[])
{
	setlocale(LC_ALL, "en_US.UTF-8");
	dictionary_set_data_dir(DICTIONARY_DIR "/data");

	int n_threads = 10;
	int niter = 30;

	printf("Creating %d threads, each parsing %d sentences\n",
		 n_threads, niter);
	std::vector<std::thread> thread_pool;
	for (int i=0; i < n_threads; i++) {
		thread_pool.push_back(std::thread(parse_sents, i, niter));
	}

	// Wait for all threads to complete
	for (std::thread& t : thread_pool) t.join();
	printf("Done with multi-threaded parsing\n");

	return 0;
}
<commit_msg>Ooooops!<commit_after>/*************************************************************************/
/* Copyright (c) 2014,2018 Linas Vepstas                                 */
/* All rights reserved                                                   */
/*                                                                       */
/* Use of the link grammar parsing system is subject to the terms of the */
/* license set forth in the LICENSE file included with this software.    */
/* This license allows free redistribution and use in source and binary  */
/* forms, with or without modification, subject to certain conditions.   */
/*                                                                       */
/*************************************************************************/

// This implements a very simple-minded multi-threaded unit test.
// All it does is to make sure the system doesn't crash e.g. due to
// memory allocation conflicts.

#include <thread>
#include <vector>

#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include "link-grammar/link-includes.h"

static void parse_one_sent(const char *sent_str)
{
	Parse_Options opts = parse_options_create();
	// Dictionary dict = dictionary_create_lang("ru");
	Dictionary dict = dictionary_create_lang("en");
	if (!dict) {
		fprintf (stderr, "Fatal error: Unable to open the dictionary\n");
		exit(1);
	}

	Sentence sent = sentence_create(sent_str, dict);
	if (!sent) {
		fprintf (stderr, "Fatal error: Unable to create parser\n");
		exit(2);
	}

	sentence_split(sent, opts);
	int num_linkages = sentence_parse(sent, opts);
	if (num_linkages <= 0) {
		fprintf (stderr, "Fatal error: Unable to parse sentence\n");
		exit(3);
	}

	if (2 < num_linkages) num_linkages = 2;
	for (int li = 0; li<num_linkages; li++)
	{
		Linkage linkage = linkage_create(li, sent, opts);
		linkage_delete(linkage);
	}
	sentence_delete(sent);

	dictionary_delete(dict);
	parse_options_delete(opts);
}

static void parse_sents(int thread_id, int niter)
{
	const char *sents[] = {
		"Frank felt vindicated when his long time friend Bill revealed that he was the winner of the competition.",
		"Logorrhea, or excessive and often incoherent talkativeness or wordiness, is a social disease.",
		"It was covered with bites.",
		"I have no idea what that is.",
		"His shout had been involuntary, something anybody might have done.",
		"Trump, Ryan and McConnell are using the budget process to pay for the GOP’s $1.5 trillion tax scam.",
		"We ate popcorn and watched movies on TV for three days.",
		"Sweat stood on his brow, fury was bright in his one good eye.",
		"One of the things you do when you stop your bicycle is apply the brake.",
		"The line extends 10 miles offshore."
// "под броню боевого робота устремились потоки энергии.",
// "через четверть часа здесь будет полно полицейских."
	};

	int nsents = sizeof(sents) / sizeof(const char *);

	for (int j=0; j<niter; j += nsents)
	{
		for (int i=0; i < nsents; ++i)
		{
			parse_one_sent(sents[i]);
		}
	}
}

int main(int argc, char* argv[])
{
	setlocale(LC_ALL, "en_US.UTF-8");
	dictionary_set_data_dir(DICTIONARY_DIR "/data");

	int n_threads = 10;
	int niter = 30;

	printf("Creating %d threads, each parsing %d sentences\n",
		 n_threads, niter);
	std::vector<std::thread> thread_pool;
	for (int i=0; i < n_threads; i++) {
		thread_pool.push_back(std::thread(parse_sents, i, niter));
	}

	// Wait for all threads to complete
	for (std::thread& t : thread_pool) t.join();
	printf("Done with multi-threaded parsing\n");

	return 0;
}
<|endoftext|>


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

#ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_
#define _XMLOFF_FORMS_OFFICEFORMS_HXX_

#ifndef _XMLOFF_FORMATTRIBUTES_HXX_
#include "formattributes.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif
#ifndef XMLOFF_FORMS_LOGGING_HXX
#include "logging.hxx"
#endif

class SvXMLElementExport;
class SvXMLExport;

//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OFormsRootImport
    //=====================================================================
    class OFormsRootImport
                :public SvXMLImportContext
                ,public OStackedLogging
    {
    public:
        TYPEINFO();

        OFormsRootImport( SvXMLImport& _rImport, sal_uInt16 _nPrfx, const rtl::OUString& _rLocalName);
        virtual ~OFormsRootImport();

        // SvXMLImportContext overriabled
        virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
            const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
        virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList );
        virtual void EndElement();

    protected:
        void implImportBool(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttributes,
            OfficeFormsAttributes _eAttribute,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo,
            const ::rtl::OUString& _rPropName,
            sal_Bool _bDefault
            );
    };

    //=====================================================================
    //= OFormsRootExport
    //=====================================================================
    class OFormsRootExport
    {
    private:
        SvXMLElementExport*     m_pImplElement;

    public:
        OFormsRootExport( SvXMLExport& _rExp );
        ~OFormsRootExport();

    private:
        void addModelAttributes(SvXMLExport& _rExp) SAL_THROW(());

        void implExportBool(
            SvXMLExport& _rExp,
            OfficeFormsAttributes _eAttribute,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo,
            const ::rtl::OUString& _rPropName,
            sal_Bool _bDefault
            );
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_OFFICEFORMS_HXX_

<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.274); FILE MERGED 2007/06/04 13:23:27 vg 1.5.274.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: officeforms.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:17:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_
#define _XMLOFF_FORMS_OFFICEFORMS_HXX_

#ifndef _XMLOFF_FORMATTRIBUTES_HXX_
#include "formattributes.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef XMLOFF_FORMS_LOGGING_HXX
#include "logging.hxx"
#endif

class SvXMLElementExport;
class SvXMLExport;

//.........................................................................
namespace xmloff
{
//.........................................................................

    //=====================================================================
    //= OFormsRootImport
    //=====================================================================
    class OFormsRootImport
                :public SvXMLImportContext
                ,public OStackedLogging
    {
    public:
        TYPEINFO();

        OFormsRootImport( SvXMLImport& _rImport, sal_uInt16 _nPrfx, const rtl::OUString& _rLocalName);
        virtual ~OFormsRootImport();

        // SvXMLImportContext overriabled
        virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,
            const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
        virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList );
        virtual void EndElement();

    protected:
        void implImportBool(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttributes,
            OfficeFormsAttributes _eAttribute,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo,
            const ::rtl::OUString& _rPropName,
            sal_Bool _bDefault
            );
    };

    //=====================================================================
    //= OFormsRootExport
    //=====================================================================
    class OFormsRootExport
    {
    private:
        SvXMLElementExport*     m_pImplElement;

    public:
        OFormsRootExport( SvXMLExport& _rExp );
        ~OFormsRootExport();

    private:
        void addModelAttributes(SvXMLExport& _rExp) SAL_THROW(());

        void implExportBool(
            SvXMLExport& _rExp,
            OfficeFormsAttributes _eAttribute,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps,
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo >& _rxPropInfo,
            const ::rtl::OUString& _rPropName,
            sal_Bool _bDefault
            );
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_OFFICEFORMS_HXX_

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

// Software Guide : BeginLatex
//
// This example illustrates how to perform Iterative Closest Point (ICP)
// registration in ITK using sets of 3D points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkEuler3DTransform.h"
#include "itkEuclideanDistancePointMetric.h"
#include "itkLevenbergMarquardtOptimizer.h"
#include "itkPointSetToPointSetRegistrationMethod.h"
// Software Guide : EndCodeSnippet

#include <fstream>

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

  if( argc < 3 )
    {
    std::cerr << "Arguments Missing. " << std::endl;
    std::cerr <<
      "Usage:  IterativeClosestPoint2   fixedPointsFile  movingPointsFile "
      << std::endl;
    return 1;
    }

// Software Guide : BeginCodeSnippet
  const unsigned int Dimension = 3;

  typedef itk::PointSet< float, Dimension >   PointSetType;

  PointSetType::Pointer fixedPointSet  = PointSetType::New();
  PointSetType::Pointer movingPointSet = PointSetType::New();

  typedef PointSetType::PointType     PointType;

  typedef PointSetType::PointsContainer  PointsContainer;

  PointsContainer::Pointer fixedPointContainer  = PointsContainer::New();
  PointsContainer::Pointer movingPointContainer = PointsContainer::New();

  PointType fixedPoint;
  PointType movingPoint;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Read the file containing coordinates of fixed points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  std::ifstream   fixedFile;
  fixedFile.open( argv[1] );
  if( fixedFile.fail() )
    {
    std::cerr << "Error opening points file with name : " << std::endl;
    std::cerr << argv[1] << std::endl;
    return 2;
    }

  unsigned int pointId = 0;
  fixedFile >> fixedPoint;
  while( !fixedFile.eof() )
    {
    fixedPointContainer->InsertElement( pointId, fixedPoint );
    fixedFile >> fixedPoint;
    pointId++;
    }
  fixedPointSet->SetPoints( fixedPointContainer );
  std::cout <<
    "Number of fixed Points = " <<
    fixedPointSet->GetNumberOfPoints() << std::endl;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Read the file containing coordinates of moving points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  std::ifstream   movingFile;
  movingFile.open( argv[2] );
  if( movingFile.fail() )
    {
    std::cerr << "Error opening points file with name : " << std::endl;
    std::cerr << argv[2] << std::endl;
    return 2;
    }

  pointId = 0;
  movingFile >> movingPoint;
  while( !movingFile.eof() )
    {
    movingPointContainer->InsertElement( pointId, movingPoint );
    movingFile >> movingPoint;
    pointId++;
    }
  movingPointSet->SetPoints( movingPointContainer );
  std::cout << "Number of moving Points = "
    << movingPointSet->GetNumberOfPoints() << std::endl;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up the Metric.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::EuclideanDistancePointMetric<
                                    PointSetType,
                                    PointSetType>
                                                    MetricType;

  MetricType::Pointer  metric = MetricType::New();
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up a Transform.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::TranslationTransform< double, Dimension >      TransformType;

  TransformType::Pointer transform = TransformType::New();
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up a the Optimizer and RegistrationMethod.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::LevenbergMarquardtOptimizer OptimizerType;

  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  optimizer->SetUseCostFunctionGradient(false);

  typedef itk::PointSetToPointSetRegistrationMethod<
                                            PointSetType,
                                            PointSetType >
                                                    RegistrationType;

  RegistrationType::Pointer   registration  = RegistrationType::New();

  // Scale the translation components of the Transform in the Optimizer
  OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );

  const double translationScale = 1000.0;   // dynamic range of translations
  const double rotationScale    =    1.0;   // dynamic range of rotations

  scales[0] = 1.0 / rotationScale;
  scales[1] = 1.0 / rotationScale;
  scales[2] = 1.0 / rotationScale;
  scales[3] = 1.0 / translationScale;
  scales[4] = 1.0 / translationScale;
  scales[5] = 1.0 / translationScale;

  unsigned long   numberOfIterations =  2000;
  double          gradientTolerance  =  1e-4;   // convergence criterion
  double          valueTolerance     =  1e-4;   // convergence criterion
  double          epsilonFunction    =  1e-5;   // convergence criterion

  optimizer->SetScales( scales );
  optimizer->SetNumberOfIterations( numberOfIterations );
  optimizer->SetValueTolerance( valueTolerance );
  optimizer->SetGradientTolerance( gradientTolerance );
  optimizer->SetEpsilonFunction( epsilonFunction );

  // Start from an Identity transform (in a normal case, the user
  // can probably provide a better guess than the identity...
  transform->SetIdentity();

  registration->SetInitialTransformParameters( transform->GetParameters() );
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Connect all the components required for Registration
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  registration->SetMetric(        metric        );
  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetFixedPointSet( fixedPointSet );
  registration->SetMovingPointSet(   movingPointSet   );

  try
    {
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << e << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Solution = " << transform->GetParameters() << std::endl;
// Software Guide : EndCodeSnippet

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Fix transform type for ITKv3/IterativeClosestPoint2.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

// Software Guide : BeginLatex
//
// This example illustrates how to perform Iterative Closest Point (ICP)
// registration in ITK using sets of 3D points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkTranslationTransform.h"
#include "itkEuclideanDistancePointMetric.h"
#include "itkLevenbergMarquardtOptimizer.h"
#include "itkPointSetToPointSetRegistrationMethod.h"
// Software Guide : EndCodeSnippet

#include <fstream>

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

  if( argc < 3 )
    {
    std::cerr << "Arguments Missing. " << std::endl;
    std::cerr <<
      "Usage:  IterativeClosestPoint2   fixedPointsFile  movingPointsFile "
      << std::endl;
    return 1;
    }

// Software Guide : BeginCodeSnippet
  const unsigned int Dimension = 3;

  typedef itk::PointSet< float, Dimension >   PointSetType;

  PointSetType::Pointer fixedPointSet  = PointSetType::New();
  PointSetType::Pointer movingPointSet = PointSetType::New();

  typedef PointSetType::PointType     PointType;

  typedef PointSetType::PointsContainer  PointsContainer;

  PointsContainer::Pointer fixedPointContainer  = PointsContainer::New();
  PointsContainer::Pointer movingPointContainer = PointsContainer::New();

  PointType fixedPoint;
  PointType movingPoint;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Read the file containing coordinates of fixed points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  std::ifstream   fixedFile;
  fixedFile.open( argv[1] );
  if( fixedFile.fail() )
    {
    std::cerr << "Error opening points file with name : " << std::endl;
    std::cerr << argv[1] << std::endl;
    return 2;
    }

  unsigned int pointId = 0;
  fixedFile >> fixedPoint;
  while( !fixedFile.eof() )
    {
    fixedPointContainer->InsertElement( pointId, fixedPoint );
    fixedFile >> fixedPoint;
    pointId++;
    }
  fixedPointSet->SetPoints( fixedPointContainer );
  std::cout <<
    "Number of fixed Points = " <<
    fixedPointSet->GetNumberOfPoints() << std::endl;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Read the file containing coordinates of moving points.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  std::ifstream   movingFile;
  movingFile.open( argv[2] );
  if( movingFile.fail() )
    {
    std::cerr << "Error opening points file with name : " << std::endl;
    std::cerr << argv[2] << std::endl;
    return 2;
    }

  pointId = 0;
  movingFile >> movingPoint;
  while( !movingFile.eof() )
    {
    movingPointContainer->InsertElement( pointId, movingPoint );
    movingFile >> movingPoint;
    pointId++;
    }
  movingPointSet->SetPoints( movingPointContainer );
  std::cout << "Number of moving Points = "
    << movingPointSet->GetNumberOfPoints() << std::endl;
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up the Metric.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::EuclideanDistancePointMetric<
                                    PointSetType,
                                    PointSetType>
                                                    MetricType;

  MetricType::Pointer  metric = MetricType::New();
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up a Transform.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::TranslationTransform< double, Dimension >      TransformType;

  TransformType::Pointer transform = TransformType::New();
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Set up a the Optimizer and RegistrationMethod.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  typedef itk::LevenbergMarquardtOptimizer OptimizerType;

  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  optimizer->SetUseCostFunctionGradient(false);

  typedef itk::PointSetToPointSetRegistrationMethod<
                                            PointSetType,
                                            PointSetType >
                                                    RegistrationType;

  RegistrationType::Pointer   registration  = RegistrationType::New();

  // Scale the translation components of the Transform in the Optimizer
  OptimizerType::ScalesType scales( transform->GetNumberOfParameters() );

  const double translationScale = 1000.0;   // dynamic range of translations
  const double rotationScale    =    1.0;   // dynamic range of rotations

  scales[0] = 1.0 / rotationScale;
  scales[1] = 1.0 / rotationScale;
  scales[2] = 1.0 / rotationScale;
  scales[3] = 1.0 / translationScale;
  scales[4] = 1.0 / translationScale;
  scales[5] = 1.0 / translationScale;

  unsigned long   numberOfIterations =  2000;
  double          gradientTolerance  =  1e-4;   // convergence criterion
  double          valueTolerance     =  1e-4;   // convergence criterion
  double          epsilonFunction    =  1e-5;   // convergence criterion

  optimizer->SetScales( scales );
  optimizer->SetNumberOfIterations( numberOfIterations );
  optimizer->SetValueTolerance( valueTolerance );
  optimizer->SetGradientTolerance( gradientTolerance );
  optimizer->SetEpsilonFunction( epsilonFunction );

  // Start from an Identity transform (in a normal case, the user
  // can probably provide a better guess than the identity...
  transform->SetIdentity();

  registration->SetInitialTransformParameters( transform->GetParameters() );
// Software Guide : EndCodeSnippet

// Software Guide : BeginLatex
//
// Connect all the components required for Registration
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
  registration->SetMetric(        metric        );
  registration->SetOptimizer(     optimizer     );
  registration->SetTransform(     transform     );
  registration->SetFixedPointSet( fixedPointSet );
  registration->SetMovingPointSet(   movingPointSet   );

  try
    {
    registration->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cout << e << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Solution = " << transform->GetParameters() << std::endl;
// Software Guide : EndCodeSnippet

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * 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.
 */

/***************************************************************************
 * Shader for model loaded with Assimp
 ***************************************************************************/

#include "assimp_shader.h"

#include "gl/gl_program.h"
#include "objects/material.h"
#include "objects/mesh.h"
#include "objects/components/render_data.h"
#include "objects/textures/texture.h"
#include "util/gvr_gl.h"

#include "util/gvr_log.h"

namespace gvr {

#define AS_TOTAL_SHADER_STRINGS_COUNT    AS_TOTAL_FEATURE_COUNT + 1

static const char DIFFUSE_TEXTURE[] = "#define AS_DIFFUSE_TEXTURE\n";
static const char NO_DIFFUSE_TEXTURE[] = "#undef AS_DIFFUSE_TEXTURE\n";

static const char SPECULAR_TEXTURE[] = "#define AS_SPECULAR_TEXTURE\n";
static const char NO_SPECULAR_TEXTURE[] = "#undef AS_SPECULAR_TEXTURE\n";

static const char VERTEX_SHADER[] =
        "attribute vec4 a_position;\n"
                "uniform mat4 u_mvp;\n"
                "\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "attribute vec4 a_tex_coord;\n"
                "varying vec2 v_tex_coord;\n"
                "#endif\n"
                "\n"
                "void main() {\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "  v_tex_coord = a_tex_coord.xy;\n"
                "#endif\n"
                "  gl_Position = u_mvp * a_position;\n"
                "}\n";

static const char FRAGMENT_SHADER[] =
        "precision highp float;\n"
                "\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "varying vec2 v_tex_coord;\n"
                "uniform sampler2D u_texture;\n"
                "#else\n"
                "uniform vec4 u_diffuse_color;\n"
                "uniform vec4 u_ambient_color;\n"
                "#endif\n"
                "\n"
                "uniform vec3 u_color;\n"
                "uniform float u_opacity;\n"
                "\n"
                "void main()\n"
                "{\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "  vec4 color;\n"
                "  color = texture2D(u_texture, v_tex_coord);\n"
                "  gl_FragColor = vec4(color.r * u_color.r * u_opacity, color.g * u_color.g * u_opacity, color.b * u_color.b * u_opacity, color.a * u_opacity);\n"
                "#else\n"
                "  gl_FragColor = (u_diffuse_color * u_opacity) + u_ambient_color;\n"
                "#endif\n"
                "}\n";

AssimpShader::AssimpShader() :
        program_(0), a_position_(0), u_mvp_(0), a_tex_coord_(0), u_diffuse_color_(
                0), u_ambient_color_(0), u_texture_(0), u_color_(0), u_opacity_(
                0) {
    program_list_ = new GLProgram*[AS_TOTAL_GL_PROGRAM_COUNT];

    const char* vertex_shader_strings[AS_TOTAL_SHADER_STRINGS_COUNT];
    GLint vertex_shader_string_lengths[AS_TOTAL_SHADER_STRINGS_COUNT];
    const char* fragment_shader_strings[AS_TOTAL_SHADER_STRINGS_COUNT];
    GLint fragment_shader_string_lengths[AS_TOTAL_SHADER_STRINGS_COUNT];

    for (int i = 0; i < AS_TOTAL_GL_PROGRAM_COUNT; i++) {
        int counter = 0;

        // TODO: remove duplicate code
        if (ISSET(i, AS_DIFFUSE_TEXTURE)) {
            vertex_shader_strings[counter] =  DIFFUSE_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(DIFFUSE_TEXTURE);
            fragment_shader_strings[counter] = DIFFUSE_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(DIFFUSE_TEXTURE);
            counter++;
        } else {
            vertex_shader_strings[counter] =  NO_DIFFUSE_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(NO_DIFFUSE_TEXTURE);
            fragment_shader_strings[counter] = NO_DIFFUSE_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(NO_DIFFUSE_TEXTURE);
            counter++;
        }

        if (ISSET(i, AS_SPECULAR_TEXTURE)) {
            vertex_shader_strings[counter] =  SPECULAR_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(SPECULAR_TEXTURE);
            fragment_shader_strings[counter] = SPECULAR_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(SPECULAR_TEXTURE);
            counter++;
        } else {
            vertex_shader_strings[counter] =  NO_SPECULAR_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(NO_SPECULAR_TEXTURE);
            fragment_shader_strings[counter] = NO_SPECULAR_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(NO_SPECULAR_TEXTURE);
            counter++;
        }

        /* Shader should be added in the last */
        vertex_shader_strings[counter] = VERTEX_SHADER;
        vertex_shader_string_lengths[counter] = (GLint) strlen(VERTEX_SHADER);
        fragment_shader_strings[counter] = FRAGMENT_SHADER;
        fragment_shader_string_lengths[counter] = (GLint) strlen(FRAGMENT_SHADER);
        counter++;

        program_list_[i] = new GLProgram(vertex_shader_strings,
                    vertex_shader_string_lengths, fragment_shader_strings,
                    fragment_shader_string_lengths, counter);
    }
}

AssimpShader::~AssimpShader() {
    if (program_list_ != 0) {
        recycle();
    }
}

void AssimpShader::recycle() {
    if (program_list_ != 0) {
        for (int i = 0; i < AS_TOTAL_GL_PROGRAM_COUNT; i++) {
            if (program_list_[i] != 0) {
                delete program_list_[i];
            }
        }
        delete program_list_;
        program_list_ = 0;
        program_ = 0;
    }
}

void AssimpShader::render(const glm::mat4& mv_matrix,
        const glm::mat4& mv_it_matrix, const glm::mat4& mvp_matrix,
        RenderData* render_data, Material* material) {
    Mesh* mesh = render_data->mesh();
    Texture* texture;
    int feature_set = material->get_shader_feature_set();

    /* Get the texture only diffuese texture is set */
    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        texture = material->getTexture("main_texture");
        if (texture->getTarget() != GL_TEXTURE_2D) {
            std::string error =
                    "TextureShader::render : texture with wrong target.";
            throw error;
        }
    }

    /* Based on feature set get the shader program */
    program_ = program_list_[feature_set];

    a_position_ = glGetAttribLocation(program_->id(), "a_position");
    u_mvp_ = glGetUniformLocation(program_->id(), "u_mvp");
    a_tex_coord_ = glGetAttribLocation(program_->id(), "a_tex_coord");
    u_texture_ = glGetUniformLocation(program_->id(), "u_texture");
    u_diffuse_color_ = glGetUniformLocation(program_->id(), "u_diffuse_color");
    u_ambient_color_ = glGetUniformLocation(program_->id(), "u_ambient_color");
    u_color_ = glGetUniformLocation(program_->id(), "u_color");
    u_opacity_ = glGetUniformLocation(program_->id(), "u_opacity");

    /* Get common attributes and uniforms from material */
    glm::vec3 color = material->getVec3("color");
    float opacity = material->getFloat("opacity");

#if _GVRF_USE_GLES3_
    mesh->setVertexLoc(a_position_);
    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        mesh->setTexCoordLoc(a_tex_coord_);
    }
    mesh->generateVAO(Material::ASSIMP_SHADER);

    glUseProgram(program_->id());
    glUniformMatrix4fv(u_mvp_, 1, GL_FALSE, glm::value_ptr(mvp_matrix));

    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        glActiveTexture (GL_TEXTURE0);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(u_texture_, 0);
    } else {
        glm::vec4 diffuse_color = material->getVec4("diffuse_color");
        glm::vec4 ambient_color = material->getVec4("ambient_color");
        glUniform4f(u_diffuse_color_, diffuse_color.r, diffuse_color.g,
                diffuse_color.b, diffuse_color.a);
        glUniform4f(u_ambient_color_, ambient_color.r, ambient_color.g,
                ambient_color.b, ambient_color.a);
    }
    glUniform3f(u_color_, color.r, color.g, color.b);
    glUniform1f(u_opacity_, opacity);

    glBindVertexArray(mesh->getVAOId(Material::ASSIMP_SHADER));
    glDrawElements(GL_TRIANGLES, mesh->triangles().size(), GL_UNSIGNED_SHORT,
            0);
    glBindVertexArray(0);
#else
    glUseProgram(program_->id());

    glVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0,
            mesh->vertices().data());
    glEnableVertexAttribArray(a_position_);

    glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, GL_FALSE, 0,
            mesh->tex_coords().data());
    glEnableVertexAttribArray(a_tex_coord_);

    glUniformMatrix4fv(u_mvp_, 1, GL_FALSE, glm::value_ptr(mvp_matrix));

    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        glActiveTexture (GL_TEXTURE0);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(u_texture_, 0);
    } else {
        glm::vec4 diffuse_color = material->getVec4("diffuse_color");
        glm::vec4 ambient_color = material->getVec4("ambient_color");
        glUniform4f(u_diffuse_color_, diffuse_color.x, diffuse_color.y, diffuse_color.z, diffuse_color.w);
        glUniform4f(u_ambient_color_, ambient_color.x, ambient_color.y, ambient_color.z, ambient_color.w);
    }

    glUniform3f(u_color_, color.r, color.g, color.b);
    glUniform1f(u_opacity_, opacity);

    glDrawElements(GL_TRIANGLES, mesh->triangles().size(), GL_UNSIGNED_SHORT,
            mesh->triangles().data());
#endif

    checkGlError("AssimpShader::render");
}

}
;
<commit_msg>check that feature set don't exceed program count<commit_after>/* Copyright 2015 Samsung Electronics Co., LTD
 *
 * 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.
 */

/***************************************************************************
 * Shader for model loaded with Assimp
 ***************************************************************************/

#include "assimp_shader.h"

#include "gl/gl_program.h"
#include "objects/material.h"
#include "objects/mesh.h"
#include "objects/components/render_data.h"
#include "objects/textures/texture.h"
#include "util/gvr_gl.h"

#include "util/gvr_log.h"

namespace gvr {

#define AS_TOTAL_SHADER_STRINGS_COUNT    AS_TOTAL_FEATURE_COUNT + 1

static const char DIFFUSE_TEXTURE[] = "#define AS_DIFFUSE_TEXTURE\n";
static const char NO_DIFFUSE_TEXTURE[] = "#undef AS_DIFFUSE_TEXTURE\n";

static const char SPECULAR_TEXTURE[] = "#define AS_SPECULAR_TEXTURE\n";
static const char NO_SPECULAR_TEXTURE[] = "#undef AS_SPECULAR_TEXTURE\n";

static const char VERTEX_SHADER[] =
        "attribute vec4 a_position;\n"
                "uniform mat4 u_mvp;\n"
                "\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "attribute vec4 a_tex_coord;\n"
                "varying vec2 v_tex_coord;\n"
                "#endif\n"
                "\n"
                "void main() {\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "  v_tex_coord = a_tex_coord.xy;\n"
                "#endif\n"
                "  gl_Position = u_mvp * a_position;\n"
                "}\n";

static const char FRAGMENT_SHADER[] =
        "precision highp float;\n"
                "\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "varying vec2 v_tex_coord;\n"
                "uniform sampler2D u_texture;\n"
                "#else\n"
                "uniform vec4 u_diffuse_color;\n"
                "uniform vec4 u_ambient_color;\n"
                "#endif\n"
                "\n"
                "uniform vec3 u_color;\n"
                "uniform float u_opacity;\n"
                "\n"
                "void main()\n"
                "{\n"
                "#ifdef AS_DIFFUSE_TEXTURE\n"
                "  vec4 color;\n"
                "  color = texture2D(u_texture, v_tex_coord);\n"
                "  gl_FragColor = vec4(color.r * u_color.r * u_opacity, color.g * u_color.g * u_opacity, color.b * u_color.b * u_opacity, color.a * u_opacity);\n"
                "#else\n"
                "  gl_FragColor = (u_diffuse_color * u_opacity) + u_ambient_color;\n"
                "#endif\n"
                "}\n";

AssimpShader::AssimpShader() :
        program_(0), a_position_(0), u_mvp_(0), a_tex_coord_(0), u_diffuse_color_(
                0), u_ambient_color_(0), u_texture_(0), u_color_(0), u_opacity_(
                0) {
    program_list_ = new GLProgram*[AS_TOTAL_GL_PROGRAM_COUNT];

    const char* vertex_shader_strings[AS_TOTAL_SHADER_STRINGS_COUNT];
    GLint vertex_shader_string_lengths[AS_TOTAL_SHADER_STRINGS_COUNT];
    const char* fragment_shader_strings[AS_TOTAL_SHADER_STRINGS_COUNT];
    GLint fragment_shader_string_lengths[AS_TOTAL_SHADER_STRINGS_COUNT];

    for (int i = 0; i < AS_TOTAL_GL_PROGRAM_COUNT; i++) {
        int counter = 0;

        // TODO: remove duplicate code
        if (ISSET(i, AS_DIFFUSE_TEXTURE)) {
            vertex_shader_strings[counter] =  DIFFUSE_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(DIFFUSE_TEXTURE);
            fragment_shader_strings[counter] = DIFFUSE_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(DIFFUSE_TEXTURE);
            counter++;
        } else {
            vertex_shader_strings[counter] =  NO_DIFFUSE_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(NO_DIFFUSE_TEXTURE);
            fragment_shader_strings[counter] = NO_DIFFUSE_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(NO_DIFFUSE_TEXTURE);
            counter++;
        }

        if (ISSET(i, AS_SPECULAR_TEXTURE)) {
            vertex_shader_strings[counter] =  SPECULAR_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(SPECULAR_TEXTURE);
            fragment_shader_strings[counter] = SPECULAR_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(SPECULAR_TEXTURE);
            counter++;
        } else {
            vertex_shader_strings[counter] =  NO_SPECULAR_TEXTURE;
            vertex_shader_string_lengths[counter] = (GLint) strlen(NO_SPECULAR_TEXTURE);
            fragment_shader_strings[counter] = NO_SPECULAR_TEXTURE;
            fragment_shader_string_lengths[counter] = (GLint) strlen(NO_SPECULAR_TEXTURE);
            counter++;
        }

        /* Shader should be added in the last */
        vertex_shader_strings[counter] = VERTEX_SHADER;
        vertex_shader_string_lengths[counter] = (GLint) strlen(VERTEX_SHADER);
        fragment_shader_strings[counter] = FRAGMENT_SHADER;
        fragment_shader_string_lengths[counter] = (GLint) strlen(FRAGMENT_SHADER);
        counter++;

        program_list_[i] = new GLProgram(vertex_shader_strings,
                    vertex_shader_string_lengths, fragment_shader_strings,
                    fragment_shader_string_lengths, counter);
    }
}

AssimpShader::~AssimpShader() {
    if (program_list_ != 0) {
        recycle();
    }
}

void AssimpShader::recycle() {
    if (program_list_ != 0) {
        for (int i = 0; i < AS_TOTAL_GL_PROGRAM_COUNT; i++) {
            if (program_list_[i] != 0) {
                delete program_list_[i];
            }
        }
        delete program_list_;
        program_list_ = 0;
        program_ = 0;
    }
}

void AssimpShader::render(const glm::mat4& mv_matrix,
        const glm::mat4& mv_it_matrix, const glm::mat4& mvp_matrix,
        RenderData* render_data, Material* material) {
    Mesh* mesh = render_data->mesh();
    Texture* texture;
    int feature_set = material->get_shader_feature_set();

    /* Get the texture only diffuse texture is set */
    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        texture = material->getTexture("main_texture");
        if (texture->getTarget() != GL_TEXTURE_2D) {
            std::string error =
                    "TextureShader::render : texture with wrong target.";
            throw error;
        }
    }

    /* Based on feature set get the shader program, feature set cannot exceed program count */
    program_ = program_list_[feature_set & (AS_TOTAL_GL_PROGRAM_COUNT - 1)];

    a_position_ = glGetAttribLocation(program_->id(), "a_position");
    u_mvp_ = glGetUniformLocation(program_->id(), "u_mvp");
    a_tex_coord_ = glGetAttribLocation(program_->id(), "a_tex_coord");
    u_texture_ = glGetUniformLocation(program_->id(), "u_texture");
    u_diffuse_color_ = glGetUniformLocation(program_->id(), "u_diffuse_color");
    u_ambient_color_ = glGetUniformLocation(program_->id(), "u_ambient_color");
    u_color_ = glGetUniformLocation(program_->id(), "u_color");
    u_opacity_ = glGetUniformLocation(program_->id(), "u_opacity");

    /* Get common attributes and uniforms from material */
    glm::vec3 color = material->getVec3("color");
    float opacity = material->getFloat("opacity");

#if _GVRF_USE_GLES3_
    mesh->setVertexLoc(a_position_);
    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        mesh->setTexCoordLoc(a_tex_coord_);
    }
    mesh->generateVAO(Material::ASSIMP_SHADER);

    glUseProgram(program_->id());
    glUniformMatrix4fv(u_mvp_, 1, GL_FALSE, glm::value_ptr(mvp_matrix));

    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        glActiveTexture (GL_TEXTURE0);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(u_texture_, 0);
    } else {
        glm::vec4 diffuse_color = material->getVec4("diffuse_color");
        glm::vec4 ambient_color = material->getVec4("ambient_color");
        glUniform4f(u_diffuse_color_, diffuse_color.r, diffuse_color.g,
                diffuse_color.b, diffuse_color.a);
        glUniform4f(u_ambient_color_, ambient_color.r, ambient_color.g,
                ambient_color.b, ambient_color.a);
    }
    glUniform3f(u_color_, color.r, color.g, color.b);
    glUniform1f(u_opacity_, opacity);

    glBindVertexArray(mesh->getVAOId(Material::ASSIMP_SHADER));
    glDrawElements(GL_TRIANGLES, mesh->triangles().size(), GL_UNSIGNED_SHORT,
            0);
    glBindVertexArray(0);
#else
    glUseProgram(program_->id());

    glVertexAttribPointer(a_position_, 3, GL_FLOAT, GL_FALSE, 0,
            mesh->vertices().data());
    glEnableVertexAttribArray(a_position_);

    glVertexAttribPointer(a_tex_coord_, 2, GL_FLOAT, GL_FALSE, 0,
            mesh->tex_coords().data());
    glEnableVertexAttribArray(a_tex_coord_);

    glUniformMatrix4fv(u_mvp_, 1, GL_FALSE, glm::value_ptr(mvp_matrix));

    if (ISSET(feature_set, AS_DIFFUSE_TEXTURE)) {
        glActiveTexture (GL_TEXTURE0);
        glBindTexture(texture->getTarget(), texture->getId());
        glUniform1i(u_texture_, 0);
    } else {
        glm::vec4 diffuse_color = material->getVec4("diffuse_color");
        glm::vec4 ambient_color = material->getVec4("ambient_color");
        glUniform4f(u_diffuse_color_, diffuse_color.x, diffuse_color.y, diffuse_color.z, diffuse_color.w);
        glUniform4f(u_ambient_color_, ambient_color.x, ambient_color.y, ambient_color.z, ambient_color.w);
    }

    glUniform3f(u_color_, color.r, color.g, color.b);
    glUniform1f(u_opacity_, opacity);

    glDrawElements(GL_TRIANGLES, mesh->triangles().size(), GL_UNSIGNED_SHORT,
            mesh->triangles().data());
#endif

    checkGlError("AssimpShader::render");
}

}
;
<|endoftext|>


<commit_before>#include <Systems/CameraSystem.hh>
#include <Utils/MatrixConversion.hpp>
#include <Context/IRenderContext.hh>
#include <Utils/ScreenPosToWorldRay.hpp>
#include <Core/Renderer.hh>
#include <Components/MeshRenderer.hh>
#include <Components/CameraComponent.hpp>
#include <Core/SceneManager.hh>
#include <OpenGL/ShadingManager.hh>
#include <OpenGL/GeometryManager.hh>
#include <Core/Drawable.hh>
#include <Core/AssetsManager.hpp>

//tmp
#include <Core/Octree.hpp>

# define VERTEX_SHADER "../../Shaders/test_pipeline_1.vp"
# define FRAG_SHADER "../../Shaders/test_pipeline_1.fp"

CameraSystem::CameraSystem(std::weak_ptr<AScene> &&scene)
	: System(std::move(scene)),
#if NEW_SHADER
	_render(NULL),
#endif
	_renderDebugMethod(false),
	_totalTime(0),
#if NEW_SHADER
	_camera(std::move(scene)),
	_drawable(std::move(scene))
#else
	_filter(std::move(scene))
#endif
{
	_name = "camera_system";
}

void CameraSystem::setRenderDebugMode(bool t)
{
	_renderDebugMethod = t;
}

bool CameraSystem::getRenderDebugMode() const
{
	return _renderDebugMethod;
}

void CameraSystem::getRayFromMousePosOnScreen(glm::vec3 &from, glm::vec3 &to)
{
#if NEW_SHADER
	if (_camera.getCollection().size() == 0)
		return;
#else
	if (_filter.getCollection().size() == 0)
		return;
#endif
	auto scene = _scene.lock();
	auto mousePos = scene->getInstance<Input>()->getMousePosition();
	auto screenSize = scene->getInstance<IRenderContext>()->getScreenSize();
#if NEW_SHADER
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_camera.getCollection().begin()));
#else
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_filter.getCollection().begin()));
#endif
	// TODO
	//screenPosToWorldRay(mousePos.x, mousePos.y, screenSize.x, screenSize.y, cameraCpt->lookAtTransform, cameraCpt->projection, from, to);
}

void CameraSystem::getRayFromCenterOfScreen(glm::vec3 &from, glm::vec3 &to)
{
#if NEW_SHADER
	if (_camera.getCollection().size() == 0)
		return;
#else
	if (_filter.getCollection().size() == 0)
		return;
#endif
	auto scene = _scene.lock();
	auto screenSize = scene->getInstance<IRenderContext>()->getScreenSize();
	auto centerPos = glm::vec2(screenSize) * glm::vec2(0.5f);
#if NEW_SHADER
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_camera.getCollection().begin()));
#else
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_filter.getCollection().begin()));
#endif
	//TODO
	//screenPosToWorldRay(
	//	static_cast<int>(centerPos.x),
	//	static_cast<int>(centerPos.y),
	//	static_cast<int>(screenSize.x),
	//	static_cast<int>(screenSize.y),
	//	cameraCpt->lookAtTransform,
	//	cameraCpt->projection,
	//	from,
	//	to);
}

#if NEW_SHADER

void CameraSystem::setManager(gl::ShadingManager &m)
{
	_render = &m;

	if (_render == NULL)
		std::cerr << "Warning: No manager set for the camerasystem" << std::endl;

	_shader = _render->addShader(VERTEX_SHADER, FRAG_SHADER);
	size_t sizeElement[2];
	gl::set_tab_sizetype<glm::mat4, glm::vec4>(sizeElement);
	_global_state = _render->addUniformBlock(2, sizeElement);
	_render->addShaderInterfaceBlock(_shader, "global_state", _global_state);
	_render->setUniformBlock(_global_state, 1, glm::vec4(0.0f, 8.0f, 0.0f, 1.0f));
	_model_matrix = _render->addShaderUniform(_shader, "model_matrix", glm::mat4(1.f));
	_view_matrix = _render->addShaderUniform(_shader, "view_matrix", glm::mat4(1.f));
	_normal_matrix = _render->addShaderUniform(_shader, "normal_matrix", glm::mat3(1.f));
	_diffuse_texture = _render->addShaderSampler(_shader, "diffuse_texture");
	_diffuse_color = _render->addShaderUniform(_shader, "diffuse_color", glm::vec4(1.0f));
	_diffuse_ratio = _render->addShaderUniform(_shader, "diffuse_ratio", 1.0f);
	_renderPass = _render->addRenderPass(_shader);
	_render->pushSetTestTaskRenderPass(_renderPass, false, false, true);
	_render->pushSetClearValueTaskRenderPass(_renderPass, glm::vec4(0.25f, 0.25f, 0.25f, 1.0f));
	_render->pushClearTaskRenderPass(_renderPass, true, true, false);
}
#endif

// Returns the number of seconds since the component creation
double CameraSystem::getLifeTime() const
{
	return (_totalTime);
}

void CameraSystem::updateBegin(double time)
{
}

void CameraSystem::updateEnd(double time)
{
}

void CameraSystem::mainUpdate(double time)
{
#if !NEW_SHADER
	unsigned int textureOffset = 0;
	auto scene = _scene.lock();
	auto &renderer = scene->getInstance<Renderer>();
	std::shared_ptr<OpenGLTools::UniformBuffer> perFrameBuffer = scene->getInstance<Renderer>()->getUniform("PerFrame");

	for (auto e : _filter.getCollection())
	{
		auto camera = scene->getComponent<Component::CameraComponent>(e);
		auto skybox = camera->getSkybox();

		auto cameraPosition = camera->lookAtTransform;
		OpenGLTools::Framebuffer &camFbo = scene->getComponent<Component::CameraComponent>(e)->frameBuffer;

		if (skybox != nullptr && camFbo.isInit() == true)
		{
			std::shared_ptr<gl::Shader> s = scene->getInstance<Renderer>()->getShader(camera->getSkyboxShader());
			assert(s != nullptr && "Skybox does not have a shader associated");

			scene->getInstance<Renderer>()->getUniform("cameraUniform")->setUniform("projection", camera->projection);

			glm::mat4 t = cameraPosition;
			t[3][0] = 0;
			t[3][1] = 0;
			t[3][2] = 0;
			t[3][3] = 1;

			scene->getInstance<Renderer>()->getUniform("cameraUniform")->setUniform("view", t);
			scene->getInstance<Renderer>()->getUniform("cameraUniform")->flushChanges();

			camFbo.bind();
			glViewport(0, 0, camFbo.getSize().x, camFbo.getSize().y);

			glEnable(GL_DEPTH_TEST);
			glDrawBuffer(GL_COLOR_ATTACHMENT0);
			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
			glDepthMask(GL_TRUE);
			glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			s->use();

			glDepthMask(GL_FALSE);
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->getId());
			skybox->draw();
			glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
			glDepthMask(GL_TRUE);
		}
	}
	_totalTime += time;
#else
	auto drawList = _scene.lock()->getInstance<AGE::Octree>()->getDrawableList();
	while (!drawList->empty())
	{
		auto &camera = drawList->front();

		_render->setUniformBlock(_global_state, 0, camera.projection);
		//_render->setUniformBlock(_global_state, 0, camera->projection);
		//_render->setUniformBlock(_global_state, 1, glm::vec4(0.0f, 8.0f, 0.0f, 1.0f));
		_render->setShaderUniform(_shader, _view_matrix, camera.transformation);
		_render->setShaderUniform(_shader, _diffuse_color, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f));
		_render->setShaderUniform(_shader, _diffuse_ratio, 1.0f);
		_render->draw(GL_TRIANGLES, _renderPass, NULL, 0);
		glUseProgram(0);
		_render->draw(GL_TRIANGLES, _renderPass, NULL, 0);
		while (!camera.drawables.empty())
		{
			auto &c = camera.drawables.front();
			_render->setShaderUniform(_shader, _model_matrix, c.transformation);
			_render->setShaderUniform(_shader, _normal_matrix, glm::transpose(glm::inverse(glm::mat3(camera.transformation * c.transformation))));
			_render->updateMemoryShader(_shader);
			_render->geometryManager.draw(GL_TRIANGLES, c.mesh.indices, c.mesh.vertices);
			camera.drawables.pop();
		}
		drawList->pop();
	}

#endif
}

bool CameraSystem::initialize()
{
#if !NEW_SHADER
	_filter.requireComponent<Component::CameraComponent>();
#else
	_camera.requireComponent<Component::CameraComponent>();
	_drawable.requireComponent<Component::MeshRenderer>();
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClearDepth(1.0f);
#endif
	return true;
}<commit_msg>clean a little problematic piece of code<commit_after>#include <Systems/CameraSystem.hh>
#include <Utils/MatrixConversion.hpp>
#include <Context/IRenderContext.hh>
#include <Utils/ScreenPosToWorldRay.hpp>
#include <Core/Renderer.hh>
#include <Components/MeshRenderer.hh>
#include <Components/CameraComponent.hpp>
#include <Core/SceneManager.hh>
#include <OpenGL/ShadingManager.hh>
#include <OpenGL/GeometryManager.hh>
#include <Core/Drawable.hh>
#include <Core/AssetsManager.hpp>

//tmp
#include <Core/Octree.hpp>

# define VERTEX_SHADER "../../Shaders/test_pipeline_1.vp"
# define FRAG_SHADER "../../Shaders/test_pipeline_1.fp"

CameraSystem::CameraSystem(std::weak_ptr<AScene> &&scene)
	: System(std::move(scene)),
#if NEW_SHADER
	_render(NULL),
#endif
	_renderDebugMethod(false),
	_totalTime(0),
#if NEW_SHADER
	_camera(std::move(scene)),
	_drawable(std::move(scene))
#else
	_filter(std::move(scene))
#endif
{
	_name = "camera_system";
}

void CameraSystem::setRenderDebugMode(bool t)
{
	_renderDebugMethod = t;
}

bool CameraSystem::getRenderDebugMode() const
{
	return _renderDebugMethod;
}

void CameraSystem::getRayFromMousePosOnScreen(glm::vec3 &from, glm::vec3 &to)
{
#if NEW_SHADER
	if (_camera.getCollection().size() == 0)
		return;
#else
	if (_filter.getCollection().size() == 0)
		return;
#endif
	auto scene = _scene.lock();
	auto mousePos = scene->getInstance<Input>()->getMousePosition();
	auto screenSize = scene->getInstance<IRenderContext>()->getScreenSize();
#if NEW_SHADER
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_camera.getCollection().begin()));
#else
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_filter.getCollection().begin()));
#endif
	// TODO
	//screenPosToWorldRay(mousePos.x, mousePos.y, screenSize.x, screenSize.y, cameraCpt->lookAtTransform, cameraCpt->projection, from, to);
}

void CameraSystem::getRayFromCenterOfScreen(glm::vec3 &from, glm::vec3 &to)
{
#if NEW_SHADER
	if (_camera.getCollection().size() == 0)
		return;
#else
	if (_filter.getCollection().size() == 0)
		return;
#endif
	auto scene = _scene.lock();
	auto screenSize = scene->getInstance<IRenderContext>()->getScreenSize();
	auto centerPos = glm::vec2(screenSize) * glm::vec2(0.5f);
#if NEW_SHADER
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_camera.getCollection().begin()));
#else
	auto cameraCpt = scene->getComponent<Component::CameraComponent>(*(_filter.getCollection().begin()));
#endif
	//TODO
	//screenPosToWorldRay(
	//	static_cast<int>(centerPos.x),
	//	static_cast<int>(centerPos.y),
	//	static_cast<int>(screenSize.x),
	//	static_cast<int>(screenSize.y),
	//	cameraCpt->lookAtTransform,
	//	cameraCpt->projection,
	//	from,
	//	to);
}

#if NEW_SHADER

void CameraSystem::setManager(gl::ShadingManager &m)
{
	_render = &m;

	if (_render == NULL)
		std::cerr << "Warning: No manager set for the camerasystem" << std::endl;

	_shader = _render->addShader(VERTEX_SHADER, FRAG_SHADER);
	size_t sizeElement[2];
	gl::set_tab_sizetype<glm::mat4, glm::vec4>(sizeElement);
	_global_state = _render->addUniformBlock(2, sizeElement);
	_render->addShaderInterfaceBlock(_shader, "global_state", _global_state);
	_render->setUniformBlock(_global_state, 1, glm::vec4(0.0f, 8.0f, 0.0f, 1.0f));
	_model_matrix = _render->addShaderUniform(_shader, "model_matrix", glm::mat4(1.f));
	_view_matrix = _render->addShaderUniform(_shader, "view_matrix", glm::mat4(1.f));
	_normal_matrix = _render->addShaderUniform(_shader, "normal_matrix", glm::mat3(1.f));
	_diffuse_texture = _render->addShaderSampler(_shader, "diffuse_texture");
	_diffuse_color = _render->addShaderUniform(_shader, "diffuse_color", glm::vec4(1.0f));
	_diffuse_ratio = _render->addShaderUniform(_shader, "diffuse_ratio", 1.0f);
	_renderPass = _render->addRenderPass(_shader);
	_render->pushSetTestTaskRenderPass(_renderPass, false, false, true);
	_render->pushSetClearValueTaskRenderPass(_renderPass, glm::vec4(0.25f, 0.25f, 0.25f, 1.0f));
	_render->pushClearTaskRenderPass(_renderPass, true, true, false);
}
#endif

// Returns the number of seconds since the component creation
double CameraSystem::getLifeTime() const
{
	return (_totalTime);
}

void CameraSystem::updateBegin(double time)
{
}

void CameraSystem::updateEnd(double time)
{
}

void CameraSystem::mainUpdate(double time)
{
#if !NEW_SHADER
	unsigned int textureOffset = 0;
	auto scene = _scene.lock();
	auto &renderer = scene->getInstance<Renderer>();
	std::shared_ptr<OpenGLTools::UniformBuffer> perFrameBuffer = scene->getInstance<Renderer>()->getUniform("PerFrame");

	for (auto e : _filter.getCollection())
	{
		auto camera = scene->getComponent<Component::CameraComponent>(e);
		auto skybox = camera->getSkybox();

		auto cameraPosition = camera->lookAtTransform;
		OpenGLTools::Framebuffer &camFbo = scene->getComponent<Component::CameraComponent>(e)->frameBuffer;

		if (skybox != nullptr && camFbo.isInit() == true)
		{
			std::shared_ptr<gl::Shader> s = scene->getInstance<Renderer>()->getShader(camera->getSkyboxShader());
			assert(s != nullptr && "Skybox does not have a shader associated");

			scene->getInstance<Renderer>()->getUniform("cameraUniform")->setUniform("projection", camera->projection);

			glm::mat4 t = cameraPosition;
			t[3][0] = 0;
			t[3][1] = 0;
			t[3][2] = 0;
			t[3][3] = 1;

			scene->getInstance<Renderer>()->getUniform("cameraUniform")->setUniform("view", t);
			scene->getInstance<Renderer>()->getUniform("cameraUniform")->flushChanges();

			camFbo.bind();
			glViewport(0, 0, camFbo.getSize().x, camFbo.getSize().y);

			glEnable(GL_DEPTH_TEST);
			glDrawBuffer(GL_COLOR_ATTACHMENT0);
			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
			glDepthMask(GL_TRUE);
			glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			s->use();

			glDepthMask(GL_FALSE);
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->getId());
			skybox->draw();
			glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
			glDepthMask(GL_TRUE);
		}
	}
	_totalTime += time;
#else
	auto drawList = _scene.lock()->getInstance<AGE::Octree>()->getDrawableList();
	while (!drawList->empty())
	{
		auto &camera = drawList->front();

		_render->setUniformBlock(_global_state, 0, camera.projection);
		//_render->setUniformBlock(_global_state, 0, camera->projection);
		//_render->setUniformBlock(_global_state, 1, glm::vec4(0.0f, 8.0f, 0.0f, 1.0f));
		_render->setShaderUniform(_shader, _view_matrix, camera.transformation);
		_render->setShaderUniform(_shader, _diffuse_color, glm::vec4(1.0f, 1.0f, 1.0f, 1.0f));
		_render->setShaderUniform(_shader, _diffuse_ratio, 1.0f);
		_render->draw(GL_TRIANGLES, _renderPass, NULL, 0);
		while (!camera.drawables.empty())
		{
			auto &c = camera.drawables.front();
			_render->setShaderUniform(_shader, _model_matrix, c.transformation);
			_render->setShaderUniform(_shader, _normal_matrix, glm::transpose(glm::inverse(glm::mat3(camera.transformation * c.transformation))));
			_render->updateMemoryShader(_shader);
			_render->geometryManager.draw(GL_TRIANGLES, c.mesh.indices, c.mesh.vertices);
			camera.drawables.pop();
		}
		drawList->pop();
	}

#endif
}

bool CameraSystem::initialize()
{
#if !NEW_SHADER
	_filter.requireComponent<Component::CameraComponent>();
#else
	_camera.requireComponent<Component::CameraComponent>();
	_drawable.requireComponent<Component::MeshRenderer>();
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClearDepth(1.0f);
#endif
	return true;
}<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_EXPECTED_INL
#define IOX_HOOFS_CXX_EXPECTED_INL

#include "iceoryx_hoofs/cxx/expected.hpp"

namespace iox
{
namespace cxx
{
namespace internal
{
template <typename... T>
struct IsOptional : std::false_type
{
};
template <typename T>
struct IsOptional<iox::cxx::optional<T>> : std::true_type
{
};
} // namespace internal

template <typename T>
inline success<T>::success(const T& t) noexcept
    : value(t)
{
}

template <typename T>
inline success<T>::success(T&& t) noexcept
    : value(std::forward<T>(t))
{
}

template <typename T>
template <typename... Targs>
inline success<T>::success(Targs&&... args) noexcept
    : value(std::forward<Targs>(args)...)
{
}

template <typename T>
inline error<T>::error(const T& t) noexcept
    : value(t)
{
}

template <typename T>
inline error<T>::error(T&& t) noexcept
    : value(std::forward<T>(t))
{
}

template <typename T>
template <typename... Targs>
inline error<T>::error(Targs&&... args) noexcept
    : value(std::forward<Targs>(args)...)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(variant<ValueType, ErrorType>&& f_store) noexcept
    : m_store(std::move(f_store))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(const success<ValueType>& successValue) noexcept
    : m_store(in_place_index<VALUE_INDEX>(), successValue.value)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(success<ValueType>&& successValue) noexcept
    : m_store(in_place_index<VALUE_INDEX>(), std::move(successValue.value))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(const error<ErrorType>& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), errorValue.value)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(error<ErrorType>&& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), std::move(errorValue.value))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(expected<ValueType, ErrorType>&& rhs) noexcept
{
    *this = std::move(rhs);
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>&
expected<ValueType, ErrorType>::operator=(expected<ValueType, ErrorType>&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_store = std::move(rhs.m_store);
    }
    return *this;
}

template <typename ValueType, typename ErrorType>
template <typename... Targs>
inline expected<ValueType, ErrorType> expected<ValueType, ErrorType>::create_value(Targs&&... args) noexcept
{
    expected<ValueType, ErrorType> returnValue{
        variant<ValueType, ErrorType>(in_place_index<VALUE_INDEX>(), std::forward<Targs>(args)...)};

    return returnValue;
}

template <typename ValueType, typename ErrorType>
template <typename... Targs>
inline expected<ValueType, ErrorType> expected<ValueType, ErrorType>::create_error(Targs&&... args) noexcept
{
    expected<ValueType, ErrorType> returnValue{
        variant<ValueType, ErrorType>(in_place_index<ERROR_INDEX>(), std::forward<Targs>(args)...)};

    return returnValue;
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::operator bool() const noexcept
{
    return !has_error();
}

template <typename ValueType, typename ErrorType>
inline bool expected<ValueType, ErrorType>::has_error() const noexcept
{
    return m_store.index() == ERROR_INDEX;
}

template <typename ValueType, typename ErrorType>
inline ErrorType&& expected<ValueType, ErrorType>::get_error() && noexcept
{
    return std::move(*m_store.template get_at_index<ERROR_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline ErrorType& expected<ValueType, ErrorType>::get_error() & noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType&& expected<ValueType, ErrorType>::value() && noexcept
{
    return std::move(*m_store.template get_at_index<VALUE_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline const ValueType& expected<ValueType, ErrorType>::value() const& noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType& expected<ValueType, ErrorType>::value() & noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ErrorType>
inline const ErrorType& expected<ErrorType>::get_error() const& noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType* expected<ValueType, ErrorType>::operator->() noexcept
{
    return m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline const ValueType* expected<ValueType, ErrorType>::operator->() const noexcept
{
    return const_cast<expected*>(this)->operator->();
}

template <typename ValueType, typename ErrorType>
inline ValueType& expected<ValueType, ErrorType>::operator*() noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline const ValueType& expected<ValueType, ErrorType>::operator*() const noexcept
{
    return const_cast<expected*>(this)->operator*();
}

template <typename ValueType, typename ErrorType>
template <typename T>
inline expected<ValueType, ErrorType>::operator expected<T>() const noexcept
{
    if (has_error())
    {
        return error<ErrorType>(get_error());
    }
    return success<>();
}

template <typename ValueType, typename ErrorType>
inline optional<ValueType> expected<ValueType, ErrorType>::to_optional() const noexcept
{
    optional<ValueType> returnValue;
    if (!has_error())
    {
        returnValue.emplace(value());
    }
    return returnValue;
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::operator optional<ValueType>() const noexcept
{
    return this->to_optional();
}
// expected<ErrorType>

template <typename ErrorType>
inline expected<ErrorType>::expected(variant<ErrorType>&& f_store) noexcept
    : m_store(std::move(f_store))
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(const success<void>&) noexcept
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(expected<ErrorType>&& rhs) noexcept
{
    *this = std::move(rhs);
}

template <typename ErrorType>
inline expected<ErrorType>& expected<ErrorType>::operator=(expected<ErrorType>&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_store = std::move(rhs.m_store);
    }
    return *this;
}

template <typename ErrorType>
inline expected<ErrorType>::expected(const error<ErrorType>& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), errorValue.value)
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(error<ErrorType>&& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), std::move(errorValue.value))
{
}

#if defined(_WIN32)
template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>::expected(const expected<ValueType, ErrorType>& rhs) noexcept
{
    m_hasError = rhs.has_error();
    if (m_hasError)
    {
        m_store.emplace_at_index<ERROR_INDEX>(rhs.get_error());
    }
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>::expected(expected<ValueType, ErrorType>&& rhs) noexcept
{
    m_hasError = rhs.has_error();
    if (m_hasError)
    {
        m_store.emplace_at_index<ERROR_INDEX>(std::move(rhs.get_error()));
    }
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>& expected<ErrorType>::operator=(const expected<ValueType, ErrorType>& rhs) noexcept
{
    if (m_hasError && rhs.has_error())
    {
        m_store.get_error() = rhs.get_error();
    }
    else if (rhs.has_error())
    {
        m_store = variant<ErrorType>(in_place_type<ErrorType>(), rhs.get_error());
    }
    m_hasError = rhs.has_error();
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>& expected<ErrorType>::operator=(expected<ValueType, ErrorType>&& rhs) noexcept
{
    if (m_hasError && rhs.has_error())
    {
        m_store.get_error() = std::move(rhs.get_error());
    }
    else if (rhs.has_error())
    {
        m_store = variant<ErrorType>(in_place_type<ErrorType>(), std::move(rhs.get_error()));
    }
    m_hasError = rhs.has_error();
}
#endif

template <typename ErrorType>
inline expected<ErrorType> expected<ErrorType>::create_value() noexcept
{
    expected<ErrorType> returnValue{variant<ErrorType>()};

    return returnValue;
}

template <typename ErrorType>
template <typename... Targs>
inline expected<ErrorType> expected<ErrorType>::create_error(Targs&&... args) noexcept
{
    expected<ErrorType> returnValue(variant<ErrorType>(in_place_index<ERROR_INDEX>(), std::forward<Targs>(args)...));

    return returnValue;
}

template <typename ErrorType>
inline expected<ErrorType>::operator bool() const noexcept
{
    return !has_error();
}

template <typename ErrorType>
inline bool expected<ErrorType>::has_error() const noexcept
{
    return (m_store.index() == ERROR_INDEX);
}

template <typename ErrorType>
inline ErrorType&& expected<ErrorType>::get_error() && noexcept
{
    return std::move(*m_store.template get_at_index<ERROR_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline const ErrorType& expected<ValueType, ErrorType>::get_error() const& noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ErrorType>
inline ErrorType& expected<ErrorType>::get_error() & noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_EXPECTED_INL
<commit_msg>iox-#996 Fix missing member m_hasError for windows<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_EXPECTED_INL
#define IOX_HOOFS_CXX_EXPECTED_INL

#include "iceoryx_hoofs/cxx/expected.hpp"

namespace iox
{
namespace cxx
{
namespace internal
{
template <typename... T>
struct IsOptional : std::false_type
{
};
template <typename T>
struct IsOptional<iox::cxx::optional<T>> : std::true_type
{
};
} // namespace internal

template <typename T>
inline success<T>::success(const T& t) noexcept
    : value(t)
{
}

template <typename T>
inline success<T>::success(T&& t) noexcept
    : value(std::forward<T>(t))
{
}

template <typename T>
template <typename... Targs>
inline success<T>::success(Targs&&... args) noexcept
    : value(std::forward<Targs>(args)...)
{
}

template <typename T>
inline error<T>::error(const T& t) noexcept
    : value(t)
{
}

template <typename T>
inline error<T>::error(T&& t) noexcept
    : value(std::forward<T>(t))
{
}

template <typename T>
template <typename... Targs>
inline error<T>::error(Targs&&... args) noexcept
    : value(std::forward<Targs>(args)...)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(variant<ValueType, ErrorType>&& f_store) noexcept
    : m_store(std::move(f_store))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(const success<ValueType>& successValue) noexcept
    : m_store(in_place_index<VALUE_INDEX>(), successValue.value)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(success<ValueType>&& successValue) noexcept
    : m_store(in_place_index<VALUE_INDEX>(), std::move(successValue.value))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(const error<ErrorType>& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), errorValue.value)
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(error<ErrorType>&& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), std::move(errorValue.value))
{
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::expected(expected<ValueType, ErrorType>&& rhs) noexcept
{
    *this = std::move(rhs);
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>&
expected<ValueType, ErrorType>::operator=(expected<ValueType, ErrorType>&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_store = std::move(rhs.m_store);
    }
    return *this;
}

template <typename ValueType, typename ErrorType>
template <typename... Targs>
inline expected<ValueType, ErrorType> expected<ValueType, ErrorType>::create_value(Targs&&... args) noexcept
{
    expected<ValueType, ErrorType> returnValue{
        variant<ValueType, ErrorType>(in_place_index<VALUE_INDEX>(), std::forward<Targs>(args)...)};

    return returnValue;
}

template <typename ValueType, typename ErrorType>
template <typename... Targs>
inline expected<ValueType, ErrorType> expected<ValueType, ErrorType>::create_error(Targs&&... args) noexcept
{
    expected<ValueType, ErrorType> returnValue{
        variant<ValueType, ErrorType>(in_place_index<ERROR_INDEX>(), std::forward<Targs>(args)...)};

    return returnValue;
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::operator bool() const noexcept
{
    return !has_error();
}

template <typename ValueType, typename ErrorType>
inline bool expected<ValueType, ErrorType>::has_error() const noexcept
{
    return m_store.index() == ERROR_INDEX;
}

template <typename ValueType, typename ErrorType>
inline ErrorType&& expected<ValueType, ErrorType>::get_error() && noexcept
{
    return std::move(*m_store.template get_at_index<ERROR_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline ErrorType& expected<ValueType, ErrorType>::get_error() & noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType&& expected<ValueType, ErrorType>::value() && noexcept
{
    return std::move(*m_store.template get_at_index<VALUE_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline const ValueType& expected<ValueType, ErrorType>::value() const& noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType& expected<ValueType, ErrorType>::value() & noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ErrorType>
inline const ErrorType& expected<ErrorType>::get_error() const& noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline ValueType* expected<ValueType, ErrorType>::operator->() noexcept
{
    return m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline const ValueType* expected<ValueType, ErrorType>::operator->() const noexcept
{
    return const_cast<expected*>(this)->operator->();
}

template <typename ValueType, typename ErrorType>
inline ValueType& expected<ValueType, ErrorType>::operator*() noexcept
{
    return *m_store.template get_at_index<VALUE_INDEX>();
}

template <typename ValueType, typename ErrorType>
inline const ValueType& expected<ValueType, ErrorType>::operator*() const noexcept
{
    return const_cast<expected*>(this)->operator*();
}

template <typename ValueType, typename ErrorType>
template <typename T>
inline expected<ValueType, ErrorType>::operator expected<T>() const noexcept
{
    if (has_error())
    {
        return error<ErrorType>(get_error());
    }
    return success<>();
}

template <typename ValueType, typename ErrorType>
inline optional<ValueType> expected<ValueType, ErrorType>::to_optional() const noexcept
{
    optional<ValueType> returnValue;
    if (!has_error())
    {
        returnValue.emplace(value());
    }
    return returnValue;
}

template <typename ValueType, typename ErrorType>
inline expected<ValueType, ErrorType>::operator optional<ValueType>() const noexcept
{
    return this->to_optional();
}
// expected<ErrorType>

template <typename ErrorType>
inline expected<ErrorType>::expected(variant<ErrorType>&& f_store) noexcept
    : m_store(std::move(f_store))
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(const success<void>&) noexcept
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(expected<ErrorType>&& rhs) noexcept
{
    *this = std::move(rhs);
}

template <typename ErrorType>
inline expected<ErrorType>& expected<ErrorType>::operator=(expected<ErrorType>&& rhs) noexcept
{
    if (this != &rhs)
    {
        m_store = std::move(rhs.m_store);
    }
    return *this;
}

template <typename ErrorType>
inline expected<ErrorType>::expected(const error<ErrorType>& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), errorValue.value)
{
}

template <typename ErrorType>
inline expected<ErrorType>::expected(error<ErrorType>&& errorValue) noexcept
    : m_store(in_place_index<ERROR_INDEX>(), std::move(errorValue.value))
{
}

#if defined(_WIN32)
template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>::expected(const expected<ValueType, ErrorType>& rhs) noexcept
{
    if (rhs.has_error())
    {
        m_store.emplace_at_index<ERROR_INDEX>(rhs.get_error());
    }
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>::expected(expected<ValueType, ErrorType>&& rhs) noexcept
{
    if (rhs.has_error())
    {
        m_store.emplace_at_index<ERROR_INDEX>(std::move(rhs.get_error()));
    }
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>& expected<ErrorType>::operator=(const expected<ValueType, ErrorType>& rhs) noexcept
{
    if (has_error() && rhs.has_error())
    {
        m_store.get_error() = rhs.get_error();
    }
    else if (rhs.has_error())
    {
        m_store = variant<ErrorType>(in_place_type<ErrorType>(), rhs.get_error());
    }
}

template <typename ErrorType>
template <typename ValueType>
inline expected<ErrorType>& expected<ErrorType>::operator=(expected<ValueType, ErrorType>&& rhs) noexcept
{
    if (has_error() && rhs.has_error())
    {
        m_store.get_error() = std::move(rhs.get_error());
    }
    else if (rhs.has_error())
    {
        m_store = variant<ErrorType>(in_place_type<ErrorType>(), std::move(rhs.get_error()));
    }
}
#endif

template <typename ErrorType>
inline expected<ErrorType> expected<ErrorType>::create_value() noexcept
{
    expected<ErrorType> returnValue{variant<ErrorType>()};

    return returnValue;
}

template <typename ErrorType>
template <typename... Targs>
inline expected<ErrorType> expected<ErrorType>::create_error(Targs&&... args) noexcept
{
    expected<ErrorType> returnValue(variant<ErrorType>(in_place_index<ERROR_INDEX>(), std::forward<Targs>(args)...));

    return returnValue;
}

template <typename ErrorType>
inline expected<ErrorType>::operator bool() const noexcept
{
    return !has_error();
}

template <typename ErrorType>
inline bool expected<ErrorType>::has_error() const noexcept
{
    return (m_store.index() == ERROR_INDEX);
}

template <typename ErrorType>
inline ErrorType&& expected<ErrorType>::get_error() && noexcept
{
    return std::move(*m_store.template get_at_index<ERROR_INDEX>());
}

template <typename ValueType, typename ErrorType>
inline const ErrorType& expected<ValueType, ErrorType>::get_error() const& noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}

template <typename ErrorType>
inline ErrorType& expected<ErrorType>::get_error() & noexcept
{
    return *m_store.template get_at_index<ERROR_INDEX>();
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_EXPECTED_INL
<|endoftext|>