<commit_before>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2017 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

#pragma once

#include "AFPlatform.hpp"

//Input param type
#ifndef IN
#define IN
#endif

//Output param type
#ifndef OUT
#define OUT
#endif

//Input and output param type
#ifndef INOUT
#define INOUT
#endif

#define ARRAY_CLEAR(v)              memset((v), 0x0, sizeof((v)))
#define MEMORY_CLEAR(v)             memset(&(v), 0x0, sizeof((v)))
#define MEMORY_CLEAR_POINTER(v)     memset((v), 0xx, sizeof(*(v)))
#define ARRAY_LENTGH(v)               (sizeof(v) / sizeof(v[0]))

#define MAX_NAME    256
#define MAX_BUF     256

#ifndef MAX_PATH
#define MAX_PATH    256
#endif

#define ARK_NEW new

#define ARK_GUID_POWER 100000
#define ARK_EPOCH 1288834974657L

#if ARK_PLATFORM == PLATFORM_WIN
//windows

inline uint32_t GetSystemTime()
{
    return ::GetTickCount();
}

#define ARK_SPRINTF sprintf_s
#define ARK_STRICMP _stricmp
#define ARK_SLEEP(s) Sleep(s)
#define ARK_STRNCPY strncpy_s
#define ARK_ASSERT(exp_, msg_, file_, func_)        \
    do                                              \
    {                                               \
        if (!(exp_))                                \
        {                                           \
            std::string strInfo("Message:");        \
            strInfo += msg_ + std::string(" don't exist or some warning") + std::string("\n\nFile:") + std::string(file_) + std::string("\n Function:") + func_;\
            MessageBox(0, TEXT(strInfo.c_str()), TEXT("Error_"#exp_), MB_RETRYCANCEL | MB_ICONERROR); \
        }                                           \
        assert(exp_);                               \
    } while (0);

#define ARK_EXPORT extern "C"  __declspec(dllexport)

#else
//linux

inline uint32_t GetSystemTime()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
};

#define ARK_SPRINTF snprintf
#define ARK_STRICMP strcasecmp
#define ARK_SLEEP(s) usleep(s)
#define ARK_STRNCPY strncpy
#define ARK_ASSERT(exp_, msg_, file_, func_)        \
    do                                              \
    {                                               \
        if ((exp_)) break;                          \
        assert(exp_);                               \
    } while (0);

#define ARK_EXPORT extern "C" __attribute ((visibility("default")))

#endif

#define ARK_ASSERT_RET_VAL(exp_, val)   \
    do                                  \
    {                                   \
        if ((exp_)) break;              \
        assert(exp_);                   \
        return val;                     \
    } while (0);

#define ARK_ASSERT_BREAK(exp_)          \
    if (!(exp_))                        \
    {                                   \
        assert(exp_);                   \
        break;                          \
    }                                   \
    else {}

#define ARK_ASSERT_CONTINUE(exp_)       \
    if (!(exp_))                        \
    {                                   \
        assert(exp_);                   \
        continue;                       \
    }                                   \
    else {}

#define ARK_ASSERT_RET_NONE(exp_)       \
    do                                  \
    {                                   \
        if ((exp_)) break;              \
        assert(exp_);                   \
        return;                         \
    } while (0);

#define ARK_ASSERT_NO_EFFECT(exp_)      \
    do                                  \
    {                                   \
        if (exp_) break;                \
        assert(exp_);                   \
    } while(0)

#if defined(USE_BOOST)
#  include <boost/lexical_cast.hpp>
#  define ARK_LEXICAL_CAST boost::lexical_cast
#  define ARK_SHARE_PTR boost::shared_ptr
#else
#  include "common/lexical_cast.hpp"
#  define ARK_LEXICAL_CAST lexical_cast
#  define ARK_SHARE_PTR std::shared_ptr
#endif

inline bool IsZeroFloat(const float value)
{
    return std::abs(value) < std::numeric_limits<float>::epsilon();
}

inline bool IsZeroDouble(const double value)
{
    return std::abs(value) < std::numeric_limits<double>::epsilon();
}

inline bool IsFloatEqual(const float lhs, const float rhs)
{
    return std::abs(lhs - rhs) < std::numeric_limits<float>::epsilon();
}

inline bool IsDoubleEqual(const double lhs, const double rhs)
{
    return std::abs(lhs - rhs) < std::numeric_limits<double>::epsilon();
}

#if ARK_PLATFORM == PLATFORM_WIN
#define PROTOBUF_USE_DLLS
#endif

#define ARK_SINGLETON_INIT(TYPE) template<> TYPE* Singleton<TYPE>::instance_ = 0;
/*
#if ARK_PLATFORM == PLATFORM_WIN
#  if defined(ARK_USE_TCMALLOC)
#  undef ARK_USE_TCMALLOC
#  endif
#else
#define ARK_USE_TCMALLOC
#endif
*/
template<typename T>
bool ARK_FROM_STR(const std::string& strValue, T& nValue)
{
    try
    {
        nValue = ARK_LEXICAL_CAST<T>(strValue);
        return true;
    }
    catch(...)
    {
        return false;
    }

    return false;
}

template<typename T>
bool ARK_TO_STR(std::string& strValue, const T& nValue)
{
    try
    {
        strValue = ARK_LEXICAL_CAST<std::string>(nValue);
        return true;
    }
    catch(...)
    {
        return false;
    }

    return false;
}

// clear player data time
#define CLEAR_HOUR 5

#if __cplusplus < 201402L
// note: this implementation does not disable this overload for array types
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif<commit_msg>change make_unique<commit_after>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2017 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

#pragma once

#include "AFPlatform.hpp"

//Input param type
#ifndef IN
#define IN
#endif

//Output param type
#ifndef OUT
#define OUT
#endif

//Input and output param type
#ifndef INOUT
#define INOUT
#endif

#define ARRAY_CLEAR(v)              memset((v), 0x0, sizeof((v)))
#define MEMORY_CLEAR(v)             memset(&(v), 0x0, sizeof((v)))
#define MEMORY_CLEAR_POINTER(v)     memset((v), 0xx, sizeof(*(v)))
#define ARRAY_LENTGH(v)               (sizeof(v) / sizeof(v[0]))

#define MAX_NAME    256
#define MAX_BUF     256

#ifndef MAX_PATH
#define MAX_PATH    256
#endif

#define ARK_NEW new

#define ARK_GUID_POWER 100000
#define ARK_EPOCH 1288834974657L

#if ARK_PLATFORM == PLATFORM_WIN
//windows

inline uint32_t GetSystemTime()
{
    return ::GetTickCount();
}

#define ARK_SPRINTF sprintf_s
#define ARK_STRICMP _stricmp
#define ARK_SLEEP(s) Sleep(s)
#define ARK_STRNCPY strncpy_s
#define ARK_ASSERT(exp_, msg_, file_, func_)        \
    do                                              \
    {                                               \
        if (!(exp_))                                \
        {                                           \
            std::string strInfo("Message:");        \
            strInfo += msg_ + std::string(" don't exist or some warning") + std::string("\n\nFile:") + std::string(file_) + std::string("\n Function:") + func_;\
            MessageBox(0, TEXT(strInfo.c_str()), TEXT("Error_"#exp_), MB_RETRYCANCEL | MB_ICONERROR); \
        }                                           \
        assert(exp_);                               \
    } while (0);

#define ARK_EXPORT extern "C"  __declspec(dllexport)

#else
//linux

inline uint32_t GetSystemTime()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
};

#define ARK_SPRINTF snprintf
#define ARK_STRICMP strcasecmp
#define ARK_SLEEP(s) usleep(s)
#define ARK_STRNCPY strncpy
#define ARK_ASSERT(exp_, msg_, file_, func_)        \
    do                                              \
    {                                               \
        if ((exp_)) break;                          \
        assert(exp_);                               \
    } while (0);

#define ARK_EXPORT extern "C" __attribute ((visibility("default")))

#endif

#define ARK_ASSERT_RET_VAL(exp_, val)   \
    do                                  \
    {                                   \
        if ((exp_)) break;              \
        assert(exp_);                   \
        return val;                     \
    } while (0);

#define ARK_ASSERT_BREAK(exp_)          \
    if (!(exp_))                        \
    {                                   \
        assert(exp_);                   \
        break;                          \
    }                                   \
    else {}

#define ARK_ASSERT_CONTINUE(exp_)       \
    if (!(exp_))                        \
    {                                   \
        assert(exp_);                   \
        continue;                       \
    }                                   \
    else {}

#define ARK_ASSERT_RET_NONE(exp_)       \
    do                                  \
    {                                   \
        if ((exp_)) break;              \
        assert(exp_);                   \
        return;                         \
    } while (0);

#define ARK_ASSERT_NO_EFFECT(exp_)      \
    do                                  \
    {                                   \
        if (exp_) break;                \
        assert(exp_);                   \
    } while(0)

#if defined(USE_BOOST)
#  include <boost/lexical_cast.hpp>
#  define ARK_LEXICAL_CAST boost::lexical_cast
#  define ARK_SHARE_PTR boost::shared_ptr
#else
#  include "common/lexical_cast.hpp"
#  define ARK_LEXICAL_CAST lexical_cast
#  define ARK_SHARE_PTR std::shared_ptr
#endif

inline bool IsZeroFloat(const float value)
{
    return std::abs(value) < std::numeric_limits<float>::epsilon();
}

inline bool IsZeroDouble(const double value)
{
    return std::abs(value) < std::numeric_limits<double>::epsilon();
}

inline bool IsFloatEqual(const float lhs, const float rhs)
{
    return std::abs(lhs - rhs) < std::numeric_limits<float>::epsilon();
}

inline bool IsDoubleEqual(const double lhs, const double rhs)
{
    return std::abs(lhs - rhs) < std::numeric_limits<double>::epsilon();
}

#if ARK_PLATFORM == PLATFORM_WIN
#define PROTOBUF_USE_DLLS
#endif

#define ARK_SINGLETON_INIT(TYPE) template<> TYPE* Singleton<TYPE>::instance_ = 0;
/*
#if ARK_PLATFORM == PLATFORM_WIN
#  if defined(ARK_USE_TCMALLOC)
#  undef ARK_USE_TCMALLOC
#  endif
#else
#define ARK_USE_TCMALLOC
#endif
*/
template<typename T>
bool ARK_FROM_STR(const std::string& strValue, T& nValue)
{
    try
    {
        nValue = ARK_LEXICAL_CAST<T>(strValue);
        return true;
    }
    catch(...)
    {
        return false;
    }

    return false;
}

template<typename T>
bool ARK_TO_STR(std::string& strValue, const T& nValue)
{
    try
    {
        strValue = ARK_LEXICAL_CAST<std::string>(nValue);
        return true;
    }
    catch(...)
    {
        return false;
    }

    return false;
}

// clear player data time
#define CLEAR_HOUR 5

#if __cplusplus < 201402L

namespace std
{
    // note: this implementation does not disable this overload for array types
    template<typename T, typename... Args>
    unique_ptr<T> make_unique(Args&&... args)
    {
        return unique_ptr<T>(new T(std::forward<Args>(args)...));
    }
}

#endif<|endoftext|>


<commit_before>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"
#include "Constants.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
	float color_weight;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

///
/// Create a quadrilateral with clockwise vertices abcd.
/// Maps to frame at time and a slice of the video frame.
///
void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice )
{
	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },

		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },
		Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f }
	} );

}

/// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut.
void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) )
{
	auto rings = time_bands;
	auto segments = 64;

	// Generate cartesian position.
	auto calc_pos = [=] (int r, int s) {
		auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f );
		auto radius = mix( inner_radius, outer_radius, distance );
		auto t = (float) s / segments;
		auto x = cos( t * Tau ) * radius;
		auto y = sin( t * Tau ) * radius;
		return vec3( x, 0, y ) + center;
	};

	// Generate texture coordinate mirrored at halfway point.
	auto calc_tc = [=] (int r, int s) {
		auto t = (float) s / segments;
		if( t < 1 ) {
			t = glm::fract( t * repeats );
		}
		// mirror copies
		t = std::abs( t - 0.5f ) * 2.0f;
		auto tc = vec2(0);
		// Repeat t with mirroring
		// insetting the texture coordinates minimizes edge color flashing.
		tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t );
		tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x );
		return tc;
	};

	// Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2)
	auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) {
		auto deform_scaling = 0.0f;
		auto pos = calc_pos(r, s);
		auto tc = calc_tc(r, s);
		auto color_tc = calc_tc( provoking.x, provoking.y );
		auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f );
		if (time_bands > 1) {
			time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands );
		}
		vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } );
	};

	// Create triangles for flat shading
	for( auto r = 0; r < rings; r += 1 )
	{
		for( auto s = 0; s < segments; s += 1 )
		{
			auto provoking = ivec2(r, s);
			add_vert( r, s, provoking );
			add_vert( r, s + 1, provoking );
			add_vert( r + 1, s + 1, provoking );

			add_vert( r, s, provoking );
			add_vert( r + 1, s, provoking );
			add_vert( r + 1, s + 1, provoking );
		}
	}
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto normal = vec3( 0, 1, 0 );

	auto inner = 0.28f;
	auto outer = 2.4f;

	struct Params {
		float repeats;
		float frames;
		float color_weight;
		vec2	insets;
	};

	auto params = std::vector<Params> {
		{ 2, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 4, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 6, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 12, 2, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 3, 0.1f, vec2( 0.05, 0.0875f ) },
		{ 8, 6, 0.3f, vec2( 0.05, 0.0875f ) },
		{ 10, 12, 0.5f, vec2( 0.05, 0.0875f ) },
		{ 8, 24, 0.8f, vec2( 0.05, 0.0875f ) }
	};

	auto center = vec3( 0, -4.4f, 0 );

	for( auto i = 0; i < params.size(); i += 1 )
	{
		auto &p = params.at( i );
		auto copies = p.repeats;
		auto t = (i + 0.0f) / params.size();
		auto t2 = (i + 1.0f) / params.size();
		auto r1 = mix( inner, outer, t );
		auto r2 = mix( inner, outer, t2 );
		addRing( vertices, center, normal, r1, r2, i * 2 + 1.0f, p.frames, copies, p.color_weight, p.insets );
	}

	auto last_frame = params.size() * 2 + 4.0f; // actually some overlap
	auto remaining_frames = 64.0f - last_frame;
	addRing( vertices, center, normal, outer, outer + 1.6f, last_frame, remaining_frames, 1, 1.0f );

	// Deform stuff
//	/*
	auto min_distance = inner;
	auto max_distance = outer + 4.0f;
	for( auto &v : vertices ) {
		auto distance = lmap<float>( glm::clamp( length( v.position ), min_distance, max_distance ), min_distance, max_distance, 0.0f, 1.0f );
		// pos is on a radial axis, rotate it 90 degrees to bend along length
		auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) );
		auto theta = mix( 0.0f, -(float)Tau / 4.0f, distance );
		auto xf = glm::rotate( theta, axis );
		v.normal = vec3(xf * vec4(v.normal, 0.0f));
//		v.deform_scaling = mix( 0.0f, 4.0f, distance );
		v.position = vec3(xf * vec4(v.position, 1.0f));
	}
//	*/

	// Plug center
	auto h = vec3( inner, 0, inner ) * 1.96f;
	auto c = center;
	addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 1, 1, 0, 0 ) );

	auto rotation = glm::rotate<float>( Tau * 0.25f, vec3( 0, 0, 1 ) );
	for( auto &v : vertices ) {
		v.position = vec3( rotation * vec4(v.position, 1.0f) );
	}

	auto copy = vertices;
	rotation = glm::rotate<float>( Tau * 0.5f, vec3( 0, 1, 0 ) );
	for( auto &v : copy ) {
		v.position = vec3( rotation * vec4(v.position, 1.0f) );
	}

	vertices.insert( vertices.end(), copy.begin(), copy.end() );

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<commit_msg>Better mirroring and more faces.<commit_after>//
//  Landscape.cpp
//
//  Created by Soso Limited on 5/26/15.
//
//

#include "Landscape.h"

#include "cinder/Log.h"
#include "Constants.h"

using namespace soso;
using namespace cinder;

namespace {

struct alignas(16) Vertex {
	vec3	position;
	vec3	normal;
	vec2	tex_coord;
	vec2	color_tex_coord;
	float deform_scaling;
	float frame_offset;
	float color_weight;
};

const auto kVertexLayout = ([] {
		auto layout = geom::BufferLayout();
		layout.append( geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position) );
		layout.append( geom::Attrib::NORMAL, 3, sizeof(Vertex), offsetof(Vertex, normal) );
		layout.append( geom::Attrib::TEX_COORD_0, 2, sizeof(Vertex), offsetof(Vertex, tex_coord) );
		layout.append( geom::Attrib::TEX_COORD_1, 2, sizeof(Vertex), offsetof(Vertex, color_tex_coord) );
		layout.append( geom::Attrib::CUSTOM_0, 1, sizeof(Vertex), offsetof(Vertex, deform_scaling) );
		layout.append( geom::Attrib::CUSTOM_1, 1, sizeof(Vertex), offsetof(Vertex, frame_offset) );
		layout.append( geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, color_weight) );
		return layout;
	} ());

const auto kVertexMapping = ([] {
		return gl::Batch::AttributeMapping{ { geom::Attrib::CUSTOM_0, "DeformScaling" }, { geom::Attrib::CUSTOM_1, "FrameOffset" }, { geom::Attrib::CUSTOM_2, "ColorWeight" } };
	} ());

// Load a shader and handle exceptions. Return nullptr on failure.
gl::GlslProgRef loadShader( const fs::path &iVertex, const fs::path &iFragment )
{
	try {
		auto shader_format = gl::GlslProg::Format()
			.vertex( app::loadAsset( iVertex ) )
			.fragment( app::loadAsset( iFragment ) );

		return gl::GlslProg::create( shader_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error loading shader: " << exc.what() );
	}

	return nullptr;
}

///
/// Create a quadrilateral with clockwise vertices abcd.
/// Maps to frame at time and a slice of the video frame.
///
void addQuad( std::vector<Vertex> &vertices, const vec3 &a, const vec3 &b, const vec3 &c, const vec3 &d, float time, const Rectf &slice )
{
	auto normal = vec3( 0, 1, 0 );
	auto deform_scaling = 0.0f;

	vertices.insert( vertices.end(), {
		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ b, normal, slice.getUpperRight(), slice.getUpperRight(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },

		Vertex{ a, normal, slice.getUpperLeft(), slice.getUpperLeft(), deform_scaling, time, 0.0f },
		Vertex{ c, normal, slice.getLowerRight(), slice.getLowerRight(), deform_scaling, time, 0.0f },
		Vertex{ d, normal, slice.getLowerLeft(), slice.getLowerLeft(), deform_scaling, time, 0.0f }
	} );

}

/// Add a ring of geometry containing a given number of time bands (slitscanning effect) and repeats around the donut.
void addRing( std::vector<Vertex> &vertices, const vec3 &center, const vec3 &normal, float inner_radius, float outer_radius, float time_offset, int time_bands, int repeats, float color_weight, const vec2 &texture_insets = vec2( 0.05, 0.0875f ) )
{
	auto rings = time_bands;
	auto segments = 64;

	// Generate cartesian position.
	auto calc_pos = [=] (int r, int s) {
		auto distance = lmap<float>( r, 0, rings, 0.0f, 1.0f );
		auto radius = mix( inner_radius, outer_radius, distance );
		auto t = (float) s / segments;
		auto x = cos( t * Tau ) * radius;
		auto y = sin( t * Tau ) * radius;
		return vec3( x, 0, y ) + center;
	};

	// Generate texture coordinate mirrored at halfway point.
	auto calc_tc = [=] (int r, int s) {
		auto t = (float) s / segments;
		if( t < 1 ) {
			t = glm::fract( t * repeats );
		}
		// mirror copies
		t = std::abs( t - 0.5f ) * 2.0f;
		auto tc = vec2(0);
		// Repeat t with mirroring
		// insetting the texture coordinates minimizes edge color flashing.
		tc.y = mix( texture_insets.y, 1.0f - texture_insets.y, t );
		tc.x = lmap<float>( r, 0, rings, 1.0f - texture_insets.x, texture_insets.x );
		return tc;
	};

	// Add a vertex to texture (color_tc parameter allows us to do flat shading in ES2)
	auto add_vert = [=,&vertices] (int r, int s, const ivec2 &provoking) {
		auto deform_scaling = 0.0f;
		auto pos = calc_pos(r, s);
		auto tc = calc_tc(r, s);
		auto color_tc = calc_tc( provoking.x, provoking.y );
		auto time = time_offset; // + lmap<float>( r, 0, rings, 0.0f, 1.0f / 64.0f );
		if (time_bands > 1) {
			time += lmap<float>( provoking.x, 0.0f, rings, 0.0f, time_bands );
		}
		vertices.push_back( Vertex{ pos, normal, tc, color_tc, deform_scaling, time, color_weight } );
	};

	// Create triangles for flat shading
	for( auto r = 0; r < rings; r += 1 )
	{
		for( auto s = 0; s < segments; s += 1 )
		{
			auto provoking = ivec2(r, s);
			add_vert( r, s, provoking );
			add_vert( r, s + 1, provoking );
			add_vert( r + 1, s + 1, provoking );

			add_vert( r, s, provoking );
			add_vert( r + 1, s, provoking );
			add_vert( r + 1, s + 1, provoking );
		}
	}
}

} // namespace

