<commit_before>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2002 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de          or                  */
/*        vigra@kogs1.informatik.uni-hamburg.de                         */
/*                                                                      */
/*    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.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_SIZED_INT_HXX
#define VIGRA_SIZED_INT_HXX

#include "metaprogramming.hxx"

namespace vigra {

#ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION

namespace detail {

template<class T, class NEXT>
struct IntTypeList
{
    enum { size = sizeof(T)*8 };
    typedef T type;
    typedef NEXT next;
};

template<int SIZE, class LIST>
struct SelectIntegerType
{
    typedef typename
       IfBool<(SIZE == LIST::size),
           typename LIST::type,
           typename SelectIntegerType<SIZE, typename LIST::next>::type >::type
       type;
};

template<int SIZE>
struct SelectIntegerType<SIZE, VigraFalseType>
{
    typedef VigraFalseType type;
};

template<class LIST>
struct SelectBiggestIntegerType
{
    enum { cursize = LIST::size,
           nextsize = SelectBiggestIntegerType<typename LIST::next>::size,
           size = (cursize < nextsize) ? nextsize : cursize };
    typedef typename
       IfBool<(cursize < nextsize),
           typename SelectBiggestIntegerType<typename LIST::next>::type,
           typename LIST::type>::type
       type;
};

template<>
struct SelectBiggestIntegerType<VigraFalseType>
{
    enum { size = 0 };
    typedef VigraFalseType type;
};

typedef IntTypeList<signed char,
        IntTypeList<signed short,
        IntTypeList<signed int,
        IntTypeList<signed long,
        VigraFalseType > > > > SignedIntTypes;
typedef IntTypeList<unsigned char,
        IntTypeList<unsigned short,
        IntTypeList<unsigned int,
        IntTypeList<unsigned long,
        VigraFalseType > > > > UnsignedIntTypes;

} // namespace detail

/** \addtogroup FixedSizeInt Fixed Size Integer Types

    Since the C++ standard does only specifiy minimal sizes for the built-in
    integer types, one cannot rely on them have a specific size. But
    pixel types with a specific size are often required in image processing,
    especially when reading or writing binary files. The VIGRA typedefs
    are guaranteed to have exactly the correct size. If the system
    does not provide a suitable type, the typedef will evaluate to
    \ref VigraFalseType.
*/
//@{

    /// 8-bit signed int
typedef detail::SelectIntegerType<8,  detail::SignedIntTypes>::type Int8;
    /// 16-bit signed int
typedef detail::SelectIntegerType<16, detail::SignedIntTypes>::type Int16;
    /// 32-bit signed int
typedef detail::SelectIntegerType<32, detail::SignedIntTypes>::type Int32;
    /// 64-bit signed int
typedef detail::SelectIntegerType<64, detail::SignedIntTypes>::type Int64;
    /// 8-bit unsigned int
typedef detail::SelectIntegerType<8,  detail::UnsignedIntTypes>::type UInt8;
    /// 16-bit unsigned int
typedef detail::SelectIntegerType<16, detail::UnsignedIntTypes>::type UInt16;
    /// 32-bit unsigned int
typedef detail::SelectIntegerType<32, detail::UnsignedIntTypes>::type UInt32;
    /// 64-bit unsigned int
typedef detail::SelectIntegerType<64, detail::UnsignedIntTypes>::type UInt64;

    /// the biggest signed integer type of the system
typedef detail::SelectBiggestIntegerType<detail::SignedIntTypes>::type   IntBiggest;
    /// the biggest unsigned integer type of the system
typedef detail::SelectBiggestIntegerType<detail::UnsignedIntTypes>::type UIntBiggest;

//@}

#else // NO_PARTIAL_TEMPLATE_SPECIALIZATION

typedef signed char    Int8;
typedef signed short   Int16;
typedef signed int     Int32;
typedef VigraFalseType Int64;
typedef unsigned char  UInt8;
typedef unsigned short UInt16;
typedef unsigned int   UInt32;
typedef VigraFalseType UInt64;

typedef Int32  IntBiggest;
typedef UInt32 UIntBiggest;

#endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION

} // namespace vigra

#endif /* VIGRA_SIZED_INT_HXX */
<commit_msg>introduced Int_type_not_supported_on_this_platform<commit_after>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2002 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de          or                  */
/*        vigra@kogs1.informatik.uni-hamburg.de                         */
/*                                                                      */
/*    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.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_SIZED_INT_HXX
#define VIGRA_SIZED_INT_HXX

#include "metaprogramming.hxx"

namespace vigra {

class Int_type_not_supported_on_this_platform {};

#ifndef NO_PARTIAL_TEMPLATE_SPECIALIZATION

namespace detail {

template<class T, class NEXT>
struct IntTypeList
{
    enum { size = sizeof(T)*8 };
    typedef T type;
    typedef NEXT next;
};

template<int SIZE, class LIST>
struct SelectIntegerType
{
    typedef typename
       IfBool<(SIZE == LIST::size),
           typename LIST::type,
           typename SelectIntegerType<SIZE, typename LIST::next>::type >::type
       type;
};

template<int SIZE>
struct SelectIntegerType<SIZE, Int_type_not_supported_on_this_platform>
{
    typedef Int_type_not_supported_on_this_platform type;
};

template<class LIST>
struct SelectBiggestIntegerType
{
    enum { cursize = LIST::size,
           nextsize = SelectBiggestIntegerType<typename LIST::next>::size,
           size = (cursize < nextsize) ? nextsize : cursize };
    typedef typename
       IfBool<(cursize < nextsize),
           typename SelectBiggestIntegerType<typename LIST::next>::type,
           typename LIST::type>::type
       type;
};

template<>
struct SelectBiggestIntegerType<Int_type_not_supported_on_this_platform>
{
    enum { size = 0 };
    typedef Int_type_not_supported_on_this_platform type;
};

typedef IntTypeList<signed char,
        IntTypeList<signed short,
        IntTypeList<signed int,
        IntTypeList<signed long,
        Int_type_not_supported_on_this_platform > > > > SignedIntTypes;
typedef IntTypeList<unsigned char,
        IntTypeList<unsigned short,
        IntTypeList<unsigned int,
        IntTypeList<unsigned long,
        Int_type_not_supported_on_this_platform > > > > UnsignedIntTypes;

} // namespace detail

/** \addtogroup FixedSizeInt Fixed Size Integer Types

    Since the C++ standard does only specifiy minimal sizes for the built-in
    integer types, one cannot rely on them have a specific size. But
    pixel types with a specific size are often required in image processing,
    especially when reading or writing binary files. The VIGRA typedefs
    are guaranteed to have exactly the correct size. If the system
    does not provide a suitable type, the typedef will evaluate to
    <tt>Int_type_not_supported_on_this_platform</tt>.
*/
//@{

    /// 8-bit signed int
typedef detail::SelectIntegerType<8,  detail::SignedIntTypes>::type Int8;
    /// 16-bit signed int
typedef detail::SelectIntegerType<16, detail::SignedIntTypes>::type Int16;
    /// 32-bit signed int
typedef detail::SelectIntegerType<32, detail::SignedIntTypes>::type Int32;
    /// 64-bit signed int
typedef detail::SelectIntegerType<64, detail::SignedIntTypes>::type Int64;
    /// 8-bit unsigned int
typedef detail::SelectIntegerType<8,  detail::UnsignedIntTypes>::type UInt8;
    /// 16-bit unsigned int
typedef detail::SelectIntegerType<16, detail::UnsignedIntTypes>::type UInt16;
    /// 32-bit unsigned int
typedef detail::SelectIntegerType<32, detail::UnsignedIntTypes>::type UInt32;
    /// 64-bit unsigned int
typedef detail::SelectIntegerType<64, detail::UnsignedIntTypes>::type UInt64;

    /// the biggest signed integer type of the system
typedef detail::SelectBiggestIntegerType<detail::SignedIntTypes>::type   IntBiggest;
    /// the biggest unsigned integer type of the system
typedef detail::SelectBiggestIntegerType<detail::UnsignedIntTypes>::type UIntBiggest;

//@}

#else // NO_PARTIAL_TEMPLATE_SPECIALIZATION

typedef signed char    Int8;
typedef signed short   Int16;
typedef signed int     Int32;
typedef Int_type_not_supported_on_this_platform Int64;
typedef unsigned char  UInt8;
typedef unsigned short UInt16;
typedef unsigned int   UInt32;
typedef Int_type_not_supported_on_this_platform UInt64;

typedef Int32  IntBiggest;
typedef UInt32 UIntBiggest;

#endif // NO_PARTIAL_TEMPLATE_SPECIALIZATION

} // namespace vigra

#endif /* VIGRA_SIZED_INT_HXX */
<|endoftext|>


<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// 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 <nvcore/StrLib.h>
#include <nvcore/StdStream.h>

