<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WW8ResourceModel.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-10 11:33:32 $
 *
 *  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 INCLUDED_WW8_EVENT_HANDLER_HXX
#define INCLUDED_WW8_EVENT_HANDLER_HXX

#include <string>
#include <memory>
#include <boost/shared_ptr.hpp>

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif // _SAL_TYPES_H_
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#include <WriterFilterDllApi.hxx>
#include <resourcemodel/OutputWithDepth.hxx>
/**
   @file WW8ResourceModel.hxx

   The classes in this file define the interfaces for the resource
   model of the DocTokenizer:

   @image html doctok.png

   A resource is a set of events that describe an object. A resource
   is only an abstract concept. It is not instanciated to a class.

   A reference to a resource represents the object that the resource
   describes. The reference can be resolved thereby generating the
   events of the resource.

   A handler receives the events generated by resolving a
   reference. There are several types of handlers each accepting their
   specific set of events.

   References always have a parameter determining the kind of handler
   they send the events they generate to. The set of events generated
   by resolving the reference is a subset of the events received by
   the handler.
*/

typedef sal_uInt32 Id;

namespace writerfilter {
using namespace ::com::sun::star;
using namespace ::std;

/**
    Reference to an resource that generates events and sends them to a
    handler.

    The reference can be resolved, i.e. the resource generates its
    events. The events must be suitable for the handler type given by
    the template parameter.

    @attention The parameter of the template does not determine the
    type of the reference's target. It determines the type of the handler!

    Example:

    A Word document can be represented as a stream of events. Event
    types in a Word document are text, properties, tables, starts and
    ends of groups. These can be handled by a stream handler (@see
    Stream). Thus a reference to a Word document is resolved by
    sending these events to a stream handler.
*/

template <class T>
class WRITERFILTER_DLLPUBLIC Reference
{
public:
    /**
        Pointer to reference

        @attention The ownership of a reference is transfered when
        the reference is passed.
    */
    typedef boost::shared_ptr< Reference<T> > Pointer_t;

    virtual ~Reference() {}

    /**
       Resolves the reference.

       The events of the references target resource are generated and
       send to a handler.

       @param rHandler         handler which receives the events
     */
    virtual void resolve(T & rHandler) = 0;

    /**
       Returns the type of the reference aka the name of the access class.
     */
    virtual string getType() const = 0;
};

class Value;
class Sprm;

/**
   Handler for properties.
 */
class WRITERFILTER_DLLPUBLIC Properties
{
public:
    /**
       Receives an attribute.

       @param name     name of the attribute
       @param val      value of the attribute
     */
    virtual void attribute(Id name, Value & val) = 0;

    /**
       Receives a SPRM.

       @param  sprm      the SPRM received
    */
    virtual void sprm(Sprm & sprm) = 0;

};

/**
   Handler for tables.
 */
class WRITERFILTER_DLLPUBLIC Table
{
public:
    /**
       Receives an entry of the table.

       @param pos     position of the entry in the table
       @param ref     reference to properties of the entry
     */
    virtual void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};

/**
   Handler for binary objects.
 */
class WRITERFILTER_DLLPUBLIC BinaryObj
{
public:
    /**
       Receives binary data of the object.

       @param buf     pointer to buffer containing the data
       @param len     size of buffer
       @param ref     reference to properties of binary object
     */
    virtual void data(const sal_uInt8* buf, size_t len,
                      writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};

/**
   Handler for a stream.
 */
class WRITERFILTER_DLLPUBLIC Stream
{
public:
    /**
       Pointer to this stream.
     */
    typedef boost::shared_ptr<Stream> Pointer_t;

    /**
       Receives start mark for group with the same section properties.
     */
    virtual void startSectionGroup() = 0;

    /**
       Receives end mark for group with the same section properties.
    */
    virtual void endSectionGroup() = 0;

    /**
       Receives start mark for group with the same paragraph properties.
     */
    virtual void startParagraphGroup() = 0;

    /**
       Receives end mark for group with the same paragraph properties.
     */
    virtual void endParagraphGroup() = 0;

    /**
       Receives start mark for group with the same character properties.
     */
    virtual void startCharacterGroup() = 0;

    /**
       Receives end mark for group with the same character properties.
     */
    virtual void endCharacterGroup() = 0;

    /**
       Receives 8-bit per character text.

       @param data  buffer containing the text
       @param len   number of characters in the text
     */
    virtual void text(const sal_uInt8 * data, size_t len) = 0;

    /**
       Receives 16-bit per character text.

       @param data    buffer containing the text
       @param len     number of characters in the text.
     */
    virtual void utext(const sal_uInt8 * data, size_t len) = 0;

    /**
       Receives properties of the current run of text.

       @param ref    reference to the properties
     */
    virtual void props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;

    /**
       Receives table.

       @param name     name of the table
       @param ref      referecne to the table
     */
    virtual void table(Id name,
                       writerfilter::Reference<Table>::Pointer_t ref) = 0;

    /**
        Receives a substream.

        @param name    name of the substream
        @param ref     reference to the substream
    */
    virtual void substream(Id name,
                           writerfilter::Reference<Stream>::Pointer_t ref) = 0;

    /**
       Debugging: Receives information about current point in stream.

       @param info     the information
     */
    virtual void info(const string & info) = 0;
};

/**
   A value.

   The methods of this class may throw exceptions if a certain aspect
   makes no sense for a certain value, e.g. the integer value of a
   string.
 */
class WRITERFILTER_DLLPUBLIC Value
{
public:
    /**
       Pointer to a value.
     */
    typedef auto_ptr<Value> Pointer_t;

    /**
       Returns integer representation of the value.
     */
    virtual int getInt() const = 0;

    /**
       Returns string representation of the value.
     */
    virtual ::rtl::OUString getString() const = 0;

    /**
       Returns representation of the value as uno::Any.
     */
    virtual uno::Any getAny() const = 0;

    /**
       Returns properties of this value.
     */
    virtual writerfilter::Reference<Properties>::Pointer_t getProperties() = 0;

    /**
       Returns stream of this value.
     */
    virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;

    /**
       Returns binary object  of this value.
     */
    virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;

    /**
       Returns string representation of this value.
     */
    virtual string toString() const = 0;
};

/**
   An SPRM.

 */
class WRITERFILTER_DLLPUBLIC Sprm
{
public:
    typedef auto_ptr<Sprm> Pointer_t;
    enum Kind { UNKNOWN, CHARACTER, PARAGRAPH, TABLE };
    /**
       Returns id of the SPRM.
     */
    virtual sal_uInt32 getId() const = 0;

    /**
       Returns value of the SPRM.
     */
    virtual Value::Pointer_t getValue() = 0;

    /**
       Returns reference to binary object contained in the SPRM.
     */
    virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;

    /**
       Returns reference to stream associated with the SPRM.
     */
    virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;

    /**
       Returns reference to properties contained in the SPRM.

     */
    virtual writerfilter::Reference<Properties>::Pointer_t getProps() = 0;

    /**
       Returns the kind of this SPRM.
    */
    virtual Kind getKind() = 0;

    /**
       Returns name of sprm.
    */
    virtual string getName() const = 0;

    /**
       Returns string repesentation of sprm.
     */
    virtual string toString() const = 0;
};

/**
   Creates handler for a stream.
*/
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createStreamHandler();

void WRITERFILTER_DLLPUBLIC analyzerIds();
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createAnalyzer();

void WRITERFILTER_DLLPUBLIC logger(string prefix, string message);

void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<Properties>::Pointer_t props);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, sal_uInt32 n);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & /*o*/, const char * /*name*/,
          const rtl::OUString & /*str*/);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<BinaryObj>::Pointer_t binary);

}

#endif // INCLUDED_WW8_EVENT_HANDLER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.20); FILE MERGED 2008/04/01 16:06:42 thb 1.2.20.2: #i85898# Stripping all external header guards 2008/03/28 15:52:57 rt 1.2.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: WW8ResourceModel.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_WW8_EVENT_HANDLER_HXX
#define INCLUDED_WW8_EVENT_HANDLER_HXX

#include <string>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <sal/types.h>
#include <com/sun/star/uno/Any.hxx>
#include <WriterFilterDllApi.hxx>
#include <resourcemodel/OutputWithDepth.hxx>
/**
   @file WW8ResourceModel.hxx

   The classes in this file define the interfaces for the resource
   model of the DocTokenizer:

   @image html doctok.png

   A resource is a set of events that describe an object. A resource
   is only an abstract concept. It is not instanciated to a class.

   A reference to a resource represents the object that the resource
   describes. The reference can be resolved thereby generating the
   events of the resource.

   A handler receives the events generated by resolving a
   reference. There are several types of handlers each accepting their
   specific set of events.

   References always have a parameter determining the kind of handler
   they send the events they generate to. The set of events generated
   by resolving the reference is a subset of the events received by
   the handler.
*/

typedef sal_uInt32 Id;

