<commit_before>#include "bim/chunk.hpp"
#include <memory>
#include <algorithm>

using namespace ei;

namespace bim {

	struct SBVBuildInfo
	{
		std::vector<Node>& hierarchy;
		std::vector<uint32>& parents;
		std::vector<UVec4>& leaves;
		const std::vector<Vec3>& positions;
		const std::vector<UVec3>& triangles;
		const std::vector<uint32>& materials;
		const uint numTrianglesPerLeaf;
		Vec3* centers; // triangle center position .xyz
		Vec2* heuristics; // auxiliary buffer for left/right heuristic pairs
		uint32* aux; // auxiliary work space 1
	};

	const uint NUM_BINS = 256;

	static float surfaceAreaHeuristic(const Box& _bv, int _num)
	{
		return surface(_bv) * _num;
	}

	// Partitions all triangle into two disjunct sets. Returns the SAH cost for the
	// split and the index for the last object in the left set.
	// _min and _max are inclusive boundaries.
	static float findObjectSplit( SBVBuildInfo& _in, uint32* _triangles, uint32 _num, uint32& _outIdx )
	{
		// Compute lhs/rhs bounding volumes for all splits. This is done from left
		// and right adding one triangle at a time.
		UVec3 t = _in.triangles[_triangles[0]];
		Box leftBox = Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z]));
		t = _in.triangles[_triangles[_num-1]];
		Box rightBox = Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z]));
		_in.heuristics[0].x   = surfaceAreaHeuristic( leftBox, 1 );
		_in.heuristics[_num-2].y = surfaceAreaHeuristic( rightBox, 1 );
		for(uint32 i = 1; i < _num-1; ++i)
		{
			// Extend bounding boxes by one triangle
			t = _in.triangles[_triangles[i]];
			leftBox = Box(leftBox, Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z])));
			t = _in.triangles[_triangles[_num-i-1]];
			rightBox = Box(rightBox, Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z])));
			// The volumes are rejected in the next iteration but remember
			// the result for the split decision.
			_in.heuristics[i].x   = surfaceAreaHeuristic( leftBox, i+1 );
			_in.heuristics[_num-i-2].y = surfaceAreaHeuristic( rightBox, i+1 );
		}

		// Find the minimum for the current dimension
		_outIdx = 0;
		float minCost = std::numeric_limits<float>::infinity();
		for(uint32 i = 0; i < _num-1; ++i)
		{
			if(sum(_in.heuristics[i]) < minCost)
			{
				minCost = sum(_in.heuristics[i]);
				_outIdx = i;
			}
		}
		return minCost;
	}

	static uint32 build( SBVBuildInfo& _in, uint32* _triangles, uint32 _num )
	{
		uint32 nodeIdx = (uint32)_in.hierarchy.size();
		_in.hierarchy.resize(nodeIdx + 1);
		_in.parents.resize(nodeIdx + 1);
		_in.hierarchy[nodeIdx].firstChild = _in.hierarchy[nodeIdx].escape = _in.parents[nodeIdx] = 0;

		// Create a leaf if less than NUM_PRIMITIVES elements remain.
		eiAssert(_num > 0, "Node without triangles!");
		if( _num <= _in.numTrianglesPerLeaf )
		{
			// Allocate a new leaf
			size_t leafIdx = _in.leaves.size();
			_in.leaves.resize(_in.leaves.size() + _in.numTrianglesPerLeaf);
			// Fill it
			UVec4* trianglesPtr = &_in.leaves[leafIdx];
			for( uint i = 0; i < _num; ++i )
				*(trianglesPtr++) = UVec4( _in.triangles[_triangles[i]], _in.materials.empty() ? 0 : _in.materials[_triangles[i]] );
			for( uint i = 0; i < _in.numTrianglesPerLeaf - _num; ++i )
				*(trianglesPtr++) = UVec4(0); // Invalid triangle per convention

			// Let the new node pointing to this leaf
			_in.hierarchy[nodeIdx].firstChild = 0x80000000 | (uint32)(leafIdx / _in.numTrianglesPerLeaf);

			return nodeIdx;
		}

		// Find SAH object split candidate.
		uint32 splitIndex = 0; // Last triangle of left set
		float objSplitSAH = std::numeric_limits<float>::infinity();
		memcpy(_in.aux, _triangles, _num * 4);
		for(int d = 0; d < 3; ++d)
		{
			std::sort( _in.aux, _in.aux + _num,
				[&](const uint32 _lhs, const uint32 _rhs) { return _in.centers[_lhs][d] < _in.centers[_rhs][d]; }
			);

			uint32 i;
			float sah = findObjectSplit(_in, _in.aux, _num, i);
			if(sah < objSplitSAH)
			{
				objSplitSAH = sah;
				splitIndex = i;
				memcpy(_triangles, _in.aux, _num * 4);	// Keep best sorted result
			}
		}

		// Build a new index set for the left side
		std::unique_ptr<uint32[]> tmpIndexSet(new uint32[_num]);
		memcpy(tmpIndexSet.get(), _triangles, (splitIndex+1) * 4);
		// Set left and right into firstChild and escape. This is corrected later in
		// remapNodePointers().
		_in.hierarchy[nodeIdx].firstChild = build( _in, tmpIndexSet.get(), splitIndex+1 );
		// Bulid index set for the right side
		memcpy(tmpIndexSet.get(), _triangles + splitIndex + 1, (_num - splitIndex - 1) * 4);
		_in.hierarchy[nodeIdx].escape = build( _in, tmpIndexSet.get(), _num - splitIndex - 1 );

		return nodeIdx;
	}

	void Chunk::buildBVH_SBVH()
	{
		uint32 n = getNumTriangles();
		std::unique_ptr<Vec3[]> centers(new Vec3[n]);
		std::unique_ptr<Vec2[]> heuristics(new Vec2[ei::max(NUM_BINS,n-1)]); // n-1 split positions
		std::unique_ptr<uint32[]> auxA(new uint32[n]);
		std::unique_ptr<uint32[]> indices(new uint32[n]);

		// Initialize unsorted and centers
		for( uint32 i = 0; i < n; ++i )
		{
			UVec3 t = getTriangles()[i];
			centers[i] = (m_positions[t.x] + m_positions[t.y] + m_positions[t.z]) / 3.0f;
			indices[i] = i;
		}

		m_hierarchy.reserve(n*2);
		m_hierarchyParents.reserve(n*2);
		m_hierarchyLeaves.reserve(n);
		SBVBuildInfo input = {m_hierarchy, m_hierarchyParents, m_hierarchyLeaves,
			m_positions, m_triangles, m_triangleMaterials, m_numTrianglesPerLeaf,
			centers.get(), heuristics.get(), auxA.get()};
		build(input, indices.get(), n);
	}

} // namespace bim<commit_msg>tried Hilbert curve sorting instead of split axis (surprisingly lower quality)<commit_after>#include "bim/chunk.hpp"
#include <memory>
#include <algorithm>

using namespace ei;

namespace bim {

	struct SBVBuildInfo
	{
		std::vector<Node>& hierarchy;
		std::vector<uint32>& parents;
		std::vector<UVec4>& leaves;
		const std::vector<Vec3>& positions;
		const std::vector<UVec3>& triangles;
		const std::vector<uint32>& materials;
		const uint numTrianglesPerLeaf;
		Vec3* centers; // triangle center position .xyz
		Vec2* heuristics; // auxiliary buffer for left/right heuristic pairs
		uint32* aux; // auxiliary work space 1
	};

	const uint NUM_BINS = 256;

	static float surfaceAreaHeuristic(const Box& _bv, int _num)
	{
		return surface(_bv) * _num;
	}

	// Two sources to derive the z-order comparator
	// (floats - unused) http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.150.9547&rep=rep1&type=pdf
	// (ints - the below one uses this int-algorithm on floats) http://dl.acm.org/citation.cfm?id=545444
	// http://www.forceflow.be/2013/10/07/morton-encodingdecoding-through-bit-interleaving-implementations/ Computing morton codes
	static uint64 partby2(uint16 _x)
	{
		uint64 r = _x;
		r = (r | (r << 16)) & 0x0000ff0000ff;
		r = (r | (r <<  8)) & 0x00f00f00f00f;
		r = (r | (r <<  4)) & 0x0c30c30c30c3;
		r = (r | (r <<  2)) & 0x249249249249;
		return r;
	}
	// Insert two 0 bits before each bit. This transforms a 16 bit number xxxxxxxx into a 48 bit number 00x00x00x00x00x00x00x00x
	static uint64 morton(uint16 _a, uint16 _b, uint16 _c)
	{
		return partby2(_a) | (partby2(_b) << 1) | (partby2(_c) << 2);
	}

	// Usefull sources for hilber curve implementations:
	// http://www.tiac.net/~sw/2008/10/Hilbert/moore/ Non recursive c-code
	// http://stackoverflow.com/questions/8459562/hilbert-sort-by-divide-and-conquer-algorithm Idea with inverse gray code
	static uint64 binaryToGray(uint64 num)
	{
		return num ^ (num >> 1);
	}
	static uint64 grayToBinary(uint64 num)
	{
		num = num ^ (num >> 32);
		num = num ^ (num >> 16);
		num = num ^ (num >> 8);
		num = num ^ (num >> 4);
		num = num ^ (num >> 2);
		num = num ^ (num >> 1);
		return num;
	}
	static bool hilbertcurvecmp(const Vec3& _a, const Vec3& _b)
	{
		// Get (positive) integer vectors
		UVec3 a = UVec3(_a * 4096.0f);
		UVec3 b = UVec3(_b * 4096.0f);
		// Interleave packages of 16 bit, convert to inverse Gray code and compare.
		uint64 codeA = grayToBinary(morton(a.x >> 16, a.y >> 16, a.z >> 16));
		uint64 codeB = grayToBinary(morton(b.x >> 16, b.y >> 16, b.z >> 16));
		// If they are equal take the next 16 less significant bit.
		if(codeA == codeB) {
			codeA = grayToBinary(morton(a.x & 0xffff, a.y & 0xffff, a.z & 0xffff));
			codeB = grayToBinary(morton(b.x & 0xffff, b.y & 0xffff, b.z & 0xffff));
		}
		return codeA < codeB;
	}