#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>

#include <nvtt/nvtt.h>

#include "cmdline.h"

#include <time.h> // clock

//#define WINDOWS_LEAN_AND_MEAN
//#include <windows.h> // TIMER

struct MyOutputHandler : public nvtt::OutputHandler
{
	MyOutputHandler(const char * name) : total(0), progress(0), percentage(0), stream(new nv::StdOutputStream(name)) {}
	virtual ~MyOutputHandler() { delete stream; }

	virtual void setTotal(int t)
	{
		total = t + 128;
	}
	virtual void setDisplayProgress(bool b)
	{
		verbose = b;
	}

	virtual void mipmap(int size, int width, int height, int depth, int face, int miplevel)
	{
		// ignore.
	}

	// Output data.
	virtual bool writeData(const void * data, int size)
	{
		nvDebugCheck(stream != NULL);
		stream->serialize(const_cast<void *>(data), size);

		progress += size;
		int p = (100 * progress) / total;
		if (verbose && p != percentage)
		{
			percentage = p;
			printf("\r%d%%", percentage);
			fflush(stdout);
		}

		return true;
	}

	int total;
	int progress;
	int percentage;
	bool verbose;
	nv::StdOutputStream * stream;
};

struct MyErrorHandler : public nvtt::ErrorHandler
{
	virtual void error(nvtt::Error e)
	{
		nvDebugBreak();
	}
};

// Set color to normal map conversion options.
void setColorToNormalMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(false);
	inputOptions.setConvertToNormalMap(true);
	inputOptions.setHeightEvaluation(1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f, 0.0f);
	//inputOptions.setNormalFilter(1.0f, 0, 0, 0);
	//inputOptions.setNormalFilter(0.0f, 0, 0, 1);
	inputOptions.setGamma(1.0f, 1.0f);
	inputOptions.setNormalizeMipmaps(true);
}

// Set options for normal maps.
void setNormalMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(true);
	inputOptions.setConvertToNormalMap(false);
	inputOptions.setGamma(1.0f, 1.0f);
	inputOptions.setNormalizeMipmaps(true);
}

// Set options for color maps.
void setColorMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(false);
	inputOptions.setConvertToNormalMap(false);
	inputOptions.setGamma(2.2f, 2.2f);
	inputOptions.setNormalizeMipmaps(false);
}

int main(int argc, char *argv[])
{
	MyAssertHandler assertHandler;
	MyMessageHandler messageHandler;

	bool normal = false;
	bool color2normal = false;
	bool wrapRepeat = false;
	bool noMipmaps = false;
	bool fast = false;
	bool nocuda = false;
	bool silent = false;
	bool bc1n = false;
	nvtt::Format format = nvtt::Format_BC1;

	const char * externalCompressor = NULL;

	nv::Path input;
	nv::Path output;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
	{
		// Input options.
		if (strcmp("-color", argv[i]) == 0)
		{
		}
		else if (strcmp("-normal", argv[i]) == 0)
		{
			normal = true;
		}
		else if (strcmp("-tonormal", argv[i]) == 0)
		{
			color2normal = true;
		}
		else if (strcmp("-clamp", argv[i]) == 0)
		{
		}
		else if (strcmp("-repeat", argv[i]) == 0)
		{
			wrapRepeat = true;
		}
		else if (strcmp("-nomips", argv[i]) == 0)
		{
			noMipmaps = true;
		}

		// Compression options.
		else if (strcmp("-fast", argv[i]) == 0)
		{
			fast = true;
		}
		else if (strcmp("-nocuda", argv[i]) == 0)
		{
			nocuda = true;
		}
		else if (strcmp("-rgb", argv[i]) == 0)
		{
			format = nvtt::Format_RGB;
		}
		else if (strcmp("-bc1", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
		}
		else if (strcmp("-bc1n", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
			bc1n = true;
		}
		else if (strcmp("-bc1a", argv[i]) == 0)
		{
			format = nvtt::Format_BC1a;
		}
		else if (strcmp("-bc2", argv[i]) == 0)
		{
			format = nvtt::Format_BC2;
		}
		else if (strcmp("-bc3", argv[i]) == 0)
		{
			format = nvtt::Format_BC3;
		}
		else if (strcmp("-bc3n", argv[i]) == 0)
		{
			format = nvtt::Format_BC3n;
		}
		else if (strcmp("-bc4", argv[i]) == 0)
		{
			format = nvtt::Format_BC4;
		}
		else if (strcmp("-bc5", argv[i]) == 0)
		{
			format = nvtt::Format_BC5;
		}

		// Undocumented option. Mainly used for testing.
		else if (strcmp("-ext", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') {
				externalCompressor = argv[i+1];
				i++;
			}
		}

		// Misc options
		else if (strcmp("-silent", argv[i]) == 0)
		{
			silent = true;
		}

		else if (argv[i][0] != '-')
		{
			input = argv[i];

			if (i+1 < argc && argv[i+1][0] != '-') {
				output = argv[i+1];
			}
			else
			{
				output.copy(input.str());
				output.stripExtension();
				output.append(".dds");
			}

			break;
		}
	}

	printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");

	if (input.isNull())
	{
		printf("usage: nvcompress [options] infile [outfile]\n\n");

		printf("Input options:\n");
		printf("  -color   \tThe input image is a color map (default).\n");
		printf("  -normal  \tThe input image is a normal map.\n");
		printf("  -tonormal\tConvert input to normal map.\n");
		printf("  -clamp   \tClamp wrapping mode (default).\n");
		printf("  -repeat  \tRepeat wrapping mode.\n");
		printf("  -nomips  \tDisable mipmap generation.\n\n");

		printf("Compression options:\n");
		printf("  -fast    \tFast compression.\n");
		printf("  -nocuda  \tDo not use cuda compressor.\n");
		printf("  -rgb     \tRGBA format\n");
		printf("  -bc1     \tBC1 format (DXT1)\n");
		printf("  -bc1n    \tBC1 normal map format (DXT1nm)\n");
		printf("  -bc1a    \tBC1 format with binary alpha (DXT1a)\n");
		printf("  -bc2     \tBC2 format (DXT3)\n");
		printf("  -bc3     \tBC3 format (DXT5)\n");
		printf("  -bc3n    \tBC3 normal map format (DXT5nm)\n");
		printf("  -bc4     \tBC4 format (ATI1)\n");
		printf("  -bc5     \tBC5 format (3Dc/ATI2)\n\n");

		return 1;
	}

	// @@ Make sure input file exists.

	// Set input options.
	nvtt::InputOptions inputOptions;

	if (nv::strCaseCmp(input.extension(), ".dds") == 0)
	{
		// Load surface.
		nv::DirectDrawSurface dds(input);
		if (!dds.isValid())
		{
			fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
			return 1;
		}

		if (!dds.isSupported() || dds.isTexture3D())
		{
			fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
			return 1;
		}

		uint faceCount;
		if (dds.isTexture2D())
		{
			inputOptions.setTextureLayout(nvtt::TextureType_2D, dds.width(), dds.height());
			faceCount = 1;
		}
		else
		{
			nvDebugCheck(dds.isTextureCube());
			inputOptions.setTextureLayout(nvtt::TextureType_Cube, dds.width(), dds.height());
			faceCount = 6;
		}

		uint mipmapCount = dds.mipmapCount();

		nv::Image mipmap;

		for (uint f = 0; f < faceCount; f++)
		{
			for (uint m = 0; m <= mipmapCount; m++)
			{
				dds.mipmap(&mipmap, f, m);

				inputOptions.setMipmapData(mipmap.pixels(), mipmap.width(), mipmap.height(), 1, f, m);
			}
		}
	}
	else
	{
		// Regular image.
		nv::Image image;
		if (!image.load(input))
		{
			fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
			return 1;
		}

		inputOptions.setTextureLayout(nvtt::TextureType_2D, image.width(), image.height());
		inputOptions.setMipmapData(image.pixels(), image.width(), image.height());
	}

	if (wrapRepeat)
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Repeat);
	}
	else
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
	}

	if (normal)
	{
		setNormalMap(inputOptions);
	}
	else if (color2normal)
	{
		setColorToNormalMap(inputOptions);
	}
	else
	{
		setColorMap(inputOptions);
	}

	if (noMipmaps)
	{
		inputOptions.setMipmapping(false);
	}

	//inputOptions.setGamma(2.2, 1);
	//inputOptions.setRoundMode(nvtt::RoundMode_ToPreviousPowerOfTwo);

	nvtt::CompressionOptions compressionOptions;
	compressionOptions.setFormat(format);
	if (fast)
	{
		compressionOptions.setQuality(nvtt::Quality_Fastest);
	}
	else
	{
		compressionOptions.setQuality(nvtt::Quality_Normal);
		//compressionOptions.setQuality(nvtt::Quality_Production);
		//compressionOptions.setQuality(nvtt::Quality_Highest);
	}

	if (bc1n)
	{
		compressionOptions.setColorWeights(1, 1, 0);
	}

	if (externalCompressor != NULL)
	{
		compressionOptions.setExternalCompressor(externalCompressor);
	}

	MyErrorHandler errorHandler;
	MyOutputHandler outputHandler(output);
	if (outputHandler.stream->isError())
	{
		fprintf(stderr, "Error opening '%s' for writting\n", output.str());
		return 1;
	}

	nvtt::Compressor compressor;
	compressor.enableCudaAcceleration(!nocuda);

	outputHandler.setTotal(compressor.estimateSize(inputOptions, compressionOptions));
	outputHandler.setDisplayProgress(!silent);

	nvtt::OutputOptions outputOptions;
	//outputOptions.setFileName(output);
	outputOptions.setOutputHandler(&outputHandler);
	outputOptions.setErrorHandler(&errorHandler);