void Landscape::setup()
{
	auto shader = loadShader( "landscape.vs", "landscape.fs" );

	std::vector<Vertex> vertices;

	auto normal = vec3( 0, 1, 0 );

	auto inner = 0.28f;
	auto outer = 2.4f;

	struct Params {
		float repeats;
		float frames;
		float color_weight;
		vec2	insets;
	};

	auto params = std::vector<Params> {
		{ 2, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 4, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 6, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 8, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 1, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 12, 2, 0.0f, vec2( 0.05, 0.0875f ) },
		{ 10, 3, 0.1f, vec2( 0.05, 0.0875f ) },
		{ 8, 6, 0.3f, vec2( 0.05, 0.0875f ) },
		{ 10, 12, 0.5f, vec2( 0.05, 0.0875f ) },
		{ 8, 24, 0.8f, vec2( 0.05, 0.0875f ) }
	};

	auto center = vec3( 0, -4.4f, 0 );

	for( auto i = 0; i < params.size(); i += 1 )
	{
		auto &p = params.at( i );
		auto copies = p.repeats;
		auto t = (i + 0.0f) / params.size();
		auto t2 = (i + 1.0f) / params.size();
		auto r1 = mix( inner, outer, t );
		auto r2 = mix( inner, outer, t2 );
		addRing( vertices, center, normal, r1, r2, i * 2 + 1.0f, p.frames, copies, p.color_weight, p.insets );
	}

	auto last_frame = params.size() * 2 + 4.0f; // actually some overlap
	auto remaining_frames = 64.0f - last_frame;
	addRing( vertices, center, normal, outer, outer + 1.6f, last_frame, remaining_frames, 2, 1.0f );

	// Deform stuff
//	/*
	auto min_distance = inner;
	auto max_distance = outer + 4.0f;
	for( auto &v : vertices ) {
		auto distance = lmap<float>( glm::clamp( length( v.position ), min_distance, max_distance ), min_distance, max_distance, 0.0f, 1.0f );
		// pos is on a radial axis, rotate it 90 degrees to bend along length
		auto axis = glm::rotate( glm::angleAxis( (float)Tau / 4.0f, vec3(0, 1, 0) ), normalize(v.position) );
		auto theta = mix( 0.0f, -(float)Tau / 4.0f, distance );
		auto xf = glm::rotate( theta, axis );
		v.normal = vec3(xf * vec4(v.normal, 0.0f));
//		v.deform_scaling = mix( 0.0f, 4.0f, distance );
		v.position = vec3(xf * vec4(v.position, 1.0f));
	}
//	*/

	// Plug center
	auto h = vec3( inner, 0, inner ) * 1.96f;
	auto c = center;
	addQuad( vertices, c + (h * vec3(-1, 0, -1)), c + (h * vec3(1, 0, -1)), c + (h * vec3(1, 0, 1)), c + (h * vec3(-1, 0, 1)), 0.0f, Rectf( 1, 1, 0, 0 ) );

	auto rotation = glm::rotate<float>( Tau * 0.25f, vec3( 0, 0, 1 ) );
	for( auto &v : vertices ) {
		v.position = vec3( rotation * vec4(v.position, 1.0f) );
	}

	auto copy = vertices;
	auto mirror = glm::angleAxis<float>( Tau * 0.5f, vec3( 0, 1, 0 ) ) * glm::angleAxis<float>( Tau * 0.25f, vec3( 1, 0, 0 ) );
	rotation = glm::mat4( mirror ); // glm::rotate<float>( Tau * 0.5f, vec3( 0, 1, 0 ) );
	for( auto &v : copy ) {
		v.position = vec3( rotation * vec4(v.position, 1.0f) );
	}

	vertices.insert( vertices.end(), copy.begin(), copy.end() );

	auto vbo = gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW );
	auto mesh = gl::VboMesh::create( vertices.size(), GL_TRIANGLES, {{ kVertexLayout, vbo }} );
	batch = gl::Batch::create( mesh, shader, kVertexMapping );
}

void Landscape::setTextureUnits( uint8_t iClearUnit, uint8_t iBlurredUnit )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uClearTexture", iClearUnit );
	shader->uniform( "uBlurredTexture", iBlurredUnit );
}

void Landscape::draw( float iFrameOffset )
{
	auto &shader = batch->getGlslProg();
	shader->uniform( "uCurrentFrame", iFrameOffset );

	batch->draw();
}
<|endoftext|>


<commit_before>
#include "AliHBTReaderITSv1.h"
#include "AliHBTEvent.h"
#include "AliHBTRun.h"
#include "AliHBTParticle.h"
#include "AliHBTParticleCut.h"

#include <iostream.h>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>
#include <TObjArray.h>
#include <TParticle.h>
#include <TString.h>
#include <TObjString.h>

#include <AliRun.h>
#include <AliMagF.h>
#include <AliKalmanTrack.h>
#include <AliITSIOTrack.h>

ClassImp(AliHBTReaderITSv1)
/********************************************************************/

AliHBTReaderITSv1::
AliHBTReaderITSv1(const Char_t* tracksfilename,const Char_t* galicefilename):
                 fITSTracksFileName(tracksfilename),fGAliceFileName(galicefilename)
 {
     fParticles = new AliHBTRun();
     fTracks    = new AliHBTRun();
     fIsRead = kFALSE;
 }
/********************************************************************/

AliHBTReaderITSv1::
AliHBTReaderITSv1(TObjArray* dirs, const Char_t* tracksfilename,const Char_t* galicefilename):
                 AliHBTReader(dirs),
                 fITSTracksFileName(tracksfilename),fGAliceFileName(galicefilename)
 {
   fParticles = new AliHBTRun();
   fTracks    = new AliHBTRun();
   fIsRead    = kFALSE;
 }
/********************************************************************/

AliHBTReaderITSv1::~AliHBTReaderITSv1()
{
   delete fParticles;
   delete fTracks;
}
/********************************************************************/

AliHBTEvent* AliHBTReaderITSv1::GetParticleEvent(Int_t n)
 {
 //returns Nth event with simulated particles
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetParticleEvent","Error in reading");
       return 0x0;
     }

   return fParticles->GetEvent(n);
 }
/********************************************************************/

AliHBTEvent* AliHBTReaderITSv1::GetTrackEvent(Int_t n)
 {
 //returns Nth event with reconstructed tracks
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetTrackEvent","Error in reading");
       return 0x0;
     }
   return fTracks->GetEvent(n);
 }
/********************************************************************/

Int_t AliHBTReaderITSv1::GetNumberOfPartEvents()
 {
 //returns number of events of particles
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetNumberOfPartEvents","Error in reading");
       return 0;
     }
   return fParticles->GetNumberOfEvents();
 }

/********************************************************************/
Int_t AliHBTReaderITSv1::GetNumberOfTrackEvents()
 {
 //returns number of events of tracks
  if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetNumberOfTrackEvents","Error in reading");
       return 0;
     }
  return fTracks->GetNumberOfEvents();
 }
/********************************************************************/

Int_t AliHBTReaderITSv1::Read(AliHBTRun* particles, AliHBTRun *tracks)
{
 Int_t Nevents = 0;
 AliITSIOTrack *iotrack=new AliITSIOTrack;
 Int_t currentdir = 0;
 Int_t Ndirs;

 if (fDirs)
  {
    Ndirs = fDirs->GetEntries();
  }
 else
  {
    Ndirs = 0;
  }

 do //do while is good even if
  {
   TFile* gAliceFile = OpenGAliceFile(currentdir);
   if(gAliceFile == 0x0)
    {
       Error("Read","Can not open the file with gAlice");
       delete iotrack;
       return 1;
    }
   TFile *file = OpenTrackFile(currentdir);
   if(file == 0x0)
    {
       Error("Read","Can not open the file with ITS tracks V1");
       delete iotrack;
       return 2;
    }

   if (gAlice->TreeE())//check if tree E exists
     {
      Nevents = (Int_t)gAlice->TreeE()->GetEntries();//if yes get number of events in gAlice
      cout<<"________________________________________________________\n";
      cout<<"Found "<<Nevents<<" event(s) in directory "<<GetDirName(currentdir)<<endl;
      cout<<"Setting Magnetic Field. Factor is "<<gAlice->Field()->Factor()<<endl;
      AliKalmanTrack::SetConvConst(100/0.299792458/0.2/gAlice->Field()->Factor());
     }
    else
     {//if not return an error
       Error("Read","Can not find Header tree (TreeE) in gAlice");
       delete iotrack;
       return 4;
     }

   char tname[30];
   Int_t totalNevents = 0;
   for (Int_t currentEvent = 0; currentEvent < Nevents; currentEvent++)
    {
      cout<<"Reading Event "<<currentEvent<<endl;

      sprintf(tname,"TreeT%d",currentEvent);
      file->cd();
      TTree *tracktree=(TTree*)file->Get(tname);
      TBranch *tbranch=tracktree->GetBranch("ITStracks");
      tbranch->SetAddress(&iotrack);

      gAliceFile->cd();
      gAlice->GetEvent(currentEvent);
      gAlice->Particles();

      Int_t nentr=(Int_t)tracktree->GetEntries();

      for (Int_t i=0; i<nentr; i++)
       {

        tracktree->GetEvent(i);
        if(!iotrack) continue;
        Int_t label = iotrack->GetLabel();
        if (label < 0)
         {
           continue;
           delete iotrack;
         }
        TParticle *p = (TParticle*)gAlice->Particle(label);
        if(!p)
         {
           Warning("Read","Can not get particle with label &d",label);
           continue;
         }
        if(Pass(p->GetPdgCode())) continue; //check if we are intersted with particles of this type
                                           //if not take next partilce

        AliHBTParticle* part = new AliHBTParticle(*p);
        if(Pass(part)) { delete part; continue;}//check if meets all criteria of any of our cuts
                                                //if it does not delete it and take next good track

        Double_t px=iotrack->GetPx();
        Double_t py=iotrack->GetPy();
        Double_t pz=iotrack->GetPz();
        Double_t mass = p->GetMass();
        Double_t tEtot = TMath::Sqrt(px*px + py*py + pz*pz + mass*mass);//total energy of the track

        Double_t x= iotrack->GetX();
        Double_t y= iotrack->GetY();
        Double_t z= iotrack->GetZ();

        AliHBTParticle* track = new AliHBTParticle(p->GetPdgCode(), px, py , pz, tEtot, x, y, z, 0.);
        if(Pass(track)) { delete  track;continue;}//check if meets all criteria of any of our cuts
                                                  //if it does not delete it and take next good track

        particles->AddParticle(totalNevents,part);//put track and particle on the run
        tracks->AddParticle(totalNevents,track);
       }//end loop over tracks in the event

       totalNevents++;

     }//end of loop over events in current directory

    gAliceFile->Close();
    delete gAliceFile;
    gAliceFile = 0;

    file->Close();
    delete file;
    file = 0;

   }while(currentdir < Ndirs);//end of loop over directories specified in fDirs Obj Array

  delete iotrack;
  fIsRead = kTRUE;
  return 0;

 }
/********************************************************************/

TFile* AliHBTReaderITSv1::OpenTrackFile(Int_t ndir)
{
//opens files to be read for given directoru nomber in fDirs Array
   const TString& dirname = GetDirName(ndir);
   if (dirname == "")
    {
      Error("OpenGAliceFile","Can not get directory name");
      return 0x0;
    }
   TString filename = dirname + "/" + fITSTracksFileName;
   TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename.Data());
   if (!file) file = new TFile(filename.Data());

   if (!file)
    {
      Error("Read","Can not open file %s",filename.Data());
      return 0x0;
    }
   if (!file->IsOpen())
    {
      Error("Read","Can not open file %s",filename.Data());
      return 0x0;
    }

   return file;
}

/********************************************************************/
TFile* AliHBTReaderITSv1::OpenGAliceFile(Int_t ndir)
{
  const TString& dirname = GetDirName(ndir);
   if (dirname == "")
    {
      Error("OpenGAliceFile","Can not get directory name");
      return 0x0;
    }

  TString filename = dirname + "/" + fGAliceFileName;

  TFile* gAliceFile = TFile::Open(filename.Data());
  if ( gAliceFile== 0x0)
   {
     Error("OpenFiles","Can't open file named %s",filename.Data());
     return 0x0;
   }
  if (!gAliceFile->IsOpen())
   {
     Error("OpenFiles","Can't open file named %s",filename.Data());
     return 0x0;
   }

  if (!(gAlice=(AliRun*)gAliceFile->Get("gAlice")))
   {
     Error("OpenFiles","gAlice have not been found on %s !\n",filename.Data());
     gAliceFile->Close();
     delete gAliceFile;
     return 0x0;
   }

  return gAliceFile;
}

/********************************************************************/
/********************************************************************/

<commit_msg>Infinite loop in Read()<commit_after>
#include "AliHBTReaderITSv1.h"
#include "AliHBTEvent.h"
#include "AliHBTRun.h"
#include "AliHBTParticle.h"
#include "AliHBTParticleCut.h"

#include <iostream.h>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>
#include <TObjArray.h>
#include <TParticle.h>
#include <TString.h>
#include <TObjString.h>

#include <AliRun.h>
#include <AliMagF.h>
#include <AliKalmanTrack.h>
#include <AliITSIOTrack.h>

ClassImp(AliHBTReaderITSv1)
/********************************************************************/

AliHBTReaderITSv1::
AliHBTReaderITSv1(const Char_t* tracksfilename,const Char_t* galicefilename):
                 fITSTracksFileName(tracksfilename),fGAliceFileName(galicefilename)
 {
     fParticles = new AliHBTRun();
     fTracks    = new AliHBTRun();
     fIsRead = kFALSE;
 }