namespace writerfilter {
using namespace ::com::sun::star;
using namespace ::std;

/**
    Reference to an resource that generates events and sends them to a
    handler.

    The reference can be resolved, i.e. the resource generates its
    events. The events must be suitable for the handler type given by
    the template parameter.

    @attention The parameter of the template does not determine the
    type of the reference's target. It determines the type of the handler!

    Example:

    A Word document can be represented as a stream of events. Event
    types in a Word document are text, properties, tables, starts and
    ends of groups. These can be handled by a stream handler (@see
    Stream). Thus a reference to a Word document is resolved by
    sending these events to a stream handler.
*/

template <class T>
class WRITERFILTER_DLLPUBLIC Reference
{
public:
    /**
        Pointer to reference

        @attention The ownership of a reference is transfered when
        the reference is passed.
    */
    typedef boost::shared_ptr< Reference<T> > Pointer_t;

    virtual ~Reference() {}

    /**
       Resolves the reference.

       The events of the references target resource are generated and
       send to a handler.

       @param rHandler         handler which receives the events
     */
    virtual void resolve(T & rHandler) = 0;

    /**
       Returns the type of the reference aka the name of the access class.
     */
    virtual string getType() const = 0;
};

class Value;
class Sprm;

/**
   Handler for properties.
 */
class WRITERFILTER_DLLPUBLIC Properties
{
public:
    /**
       Receives an attribute.

       @param name     name of the attribute
       @param val      value of the attribute
     */
    virtual void attribute(Id name, Value & val) = 0;

    /**
       Receives a SPRM.

       @param  sprm      the SPRM received
    */
    virtual void sprm(Sprm & sprm) = 0;

};

/**
   Handler for tables.
 */
class WRITERFILTER_DLLPUBLIC Table
{
public:
    /**
       Receives an entry of the table.

       @param pos     position of the entry in the table
       @param ref     reference to properties of the entry
     */
    virtual void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};

/**
   Handler for binary objects.
 */
class WRITERFILTER_DLLPUBLIC BinaryObj
{
public:
    /**
       Receives binary data of the object.

       @param buf     pointer to buffer containing the data
       @param len     size of buffer
       @param ref     reference to properties of binary object
     */
    virtual void data(const sal_uInt8* buf, size_t len,
                      writerfilter::Reference<Properties>::Pointer_t ref) = 0;
};

/**
   Handler for a stream.
 */
class WRITERFILTER_DLLPUBLIC Stream
{
public:
    /**
       Pointer to this stream.
     */
    typedef boost::shared_ptr<Stream> Pointer_t;

    /**
       Receives start mark for group with the same section properties.
     */
    virtual void startSectionGroup() = 0;

    /**
       Receives end mark for group with the same section properties.
    */
    virtual void endSectionGroup() = 0;

    /**
       Receives start mark for group with the same paragraph properties.
     */
    virtual void startParagraphGroup() = 0;

    /**
       Receives end mark for group with the same paragraph properties.
     */
    virtual void endParagraphGroup() = 0;

    /**
       Receives start mark for group with the same character properties.
     */
    virtual void startCharacterGroup() = 0;

    /**
       Receives end mark for group with the same character properties.
     */
    virtual void endCharacterGroup() = 0;

    /**
       Receives 8-bit per character text.

       @param data  buffer containing the text
       @param len   number of characters in the text
     */
    virtual void text(const sal_uInt8 * data, size_t len) = 0;

    /**
       Receives 16-bit per character text.

       @param data    buffer containing the text
       @param len     number of characters in the text.
     */
    virtual void utext(const sal_uInt8 * data, size_t len) = 0;

    /**
       Receives properties of the current run of text.

       @param ref    reference to the properties
     */
    virtual void props(writerfilter::Reference<Properties>::Pointer_t ref) = 0;

    /**
       Receives table.

       @param name     name of the table
       @param ref      referecne to the table
     */
    virtual void table(Id name,
                       writerfilter::Reference<Table>::Pointer_t ref) = 0;

    /**
        Receives a substream.

        @param name    name of the substream
        @param ref     reference to the substream
    */
    virtual void substream(Id name,
                           writerfilter::Reference<Stream>::Pointer_t ref) = 0;

    /**
       Debugging: Receives information about current point in stream.

       @param info     the information
     */
    virtual void info(const string & info) = 0;
};

/**
   A value.

   The methods of this class may throw exceptions if a certain aspect
   makes no sense for a certain value, e.g. the integer value of a
   string.
 */
class WRITERFILTER_DLLPUBLIC Value
{
public:
    /**
       Pointer to a value.
     */
    typedef auto_ptr<Value> Pointer_t;

    /**
       Returns integer representation of the value.
     */
    virtual int getInt() const = 0;

    /**
       Returns string representation of the value.
     */
    virtual ::rtl::OUString getString() const = 0;

    /**
       Returns representation of the value as uno::Any.
     */
    virtual uno::Any getAny() const = 0;

    /**
       Returns properties of this value.
     */
    virtual writerfilter::Reference<Properties>::Pointer_t getProperties() = 0;

    /**
       Returns stream of this value.
     */
    virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;

    /**
       Returns binary object  of this value.
     */
    virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;

    /**
       Returns string representation of this value.
     */
    virtual string toString() const = 0;
};

/**
   An SPRM.

 */
class WRITERFILTER_DLLPUBLIC Sprm
{
public:
    typedef auto_ptr<Sprm> Pointer_t;
    enum Kind { UNKNOWN, CHARACTER, PARAGRAPH, TABLE };
    /**
       Returns id of the SPRM.
     */
    virtual sal_uInt32 getId() const = 0;

    /**
       Returns value of the SPRM.
     */
    virtual Value::Pointer_t getValue() = 0;

    /**
       Returns reference to binary object contained in the SPRM.
     */
    virtual writerfilter::Reference<BinaryObj>::Pointer_t getBinary() = 0;

    /**
       Returns reference to stream associated with the SPRM.
     */
    virtual writerfilter::Reference<Stream>::Pointer_t getStream() = 0;

    /**
       Returns reference to properties contained in the SPRM.

     */
    virtual writerfilter::Reference<Properties>::Pointer_t getProps() = 0;

    /**
       Returns the kind of this SPRM.
    */
    virtual Kind getKind() = 0;

    /**
       Returns name of sprm.
    */
    virtual string getName() const = 0;

    /**
       Returns string repesentation of sprm.
     */
    virtual string toString() const = 0;
};

/**
   Creates handler for a stream.
*/
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createStreamHandler();

void WRITERFILTER_DLLPUBLIC analyzerIds();
Stream::Pointer_t WRITERFILTER_DLLPUBLIC createAnalyzer();

void WRITERFILTER_DLLPUBLIC logger(string prefix, string message);

void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<Properties>::Pointer_t props);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, sal_uInt32 n);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & /*o*/, const char * /*name*/,
          const rtl::OUString & /*str*/);
void WRITERFILTER_DLLPUBLIC dump(OutputWithDepth<string> & o, const char * name, writerfilter::Reference<BinaryObj>::Pointer_t binary);

}

#endif // INCLUDED_WW8_EVENT_HANDLER_HXX
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	delay ユーティリティー (RL78/G13 32MHz) @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>

namespace utils {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  基準クロック３２ＭＨｚの待ち @n
				※-O2、-Os などの最適化が条件、最適化無しの場合などは、@n
				アセンブルリストを参照の上、マシンサイクルを確認
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct delay {

		//-----------------------------------------------------------------//
		/*!
			@brief  マイクロ秒単位の待ち
			@param[in]	us	待ち時間（マイクロ秒）
		*/
		//-----------------------------------------------------------------//
		static void micro_second(uint16_t us) {
			while(us > 0) {
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				--us;
			}
			// (2) decw	0xffef0
			// (1) movw	ax, 0xffef0
    		// (1) cmpw	ax, #0
    		// (1) skz
    		// (3) br	!!4922 <.L629>
		}
	};
}
<commit_msg>add milli-second api<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	delay ユーティリティー (RL78/G13 32MHz) @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>

namespace utils {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  基準クロック３２ＭＨｚの待ち @n
				※-O2、-Os などの最適化が条件、最適化無しの場合などは、@n
				アセンブルリストを参照の上、マシンサイクルを確認
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct delay {

		//-----------------------------------------------------------------//
		/*!
			@brief  マイクロ秒単位の待ち
			@param[in]	us	待ち時間（マイクロ秒）
		*/
		//-----------------------------------------------------------------//
		static void micro_second(uint16_t us) {
			while(us > 0) {
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				asm("nop"); asm("nop"); asm("nop"); asm("nop");
				--us;
			}
			// (2) decw	0xffef0
			// (1) movw	ax, 0xffef0
    		// (1) cmpw	ax, #0
    		// (1) skz
    		// (3) br	!!4922 <.L629>
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ミリ秒単位の待ち
			@param[in]	ms	待ち時間（ミリ秒）
		*/
		//-----------------------------------------------------------------//
		static void milli_second(uint16_t ms) {
			for(uint16_t i = 0; i < ms; ++i) {
				micro_second(1000);
			}
		}
	};
}
<|endoftext|>


<commit_before>#include "restclient-cpp/restclient.h"
#include <gtest/gtest.h>
#include <json/json.h>
#include <string>

class RestClientTest : public ::testing::Test
{
 protected:

    RestClientTest()
    {
    }