//	printf("Press ENTER.\n");
//	fflush(stdout);
//	getchar();

/*	LARGE_INTEGER temp;
	QueryPerformanceFrequency((LARGE_INTEGER*) &temp);
	double freq = ((double) temp.QuadPart) / 1000.0;

    LARGE_INTEGER start_time;
    QueryPerformanceCounter((LARGE_INTEGER*) &start_time);
*/
	clock_t start = clock();

	compressor.process(inputOptions, compressionOptions, outputOptions);
/*
	LARGE_INTEGER end_time;
	QueryPerformanceCounter((LARGE_INTEGER*) &end_time);

	float diff_time = (float) (((double) end_time.QuadPart - (double) start_time.QuadPart) / freq);
	printf("\rtime taken: %.3f seconds\n", diff_time/1000);
*/

	clock_t end = clock();
	printf("\rtime taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC);

	return 0;
}

<commit_msg>Remove commented out code.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// 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 <nvcore/StrLib.h>
#include <nvcore/StdStream.h>

#include <nvimage/Image.h>
#include <nvimage/DirectDrawSurface.h>

#include <nvtt/nvtt.h>

#include "cmdline.h"

#include <time.h> // clock

//#define WINDOWS_LEAN_AND_MEAN
//#include <windows.h> // TIMER

struct MyOutputHandler : public nvtt::OutputHandler
{
	MyOutputHandler(const char * name) : total(0), progress(0), percentage(0), stream(new nv::StdOutputStream(name)) {}
	virtual ~MyOutputHandler() { delete stream; }

	virtual void setTotal(int t)
	{
		total = t + 128;
	}
	virtual void setDisplayProgress(bool b)
	{
		verbose = b;
	}

	virtual void mipmap(int size, int width, int height, int depth, int face, int miplevel)
	{
		// ignore.
	}

	// Output data.
	virtual bool writeData(const void * data, int size)
	{
		nvDebugCheck(stream != NULL);
		stream->serialize(const_cast<void *>(data), size);

		progress += size;
		int p = (100 * progress) / total;
		if (verbose && p != percentage)
		{
			percentage = p;
			printf("\r%d%%", percentage);
			fflush(stdout);
		}

		return true;
	}

	int total;
	int progress;
	int percentage;
	bool verbose;
	nv::StdOutputStream * stream;
};

struct MyErrorHandler : public nvtt::ErrorHandler
{
	virtual void error(nvtt::Error e)
	{
		nvDebugBreak();
	}
};

// Set color to normal map conversion options.
void setColorToNormalMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(false);
	inputOptions.setConvertToNormalMap(true);
	inputOptions.setHeightEvaluation(1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f, 0.0f);
	//inputOptions.setNormalFilter(1.0f, 0, 0, 0);
	//inputOptions.setNormalFilter(0.0f, 0, 0, 1);
	inputOptions.setGamma(1.0f, 1.0f);
	inputOptions.setNormalizeMipmaps(true);
}

// Set options for normal maps.
void setNormalMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(true);
	inputOptions.setConvertToNormalMap(false);
	inputOptions.setGamma(1.0f, 1.0f);
	inputOptions.setNormalizeMipmaps(true);
}

// Set options for color maps.
void setColorMap(nvtt::InputOptions & inputOptions)
{
	inputOptions.setNormalMap(false);
	inputOptions.setConvertToNormalMap(false);
	inputOptions.setGamma(2.2f, 2.2f);
	inputOptions.setNormalizeMipmaps(false);
}

int main(int argc, char *argv[])
{
	MyAssertHandler assertHandler;
	MyMessageHandler messageHandler;

	bool normal = false;
	bool color2normal = false;
	bool wrapRepeat = false;
	bool noMipmaps = false;
	bool fast = false;
	bool nocuda = false;
	bool silent = false;
	bool bc1n = false;
	nvtt::Format format = nvtt::Format_BC1;

	const char * externalCompressor = NULL;

	nv::Path input;
	nv::Path output;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
	{
		// Input options.
		if (strcmp("-color", argv[i]) == 0)
		{
		}
		else if (strcmp("-normal", argv[i]) == 0)
		{
			normal = true;
		}
		else if (strcmp("-tonormal", argv[i]) == 0)
		{
			color2normal = true;
		}
		else if (strcmp("-clamp", argv[i]) == 0)
		{
		}
		else if (strcmp("-repeat", argv[i]) == 0)
		{
			wrapRepeat = true;
		}
		else if (strcmp("-nomips", argv[i]) == 0)
		{
			noMipmaps = true;
		}

		// Compression options.
		else if (strcmp("-fast", argv[i]) == 0)
		{
			fast = true;
		}
		else if (strcmp("-nocuda", argv[i]) == 0)
		{
			nocuda = true;
		}
		else if (strcmp("-rgb", argv[i]) == 0)
		{
			format = nvtt::Format_RGB;
		}
		else if (strcmp("-bc1", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
		}
		else if (strcmp("-bc1n", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
			bc1n = true;
		}
		else if (strcmp("-bc1a", argv[i]) == 0)
		{
			format = nvtt::Format_BC1a;
		}
		else if (strcmp("-bc2", argv[i]) == 0)
		{
			format = nvtt::Format_BC2;
		}
		else if (strcmp("-bc3", argv[i]) == 0)
		{
			format = nvtt::Format_BC3;
		}
		else if (strcmp("-bc3n", argv[i]) == 0)
		{
			format = nvtt::Format_BC3n;
		}
		else if (strcmp("-bc4", argv[i]) == 0)
		{
			format = nvtt::Format_BC4;
		}
		else if (strcmp("-bc5", argv[i]) == 0)
		{
			format = nvtt::Format_BC5;
		}

		// Undocumented option. Mainly used for testing.
		else if (strcmp("-ext", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') {
				externalCompressor = argv[i+1];
				i++;
			}
		}

		// Misc options
		else if (strcmp("-silent", argv[i]) == 0)
		{
			silent = true;
		}

		else if (argv[i][0] != '-')
		{
			input = argv[i];

			if (i+1 < argc && argv[i+1][0] != '-') {
				output = argv[i+1];
			}
			else
			{
				output.copy(input.str());
				output.stripExtension();
				output.append(".dds");
			}

			break;
		}
	}

	printf("NVIDIA Texture Tools - Copyright NVIDIA Corporation 2007\n\n");

	if (input.isNull())
	{
		printf("usage: nvcompress [options] infile [outfile]\n\n");

		printf("Input options:\n");
		printf("  -color   \tThe input image is a color map (default).\n");
		printf("  -normal  \tThe input image is a normal map.\n");
		printf("  -tonormal\tConvert input to normal map.\n");
		printf("  -clamp   \tClamp wrapping mode (default).\n");
		printf("  -repeat  \tRepeat wrapping mode.\n");
		printf("  -nomips  \tDisable mipmap generation.\n\n");

		printf("Compression options:\n");
		printf("  -fast    \tFast compression.\n");
		printf("  -nocuda  \tDo not use cuda compressor.\n");
		printf("  -rgb     \tRGBA format\n");
		printf("  -bc1     \tBC1 format (DXT1)\n");
		printf("  -bc1n    \tBC1 normal map format (DXT1nm)\n");
		printf("  -bc1a    \tBC1 format with binary alpha (DXT1a)\n");
		printf("  -bc2     \tBC2 format (DXT3)\n");
		printf("  -bc3     \tBC3 format (DXT5)\n");
		printf("  -bc3n    \tBC3 normal map format (DXT5nm)\n");
		printf("  -bc4     \tBC4 format (ATI1)\n");
		printf("  -bc5     \tBC5 format (3Dc/ATI2)\n\n");

		return 1;
	}

	// @@ Make sure input file exists.

	// Set input options.
	nvtt::InputOptions inputOptions;

	if (nv::strCaseCmp(input.extension(), ".dds") == 0)
	{
		// Load surface.
		nv::DirectDrawSurface dds(input);
		if (!dds.isValid())
		{
			fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
			return 1;
		}

		if (!dds.isSupported() || dds.isTexture3D())
		{
			fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
			return 1;
		}

		uint faceCount;
		if (dds.isTexture2D())
		{
			inputOptions.setTextureLayout(nvtt::TextureType_2D, dds.width(), dds.height());
			faceCount = 1;
		}
		else
		{
			nvDebugCheck(dds.isTextureCube());
			inputOptions.setTextureLayout(nvtt::TextureType_Cube, dds.width(), dds.height());
			faceCount = 6;
		}

		uint mipmapCount = dds.mipmapCount();

		nv::Image mipmap;

		for (uint f = 0; f < faceCount; f++)
		{
			for (uint m = 0; m <= mipmapCount; m++)
			{
				dds.mipmap(&mipmap, f, m);

				inputOptions.setMipmapData(mipmap.pixels(), mipmap.width(), mipmap.height(), 1, f, m);
			}
		}
	}
	else
	{
		// Regular image.
		nv::Image image;
		if (!image.load(input))
		{
			fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
			return 1;
		}

		inputOptions.setTextureLayout(nvtt::TextureType_2D, image.width(), image.height());
		inputOptions.setMipmapData(image.pixels(), image.width(), image.height());
	}

	if (wrapRepeat)
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Repeat);
	}
	else
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
	}

	if (normal)
	{
		setNormalMap(inputOptions);
	}
	else if (color2normal)
	{
		setColorToNormalMap(inputOptions);
	}
	else
	{
		setColorMap(inputOptions);
	}

	if (noMipmaps)
	{
		inputOptions.setMipmapping(false);
	}

	nvtt::CompressionOptions compressionOptions;
	compressionOptions.setFormat(format);
	if (fast)
	{
		compressionOptions.setQuality(nvtt::Quality_Fastest);
	}
	else
	{
		compressionOptions.setQuality(nvtt::Quality_Normal);
		//compressionOptions.setQuality(nvtt::Quality_Production);
		//compressionOptions.setQuality(nvtt::Quality_Highest);
	}

	if (bc1n)
	{
		compressionOptions.setColorWeights(1, 1, 0);
	}

	if (externalCompressor != NULL)
	{
		compressionOptions.setExternalCompressor(externalCompressor);
	}

	MyErrorHandler errorHandler;
	MyOutputHandler outputHandler(output);
	if (outputHandler.stream->isError())
	{
		fprintf(stderr, "Error opening '%s' for writting\n", output.str());
		return 1;
	}

	nvtt::Compressor compressor;
	compressor.enableCudaAcceleration(!nocuda);

	outputHandler.setTotal(compressor.estimateSize(inputOptions, compressionOptions));
	outputHandler.setDisplayProgress(!silent);

	nvtt::OutputOptions outputOptions;
	//outputOptions.setFileName(output);
	outputOptions.setOutputHandler(&outputHandler);
	outputOptions.setErrorHandler(&errorHandler);