/********************************************************************/

AliHBTReaderITSv1::
AliHBTReaderITSv1(TObjArray* dirs, const Char_t* tracksfilename,const Char_t* galicefilename):
                 AliHBTReader(dirs),
                 fITSTracksFileName(tracksfilename),fGAliceFileName(galicefilename)
 {
   fParticles = new AliHBTRun();
   fTracks    = new AliHBTRun();
   fIsRead    = kFALSE;
 }
/********************************************************************/

AliHBTReaderITSv1::~AliHBTReaderITSv1()
{
   delete fParticles;
   delete fTracks;
}
/********************************************************************/

AliHBTEvent* AliHBTReaderITSv1::GetParticleEvent(Int_t n)
 {
 //returns Nth event with simulated particles
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetParticleEvent","Error in reading");
       return 0x0;
     }

   return fParticles->GetEvent(n);
 }
/********************************************************************/

AliHBTEvent* AliHBTReaderITSv1::GetTrackEvent(Int_t n)
 {
 //returns Nth event with reconstructed tracks
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetTrackEvent","Error in reading");
       return 0x0;
     }
   return fTracks->GetEvent(n);
 }
/********************************************************************/

Int_t AliHBTReaderITSv1::GetNumberOfPartEvents()
 {
 //returns number of events of particles
   if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetNumberOfPartEvents","Error in reading");
       return 0;
     }
   return fParticles->GetNumberOfEvents();
 }

/********************************************************************/
Int_t AliHBTReaderITSv1::GetNumberOfTrackEvents()
 {
 //returns number of events of tracks
  if (!fIsRead)
    if(Read(fParticles,fTracks))
     {
       Error("GetNumberOfTrackEvents","Error in reading");
       return 0;
     }
  return fTracks->GetNumberOfEvents();
 }
/********************************************************************/

Int_t AliHBTReaderITSv1::Read(AliHBTRun* particles, AliHBTRun *tracks)
{
 cout<<"AliHBTReaderITSv1::Read()"<<endl;
 Int_t Nevents = 0;
 AliITSIOTrack *iotrack=new AliITSIOTrack;
 Int_t currentdir = 0;
 Int_t Ndirs;

 if (fDirs)
  {
    Ndirs = fDirs->GetEntries();
  }
 else
  {
    Ndirs = 0;
  }

 do //do while is good even if
  {
   TFile* gAliceFile = OpenGAliceFile(currentdir);
   if(gAliceFile == 0x0)
    {
       Error("Read","Can not open the file with gAlice");
       delete iotrack;
       return 1;
    }
   TFile *file = OpenTrackFile(currentdir);
   if(file == 0x0)
    {
       Error("Read","Can not open the file with ITS tracks V1");
       delete iotrack;
       return 2;
    }

   if (gAlice->TreeE())//check if tree E exists
     {
      Nevents = (Int_t)gAlice->TreeE()->GetEntries();//if yes get number of events in gAlice
      cout<<"________________________________________________________\n";
      cout<<"Found "<<Nevents<<" event(s) in directory "<<GetDirName(currentdir)<<endl;
      cout<<"Setting Magnetic Field. Factor is "<<gAlice->Field()->Factor()<<endl;
      AliKalmanTrack::SetConvConst(100/0.299792458/0.2/gAlice->Field()->Factor());
     }
    else
     {//if not return an error
       Error("Read","Can not find Header tree (TreeE) in gAlice");
       delete iotrack;
       return 4;
     }

   char tname[30];
   Int_t totalNevents = 0;
   for (Int_t currentEvent = 0; currentEvent < Nevents; currentEvent++)
    {
      cout<<"Reading Event "<<currentEvent<<endl;

      sprintf(tname,"TreeT%d",currentEvent);
      file->cd();
      TTree *tracktree=(TTree*)file->Get(tname);
      TBranch *tbranch=tracktree->GetBranch("ITStracks");
      tbranch->SetAddress(&iotrack);

      gAliceFile->cd();
      gAlice->GetEvent(currentEvent);
      gAlice->Particles();

      Int_t nentr=(Int_t)tracktree->GetEntries();

      for (Int_t i=0; i<nentr; i++)
       {

        tracktree->GetEvent(i);
        if(!iotrack) continue;
        Int_t label = iotrack->GetLabel();
        if (label < 0)
         {
           continue;
           delete iotrack;
         }
        TParticle *p = (TParticle*)gAlice->Particle(label);
        if(!p)
         {
           Warning("Read","Can not get particle with label &d",label);
           continue;
         }
        if(Pass(p->GetPdgCode())) continue; //check if we are intersted with particles of this type
                                           //if not take next partilce

        AliHBTParticle* part = new AliHBTParticle(*p);
        if(Pass(part)) { delete part; continue;}//check if meets all criteria of any of our cuts
                                                //if it does not delete it and take next good track

        Double_t px=iotrack->GetPx();
        Double_t py=iotrack->GetPy();
        Double_t pz=iotrack->GetPz();
        Double_t mass = p->GetMass();
        Double_t tEtot = TMath::Sqrt(px*px + py*py + pz*pz + mass*mass);//total energy of the track

        Double_t x= iotrack->GetX();
        Double_t y= iotrack->GetY();
        Double_t z= iotrack->GetZ();

        AliHBTParticle* track = new AliHBTParticle(p->GetPdgCode(), px, py , pz, tEtot, x, y, z, 0.);
        if(Pass(track)) { delete  track;continue;}//check if meets all criteria of any of our cuts
                                                  //if it does not delete it and take next good track

        particles->AddParticle(totalNevents,part);//put track and particle on the run
        tracks->AddParticle(totalNevents,track);
       }//end loop over tracks in the event

       totalNevents++;

     }//end of loop over events in current directory

    gAliceFile->Close();
    delete gAliceFile;
    gAliceFile = 0;

    file->Close();
    delete file;
    file = 0;
    currentdir++;
   }while(currentdir < Ndirs);//end of loop over directories specified in fDirs Obj Array

  delete iotrack;
  fIsRead = kTRUE;
  return 0;

 }
/********************************************************************/

TFile* AliHBTReaderITSv1::OpenTrackFile(Int_t ndir)
{
//opens files to be read for given directoru nomber in fDirs Array
   const TString& dirname = GetDirName(ndir);
   if (dirname == "")
    {
      Error("OpenGAliceFile","Can not get directory name");
      return 0x0;
    }
   TString filename = dirname + "/" + fITSTracksFileName;
   TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(filename.Data());
   if (!file) file = new TFile(filename.Data());

   if (!file)
    {
      Error("Read","Can not open file %s",filename.Data());
      return 0x0;
    }
   if (!file->IsOpen())
    {
      Error("Read","Can not open file %s",filename.Data());
      return 0x0;
    }

   return file;
}

/********************************************************************/
TFile* AliHBTReaderITSv1::OpenGAliceFile(Int_t ndir)
{
  const TString& dirname = GetDirName(ndir);
   if (dirname == "")
    {
      Error("OpenGAliceFile","Can not get directory name");
      return 0x0;
    }

  TString filename = dirname + "/" + fGAliceFileName;

  TFile* gAliceFile = TFile::Open(filename.Data());
  if ( gAliceFile== 0x0)
   {
     Error("OpenFiles","Can't open file named %s",filename.Data());
     return 0x0;
   }
  if (!gAliceFile->IsOpen())
   {
     Error("OpenFiles","Can't open file named %s",filename.Data());
     return 0x0;
   }

  if (!(gAlice=(AliRun*)gAliceFile->Get("gAlice")))
   {
     Error("OpenFiles","gAlice have not been found on %s !\n",filename.Data());
     gAliceFile->Close();
     delete gAliceFile;
     return 0x0;
   }

  return gAliceFile;
}

/********************************************************************/
/********************************************************************/

<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetOptions.cpp
 */

#include "./JPetOptions.h"
#include "../JPetLoggerInclude.h"

JPetOptions::Options JPetOptions::kDefaultOptions = {
  {"inputFile", ""},
  {"inputFileType", ""},
  {"scopeConfigFile", ""},
  {"scopeInputDirectory", ""},
  {"outputPath", ""},
  {"outputFile", "root"},
  {"outputFileType", "test.root"},
  {"firstEvent", "-1"},
  {"lastEvent", "-1"},
  {"progressBar", "false"},
  {"runId", "-1"}
};

JPetOptions::JPetOptions()
{
  setStringToFileTypeConversion();
  fOptions = JPetOptions::kDefaultOptions;
}

JPetOptions::JPetOptions(const Options& opts):
  fOptions(opts)
{
  setStringToFileTypeConversion();
  if (areCorrect(opts)) {
    setOptions(opts);
  } else {
    ERROR("Options are not correct using default ones");
  }
}

void JPetOptions::handleErrorMessage(const std::string& errorMessage, const std::out_of_range& outOfRangeException) const
{
  std::cerr << errorMessage << outOfRangeException.what() << '\n';
  ERROR(errorMessage);
}

JPetOptions::FileType JPetOptions::handleFileType(const std::string& fileType) const
{
  try {
    auto option = fOptions.at(fileType);

    try {
      return fStringToFileType.at(option);
    } catch (const std::out_of_range& outOfRangeFileTypeException) {
    }
  } catch (const std::out_of_range& outOfRangeOptionException) {
    std::string errorMessage = "Out of range error in Options container ";
    handleErrorMessage(errorMessage, outOfRangeOptionException);
  }

  return FileType::kUndefinedFileType;
}

void JPetOptions::setStringToFileTypeConversion()
{
  fStringToFileType = {
    {"", kNoType},
    {"root", kRoot},
    {"scope", kScope},
    {"raw", kRaw},
    {"hld", kHld},
    {"phys.eve", kPhysEve},
    {"phys.hit", kPhysHit},
    {"phys.sig", kPhysSig},
    {"raw.sig", kRawSig},
    {"reco.sig", kRecoSig},
    {"tslot.cal", kTslotCal},
    {"tslot.raw", kTslotRaw}
  };
}

bool JPetOptions::areCorrect(const Options&) const
{
  return true;
}

JPetOptions::FileType JPetOptions::getInputFileType() const
{
  return handleFileType("inputFileType");
}

JPetOptions::FileType JPetOptions::getOutputFileType() const
{
  return handleFileType("outputFileType");
}

void JPetOptions::resetEventRange()
{
  fOptions.at("firstEvent") = "-1";
  fOptions.at("lastEvent") = "-1";
}

JPetOptions::Options JPetOptions::resetEventRange(const Options& srcOpts)
{
  Options opts(srcOpts);
  opts.at("firstEvent") = "-1";
  opts.at("lastEvent") = "-1";
  return opts;
}

/// It returns the total number of events calculated from
/// first and last event given in the range of events to calculate.
/// If first or last event is set to -1 then the -1 is returned.
/// If last - first < 0 then -1 is returned.
/// Otherwise last - first +1 is returned.
long long JPetOptions::getTotalEvents() const
{
  long long first = getFirstEvent();
  long long last = getLastEvent();
  long long diff = -1;
  if ((first >= 0) && (last >= 0) && ((last - first) >= 0)) {
    diff = last - first + 1;
  }
  return diff;
}
<commit_msg>Added zip handling in setStringToFileConversion in JPetOptions<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetOptions.cpp
 */

#include "./JPetOptions.h"
#include "../JPetLoggerInclude.h"

JPetOptions::Options JPetOptions::kDefaultOptions = {
  {"inputFile", ""},
  {"inputFileType", ""},
  {"scopeConfigFile", ""},
  {"scopeInputDirectory", ""},
  {"outputPath", ""},
  {"outputFile", "root"},
  {"outputFileType", "test.root"},
  {"firstEvent", "-1"},
  {"lastEvent", "-1"},
  {"progressBar", "false"},
  {"runId", "-1"}
};