	// Partitions all triangle into two disjunct sets. Returns the SAH cost for the
	// split and the index for the last object in the left set.
	// _min and _max are inclusive boundaries.
	static float findObjectSplit( SBVBuildInfo& _in, uint32* _triangles, uint32 _num, uint32& _outIdx )
	{
		// Compute lhs/rhs bounding volumes for all splits. This is done from left
		// and right adding one triangle at a time.
		UVec3 t = _in.triangles[_triangles[0]];
		Box leftBox = Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z]));
		t = _in.triangles[_triangles[_num-1]];
		Box rightBox = Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z]));
		_in.heuristics[0].x   = surfaceAreaHeuristic( leftBox, 1 );
		_in.heuristics[_num-2].y = surfaceAreaHeuristic( rightBox, 1 );
		for(uint32 i = 1; i < _num-1; ++i)
		{
			// Extend bounding boxes by one triangle
			t = _in.triangles[_triangles[i]];
			leftBox = Box(leftBox, Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z])));
			t = _in.triangles[_triangles[_num-i-1]];
			rightBox = Box(rightBox, Box(Triangle(_in.positions[t.x], _in.positions[t.y], _in.positions[t.z])));
			// The volumes are rejected in the next iteration but remember
			// the result for the split decision.
			_in.heuristics[i].x   = surfaceAreaHeuristic( leftBox, i+1 );
			_in.heuristics[_num-i-2].y = surfaceAreaHeuristic( rightBox, i+1 );
		}

		// Find the minimum for the current dimension
		_outIdx = 0;
		float minCost = std::numeric_limits<float>::infinity();
		for(uint32 i = 0; i < _num-1; ++i)
		{
			if(sum(_in.heuristics[i]) < minCost)
			{
				minCost = sum(_in.heuristics[i]);
				_outIdx = i;
			}
		}
		return minCost;
	}

	static uint32 build( SBVBuildInfo& _in, uint32* _triangles, uint32 _num )
	{
		uint32 nodeIdx = (uint32)_in.hierarchy.size();
		_in.hierarchy.resize(nodeIdx + 1);
		_in.parents.resize(nodeIdx + 1);
		_in.hierarchy[nodeIdx].firstChild = _in.hierarchy[nodeIdx].escape = _in.parents[nodeIdx] = 0;

		// Create a leaf if less than NUM_PRIMITIVES elements remain.
		eiAssert(_num > 0, "Node without triangles!");
		if( _num <= _in.numTrianglesPerLeaf )
		{
			// Allocate a new leaf
			size_t leafIdx = _in.leaves.size();
			_in.leaves.resize(_in.leaves.size() + _in.numTrianglesPerLeaf);
			// Fill it
			UVec4* trianglesPtr = &_in.leaves[leafIdx];
			for( uint i = 0; i < _num; ++i )
				*(trianglesPtr++) = UVec4( _in.triangles[_triangles[i]], _in.materials.empty() ? 0 : _in.materials[_triangles[i]] );
			for( uint i = 0; i < _in.numTrianglesPerLeaf - _num; ++i )
				*(trianglesPtr++) = UVec4(0); // Invalid triangle per convention

			// Let the new node pointing to this leaf
			_in.hierarchy[nodeIdx].firstChild = 0x80000000 | (uint32)(leafIdx / _in.numTrianglesPerLeaf);

			return nodeIdx;
		}

		// Find SAH object split candidate.
		uint32 splitIndex = 0; // Last triangle of left set
		float objSplitSAH = std::numeric_limits<float>::infinity();
		memcpy(_in.aux, _triangles, _num * 4);
		for(int d = 0; d < 3; ++d)
		{
			std::sort( _in.aux, _in.aux + _num,
				[&](const uint32 _lhs, const uint32 _rhs) { return _in.centers[_lhs][d] < _in.centers[_rhs][d]; }
			);

			uint32 i;
			float sah = findObjectSplit(_in, _in.aux, _num, i);
			if(sah < objSplitSAH)
			{
				objSplitSAH = sah;
				splitIndex = i;
				memcpy(_triangles, _in.aux, _num * 4);	// Keep best sorted result
			}
		}
		// Try again with Hilbert curve instead of the main axis.
		/*std::sort( _in.aux, _in.aux + _num,
			[&](const uint32 _lhs, const uint32 _rhs) { return hilbertcurvecmp(_in.centers[_lhs], _in.centers[_rhs]); }
		);
		uint32 i;
		float sah = findObjectSplit(_in, _in.aux, _num, i);
		if(sah < objSplitSAH)
		{
			objSplitSAH = sah;
			splitIndex = i;
			memcpy(_triangles, _in.aux, _num * 4);	// Keep best sorted result
		}//*/

		// Build a new index set for the left side
		std::unique_ptr<uint32[]> tmpIndexSet(new uint32[_num]);
		memcpy(tmpIndexSet.get(), _triangles, (splitIndex+1) * 4);
		// Set left and right into firstChild and escape. This is corrected later in
		// remapNodePointers().
		_in.hierarchy[nodeIdx].firstChild = build( _in, tmpIndexSet.get(), splitIndex+1 );
		// Bulid index set for the right side
		memcpy(tmpIndexSet.get(), _triangles + splitIndex + 1, (_num - splitIndex - 1) * 4);
		_in.hierarchy[nodeIdx].escape = build( _in, tmpIndexSet.get(), _num - splitIndex - 1 );

		return nodeIdx;
	}

	void Chunk::buildBVH_SBVH()
	{
		uint32 n = getNumTriangles();
		std::unique_ptr<Vec3[]> centers(new Vec3[n]);
		std::unique_ptr<Vec2[]> heuristics(new Vec2[ei::max(NUM_BINS,n-1)]); // n-1 split positions
		std::unique_ptr<uint32[]> auxA(new uint32[n]);
		std::unique_ptr<uint32[]> indices(new uint32[n]);

		// Initialize unsorted and centers
		for( uint32 i = 0; i < n; ++i )
		{
			UVec3 t = getTriangles()[i];
			centers[i] = (m_positions[t.x] + m_positions[t.y] + m_positions[t.z]) / 3.0f;
			indices[i] = i;
		}

		m_hierarchy.reserve(n*2);
		m_hierarchyParents.reserve(n*2);
		m_hierarchyLeaves.reserve(n);
		SBVBuildInfo input = {m_hierarchy, m_hierarchyParents, m_hierarchyLeaves,
			m_positions, m_triangles, m_triangleMaterials, m_numTrianglesPerLeaf,
			centers.get(), heuristics.get(), auxA.get()};
		build(input, indices.get(), n);
	}

} // namespace bim<|endoftext|>


<commit_before>//===--- CompatibilityOverride.cpp - Compatibility override tests ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "../../stdlib/public/runtime/CompatibilityOverride.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Metadata.h"
#include "gtest/gtest.h"

#include <stdio.h>

using namespace swift;

bool EnableOverride;
bool Ran;

#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  static ret name ## Override(COMPATIBILITY_UNPAREN typedArgs,      \
                          Original_ ## name originalImpl) {         \
    if (!EnableOverride)                                            \
      return originalImpl namedArgs;                                \
    Ran = true;                                                     \
    return nullptr;                                                 \
  }
#include "../../stdlib/public/runtime/CompatibilityOverride.def"

struct OverrideSection {
  uintptr_t version;

#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  Override_ ## name name;
#include "../../stdlib/public/runtime/CompatibilityOverride.def"
};

OverrideSection Overrides __attribute__((section("__DATA,__swift_lite"))) = {
  0,
#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  name ## Override,
#include "../../stdlib/public/runtime/CompatibilityOverride.def"
};

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
const Metadata * _Nullable
swift_getTypeByMangledName(const char *typeNameStart, size_t typeNameLength,
                           size_t numberOfLevels,
                           size_t *parametersPerLevel,
                           const Metadata * const *flatSubstitutions);

class CompatibilityOverrideTest : public ::testing::Test {
protected:
  virtual void SetUp() {
    // This check is a bit pointless, as long as you trust the section
    // attribute to work correctly, but it ensures that the override
    // section actually gets linked into the test executable. If it's not
    // used then it disappears and the real tests begin to fail.
    ASSERT_EQ(Overrides.version, static_cast<uintptr_t>(0));

    EnableOverride = true;
    Ran = false;
  }

  virtual void TearDown() {
    EnableOverride = false;
    ASSERT_TRUE(Ran);
  }
};