    virtual ~RestClientTest()
    {
    }

    virtual void SetUp()
    {
      RestClient::init();
    }

    virtual void TearDown()
    {
      RestClient::disable();
    }

};

// DELETE Tests
// check return code
TEST_F(RestClientTest, TestRestClientDeleteCode)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientDeleteBody)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/delete", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}

// check for failure
TEST_F(RestClientTest, TestRestClientDeleteFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::del(u);
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientDeleteHeaders)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// GET Tests
TEST_F(RestClientTest, TestRestClientGETCode)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientGETBodyCode)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/get", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}

// check for failure
TEST_F(RestClientTest, TestRestClientGETFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::get(u);
  EXPECT_EQ("Failed to query.", res.body);
  EXPECT_EQ(-1, res.code);
}

TEST_F(RestClientTest, TestRestClientGETHeaders)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// POST Tests
// check return code
TEST_F(RestClientTest, TestRestClientPOSTCode)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientPostBody)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/post", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}
// check for failure
TEST_F(RestClientTest, TestRestClientPOSTFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::post(u, "text/text", "data");
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientPOSTHeaders)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// PUT Tests
// check return code
TEST_F(RestClientTest, TestRestClientPUTCode)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientPutBody)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/put", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}
// check for failure
TEST_F(RestClientTest, TestRestClientPUTFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::put(u, "text/text", "data");
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientPUTHeaders)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}
TEST_F(RestClientTest, TestRestClientAuth)
{
  RestClient::Response res = RestClient::get("http://foo:bar@httpbin.org/basic-auth/foo/bar");
  EXPECT_EQ(200, res.code);

  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("foo", root.get("user", "no user").asString());
  EXPECT_EQ(true, root.get("authenticated", false).asBool());

  res = RestClient::get("http://httpbin.org/basic-auth/foo/bar");
  EXPECT_EQ(401, res.code);
}
TEST_F(RestClientTest, TestRestClientHeadCode)
{
  RestClient::Response res = RestClient::head("http://httpbin.org/get");
  EXPECT_EQ(200, res.code);
  EXPECT_EQ("", res.body);
}
<commit_msg>add unit test for http2 connection<commit_after>#include "restclient-cpp/restclient.h"
#include <gtest/gtest.h>
#include <json/json.h>
#include <string>

class RestClientTest : public ::testing::Test
{
 protected:

    RestClientTest()
    {
    }

    virtual ~RestClientTest()
    {
    }

    virtual void SetUp()
    {
      RestClient::init();
    }

    virtual void TearDown()
    {
      RestClient::disable();
    }

};

// DELETE Tests
// check return code
TEST_F(RestClientTest, TestRestClientDeleteCode)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientDeleteBody)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/delete", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}

// check for failure
TEST_F(RestClientTest, TestRestClientDeleteFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::del(u);
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientDeleteHeaders)
{
  RestClient::Response res = RestClient::del("http://httpbin.org/delete");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// GET Tests
TEST_F(RestClientTest, TestRestClientGETCode)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientGETHTTP2Code)
{
  RestClient::Response res = RestClient::get("https://http2.golang.org/reqinfo");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientGETBodyCode)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/get", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}

// check for failure
TEST_F(RestClientTest, TestRestClientGETFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::get(u);
  EXPECT_EQ("Failed to query.", res.body);
  EXPECT_EQ(-1, res.code);
}

TEST_F(RestClientTest, TestRestClientGETHeaders)
{
  RestClient::Response res = RestClient::get("http://httpbin.org/get");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// POST Tests
// check return code
TEST_F(RestClientTest, TestRestClientPOSTCode)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientPostBody)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/post", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}
// check for failure
TEST_F(RestClientTest, TestRestClientPOSTFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::post(u, "text/text", "data");
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientPOSTHeaders)
{
  RestClient::Response res = RestClient::post("http://httpbin.org/post", "text/text", "data");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}

// PUT Tests
// check return code
TEST_F(RestClientTest, TestRestClientPUTCode)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  EXPECT_EQ(200, res.code);
}
TEST_F(RestClientTest, TestRestClientPutBody)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("http://httpbin.org/put", root.get("url", "no url set").asString());
  EXPECT_EQ("restclient-cpp/" RESTCLIENT_VERSION, root["headers"].get("User-Agent", "no url set").asString());
}
// check for failure
TEST_F(RestClientTest, TestRestClientPUTFailureCode)
{
  std::string u = "http://nonexistent";
  RestClient::Response res = RestClient::put(u, "text/text", "data");
  EXPECT_EQ(-1, res.code);
}
TEST_F(RestClientTest, TestRestClientPUTHeaders)
{
  RestClient::Response res = RestClient::put("http://httpbin.org/put", "text/text", "data");
  EXPECT_EQ("keep-alive", res.headers["Connection"]);
}
TEST_F(RestClientTest, TestRestClientAuth)
{
  RestClient::Response res = RestClient::get("http://foo:bar@httpbin.org/basic-auth/foo/bar");
  EXPECT_EQ(200, res.code);

  Json::Value root;
  std::istringstream str(res.body);
  str >> root;

  EXPECT_EQ("foo", root.get("user", "no user").asString());
  EXPECT_EQ(true, root.get("authenticated", false).asBool());

  res = RestClient::get("http://httpbin.org/basic-auth/foo/bar");
  EXPECT_EQ(401, res.code);
}
TEST_F(RestClientTest, TestRestClientHeadCode)
{
  RestClient::Response res = RestClient::head("http://httpbin.org/get");
  EXPECT_EQ(200, res.code);
  EXPECT_EQ("", res.body);
}
<|endoftext|>


<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"

namespace model
{
    class World
    {
        friend class Shader;
        friend class Species;

        public:
            // constructor.
            World();

            // destructor.
            ~World();

            // this method renders the entire world, one shader at a time.
            void render();

        protected:
            // this method sets a shader pointer.
            void set_shader_pointer(GLuint shaderID, void* shader_pointer);

            // this method gets a shader pointer.
            void* get_shader_pointer(GLuint shaderID);

            // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
            GLuint get_shaderID();

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

        private:
            void compute_matrices_from_inputs();

            void* world_species_pointer;              // pointer to world species (used in collision detection).

            std::vector<void*> shader_pointer_vector;
            std::queue<GLuint> free_shaderID_queue;
    };

    class Shader
    {
        friend class World;
        friend class Texture;
        friend class Species;
        friend class Object;

        public:
            // constructor.
            Shader(ShaderStruct shader_struct);

            // destructor.
            ~Shader();

        protected:
            // this method renders all textures using this shader.
            void render();

            // this method sets a texture pointer.
            void set_texture_pointer(GLuint textureID, void* texture_pointer);

            // this method gets a texture pointer.
            void* get_texture_pointer(GLuint textureID);

            // this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
            GLuint get_textureID();

            // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
            void switch_to_new_world(model::World *new_world_pointer);

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

            model::World *world_pointer;          // pointer to the world.

            GLuint programID;                     // shaders' programID, returned by `LoadShaders`.

            GLuint MatrixID;
            GLuint ViewMatrixID;
            GLuint ModelMatrixID;

        private:
            void bind_to_world();

            void* world_species_pointer;          // pointer to world species (used in collision detection).

            GLuint shaderID;                      // shader ID, returned by `model::World->get_shaderID()`.

            std::string vertex_shader;            // filename of vertex shader.
            std::string fragment_shader;          // filename of fragment shader.

            std::vector<void*> texture_pointer_vector;
            std::queue<GLuint> free_textureID_queue;

            const char *char_vertex_shader;
            const char *char_fragment_shader;
    };

    class Texture
    {
        public:
            // constructor.
            Texture(TextureStruct texture_struct);

            // destructor.
            ~Texture();

            // this method renders all species using this texture.
            void render();

            // this method sets a species pointer.
            void set_species_pointer(GLuint speciesID, void* species_pointer);

            // this method gets a species pointer.
            void* get_species_pointer(GLuint speciesID);

            // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
            GLuint get_speciesID();

            // this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
            void switch_to_new_shader(model::Shader *new_world_pointer);

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

            model::Shader *shader_pointer;         // pointer to the shader.

        private:
            void bind_to_shader();

            void* world_species_pointer;           // pointer to world species (used in collision detection).

            GLuint texture;                        // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
            GLuint openGL_textureID;               // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.

            std::vector<void*> species_pointer_vector;
            std::queue<GLuint> free_speciesID_queue;

            std::string texture_file_format;       // type of the model file, eg. `"bmp"`.
            std::string texture_filename;          // filename of the model file.
            GLuint textureID;                      // texture ID, returned by `Shader::get_textureID`.
            const char *char_texture_file_format;
            const char *char_texture_filename;
    };

    class Graph
    {
        public:
            // constructor.
            Graph();

            // destructor.
            ~Graph();

            // this method sets a node pointer.
            void set_node_pointer(GLuint nodeID, void* node_pointer);

            // this method gets a node pointer.
            void* get_node_pointer(GLuint nodeID);

            // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
            GLuint get_nodeID();

        private:
            std::vector<void*> node_pointer_vector;
            std::queue<GLuint> free_nodeID_queue;
    };

    // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
    // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
    // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
    class Node
    {
        public:
            // constructor.
            Node(NodeStruct node_struct);

            // destructor.
            ~Node();

            // this method creates a bidirectional link.
            // creating of bidirectional links is not possible before all nodes are created.
            void create_bidirectional_link(GLuint nodeID);

            // this method deletes a bidirectional link.
            // deleting of links is not possible before all nodes are created.
            void delete_bidirectional_link(GLuint nodeID);

            // this method transfers this node to a new graph.
            // links will not be changed.
            // all nodes that are to be transferred must be transferred separately.
            // before transfering any node to a new graph,
            // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
            void transfer_to_new_graph(model::Graph *new_graph_pointer);

            GLuint nodeID;
            model::Graph *graph_pointer;

        private:
            // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
            std::vector<GLuint> neighbor_nodeIDs;

            // this method creates an unidirectional link.
            // in the constructor only unidirectional links can be created.
            void create_unidirectional_link(GLuint nodeID);

            // this method deletes an unidirectional link.
            void delete_unidirectional_link(GLuint nodeID);

            glm::vec3 coordinate_vector;
    };

    class Species
    {
        public:
            // constructor.
            Species(SpeciesStruct species_struct);

            // destructor.
            ~Species();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_object_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_object_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
            void switch_to_new_texture(model::Texture *new_texture_pointer);

            bool is_world;                           // worlds currently do not rotate nor translate.

            std::string color_channel;               // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            model::Texture *texture_pointer;       // pointer to the texture.