JPetOptions::JPetOptions()
{
  setStringToFileTypeConversion();
  fOptions = JPetOptions::kDefaultOptions;
}

JPetOptions::JPetOptions(const Options& opts):
  fOptions(opts)
{
  setStringToFileTypeConversion();
  if (areCorrect(opts)) {
    setOptions(opts);
  } else {
    ERROR("Options are not correct using default ones");
  }
}

void JPetOptions::handleErrorMessage(const std::string& errorMessage, const std::out_of_range& outOfRangeException) const
{
  std::cerr << errorMessage << outOfRangeException.what() << '\n';
  ERROR(errorMessage);
}

JPetOptions::FileType JPetOptions::handleFileType(const std::string& fileType) const
{
  try {
    auto option = fOptions.at(fileType);

    try {
      return fStringToFileType.at(option);
    } catch (const std::out_of_range& outOfRangeFileTypeException) {
    }
  } catch (const std::out_of_range& outOfRangeOptionException) {
    std::string errorMessage = "Out of range error in Options container ";
    handleErrorMessage(errorMessage, outOfRangeOptionException);
  }

  return FileType::kUndefinedFileType;
}

void JPetOptions::setStringToFileTypeConversion()
{
  fStringToFileType = {
    {"", kNoType},
    {"root", kRoot},
    {"scope", kScope},
    {"raw", kRaw},
    {"hld", kHld},
    {"zip", kZip},
    {"phys.eve", kPhysEve},
    {"phys.hit", kPhysHit},
    {"phys.sig", kPhysSig},
    {"raw.sig", kRawSig},
    {"reco.sig", kRecoSig},
    {"tslot.cal", kTslotCal},
    {"tslot.raw", kTslotRaw}
  };
}

bool JPetOptions::areCorrect(const Options&) const
{
  return true;
}

JPetOptions::FileType JPetOptions::getInputFileType() const
{
  return handleFileType("inputFileType");
}

JPetOptions::FileType JPetOptions::getOutputFileType() const
{
  return handleFileType("outputFileType");
}

void JPetOptions::resetEventRange()
{
  fOptions.at("firstEvent") = "-1";
  fOptions.at("lastEvent") = "-1";
}

JPetOptions::Options JPetOptions::resetEventRange(const Options& srcOpts)
{
  Options opts(srcOpts);
  opts.at("firstEvent") = "-1";
  opts.at("lastEvent") = "-1";
  return opts;
}

/// It returns the total number of events calculated from
/// first and last event given in the range of events to calculate.
/// If first or last event is set to -1 then the -1 is returned.
/// If last - first < 0 then -1 is returned.
/// Otherwise last - first +1 is returned.
long long JPetOptions::getTotalEvents() const
{
  long long first = getFirstEvent();
  long long last = getLastEvent();
  long long diff = -1;
  if ((first >= 0) && (last >= 0) && ((last - first) >= 0)) {
    diff = last - first + 1;
  }
  return diff;
}
<|endoftext|>


<commit_before>#include "quickgridstar.h"

QuickGridStarAttached::QuickGridStarAttached(QObject *object) : QObject(object)
{
}

QuickGridStar::QuickGridStar(QQuickItem *parent) : QQuickItem(parent)
{
}

QuickGridStar::~QuickGridStar()
{
    for(QuickGridItem *item : _items)
    {
        delete item;
    }
}

void QuickGridStar::componentComplete()
{
    QList<QQuickItem *>
        children = childItems();

    for(QQuickItem *child : children)
    {
        QString
            className(child->metaObject()->className());

        if(!className.compare("QuickRowDefinition"))
        {
            QuickRowDefinition
                *def = qobject_cast<QuickRowDefinition *>(child);

            _gridDefinition.addRowDefinition(def->_weight);
        }
        else if(!className.compare("QuickColumnDefinition"))
        {
            QuickColumnDefinition
                *def = qobject_cast<QuickColumnDefinition *>(child);

            _gridDefinition.addColumnDefinition(def->_weight);
        }
        else
        {
            QuickGridStarAttached
                *attached = qobject_cast<QuickGridStarAttached *>(qmlAttachedPropertiesObject<QuickGridStar>(child));

            _items << new QuickGridItem(child, attached->_row, attached->_column, attached->_rowSpan, attached->_columnSpan);
        }
    }

    QRectF
        rect;

    if(QString(parent()->metaObject()->className()).contains("ApplicationWindow"))
    {
        QQuickWindow
            *p = qobject_cast<QQuickWindow *>(parent());

        rect = QRectF(p->position(), QSizeF(p->width(), p->height()));
    }
    else
    {
        QQuickItem
            *p = qobject_cast<QQuickItem *>(parent());

        rect = QRectF(p->position(), QSizeF(p->width(), p->height()));
    }

    for(QuickGridItem *item : _items)
    {
        QRectF
            cellRect(_gridDefinition.cellRect(rect, item->_row, item->_column, item->_rowSpan, item->_columnSpan));

        item->_item->setPosition(cellRect.topLeft());
        item->_item->setWidth(cellRect.width());
        item->_item->setHeight(cellRect.height());
    }

    QQuickItem::componentComplete();
}

QuickGridStarAttached *QuickGridStar::qmlAttachedProperties(QObject *object)
{
    return new QuickGridStarAttached(object);
}

QuickRowDefinition::QuickRowDefinition(QQuickItem *parent) : QQuickItem(parent)
{
}

QuickColumnDefinition::QuickColumnDefinition(QQuickItem *parent) : QQuickItem(parent)
{
}
<commit_msg>Update quickgridstar.cpp<commit_after>#include "quickgridstar.h"

QuickGridStarAttached::QuickGridStarAttached(QObject *object) :
    QObject(object),
    _row(0),
    _column(0),
    _rowSpan(1),
    _columnSpan(1)
{
}

QuickGridStar::QuickGridStar(QQuickItem *parent) :
    QQuickItem(parent)
{
}

QuickGridStar::~QuickGridStar()
{
    for(QuickGridItem *item : _items)
    {
        delete item;
    }
}

void QuickGridStar::componentComplete()
{
    QList<QQuickItem *>
        children = childItems();

    for(QQuickItem *child : children)
    {
        QString
            className(child->metaObject()->className());

        if(!className.compare("QuickRowDefinition"))
        {
            QuickRowDefinition
                *def = qobject_cast<QuickRowDefinition *>(child);

            _gridDefinition.addRowDefinition(def->_weight);
        }
        else if(!className.compare("QuickColumnDefinition"))
        {
            QuickColumnDefinition
                *def = qobject_cast<QuickColumnDefinition *>(child);

            _gridDefinition.addColumnDefinition(def->_weight);
        }
        else
        {
            QuickGridStarAttached
                *attached = qobject_cast<QuickGridStarAttached *>(qmlAttachedPropertiesObject<QuickGridStar>(child));

            _items << new QuickGridItem(child, attached->_row, attached->_column, attached->_rowSpan, attached->_columnSpan);
        }
    }

    QRectF
        rect;

    if(QString(parent()->metaObject()->className()).contains("ApplicationWindow"))
    {
        QQuickWindow
            *p = qobject_cast<QQuickWindow *>(parent());

        rect = QRectF(p->position(), QSizeF(p->width(), p->height()));
    }
    else
    {
        QQuickItem
            *p = qobject_cast<QQuickItem *>(parent());

        rect = QRectF(p->position(), QSizeF(p->width(), p->height()));
    }

    for(QuickGridItem *item : _items)
    {
        QRectF
            cellRect(_gridDefinition.cellRect(rect, item->_row, item->_column, item->_rowSpan, item->_columnSpan));

        item->_item->setPosition(cellRect.topLeft());
        item->_item->setWidth(cellRect.width());
        item->_item->setHeight(cellRect.height());
    }

    QQuickItem::componentComplete();
}

QuickGridStarAttached *QuickGridStar::qmlAttachedProperties(QObject *object)
{
    return new QuickGridStarAttached(object);
}

QuickRowDefinition::QuickRowDefinition(QQuickItem *parent) :
    QQuickItem(parent)
{
}

QuickColumnDefinition::QuickColumnDefinition(QQuickItem *parent) :
    QQuickItem(parent)
{
}
<|endoftext|>