TEST_F(CompatibilityOverrideTest, test_swift_getTypeByMangledName) {
  auto Result = swift_getTypeByMangledName("", 0, 0, nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCast) {
  auto Result = swift_dynamicCast(nullptr, nullptr, nullptr, nullptr,
                                  DynamicCastFlags::Default);
  ASSERT_TRUE(Result);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastClass) {
  auto Result = swift_dynamicCastClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastClassUnconditional) {
  auto Result = swift_dynamicCastClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClass) {
  auto Result = swift_dynamicCastObjCClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassUnconditional) {
  auto Result = swift_dynamicCastObjCClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClass) {
  auto Result = swift_dynamicCastForeignClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClassUnconditional) {
  auto Result = swift_dynamicCastForeignClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastUnknownClass) {
  auto Result = swift_dynamicCastUnknownClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastUnknownClassUnconditional) {
  auto Result = swift_dynamicCastUnknownClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastMetatype) {
  auto Result = swift_dynamicCastMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastMetatypeUnconditional) {
  auto Result = swift_dynamicCastMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassMetatype) {
  auto Result = swift_dynamicCastObjCClassMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassMetatypeUnconditional) {
  auto Result = swift_dynamicCastObjCClassMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClassMetatype) {
  auto Result = swift_dynamicCastForeignClassMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest,
       test_swift_dynamicCastForeignClassMetatypeUnconditional) {
  auto Result = swift_dynamicCastForeignClassMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_conformsToProtocol) {
  auto Result = swift_conformsToProtocol(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}
<commit_msg>[Runtime] Fix spurious test failure in CompatibilityOverride.cpp.<commit_after>//===--- CompatibilityOverride.cpp - Compatibility override tests ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "../../stdlib/public/runtime/CompatibilityOverride.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Metadata.h"
#include "gtest/gtest.h"

#include <stdio.h>

using namespace swift;

bool EnableOverride;
bool Ran;

#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  static ret name ## Override(COMPATIBILITY_UNPAREN typedArgs,      \
                          Original_ ## name originalImpl) {         \
    if (!EnableOverride)                                            \
      return originalImpl namedArgs;                                \
    Ran = true;                                                     \
    return nullptr;                                                 \
  }
#include "../../stdlib/public/runtime/CompatibilityOverride.def"

struct OverrideSection {
  uintptr_t version;

#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  Override_ ## name name;
#include "../../stdlib/public/runtime/CompatibilityOverride.def"
};

OverrideSection Overrides __attribute__((section("__DATA,__swift_lite"))) = {
  0,
#define OVERRIDE(name, ret, attrs, namespace, typedArgs, namedArgs) \
  name ## Override,
#include "../../stdlib/public/runtime/CompatibilityOverride.def"
};

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
const Metadata * _Nullable
swift_getTypeByMangledName(const char *typeNameStart, size_t typeNameLength,
                           size_t numberOfLevels,
                           size_t *parametersPerLevel,
                           const Metadata * const *flatSubstitutions);

class CompatibilityOverrideTest : public ::testing::Test {
protected:
  virtual void SetUp() {
    // This check is a bit pointless, as long as you trust the section
    // attribute to work correctly, but it ensures that the override
    // section actually gets linked into the test executable. If it's not
    // used then it disappears and the real tests begin to fail.
    ASSERT_EQ(Overrides.version, static_cast<uintptr_t>(0));

    EnableOverride = true;
    Ran = false;
  }

  virtual void TearDown() {
    EnableOverride = false;
    ASSERT_TRUE(Ran);
  }
};

TEST_F(CompatibilityOverrideTest, test_swift_getTypeByMangledName) {
  auto Result = swift_getTypeByMangledName("", 0, 0, nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCast) {
  auto Result = swift_dynamicCast(nullptr, nullptr, nullptr, nullptr,
                                  DynamicCastFlags::Default);
  ASSERT_FALSE(Result);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastClass) {
  auto Result = swift_dynamicCastClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastClassUnconditional) {
  auto Result = swift_dynamicCastClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClass) {
  auto Result = swift_dynamicCastObjCClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassUnconditional) {
  auto Result = swift_dynamicCastObjCClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClass) {
  auto Result = swift_dynamicCastForeignClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClassUnconditional) {
  auto Result = swift_dynamicCastForeignClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastUnknownClass) {
  auto Result = swift_dynamicCastUnknownClass(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastUnknownClassUnconditional) {
  auto Result = swift_dynamicCastUnknownClassUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastMetatype) {
  auto Result = swift_dynamicCastMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastMetatypeUnconditional) {
  auto Result = swift_dynamicCastMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassMetatype) {
  auto Result = swift_dynamicCastObjCClassMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastObjCClassMetatypeUnconditional) {
  auto Result = swift_dynamicCastObjCClassMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_dynamicCastForeignClassMetatype) {
  auto Result = swift_dynamicCastForeignClassMetatype(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest,
       test_swift_dynamicCastForeignClassMetatypeUnconditional) {
  auto Result = swift_dynamicCastForeignClassMetatypeUnconditional(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}

TEST_F(CompatibilityOverrideTest, test_swift_conformsToProtocol) {
  auto Result = swift_conformsToProtocol(nullptr, nullptr);
  ASSERT_EQ(Result, nullptr);
}
<|endoftext|>


<commit_before>/*
 *  Player.cpp
 *  Roguelike
 *
 *  Created by Daniel on 13/04/10.
 *  Copyright 2010 quantoaduro.com. All rights reserved.
 *
 */

#include "Player.h"

Player::Player() : Monster(new Ascii(64,1.0,0,0))
{
	behaviour = BehaviourNone;
	ai = AINone;
    sight = 20;
}<commit_msg>fixed bug<commit_after>/*
 *  Player.cpp
 *  Roguelike
 *
 *  Created by Daniel on 13/04/10.
 *  Copyright 2010 quantoaduro.com. All rights reserved.
 *
 */

#include "Player.h"

Player::Player() : Monster(new Ascii(64,1.0,0,0))
{
	behaviour = BehaviourNone;
    sight = 20;
}<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: modularWidget.C,v 1.13 2004/08/30 15:35:31 amoll Exp $
//

#include <BALL/VIEW/KERNEL/modularWidget.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/FORMAT/INIFile.h>
#include <BALL/VIEW/DIALOGS/preferences.h>
#include <qmenubar.h>

using namespace std;

namespace BALL
{
  namespace VIEW
	{

ModularWidget::ModularWidget(const char* name)
	throw()
	: Embeddable(),
		ConnectionObject(),
		window_menu_entry_id_(-1),
		show_window_enty_(false),
		default_visible_(true)
{
	if (name) setIdentifier(name);
}

ModularWidget::ModularWidget(const ModularWidget& widget)
	throw()
	: Embeddable(widget),
		ConnectionObject(widget)
{
}

ModularWidget::~ModularWidget()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "Destructing object " << (void *)this
							 << " of class " << RTTI::getName<ModularWidget>() << endl;
	#endif

	if (getMainControl() != 0)
	{
		getMainControl()->removeModularWidget(this);
	}
}

void ModularWidget::clear()
	throw()
{
}

void ModularWidget::registerWidget(ModularWidget* mwidget)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "registering ModularWidget at " << mwidget << endl;
	#endif

	if (!mwidget) throw(Exception::NullPointer(__FILE__, __LINE__));

	if (!RTTI::isKindOf<QObject>(*mwidget))
	{
		Log.error() << "ModularWidget::ModularWidget: widget " << this << " is not "
								<< "in a MainControl object!" << endl;
		return;
	}

	MainControl* mc = MainControl::getMainControl(dynamic_cast<QObject*>(mwidget));
	if (!mc)
	{
		Log.error() << "ModularWidget::ModularWidget(): widget " << this << " is not in a MainControl object!" << endl;
		return;
	}

	mc->addModularWidget(mwidget);

	#ifdef BALL_VIEW_DEBUG
		Log.info() << "ModularWidget::registered: " << mwidget << endl;
	#endif
}

void ModularWidget::initializeWidget(MainControl& /*main_control*/)
{
}

void ModularWidget::finalizeWidget(MainControl& /* main_control */)
//	throw()
{
}

void ModularWidget::checkMenu(MainControl& /* main_control */)
	throw()
{
}

void ModularWidget::initializePreferencesTab(Preferences & /* preferences */)
	throw()
{
}

void ModularWidget::finalizePreferencesTab(Preferences & /* preferences */)
	throw()
{
}

void ModularWidget::fetchPreferences(INIFile& inifile)
	throw()
{
	QWidget* widget= dynamic_cast<QWidget*>(this);
	if (!widget) return;

	if (inifile.hasEntry("WINDOWS", getIdentifier() + "::x"))
	{
		widget->move(inifile.getValue("WINDOWS", getIdentifier() + "::x").toUnsignedInt(),
								 inifile.getValue("WINDOWS", getIdentifier() + "::y").toUnsignedInt());
		widget->resize(inifile.getValue("WINDOWS", getIdentifier() + "::width").toUnsignedInt(),
									 inifile.getValue("WINDOWS", getIdentifier() + "::height").toUnsignedInt());
	}
}

void ModularWidget::writePreferences(INIFile& inifile)
	throw()
{
	QWidget* widget= dynamic_cast<QWidget*>(this);
	if (!widget) return;

	if (window_menu_entry_id_ != -1)
	{
		inifile.insertValue("WINDOWS", getIdentifier() + "::on",
			String(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));
	}

	inifile.insertValue("WINDOWS", getIdentifier() + "::x", String(widget->x()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::y", String(widget->y()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::width", String(widget->width()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::height", String(widget->height()));
}

void ModularWidget::setStatusbarText(String text)
	throw()
{
	getMainControl()->setStatusbarText(text);
}

MainControl* ModularWidget::getMainControl() const
	throw()
{
	return (MainControl*) ((ConnectionObject*)this)->getRoot();
}

FragmentDB& ModularWidget::getFragmentDB() const
	throw()
{
	return *((FragmentDB*)&getMainControl()->getFragmentDB());
}

void ModularWidget::dump(ostream& s, Size depth) const
	throw()
{
	ConnectionObject::dump(s, depth);
}

int ModularWidget::insertMenuEntry(int ID, const String& name, const QObject* receiver, const char* slot,
																	 int accel, int entry_ID, String hint)
	throw()
{
	return getMainControl()->insertMenuEntry(ID, name, receiver, slot, accel, entry_ID, hint);
}

QMenuBar* ModularWidget::menuBar()
	throw()
{
	return getMainControl()->menuBar();
}

String ModularWidget::getWorkingDir()
	throw()
{
	return getMainControl()->getWorkingDir();
}

void ModularWidget::setWorkingDir(const String& dir)
	throw()
{
	getMainControl()->setWorkingDir(dir);
}

void ModularWidget::setWorkingDirFromFilename_(String filename)
	throw()
{
	String seperators(FileSystem::PATH_SEPARATOR);
	// workaround on windows: QT returns the filename in linux style
	// but I am not sure, if this will stay this way.
#ifdef BALL_PLATFORM_WINDOWS
	 seperators += "/";
#endif
	vector<String> fields;
	Position p = filename.split(fields, seperators.c_str()) -1;
	if (p == 0) return;
	String suffix = fields[p];
	setWorkingDir(filename.getSubstring(0, filename.size() - (suffix.size() + 1)));
}

} } // namespaces
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: modularWidget.C,v 1.14 2004/08/30 15:36:04 amoll Exp $
//

#include <BALL/VIEW/KERNEL/modularWidget.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/FORMAT/INIFile.h>
#include <BALL/VIEW/DIALOGS/preferences.h>
#include <qmenubar.h>

using namespace std;

namespace BALL
{
  namespace VIEW
	{

ModularWidget::ModularWidget(const char* name)
	throw()
	: Embeddable(),
		ConnectionObject(),
		window_menu_entry_id_(-1),
		show_window_enty_(false),
		default_visible_(true)
{
	if (name) setIdentifier(name);
}

ModularWidget::ModularWidget(const ModularWidget& widget)
	throw()
	: Embeddable(widget),
		ConnectionObject(widget)
{
}

ModularWidget::~ModularWidget()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "Destructing object " << (void *)this
							 << " of class " << RTTI::getName<ModularWidget>() << endl;
	#endif

	if (getMainControl() != 0)
	{
		getMainControl()->removeModularWidget(this);
	}
}

void ModularWidget::clear()
	throw()
{
}

void ModularWidget::registerWidget(ModularWidget* mwidget)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "registering ModularWidget at " << mwidget << endl;
	#endif

	if (!mwidget) throw(Exception::NullPointer(__FILE__, __LINE__));

	if (!RTTI::isKindOf<QObject>(*mwidget))
	{
		Log.error() << "ModularWidget::ModularWidget: widget " << mwidget << " is not "
								<< "in a MainControl object!" << endl;
		return;
	}

	MainControl* mc = MainControl::getMainControl(dynamic_cast<QObject*>(mwidget));
	if (!mc)
	{
		Log.error() << "ModularWidget::ModularWidget(): widget " << mwidget << " is not in a MainControl object!" << endl;
		return;
	}

	mc->addModularWidget(mwidget);

	#ifdef BALL_VIEW_DEBUG
		Log.info() << "ModularWidget::registered: " << mwidget << endl;
	#endif
}

void ModularWidget::initializeWidget(MainControl& /*main_control*/)
{
}

void ModularWidget::finalizeWidget(MainControl& /* main_control */)
//	throw()
{
}

void ModularWidget::checkMenu(MainControl& /* main_control */)
	throw()
{
}

void ModularWidget::initializePreferencesTab(Preferences & /* preferences */)
	throw()
{
}

void ModularWidget::finalizePreferencesTab(Preferences & /* preferences */)
	throw()
{
}

void ModularWidget::fetchPreferences(INIFile& inifile)
	throw()
{
	QWidget* widget= dynamic_cast<QWidget*>(this);
	if (!widget) return;

	if (inifile.hasEntry("WINDOWS", getIdentifier() + "::x"))
	{
		widget->move(inifile.getValue("WINDOWS", getIdentifier() + "::x").toUnsignedInt(),
								 inifile.getValue("WINDOWS", getIdentifier() + "::y").toUnsignedInt());
		widget->resize(inifile.getValue("WINDOWS", getIdentifier() + "::width").toUnsignedInt(),
									 inifile.getValue("WINDOWS", getIdentifier() + "::height").toUnsignedInt());
	}
}

void ModularWidget::writePreferences(INIFile& inifile)
	throw()
{
	QWidget* widget= dynamic_cast<QWidget*>(this);
	if (!widget) return;

	if (window_menu_entry_id_ != -1)
	{
		inifile.insertValue("WINDOWS", getIdentifier() + "::on",
			String(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));
	}

	inifile.insertValue("WINDOWS", getIdentifier() + "::x", String(widget->x()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::y", String(widget->y()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::width", String(widget->width()));
	inifile.insertValue("WINDOWS", getIdentifier() + "::height", String(widget->height()));
}

void ModularWidget::setStatusbarText(String text)
	throw()
{
	getMainControl()->setStatusbarText(text);
}

MainControl* ModularWidget::getMainControl() const
	throw()
{
	return (MainControl*) ((ConnectionObject*)this)->getRoot();
}

FragmentDB& ModularWidget::getFragmentDB() const
	throw()
{
	return *((FragmentDB*)&getMainControl()->getFragmentDB());
}

void ModularWidget::dump(ostream& s, Size depth) const
	throw()
{
	ConnectionObject::dump(s, depth);
}

int ModularWidget::insertMenuEntry(int ID, const String& name, const QObject* receiver, const char* slot,
																	 int accel, int entry_ID, String hint)
	throw()
{
	return getMainControl()->insertMenuEntry(ID, name, receiver, slot, accel, entry_ID, hint);
}

QMenuBar* ModularWidget::menuBar()
	throw()
{
	return getMainControl()->menuBar();
}

String ModularWidget::getWorkingDir()
	throw()
{
	return getMainControl()->getWorkingDir();
}

void ModularWidget::setWorkingDir(const String& dir)
	throw()
{
	getMainControl()->setWorkingDir(dir);
}

void ModularWidget::setWorkingDirFromFilename_(String filename)
	throw()
{
	String seperators(FileSystem::PATH_SEPARATOR);
	// workaround on windows: QT returns the filename in linux style
	// but I am not sure, if this will stay this way.
#ifdef BALL_PLATFORM_WINDOWS
	 seperators += "/";
#endif
	vector<String> fields;
	Position p = filename.split(fields, seperators.c_str()) -1;
	if (p == 0) return;
	String suffix = fields[p];
	setWorkingDir(filename.getSubstring(0, filename.size() - (suffix.size() + 1)));
}

} } // namespaces
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "common.hxx"
#include "misc.hxx"
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
#include <osl/diagnose.h>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/awt/FontEmphasisMark.hpp>
#include <com/sun/star/awt/FontRelief.hpp>
#include <vector>

namespace xmlscript
{

struct Style
{
    sal_uInt32 _backgroundColor;
    sal_uInt32 _textColor;
    sal_uInt32 _textLineColor;
    sal_Int16 _border;
    sal_Int32 _borderColor;
    css::awt::FontDescriptor _descr;
    sal_uInt16 _fontRelief;
    sal_uInt16 _fontEmphasisMark;
    sal_uInt32 _fillColor;
    sal_Int16 _visualEffect;

    // current highest mask: 0x40
    short _all;
    short _set;

    OUString _id;

    inline Style( short all_ ) SAL_THROW(())
        : _fontRelief( css::awt::FontRelief::NONE )
        , _fontEmphasisMark( css::awt::FontEmphasisMark::NONE )
        , _all( all_ )
        , _set( 0 )
        {}

    css::uno::Reference< css::xml::sax::XAttributeList > createElement();
};
class StyleBag
{
    ::std::vector< Style * > _styles;

public:
    ~StyleBag() SAL_THROW(());

    OUString getStyleId( Style const & rStyle ) SAL_THROW(());

    void dump( css::uno::Reference< css::xml::sax::XExtendedDocumentHandler >
               const & xOut );
};

class ElementDescriptor
    : public ::xmlscript::XMLElement
{
    css::uno::Reference< css::beans::XPropertySet > _xProps;
    css::uno::Reference< css::beans::XPropertyState > _xPropState;
    css::uno::Reference< css::frame::XModel > _xDocument;

public:
    inline ElementDescriptor(
        css::uno::Reference< css::beans::XPropertySet > const & xProps,
        css::uno::Reference< css::beans::XPropertyState > const & xPropState,
        OUString const & name, css::uno::Reference< css::frame::XModel > const & xDocument )
        SAL_THROW(())
        : XMLElement( name )
        , _xProps( xProps )
        , _xPropState( xPropState )
        , _xDocument( xDocument )
        {}
    inline ElementDescriptor(
        OUString const & name )
        SAL_THROW(())
        : XMLElement( name )
        {}

    template<typename T>
    inline void read(
        OUString const & propName, OUString const & attrName,
        bool forceAttribute = false );

    template<typename T>
    inline bool readProp( T * ret, OUString const & rPropName );
    css::uno::Any readProp( OUString const & rPropName );
    void readScrollableSettings();
    void readDefaults( bool supportPrintable = true, bool supportVisible = true );
    void readStringAttr(
        OUString const & rPropName, OUString const & rAttrName );
    inline void readDoubleAttr(
        OUString const & rPropName, OUString const & rAttrName )
        { read<double>( rPropName, rAttrName ); }
    inline void readLongAttr(
        OUString const & rPropName, OUString const & rAttrName,
        bool forceAttribute = false )
        { read<sal_Int32>( rPropName, rAttrName, forceAttribute ); }
    void readHexLongAttr(
        OUString const & rPropName, OUString const & rAttrName );
    inline void readShortAttr(
        OUString const & rPropName, OUString const & rAttrName )
        { read<sal_Int32>( rPropName, rAttrName ); }
    inline void readBoolAttr(
        OUString const & rPropName, OUString const & rAttrName );

    void readAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readVerticalAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImageURLAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImageAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImagePositionAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDateAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDateFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readTimeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readTimeFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readOrientationAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readButtonTypeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readLineEndFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readSelectionTypeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDataAwareAttr(
        OUString const & rAttrName );
    inline void addBoolAttr(
        OUString const & rAttrName, sal_Bool bValue )
        { addAttribute( rAttrName, OUString::boolean(bValue) ); }
    void addNumberFormatAttr(
        css::uno::Reference< css::beans::XPropertySet >
        const & xFormatProperties );

    void readEvents() SAL_THROW( (css::uno::Exception) );
    void readDialogModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readBullitinBoard( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readMultiPageModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFrameModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readPageModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readEditModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readCheckBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readRadioButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readComboBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readCurrencyFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readDateFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFileControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readTreeControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedTextModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readGroupBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readImageControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readListBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readNumericFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readPatternFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFormattedFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readTimeFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedLineModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readProgressBarModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readScrollBarModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readSpinButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedHyperLinkModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
};

template<typename T>
inline void ElementDescriptor::read(
    OUString const & propName, OUString const & attrName,
    bool forceAttribute )
{
    if (forceAttribute ||
        css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( propName ))
    {
        css::uno::Any a( _xProps->getPropertyValue( propName ) );
        T v = T();
        if (a >>= v)
            addAttribute( attrName, OUString::number(v) );
        else
            OSL_FAIL( "### unexpected property type!" );
    }
}

template<>
inline void ElementDescriptor::read<sal_Bool>(
    OUString const & propName, OUString const & attrName,
    bool forceAttribute )
{
    if (forceAttribute ||
        css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( propName ))
    {
        css::uno::Any a( _xProps->getPropertyValue( propName ) );
        sal_Bool v = sal_Bool();
        if (a >>= v)
            addAttribute( attrName, OUString::boolean(v) );
        else
            OSL_FAIL( "### unexpected property type!" );
    }
}

inline void ElementDescriptor::readBoolAttr(
    OUString const & rPropName, OUString const & rAttrName )
{
    read<sal_Bool>( rPropName, rAttrName );
}

template<typename T>
inline bool ElementDescriptor::readProp(
    T * ret, OUString const & rPropName )
{
    _xProps->getPropertyValue( rPropName ) >>= *ret;
    return css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( rPropName );
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708728 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "common.hxx"
#include "misc.hxx"
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
#include <osl/diagnose.h>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/awt/FontDescriptor.hpp>
#include <com/sun/star/awt/FontEmphasisMark.hpp>
#include <com/sun/star/awt/FontRelief.hpp>
#include <vector>

namespace xmlscript
{

struct Style
{
    sal_uInt32 _backgroundColor;
    sal_uInt32 _textColor;
    sal_uInt32 _textLineColor;
    sal_Int16 _border;
    sal_Int32 _borderColor;
    css::awt::FontDescriptor _descr;
    sal_uInt16 _fontRelief;
    sal_uInt16 _fontEmphasisMark;
    sal_uInt32 _fillColor;
    sal_Int16 _visualEffect;

    // current highest mask: 0x40
    short _all;
    short _set;

    OUString _id;

    Style( short all_ ) SAL_THROW(())
        : _backgroundColor(0)
        , _textColor(0)
        , _textLineColor(0)
        , _border(0)
        , _borderColor(0)
        , _fontRelief(css::awt::FontRelief::NONE)
        , _fontEmphasisMark(css::awt::FontEmphasisMark::NONE)
        , _fillColor(0)
        , _visualEffect(0)
        , _all(all_)
        , _set(0)
    {
    }

    css::uno::Reference< css::xml::sax::XAttributeList > createElement();
};
class StyleBag
{
    ::std::vector< Style * > _styles;

public:
    ~StyleBag() SAL_THROW(());

    OUString getStyleId( Style const & rStyle ) SAL_THROW(());

    void dump( css::uno::Reference< css::xml::sax::XExtendedDocumentHandler >
               const & xOut );
};

class ElementDescriptor
    : public ::xmlscript::XMLElement
{
    css::uno::Reference< css::beans::XPropertySet > _xProps;
    css::uno::Reference< css::beans::XPropertyState > _xPropState;
    css::uno::Reference< css::frame::XModel > _xDocument;

public:
    inline ElementDescriptor(
        css::uno::Reference< css::beans::XPropertySet > const & xProps,
        css::uno::Reference< css::beans::XPropertyState > const & xPropState,
        OUString const & name, css::uno::Reference< css::frame::XModel > const & xDocument )
        SAL_THROW(())
        : XMLElement( name )
        , _xProps( xProps )
        , _xPropState( xPropState )
        , _xDocument( xDocument )
        {}
    inline ElementDescriptor(
        OUString const & name )
        SAL_THROW(())
        : XMLElement( name )
        {}

    template<typename T>
    inline void read(
        OUString const & propName, OUString const & attrName,
        bool forceAttribute = false );

    template<typename T>
    inline bool readProp( T * ret, OUString const & rPropName );
    css::uno::Any readProp( OUString const & rPropName );
    void readScrollableSettings();
    void readDefaults( bool supportPrintable = true, bool supportVisible = true );
    void readStringAttr(
        OUString const & rPropName, OUString const & rAttrName );
    inline void readDoubleAttr(
        OUString const & rPropName, OUString const & rAttrName )
        { read<double>( rPropName, rAttrName ); }
    inline void readLongAttr(
        OUString const & rPropName, OUString const & rAttrName,
        bool forceAttribute = false )
        { read<sal_Int32>( rPropName, rAttrName, forceAttribute ); }
    void readHexLongAttr(
        OUString const & rPropName, OUString const & rAttrName );
    inline void readShortAttr(
        OUString const & rPropName, OUString const & rAttrName )
        { read<sal_Int32>( rPropName, rAttrName ); }
    inline void readBoolAttr(
        OUString const & rPropName, OUString const & rAttrName );

    void readAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readVerticalAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImageURLAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImageAlignAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readImagePositionAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDateAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDateFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readTimeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readTimeFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readOrientationAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readButtonTypeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readLineEndFormatAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readSelectionTypeAttr(
        OUString const & rPropName, OUString const & rAttrName );
    void readDataAwareAttr(
        OUString const & rAttrName );
    inline void addBoolAttr(
        OUString const & rAttrName, sal_Bool bValue )
        { addAttribute( rAttrName, OUString::boolean(bValue) ); }
    void addNumberFormatAttr(
        css::uno::Reference< css::beans::XPropertySet >
        const & xFormatProperties );

    void readEvents() SAL_THROW( (css::uno::Exception) );
    void readDialogModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readBullitinBoard( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readMultiPageModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFrameModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readPageModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readEditModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readCheckBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readRadioButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readComboBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readCurrencyFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readDateFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFileControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readTreeControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedTextModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readGroupBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readImageControlModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readListBoxModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readNumericFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readPatternFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFormattedFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readTimeFieldModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedLineModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readProgressBarModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readScrollBarModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readSpinButtonModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
    void readFixedHyperLinkModel( StyleBag * all_styles )
        SAL_THROW( (css::uno::Exception) );
};

template<typename T>
inline void ElementDescriptor::read(
    OUString const & propName, OUString const & attrName,
    bool forceAttribute )
{
    if (forceAttribute ||
        css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( propName ))
    {
        css::uno::Any a( _xProps->getPropertyValue( propName ) );
        T v = T();
        if (a >>= v)
            addAttribute( attrName, OUString::number(v) );
        else
            OSL_FAIL( "### unexpected property type!" );
    }
}

template<>
inline void ElementDescriptor::read<sal_Bool>(
    OUString const & propName, OUString const & attrName,
    bool forceAttribute )
{
    if (forceAttribute ||
        css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( propName ))
    {
        css::uno::Any a( _xProps->getPropertyValue( propName ) );
        sal_Bool v = sal_Bool();
        if (a >>= v)
            addAttribute( attrName, OUString::boolean(v) );
        else
            OSL_FAIL( "### unexpected property type!" );
    }
}

inline void ElementDescriptor::readBoolAttr(
    OUString const & rPropName, OUString const & rAttrName )
{
    read<sal_Bool>( rPropName, rAttrName );
}

template<typename T>
inline bool ElementDescriptor::readProp(
    T * ret, OUString const & rPropName )
{
    _xProps->getPropertyValue( rPropName ) >>= *ret;
    return css::beans::PropertyState_DEFAULT_VALUE !=
        _xPropState->getPropertyState( rPropName );
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>
#include <QGuiApplication>
#include <QQmlFileSelector>
#include <QStringList>
#include <QTranslator>

#include <qmltoolbox/qmltoolbox-version.h>
#include <qmltoolbox/QmlApplicationEngine.h>
#include <qmltoolbox/MessageHandler.h>

int main(int argc, char *argv[])
{
    qInstallMessageHandler(qmltoolbox::globalMessageHandler);
    qmltoolbox::MessageHandler::instance().installStdHandlers();

#ifndef QMLTOOLBOX_QT57
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);
    app.setOrganizationName(QMLTOOLBOX_AUTHOR_ORGANIZATION);
    app.setOrganizationDomain("cginternals.com");
    app.setApplicationName(QString(QMLTOOLBOX_PROJECT_NAME) + "_uiconcept");

    // Create QtQuick engine
    qmltoolbox::QmlApplicationEngine engine;

    // Setup Localization
    QTranslator translator;
    translator.load(QLocale::system(), "uiconcept", ".", engine.qmlToolboxModulePath() + "/examples/uiconcept/i18n");
    app.installTranslator(&translator);

#ifdef QMLTOOLBOX_QT54
    auto fileSelector = QQmlFileSelector::get(&engine);
    fileSelector->setExtraSelectors(QStringList{ QMLTOOLBOX_QT54 });
#endif

    // Load and show QML
    engine.load(QUrl::fromLocalFile(engine.qmlToolboxModulePath() + "/examples/uiconcept/window.qml"));

    // Run application
    int res = app.exec();

    // Stop application
    return res;
}
<commit_msg>add fullScreen capabilities<commit_after>
#include <QGuiApplication>
#include <QQmlFileSelector>
#include <QStringList>
#include <QTranslator>
#include <QWindow>

#include <qmltoolbox/qmltoolbox-version.h>
#include <qmltoolbox/QmlApplicationEngine.h>
#include <qmltoolbox/MessageHandler.h>

int main(int argc, char *argv[])
{
    qInstallMessageHandler(qmltoolbox::globalMessageHandler);
    qmltoolbox::MessageHandler::instance().installStdHandlers();

#ifndef QMLTOOLBOX_QT57
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);
    app.setOrganizationName(QMLTOOLBOX_AUTHOR_ORGANIZATION);
    app.setOrganizationDomain("cginternals.com");
    app.setApplicationName(QString(QMLTOOLBOX_PROJECT_NAME) + "_uiconcept");

    // Create QtQuick engine
    qmltoolbox::QmlApplicationEngine engine;

    // Setup Localization
    QTranslator translator;
    translator.load(QLocale::system(), "uiconcept", ".", engine.qmlToolboxModulePath() + "/examples/uiconcept/i18n");
    app.installTranslator(&translator);

#ifdef QMLTOOLBOX_QT54
    auto fileSelector = QQmlFileSelector::get(&engine);
    fileSelector->setExtraSelectors(QStringList{ QMLTOOLBOX_QT54 });
#endif

    // Load and show QML
    engine.load(QUrl::fromLocalFile(engine.qmlToolboxModulePath() + "/examples/uiconcept/window.qml"));

    auto windows = app.allWindows();
	if (!windows.empty())
	{
		auto window = windows.first();
		QObject::connect(window, SIGNAL(toFullScreen()), window, SLOT(showFullScreen()));
		QObject::connect(window, SIGNAL(toNormalScreen()), window, SLOT(showNormal()));
	}

    // Run application
    int res = app.exec();

    // Stop application
    return res;
}
<|endoftext|>


<commit_before>#include "bitstream.h"

#include <complex>

#include "wdsp/wdsp.h"

#include "filters.h"

#define FS        250000.0
#define FC_0      57000.0
#define IBUFLEN   4096
#define OBUFLEN   128
#define BITBUFLEN 1024

namespace redsea {

int sign(double a) {
  return (a >= 0 ? 1 : 0);
}

BitStream::BitStream() : tot_errs_(2), reading_frame_(0), counter_(0), subcarr_freq_(FC_0), bit_buffer_(BITBUFLEN), mixer_phi_(0), clock_offset_(0), is_eof_(false), subcarr_lopass_fir_(wdsp::FIR(4000.0 / FS, 127)), subcarr_baseband_(IBUFLEN) {

}

void BitStream::deltaBit(int b) {
  bit_buffer_.append(b ^ dbit_);
  dbit_ = b;
}

void BitStream::biphase(double acc) {

  if (sign(acc) != sign(prev_acc_)) {
    tot_errs_[counter_ % 2] ++;
  }

  if (counter_ % 2 == reading_frame_) {
    deltaBit(sign(acc + prev_acc_));
  }
  if (counter_ == 0) {
    if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) {
      reading_frame_ = 1 - reading_frame_;
    }
    tot_errs_[0] = 0;
    tot_errs_[1] = 0;
  }

  prev_acc_ = acc;
  counter_ = (counter_ + 1) % 800;
}

void BitStream::demodulateMoreBits() {

  int16_t sample[IBUFLEN];
  int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin);
  if (bytesread < IBUFLEN) {
    is_eof_ = true;
    return;
  }

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

    /* Subcarrier downmix & phase recovery */

    mixer_phi_ += 2 * M_PI * subcarr_freq_ * (1.0/FS);
    subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] / 32768.0,
        mixer_phi_), subcarr_lopass_fir_);

    double pll_beta = 16e-3;

    /* Decimate band-limited signal */
    if (numsamples_ % 8 == 0) {

      std::complex<double> sc_sample = subcarr_baseband_.at(0);
      subcarr_baseband_.forward(8);

      double phase_error = arg(sc_sample);
      if (phase_error >= M_PI_2) {
        phase_error -= M_PI;
      } else if (phase_error <= -M_PI_2) {
        phase_error += M_PI;
      }

      mixer_phi_    -= pll_beta * phase_error;
      subcarr_freq_ -= .5 * pll_beta * phase_error;

      /* 1187.5 Hz clock */

      double clock_phi = mixer_phi_ / 48.0 + clock_offset_;
      double lo_clock  = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1);

      /* Clock phase recovery */

      if (sign(prev_bb_) != sign(real(sc_sample))) {
        double d_cphi = fmod(clock_phi, M_PI);
        if (d_cphi >= M_PI_2) d_cphi -= M_PI;
        clock_offset_ -= 0.005 * d_cphi;
      }

      /* biphase symbol integrate & dump */
      acc_ += real(sc_sample) * lo_clock;

      if (sign(lo_clock) != sign(prevclock_)) {
        biphase(acc_);
        acc_ = 0;
      }

      prevclock_ = lo_clock;
      prev_bb_ = real(sc_sample);
    }

    if (numsamples_ % 1000000 == 0)
      printf(":%.2f Hz\n", subcarr_freq_);

    numsamples_ ++;

  }

}

int BitStream::getNextBit() {
  while (bit_buffer_.getFillCount() < 1 && !isEOF())
    demodulateMoreBits();

  return bit_buffer_.getNext();
}

bool BitStream::isEOF() const {
  return is_eof_;
}

} // namespace redsea
<commit_msg>formatting<commit_after>#include "bitstream.h"

#include <complex>

#include "wdsp/wdsp.h"

#include "filters.h"

#define FS        250000.0
#define FC_0      57000.0
#define IBUFLEN   4096
#define OBUFLEN   128
#define BITBUFLEN 1024

namespace redsea {

int sign(double a) {
  return (a >= 0 ? 1 : 0);
}

BitStream::BitStream() : subcarr_freq_(FC_0), counter_(0), tot_errs_(2), reading_frame_(0),
  bit_buffer_(BITBUFLEN), subcarr_lopass_fir_(wdsp::FIR(4000.0 / FS, 127)),
  subcarr_baseband_(IBUFLEN), is_eof_(false) {

}

void BitStream::deltaBit(int b) {
  bit_buffer_.append(b ^ dbit_);
  dbit_ = b;
}

void BitStream::biphase(double acc) {

  if (sign(acc) != sign(prev_acc_)) {
    tot_errs_[counter_ % 2] ++;
  }

  if (counter_ % 2 == reading_frame_) {
    deltaBit(sign(acc + prev_acc_));
  }
  if (counter_ == 0) {
    if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) {
      reading_frame_ = 1 - reading_frame_;
    }
    tot_errs_[0] = 0;
    tot_errs_[1] = 0;
  }

  prev_acc_ = acc;
  counter_ = (counter_ + 1) % 800;
}

void BitStream::demodulateMoreBits() {

  int16_t sample[IBUFLEN];
  int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin);
  if (bytesread < IBUFLEN) {
    is_eof_ = true;
    return;
  }

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

    /* Subcarrier downmix & phase recovery */

    mixer_phi_ += 2 * M_PI * subcarr_freq_ * (1.0/FS);
    subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] / 32768.0,
        mixer_phi_), subcarr_lopass_fir_);

    double pll_beta = 16e-3;

    /* Decimate band-limited signal */
    if (numsamples_ % 8 == 0) {

      std::complex<double> sc_sample = subcarr_baseband_.at(0);
      subcarr_baseband_.forward(8);

      double phase_error = arg(sc_sample);
      if (phase_error >= M_PI_2) {
        phase_error -= M_PI;
      } else if (phase_error <= -M_PI_2) {
        phase_error += M_PI;
      }

      mixer_phi_    -= pll_beta * phase_error;
      subcarr_freq_ -= .5 * pll_beta * phase_error;

      /* 1187.5 Hz clock */

      double clock_phi = mixer_phi_ / 48.0 + clock_offset_;
      double lo_clock  = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1);

      /* Clock phase recovery */

      if (sign(prev_bb_) != sign(real(sc_sample))) {
        double d_cphi = fmod(clock_phi, M_PI);
        if (d_cphi >= M_PI_2) d_cphi -= M_PI;
        clock_offset_ -= 0.005 * d_cphi;
      }

      /* biphase symbol integrate & dump */
      acc_ += real(sc_sample) * lo_clock;

      if (sign(lo_clock) != sign(prevclock_)) {
        biphase(acc_);
        acc_ = 0;
      }

      prevclock_ = lo_clock;
      prev_bb_ = real(sc_sample);
    }

    if (numsamples_ % 1000000 == 0)
      printf(":%.2f Hz\n", subcarr_freq_);

    numsamples_ ++;

  }

}