//	printf("Press ENTER.\n");
//	fflush(stdout);
//	getchar();

/*	LARGE_INTEGER temp;
	QueryPerformanceFrequency((LARGE_INTEGER*) &temp);
	double freq = ((double) temp.QuadPart) / 1000.0;

    LARGE_INTEGER start_time;
    QueryPerformanceCounter((LARGE_INTEGER*) &start_time);
*/
	clock_t start = clock();

	compressor.process(inputOptions, compressionOptions, outputOptions);
/*
	LARGE_INTEGER end_time;
	QueryPerformanceCounter((LARGE_INTEGER*) &end_time);

	float diff_time = (float) (((double) end_time.QuadPart - (double) start_time.QuadPart) / freq);
	printf("\rtime taken: %.3f seconds\n", diff_time/1000);
*/

	clock_t end = clock();
	printf("\rtime taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC);

	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2014-2019, CNRS
 * Copyright 2018-2019, INRIA
 */

#include "eigenpy/eigenpy.hpp"
#include <stdlib.h>

namespace eigenpy
{

  void seed(unsigned int seed_value)
  {
    srand(seed_value);
  }

  /* Enable Eigen-Numpy serialization for a set of standard MatrixBase instances. */
  void enableEigenPy()
  {
    using namespace Eigen;

    Exception::registerException();

    bp::def("setNumpyType",&NumpyType::setNumpyType,
            bp::arg("Numpy type (np.ndarray or np.matrix)"),
            "Change the Numpy type returned by the converters from an Eigen object.");

    bp::def("getNumpyType",&NumpyType::getNumpyType,
            "Get the Numpy type returned by the converters from an Eigen object.");

    bp::def("switchToNumpyArray",&NumpyType::switchToNumpyArray,
            "Set the conversion from Eigen::Matrix to numpy.ndarray.");

    bp::def("switchToNumpyMatrix",&NumpyType::switchToNumpyMatrix,
            "Set the conversion from Eigen::Matrix to numpy.matrix.");

    bp::def("seed",&seed,bp::arg("seed_value"),
            "Initialize the pseudo-random number generator with the argument seed_value.");

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXi);

    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXi);

    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXi);
  }

} // namespace eigenpy
<commit_msg>core: expose complex default Eigen::Matrix<commit_after>/*
 * Copyright 2014-2019, CNRS
 * Copyright 2018-2020, INRIA
 */

#include "eigenpy/eigenpy.hpp"
#include <stdlib.h>

namespace eigenpy
{

  void seed(unsigned int seed_value)
  {
    srand(seed_value);
  }

  /* Enable Eigen-Numpy serialization for a set of standard MatrixBase instances. */
  void enableEigenPy()
  {
    using namespace Eigen;

    Exception::registerException();

    bp::def("setNumpyType",&NumpyType::setNumpyType,
            bp::arg("Numpy type (np.ndarray or np.matrix)"),
            "Change the Numpy type returned by the converters from an Eigen object.");

    bp::def("getNumpyType",&NumpyType::getNumpyType,
            "Get the Numpy type returned by the converters from an Eigen object.");

    bp::def("switchToNumpyArray",&NumpyType::switchToNumpyArray,
            "Set the conversion from Eigen::Matrix to numpy.ndarray.");

    bp::def("switchToNumpyMatrix",&NumpyType::switchToNumpyMatrix,
            "Set the conversion from Eigen::Matrix to numpy.matrix.");

    bp::def("seed",&seed,bp::arg("seed_value"),
            "Initialize the pseudo-random number generator with the argument seed_value.");

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix2Xcd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix3Xcd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xd);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xi);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Matrix4Xcd);

    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX2cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX3cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixX4cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXi);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXcd);

    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector2cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector3cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVector4cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXi);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXcd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector2cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector3cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4d);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4f);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4i);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4cf);
    ENABLE_SPECIFIC_MATRIX_TYPE(Vector4cd);

    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXd);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXf);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXi);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXcf);
    ENABLE_SPECIFIC_MATRIX_TYPE(VectorXcd);
  }

} // namespace eigenpy
<|endoftext|>


<commit_before>#pragma once

#include <utility>
#include <type_traits>
#include <tuple>

namespace gcl::mp::utility
{
	template <typename T, T value>
    constexpr static auto reverse_integer_sequence_v = []<typename T, T ... indexes>(std::integer_sequence<T, indexes...>)
    {
        return std::integer_sequence<T, (value - 1 - indexes)...>{};
    }(std::make_integer_sequence<T, value>{});

    template <typename T, T value>
    using make_reverse_integer_sequence = decltype(reverse_integer_sequence_v<T, value>);
    template <std::size_t N>
    using make_reverse_index_sequence = make_reverse_integer_sequence<std::size_t, N>;
    template <class ... Ts>
    using reverse_index_sequence_for = make_reverse_index_sequence<sizeof...(Ts)>;

    template <std::size_t ... Ints>
    constexpr static auto reverse_index_sequence_v = []<std::size_t ... indexes>(std::index_sequence<indexes...>){
        constexpr auto Ints_as_tuple = std::tuple{Ints...};
        return std::index_sequence<std::get<indexes>(Ints_as_tuple)...>{};
    }(reverse_index_sequence_for<decltype(Ints)...>{});

    template <std::size_t ... Ints>
    using reverse_index_sequence = std::decay_t<decltype(reverse_index_sequence_v<Ints...>)>;
}

namespace gcl::mp::utility::tests
{
    static_assert(std::is_same_v<
        reverse_index_sequence<11, 22, 33>,
        std::index_sequence<33, 22, 11>
    >);
}<commit_msg>[gcl::utility] reverse_integer_sequence : fix cv-qualifier, add test<commit_after>#pragma once

#include <utility>
#include <type_traits>
#include <tuple>