        private:
            void bind_to_texture();

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            GLuint speciesID;                      // species ID, returned by `model::Texture->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Font
    {
        public:
            // constructor.
            Font(FontStruct font_struct);

            // destructor.
            ~Font();

            // this method renders all objects of this species.
            void render();

            // this method sets a glyph pointer.
            void set_glyph_pointer(GLuint objectID, void* object_pointer);

            // this method gets a glyph pointer.
            void* get_glyph_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_glyphID();

            // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
            void switch_to_new_texture(model::Texture *new_texture_pointer);

            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            model::Texture *texture_pointer;       // pointer to the texture.

        private:
            void bind_to_texture();

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            GLuint speciesID;                      // species ID, returned by `model::Texture->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Glyph
    {
        public:
            // constructor.
            Glyph(GlyphStruct glyph_struct);

            // destructor.
            ~Glyph();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_object_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_object_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            model::Font *font_pointer;             // pointer to the font.

        private:
            void bind_to_font();

            GLuint glyphID;                        // glyph ID, returned by `model::Font->get_glyphID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Object
    {
        public:
            // constructor.
            Object(ObjectStruct object_struct);

            // destructor.
            ~Object();

            // this method renders this object.
            void render();

            // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
            void switch_to_new_species(model::Species *new_species_pointer);

        private:
            void bind_to_species();

            model::Species *species_pointer;       // pointer to the species.

            GLuint objectID;                       // object ID, returned by `model::Species->get_objectID()`.
            bool has_entered;

            glm::vec3 coordinate_vector;           // coordinate vector.
            glm::vec3 original_scale_vector;       // original scale vector.
            GLfloat rotate_angle;                  // rotate angle.
            glm::vec3 rotate_vector;               // rotate vector.
            glm::vec3 translate_vector;            // translate vector.

            // The rest fields are created in the constructor.
            glm::mat4 model_matrix;                // model matrix.
            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object. not used at the moment.

            glm::mat4 MVP_matrix;                  // model view projection matrix.
    };
}

#endif
<commit_msg>`class Texture`:n `public`-funktioista tehty `protected`-funktioita.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"

namespace model
{
    class World
    {
        friend class Shader;
        friend class Species;

        public:
            // constructor.
            World();

            // destructor.
            ~World();

            // this method renders the entire world, one shader at a time.
            void render();

        protected:
            // this method sets a shader pointer.
            void set_shader_pointer(GLuint shaderID, void* shader_pointer);

            // this method gets a shader pointer.
            void* get_shader_pointer(GLuint shaderID);

            // this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
            GLuint get_shaderID();

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

        private:
            void compute_matrices_from_inputs();

            void* world_species_pointer;              // pointer to world species (used in collision detection).

            std::vector<void*> shader_pointer_vector;
            std::queue<GLuint> free_shaderID_queue;
    };

    class Shader
    {
        friend class World;
        friend class Texture;
        friend class Species;
        friend class Object;

        public:
            // constructor.
            Shader(ShaderStruct shader_struct);

            // destructor.
            ~Shader();

        protected:
            // this method renders all textures using this shader.
            void render();

            // this method sets a texture pointer.
            void set_texture_pointer(GLuint textureID, void* texture_pointer);

            // this method gets a texture pointer.
            void* get_texture_pointer(GLuint textureID);

            // this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
            GLuint get_textureID();

            // this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
            void switch_to_new_world(model::World *new_world_pointer);

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

            model::World *world_pointer;          // pointer to the world.

            GLuint programID;                     // shaders' programID, returned by `LoadShaders`.

            GLuint MatrixID;
            GLuint ViewMatrixID;
            GLuint ModelMatrixID;

        private:
            void bind_to_world();

            void* world_species_pointer;          // pointer to world species (used in collision detection).

            GLuint shaderID;                      // shader ID, returned by `model::World->get_shaderID()`.

            std::string vertex_shader;            // filename of vertex shader.
            std::string fragment_shader;          // filename of fragment shader.

            std::vector<void*> texture_pointer_vector;
            std::queue<GLuint> free_textureID_queue;

            const char *char_vertex_shader;
            const char *char_fragment_shader;
    };

    class Texture
    {
        friend class Shader;
        friend class Species;
        friend class Object;

        public:
            // constructor.
            Texture(TextureStruct texture_struct);

            // destructor.
            ~Texture();

        protected:
            // this method renders all species using this texture.
            void render();

            // this method sets a species pointer.
            void set_species_pointer(GLuint speciesID, void* species_pointer);

            // this method gets a species pointer.
            void* get_species_pointer(GLuint speciesID);

            // this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
            GLuint get_speciesID();

            // this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
            void switch_to_new_shader(model::Shader *new_world_pointer);

            // this method sets a world species pointer.
            void set_world_species_pointer(void* world_species_pointer);

            model::Shader *shader_pointer;         // pointer to the shader.

        private:
            void bind_to_shader();

            void* world_species_pointer;           // pointer to world species (used in collision detection).

            GLuint texture;                        // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
            GLuint openGL_textureID;               // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.

            std::vector<void*> species_pointer_vector;
            std::queue<GLuint> free_speciesID_queue;

            std::string texture_file_format;       // type of the model file, eg. `"bmp"`.
            std::string texture_filename;          // filename of the model file.
            GLuint textureID;                      // texture ID, returned by `Shader::get_textureID`.
            const char *char_texture_file_format;
            const char *char_texture_filename;
    };

    class Graph
    {
        public:
            // constructor.
            Graph();

            // destructor.
            ~Graph();

            // this method sets a node pointer.
            void set_node_pointer(GLuint nodeID, void* node_pointer);

            // this method gets a node pointer.
            void* get_node_pointer(GLuint nodeID);

            // this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
            GLuint get_nodeID();

        private:
            std::vector<void*> node_pointer_vector;
            std::queue<GLuint> free_nodeID_queue;
    };

    // `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
    // Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
    // The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
    class Node
    {
        public:
            // constructor.
            Node(NodeStruct node_struct);

            // destructor.
            ~Node();

            // this method creates a bidirectional link.
            // creating of bidirectional links is not possible before all nodes are created.
            void create_bidirectional_link(GLuint nodeID);

            // this method deletes a bidirectional link.
            // deleting of links is not possible before all nodes are created.
            void delete_bidirectional_link(GLuint nodeID);

            // this method transfers this node to a new graph.
            // links will not be changed.
            // all nodes that are to be transferred must be transferred separately.
            // before transfering any node to a new graph,
            // all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
            void transfer_to_new_graph(model::Graph *new_graph_pointer);

            GLuint nodeID;
            model::Graph *graph_pointer;

        private:
            // nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
            std::vector<GLuint> neighbor_nodeIDs;

            // this method creates an unidirectional link.
            // in the constructor only unidirectional links can be created.
            void create_unidirectional_link(GLuint nodeID);

            // this method deletes an unidirectional link.
            void delete_unidirectional_link(GLuint nodeID);

            glm::vec3 coordinate_vector;
    };

    class Species
    {
        public:
            // constructor.
            Species(SpeciesStruct species_struct);

            // destructor.
            ~Species();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_object_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_object_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
            void switch_to_new_texture(model::Texture *new_texture_pointer);

            bool is_world;                           // worlds currently do not rotate nor translate.

            std::string color_channel;               // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            model::Texture *texture_pointer;       // pointer to the texture.

        private:
            void bind_to_texture();

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            GLuint speciesID;                      // species ID, returned by `model::Texture->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Font
    {
        public:
            // constructor.
            Font(FontStruct font_struct);

            // destructor.
            ~Font();

            // this method renders all objects of this species.
            void render();

            // this method sets a glyph pointer.
            void set_glyph_pointer(GLuint objectID, void* object_pointer);

            // this method gets a glyph pointer.
            void* get_glyph_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_glyphID();

            // this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
            void switch_to_new_texture(model::Texture *new_texture_pointer);

            std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
            glm::vec3 lightPos;                      // light position.

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            model::Texture *texture_pointer;       // pointer to the texture.

        private:
            void bind_to_texture();

            std::string model_file_format;         // type of the model file, eg. `"bmp"`.
            std::string model_filename;            // filename of the model file.
            GLuint speciesID;                      // species ID, returned by `model::Texture->get_speciesID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
            const char *char_model_file_format;
            const char *char_model_filename;
            const char *char_color_channel;

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Glyph
    {
        public:
            // constructor.
            Glyph(GlyphStruct glyph_struct);

            // destructor.
            ~Glyph();

            // this method renders all objects of this species.
            void render();

            // this method sets a object pointer.
            void set_object_pointer(GLuint objectID, void* object_pointer);

            // this method gets a object pointer.
            void* get_object_pointer(GLuint objectID);

            // this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
            GLuint get_objectID();

            // The rest fields are created in the constructor.
            GLuint image_width;
            GLuint image_height;

            GLuint vertexPosition_modelspaceID;
            GLuint vertexUVID;
            GLuint vertexNormal_modelspaceID;

            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object.

            std::vector<GLuint> indices;           // the deleted vertices will be reused (though it is not required, if there's enough memory).
            std::vector<glm::vec3> indexed_vertices;
            std::vector<glm::vec2> indexed_UVs;
            std::vector<glm::vec3> indexed_normals;

            GLuint vertexbuffer;
            GLuint uvbuffer;
            GLuint normalbuffer;
            GLuint elementbuffer;

            model::Font *font_pointer;             // pointer to the font.

        private:
            void bind_to_font();

            GLuint glyphID;                        // glyph ID, returned by `model::Font->get_glyphID()`.
            GLuint lightID;                        // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.

            std::vector<void*> object_pointer_vector;
            std::queue<GLuint> free_objectID_queue;
    };

    class Object
    {
        public:
            // constructor.
            Object(ObjectStruct object_struct);

            // destructor.
            ~Object();

            // this method renders this object.
            void render();

            // this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
            void switch_to_new_species(model::Species *new_species_pointer);

        private:
            void bind_to_species();

            model::Species *species_pointer;       // pointer to the species.

            GLuint objectID;                       // object ID, returned by `model::Species->get_objectID()`.
            bool has_entered;

            glm::vec3 coordinate_vector;           // coordinate vector.
            glm::vec3 original_scale_vector;       // original scale vector.
            GLfloat rotate_angle;                  // rotate angle.
            glm::vec3 rotate_vector;               // rotate vector.
            glm::vec3 translate_vector;            // translate vector.

            // The rest fields are created in the constructor.
            glm::mat4 model_matrix;                // model matrix.
            std::vector<glm::vec3> vertices;       // vertices of the object.
            std::vector<glm::vec2> UVs;            // UVs of the object.
            std::vector<glm::vec3> normals;        // normals of the object. not used at the moment.

            glm::mat4 MVP_matrix;                  // model view projection matrix.
    };
}

#endif
<|endoftext|>


<commit_before>//
// Created by martin on 21.05.15.
//

#include "test_data_generator.h"
#include <iostream>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/normal_distribution.hpp>

void test_data_generator::init() {
    parameter_names.reserve(TREE_SIZE);
    boost::random::uniform_int_distribution<> dist_tree_depth(0, TREE_DEPTH - 1);
    std::string name;
    while (parameter_names.size() < TREE_SIZE) {
        name.clear();
        int node_depth = dist_tree_depth(rng);
        add_parameter("", 0, node_depth);
    }
    generate_access_order();
}

std::string test_data_generator::generate_parameter_name() {
    const std::string chars("abcdefghijklmnopqrstuvwxyz");
    boost::random::uniform_int_distribution<> dist_char_index(0, static_cast<int>(chars.size() - 1));
    boost::random::normal_distribution<> dist_parameter_name_length(PARAMETER_LENGTH_AVG, 3);
    std::string name;
    int parameter_name_size = static_cast<int>(dist_parameter_name_length(rng));
    for(int name_index = 0; name_index < parameter_name_size; ++name_index) {
        name.push_back(chars[dist_char_index(rng)]);
    }
    return name;
}

void test_data_generator::add_parameter(std::string prefix, int layer, int node_depth) {
    std::string parameter_name;
    if(!prefix.empty()) {
        parameter_name.append(prefix);
        parameter_name.push_back('.');
    }
    parameter_name.append(generate_parameter_name());
    if(layer == node_depth) {
        parameter_names.push_back(parameter_name);
        return;
    }
    boost::random::normal_distribution<> dist_node_leafes(NODE_LEAFES_AVG, 1.5);
    int node_leafes = static_cast<int>(dist_node_leafes(rng));
    for(int node_leaf = 0; node_leaf < node_leafes; node_leaf++) {
        add_parameter(parameter_name, layer + 1, node_depth);
    }
}

const std::vector<std::string> &test_data_generator::get_parameter_names() const {
    return parameter_names;
}

const std::vector<std::size_t> &test_data_generator::get_access_order() const {
    return access_order;
}

void test_data_generator::generate_access_order() {
    boost::random::uniform_int_distribution<> dist_parameter_access(0, static_cast<int>(TREE_SIZE) - 1);
    std::size_t access_list_length = 10000;
    access_order.clear();
    access_order.reserve(access_list_length);
    for(std::size_t i = 0; i < access_list_length; i++) {
        access_order.push_back(dist_parameter_access(rng));
    }
}
<commit_msg>simulate 1 million find requests now<commit_after>//
// Created by martin on 21.05.15.
//

#include "test_data_generator.h"
#include <iostream>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/normal_distribution.hpp>

void test_data_generator::init() {
    parameter_names.reserve(TREE_SIZE);
    boost::random::uniform_int_distribution<> dist_tree_depth(0, TREE_DEPTH - 1);
    std::string name;
    while (parameter_names.size() < TREE_SIZE) {
        name.clear();
        int node_depth = dist_tree_depth(rng);
        add_parameter("", 0, node_depth);
    }
    generate_access_order();
}

std::string test_data_generator::generate_parameter_name() {
    const std::string chars("abcdefghijklmnopqrstuvwxyz");
    boost::random::uniform_int_distribution<> dist_char_index(0, static_cast<int>(chars.size() - 1));
    boost::random::normal_distribution<> dist_parameter_name_length(PARAMETER_LENGTH_AVG, 3);
    std::string name;
    int parameter_name_size = static_cast<int>(dist_parameter_name_length(rng));
    for(int name_index = 0; name_index < parameter_name_size; ++name_index) {
        name.push_back(chars[dist_char_index(rng)]);
    }
    return name;
}

void test_data_generator::add_parameter(std::string prefix, int layer, int node_depth) {
    std::string parameter_name;
    if(!prefix.empty()) {
        parameter_name.append(prefix);
        parameter_name.push_back('.');
    }
    parameter_name.append(generate_parameter_name());
    if(layer == node_depth) {
        parameter_names.push_back(parameter_name);
        return;
    }
    boost::random::normal_distribution<> dist_node_leafes(NODE_LEAFES_AVG, 1.5);
    int node_leafes = static_cast<int>(dist_node_leafes(rng));
    for(int node_leaf = 0; node_leaf < node_leafes; node_leaf++) {
        add_parameter(parameter_name, layer + 1, node_depth);
    }
}

const std::vector<std::string> &test_data_generator::get_parameter_names() const {
    return parameter_names;
}

const std::vector<std::size_t> &test_data_generator::get_access_order() const {
    return access_order;
}

void test_data_generator::generate_access_order() {
    boost::random::uniform_int_distribution<> dist_parameter_access(0, static_cast<int>(TREE_SIZE) - 1);
    std::size_t access_list_length = 1000000;
    access_order.clear();
    access_order.reserve(access_list_length);
    for(std::size_t i = 0; i < access_list_length; i++) {
        access_order.push_back(dist_parameter_access(rng));
    }
}
<|endoftext|>


<commit_before>/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

// CPPAD_HAS_* defines
# include <cppad/configure.hpp>

# if CPPAD_HAS_ADOLC
# include <adolc/adouble.h>
# include <adolc/taping.h>
# include <adolc/interfaces.h>
// adouble definitions not in Adolc distribution and
// required in order to use CppAD::AD<adouble>
# include <cppad/example/base_adolc.hpp>
# endif

# include <cppad/cppad.hpp>
# include <limits>

namespace { // BEGIN empty namespace

bool One(void)
{	bool ok = true;                          // initialize test result
	using CppAD::NearEqual;
	double eps = 10. * std::numeric_limits<double>::epsilon();

	typedef CppAD::AD<double>   ADdouble;    // for one level of taping
	typedef CppAD::AD<ADdouble> ADDdouble;   // for two levels of taping
	size_t n = 2;                            // dimension for example

	// value of the independent variables
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);
	aa_x[0] = 1.; aa_x[1] = 3.; // test conversion double to AD< AD<double> >
	aa_x[0] = 2. * aa_x[0];     // test double * AD< AD<double> >
	CppAD::Independent(aa_x);

	// compute the function f(x) = 2 * x[0] * x[1]
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);
	aa_f[0] = 2. * aa_x[0] * aa_x[1];
	CppAD::ADFun<ADdouble> F(aa_x, aa_f);

	// value of the independent variables
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	a_x[0] = 2.; a_x[1] = 3.;
	Independent(a_x);

	// re-evaluate f(2, 3) (must get deepedence on a_x).
	size_t p = 0;
	CPPAD_TESTVECTOR(ADdouble) a_fp(1);
	a_fp    = F.Forward(p, a_x);
	ok     &= NearEqual(a_fp[0], 2. * a_x[0] * a_x[1], eps, eps);

	// compute the function g(x) = 2 * partial_x[0] f(x) = 4 * x[1]
	p = 1;
	CPPAD_TESTVECTOR(ADdouble) a_dx(n), a_g(1);
	a_dx[0] = 1.; a_dx[1] = 0.;
	a_fp    = F.Forward(p, a_dx);
	a_g[0]  = 2. * a_fp[0];
	CppAD::ADFun<double> G(a_x, a_g);

	// compute partial_x[1] g(x)
	CPPAD_TESTVECTOR(double)  xp(n), gp(1);
	p = 0;
	xp[0] = 4.; xp[1] = 5.;
	gp    = G.Forward(p, xp);
	ok   &= NearEqual(gp[0], 4. * xp[1], eps, eps);

	p = 1;
	xp[0] = 0.; xp[1] = 1.;
	gp    = G.Forward(p, xp);
	ok   &= NearEqual(gp[0], 4., eps, eps);

	return ok;
}

// f(x) = |x|^2 = .5 * ( x[0]^2 + ... + x[n-1]^2 )
template <class Type>
Type f_Two(CPPAD_TESTVECTOR(Type) &x)
{	Type sum;

	// check assignment of AD< AD<double> > = double
	sum  = .5;
	sum += .5;

	size_t i = x.size();
	while(i--)
		sum += x[i] * x[i];

	// check compound assignment AD< AD<double> > -= int
	sum -= 1;

	// check double * AD< AD<double> >
	return .5 * sum;
}

bool Two(void)
{	bool ok = true;                          // initialize test result
	double eps99 = 99.0 * std::numeric_limits<double>::epsilon();

	typedef CppAD::AD<double>   ADdouble;    // for one level of taping
	typedef CppAD::AD<ADdouble> ADDdouble;   // for two levels of taping
	size_t n = 5;                            // dimension for example
	size_t j;                                // a temporary index variable

	CPPAD_TESTVECTOR(double)       x(n);
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);

	// value of the independent variables
	for(j = 0; j < n; j++)
		a_x[j] = x[j] = double(j); // x[j] = j
	Independent(a_x);                  // a_x is indedendent for ADdouble
	for(j = 0; j < n; j++)
		aa_x[j] = a_x[j];          // track how aa_x depends on a_x
	CppAD::Independent(aa_x);          // aa_x is independent for ADDdouble

	// compute function
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);    // scalar valued function
	aa_f[0] = f_Two(aa_x);                   // has only one component

	// declare inner function (corresponding to ADDdouble calculation)
	CppAD::ADFun<ADdouble> a_F(aa_x, aa_f);

	// compute f'(x)
	size_t p = 1;                        // order of derivative of a_F
	CPPAD_TESTVECTOR(ADdouble) a_w(1);  // weight vector for a_F
	CPPAD_TESTVECTOR(ADdouble) a_df(n); // value of derivative
	a_w[0] = 1;                          // weighted function same as a_F
	a_df   = a_F.Reverse(p, a_w);        // gradient of f

	// declare outter function (corresponding to ADdouble calculation)
	CppAD::ADFun<double> df(a_x, a_df);

	// compute the d/dx of f'(x) * v = f''(x) * v
	CPPAD_TESTVECTOR(double) v(n);
	CPPAD_TESTVECTOR(double) ddf_v(n);
	for(j = 0; j < n; j++)
		v[j] = double(n - j);
	ddf_v = df.Reverse(p, v);

	// f(x)       = .5 * ( x[0]^2 + x[1]^2 + ... + x[n-1]^2 )
	// f'(x)      = (x[0], x[1], ... , x[n-1])
	// f''(x) * v = ( v[0], v[1],  ... , x[n-1] )
	for(j = 0; j < n; j++)
		ok &= CppAD::NearEqual(ddf_v[j], v[j], eps99, eps99);

	return ok;
}

# if CPPAD_HAS_ADOLC

bool adolc(void)
{	bool ok = true;                   // initialize test result
	double eps99 = 99.0 * std::numeric_limits<double>::epsilon();

	typedef adouble      ADdouble;         // for first level of taping
	typedef CppAD::AD<ADdouble> ADDdouble; // for second level of taping
	size_t n = 5;                          // number independent variables

	CPPAD_TESTVECTOR(double)       x(n);
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);