int BitStream::getNextBit() {
  while (bit_buffer_.getFillCount() < 1 && !isEOF())
    demodulateMoreBits();

  return bit_buffer_.getNext();
}

bool BitStream::isEOF() const {
  return is_eof_;
}

} // namespace redsea
<|endoftext|>


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

#include "build_log.h"

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#ifndef _WIN32
#include <unistd.h>
#endif

#include "build.h"
#include "graph.h"
#include "metrics.h"
#include "util.h"

// Implementation details:
// Each run's log appends to the log file.
// To load, we run through all log entries in series, throwing away
// older runs.
// Once the number of redundant entries exceeds a threshold, we write
// out a new file and replace the existing one with it.

namespace {

const char kFileSignature[] = "# ninja log v%d\n";
const int kCurrentVersion = 4;

}  // namespace

BuildLog::BuildLog()
  : log_file_(NULL), config_(NULL), needs_recompaction_(false) {}

BuildLog::~BuildLog() {
  Close();
}

bool BuildLog::OpenForWrite(const string& path, string* err) {
  if (config_ && config_->dry_run)
    return true;  // Do nothing, report success.

  if (needs_recompaction_) {
    Close();
    if (!Recompact(path, err))
      return false;
  }

  log_file_ = fopen(path.c_str(), "ab");
  if (!log_file_) {
    *err = strerror(errno);
    return false;
  }
  setvbuf(log_file_, NULL, _IOLBF, BUFSIZ);
  SetCloseOnExec(fileno(log_file_));

  // Opening a file in append mode doesn't set the file pointer to the file's
  // end on Windows. Do that explicitly.
  fseek(log_file_, 0, SEEK_END);

  if (ftell(log_file_) == 0) {
    if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
      *err = strerror(errno);
      return false;
    }
  }

  return true;
}