namespace gcl::mp::utility
{
	template <typename T, T value>
    constexpr static auto reverse_integer_sequence_v = []<typename T, T ... indexes>(std::integer_sequence<T, indexes...>)
    {
        return std::integer_sequence<T, (value - 1 - indexes)...>{};
    }(std::make_integer_sequence<T, value>{});

    template <typename T, T value> // std::make_integer_sequence does not use auto-value
    using make_reverse_integer_sequence = std::decay_t<decltype(reverse_integer_sequence_v<T, value>)>;
    template <std::size_t N>
    using make_reverse_index_sequence = make_reverse_integer_sequence<std::size_t, N>;
    template <class ... Ts>
    using reverse_index_sequence_for = make_reverse_index_sequence<sizeof...(Ts)>;

    template <std::size_t ... Ints>
    constexpr static auto reverse_index_sequence_v = []<std::size_t ... indexes>(std::index_sequence<indexes...>){
        constexpr auto Ints_as_tuple = std::tuple{Ints...};
        return std::index_sequence<std::get<indexes>(Ints_as_tuple)...>{};
    }(reverse_index_sequence_for<decltype(Ints)...>{});

    template <std::size_t ... Ints>
    using reverse_index_sequence = std::decay_t<decltype(reverse_index_sequence_v<Ints...>)>;
}

namespace gcl::mp::utility::tests
{
    static_assert(std::is_same_v<
        make_reverse_index_sequence<3>,
        std::index_sequence<2, 1, 0>>
    );

    static_assert(std::is_same_v<
        reverse_index_sequence<11, 22, 33>,
        std::index_sequence<33, 22, 11>
    >);
}<|endoftext|>


<commit_before>#include "character.h"
#include "util/bitmap.h"
#include "util/load_exception.h"
#include "nameplacer.h"
#include "animation.h"
#include "util/font.h"
#include "world.h"
#include "globals.h"
#include "util/funcs.h"
#include "buddy_player.h"
#include "factory/font_render.h"

static const char * PLAYER_FONT = "/fonts/arial.ttf";

static const int SPAWN_TIME = 1500;

BuddyPlayer::BuddyPlayer( const Character & chr ) throw( LoadException ):
Character( chr ),
name_id(-1),
invincible( false ),
want_x( -1 ),
want_z( -1 ),
spawn_time( SPAWN_TIME ){
	show_life = getHealth();
	int x, y;
	NamePlacer::getPlacement( x, y, name_id );
}

void BuddyPlayer::draw( Bitmap * work, int rel_x ){
	Character::draw( work, rel_x );

	int x1, y1;
	NamePlacer::getPlacement( x1, y1, name_id );

	if ( icon )
		icon->draw( x1, y1, *work );

	int hasIcon = icon ? icon->getWidth() : 0;

	if ( show_life < 0 ){
		show_life = 0;
	}

	const Font & player_font = Font::getFont( Util::getDataPath() + PLAYER_FONT, 20, 20 );
	const string & name = getName();
	int nameHeight = player_font.getHeight( name ) / 2;
	nameHeight = 20 / 2;
	FontRender * render = FontRender::getInstance();
	render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name );
	drawLifeBar( hasIcon + x1, y1 + nameHeight, work );
	int max = getMaxHealth() < 100 ? getMaxHealth() : 100;
	render->addMessage( player_font, (x1 + hasIcon + max + 5) * 2, y1 + nameHeight, Bitmap::makeColor(255,255,255), -1, "x %d", getLives() );

}

void BuddyPlayer::drawLifeBar( int x, int y, Bitmap * work ){
	drawLifeBar( x, y, show_life, work );
}

Object * BuddyPlayer::copy(){
	return new BuddyPlayer( *this );
}

static int furthestFriend( vector< Object * > * others, int alliance ){
	double x = -1;
	for ( vector< Object * >::iterator it = others->begin(); it != others->end(); it++ ){
		Object * o = *it;
		if ( o->getAlliance() == alliance && o->getX() > x ){
			x = o->getX();
		}
	}

	return (int) x;
}

const Object * BuddyPlayer::findClosest( const vector< Object * > & enemies ){
	Object * e = NULL;
	double max = 0;
	for ( vector< Object * >::const_iterator it = enemies.begin(); it != enemies.end(); it++ ){
		Object * current = *it;
		/* should probably see if current is a character.. */
		double distance = fabs( current->getX() - getX() );
		if ( e == NULL || distance < max ){
			e = current;
			max = distance;
		}
	}

	return e;
}

void BuddyPlayer::act( vector< Object * > * others, World * world, vector< Object * > * add ){
	Character::act( others, world, add );

	if ( show_life > getHealth() ){
		show_life--;
	}

	if ( show_life < getHealth() ){
		show_life++;
	}

	vector< Object * > enemies;

	if ( getStatus() != Status_Ground && getStatus() != Status_Jumping )
		return;

	filterEnemies( enemies, others );

	if ( animation_current->Act() ){
		animation_current->reset();
		// nextTicket();
		// animation_current = movements[ "idle" ];
		animation_current = getMovement( "idle" );
		animation_current->reset();
	}

	if ( animation_current == getMovement( "idle" ) ||
	     animation_current == getMovement( "walk" ) ){
		if ( enemies.empty() && want_x == -1 && want_z == -1 && Util::rnd( 10 ) == 0 ){
			want_x = Util::rnd( 80 ) - 40 + furthestFriend( others, getAlliance() );
			want_z = Util::rnd( world->getMinimumZ(), world->getMaximumZ() );
		} else if ( ! enemies.empty() ){
			const Object * main_enemy = findClosest( enemies );
			if ( main_enemy->getX() > getX() ){
				want_x = (int)(main_enemy->getX() - 20 - Util::rnd( 20 ));
			} else {
				want_x = (int)(main_enemy->getX() + 20 + Util::rnd( 20 ));
			}
			want_z = (int)(Util::rnd( 3 ) - 1 + main_enemy->getZ());
			faceObject( main_enemy );

			if ( Util::rnd( 40 ) == 0 ){
				vector< Animation * > attacks;
				for ( map<string,Animation *>::const_iterator it = getMovements().begin(); it != getMovements().end(); it++ ){
					Animation * maybe = (*it).second;
					if ( maybe->isAttack() && maybe->getStatus() == Status_Ground && maybe->getName() != "special" )
						attacks.push_back( maybe );
				}

				double attack_range = fabs( getX() - main_enemy->getX() );
				double zdistance = ZDistance( main_enemy );
				for ( vector< Animation * >::iterator it = attacks.begin(); it != attacks.end(); ){
					Animation * maybe = *it;
					if ( attack_range > maybe->getRange() || zdistance > maybe->getMinZDistance() ){
						it = attacks.erase( it );
					} else {
						it++;
					}
				}

				if ( !attacks.empty() ){
					animation_current = attacks[ Util::rnd( attacks.size() ) ];
					world->addMessage( animationMessage() );
					nextTicket();
					animation_current->reset();
					return;
				} else {
				}
			}
		}

		if ( want_x != -1 && want_z != -1 ){
			bool walk = false;
			if ( getX() - want_x < -2 ){
				moveX( getSpeed() );
				setFacing( FACING_RIGHT );
				walk = true;
			} else if ( getX() - want_x > 2 ){
				setFacing( FACING_LEFT );
				moveX( getSpeed() );
				walk = true;
			}

			if ( getZ() < want_z ){
				moveZ( getSpeed() );
				walk = true;
			} else if ( getZ() > want_z ){
				moveZ( -getSpeed() );
				walk = true;
			}

			if ( walk ){
				animation_current = getMovement( "walk" );
			}

			if ( fabs(getX() - want_x) <= 2 &&
					fabs(getZ() - want_z) <= 2 ){
				want_x = -1;
				want_z = -1;
				animation_current = getMovement( "idle" );
			}
		}
	}
}

int BuddyPlayer::spawnTime(){
	spawn_time -= 1;
	return spawn_time;
}

void BuddyPlayer::deathReset(){
	setY( 200 );
	spawn_time = SPAWN_TIME;
	setMoving( true );
	setStatus( Status_Falling );
	setHealth( getMaxHealth() );
	setDeath( 0 );
	animation_current = getMovement( "idle" );
}

void BuddyPlayer::takeDamage( World * world, ObjectAttack * obj, int x ){
	Character::takeDamage( world, obj, x );
}

void BuddyPlayer::hurt( int x ){
	if ( ! isInvincible() ){
		Character::hurt( x );
	}
}
<commit_msg>tweak buddy parameters<commit_after>#include "character.h"
#include "util/bitmap.h"
#include "util/load_exception.h"
#include "nameplacer.h"
#include "animation.h"
#include "util/font.h"
#include "world.h"
#include "globals.h"
#include "util/funcs.h"
#include "buddy_player.h"
#include "factory/font_render.h"