	// value of the independent variables
	int tag = 0;                         // Adolc setup
	int keep = 1;
	trace_on(tag, keep);
	size_t j;
	for(j = 0; j < n; j++)
	{	x[j] = double(j);           // x[j] = j
		a_x[j] <<= x[j];            // a_x is independent for ADdouble
	}
	for(j = 0; j < n; j++)
		aa_x[j] = a_x[j];          // track how aa_x depends on a_x
	CppAD::Independent(aa_x);          // aa_x is independent for ADDdouble

	// compute function
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);    // scalar valued function
	aa_f[0] = f_Two(aa_x);                   // has only one component

	// declare inner function (corresponding to ADDdouble calculation)
	CppAD::ADFun<ADdouble> a_F(aa_x, aa_f);

	// compute f'(x)
	size_t p = 1;                        // order of derivative of a_F
	CPPAD_TESTVECTOR(ADdouble) a_w(1);  // weight vector for a_F
	CPPAD_TESTVECTOR(ADdouble) a_df(n); // value of derivative
	a_w[0] = 1;                          // weighted function same as a_F
	a_df   = a_F.Reverse(p, a_w);        // gradient of f

	// declare outter function
	// (corresponding to the tape of adouble operations)
	double df_j;
	for(j = 0; j < n; j++)
		a_df[j] >>= df_j;
	trace_off();

	// compute the d/dx of f'(x) * v = f''(x) * v
	size_t m      = n;                     // # dependent in f'(x)
	double *v = CPPAD_NULL, *ddf_v = CPPAD_NULL;
	v     = CPPAD_TRACK_NEW_VEC(m, v);     // track v = new double[m]
	ddf_v = CPPAD_TRACK_NEW_VEC(n, ddf_v); // track ddf_v = new double[n]
	for(j = 0; j < n; j++)
		v[j] = double(n - j);
	fos_reverse(tag, int(m), int(n), v, ddf_v);

	// f(x)       = .5 * ( x[0]^2 + x[1]^2 + ... + x[n-1]^2 )
	// f'(x)      = (x[0], x[1], ... , x[n-1])
	// f''(x) * v = ( v[0], v[1],  ... , x[n-1] )
	for(j = 0; j < n; j++)
		ok &= CppAD::NearEqual(ddf_v[j], v[j], eps99, eps99);

	CPPAD_TRACK_DEL_VEC(v);                 // check usage of delete
	CPPAD_TRACK_DEL_VEC(ddf_v);
	return ok;
}

# endif // CPPAD_HAS_ADOLC

bool std_math(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::Independent;
	using CppAD::ADFun;
	double eps = std::numeric_limits<double>::epsilon();

	typedef AD<double>      ADdouble; // for first level of taping
	typedef AD<ADdouble>   ADDdouble; // for second level of taping
	size_t n = 1;         // number independent variables
	size_t m = 1;         // number dependent and independent variables

	CPPAD_TESTVECTOR(double)       x(n),   y(m);
	CPPAD_TESTVECTOR(ADdouble)    ax(n),  ay(m);
	CPPAD_TESTVECTOR(ADDdouble)  aax(n), aay(m);

	// create af(x) = tanh(x)
	aax[0] = 1.;
	Independent( aax );
	aay[0] = tanh(aax[0]);
	ADFun<ADdouble> af(aax, aay);

	// create g(x) = af(x)
	ax[0] = 1.;
	Independent( ax );
	ay = af.Forward(0, ax);
	ADFun<double> g(ax, ay);

	// evaluate h(x) = g(x)
	x[0] = 1.;
	y = g.Forward(0, x);

	// check result
	double check  = tanh(x[0]);
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	return ok;
}