void BuildLog::RecordCommand(Edge* edge, int start_time, int end_time,
                             TimeStamp restat_mtime) {
  string command = edge->EvaluateCommand(true);
  for (vector<Node*>::iterator out = edge->outputs_.begin();
       out != edge->outputs_.end(); ++out) {
    const string& path = (*out)->path();
    Log::iterator i = log_.find(path);
    LogEntry* log_entry;
    if (i != log_.end()) {
      log_entry = i->second;
    } else {
      log_entry = new LogEntry;
      log_entry->output = path;
      log_.insert(Log::value_type(log_entry->output, log_entry));
    }
    log_entry->command = command;
    log_entry->start_time = start_time;
    log_entry->end_time = end_time;
    log_entry->restat_mtime = restat_mtime;

    if (log_file_)
      WriteEntry(log_file_, *log_entry);
  }
}

void BuildLog::Close() {
  if (log_file_)
    fclose(log_file_);
  log_file_ = NULL;
}

class LineReader {
 public:
  explicit LineReader(FILE* file) : file_(file) {}

  // Reads a \n-terminated line from the file passed to the constructor.
  // On return, *line_start points to the beginning of the next line, and
  // *line_end points to the \n at the end of the line. If no newline is seen
  // in a fixed buffer size, *line_end is set to NULL. Returns false on EOF.
  bool ReadLine(char** line_start, char** line_end) {
    if (!fgets(buf_, sizeof(buf_), file_))
      return false;

    *line_start = buf_;
    *line_end = strchr(buf_, '\n');
    return true;
  }