static const char * PLAYER_FONT = "/fonts/arial.ttf";

static const int SPAWN_TIME = 1500;

BuddyPlayer::BuddyPlayer( const Character & chr ) throw( LoadException ):
Character( chr ),
name_id(-1),
invincible( false ),
want_x( -1 ),
want_z( -1 ),
spawn_time( SPAWN_TIME ){
	show_life = getHealth();
	int x, y;
	NamePlacer::getPlacement( x, y, name_id );
}

void BuddyPlayer::draw( Bitmap * work, int rel_x ){
	Character::draw( work, rel_x );

	int x1, y1;
	NamePlacer::getPlacement( x1, y1, name_id );

	if ( icon )
		icon->draw( x1, y1, *work );

	int hasIcon = icon ? icon->getWidth() : 0;

	if ( show_life < 0 ){
		show_life = 0;
	}

	const Font & player_font = Font::getFont( Util::getDataPath() + PLAYER_FONT, 20, 20 );
	const string & name = getName();
	int nameHeight = player_font.getHeight( name ) / 2;
	nameHeight = 20 / 2;
	FontRender * render = FontRender::getInstance();
	render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name );
	drawLifeBar( hasIcon + x1, y1 + nameHeight, work );
	int max = getMaxHealth() < 100 ? getMaxHealth() : 100;
	render->addMessage( player_font, (x1 + hasIcon + max + 5) * 2, y1 + nameHeight, Bitmap::makeColor(255,255,255), -1, "x %d", getLives() );

}

void BuddyPlayer::drawLifeBar( int x, int y, Bitmap * work ){
	drawLifeBar( x, y, show_life, work );
}

Object * BuddyPlayer::copy(){
	return new BuddyPlayer( *this );
}

static int furthestFriend( vector< Object * > * others, int alliance ){
	double x = -1;
	for ( vector< Object * >::iterator it = others->begin(); it != others->end(); it++ ){
		Object * o = *it;
		if ( o->getAlliance() == alliance && o->getX() > x ){
			x = o->getX();
		}
	}

	return (int) x;
}

const Object * BuddyPlayer::findClosest( const vector< Object * > & enemies ){
	Object * e = NULL;
	double max = 0;
	for ( vector< Object * >::const_iterator it = enemies.begin(); it != enemies.end(); it++ ){
		Object * current = *it;
		/* should probably see if current is a character.. */
		double distance = fabs( current->getX() - getX() );
		if ( e == NULL || distance < max ){
			e = current;
			max = distance;
		}
	}

	return e;
}

void BuddyPlayer::act( vector< Object * > * others, World * world, vector< Object * > * add ){
	Character::act( others, world, add );

	if ( show_life > getHealth() ){
		show_life--;
	}

	if ( show_life < getHealth() ){
		show_life++;
	}

	vector< Object * > enemies;

	if ( getStatus() != Status_Ground && getStatus() != Status_Jumping )
		return;

	filterEnemies( enemies, others );

	if ( animation_current->Act() ){
		animation_current->reset();
		// nextTicket();
		// animation_current = movements[ "idle" ];
		animation_current = getMovement( "idle" );
		animation_current->reset();
	}

	if ( animation_current == getMovement( "idle" ) ||
	     animation_current == getMovement( "walk" ) ){
		if ( enemies.empty() && want_x == -1 && want_z == -1 && Util::rnd( 15 ) == 0 ){
			want_x = Util::rnd( 100 ) - 50 + furthestFriend( others, getAlliance() );
			want_z = Util::rnd( world->getMinimumZ(), world->getMaximumZ() );
		} else if ( ! enemies.empty() ){
			const Object * main_enemy = findClosest( enemies );
			if ( main_enemy->getX() > getX() ){
				want_x = (int)(main_enemy->getX() - 20 - Util::rnd( 20 ));
			} else {
				want_x = (int)(main_enemy->getX() + 20 + Util::rnd( 20 ));
			}
			want_z = (int)(Util::rnd( 3 ) - 1 + main_enemy->getZ());
			faceObject( main_enemy );

			if ( Util::rnd( 35 ) == 0 ){
				vector< Animation * > attacks;
				for ( map<string,Animation *>::const_iterator it = getMovements().begin(); it != getMovements().end(); it++ ){
					Animation * maybe = (*it).second;
					if ( maybe->isAttack() && maybe->getStatus() == Status_Ground && maybe->getName() != "special" )
						attacks.push_back( maybe );
				}

				double attack_range = fabs( getX() - main_enemy->getX() );
				double zdistance = ZDistance( main_enemy );
				for ( vector< Animation * >::iterator it = attacks.begin(); it != attacks.end(); ){
					Animation * maybe = *it;
					if ( attack_range > maybe->getRange() || zdistance > maybe->getMinZDistance() ){
						it = attacks.erase( it );
					} else {
						it++;
					}
				}

				if ( !attacks.empty() ){
					animation_current = attacks[ Util::rnd( attacks.size() ) ];
					world->addMessage( animationMessage() );
					nextTicket();
					animation_current->reset();
					return;
				} else {
				}
			}
		}

		if ( want_x != -1 && want_z != -1 ){
			bool walk = false;
			if ( getX() - want_x < -2 ){
				moveX( getSpeed() );
				setFacing( FACING_RIGHT );
				walk = true;
			} else if ( getX() - want_x > 2 ){
				setFacing( FACING_LEFT );
				moveX( getSpeed() );
				walk = true;
			}

			if ( getZ() < want_z ){
				moveZ( getSpeed() );
				walk = true;
			} else if ( getZ() > want_z ){
				moveZ( -getSpeed() );
				walk = true;
			}

			if ( walk ){
				animation_current = getMovement( "walk" );
			}

			if ( fabs(getX() - want_x) <= 2 &&
					fabs(getZ() - want_z) <= 2 ){
				want_x = -1;
				want_z = -1;
				animation_current = getMovement( "idle" );
			}
		}
	}
}

int BuddyPlayer::spawnTime(){
	spawn_time -= 1;
	return spawn_time;
}

void BuddyPlayer::deathReset(){
	setY( 200 );
	spawn_time = SPAWN_TIME;
	setMoving( true );
	setStatus( Status_Falling );
	setHealth( getMaxHealth() );
	setDeath( 0 );
	animation_current = getMovement( "idle" );
}

void BuddyPlayer::takeDamage( World * world, ObjectAttack * obj, int x ){
	Character::takeDamage( world, obj, x );
}

void BuddyPlayer::hurt( int x ){
	if ( ! isInvincible() ){
		Character::hurt( x );
	}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_clear_firs.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_xbus_clear_firs.C
/// @brief Clears I/O Firs
///-----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 2
/// *HWP Consumed by      : FSP:HB
///-----------------------------------------------------------------------------
///
/// @verbatim
/// High-level procedure flow:
///
/// Clears I/O Xbus FIRs on the PHY Rx/Tx.
///
/// Clocks must be running.
///
/// @endverbatim
///----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//  Includes
//-----------------------------------------------------------------------------
#include <p9_io_xbus_clear_firs.H>
#include <p9_io_gcr.H>
#include <p9_io_regs.H>

//-----------------------------------------------------------------------------
//  Definitions
//-----------------------------------------------------------------------------
fapi2::ReturnCode io_rx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group);

fapi2::ReturnCode io_tx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group);