// supress this test until ../bug/abs.sh is fixed
# ifdef CPPAD_NOT_DEFINED
bool fabs(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::Independent;
	using CppAD::ADFun;
	double eps = std::numeric_limits<double>::epsilon();

	typedef AD<double>      ADdouble; // for first level of taping
	typedef AD<ADdouble>   ADDdouble; // for second level of taping
	size_t n = 1;         // number independent variables
	size_t m = 1;         // number dependent and independent variables

	CPPAD_TESTVECTOR(double)       x(n),   y(m);
	CPPAD_TESTVECTOR(ADdouble)    ax(n),  ay(m);
	CPPAD_TESTVECTOR(ADDdouble)  aax(n), aay(m);

	// create af(x) = fabs(x)
	aax[0] = 1.;
	Independent( aax );
	aay[0] = fabs(aax[0]);
	ADFun<ADdouble> af(aax, aay);

	// create g(x) = af'(x)
	ax[0] = 1.;
	Independent( ax );
	ay = af.Jacobian(ax);
	ADFun<double> g(ax, ay);

	// evaluate g(x) at same x as recording
	x[0] = 1.;
	y = g.Forward(0, x);

	// check result
	double check  = 1.;
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	// evaluate g(x) at different x from recording
	// (but abs is an atomic operation so derivative should work)
	x[0] = -1.;
	y = g.Forward(0, x);

	// check result
	check  = -1.;
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	return ok;
}
# endif

} // END empty namespace

bool mul_level(void)
{	bool ok = true;
	ok     &= One();
	ok     &= Two();
# if CPPAD_HAS_ADOLC
	ok     &= adolc();
# endif
	ok     &= std_math();
# ifdef CPPAD_NOT_DEFINED
	ok     &= fabs();
# endif

	return ok;
}
<commit_msg>mul_level.cpp: include test of fabs.<commit_after>/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

// CPPAD_HAS_* defines
# include <cppad/configure.hpp>

# if CPPAD_HAS_ADOLC
# include <adolc/adouble.h>
# include <adolc/taping.h>
# include <adolc/interfaces.h>
// adouble definitions not in Adolc distribution and
// required in order to use CppAD::AD<adouble>
# include <cppad/example/base_adolc.hpp>
# endif

# include <cppad/cppad.hpp>
# include <limits>

namespace { // BEGIN empty namespace

bool One(void)
{	bool ok = true;                          // initialize test result
	using CppAD::NearEqual;
	double eps = 10. * std::numeric_limits<double>::epsilon();

	typedef CppAD::AD<double>   ADdouble;    // for one level of taping
	typedef CppAD::AD<ADdouble> ADDdouble;   // for two levels of taping
	size_t n = 2;                            // dimension for example

	// value of the independent variables
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);
	aa_x[0] = 1.; aa_x[1] = 3.; // test conversion double to AD< AD<double> >
	aa_x[0] = 2. * aa_x[0];     // test double * AD< AD<double> >
	CppAD::Independent(aa_x);

	// compute the function f(x) = 2 * x[0] * x[1]
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);
	aa_f[0] = 2. * aa_x[0] * aa_x[1];
	CppAD::ADFun<ADdouble> F(aa_x, aa_f);

	// value of the independent variables
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	a_x[0] = 2.; a_x[1] = 3.;
	Independent(a_x);

	// re-evaluate f(2, 3) (must get deepedence on a_x).
	size_t p = 0;
	CPPAD_TESTVECTOR(ADdouble) a_fp(1);
	a_fp    = F.Forward(p, a_x);
	ok     &= NearEqual(a_fp[0], 2. * a_x[0] * a_x[1], eps, eps);

	// compute the function g(x) = 2 * partial_x[0] f(x) = 4 * x[1]
	p = 1;
	CPPAD_TESTVECTOR(ADdouble) a_dx(n), a_g(1);
	a_dx[0] = 1.; a_dx[1] = 0.;
	a_fp    = F.Forward(p, a_dx);
	a_g[0]  = 2. * a_fp[0];
	CppAD::ADFun<double> G(a_x, a_g);

	// compute partial_x[1] g(x)
	CPPAD_TESTVECTOR(double)  xp(n), gp(1);
	p = 0;
	xp[0] = 4.; xp[1] = 5.;
	gp    = G.Forward(p, xp);
	ok   &= NearEqual(gp[0], 4. * xp[1], eps, eps);

	p = 1;
	xp[0] = 0.; xp[1] = 1.;
	gp    = G.Forward(p, xp);
	ok   &= NearEqual(gp[0], 4., eps, eps);

	return ok;
}

// f(x) = |x|^2 = .5 * ( x[0]^2 + ... + x[n-1]^2 )
template <class Type>
Type f_Two(CPPAD_TESTVECTOR(Type) &x)
{	Type sum;

	// check assignment of AD< AD<double> > = double
	sum  = .5;
	sum += .5;

	size_t i = x.size();
	while(i--)
		sum += x[i] * x[i];

	// check compound assignment AD< AD<double> > -= int
	sum -= 1;

	// check double * AD< AD<double> >
	return .5 * sum;
}

bool Two(void)
{	bool ok = true;                          // initialize test result
	double eps99 = 99.0 * std::numeric_limits<double>::epsilon();

	typedef CppAD::AD<double>   ADdouble;    // for one level of taping
	typedef CppAD::AD<ADdouble> ADDdouble;   // for two levels of taping
	size_t n = 5;                            // dimension for example
	size_t j;                                // a temporary index variable

	CPPAD_TESTVECTOR(double)       x(n);
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);

	// value of the independent variables
	for(j = 0; j < n; j++)
		a_x[j] = x[j] = double(j); // x[j] = j
	Independent(a_x);                  // a_x is indedendent for ADdouble
	for(j = 0; j < n; j++)
		aa_x[j] = a_x[j];          // track how aa_x depends on a_x
	CppAD::Independent(aa_x);          // aa_x is independent for ADDdouble

	// compute function
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);    // scalar valued function
	aa_f[0] = f_Two(aa_x);                   // has only one component

	// declare inner function (corresponding to ADDdouble calculation)
	CppAD::ADFun<ADdouble> a_F(aa_x, aa_f);

	// compute f'(x)
	size_t p = 1;                        // order of derivative of a_F
	CPPAD_TESTVECTOR(ADdouble) a_w(1);  // weight vector for a_F
	CPPAD_TESTVECTOR(ADdouble) a_df(n); // value of derivative
	a_w[0] = 1;                          // weighted function same as a_F
	a_df   = a_F.Reverse(p, a_w);        // gradient of f

	// declare outter function (corresponding to ADdouble calculation)
	CppAD::ADFun<double> df(a_x, a_df);

	// compute the d/dx of f'(x) * v = f''(x) * v
	CPPAD_TESTVECTOR(double) v(n);
	CPPAD_TESTVECTOR(double) ddf_v(n);
	for(j = 0; j < n; j++)
		v[j] = double(n - j);
	ddf_v = df.Reverse(p, v);

	// f(x)       = .5 * ( x[0]^2 + x[1]^2 + ... + x[n-1]^2 )
	// f'(x)      = (x[0], x[1], ... , x[n-1])
	// f''(x) * v = ( v[0], v[1],  ... , x[n-1] )
	for(j = 0; j < n; j++)
		ok &= CppAD::NearEqual(ddf_v[j], v[j], eps99, eps99);

	return ok;
}

# if CPPAD_HAS_ADOLC

bool adolc(void)
{	bool ok = true;                   // initialize test result
	double eps99 = 99.0 * std::numeric_limits<double>::epsilon();

	typedef adouble      ADdouble;         // for first level of taping
	typedef CppAD::AD<ADdouble> ADDdouble; // for second level of taping
	size_t n = 5;                          // number independent variables

	CPPAD_TESTVECTOR(double)       x(n);
	CPPAD_TESTVECTOR(ADdouble)   a_x(n);
	CPPAD_TESTVECTOR(ADDdouble) aa_x(n);

	// value of the independent variables
	int tag = 0;                         // Adolc setup
	int keep = 1;
	trace_on(tag, keep);
	size_t j;
	for(j = 0; j < n; j++)
	{	x[j] = double(j);           // x[j] = j
		a_x[j] <<= x[j];            // a_x is independent for ADdouble
	}
	for(j = 0; j < n; j++)
		aa_x[j] = a_x[j];          // track how aa_x depends on a_x
	CppAD::Independent(aa_x);          // aa_x is independent for ADDdouble

	// compute function
	CPPAD_TESTVECTOR(ADDdouble) aa_f(1);    // scalar valued function
	aa_f[0] = f_Two(aa_x);                   // has only one component

	// declare inner function (corresponding to ADDdouble calculation)
	CppAD::ADFun<ADdouble> a_F(aa_x, aa_f);

	// compute f'(x)
	size_t p = 1;                        // order of derivative of a_F
	CPPAD_TESTVECTOR(ADdouble) a_w(1);  // weight vector for a_F
	CPPAD_TESTVECTOR(ADdouble) a_df(n); // value of derivative
	a_w[0] = 1;                          // weighted function same as a_F
	a_df   = a_F.Reverse(p, a_w);        // gradient of f

	// declare outter function
	// (corresponding to the tape of adouble operations)
	double df_j;
	for(j = 0; j < n; j++)
		a_df[j] >>= df_j;
	trace_off();

	// compute the d/dx of f'(x) * v = f''(x) * v
	size_t m      = n;                     // # dependent in f'(x)
	double *v = CPPAD_NULL, *ddf_v = CPPAD_NULL;
	v     = CPPAD_TRACK_NEW_VEC(m, v);     // track v = new double[m]
	ddf_v = CPPAD_TRACK_NEW_VEC(n, ddf_v); // track ddf_v = new double[n]
	for(j = 0; j < n; j++)
		v[j] = double(n - j);
	fos_reverse(tag, int(m), int(n), v, ddf_v);

	// f(x)       = .5 * ( x[0]^2 + x[1]^2 + ... + x[n-1]^2 )
	// f'(x)      = (x[0], x[1], ... , x[n-1])
	// f''(x) * v = ( v[0], v[1],  ... , x[n-1] )
	for(j = 0; j < n; j++)
		ok &= CppAD::NearEqual(ddf_v[j], v[j], eps99, eps99);

	CPPAD_TRACK_DEL_VEC(v);                 // check usage of delete
	CPPAD_TRACK_DEL_VEC(ddf_v);
	return ok;
}