<commit_before>/***********************************************************************
 test/tcp.cpp - Tests the address parser/verifier in TCPConnection.

 Copyright (c) 2007 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the
 CREDITS file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include <exceptions.h>
#include <tcp_connection.h>

#include <iostream>
#include <sstream>

static void
test(const char* addr_svc, const char* exp_addr, unsigned int exp_port)
{
	std::string addr(addr_svc), error;
	unsigned int port;

	mysqlpp::TCPConnection::parse_address(addr, port, error);
	if (error.size()) {
		throw mysqlpp::SelfTestFailed("TCP address parse error: " +
				error);
	}
	else if (addr.compare(exp_addr) != 0) {
		std::ostringstream outs;
		outs << "TCP address parse mismatch: '" << addr << "' != '" <<
				exp_addr << "'";
		throw mysqlpp::SelfTestFailed(outs.str());
	}
	else if (port != exp_port) {
		std::ostringstream outs;
		outs << "TCP port parse mismatch: '" << port << "' != '" <<
				exp_port << "'";
		throw mysqlpp::SelfTestFailed(outs.str());
	}
}

static void
fail(const char* addr_svc, const char* exp_addr, unsigned int exp_port)
{
	try {
		test(addr_svc, exp_addr, exp_port);
	}
	catch (...) {
		return;		// eat expected error
	}

	std::ostringstream outs;
	outs << "'" << addr_svc << "' == ('" << exp_addr <<
			"', " << exp_port << ") but should not.";
	throw mysqlpp::SelfTestFailed(outs.str());
}

int
main()
{
	try {
		// Domain name and IPv4 literal tests
		test(":", "", 0);
		test("1.2.3.4", "1.2.3.4", 0);
		test("1.2.3.4:", "1.2.3.4", 0);
		test("1.2.3.4:567", "1.2.3.4", 567);
		test("1.2.3.4:telnet", "1.2.3.4", 23);
		test("a.b.com", "a.b.com", 0);
		fail("@", "@", 0);
		fail("::", "", 0);
		fail(":", "1.2.3.4", 45);
		fail("a.b.com::", "a.b.com", 0);
		fail("a.b:com:1", "a.b.com", 1);

		// IPv6 literal tests
		test("[]:123", "", 123);
		test("[::]:telnet", "::", 23);

		std::cout << "TCP address parsing passed." << std::endl;
		return 0;
	}
	catch (mysqlpp::SelfTestFailed& e) {
		std::cerr << "TCP address parse error: " << e.what() << std::endl;
		return 1;
	}
	catch (std::exception& e) {
		std::cerr << "Unexpected test failure: " << e.what() << std::endl;
		return 2;
	}
}
<commit_msg>Updated test/tcp.cpp to a) fix breakage due to previous patch; and b) to add a few more cases to catch regressions.<commit_after>/***********************************************************************
 test/tcp.cpp - Tests the address parser/verifier in TCPConnection.

 Copyright (c) 2007 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the
 CREDITS file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include <exceptions.h>
#include <tcp_connection.h>

#include <iostream>
#include <sstream>

static void
test(const char* addr_svc, unsigned int port, const char* exp_addr,
		unsigned int exp_port)
{
	std::string addr(addr_svc), error;

	mysqlpp::TCPConnection::parse_address(addr, port, error);
	if (error.size()) {
		throw mysqlpp::SelfTestFailed("TCP address parse error: " +
				error);
	}
	else if (addr.compare(exp_addr) != 0) {
		std::ostringstream outs;
		outs << "TCP address parse mismatch: '" << addr << "' != '" <<
				exp_addr << "'";
		throw mysqlpp::SelfTestFailed(outs.str());
	}
	else if (port != exp_port) {
		std::ostringstream outs;
		outs << "TCP port parse mismatch: '" << port << "' != '" <<
				exp_port << "'";
		throw mysqlpp::SelfTestFailed(outs.str());
	}
}

static void
fail(const char* addr_svc, unsigned int port, const char* exp_addr,
		unsigned int exp_port)
{
	try {
		test(addr_svc, port, exp_addr, exp_port);
	}
	catch (...) {
		return;		// eat expected error
	}

	std::ostringstream outs;
	outs << "'" << addr_svc << "' == ('" << exp_addr <<
			"', " << exp_port << ") but should not.";
	throw mysqlpp::SelfTestFailed(outs.str());
}

int
main()
{
	try {
		// Domain name and IPv4 literal tests
		test(":", 0, "", 0);
		test("1.2.3.4", 0, "1.2.3.4", 0);
		test("1.2.3.4:", 0, "1.2.3.4", 0);
		test("1.2.3.4:567", 0, "1.2.3.4", 567);
		test("1.2.3.4", 890, "1.2.3.4", 890);
		test("1.2.3.4:telnet", 0, "1.2.3.4", 23);
		test("a.b.com", 0, "a.b.com", 0);
		test("a.b.com", 987, "a.b.com", 987);
		fail("@", 0, "@", 0);
		fail("::", 0, "", 0);
		fail(":", 0, "1.2.3.4", 45);
		fail("a.b.com::", 0, "a.b.com", 0);
		fail("a.b:com:1", 0, "a.b.com", 1);

		// IPv6 literal tests
		test("[]:123", 0, "", 123);
		test("[::]:telnet", 0, "::", 23);

		std::cout << "TCP address parsing passed." << std::endl;
		return 0;
	}
	catch (mysqlpp::SelfTestFailed& e) {
		std::cerr << "TCP address parse error: " << e.what() << std::endl;
		return 1;
	}
	catch (std::exception& e) {
		std::cerr << "Unexpected test failure: " << e.what() << std::endl;
		return 2;
	}
}
<|endoftext|>


<commit_before>#include "ARVersion.h"
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBId.h"
#include "AliCDBMetaData.h"
#include "AliGeomManager.h"
#include <TROOT.h>
#include "AliRun.h"
#include <TGeoManager.h>
#include <TString.h>
#endif

void UpdateCDBIdealGeom(const char* cdbUri, const char* cfgFile){
  // Produce the ideal geometry and store it in the specified CDB
  // The second argument allows to specify the config file to be used
  // in particular for giving the choice to generate either a full or
  // a partial geometry.
  //

  AliCDBManager* cdb = AliCDBManager::Instance();
  // we set the default storage to the repository because some dets require
  // already at the time of geometry creation to find calibration objects in the cdb
  AliCDBStorage* storage = 0;
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  storage = cdb->GetStorage(cdbUri);
  if(!storage)
  {
    Printf("unable to create valid storage from: %s", cdbUri);
    return;
  }
  cdb->SetRun(0);
  AliCDBId id("GRP/Geometry/Data",0,AliCDBRunRange::Infinity());
  AliCDBMetaData *md= new AliCDBMetaData();

  // Get root and AliRoot versions
  const char* rootv = gROOT->GetVersion();
  TString av(ALIROOT_SVN_BRANCH);
  Int_t revnum = ALIROOT_SVN_REVISION;

  Printf("root version: %s.  AliRoot %s, revision number %d",rootv,av.Data(),revnum);

  md->SetAliRootVersion(av.Data());
  md->SetComment(Form("Geometry produced with root version %s and AliRoot %s, revision number %d",rootv,av.Data(),revnum));

  gROOT->LoadMacro(cfgFile);
  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
  gAlice->GetMCApp()->Init();

  if(!gGeoManager){
    Printf("Unable to produce a valid geometry to be put in the CDB!");
    return;
  }
  gGeoManager->DefaultColors(); // assign default colors according to Z of material
  // (many colors turned into dark gray nuances some time ago, when the root palette was changed)

  Printf("Storing in CDB geometry produced with root version %s and AliRoot version %s",rootv,av.Data());
  storage->Put(gGeoManager,id,md);
  // This is to allow macros lauched after this one in the same session to find the
  // newly produced geometry.
  storage->QueryCDB(cdb->GetRun());

}

<commit_msg>Added two missing includes to allow macro compilation (thanks to Laurent for remarking it).<commit_after>#include "ARVersion.h"
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBId.h"
#include "AliCDBMetaData.h"
#include "AliGeomManager.h"
#include "AliMC.h"
#include <TROOT.h>
#include "AliRun.h"
#include <TGeoManager.h>
#include <TString.h>
#include <TInterpreter.h>
#endif

void UpdateCDBIdealGeom(const char* cdbUri, const char* cfgFile){
  // Produce the ideal geometry and store it in the specified CDB
  // The second argument allows to specify the config file to be used
  // in particular for giving the choice to generate either a full or
  // a partial geometry.
  //

  AliCDBManager* cdb = AliCDBManager::Instance();
  // we set the default storage to the repository because some dets require
  // already at the time of geometry creation to find calibration objects in the cdb
  AliCDBStorage* storage = 0;
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  storage = cdb->GetStorage(cdbUri);
  if(!storage)
  {
    Printf("unable to create valid storage from: %s", cdbUri);
    return;
  }
  cdb->SetRun(0);
  AliCDBId id("GRP/Geometry/Data",0,AliCDBRunRange::Infinity());
  AliCDBMetaData *md= new AliCDBMetaData();

  // Get root and AliRoot versions
  const char* rootv = gROOT->GetVersion();
  TString av(ALIROOT_SVN_BRANCH);
  Int_t revnum = ALIROOT_SVN_REVISION;

  Printf("root version: %s.  AliRoot %s, revision number %d",rootv,av.Data(),revnum);

  md->SetAliRootVersion(av.Data());
  md->SetComment(Form("Geometry produced with root version %s and AliRoot %s, revision number %d",rootv,av.Data(),revnum));

  gROOT->LoadMacro(cfgFile);
  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
  gAlice->GetMCApp()->Init();

  if(!gGeoManager){
    Printf("Unable to produce a valid geometry to be put in the CDB!");
    return;
  }
  gGeoManager->DefaultColors(); // assign default colors according to Z of material
  // (many colors turned into dark gray nuances some time ago, when the root palette was changed)

  Printf("Storing in CDB geometry produced with root version %s and AliRoot version %s",rootv,av.Data());
  storage->Put(gGeoManager,id,md);
  // This is to allow macros lauched after this one in the same session to find the
  // newly produced geometry.
  storage->QueryCDB(cdb->GetRun());

}

<|endoftext|>


<commit_before>/*
	This file is part of the GUI library.
	Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <GUI/Components/Button.h>
#include <GUI/Components/Textfield.h>
#include <GUI/Components/Window.h>
#include <GUI/GUI_Manager.h>
#include <Util/UI/EventContext.h>
#include <Util/UI/UI.h>
#include <Util/References.h>
#include <Util/StringIdentifier.h>
#include <Util/Util.h>
#include <cstdlib>
#include <iostream>

/**
 * @file
 * @brief Simple usage example for GUI
 *
 * The example uses a GUI::GUI_Manager to create a GUI::Window, a
 * GUI::Textfield, and a GUI::Button. Then, it registers a GUI::ActionListener
 * to wait for a click onto the button. When the button is clicked, the text
 * field is cleared.
 */

int main(int /*argc*/, char */*argv*/[]) {
	Util::init();

	Util::UI::Window::Properties properties;
	properties.positioned = true;
	properties.posX = 100;
	properties.posY = 100;
	properties.clientAreaWidth = 1024;
	properties.clientAreaHeight = 768;
	properties.title = "GUI Textfield and Buttons";
	properties.compatibilityProfile = true;
	auto window = Util::UI::createWindow(properties);

	Util::UI::EventContext eventContext;
	eventContext.getEventQueue().registerEventGenerator(std::bind(&Util::UI::Window::fetchEvents, window.get()));

	GUI::GUI_Manager guiManager(&eventContext);
	guiManager.setWindow(window.get());

	Util::Reference<GUI::Window> guiWin = guiManager.createWindow(Geometry::Rect_f(10, 10, 200, 200), "Window");

	Util::Reference<GUI::Textfield> guiText = guiManager.createTextfield("Text");
	guiText->setRect(Geometry::Rect_f(0, 0, 40, 20));
	guiWin->addContent(guiText.get());

	Util::Reference<GUI::Button> guiButton = guiManager.createButton("Clear");
	guiButton->setActionListener(	[&guiText](GUI::Component *, const Util::StringIdentifier &) {
										guiText->setText("");
										return true;
									});
	guiButton->setRect(Geometry::Rect_f(0, 25, 40, 20));
	guiWin->addContent(guiButton.get());

	bool done = false;
	while(!done) {
		eventContext.getEventQueue().process();
		while(eventContext.getEventQueue().getNumEventsAvailable() > 0) {
			auto event = eventContext.getEventQueue().popEvent();
			if(event.type == Util::UI::EVENT_QUIT ||
						(event.type == Util::UI::EVENT_KEYBOARD &&
						 event.keyboard.pressed &&
						 event.keyboard.key == Util::UI::KEY_ESCAPE)) {
				done = true;
			} else {
				guiManager.handleEvent(event);
			}
		}
		guiManager.display();
		window->swapBuffers();
	}
	return EXIT_SUCCESS;
}
<commit_msg>fixed example's header includes<commit_after>/*
	This file is part of the GUI library.
	Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <Components/Button.h>
#include <Components/Textfield.h>
#include <Components/Window.h>
#include <GUI_Manager.h>
#include <Util/UI/EventContext.h>
#include <Util/UI/UI.h>
#include <Util/References.h>
#include <Util/StringIdentifier.h>
#include <Util/Util.h>
#include <cstdlib>
#include <iostream>

/**
 * @file
 * @brief Simple usage example for GUI
 *
 * The example uses a GUI::GUI_Manager to create a GUI::Window, a
 * GUI::Textfield, and a GUI::Button. Then, it registers a GUI::ActionListener
 * to wait for a click onto the button. When the button is clicked, the text
 * field is cleared.
 */