/**
 * @brief A HWP that runs on every instance of the XBUS(EDI+)
 * @param[in] i_target         FAPI2 Target
 * @param[in] i_clock_group    Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode p9_io_xbus_clear_firs(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    FAPI_IMP("I/O Start Xbus Clear FIRs");

    FAPI_TRY(io_tx_fir_reset(i_target, i_clock_group), "Tx Reset Failed");

    FAPI_TRY(io_rx_fir_reset(i_target, i_clock_group), "Rx Reset Failed");

fapi_try_exit:
    FAPI_IMP("I/O End Xbus Clear FIRs");
    return fapi2::current_err;
}

/**
 * @brief This function resets the Rx Firs on a EDI+ Xbus
 * @param[in] i_target       FAPI2 Target
 * @param[in] i_clock_group  Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode io_rx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    Register < EDIP_RX_GLBSM_CNTL1_EO_PG > rx_fir_reg;

    FAPI_TRY(rx_fir_reg.read(i_target, i_clock_group),
             "Reading Rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing Rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(1);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing Rx Fir Reg Failed");

fapi_try_exit:
    return fapi2::current_err;
}

/**
 * @brief This function resets the Tx Firs on a EDI+ Xbus
 * @param[in] i_target       FAPI2 Target
 * @param[in] i_clock_group  Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode io_tx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    Register < EDIP_TX_FIR_RESET_PG  > tx_fir_reg;

    FAPI_TRY(tx_fir_reg.read(i_target, i_clock_group),
             "Reading Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(1);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Updated IO Regs to Drop Y and added Scom Access Method<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_clear_firs.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_xbus_clear_firs.C
/// @brief Clears I/O Firs
///-----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 2
/// *HWP Consumed by      : FSP:HB
///-----------------------------------------------------------------------------
///
/// @verbatim
/// High-level procedure flow:
///
/// Clears I/O Xbus FIRs on the PHY Rx/Tx.
///
/// Clocks must be running.
///
/// @endverbatim
///----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//  Includes
//-----------------------------------------------------------------------------
#include <p9_io_xbus_clear_firs.H>
#include <p9_io_gcr.H>
#include <p9_io_regs.H>

//-----------------------------------------------------------------------------
//  Definitions
//-----------------------------------------------------------------------------
fapi2::ReturnCode io_rx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group);

fapi2::ReturnCode io_tx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group);

/**
 * @brief A HWP that runs on every instance of the XBUS(EDI+)
 * @param[in] i_target         FAPI2 Target
 * @param[in] i_clock_group    Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode p9_io_xbus_clear_firs(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    FAPI_IMP("I/O Start Xbus Clear FIRs");

    FAPI_TRY(io_tx_fir_reset(i_target, i_clock_group), "Tx Reset Failed");

    FAPI_TRY(io_rx_fir_reset(i_target, i_clock_group), "Rx Reset Failed");

fapi_try_exit:
    FAPI_IMP("I/O End Xbus Clear FIRs");
    return fapi2::current_err;
}

/**
 * @brief This function resets the Rx Firs on a EDI+ Xbus
 * @param[in] i_target       FAPI2 Target
 * @param[in] i_clock_group  Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode io_rx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    Register < EDIP_RX_GLBSM_CNTLX1_EO_PG > rx_fir_reg;

    FAPI_TRY(rx_fir_reg.read(i_target, i_clock_group),
             "Reading Rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing Rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(1);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing rx Fir Reg Failed");

    rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
    FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
             "Writing Rx Fir Reg Failed");

fapi_try_exit:
    return fapi2::current_err;
}

/**
 * @brief This function resets the Tx Firs on a EDI+ Xbus
 * @param[in] i_target       FAPI2 Target
 * @param[in] i_clock_group  Clock Group
 * @retval ReturnCode
 */
fapi2::ReturnCode io_tx_fir_reset(
    const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
    const uint8_t& i_clock_group)
{
    Register < EDIP_TX_FIR_RESET_PG  > tx_fir_reg;

    FAPI_TRY(tx_fir_reg.read(i_target, i_clock_group),
             "Reading Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(1);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

    tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
    FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
             "Writing Tx Fir Reg Failed");

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: navigationbar.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-04-13 11:15:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef FORMS_COMPONENT_NAVIGATION_BAR_HXX
#define FORMS_COMPONENT_NAVIGATION_BAR_HXX

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif

#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_
#include <com/sun/star/io/XPersistObject.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef COMPHELPER_PROPERTYCONTAINERHELPER_HXX
#include <comphelper/propertycontainerhelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef FORMS_SOURCE_COMPONENT_FORMCONTROLFONT_HXX
#include "formcontrolfont.hxx"
#endif

#include <set>

//.........................................................................
namespace frm
{
//.........................................................................

    //==================================================================
    // ONavigationBarModel
    //==================================================================
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::awt::XControlModel
                                > ONavigationBarModel_BASE;

    class ONavigationBarModel
                        :public OControlModel
                        ,public FontControlModel
                        ,public OPropertyContainerHelper
                        ,public OAggregationArrayUsageHelper< ONavigationBarModel >
                            // though we don't use aggregation, we're derived from an OPropertySetAggregationHelper,
                            // which expects that we use an OPropertyArrayAggregationHelper, which we ensure
                            // with deriving from OAggregationArrayUsageHelper
                        ,public ONavigationBarModel_BASE
    {
        // <properties>
        ::com::sun::star::uno::Any          m_aTabStop;
        ::com::sun::star::uno::Any          m_aBackgroundColor;
        ::rtl::OUString                     m_sDefaultControl;
        ::rtl::OUString                     m_sHelpText;
        ::rtl::OUString                     m_sHelpURL;
        sal_Int16                           m_nIconSize;
        sal_Int16                           m_nBorder;
        sal_Int32                           m_nDelay;
        sal_Bool                            m_bEnabled;
        sal_Bool                            m_bShowPosition;
        sal_Bool                            m_bShowNavigation;
        sal_Bool                            m_bShowActions;
        sal_Bool                            m_bShowFilterSort;
        // </properties>

    public:
        DECLARE_DEFAULT_LEAF_XTOR( ONavigationBarModel );

        // XServiceInfo - static version
        static  ::rtl::OUString SAL_CALL getImplementationName_Static();
        static  ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
        static  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );

    protected:
        // UNO
        DECLARE_UNO3_AGG_DEFAULTS( ONavigationBarModel, OControlModel );
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName()  throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()  throw(::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // OComponentHelper
        virtual void SAL_CALL disposing();

        // XPersistObject
        virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
        virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,
                                              sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                                            throw(::com::sun::star::lang::IllegalArgumentException);
        virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

        // ::com::sun::star::beans::XPropertyState
        virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

        // OAggregationArrayUsageHelper
        virtual void fillProperties(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
            ) const;
        IMPLEMENT_INFO_SERVICE()

    protected:
        DECLARE_XCLONEABLE();

    private:
        void implInitPropertyContainer();
    };

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // FORMS_COMPONENT_NAVIGATION_BAR_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.154); FILE MERGED 2005/09/05 13:50:30 rt 1.2.154.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: navigationbar.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:51:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef FORMS_COMPONENT_NAVIGATION_BAR_HXX
#define FORMS_COMPONENT_NAVIGATION_BAR_HXX

#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif

#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_
#include <com/sun/star/io/XPersistObject.hpp>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef COMPHELPER_PROPERTYCONTAINERHELPER_HXX
#include <comphelper/propertycontainerhelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XSET_HPP_
#include <com/sun/star/container/XSet.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef FORMS_SOURCE_COMPONENT_FORMCONTROLFONT_HXX
#include "formcontrolfont.hxx"
#endif

#include <set>

//.........................................................................
namespace frm
{
//.........................................................................

    //==================================================================
    // ONavigationBarModel
    //==================================================================
    typedef ::cppu::ImplHelper1 <   ::com::sun::star::awt::XControlModel
                                > ONavigationBarModel_BASE;

    class ONavigationBarModel
                        :public OControlModel
                        ,public FontControlModel
                        ,public OPropertyContainerHelper
                        ,public OAggregationArrayUsageHelper< ONavigationBarModel >
                            // though we don't use aggregation, we're derived from an OPropertySetAggregationHelper,
                            // which expects that we use an OPropertyArrayAggregationHelper, which we ensure
                            // with deriving from OAggregationArrayUsageHelper
                        ,public ONavigationBarModel_BASE
    {
        // <properties>
        ::com::sun::star::uno::Any          m_aTabStop;
        ::com::sun::star::uno::Any          m_aBackgroundColor;
        ::rtl::OUString                     m_sDefaultControl;
        ::rtl::OUString                     m_sHelpText;
        ::rtl::OUString                     m_sHelpURL;
        sal_Int16                           m_nIconSize;
        sal_Int16                           m_nBorder;
        sal_Int32                           m_nDelay;
        sal_Bool                            m_bEnabled;
        sal_Bool                            m_bShowPosition;
        sal_Bool                            m_bShowNavigation;
        sal_Bool                            m_bShowActions;
        sal_Bool                            m_bShowFilterSort;
        // </properties>

    public:
        DECLARE_DEFAULT_LEAF_XTOR( ONavigationBarModel );

        // XServiceInfo - static version
        static  ::rtl::OUString SAL_CALL getImplementationName_Static();
        static  ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_Static();
        static  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory );

    protected:
        // UNO
        DECLARE_UNO3_AGG_DEFAULTS( ONavigationBarModel, OControlModel );
        virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName()  throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()  throw(::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        DECLARE_XTYPEPROVIDER()

        // OComponentHelper
        virtual void SAL_CALL disposing();

        // XPersistObject
        virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
        virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,
                                              sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
                                            throw(::com::sun::star::lang::IllegalArgumentException);
        virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

        // ::com::sun::star::beans::XPropertyState
        virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;

        // OAggregationArrayUsageHelper
        virtual void fillProperties(
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
            ) const;
        IMPLEMENT_INFO_SERVICE()

    protected:
        DECLARE_XCLONEABLE();

    private:
        void implInitPropertyContainer();
    };

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // FORMS_COMPONENT_NAVIGATION_BAR_HXX

<|endoftext|>


<commit_before>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// This library is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
/// Library General Public License for more details.
///
/// You should have received a copy of the GNU Library General Public License
/// along with this library; see the file COPYING.LIB.  If not, write to
/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
/// Boston, MA 02110-1301, USA.

#define KDE_DEFAULT_DEBUG_AREA 13050

#include "katescript.h"
#include "katescriptdocument.h"
#include "katescriptview.h"
#include "kateview.h"
#include "katedocument.h"

#include <QFile>

#include <QScriptEngine>
#include <QScriptValue>
#include <QScriptContext>

#include <kdebug.h>
#include <klocale.h>

#include <iostream>

/**
 * metatype register
 */
Q_DECLARE_METATYPE(KTextEditor::Cursor)

/**
 * conversion functions
 */
static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor)
{
  QScriptValue obj = engine->newObject();
  obj.setProperty("line", QScriptValue(engine, cursor.line()));
  obj.setProperty("column", QScriptValue(engine, cursor.column()));
  return obj;
}

static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor)
{
  cursor.setLine (obj.property("line").toInt32());
  cursor.setColumn (obj.property("column").toInt32());
}

namespace Kate {
  namespace Script {

    QScriptValue debug(QScriptContext *context, QScriptEngine *engine) {
      QStringList message;
      for(int i = 0; i < context->argumentCount(); ++i) {
        message << context->argument(i).toString();
      }
      // debug in blue to distance from other debug output if necessary
      kDebug() << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n";
      return engine->nullValue();
    }

  }
}

KateScript::KateScript(const QString &url, const KateScriptInformation &information) :
    m_loaded(false), m_url(url), m_information(information), m_engine(0)
  , m_document (0), m_view (0)
{
}

KateScript::~KateScript()
{
  if(m_loadSuccessful) {
    // remove data...
    delete m_engine;
    delete m_document;
    delete m_view;
  }
}

void KateScript::displayBacktrace(const QScriptValue &error, const QString &header)
{
  if(!m_engine) {
    kDebug(13050) << "KateScript::displayBacktrace: no engine, cannot display error\n";
    return;
  }
  kDebug() << "\033[31m";
  if(!header.isNull())
    kDebug() << qPrintable(header) << ":\n";
  if(error.isError())
    kDebug() << qPrintable(error.toString()) << '\n';
  kDebug() << qPrintable(m_engine->uncaughtExceptionBacktrace().join("\n"));
  kDebug() << "\033[0m" << '\n';
}

QScriptValue KateScript::global(const QString &name)
{
  // load the script if necessary
  if(!load())
    return QScriptValue();
  return m_engine->globalObject().property(name);
}

QScriptValue KateScript::function(const QString &name)
{
  QScriptValue value = global(name);
  if(!value.isFunction())
    return QScriptValue();
  return value;
}

bool KateScript::load()
{
  if(m_loaded)
    return m_loadSuccessful;

  m_loaded = true;
  // read the file into memory
  QString filename = QFile::encodeName(m_url);
  QFile file(filename);
  if (!file.open(QIODevice::ReadOnly)) {
    m_errorMessage = i18n("Unable to read file: '%1'", filename);
    kDebug(13051) << m_errorMessage;
    m_loadSuccessful = false;
    return false;
  }
  QTextStream stream(&file);
  stream.setCodec("UTF-8");
  QString source = stream.readAll();
  file.close();

  // evaluate it
  m_engine = new QScriptEngine();

  // register our types
  qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue);

  QScriptValue result = m_engine->evaluate(source, m_url);
  if(m_engine->hasUncaughtException()) {
    displayBacktrace(result, QString("Error loading %1\n").arg(m_url));
    m_errorMessage = i18n("Error loading script %1", filename);
    m_loadSuccessful = false;
    return false;
  }
  // yip yip!
  initEngine();
  m_loadSuccessful = true;
  return true;
}

