<commit_before>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTUInt16			numChannels = 2;
	TTUInt16			numSamples = 50000;
	TTFloat32			duration = 1500;
	TTUInt32			test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue(TT("numChannels"), numChannels);

	this->getAttributeValue(TT("numChannels"), test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue(TT("lengthInSamples"), numSamples);

	this->getAttributeValue(TT("lengthInSamples"), test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue(TT("length"), test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue(TT("length"), duration);

	this->getAttributeValue(TT("length"), test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue(TT("lengthInSamples"), test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<commit_msg>SampleMatrix: built tests for interpolation between samples<commit_after>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTUInt16			numChannels = 2;
	TTUInt16			numSamples = 50000;
	TTFloat32			duration = 1500;
	TTUInt32			test9Index = 10;
	TTUInt32			test10Index = 11;
	TTUInt32			test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;
	TTSampleValue		test9Return, test10Return, test11Return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue(TT("numChannels"), numChannels);

	this->getAttributeValue(TT("numChannels"), test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue(TT("lengthInSamples"), numSamples);

	this->getAttributeValue(TT("lengthInSamples"), test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue(TT("length"), test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue(TT("length"), duration);

	this->getAttributeValue(TT("length"), test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue(TT("lengthInSamples"), test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	// TEST 9 & 10: set the value of two consecutive samples
	TTSampleValue pokeValue9 = TTRandom64();
	TTSampleValue pokeValue10 = TTRandom64();

	this->poke(test9Index, 1, pokeValue9);
	this->poke(test10Index, 1, pokeValue10);

	this->peek(test9Index, 1, test9Return);
	this->peek(test10Index, 1, test10Return);

	TTBoolean result9 = { pokeValue9 == test9Return };

	TTTestAssertion("set value one of two consecutive samples",
								result9,
								testAssertionCount,
								errorCount);

	if(!result9)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return);
	}

	TTBoolean result10 = { pokeValue10 == test10Return };

	TTTestAssertion("set value two of two consecutive samples",
								result10,
								testAssertionCount,
								errorCount);

	if(!result10)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return);
	}

	// TEST 11: test for interpolation between two consecutive samples
	TTFloat64 computedInterpFraction = TTRandom64();
	TTFloat64 computedInterpIndex = test9Index + computedInterpFraction;
	TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);

	this->peeki(computedInterpIndex, 1, test11Return);

	TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);

	TTTestAssertion("interpolate between two consecutive samples",
								result11,
								testAssertionCount,
								errorCount);

	if(!result11)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return);
	}

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<|endoftext|>


<commit_before>#ifndef __JSON_HPP__
#define __JSON_HPP__

#include <cctype>
#include <string>
#include <vector>
#include <regex>

namespace JSON {
	using namespace std;

	struct Error {};
	struct SyntaxError : public Error {};
	struct LoadError : public Error {};
	struct AccessError : public Error {};

	template<typename _Value, char const ..._szName>
	struct Field {
		static char const s_szName;
		typedef _Value Type;
	};

	template<char const ..._sz>
	struct FieldName {};

	template<typename _Name, typename ..._Fields>
	struct GetFieldType {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct GetFieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
		typedef _Value Type;
	};

	template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
	struct GetFieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
		typedef typename GetFieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
	};

	template<typename _Value, char const ..._szName>
	char const Field<_Value, _szName...>::s_szName = { _szName... };

	template<typename ..._Fields>
	struct Object {};

	template<typename _Field, typename ..._Fields>
	struct Getter {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
		static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
			return rObject.m_Value;
		}

		static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
			return rObject.m_Value;
		}
	};

	template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
		static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
			return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
		}

		static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
			return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
		}
	};

	template<>
	struct Object<> {
		Object() {}
		virtual ~Object() {}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<Field<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;

		Object() {}

		virtual ~Object() {}

		template<char const ..._szFieldName>
		typename GetFieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
			return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this);
		}

		template<char const ..._szFieldName>
		typename GetFieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
			return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this);
		}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Type>
	struct Loader {
		static _Type Load(istream &ris);
	};

	template<>
	struct Loader<nullptr_t> {
		static nullptr_t Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<bool> {
		static bool Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<int> {
		static int Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<unsigned int> {
		static unsigned int Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<double> {
		static double Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<string> {
		static string Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename ..._Fields>
	struct Loader<Object<_Fields...>> {
		static Object<_Fields...> Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element>
	struct Loader<vector<_Element>> {
		static vector<_Element> Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename _Type>
	_Type Load(istream &ris) {
		return Loader<_Type>::Load(ris);
	}
}

#define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0

#endif
<commit_msg>GetFieldType -> FieldType<commit_after>#ifndef __JSON_HPP__
#define __JSON_HPP__

#include <cctype>
#include <string>
#include <vector>
#include <regex>

namespace JSON {
	using namespace std;

	struct Error {};
	struct SyntaxError : public Error {};
	struct LoadError : public Error {};
	struct AccessError : public Error {};

	template<typename _Value, char const ..._szName>
	struct Field {
		static char const s_szName;
		typedef _Value Type;
	};

	template<char const ..._sz>
	struct FieldName {};

	template<typename _Name, typename ..._Fields>
	struct FieldType {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
		typedef _Value Type;
	};

	template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
	struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
		typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
	};

	template<typename _Value, char const ..._szName>
	char const Field<_Value, _szName...>::s_szName = { _szName... };

	template<typename ..._Fields>
	struct Object {};

	template<typename _Field, typename ..._Fields>
	struct Getter {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
		static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
			return rObject.m_Value;
		}

		static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
			return rObject.m_Value;
		}
	};

	template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
		static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
			return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
		}

		static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
			return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
		}
	};

	template<>
	struct Object<> {
		Object() {}
		virtual ~Object() {}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<Field<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;

		Object() {}

		virtual ~Object() {}

		template<char const ..._szFieldName>
		typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
			return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this);
		}

		template<char const ..._szFieldName>
		typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
			return Getter<Field<_Value, _szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Get(*this);
		}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Type>
	struct Loader {
		static _Type Load(istream &ris);
	};

	template<>
	struct Loader<nullptr_t> {
		static nullptr_t Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<bool> {
		static bool Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<int> {
		static int Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<unsigned int> {
		static unsigned int Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<double> {
		static double Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<>
	struct Loader<string> {
		static string Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename ..._Fields>
	struct Loader<Object<_Fields...>> {
		static Object<_Fields...> Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element>
	struct Loader<vector<_Element>> {
		static vector<_Element> Load(istream &ris) {
			// TODO
			throw Error();
		}
	};

	template<typename _Type>
	_Type Load(istream &ris) {
		return Loader<_Type>::Load(ris);
	}
}

#define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0

#endif
<|endoftext|>


<commit_before>#include "socket.h"
#include "dialer.h"
#include "listener.h"
#include "exceptions.hpp"

#include <vector>

namespace nng {

    using std::placeholders::_1;
    using std::placeholders::_2;
    using std::placeholders::_3;
    using std::placeholders::_4;

    socket::socket(const nng_ctor_func& nng_ctor)
        : sid(0)
        , sender()
        , receiver()
        , messenger()
        , options() {

        const auto errnum = nng_ctor(&sid);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    socket::~socket() {
        close();
    }

    void socket::close() {
        // Close is its own operation apart from Shutdown.
        const auto op = std::bind(&::nng_close, _1);
        const auto errnum = op(sid);
        THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone);
        // Closed is closed.
        sid = 0;
    }

    void socket::shutdown() {
        // Shutdown is its own operation apart from Closed.
        const auto op = std::bind(&::nng_shutdown, _1);
        const auto errnum = op(sid);
        THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone);
        // Which socket can still be in operation.
    }

    bool socket::is_open() const {
        return sid != 0;
    }

    // TODO: TBD: ditto ec handling...
    void socket::listen(const std::string& addr, flag_type flags) {
        const auto errnum = ::nng_listen(sid, addr.c_str(), nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::listen(const std::string& addr, listener* const lp, flag_type flags) {
        const auto errnum = ::nng_listen(sid, addr.c_str(), lp ? &(lp->lid) : nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::dial(const std::string& addr, flag_type flags) {
        const auto errnum = ::nng_dial(sid, addr.c_str(), nullptr, flags);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::dial(const std::string& addr, dialer* const dp, flag_type flags) {
        const auto errnum = ::nng_dial(sid, addr.c_str(), dp ? &(dp->did) : nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    template<class Buffer_>
    int send(int id, const Buffer_& buf, std::size_t sz, flag_type flags) {
        // &buf[0] ????
        const auto errnum = ::nng_send(id, (void*)buf.data(), sz, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
        return errnum;
    }

    template<class Buffer_>
    int try_receive(int id, Buffer_& buf, std::size_t& sz, flag_type flags) {
        buf.resize(sz);
        // &buf[0] ????
        const auto errnum = ::nng_recv(id, (void*)buf.data(), &sz, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
        return errnum;
    }

    void socket::send(binary_message_type* const bmp, flag_type flags) {
        auto* msgp = bmp->get_msgp();
        const auto op = std::bind(&::nng_sendmsg, _1, _2, _3);
        const auto errnum = op(sid, msgp, static_cast<int>(flags));
        /* Yes, this is not a mistake. Message passing semantics means that NNG assumes
        ownership of the message after passing. Effectively, this nullifies the message. */
        // TODO: TBD: at least for now this seems reasonable: depending on the error code, we may or may not want to do this...
        if (!errnum) { bmp->on_sent(); }
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    int socket::send(const buffer_vector_type* const bufp, flag_type flags) {
        return nng::send(sid, *bufp, bufp->size(), flags);
    }

    int socket::send(const buffer_vector_type* const bufp, size_type sz, flag_type flags) {
        return nng::send(sid, *bufp, sz, flags);
    }

    std::unique_ptr<socket::binary_message_type> socket::receive(flag_type flags) {
        auto bmup = std::make_unique<binary_message_type>();
        try_receive(bmup.get(), flags);
        return bmup;
    }

    int socket::try_receive(binary_message_type* const bmp, flag_type flags) {
        /* So this is somewhat of a long way around, but it represents the cost of NNG message
        ownership semantics. The cost has to be paid at some point, either on the front side or
        the back side, so we pay for it here in additional semantics. */
        ::nng_msg* msgp = nullptr;
        const auto errnum = ::nng_recvmsg(sid, &msgp, static_cast<int>(flags));
        try {
            // Which we actually do want to set this one.
            THROW_NNG_EXCEPTION_EC(errnum);
        }
        catch (...) {
            // TODO: TBD: this is probably (PROBABLY) about as good as we can expect here...
            if (msgp) { ::nng_msg_free(msgp); }
            // Re-throw the exception after taking care of potential memory allocation.
            throw;
        }
        bmp->set_msgp(msgp);
        return errnum;
    }

    socket::buffer_vector_type socket::receive(size_type& sz, flag_type flags) {
        buffer_vector_type buf;
        try_receive(&buf, sz, flags);
        return buf;
    }

    int socket::try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags) {
        return nng::try_receive(sid, *bufp, sz, flags);
    }

    // Convenience option wrappers.
    void socket::set_option(const std::string& name, const std::string& val, size_type sz) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), sz);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option(const std::string& name, const std::string& val) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), val.length());
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option(const std::string& name, std::string& val, size_type& sz) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz);
        THROW_NNG_EXCEPTION_EC(errnum);
        // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers.
        val.resize(sz - 1);
    }

    void socket::get_option(const std::string& name, std::string& val) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        size_type sz = val.size();
        const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz);
        THROW_NNG_EXCEPTION_EC(errnum);
        // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers.
        val.resize(sz - 1);
    }

    void socket::set_option(const std::string& name, const void* valp, size_type sz) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), valp, sz);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option(const std::string& name, void* val, size_type* szp) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), val, szp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_int(const std::string& name, int val) {
        const auto op = std::bind(&::nng_setopt_int, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_size(const std::string& name, size_type val) {
        const auto op = std::bind(&::nng_setopt_size, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_usec(const std::string& name, uint64_t val) {
        const auto op = std::bind(&::nng_setopt_usec, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_int(const std::string& name, int* valp) {
        const auto op = std::bind(&::nng_getopt_int, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_size(const std::string& name, size_type* valp) {
        const auto op = std::bind(&::nng_getopt_size, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_usec(const std::string& name, uint64_t* valp) {
        const auto op = std::bind(&::nng_getopt_usec, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    protocol_type to_protocol_type(int value) {
        return static_cast<protocol_type>(value);
    }

    int to_int(const protocol_type value) {
        return static_cast<int>(value);
    }

    protocol_type socket::get_protocol() const {
        return to_protocol_type(::nng_protocol(sid));
    }

    protocol_type socket::get_peer() const {
        return to_protocol_type(::nng_peer(sid));
    }

    bool socket::is_protocol_configured() const {
        return get_protocol() != protocol_none;
    }

    bool socket::is_peer_configured() const {
        return get_peer() != protocol_none;
    }
}
<commit_msg>bindings were not the problem with IPC but I prefer the bindings to help with troubleshooting later on<commit_after>#include "socket.h"
#include "dialer.h"
#include "listener.h"
#include "exceptions.hpp"

#include <vector>

namespace nng {

    using std::placeholders::_1;
    using std::placeholders::_2;
    using std::placeholders::_3;
    using std::placeholders::_4;

    socket::socket(const nng_ctor_func& nng_ctor)
        : sid(0)
        , sender()
        , receiver()
        , messenger()
        , options() {

        const auto errnum = nng_ctor(&sid);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    socket::~socket() {
        close();
    }

    void socket::close() {
        // Close is its own operation apart from Shutdown.
        const auto op = std::bind(&::nng_close, _1);
        const auto errnum = op(sid);
        THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone);
        // Closed is closed.
        sid = 0;
    }

    void socket::shutdown() {
        // Shutdown is its own operation apart from Closed.
        const auto op = std::bind(&::nng_shutdown, _1);
        const auto errnum = op(sid);
        THROW_NNG_EXCEPTION_IF_NOT_ONEOF(errnum, ec_eunknown, ec_enone);
        // Which socket can still be in operation.
    }

    bool socket::is_open() const {
        return sid != 0;
    }

    // TODO: TBD: ditto ec handling...
    void socket::listen(const std::string& addr, flag_type flags) {
        const auto& op = std::bind(&::nng_listen, _1, _2, _3, _4);
        const auto errnum = op(sid, addr.c_str(), nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::listen(const std::string& addr, listener* const lp, flag_type flags) {
        const auto& op = std::bind(&::nng_listen, _1, _2, _3, _4);
        const auto errnum = op(sid, addr.c_str(), lp ? &(lp->lid) : nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::dial(const std::string& addr, flag_type flags) {
        const auto& op = std::bind(&::nng_dial, _1, _2, _3, _4);
        const auto errnum = op(sid, addr.c_str(), nullptr, flags);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::dial(const std::string& addr, dialer* const dp, flag_type flags) {
        const auto& op = std::bind(&::nng_dial, _1, _2, _3, _4);
        const auto errnum = op(sid, addr.c_str(), dp ? &(dp->did) : nullptr, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    template<class Buffer_>
    int send(int id, const Buffer_& buf, std::size_t sz, flag_type flags) {
        // &buf[0] ????
        const auto errnum = ::nng_send(id, (void*)buf.data(), sz, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
        return errnum;
    }

    template<class Buffer_>
    int try_receive(int id, Buffer_& buf, std::size_t& sz, flag_type flags) {
        buf.resize(sz);
        // &buf[0] ????
        const auto errnum = ::nng_recv(id, (void*)buf.data(), &sz, static_cast<int>(flags));
        THROW_NNG_EXCEPTION_EC(errnum);
        return errnum;
    }

    void socket::send(binary_message_type* const bmp, flag_type flags) {
        auto* msgp = bmp->get_msgp();
        const auto op = std::bind(&::nng_sendmsg, _1, _2, _3);
        const auto errnum = op(sid, msgp, static_cast<int>(flags));
        /* Yes, this is not a mistake. Message passing semantics means that NNG assumes
        ownership of the message after passing. Effectively, this nullifies the message. */
        // TODO: TBD: at least for now this seems reasonable: depending on the error code, we may or may not want to do this...
        if (!errnum) { bmp->on_sent(); }
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    int socket::send(const buffer_vector_type* const bufp, flag_type flags) {
        return nng::send(sid, *bufp, bufp->size(), flags);
    }

    int socket::send(const buffer_vector_type* const bufp, size_type sz, flag_type flags) {
        return nng::send(sid, *bufp, sz, flags);
    }

    std::unique_ptr<socket::binary_message_type> socket::receive(flag_type flags) {
        auto bmup = std::make_unique<binary_message_type>();
        try_receive(bmup.get(), flags);
        return bmup;
    }

    int socket::try_receive(binary_message_type* const bmp, flag_type flags) {
        /* So this is somewhat of a long way around, but it represents the cost of NNG message
        ownership semantics. The cost has to be paid at some point, either on the front side or
        the back side, so we pay for it here in additional semantics. */
        ::nng_msg* msgp = nullptr;
        const auto errnum = ::nng_recvmsg(sid, &msgp, static_cast<int>(flags));
        try {
            // Which we actually do want to set this one.
            THROW_NNG_EXCEPTION_EC(errnum);
        }
        catch (...) {
            // TODO: TBD: this is probably (PROBABLY) about as good as we can expect here...
            if (msgp) { ::nng_msg_free(msgp); }
            // Re-throw the exception after taking care of potential memory allocation.
            throw;
        }
        bmp->set_msgp(msgp);
        return errnum;
    }

    socket::buffer_vector_type socket::receive(size_type& sz, flag_type flags) {
        buffer_vector_type buf;
        try_receive(&buf, sz, flags);
        return buf;
    }

    int socket::try_receive(buffer_vector_type* const bufp, size_type& sz, flag_type flags) {
        return nng::try_receive(sid, *bufp, sz, flags);
    }

    // Convenience option wrappers.
    void socket::set_option(const std::string& name, const std::string& val, size_type sz) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), sz);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option(const std::string& name, const std::string& val) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = ::nng_setopt(sid, name.c_str(), val.c_str(), val.length());
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option(const std::string& name, std::string& val, size_type& sz) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz);
        THROW_NNG_EXCEPTION_EC(errnum);
        // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers.
        val.resize(sz - 1);
    }

    void socket::get_option(const std::string& name, std::string& val) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        size_type sz = val.size();
        const auto errnum = op(sid, name.c_str(), (void*)&val[0], &sz);
        THROW_NNG_EXCEPTION_EC(errnum);
        // Do this because the C++ buffer does not appear to be honored quite right when working with the C buffers.
        val.resize(sz - 1);
    }

    void socket::set_option(const std::string& name, const void* valp, size_type sz) {
        const auto op = std::bind(&::nng_setopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), valp, sz);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option(const std::string& name, void* val, size_type* szp) {
        const auto op = std::bind(&::nng_getopt, _1, _2, _3, _4);
        const auto errnum = op(sid, name.c_str(), val, szp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_int(const std::string& name, int val) {
        const auto op = std::bind(&::nng_setopt_int, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_size(const std::string& name, size_type val) {
        const auto op = std::bind(&::nng_setopt_size, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::set_option_usec(const std::string& name, uint64_t val) {
        const auto op = std::bind(&::nng_setopt_usec, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), val);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_int(const std::string& name, int* valp) {
        const auto op = std::bind(&::nng_getopt_int, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_size(const std::string& name, size_type* valp) {
        const auto op = std::bind(&::nng_getopt_size, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    void socket::get_option_usec(const std::string& name, uint64_t* valp) {
        const auto op = std::bind(&::nng_getopt_usec, _1, _2, _3);
        const auto errnum = op(sid, name.c_str(), valp);
        THROW_NNG_EXCEPTION_EC(errnum);
    }

    protocol_type to_protocol_type(int value) {
        return static_cast<protocol_type>(value);
    }

    int to_int(const protocol_type value) {
        return static_cast<int>(value);
    }

    protocol_type socket::get_protocol() const {
        return to_protocol_type(::nng_protocol(sid));
    }

    protocol_type socket::get_peer() const {
        return to_protocol_type(::nng_peer(sid));
    }

    bool socket::is_protocol_configured() const {
        return get_protocol() != protocol_none;
    }

    bool socket::is_peer_configured() const {
        return get_peer() != protocol_none;
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_RESOURCEREF_HPP
#define NAZARA_RESOURCEREF_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <type_traits>

template<typename T>
class NzObjectRef
{
	static_assert(std::is_base_of<NzRefCounted, T>::value, "ObjectRef shall only be used with RefCounted-derived type");

	public:
		NzObjectRef();
		NzObjectRef(T* object);
		NzObjectRef(const NzObjectRef& ref);
		template<typename U> NzObjectRef(const NzObjectRef<U>& ref);
		NzObjectRef(NzObjectRef&& ref) noexcept;
		~NzObjectRef();

		T* Get() const;
		bool IsValid() const;
		T* Release();
		bool Reset(T* object = nullptr);
		NzObjectRef& Swap(NzObjectRef& ref);

		operator bool() const;
		operator T*() const;
		T* operator->() const;

		NzObjectRef& operator=(T* object);
		NzObjectRef& operator=(const NzObjectRef& ref);
		template<typename U> NzObjectRef& operator=(const NzObjectRef<U>& ref);
		NzObjectRef& operator=(NzObjectRef&& ref) noexcept;

	private:
		T* m_object;
};

#include <Nazara/Core/ObjectRef.inl>

#endif // NAZARA_RESOURCEREF_HPP
<commit_msg>Core/ObjectRef: Remove static_assert<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_RESOURCEREF_HPP
#define NAZARA_RESOURCEREF_HPP

#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <type_traits>

template<typename T>
class NzObjectRef
{
	public:
		NzObjectRef();
		NzObjectRef(T* object);
		NzObjectRef(const NzObjectRef& ref);
		template<typename U> NzObjectRef(const NzObjectRef<U>& ref);
		NzObjectRef(NzObjectRef&& ref) noexcept;
		~NzObjectRef();

		T* Get() const;
		bool IsValid() const;
		T* Release();
		bool Reset(T* object = nullptr);
		NzObjectRef& Swap(NzObjectRef& ref);

		operator bool() const;
		operator T*() const;
		T* operator->() const;

		NzObjectRef& operator=(T* object);
		NzObjectRef& operator=(const NzObjectRef& ref);
		template<typename U> NzObjectRef& operator=(const NzObjectRef<U>& ref);
		NzObjectRef& operator=(NzObjectRef&& ref) noexcept;

	private:
		T* m_object;
};

#include <Nazara/Core/ObjectRef.inl>

#endif // NAZARA_RESOURCEREF_HPP
<|endoftext|>


<commit_before>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <boost/filesystem.hpp>

#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

#include <dune/grid/multiscale/provider/cube.hh>

#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/misc/gridwidth.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/discretefunction/norm.hh>
#include <dune/stuff/function/expression.hh>

#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
  const int polOrder = POLORDER;
#else
  const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.ms.semidg.ddd";

using namespace Dune;

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "exact_solution.order = 2" << std::endl;
    file << "exact_solution.variable = x" << std::endl;
    file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl;
    file << "[grid.multiscale.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = [4; 4; 4]" << std::endl;
    file << "boundaryId = 7" << std::endl;                  // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
    file << "partitions = [2; 2; 2]" << std::endl;
    file << "filename = " << id << ".msGrid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0" << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl;
    file << "force.order = 0" << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [0.0; 0.0; 0.0]" << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [0.0; 0.0; 0.0]" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
    file << "discretization.penaltyFactor = 10.0" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class MultiscaleDiscreteFunctionType,
          class OutStreamType >
void compute_errors(Dune::ParameterTree& paramTree,
                    const MultiscaleDiscreteFunctionType& discreteFunction,
                    OutStreamType& out,
                    std::string prefix = "")
{
  // exact solution
  typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType;
  typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType;
  typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType;
  typedef Dune::Stuff::Function::Expression<
      DomainFieldType,
      DiscreteFunctionType::dimDomain,
      RangeFieldType,
      DiscreteFunctionType::dimRange >
    FunctionType;
  const FunctionType function(paramTree);
  const unsigned int functionOrder = paramTree.get("order", 100);
  // compute norms
  out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
  const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()),
                                                                               function,
                                                                               functionOrder);
  out.precision(2);
  out << prefix << "   L2 | " << std::setw(14) << std::scientific << L2_reference_norm
                                      << " | " << std::flush;
  const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction);
  out << std::setw(17) << std::scientific << L2_discrete_norm
                                                          << " | " << std::flush;
  const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction);
  out << std::setw(11) << std::scientific << L2_difference
                                                                        << " | " << std::flush;
  out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
//  const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution);
//  out.precision(2);
//  out << prefix << "   h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush;
//  const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution);
//  out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush;
//  const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution);
//  out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush;
//  out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl;
//  out << prefix << "------+-----------+------------+-------------+-------------" << std::endl;
} // void compute_norms(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Stuff::Common::ParameterTreeX paramTree(argc, argv, filename);

    // logger
    Stuff::Common::Logger().create(Stuff::Common::LOG_INFO |
                                   Stuff::Common::LOG_CONSOLE |
                                   Stuff::Common::LOG_DEBUG);
    Stuff::Common::LogStream& info = Stuff::Common::Logger().info();
    Stuff::Common::LogStream& debug = Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
    const GridProviderType gridProvider = GridProviderType::createFromParamTree(paramTree);
    typedef GridProviderType::MsGridType MsGridType;
    const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGrid();
    info << "  took " << timer.elapsed()
         << " sec (has " << gridProvider.grid()->size(0) << " elements, "
         << msGrid->size() << " subdomain";
    if (msGrid->size() > 1)
      info << "s";
    info << " and a width of "
         << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl;
    debug.resume();
    info << "visualizing grid... " << std::flush;
    timer.reset();
    debug.suspend();
    msGrid->visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_msGrid"));
    info << "done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    info << "setting up model... " << std::flush;
    debug.suspend();
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    typedef Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const shared_ptr< const ModelType > model(new ModelType(ModelType::createFromParamTree(paramTree)));
    typedef Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    // solver
    info << "initializing solver";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::Multiscale
        ::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder >
        SolverType;
    const Stuff::Common::ParameterTreeX solverTree = paramTree.sub(SolverType::id());
    const Stuff::Common::ParameterTreeX discretizationTree = solverTree.sub("discretization");
    SolverType solver(model, msGrid, boundaryInfo, discretizationTree.get< RangeFieldType >("penaltyFactor"));
    solver.init("  ", debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    info << "solving";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef SolverType::VectorBackendType VectorType;
    Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector();
    solver.solve(*solution,
                 solverTree.get("solve.type", "eigen.bicgstab.diagonal"),
                 solverTree.get("solve.maxIter", 5000u),
                 solverTree.get("solve.precision", 1e-12),
                 "  ",
                 debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

//    info << "computing detailed reference solution... " << std::flush;
//    debug.suspend();
//    timer.reset();
//    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations<
//        ModelType,
//        typename MsGridType::GlobalGridPartType,
//        BoundaryInfoType,
//        polOrder >
//      ReferenceSolverType;
//    ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo);
//    referenceSolver.init();
//    Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector();
//    referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), "  ", debug);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
//    debug.resume();

    info << "postprocessing";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    solver.visualize(*solution,
                     solverTree.get("visualize.filename", id + ".solution"),
                     solverTree.get("visualize.name", "solution"),
                     "  ",
                     debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

//    if (dimDomain == 1) {
//      info << "computing norms:" << std::endl;
//      debug.suspend();
//      referenceSolver.visualize(*referenceSolution,
//                                paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference",
//                                paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference",
//                                "  ",
//                                debug);

//      Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution");
//      debug.resume();
//      compute_errors(paramTree.sub(id).sub("exact_solution"),
//                     *discreteSolution,
//                     info, "  ");
//    }
    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples...elliptic.ms.semidg...] update<commit_after>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <boost/filesystem.hpp>

#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

#include <dune/grid/multiscale/provider/cube.hh>

#include <dune/fem/misc/mpimanager.hh>
#include <dune/fem/misc/gridwidth.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/discretefunction/norm.hh>
#include <dune/stuff/function/expression.hh>

#include <dune/detailed/solvers/stationary/linear/elliptic/model.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/continuousgalerkin/dune-detailed-discretizations.hh>

#ifdef POLORDER
  const int polOrder = POLORDER;
#else
  const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.ms.semidg.ddd";

using namespace Dune;
using namespace Dune::Detailed::Solvers;

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "exact_solution.order = 2" << std::endl;
    file << "exact_solution.variable = x" << std::endl;
    file << "exact_solution.expression.0 = -0.5*x[0]*x[0] + 0.5*x[0]" << std::endl;
    file << "[grid.multiscale.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = [4; 4; 4]" << std::endl;
    file << "boundaryId = 7" << std::endl;                  // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
    file << "partitions = [2; 2; 2]" << std::endl;
    file << "filename = " << id << ".msGrid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0" << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression = [1.0; 1.0; 1.0]" << std::endl;
    file << "force.order = 0" << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]" << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [0.0; 0.0; 0.0]" << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [0.0; 0.0; 0.0]" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
    file << "discretization.penaltyFactor = 10.0" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class MultiscaleDiscreteFunctionType,
          class OutStreamType >
void compute_errors(Dune::ParameterTree& paramTree,
                    const MultiscaleDiscreteFunctionType& discreteFunction,
                    OutStreamType& out,
                    std::string prefix = "")
{
  // exact solution
  typedef typename MultiscaleDiscreteFunctionType::LocalDiscreteFunctionType DiscreteFunctionType;
  typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType;
  typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType;
  typedef Dune::Stuff::Function::Expression<
      DomainFieldType,
      DiscreteFunctionType::dimDomain,
      RangeFieldType,
      DiscreteFunctionType::dimRange >
    FunctionType;
  const FunctionType function(paramTree);
  const unsigned int functionOrder = paramTree.get("order", 100);
  // compute norms
  out << prefix << " norm | exact solution | discrete solution | error (abs) | error (rel)" << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
  const RangeFieldType L2_reference_norm = Dune::Stuff::DiscreteFunction::Norm::L2(*(discreteFunction.msGrid().globalGridPart()),
                                                                               function,
                                                                               functionOrder);
  out.precision(2);
  out << prefix << "   L2 | " << std::setw(14) << std::scientific << L2_reference_norm
                                      << " | " << std::flush;
  const RangeFieldType L2_discrete_norm = Dune::Stuff::DiscreteFunction::Norm::L2(discreteFunction);
  out << std::setw(17) << std::scientific << L2_discrete_norm
                                                          << " | " << std::flush;
  const RangeFieldType L2_difference = Dune::Stuff::DiscreteFunction::Norm::L2_difference(function, functionOrder, discreteFunction);
  out << std::setw(11) << std::scientific << L2_difference
                                                                        << " | " << std::flush;
  out << std::setw(11) << std::scientific << L2_difference/L2_reference_norm << std::endl;
  out << prefix << "------+----------------+-------------------+-------------+-------------" << std::endl;
//  const RangeFieldType h1_reference_norm = Dune::Stuff::DiscreteFunction::Norm::h1(referenceSolution);
//  out.precision(2);
//  out << prefix << "   h1 | " << std::setw(9) << std::scientific << h1_reference_norm << " | " << std::flush;
//  const RangeFieldType h1_multiscale_norm = Dune::Stuff::DiscreteFunction::Norm::h1(multiscaleSolution);
//  out << std::setw(10) << std::scientific << h1_multiscale_norm << " | " << std::flush;
//  const RangeFieldType h1_difference = Dune::Stuff::DiscreteFunction::Norm::h1_difference(referenceSolution, multiscaleSolution);
//  out << std::setw(11) << std::scientific << h1_difference << " | " << std::flush;
//  out << std::setw(11) << std::scientific << h1_difference/h1_reference_norm << std::endl;
//  out << prefix << "------+-----------+------------+-------------+-------------" << std::endl;
} // void compute_norms(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    MPIManager::initialize(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Stuff::Common::ParameterTreeX paramTree(argc, argv, filename);

    // logger
    Stuff::Common::Logger().create(Stuff::Common::LOG_INFO |
                                   Stuff::Common::LOG_CONSOLE |
                                   Stuff::Common::LOG_DEBUG);
    Stuff::Common::LogStream& info = Stuff::Common::Logger().info();
    Stuff::Common::LogStream& debug = Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
    const GridProviderType gridProvider = GridProviderType::createFromParamTree(paramTree);
    typedef GridProviderType::MsGridType MsGridType;
    const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGrid();
    info << "  took " << timer.elapsed()
         << " sec (has " << gridProvider.grid()->size(0) << " elements, "
         << msGrid->size() << " subdomain";
    if (msGrid->size() > 1)
      info << "s";
    info << " and a width of "
         << Dune::GridWidth::calcGridWidth(*(msGrid->globalGridPart())) << ")" << std::endl;
    debug.resume();
    info << "visualizing grid... " << std::flush;
    timer.reset();
    debug.suspend();
    msGrid->visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_msGrid"));
    info << "done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    info << "setting up model... " << std::flush;
    debug.suspend();
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    typedef Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain,
                                                            RangeFieldType, dimRange >
        ModelType;
    const std::string modelType = paramTree.get< std::string >(id + ".model");
    const shared_ptr< const ModelType > model(
          Stationary::Linear::Elliptic::Model::create< DomainFieldType, dimDomain, RangeFieldType, dimRange >(modelType,
                                                                                paramTree));
    typedef Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    // solver
    info << "initializing solver";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::Multiscale
        ::SemicontinuousGalerkin::DuneDetailedDiscretizations< ModelType, MsGridType, BoundaryInfoType, polOrder >
        SolverType;
    const Stuff::Common::ParameterTreeX solverTree = paramTree.sub(SolverType::id());
    const Stuff::Common::ParameterTreeX discretizationTree = solverTree.sub("discretization");
    SolverType solver(model, msGrid, boundaryInfo, discretizationTree.get< RangeFieldType >("penaltyFactor"));
    solver.init("  ", debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

    info << "solving";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    typedef SolverType::VectorBackendType VectorType;
    Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector();
    solver.solve(*solution,
                 solverTree.get("solve.type", "eigen.bicgstab.diagonal"),
                 solverTree.get("solve.maxIter", 5000u),
                 solverTree.get("solve.precision", 1e-12),
                 "  ",
                 debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

//    info << "computing detailed reference solution... " << std::flush;
//    debug.suspend();
//    timer.reset();
//    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::ContinuousGalerkin::DuneDetailedDiscretizations<
//        ModelType,
//        typename MsGridType::GlobalGridPartType,
//        BoundaryInfoType,
//        polOrder >
//      ReferenceSolverType;
//    ReferenceSolverType referenceSolver(model, msGrid->globalGridPart(), boundaryInfo);
//    referenceSolver.init();
//    Dune::shared_ptr< VectorType > referenceSolution = referenceSolver.createVector();
//    referenceSolver.solve(*referenceSolution, paramTree.sub(SolverType::id).sub("solve"), "  ", debug);
//    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
//    debug.resume();

    info << "postprocessing";
//    info << ":" << std::endl;
    info << "... " << std::flush;
    debug.suspend();
    timer.reset();
    solver.visualize(*solution,
                     solverTree.get("visualize.filename", id + ".solution"),
                     solverTree.get("visualize.name", "solution"),
                     "  ",
                     debug);
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;
    debug.resume();

//    if (dimDomain == 1) {
//      info << "computing norms:" << std::endl;
//      debug.suspend();
//      referenceSolver.visualize(*referenceSolution,
//                                paramTree.sub(SolverType::id).sub("visualize").get("filename", id + ".solution") + "_reference",
//                                paramTree.sub(SolverType::id).sub("visualize").get("name", "solution") + "_reference",
//                                "  ",
//                                debug);

//      Dune::shared_ptr< typename SolverType::DiscreteFunctionType > discreteSolution = solver.createDiscreteFunction(*solution, "discrete_solution");
//      debug.resume();
//      compute_errors(paramTree.sub(id).sub("exact_solution"),
//                     *discreteSolution,
//                     info, "  ");
//    }
    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


<commit_before>/*
 * ArmorObjectImplementation.cpp
 *
 *  Created on: 02/08/2009
 *      Author: victor
 */

#include "ArmorObject.h"
#include "server/zone/templates/tangible/ArmorObjectTemplate.h"
#include "server/zone/objects/manufactureschematic/ManufactureSchematic.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"

void ArmorObjectImplementation::initializeTransientMembers() {
	TangibleObjectImplementation::initializeTransientMembers();

	setLoggingName("ArmorObject");
}

void ArmorObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
	WearableObjectImplementation::loadTemplateData(templateData);

	if (!templateData->isArmorObjectTemplate())
		return;

	ArmorObjectTemplate* armorTemplate = (ArmorObjectTemplate*) templateData;

	vulnerabilites = armorTemplate->getVulnerabilites();

	healthEncumbrance = armorTemplate->getHealthEncumbrance();
	actionEncumbrance = armorTemplate->getActionEncumbrance();
	mindEncumbrance = armorTemplate->getMindEncumbrance();

	rating = armorTemplate->getRating();

	kinetic = armorTemplate->getKinetic();
	energy = armorTemplate->getEnergy();
	electricity = armorTemplate->getElectricity();
	stun = armorTemplate->getStun();
	blast = armorTemplate->getBlast();
	heat = armorTemplate->getHeat();
	cold = armorTemplate->getCold();
	acid = armorTemplate->getAcid();
	lightSaber = armorTemplate->getLightSaber();

	specialBase = armorTemplate->getSpecialBase();

}

void ArmorObjectImplementation::fillAttributeList(AttributeListMessage* alm, PlayerCreature* object) {
	WearableObjectImplementation::fillAttributeList(alm, object);

	if (socketsLeft() > 0)
		alm->insertAttribute("sockets", socketsLeft());

	wearableSkillModMap.insertStatMods(alm);

	//Armor Rating
	if (rating == LIGHT)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_light"); //Light
	else if (rating == MEDIUM)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_medium"); //Medium
	else if (rating == HEAVY)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_heavy"); //Heavy
	else
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_none"); //None

	//Check for special protections
	if (isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) {
		StringBuffer txt;
		txt << round(kinetic) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ENERGY) && energy >= 0.5) {
		StringBuffer txt;
		txt << round(energy) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_energy",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) {
		StringBuffer txt;
		txt << round(electricity) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_electrical",
				txt.toString());
	}
	if (isSpecial(WeaponObject::STUN) && stun >= 0.5) {
		StringBuffer txt;
		txt << round(stun) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_stun",
				txt.toString());
	}
	if (isSpecial(WeaponObject::BLAST) && blast >= 0.5) {
		StringBuffer txt;
		txt << round(blast) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_blast",
				txt.toString());
	}
	if (isSpecial(WeaponObject::HEAT) && heat >= 0.5) {
		StringBuffer txt;
		txt << round(heat) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_heat",
				txt.toString());
	}
	if (isSpecial(WeaponObject::COLD) && cold >= 0.5) {
		StringBuffer txt;
		txt << round(cold) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_cold",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ACID) && acid >= 0.5) {
		StringBuffer txt;
		txt << round(acid) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_acid",
				txt.toString());
	}
	if (isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) {
		StringBuffer txt;
		txt << round(lightSaber) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_restraint",
				txt.toString());
	}
	//Check for Effectiveness protections(Normal)
	if (!isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) {
		StringBuffer txt;
		txt << round(kinetic) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ENERGY) && energy >= 0.5) {
		StringBuffer txt;
		txt << round(energy) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) {
		StringBuffer txt;
		txt << round(electricity) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_electrical",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::STUN) && stun >= 0.5) {
		StringBuffer txt;
		txt << round(stun) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::BLAST) && blast >= 0.5) {
		StringBuffer txt;
		txt << round(blast) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::HEAT) && heat >= 0.5) {
		StringBuffer txt;
		txt << round(heat) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_heat",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::COLD) && cold >= 0.5) {
		StringBuffer txt;
		txt << round(cold) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_cold",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ACID) && acid >= 0.5) {
		StringBuffer txt;
		txt << round(acid) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_acid",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) {
		StringBuffer txt;
		txt << round(lightSaber) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint",
				txt.toString());
	}

	//Vulnerabilities
	if (kinetic < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_kinetic", "-");

	if (energy < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_energy", "-");

	if (electricity < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_electrical", "-");

	if (stun < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_stun", "-");

	if (blast < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast", "-");

	if (heat < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_heat", "-");

	if (cold < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_cold", "-");

	if (acid < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_acid", "-");

	if (lightSaber < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_restraint", "-");

	//Encumbrances
	alm->insertAttribute("cat_armor_encumbrance.health", healthEncumbrance);

	alm->insertAttribute("cat_armor_encumbrance.action", actionEncumbrance);

	alm->insertAttribute("cat_armor_encumbrance.mind", mindEncumbrance);

	if (craftersName != "") {
		alm->insertAttribute("crafter", craftersName);
	}

	if (craftersSerial != "") {
		alm->insertAttribute("serial_number", craftersSerial);
	}

	if (sliced)
		alm->insertAttribute("arm_attr", "@obj_attr_n:hacked");

}

void ArmorObjectImplementation::updateCraftingValues(ManufactureSchematic* schematic) {

	WearableObjectImplementation::updateCraftingValues(schematic);

	/*
	 * Incoming Values:					Ranges:
	 * sockets							All depend on type of armor
	 * hit_points
	 * armor_effectiveness
	 * armor_integrity
	 * armor_health_encumbrance
	 * armor_action_encumbrance
	 * armor_mind_encumbrance
	 * armor_rating
	 * armor_special_type
	 * armor_special_effectiveness
	 * armor_special_integrity
	 */
	CraftingValues* craftingValues = schematic->getCraftingValues();
	//craftingValues->toString();

	if(schematic->getFirstCraftingUpdate()) {

		int special = craftingValues->getCurrentValue("armor_special_type");
		specialResists = special;

		setRating((int) craftingValues->getCurrentValue("armor_rating"));

		setMaxCondition((int) craftingValues->getCurrentValue("armor_integrity"));
		setConditionDamage(0);
	}

	setHealthEncumbrance((int) craftingValues->getCurrentValue(
			"armor_health_encumbrance"));
	setActionEncumbrance((int) craftingValues->getCurrentValue(
			"armor_action_encumbrance"));
	setMindEncumbrance((int) craftingValues->getCurrentValue(
			"armor_mind_encumbrance"));

	float base = craftingValues->getCurrentValue("armor_effectiveness");

	setProtection(schematic, WeaponObject::KINETIC, base);
	setProtection(schematic, WeaponObject::ENERGY, base);
	setProtection(schematic, WeaponObject::ELECTRICITY, base);
	setProtection(schematic, WeaponObject::STUN, base);
	setProtection(schematic, WeaponObject::BLAST, base);
	setProtection(schematic, WeaponObject::HEAT, base);
	setProtection(schematic, WeaponObject::COLD, base);
	setProtection(schematic, WeaponObject::ACID, base);
	setProtection(schematic, WeaponObject::LIGHTSABER, base);
}

void ArmorObjectImplementation::calculateSpecalProtection(
		ManufactureSchematic* schematic) {

	CraftingValues* craftingValues = schematic->getCraftingValues();

	float base = craftingValues->getCurrentValue("armor_effectiveness");
	float value, min, max, currentValue;
	String title = "exp_resistance";
	String subtitle;
	//float min = craftingValues->getMinValue("armor_effectiveness");
	//float max = craftingValues->getMaxValue("armor_effectiveness");
	float currentPercentage = craftingValues->getCurrentPercentage("armor_effectiveness");
	float maxPercentage = craftingValues->getMaxPercentage("armor_effectiveness");
	int precision = craftingValues->getPrecision("armor_effectiveness");

	for (int i = 0; i <= 8; ++i) {

		int type = pow(2,i);

		if(isSpecial(type)) {

			subtitle = getStringType(type);

			value = craftingValues->getCurrentValue(subtitle);
			min = 2;
			max = (value - min + (min * currentPercentage)) / currentPercentage;
			currentValue = (currentPercentage * (max - min)) + min;

			craftingValues->addExperimentalProperty(title, subtitle, min, max,
				precision, false);
			craftingValues->setMaxPercentage(subtitle, maxPercentage);
			craftingValues->setCurrentPercentage(subtitle, currentPercentage);
			craftingValues->setCurrentValue(subtitle, currentValue);
		}
	}
}

void ArmorObjectImplementation::setProtection(ManufactureSchematic* schematic,
		int type, float base) {

	CraftingValues* craftingValues = schematic->getCraftingValues();

	float value = craftingValues->getCurrentValue(getStringType(type));

	if (value == CraftingValues::VALUENOTFOUND
			&& schematic->getFirstCraftingUpdate()) {
		craftingValues->lockValue(getStringType(type));
	}

	if (value == CraftingValues::VALUENOTFOUND) {
		if (isVulnerable(type))
			setProtectionValue(type, 0.0f);
		else
			setProtectionValue(type, base);
	} else {
		if (value + base > 80.0f)
			setProtectionValue(type, 80.0f);
		else
			setProtectionValue(type, value + base);
	}
}

String ArmorObjectImplementation::getStringType(int type) {

	switch(type) {
	case WeaponObject::KINETIC:
		return "kineticeffectiveness";
		break;
	case WeaponObject::ENERGY:
		return "energyeffectiveness";
	break;
	case WeaponObject::ELECTRICITY:
		return "electricaleffectiveness";
		break;
	case WeaponObject::STUN:
		return "stuneffectiveness";
		break;
	case WeaponObject::BLAST:
		return "blasteffectiveness";
		break;
	case WeaponObject::HEAT:
		return "heateffectiveness";
		break;
	case WeaponObject::COLD:
		return "coldeffectiveness";
		break;
	case WeaponObject::ACID:
		return "acideffectiveness";
		break;
	case WeaponObject::LIGHTSABER:
		return "restraineffectiveness";
		break;
	default:
		return "";
	}
}

void ArmorObjectImplementation::setProtectionValue(int type, float value) {

	if (type & WeaponObject::KINETIC)
		setKinetic(value);
	if (type & WeaponObject::ENERGY)
		setEnergy(value);
	if (type & WeaponObject::BLAST)
		setBlast(value);
	if (type & WeaponObject::STUN)
		setStun(value);
	if (type & WeaponObject::LIGHTSABER)
		setLightSaber(value);
	if (type & WeaponObject::HEAT)
		setHeat(value);
	if (type & WeaponObject::COLD)
		setCold(value);
	if (type & WeaponObject::ACID)
		setAcid(value);
	if (type & WeaponObject::ELECTRICITY)
		setElectricity(value);
}
<commit_msg>[Update] Armor Special Protection<commit_after>/*
 * ArmorObjectImplementation.cpp
 *
 *  Created on: 02/08/2009
 *      Author: victor
 */

#include "ArmorObject.h"
#include "server/zone/templates/tangible/ArmorObjectTemplate.h"
#include "server/zone/objects/manufactureschematic/ManufactureSchematic.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"

void ArmorObjectImplementation::initializeTransientMembers() {
	TangibleObjectImplementation::initializeTransientMembers();

	setLoggingName("ArmorObject");
}

void ArmorObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
	WearableObjectImplementation::loadTemplateData(templateData);

	if (!templateData->isArmorObjectTemplate())
		return;

	ArmorObjectTemplate* armorTemplate = (ArmorObjectTemplate*) templateData;

	vulnerabilites = armorTemplate->getVulnerabilites();

	healthEncumbrance = armorTemplate->getHealthEncumbrance();
	actionEncumbrance = armorTemplate->getActionEncumbrance();
	mindEncumbrance = armorTemplate->getMindEncumbrance();

	rating = armorTemplate->getRating();

	kinetic = armorTemplate->getKinetic();
	energy = armorTemplate->getEnergy();
	electricity = armorTemplate->getElectricity();
	stun = armorTemplate->getStun();
	blast = armorTemplate->getBlast();
	heat = armorTemplate->getHeat();
	cold = armorTemplate->getCold();
	acid = armorTemplate->getAcid();
	lightSaber = armorTemplate->getLightSaber();

	specialBase = armorTemplate->getSpecialBase();

}

void ArmorObjectImplementation::fillAttributeList(AttributeListMessage* alm, PlayerCreature* object) {
	WearableObjectImplementation::fillAttributeList(alm, object);

	if (socketsLeft() > 0)
		alm->insertAttribute("sockets", socketsLeft());

	wearableSkillModMap.insertStatMods(alm);

	//Armor Rating
	if (rating == LIGHT)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_light"); //Light
	else if (rating == MEDIUM)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_medium"); //Medium
	else if (rating == HEAVY)
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_heavy"); //Heavy
	else
		alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_none"); //None

	//Check for special protections
	if (isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) {
		StringBuffer txt;
		txt << round(kinetic) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ENERGY) && energy >= 0.5) {
		StringBuffer txt;
		txt << round(energy) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_energy",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) {
		StringBuffer txt;
		txt << round(electricity) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_electrical",
				txt.toString());
	}
	if (isSpecial(WeaponObject::STUN) && stun >= 0.5) {
		StringBuffer txt;
		txt << round(stun) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_stun",
				txt.toString());
	}
	if (isSpecial(WeaponObject::BLAST) && blast >= 0.5) {
		StringBuffer txt;
		txt << round(blast) << "%";
		alm->insertAttribute("cat_armor_special_protection.armor_eff_blast",
				txt.toString());
	}
	if (isSpecial(WeaponObject::HEAT) && heat >= 0.5) {
		StringBuffer txt;
		txt << round(heat) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_heat",
				txt.toString());
	}
	if (isSpecial(WeaponObject::COLD) && cold >= 0.5) {
		StringBuffer txt;
		txt << round(cold) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_cold",
				txt.toString());
	}
	if (isSpecial(WeaponObject::ACID) && acid >= 0.5) {
		StringBuffer txt;
		txt << round(acid) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_elemental_acid",
				txt.toString());
	}
	if (isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) {
		StringBuffer txt;
		txt << round(lightSaber) << "%";
		alm->insertAttribute(
				"cat_armor_special_protection.armor_eff_restraint",
				txt.toString());
	}
	//Check for Effectiveness protections(Normal)
	if (!isSpecial(WeaponObject::KINETIC) && kinetic >= 0.5) {
		StringBuffer txt;
		txt << round(kinetic) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_kinetic",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ENERGY) && energy >= 0.5) {
		StringBuffer txt;
		txt << round(energy) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ELECTRICITY) && electricity >= 0.5) {
		StringBuffer txt;
		txt << round(electricity) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_electrical",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::STUN) && stun >= 0.5) {
		StringBuffer txt;
		txt << round(stun) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::BLAST) && blast >= 0.5) {
		StringBuffer txt;
		txt << round(blast) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::HEAT) && heat >= 0.5) {
		StringBuffer txt;
		txt << round(heat) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_heat",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::COLD) && cold >= 0.5) {
		StringBuffer txt;
		txt << round(cold) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_cold",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::ACID) && acid >= 0.5) {
		StringBuffer txt;
		txt << round(acid) << "%";
		alm->insertAttribute(
				"cat_armor_effectiveness.armor_eff_elemental_acid",
				txt.toString());
	}
	if (!isSpecial(WeaponObject::LIGHTSABER) && lightSaber >= 0.5) {
		StringBuffer txt;
		txt << round(lightSaber) << "%";
		alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint",
				txt.toString());
	}

	//Vulnerabilities
	if (kinetic < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_kinetic", "-");

	if (energy < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_energy", "-");

	if (electricity < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_electrical", "-");

	if (stun < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_stun", "-");

	if (blast < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_blast", "-");

	if (heat < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_heat", "-");

	if (cold < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_cold", "-");

	if (acid < 0.5)
		alm->insertAttribute(
				"cat_armor_vulnerability.armor_eff_elemental_acid", "-");

	if (lightSaber < 0.5)
		alm->insertAttribute("cat_armor_vulnerability.armor_eff_restraint", "-");

	//Encumbrances
	alm->insertAttribute("cat_armor_encumbrance.health", healthEncumbrance);

	alm->insertAttribute("cat_armor_encumbrance.action", actionEncumbrance);

	alm->insertAttribute("cat_armor_encumbrance.mind", mindEncumbrance);

	if (craftersName != "") {
		alm->insertAttribute("crafter", craftersName);
	}

	if (craftersSerial != "") {
		alm->insertAttribute("serial_number", craftersSerial);
	}

	if (sliced)
		alm->insertAttribute("arm_attr", "@obj_attr_n:hacked");

}

void ArmorObjectImplementation::updateCraftingValues(ManufactureSchematic* schematic) {

	WearableObjectImplementation::updateCraftingValues(schematic);

	/*
	 * Incoming Values:					Ranges:
	 * sockets							All depend on type of armor
	 * hit_points
	 * armor_effectiveness
	 * armor_integrity
	 * armor_health_encumbrance
	 * armor_action_encumbrance
	 * armor_mind_encumbrance
	 * armor_rating
	 * armor_special_type
	 * armor_special_effectiveness
	 * armor_special_integrity
	 */
	CraftingValues* craftingValues = schematic->getCraftingValues();
	//craftingValues->toString();

	if(schematic->getFirstCraftingUpdate()) {

		int special = craftingValues->getCurrentValue("armor_special_type");
		specialResists = special;
		calculateSpecalProtection(schematic);

		setRating((int) craftingValues->getCurrentValue("armor_rating"));

		setMaxCondition((int) craftingValues->getCurrentValue("armor_integrity"));
		setConditionDamage(0);
	}

	setHealthEncumbrance((int) craftingValues->getCurrentValue(
			"armor_health_encumbrance"));
	setActionEncumbrance((int) craftingValues->getCurrentValue(
			"armor_action_encumbrance"));
	setMindEncumbrance((int) craftingValues->getCurrentValue(
			"armor_mind_encumbrance"));

	float base = craftingValues->getCurrentValue("armor_effectiveness");

	setProtection(schematic, WeaponObject::KINETIC, base);
	setProtection(schematic, WeaponObject::ENERGY, base);
	setProtection(schematic, WeaponObject::ELECTRICITY, base);
	setProtection(schematic, WeaponObject::STUN, base);
	setProtection(schematic, WeaponObject::BLAST, base);
	setProtection(schematic, WeaponObject::HEAT, base);
	setProtection(schematic, WeaponObject::COLD, base);
	setProtection(schematic, WeaponObject::ACID, base);
	setProtection(schematic, WeaponObject::LIGHTSABER, base);
}

void ArmorObjectImplementation::calculateSpecalProtection(
		ManufactureSchematic* schematic) {

	CraftingValues* craftingValues = schematic->getCraftingValues();

	float base = craftingValues->getCurrentValue("armor_effectiveness");
	float value, min, max, currentValue;
	String title = "exp_resistance";
	String subtitle;
	//float min = craftingValues->getMinValue("armor_effectiveness");
	//float max = craftingValues->getMaxValue("armor_effectiveness");
	float currentPercentage = craftingValues->getCurrentPercentage("armor_effectiveness");
	float maxPercentage = craftingValues->getMaxPercentage("armor_effectiveness");
	int precision = craftingValues->getPrecision("armor_effectiveness");

	for (int i = 0; i <= 8; ++i) {

		int type = pow(2,i);

		if(isSpecial(type)) {

			subtitle = getStringType(type);

			value = craftingValues->getCurrentValue(subtitle);
			min = 2;
			max = (value - min + (min * currentPercentage)) / currentPercentage;
			currentValue = (currentPercentage * (max - min)) + min;

			craftingValues->addExperimentalProperty(title, subtitle, min, max,
				precision, false);
			craftingValues->setMaxPercentage(subtitle, maxPercentage);
			craftingValues->setCurrentPercentage(subtitle, currentPercentage);
			craftingValues->setCurrentValue(subtitle, currentValue);
		}
	}
}

void ArmorObjectImplementation::setProtection(ManufactureSchematic* schematic,
		int type, float base) {

	CraftingValues* craftingValues = schematic->getCraftingValues();

	float value = craftingValues->getCurrentValue(getStringType(type));

	if (value == CraftingValues::VALUENOTFOUND
			&& schematic->getFirstCraftingUpdate()) {
		craftingValues->lockValue(getStringType(type));
	}

	if (value == CraftingValues::VALUENOTFOUND) {
		if (isVulnerable(type))
			setProtectionValue(type, 0.0f);
		else
			setProtectionValue(type, base);
	} else {
		if (value + base > 80.0f)
			setProtectionValue(type, 80.0f);
		else
			setProtectionValue(type, value + base);
	}
}

String ArmorObjectImplementation::getStringType(int type) {

	switch(type) {
	case WeaponObject::KINETIC:
		return "kineticeffectiveness";
		break;
	case WeaponObject::ENERGY:
		return "energyeffectiveness";
	break;
	case WeaponObject::ELECTRICITY:
		return "electricaleffectiveness";
		break;
	case WeaponObject::STUN:
		return "stuneffectiveness";
		break;
	case WeaponObject::BLAST:
		return "blasteffectiveness";
		break;
	case WeaponObject::HEAT:
		return "heateffectiveness";
		break;
	case WeaponObject::COLD:
		return "coldeffectiveness";
		break;
	case WeaponObject::ACID:
		return "acideffectiveness";
		break;
	case WeaponObject::LIGHTSABER:
		return "restraineffectiveness";
		break;
	default:
		return "";
	}
}

void ArmorObjectImplementation::setProtectionValue(int type, float value) {

	if (type & WeaponObject::KINETIC)
		setKinetic(value);
	if (type & WeaponObject::ENERGY)
		setEnergy(value);
	if (type & WeaponObject::BLAST)
		setBlast(value);
	if (type & WeaponObject::STUN)
		setStun(value);
	if (type & WeaponObject::LIGHTSABER)
		setLightSaber(value);
	if (type & WeaponObject::HEAT)
		setHeat(value);
	if (type & WeaponObject::COLD)
		setCold(value);
	if (type & WeaponObject::ACID)
		setAcid(value);
	if (type & WeaponObject::ELECTRICITY)
		setElectricity(value);
}
<|endoftext|>