# endif // CPPAD_HAS_ADOLC

bool std_math(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::Independent;
	using CppAD::ADFun;
	double eps = std::numeric_limits<double>::epsilon();

	typedef AD<double>      ADdouble; // for first level of taping
	typedef AD<ADdouble>   ADDdouble; // for second level of taping
	size_t n = 1;         // number independent variables
	size_t m = 1;         // number dependent and independent variables

	CPPAD_TESTVECTOR(double)       x(n),   y(m);
	CPPAD_TESTVECTOR(ADdouble)    ax(n),  ay(m);
	CPPAD_TESTVECTOR(ADDdouble)  aax(n), aay(m);

	// create af(x) = tanh(x)
	aax[0] = 1.;
	Independent( aax );
	aay[0] = tanh(aax[0]);
	ADFun<ADdouble> af(aax, aay);

	// create g(x) = af(x)
	ax[0] = 1.;
	Independent( ax );
	ay = af.Forward(0, ax);
	ADFun<double> g(ax, ay);

	// evaluate h(x) = g(x)
	x[0] = 1.;
	y = g.Forward(0, x);

	// check result
	double check  = tanh(x[0]);
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	return ok;
}

bool fabs(void)
{	bool ok = true;
	using CppAD::AD;
	using CppAD::Independent;
	using CppAD::ADFun;
	double eps = std::numeric_limits<double>::epsilon();

	typedef AD<double>      ADdouble; // for first level of taping
	typedef AD<ADdouble>   ADDdouble; // for second level of taping
	size_t n = 1;         // number independent variables
	size_t m = 1;         // number dependent and independent variables

	CPPAD_TESTVECTOR(double)       x(n),   y(m);
	CPPAD_TESTVECTOR(ADdouble)    ax(n),  ay(m);
	CPPAD_TESTVECTOR(ADDdouble)  aax(n), aay(m);

	// create af(x) = fabs(x)
	aax[0] = 1.;
	Independent( aax );
	aay[0] = fabs(aax[0]);
	ADFun<ADdouble> af(aax, aay);

	// create g(x) = af'(x)
	ax[0] = 1.;
	Independent( ax );
	ay = af.Jacobian(ax);
	ADFun<double> g(ax, ay);

	// evaluate g(x) at same x as recording
	x[0] = 1.;
	y = g.Forward(0, x);

	// check result
	double check  = 1.;
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	// evaluate g(x) at different x from recording
	// (but abs is an atomic operation so derivative should work)
	x[0] = -1.;
	y = g.Forward(0, x);

	// check result
	check  = -1.;
	ok &= CppAD::NearEqual(y[0], check, eps, eps);

	return ok;
}

} // END empty namespace

bool mul_level(void)
{	bool ok = true;
	ok     &= One();
	ok     &= Two();
# if CPPAD_HAS_ADOLC
	ok     &= adolc();
# endif
	ok     &= std_math();
	ok     &= fabs();

	return ok;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "subprocess.hpp"
#include <cstring>

// Note: this works even for ffmpeg with image2pipe to get err and out stream!
int manual_subprocess(const char* const* cmd)
{
	struct subprocess_s process;
	if(subprocess_create(cmd, subprocess_option_enable_async | subprocess_option_inherit_environment | subprocess_option_no_window, &process) != 0)
		return -1;

	int nchars = 128, nerrchars = nchars * 2;
	char buf[nchars], errbuf[nerrchars];
	memset(buf, '\0', nchars);
	memset(errbuf, '\0', nerrchars);
	int ret2 = subprocess_read_stderr(&process, errbuf, nerrchars);
	if(ret2 == 0)
	{
		std::cout << "subprocess_read_stderr failure." << std::endl;
		return -1;
	}
	std::cout << "err ret:" << ret2 << std::endl;
	std::cout << "errbuf:" << errbuf << std::endl;
	int ret = subprocess_read_stdout(&process, buf, nchars); // struct subprocess_s *const process, char *const buffer,unsigned size);
	if(ret == 0) // TODO: this handling is missing in struct initialization for SPREAD
	{
		std::cout << "subprocess_read_stdout failure." << std::endl;
		return -1;
	}
	std::cout << "out ret:" << ret << std::endl;
	std::cout << "out buf:" << buf << std::endl;
	subprocess_destroy(&process);
	return 0;
}

int main(int argc,char** argv)
{
    std::cout << "Hello, world" << std::endl;
    //const char* cmd[]={"/usr/bin/ffmpeg",0}; // works if don't use errstream
	//const char *const cmd[] = {"/usr/bin/ffmpeg", "-v","24","-pix_fmts", 0};
    const char* cmd[] = {"/usr/bin/ffmpeg", "-i", "test.mp4", "-pix_fmt", "rgba", "-vcodec", "rawvideo", "-f", "image2pipe", "pipe:1", 0};

	manual_subprocess(cmd);

    Subprocess sp{cmd};
	/*if(sp.errstream.good())
		std::cout << "errorstream good!" << std::endl;
    std::cout << sp.errstream.rdbuf();
	*/
	if(sp.errstream.good())
		std::cout << "outstream good!" << std::endl;
    std::cout << sp.errstream.rdbuf();
    return 0;
}
<commit_msg>Updated subprocess test case to use new Subprocess.<commit_after>#include <iostream>
#include "subprocess.hpp"
#include <cstring>

// Note: this works even for ffmpeg with image2pipe to get err and out stream!
int manual_subprocess(const char* const* cmd)
{
	struct subprocess_s process;
	if(subprocess_create(cmd, subprocess_option_enable_async | subprocess_option_inherit_environment | subprocess_option_no_window, &process) != 0)
		return -1;

	int nchars = 128, nerrchars = nchars * 2;
	char buf[nchars], errbuf[nerrchars];
	memset(buf, '\0', nchars);
	memset(errbuf, '\0', nerrchars);
	int ret2 = subprocess_read_stderr(&process, errbuf, nerrchars);
	if(ret2 == 0)
	{
		std::cout << "subprocess_read_stderr failure." << std::endl;
		return -1;
	}
	std::cout << "err ret:" << ret2 << std::endl;
	std::cout << "errbuf:" << errbuf << std::endl;
	int ret = subprocess_read_stdout(&process, buf, nchars); // struct subprocess_s *const process, char *const buffer,unsigned size);
	if(ret == 0) // TODO: this handling is missing in struct initialization for SPREAD
	{
		std::cout << "subprocess_read_stdout failure." << std::endl;
		return -1;
	}
	std::cout << "out ret:" << ret << std::endl;
	std::cout << "out buf:" << buf << std::endl;
	subprocess_destroy(&process);
	return 0;
}

int manual_subprocess_class(const char* const* cmd)
{
    Subprocess sp{cmd};

	int nchars = 128, nerrchars = nchars * 2;
	char buf[nchars], errbuf[nerrchars];
	memset(buf, '\0', nchars);
	memset(errbuf, '\0', nerrchars);
	int ret2 = sp.read_from_stderr(errbuf, nerrchars);
	if(ret2 == 0)
	{
		std::cout << "subprocess_read_stderr completion of process, no data read." << std::endl;
		return -1;
	}
	std::cout << "err ret:" << ret2 << std::endl;
	std::cout << "errbuf:" << errbuf << std::endl;
	int ret = sp.read_from_stdout(buf, nchars); // struct subprocess_s *const process, char *const buffer,unsigned size);
	if(ret == 0) // TODO: this handling is missing in struct initialization for SPREAD
	{
		std::cout << "subprocess_read_stdout completion of process, no data read." << std::endl;
		return -1;
	}
	std::cout << "out ret:" << ret << std::endl;
	std::cout << "out buf:" << buf << std::endl;
	return 0;
}

int main(int argc,char** argv)
{
    std::cout << "Hello, world" << std::endl;
    //const char* cmd[]={"/usr/bin/ffmpeg",0}; // works if don't use errstream
	//const char *const cmd[] = {"/usr/bin/ffmpeg", "-v","24","-pix_fmts", 0};
    const char* cmd[] = {"/usr/bin/ffmpeg", "-i", "test.mp4", "-pix_fmt", "rgba", "-vcodec", "rawvideo", "-f", "image2pipe", "pipe:1", 0};

	manual_subprocess_class(cmd);
    return 0;
}
<|endoftext|>