void KateScript::initEngine() {
  // set the view/document objects as necessary
  m_engine->globalObject().setProperty("document", m_engine->newQObject(m_document = new KateScriptDocument()));
  m_engine->globalObject().setProperty("view", m_engine->newQObject(m_view = new KateScriptView()));

  m_engine->globalObject().setProperty("debug", m_engine->newFunction(Kate::Script::debug));
}

bool KateScript::setView(KateView *view)
{
  if (!load())
    return false;
  // setup the stuff
  m_document->setDocument (view->doc());
  m_view->setView (view);
  return true;
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Initialise variable. Either that or check if m_loaded is true in the destructor.<commit_after>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// This library is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
/// Library General Public License for more details.
///
/// You should have received a copy of the GNU Library General Public License
/// along with this library; see the file COPYING.LIB.  If not, write to
/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
/// Boston, MA 02110-1301, USA.

#define KDE_DEFAULT_DEBUG_AREA 13050

#include "katescript.h"
#include "katescriptdocument.h"
#include "katescriptview.h"
#include "kateview.h"
#include "katedocument.h"

#include <QFile>

#include <QScriptEngine>
#include <QScriptValue>
#include <QScriptContext>

#include <kdebug.h>
#include <klocale.h>

#include <iostream>

/**
 * metatype register
 */
Q_DECLARE_METATYPE(KTextEditor::Cursor)

/**
 * conversion functions
 */
static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor)
{
  QScriptValue obj = engine->newObject();
  obj.setProperty("line", QScriptValue(engine, cursor.line()));
  obj.setProperty("column", QScriptValue(engine, cursor.column()));
  return obj;
}

static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor)
{
  cursor.setLine (obj.property("line").toInt32());
  cursor.setColumn (obj.property("column").toInt32());
}

namespace Kate {
  namespace Script {

    QScriptValue debug(QScriptContext *context, QScriptEngine *engine) {
      QStringList message;
      for(int i = 0; i < context->argumentCount(); ++i) {
        message << context->argument(i).toString();
      }
      // debug in blue to distance from other debug output if necessary
      kDebug() << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n";
      return engine->nullValue();
    }

  }
}

KateScript::KateScript(const QString &url, const KateScriptInformation &information) :
    m_loaded(false), m_loadSuccessful(false), m_url(url), m_information(information), m_engine(0)
  , m_document (0), m_view (0)
{
}

KateScript::~KateScript()
{
  if(m_loadSuccessful) {
    // remove data...
    delete m_engine;
    delete m_document;
    delete m_view;
  }
}

void KateScript::displayBacktrace(const QScriptValue &error, const QString &header)
{
  if(!m_engine) {
    kDebug(13050) << "KateScript::displayBacktrace: no engine, cannot display error\n";
    return;
  }
  kDebug() << "\033[31m";
  if(!header.isNull())
    kDebug() << qPrintable(header) << ":\n";
  if(error.isError())
    kDebug() << qPrintable(error.toString()) << '\n';
  kDebug() << qPrintable(m_engine->uncaughtExceptionBacktrace().join("\n"));
  kDebug() << "\033[0m" << '\n';
}

QScriptValue KateScript::global(const QString &name)
{
  // load the script if necessary
  if(!load())
    return QScriptValue();
  return m_engine->globalObject().property(name);
}

QScriptValue KateScript::function(const QString &name)
{
  QScriptValue value = global(name);
  if(!value.isFunction())
    return QScriptValue();
  return value;
}

bool KateScript::load()
{
  if(m_loaded)
    return m_loadSuccessful;

  m_loaded = true;
  // read the file into memory
  QString filename = QFile::encodeName(m_url);
  QFile file(filename);
  if (!file.open(QIODevice::ReadOnly)) {
    m_errorMessage = i18n("Unable to read file: '%1'", filename);
    kDebug(13051) << m_errorMessage;
    m_loadSuccessful = false;
    return false;
  }
  QTextStream stream(&file);
  stream.setCodec("UTF-8");
  QString source = stream.readAll();
  file.close();

  // evaluate it
  m_engine = new QScriptEngine();

  // register our types
  qScriptRegisterMetaType (m_engine, cursorToScriptValue, cursorFromScriptValue);

  QScriptValue result = m_engine->evaluate(source, m_url);
  if(m_engine->hasUncaughtException()) {
    displayBacktrace(result, QString("Error loading %1\n").arg(m_url));
    m_errorMessage = i18n("Error loading script %1", filename);
    m_loadSuccessful = false;
    return false;
  }
  // yip yip!
  initEngine();
  m_loadSuccessful = true;
  return true;
}

void KateScript::initEngine() {
  // set the view/document objects as necessary
  m_engine->globalObject().setProperty("document", m_engine->newQObject(m_document = new KateScriptDocument()));
  m_engine->globalObject().setProperty("view", m_engine->newQObject(m_view = new KateScriptView()));

  m_engine->globalObject().setProperty("debug", m_engine->newFunction(Kate::Script::debug));
}

bool KateScript::setView(KateView *view)
{
  if (!load())
    return false;
  // setup the stuff
  m_document->setDocument (view->doc());
  m_view->setView (view);
  return true;
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>