int main(int /*argc*/, char */*argv*/[]) {
	Util::init();

	Util::UI::Window::Properties properties;
	properties.positioned = true;
	properties.posX = 100;
	properties.posY = 100;
	properties.clientAreaWidth = 1024;
	properties.clientAreaHeight = 768;
	properties.title = "GUI Textfield and Buttons";
	properties.compatibilityProfile = true;
	auto window = Util::UI::createWindow(properties);

	Util::UI::EventContext eventContext;
	eventContext.getEventQueue().registerEventGenerator(std::bind(&Util::UI::Window::fetchEvents, window.get()));

	GUI::GUI_Manager guiManager(&eventContext);
	guiManager.setWindow(window.get());

	Util::Reference<GUI::Window> guiWin = guiManager.createWindow(Geometry::Rect_f(10, 10, 200, 200), "Window");

	Util::Reference<GUI::Textfield> guiText = guiManager.createTextfield("Text");
	guiText->setRect(Geometry::Rect_f(0, 0, 40, 20));
	guiWin->addContent(guiText.get());

	Util::Reference<GUI::Button> guiButton = guiManager.createButton("Clear");
	guiButton->setActionListener(	[&guiText](GUI::Component *, const Util::StringIdentifier &) {
										guiText->setText("");
										return true;
									});
	guiButton->setRect(Geometry::Rect_f(0, 25, 40, 20));
	guiWin->addContent(guiButton.get());

	bool done = false;
	while(!done) {
		eventContext.getEventQueue().process();
		while(eventContext.getEventQueue().getNumEventsAvailable() > 0) {
			auto event = eventContext.getEventQueue().popEvent();
			if(event.type == Util::UI::EVENT_QUIT ||
						(event.type == Util::UI::EVENT_KEYBOARD &&
						 event.keyboard.pressed &&
						 event.keyboard.key == Util::UI::KEY_ESCAPE)) {
				done = true;
			} else {
				guiManager.handleEvent(event);
			}
		}
		guiManager.display();
		window->swapBuffers();
	}
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "IO/File.h"
#include <cstdio>
#include <cstdint>
#include <filesystem>
#include <stdexcept>
#include <memory>
#include <string>

namespace HedgeLib::IO
{
	constexpr const char* GetFileOpenMode(const FileMode mode)
	{
		switch (mode)
		{
		case ReadBinary:
			return "rb";
		case WriteBinary:
			return "wb";
		case AppendBinary:
			return "ab";
		case ReadUpdateBinary:
			return "r+b";
		case WriteUpdateBinary:
			return "w+b";
		case AppendUpdateBinary:
			return "a+b";
		case ReadText:
			return "r";
		case WriteText:
			return "w";
		case AppendText:
			return "a";
		case ReadUpdateText:
			return "r+";
		case WriteUpdateText:
			return "w+";
		case AppendUpdateText:
			return "a+";
		default:
			return nullptr;
		}
	}

	constexpr const wchar_t* GetFileOpenModeW(const FileMode mode)
	{
		switch (mode)
		{
		case ReadBinary:
			return L"rb";
		case WriteBinary:
			return L"wb";
		case AppendBinary:
			return L"ab";
		case ReadUpdateBinary:
			return L"r+b";
		case WriteUpdateBinary:
			return L"w+b";
		case AppendUpdateBinary:
			return L"a+b";
		case ReadText:
			return L"r";
		case WriteText:
			return L"w";
		case AppendText:
			return L"a";
		case ReadUpdateText:
			return L"r+";
		case WriteUpdateText:
			return L"w+";
		case AppendUpdateText:
			return L"a+";
		default:
			return nullptr;
		}
	}

	void File::OpenNoClose(const std::filesystem::path filePath, const FileMode mode)
	{
#ifdef _WIN32
#ifdef UNICODE
		if (_wfopen_s(&fs, filePath.wstring().c_str(), GetFileOpenModeW(mode)))
#else
		if (fopen_s(&fs, filePath.u8string().c_str(), GetFileOpenMode(mode))
#endif
#else
		fs = std::fopen(filePath.u8string().c_str(), GetFileOpenMode(mode));
		if (!fs)
#endif
			throw std::runtime_error("Could not load the given file!");
	}

	void File::Open(const std::filesystem::path filePath, const FileMode mode)
	{
		Close();
		OpenNoClose(filePath, mode);
	}

	void File::WriteNulls(std::size_t amount) const noexcept
	{
		if (amount < 1) return;

		std::unique_ptr<std::uint8_t[]> nulls =
			std::make_unique<std::uint8_t[]>(amount);

		Write(nulls.get(), amount, 1);
	}

	void File::ReadWString(std::wstring& str) const noexcept
	{
		wchar_t c;
		while (Read(&c, sizeof(c), 1))
		{
			str += c;
			if (c == L'\0')
				return;
		}
	}

	void File::ReadString(std::string& str) const noexcept
	{
		char c;
		while (Read(&c, sizeof(c), 1))
		{
			str += c;
			if (c == '\0')
				return;
		}
	}

	void File::Align(long stride) const noexcept
	{
		if (stride < 2)
			return;

		--stride;

		// TODO: Add an overflow check? Idk seems pointless here since
		// ftell() returns a signed long anyway.

		Seek((Tell() + stride) & ~stride);
	}

	void File::Pad(long stride) const noexcept
	{
		if (stride < 2)
			return;

		long pos = Tell();
		--stride;

		WriteNulls(((pos + stride) & ~stride) - pos);
	}
}
<commit_msg>Bugfix for File ReadString functions Previously these functions added the terminating null character to the string. std::strings are guaranteed to always have a terminating null character, so one is added at the end of the string automatically, meaning the File ReadString functions returned a string with two terminating null characters rather than one.<commit_after>#include "IO/File.h"
#include <cstdio>
#include <cstdint>
#include <filesystem>
#include <stdexcept>
#include <memory>
#include <string>

namespace HedgeLib::IO
{
	constexpr const char* GetFileOpenMode(const FileMode mode)
	{
		switch (mode)
		{
		case ReadBinary:
			return "rb";
		case WriteBinary:
			return "wb";
		case AppendBinary:
			return "ab";
		case ReadUpdateBinary:
			return "r+b";
		case WriteUpdateBinary:
			return "w+b";
		case AppendUpdateBinary:
			return "a+b";
		case ReadText:
			return "r";
		case WriteText:
			return "w";
		case AppendText:
			return "a";
		case ReadUpdateText:
			return "r+";
		case WriteUpdateText:
			return "w+";
		case AppendUpdateText:
			return "a+";
		default:
			return nullptr;
		}
	}

	constexpr const wchar_t* GetFileOpenModeW(const FileMode mode)
	{
		switch (mode)
		{
		case ReadBinary:
			return L"rb";
		case WriteBinary:
			return L"wb";
		case AppendBinary:
			return L"ab";
		case ReadUpdateBinary:
			return L"r+b";
		case WriteUpdateBinary:
			return L"w+b";
		case AppendUpdateBinary:
			return L"a+b";
		case ReadText:
			return L"r";
		case WriteText:
			return L"w";
		case AppendText:
			return L"a";
		case ReadUpdateText:
			return L"r+";
		case WriteUpdateText:
			return L"w+";
		case AppendUpdateText:
			return L"a+";
		default:
			return nullptr;
		}
	}

	void File::OpenNoClose(const std::filesystem::path filePath, const FileMode mode)
	{
#ifdef _WIN32
#ifdef UNICODE
		if (_wfopen_s(&fs, filePath.wstring().c_str(), GetFileOpenModeW(mode)))
#else
		if (fopen_s(&fs, filePath.u8string().c_str(), GetFileOpenMode(mode))
#endif
#else
		fs = std::fopen(filePath.u8string().c_str(), GetFileOpenMode(mode));
		if (!fs)
#endif
			throw std::runtime_error("Could not load the given file!");
	}

	void File::Open(const std::filesystem::path filePath, const FileMode mode)
	{
		Close();
		OpenNoClose(filePath, mode);
	}

	void File::WriteNulls(std::size_t amount) const noexcept
	{
		if (amount < 1) return;

		std::unique_ptr<std::uint8_t[]> nulls =
			std::make_unique<std::uint8_t[]>(amount);

		Write(nulls.get(), amount, 1);
	}

	void File::ReadWString(std::wstring& str) const noexcept
	{
		wchar_t c;
		while (Read(&c, sizeof(c), 1))
		{
			if (c == L'\0')
				return;

            str += c;
		}
	}

	void File::ReadString(std::string& str) const noexcept
	{
		char c;
		while (Read(&c, sizeof(c), 1))
		{
			if (c == '\0')
				return;

            str += c;
		}
	}

	void File::Align(long stride) const noexcept
	{
		if (stride < 2)
			return;

		--stride;

		// TODO: Add an overflow check? Idk seems pointless here since
		// ftell() returns a signed long anyway.

		Seek((Tell() + stride) & ~stride);
	}

	void File::Pad(long stride) const noexcept
	{
		if (stride < 2)
			return;

		long pos = Tell();
		--stride;

		WriteNulls(((pos + stride) & ~stride) - pos);
	}
}
<|endoftext|>


<commit_before>/*!
 * \file SU2_CFD.cpp
 * \brief Main file of the SU2 Computational Fluid Dynamics code
 * \author F. Palacios, T. Economon
 * \version 6.2.0 "Falcon"
 *
 * The current SU2 release has been coordinated by the
 * SU2 International Developers Society <www.su2devsociety.org>
 * with selected contributions from the open-source community.
 *
 * The main research teams contributing to the current release are:
 *  - Prof. Juan J. Alonso's group at Stanford University.
 *  - Prof. Piero Colonna's group at Delft University of Technology.
 *  - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
 *  - Prof. Alberto Guardone's group at Polytechnic University of Milan.
 *  - Prof. Rafael Palacios' group at Imperial College London.
 *  - Prof. Vincent Terrapon's group at the University of Liege.
 *  - Prof. Edwin van der Weide's group at the University of Twente.
 *  - Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics.
 *
 * Copyright 2012-2019, Francisco D. Palacios, Thomas D. Economon,
 *                      Tim Albring, and the SU2 contributors.
 *
 * SU2 is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>.
 */

#include "../include/SU2_CFD.hpp"

/* LIBXSMM include files, if supported. */
#ifdef HAVE_LIBXSMM
#include "libxsmm.h"
#endif

/* Include file, needed for the runtime NaN catching. */
//#include <fenv.h>

using namespace std;

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

  unsigned short nZone;
  char config_file_name[MAX_STRING_SIZE];
  bool fsi, turbo, zone_specific;

  /*--- MPI initialization, and buffer setting ---*/

#ifdef HAVE_MPI
  int  buffsize;
  char *buffptr;
  SU2_MPI::Init(&argc, &argv);
  SU2_MPI::Buffer_attach( malloc(BUFSIZE), BUFSIZE );
  SU2_Comm MPICommunicator(MPI_COMM_WORLD);
#else
  SU2_Comm MPICommunicator(0);
#endif

  /*--- Uncomment the following line if runtime NaN catching is desired. ---*/
  // feenableexcept(FE_INVALID | FE_OVERFLOW);

  /*--- Initialize libxsmm, if supported. ---*/
#ifdef HAVE_LIBXSMM
  libxsmm_init();
#endif

  /*--- Create a pointer to the main SU2 Driver ---*/

  CDriver *driver = NULL;

  /*--- Load in the number of zones and spatial dimensions in the mesh file (If no config
   file is specified, default.cfg is used) ---*/

  if (argc == 2) { strcpy(config_file_name, argv[1]); }
  else { strcpy(config_file_name, "default.cfg"); }

  /*--- Read the name and format of the input mesh file to get from the mesh
   file the number of zones and dimensions from the numerical grid (required
   for variables allocation). ---*/

  CConfig *config = NULL;
  config = new CConfig(config_file_name, SU2_CFD);
  nZone    = config->GetnZone();
  fsi      = config->GetFSI_Simulation();
  turbo    = config->GetBoolTurbomachinery();
  zone_specific = config->GetBoolZoneSpecific();

  /*--- First, given the basic information about the number of zones and the
   solver types from the config, instantiate the appropriate driver for the problem
   and perform all the preprocessing. ---*/

  if ((config->GetSinglezone_Driver() || (nZone == 1 && config->GetDiscrete_Adjoint()))
    && config->GetUnsteady_Simulation() != HARMONIC_BALANCE && !turbo ) {

    /*--- Single zone problem: instantiate the single zone driver class. ---*/

    if (nZone > 1 ) {
      SU2_MPI::Error("The required solver doesn't support multizone simulations", CURRENT_FUNCTION);
    }
    if (config->GetDiscrete_Adjoint())
       driver = new CDiscAdjSinglezoneDriver(config_file_name, nZone, MPICommunicator);
    else
       driver = new CSinglezoneDriver(config_file_name, nZone, MPICommunicator);

  }
  else if (config->GetMultizone_Problem() && !turbo && !fsi) {

    /*--- Multizone Driver. ---*/

    driver = new CMultizoneDriver(config_file_name, nZone, MPICommunicator);

  } else if (config->GetUnsteady_Simulation() == HARMONIC_BALANCE) {

    /*--- Harmonic balance problem: instantiate the Harmonic Balance driver class. ---*/

    driver = new CHBDriver(config_file_name, nZone, MPICommunicator);

  } else if ((nZone == 2) && fsi) {

    bool stat_fsi = ((config->GetDynamic_Analysis() == STATIC) && (config->GetUnsteady_Simulation() == STEADY));
    bool disc_adj_fsi = (config->GetDiscrete_Adjoint());

    /*--- If the problem is a discrete adjoint FSI problem ---*/
    if (disc_adj_fsi) {
      if (stat_fsi) {
        driver = new CDiscAdjFSIDriver(config_file_name, nZone, MPICommunicator);
      }
      else {
        SU2_MPI::Error("WARNING: There is no discrete adjoint implementation for dynamic FSI. ", CURRENT_FUNCTION);
      }
    }
    /*--- If the problem is a direct FSI problem ---*/
    else{
      driver = new CFSIDriver(config_file_name, nZone, MPICommunicator);
    }

  } else if (zone_specific) {
    driver = new CMultiphysicsZonalDriver(config_file_name, nZone, MPICommunicator);
  } else {

    /*--- Multi-zone problem: instantiate the multi-zone driver class by default
    or a specialized driver class for a particular multi-physics problem. ---*/

    if (turbo) {

      driver = new CTurbomachineryDriver(config_file_name, nZone, MPICommunicator);

    } else {

      /*--- Instantiate the class for external aerodynamics ---*/

      driver = new CFluidDriver(config_file_name, nZone, MPICommunicator);

    }

  }

  delete config;
  config = NULL;

  /*--- Launch the main external loop of the solver ---*/

  driver->StartSolver();

  /*--- Postprocess all the containers, close history file, exit SU2 ---*/

  driver->Postprocessing();

  if (driver != NULL) delete driver;
  driver = NULL;

  /*---Finalize libxsmm, if supported. ---*/
#ifdef HAVE_LIBXSMM
  libxsmm_finalize();
#endif

  /*--- Finalize MPI parallelization ---*/
#ifdef HAVE_MPI
  SU2_MPI::Buffer_detach(&buffptr, &buffsize);
  free(buffptr);
  SU2_MPI::Finalize();
#endif

  return EXIT_SUCCESS;

}
<commit_msg>Fixed driver init for turbo adj<commit_after>/*!
 * \file SU2_CFD.cpp
 * \brief Main file of the SU2 Computational Fluid Dynamics code
 * \author F. Palacios, T. Economon
 * \version 6.2.0 "Falcon"
 *
 * The current SU2 release has been coordinated by the
 * SU2 International Developers Society <www.su2devsociety.org>
 * with selected contributions from the open-source community.
 *
 * The main research teams contributing to the current release are:
 *  - Prof. Juan J. Alonso's group at Stanford University.
 *  - Prof. Piero Colonna's group at Delft University of Technology.
 *  - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.
 *  - Prof. Alberto Guardone's group at Polytechnic University of Milan.
 *  - Prof. Rafael Palacios' group at Imperial College London.
 *  - Prof. Vincent Terrapon's group at the University of Liege.
 *  - Prof. Edwin van der Weide's group at the University of Twente.
 *  - Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics.
 *
 * Copyright 2012-2019, Francisco D. Palacios, Thomas D. Economon,
 *                      Tim Albring, and the SU2 contributors.
 *
 * SU2 is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>.
 */

#include "../include/SU2_CFD.hpp"

/* LIBXSMM include files, if supported. */
#ifdef HAVE_LIBXSMM
#include "libxsmm.h"
#endif

/* Include file, needed for the runtime NaN catching. */
//#include <fenv.h>

using namespace std;

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

  unsigned short nZone;
  char config_file_name[MAX_STRING_SIZE];
  bool fsi, turbo, zone_specific;

  /*--- MPI initialization, and buffer setting ---*/

#ifdef HAVE_MPI
  int  buffsize;
  char *buffptr;
  SU2_MPI::Init(&argc, &argv);
  SU2_MPI::Buffer_attach( malloc(BUFSIZE), BUFSIZE );
  SU2_Comm MPICommunicator(MPI_COMM_WORLD);
#else
  SU2_Comm MPICommunicator(0);
#endif

  /*--- Uncomment the following line if runtime NaN catching is desired. ---*/
  // feenableexcept(FE_INVALID | FE_OVERFLOW);

  /*--- Initialize libxsmm, if supported. ---*/
#ifdef HAVE_LIBXSMM
  libxsmm_init();
#endif

  /*--- Create a pointer to the main SU2 Driver ---*/

  CDriver *driver = NULL;

  /*--- Load in the number of zones and spatial dimensions in the mesh file (If no config
   file is specified, default.cfg is used) ---*/

  if (argc == 2) { strcpy(config_file_name, argv[1]); }
  else { strcpy(config_file_name, "default.cfg"); }

  /*--- Read the name and format of the input mesh file to get from the mesh
   file the number of zones and dimensions from the numerical grid (required
   for variables allocation). ---*/

  CConfig *config = NULL;
  config = new CConfig(config_file_name, SU2_CFD);
  nZone    = config->GetnZone();
  fsi      = config->GetFSI_Simulation();
  turbo    = config->GetBoolTurbomachinery();
  zone_specific = config->GetBoolZoneSpecific();

  /*--- First, given the basic information about the number of zones and the
   solver types from the config, instantiate the appropriate driver for the problem
   and perform all the preprocessing. ---*/

  if (((config->GetSinglezone_Driver() || (nZone == 1 && config->GetDiscrete_Adjoint()))
    && config->GetUnsteady_Simulation() != HARMONIC_BALANCE && (!turbo)) || (turbo && config->GetDiscrete_Adjoint())) {

    /*--- Single zone problem: instantiate the single zone driver class. ---*/

    if (nZone > 1 ) {
      SU2_MPI::Error("The required solver doesn't support multizone simulations", CURRENT_FUNCTION);
    }
    if (config->GetDiscrete_Adjoint())
       driver = new CDiscAdjSinglezoneDriver(config_file_name, nZone, MPICommunicator);
    else
       driver = new CSinglezoneDriver(config_file_name, nZone, MPICommunicator);

  }
  else if (config->GetMultizone_Problem() && !turbo && !fsi) {

    /*--- Multizone Driver. ---*/

    driver = new CMultizoneDriver(config_file_name, nZone, MPICommunicator);

  } else if (config->GetUnsteady_Simulation() == HARMONIC_BALANCE) {

    /*--- Harmonic balance problem: instantiate the Harmonic Balance driver class. ---*/

    driver = new CHBDriver(config_file_name, nZone, MPICommunicator);

  } else if ((nZone == 2) && fsi) {

    bool stat_fsi = ((config->GetDynamic_Analysis() == STATIC) && (config->GetUnsteady_Simulation() == STEADY));
    bool disc_adj_fsi = (config->GetDiscrete_Adjoint());

    /*--- If the problem is a discrete adjoint FSI problem ---*/
    if (disc_adj_fsi) {
      if (stat_fsi) {
        driver = new CDiscAdjFSIDriver(config_file_name, nZone, MPICommunicator);
      }
      else {
        SU2_MPI::Error("WARNING: There is no discrete adjoint implementation for dynamic FSI. ", CURRENT_FUNCTION);
      }
    }
    /*--- If the problem is a direct FSI problem ---*/
    else{
      driver = new CFSIDriver(config_file_name, nZone, MPICommunicator);
    }

  } else if (zone_specific) {
    driver = new CMultiphysicsZonalDriver(config_file_name, nZone, MPICommunicator);
  } else {

    /*--- Multi-zone problem: instantiate the multi-zone driver class by default
    or a specialized driver class for a particular multi-physics problem. ---*/

    if (turbo) {

      driver = new CTurbomachineryDriver(config_file_name, nZone, MPICommunicator);

    } else {

      /*--- Instantiate the class for external aerodynamics ---*/

      driver = new CFluidDriver(config_file_name, nZone, MPICommunicator);

    }

  }

  delete config;
  config = NULL;

  /*--- Launch the main external loop of the solver ---*/

  driver->StartSolver();

  /*--- Postprocess all the containers, close history file, exit SU2 ---*/

  driver->Postprocessing();

  if (driver != NULL) delete driver;
  driver = NULL;

  /*---Finalize libxsmm, if supported. ---*/
#ifdef HAVE_LIBXSMM
  libxsmm_finalize();
#endif

  /*--- Finalize MPI parallelization ---*/
#ifdef HAVE_MPI
  SU2_MPI::Buffer_detach(&buffptr, &buffsize);
  free(buffptr);
  SU2_MPI::Finalize();
#endif

  return EXIT_SUCCESS;

}
<|endoftext|>


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

#include <iostream>
#include <fmi4cpp/tools/os_util.hpp>
#include <fmi4cpp/fmi2/fmi4cpp.hpp>

using namespace std;
using namespace fmi4cpp::fmi2;

int main() {

    const string fmu_path1 = string(getenv("TEST_FMUs"))
                            + "/FMI_2.0/CoSimulation/" + getOs() +
                            "/20sim/4.6.4.8004/TorsionBar/TorsionBar.fmu";

    const string fmu_path2 = string(getenv("TEST_FMUs"))
                             + "/FMI_2.0/CoSimulation/" + getOs() +
                             "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

    import::Fmu fmu1(fmu_path1);
    import::Fmu fmu2(fmu_path2);

    const auto slave1 = fmu1.asCoSimulationFmu()->newInstance();
    slave1->init();

    const auto slave2 = fmu2.asCoSimulationFmu()->newInstance();
    slave2->init();

    slave1->doStep(1E-5);
    slave2->doStep(1E-4);

    double ref;
    fmi2ValueReference vr = slave1->getValueReference("MotorDiskRev");
    assert(vr == 105);
    slave1->readReal(vr, ref);
    cout << "MotorDiskRev=" << ref << endl;

    vr = slave2->getValueReference("Temperature_Room");
    assert(vr == 47);
    slave2->readReal(vr, ref);
    cout << "Temperature_Room=" << ref << endl;

    slave1->terminate();
    slave2->terminate();

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

#include <iostream>
#include <fmi4cpp/tools/os_util.hpp>
#include <fmi4cpp/fmi2/fmi4cpp.hpp>

using namespace std;
using namespace fmi4cpp::fmi2;

int main() {

    const string fmu_path1 = string(getenv("TEST_FMUs"))
                            + "/FMI_2.0/CoSimulation/" + getOs() +
                            "/20sim/4.6.4.8004/TorsionBar/TorsionBar.fmu";

    const string fmu_path2 = string(getenv("TEST_FMUs"))
                             + "/FMI_2.0/CoSimulation/" + getOs() +
                             "/20sim/4.6.4.8004/ControlledTemperature/ControlledTemperature.fmu";

    import::Fmu fmu1(fmu_path1);
    import::Fmu fmu2(fmu_path2);

    const auto slave1 = fmu1.asCoSimulationFmu()->newInstance();
    slave1->init();

    const auto slave2 = fmu2.asCoSimulationFmu()->newInstance();
    slave2->init();

    slave1->doStep(1E-5);
    slave2->doStep(1E-4);

    double ref;
    auto var = slave1->getModelDescription()->getVariableByName("MotorDiskRev").asReal();
    assert(var.valueReference() == 105);
    var.read(*slave1, ref);
    cout << "MotorDiskRev=" << ref << endl;

    auto vr = slave2->getValueReference("Temperature_Room");
    assert(vr == 47);
    slave2->readReal(vr, ref);
    cout << "Temperature_Room=" << ref << endl;

    slave1->terminate();
    slave2->terminate();

}<|endoftext|>