 private:
  FILE* file_;
  char buf_[256 << 10];
};

bool BuildLog::Load(const string& path, string* err) {
  METRIC_RECORD(".ninja_log load");
  FILE* file = fopen(path.c_str(), "r");
  if (!file) {
    if (errno == ENOENT)
      return true;
    *err = strerror(errno);
    return false;
  }

  int log_version = 0;
  int unique_entry_count = 0;
  int total_entry_count = 0;

  LineReader reader(file);
  char* line_start, *line_end;
  while (reader.ReadLine(&line_start, &line_end)) {
    if (!log_version) {
      log_version = 1;  // Assume by default.
      if (sscanf(line_start, kFileSignature, &log_version) > 0)
        continue;
    }

    // If no newline was found in this chunk, read the next.
    if (!line_end)
      continue;

    char field_separator = log_version >= 4 ? '\t' : ' ';

    char* start = line_start;
    char* end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;

    int start_time = 0, end_time = 0;
    TimeStamp restat_mtime = 0;

    start_time = atoi(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;
    end_time = atoi(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;
    restat_mtime = atol(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    string output = string(start, end - start);

    start = end + 1;
    end = line_end;

    LogEntry* entry;
    Log::iterator i = log_.find(output);
    if (i != log_.end()) {
      entry = i->second;
    } else {
      entry = new LogEntry;
      entry->output = output;
      log_.insert(Log::value_type(entry->output, entry));
      ++unique_entry_count;
    }
    ++total_entry_count;

    entry->start_time = start_time;
    entry->end_time = end_time;
    entry->restat_mtime = restat_mtime;
    entry->command = string(start, end - start);
  }

  // Decide whether it's time to rebuild the log:
  // - if we're upgrading versions
  // - if it's getting large
  int kMinCompactionEntryCount = 100;
  int kCompactionRatio = 3;
  if (log_version < kCurrentVersion) {
    needs_recompaction_ = true;
  } else if (total_entry_count > kMinCompactionEntryCount &&
             total_entry_count > unique_entry_count * kCompactionRatio) {
    needs_recompaction_ = true;
  }

  fclose(file);

  return true;
}

BuildLog::LogEntry* BuildLog::LookupByOutput(const string& path) {
  Log::iterator i = log_.find(path);
  if (i != log_.end())
    return i->second;
  return NULL;
}

void BuildLog::WriteEntry(FILE* f, const LogEntry& entry) {
  fprintf(f, "%d\t%d\t%ld\t%s\t%s\n",
          entry.start_time, entry.end_time, (long) entry.restat_mtime,
          entry.output.c_str(), entry.command.c_str());
}

bool BuildLog::Recompact(const string& path, string* err) {
  printf("Recompacting log...\n");

  string temp_path = path + ".recompact";
  FILE* f = fopen(temp_path.c_str(), "wb");
  if (!f) {
    *err = strerror(errno);
    return false;
  }

  if (fprintf(f, kFileSignature, kCurrentVersion) < 0) {
    *err = strerror(errno);
    fclose(f);
    return false;
  }

  for (Log::iterator i = log_.begin(); i != log_.end(); ++i) {
    WriteEntry(f, *i->second);
  }

  fclose(f);
  if (unlink(path.c_str()) < 0) {
    *err = strerror(errno);
    return false;
  }

  if (rename(temp_path.c_str(), path.c_str()) < 0) {
    *err = strerror(errno);
    return false;
  }

  return true;
}
<commit_msg>Switch LineReader from fgets() to just fread().<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "build_log.h"

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#ifndef _WIN32
#include <unistd.h>
#endif

#include "build.h"
#include "graph.h"
#include "metrics.h"
#include "util.h"

// Implementation details:
// Each run's log appends to the log file.
// To load, we run through all log entries in series, throwing away
// older runs.
// Once the number of redundant entries exceeds a threshold, we write
// out a new file and replace the existing one with it.

namespace {

const char kFileSignature[] = "# ninja log v%d\n";
const int kCurrentVersion = 4;

}  // namespace

BuildLog::BuildLog()
  : log_file_(NULL), config_(NULL), needs_recompaction_(false) {}

BuildLog::~BuildLog() {
  Close();
}

bool BuildLog::OpenForWrite(const string& path, string* err) {
  if (config_ && config_->dry_run)
    return true;  // Do nothing, report success.

  if (needs_recompaction_) {
    Close();
    if (!Recompact(path, err))
      return false;
  }

  log_file_ = fopen(path.c_str(), "ab");
  if (!log_file_) {
    *err = strerror(errno);
    return false;
  }
  setvbuf(log_file_, NULL, _IOLBF, BUFSIZ);
  SetCloseOnExec(fileno(log_file_));

  // Opening a file in append mode doesn't set the file pointer to the file's
  // end on Windows. Do that explicitly.
  fseek(log_file_, 0, SEEK_END);

  if (ftell(log_file_) == 0) {
    if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
      *err = strerror(errno);
      return false;
    }
  }

  return true;
}

void BuildLog::RecordCommand(Edge* edge, int start_time, int end_time,
                             TimeStamp restat_mtime) {
  string command = edge->EvaluateCommand(true);
  for (vector<Node*>::iterator out = edge->outputs_.begin();
       out != edge->outputs_.end(); ++out) {
    const string& path = (*out)->path();
    Log::iterator i = log_.find(path);
    LogEntry* log_entry;
    if (i != log_.end()) {
      log_entry = i->second;
    } else {
      log_entry = new LogEntry;
      log_entry->output = path;
      log_.insert(Log::value_type(log_entry->output, log_entry));
    }
    log_entry->command = command;
    log_entry->start_time = start_time;
    log_entry->end_time = end_time;
    log_entry->restat_mtime = restat_mtime;

    if (log_file_)
      WriteEntry(log_file_, *log_entry);
  }
}

void BuildLog::Close() {
  if (log_file_)
    fclose(log_file_);
  log_file_ = NULL;
}

class LineReader {
 public:
  explicit LineReader(FILE* file)
    : file_(file), buf_end_(buf_), line_start_(buf_), line_end_(NULL) {}

  // Reads a \n-terminated line from the file passed to the constructor.
  // On return, *line_start points to the beginning of the next line, and
  // *line_end points to the \n at the end of the line. If no newline is seen
  // in a fixed buffer size, *line_end is set to NULL. Returns false on EOF.
  bool ReadLine(char** line_start, char** line_end) {
    if (line_start_ >= buf_end_ || !line_end_) {
      // Buffer empty, refill.
      size_t size_read = fread(buf_, 1, sizeof(buf_), file_);
      if (!size_read)
        return false;
      line_start_ = buf_;
      buf_end_ = buf_ + size_read;
    } else {
      // Advance to next line in buffer.
      line_start_ = line_end_ + 1;
    }

    line_end_ = (char*)memchr(line_start_, '\n', buf_end_ - line_start_);
    if (!line_end_) {
      // No newline. Move rest of data to start of buffer, fill rest.
      size_t already_consumed = line_start_ - buf_;
      size_t size_rest = (buf_end_ - buf_) - already_consumed;
      memmove(buf_, line_start_, size_rest);

      size_t read = fread(buf_ + size_rest, 1, sizeof(buf_) - size_rest, file_);
      buf_end_ = buf_ + size_rest + read;
      line_start_ = buf_;
      line_end_ = (char*)memchr(line_start_, '\n', buf_end_ - line_start_);
    }

    *line_start = line_start_;
    *line_end = line_end_;
    return true;
  }

 private:
  FILE* file_;
  char buf_[256 << 10];
  char* buf_end_;  // Points one past the last valid byte in |buf_|.

  char* line_start_;
  // Points at the next \n in buf_ after line_start, or NULL.
  char* line_end_;
};

bool BuildLog::Load(const string& path, string* err) {
  METRIC_RECORD(".ninja_log load");
  FILE* file = fopen(path.c_str(), "r");
  if (!file) {
    if (errno == ENOENT)
      return true;
    *err = strerror(errno);
    return false;
  }

  int log_version = 0;
  int unique_entry_count = 0;
  int total_entry_count = 0;

  LineReader reader(file);
  char* line_start, *line_end;
  while (reader.ReadLine(&line_start, &line_end)) {
    if (!log_version) {
      log_version = 1;  // Assume by default.
      if (sscanf(line_start, kFileSignature, &log_version) > 0)
        continue;
    }

    // If no newline was found in this chunk, read the next.
    if (!line_end)
      continue;

    char field_separator = log_version >= 4 ? '\t' : ' ';

    char* start = line_start;
    char* end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;

    int start_time = 0, end_time = 0;
    TimeStamp restat_mtime = 0;

    start_time = atoi(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;
    end_time = atoi(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    *end = 0;
    restat_mtime = atol(start);
    start = end + 1;

    end = (char*)memchr(start, field_separator, line_end - start);
    if (!end)
      continue;
    string output = string(start, end - start);

    start = end + 1;
    end = line_end;

    LogEntry* entry;
    Log::iterator i = log_.find(output);
    if (i != log_.end()) {
      entry = i->second;
    } else {
      entry = new LogEntry;
      entry->output = output;
      log_.insert(Log::value_type(entry->output, entry));
      ++unique_entry_count;
    }
    ++total_entry_count;

    entry->start_time = start_time;
    entry->end_time = end_time;
    entry->restat_mtime = restat_mtime;
    entry->command = string(start, end - start);
  }

  // Decide whether it's time to rebuild the log:
  // - if we're upgrading versions
  // - if it's getting large
  int kMinCompactionEntryCount = 100;
  int kCompactionRatio = 3;
  if (log_version < kCurrentVersion) {
    needs_recompaction_ = true;
  } else if (total_entry_count > kMinCompactionEntryCount &&
             total_entry_count > unique_entry_count * kCompactionRatio) {
    needs_recompaction_ = true;
  }

  fclose(file);

  return true;
}

BuildLog::LogEntry* BuildLog::LookupByOutput(const string& path) {
  Log::iterator i = log_.find(path);
  if (i != log_.end())
    return i->second;
  return NULL;
}

void BuildLog::WriteEntry(FILE* f, const LogEntry& entry) {
  fprintf(f, "%d\t%d\t%ld\t%s\t%s\n",
          entry.start_time, entry.end_time, (long) entry.restat_mtime,
          entry.output.c_str(), entry.command.c_str());
}

bool BuildLog::Recompact(const string& path, string* err) {
  printf("Recompacting log...\n");

  string temp_path = path + ".recompact";
  FILE* f = fopen(temp_path.c_str(), "wb");
  if (!f) {
    *err = strerror(errno);
    return false;
  }

  if (fprintf(f, kFileSignature, kCurrentVersion) < 0) {
    *err = strerror(errno);
    fclose(f);
    return false;
  }

  for (Log::iterator i = log_.begin(); i != log_.end(); ++i) {
    WriteEntry(f, *i->second);
  }

  fclose(f);
  if (unlink(path.c_str()) < 0) {
    *err = strerror(errno);
    return false;
  }

  if (rename(temp_path.c_str(), path.c_str()) < 0) {
    *err = strerror(errno);
    return false;
  }

  return true;
}
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
#define BTS_TEST_NETWORK

#define BTS_TEST_NETWORK_VERSION                            39

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                              109
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     151

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "XTS"
#define BTS_BLOCKCHAIN_SYMBOL                               "XTS"
#define BTS_BLOCKCHAIN_NAME                                 "BitShares XTS"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "BitShares X Test Network"
#define BTS_BLOCKCHAIN_PRECISION                            100000
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)
//#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 30 days * 24 hours * 60 minutes * 60 seconds = 1 month
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours for test network

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + BTS_BLOCKCHAIN_NUM_DELEGATES/10)
#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     (BTS_BLOCKCHAIN_NUM_DELEGATES*4)

#define BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES                false

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT                   1

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                             (1024*1024*1024*int64_t(100)) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      5 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters
#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE       1024 // bytes

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                       (BTS_BLOCKCHAIN_MAX_SHARES/5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE                     512 // just a random assumption used to calibrate TRX per SEC
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                       (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR                     10  // 10% per year

/**
    This constant defines the number of blocks a delegate must produce before
    they are expected to break even on registration costs with their earned income.

 *   Currently set to 2 hours of active block production to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE            (BTS_BLOCKCHAIN_BLOCKS_PER_DAY/12)

/**
    If you are going to create an asset, you expect that it will be used in transactions.  We would
    like to limit the issuance of assets that have no demand for transactions, so we charge a fee
    proportional to average transaction fees included in a block (AKA delegate pay).  This constant
    defines the number of blocks worth of transactions that justify the creation of a new asset.

    The fee is set such that the transactions of this asset alone could justify filling up 2 full weeks of
    block production.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE               (BTS_BLOCKCHAIN_BLOCKS_PER_DAY * 14)
<commit_msg>Bump chain db version<commit_after>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
#define BTS_TEST_NETWORK

#define BTS_TEST_NETWORK_VERSION                            39

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                              109
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     152

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "XTS"
#define BTS_BLOCKCHAIN_SYMBOL                               "XTS"
#define BTS_BLOCKCHAIN_NAME                                 "BitShares XTS"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "BitShares X Test Network"
#define BTS_BLOCKCHAIN_PRECISION                            100000
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)
//#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 30 days * 24 hours * 60 minutes * 60 seconds = 1 month
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours for test network

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + BTS_BLOCKCHAIN_NUM_DELEGATES/10)
#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     (BTS_BLOCKCHAIN_NUM_DELEGATES*4)

#define BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES                false

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT                   1

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                             (1024*1024*1024*int64_t(100)) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      5 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters
#define BTS_BLOCKCHAIN_PROPOSAL_VOTE_MESSAGE_MAX_SIZE       1024 // bytes

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                       (BTS_BLOCKCHAIN_MAX_SHARES/5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE                     512 // just a random assumption used to calibrate TRX per SEC
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                       (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

#define BTS_BLOCKCHAIN_INACTIVE_FEE_APR                     10  // 10% per year

/**
    This constant defines the number of blocks a delegate must produce before
    they are expected to break even on registration costs with their earned income.

 *   Currently set to 2 hours of active block production to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE            (BTS_BLOCKCHAIN_BLOCKS_PER_DAY/12)

/**
    If you are going to create an asset, you expect that it will be used in transactions.  We would
    like to limit the issuance of assets that have no demand for transactions, so we charge a fee
    proportional to average transaction fees included in a block (AKA delegate pay).  This constant
    defines the number of blocks worth of transactions that justify the creation of a new asset.

    The fee is set such that the transactions of this asset alone could justify filling up 2 full weeks of
    block production.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE               (BTS_BLOCKCHAIN_BLOCKS_PER_DAY * 14)
<|endoftext|>


<commit_before><commit_msg>Explicitly ignore unused return values #6992<commit_after><|endoftext|>