text:
#include "stdafx.h"

#include "NuiCompositeFrame.h"

#include "Shape\NuiCLMappableData.h"
#include "Shape\NuiMeshShape.h"
#include "OpenCLUtilities/NuiOpenCLGlobal.h"
#include "OpenCLUtilities/NuiOpenCLBufferFactory.h"
#include "OpenCLUtilities/NuiOpenCLUtil.h"

#include <boost/smart_ptr.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

namespace NuiFrameUtilities
{
	static const int	cDepthFps = 30;
	static const int	cHalfADepthFrameMs = (1000 / cDepthFps) * 2;

	bool FrameToCompoundImage (NuiCompositeFrame* pCompositeFrame)
	{
		assert(pCompositeFrame);
		if(!pCompositeFrame)
			return false;

		BGRQUAD* pColorBuffer = pCompositeFrame->m_colorFrame.GetBuffer();
		if(!pColorBuffer)
			return false;

		UINT16* pDepthBuffer = pCompositeFrame->m_depthFrame.GetBuffer();
		if(!pDepthBuffer)
			return false;

		if(std::abs(pCompositeFrame->m_depthFrame.GetTimeStamp() - pCompositeFrame->m_colorFrame.GetTimeStamp()) > cHalfADepthFrameMs)
			return false;

		UINT nDepthWidth = pCompositeFrame->m_depthFrame.GetWidth();
		UINT nDepthHeight = pCompositeFrame->m_depthFrame.GetHeight();
		UINT nDepthPointNum = nDepthWidth * nDepthHeight;

		UINT nColorWidth = pCompositeFrame->m_depthMapFrame.GetWidth();
		UINT nColorHeight = pCompositeFrame->m_depthMapFrame.GetHeight();
		UINT nColorPointNum = nColorWidth * nColorHeight;
		if(!nColorPointNum)
			return false;

	//	DepthSpacePoint* pColorToDepth = pCompositeFrame->m_depthMapFrame.GetBuffer();
	//	if (pColorToDepth)
	//	{
	//		BYTE* pBodyIndexBuffer = NULL;
	//		//assert((m_nBodyIndexWidth == m_nDepthWidth) && (m_nBodyIndexHeight == m_nDepthHeight));
	//		if(std::abs(pCompositeFrame->m_depthFrame.GetTimeStamp() - pCompositeFrame->m_bodyIndexFrame.GetTimeStamp()) < cHalfADepthFrameMs)
	//			pBodyIndexBuffer = pCompositeFrame->m_bodyIndexFrame.GetBuffer();

	//		NuiCompoundPixel* pCachedPixels = pCompositeFrame->m_compoundImageFrame.AllocatePixels(nColorWidth, nColorHeight);
	//		assert(pCachedPixels);
	//		pCompositeFrame->m_compoundImageFrame.WriteFrameLock();
	//		// loop over output pixels
	//#pragma omp parallel for schedule(dynamic)
	//		for (UINT colorIndex = 0; colorIndex < nColorPointNum; ++colorIndex)
	//		{
	//			NuiCompoundPixel* pPixel = pCachedPixels + colorIndex;
	//			if(!pPixel)
	//				continue;

	//			pPixel->fColor = pColorBuffer[colorIndex];

	//			const DepthSpacePoint& rPt = pColorToDepth[colorIndex];
	//			// Values that are negative infinity means it is an invalid depth to color mapping so we
	//			// skip processing for this pixel
	//			if (rPt.X != -std::numeric_limits<float>::infinity() && rPt.Y != -std::numeric_limits<float>::infinity())
	//			{
	//				int depthX = static_cast<int>(rPt.X + 0.5f);
	//				int depthY = static_cast<int>(rPt.Y + 0.5f);

	//				if ((depthX >= 0 && depthX < (int)nDepthWidth) && (depthY >= 0 && depthY < (int)nDepthHeight))
	//				{
	//					UINT depthIndex = depthX + depthY * nDepthWidth;
	//					pPixel->fDepth = pDepthBuffer[depthIndex];

	//					if(pBodyIndexBuffer)
	//					{
	//						pPixel->fBodyIndex = pBodyIndexBuffer[depthIndex];
	//					}
	//					else
	//					{
	//						pPixel->fBodyIndex = 0xff;
	//					}
	//				}
	//				else
	//				{
	//					pPixel->fDepth = 0;
	//					pPixel->fBodyIndex = 0xff;
	//				}
	//			}
	//		}
	//		pCompositeFrame->m_compoundImageFrame.WriteFrameUnlock();
	//	}

		return true;
	}

	bool FrameToPointCloud (NuiCompositeFrame* pCompositeFrame)
	{
		assert(pCompositeFrame);
		if(!pCompositeFrame)
			return false;

		UINT16* pDepthBuffer = pCompositeFrame->m_depthFrame.GetBuffer();
		if(!pDepthBuffer)
			return false;

		UINT nDepthWidth = pCompositeFrame->m_depthFrame.GetWidth();
		UINT nDepthHeight = pCompositeFrame->m_depthFrame.GetHeight();
		UINT nDepthPointNum = nDepthWidth * nDepthHeight;
		if(!nDepthPointNum)
			return false;

		CameraSpacePoint* pDepthToCamera = pCompositeFrame->m_cameraMapFrame.GetBuffer();
		if (pDepthToCamera)
		{
			UINT nColorWidth = pCompositeFrame->m_colorFrame.GetWidth();
			UINT nColorHeight = pCompositeFrame->m_colorFrame.GetHeight();
			UINT nColorPointNum = nColorWidth * nColorHeight;
			BGRQUAD* pColorBuffer = pCompositeFrame->m_colorFrame.GetBuffer();
			ColorSpacePoint* pDepthToColor = NULL;
			if(pColorBuffer && nColorPointNum > 0 /*&&
				(std::abs(m_depthFrameBuffer.GetTimeStamp() - m_colorFrameBuffer.GetTimeStamp()) < cHalfADepthFrameMs)*/)
			{
				pCompositeFrame->m_pointCloudFrame.SetColorImage(pCompositeFrame->m_colorFrame.GetImage());
				// map to color space
				ColorSpacePoint* pDepthToColor = pCompositeFrame->m_colorMapFrame.GetBuffer();
				if(!pDepthToColor)
					pColorBuffer = nullptr;
			}
			else
			{
				pColorBuffer = nullptr;
			}

			BYTE* pBodyIndexBuffer = nullptr;
			//assert((m_nBodyIndexWidth == m_nDepthWidth) && (m_nBodyIndexHeight == m_nDepthHeight));
			if(std::abs(pCompositeFrame->m_depthFrame.GetTimeStamp() - pCompositeFrame->m_bodyIndexFrame.GetTimeStamp()) < cHalfADepthFrameMs)
				pBodyIndexBuffer = pCompositeFrame->m_bodyIndexFrame.GetBuffer();

			UINT16 minZ = pCompositeFrame->m_depthFrame.GetMinDepth();
			UINT16 maxZ = pCompositeFrame->m_depthFrame.GetMaxDepth();

			NuiDevicePoint* pPoints = pCompositeFrame->m_pointCloudFrame.AllocatePoints(nDepthPointNum);
			pCompositeFrame->m_pointCloudFrame.SetWidthStep(nDepthWidth);
			assert(pPoints);
			pCompositeFrame->m_pointCloudFrame.WriteFrameLock();
			// loop over output pixels
	#pragma omp parallel for schedule(dynamic)
			for (UINT depthIndex = 0; depthIndex < nDepthPointNum; ++depthIndex)
			{
				NuiDevicePoint* pCachePt = pPoints + depthIndex;
				if(!pCachePt)
					continue;
				const CameraSpacePoint& rPt = pDepthToCamera[depthIndex];
				pCachePt->fIsValid = (rPt.Z > 0) && (pDepthBuffer[depthIndex] > minZ) && (pDepthBuffer[depthIndex] < maxZ);
				if(pCachePt->fIsValid)
				{
					pCachePt->fVertex.x = rPt.X;
					pCachePt->fVertex.y = rPt.Y;
					pCachePt->fVertex.z = rPt.Z;
				}
				else
				{
					pCachePt->fVertex.x = 0.0f;
					pCachePt->fVertex.y = 0.0f;
					pCachePt->fVertex.z = 0.0f;
				}
				bool bIsColorValid = false;
				if(pColorBuffer && pDepthToColor)
				{
					ColorSpacePoint p = pDepthToColor[depthIndex];
					// Values that are negative infinity means it is an invalid depth to color mapping so we
					// skip processing for this pixel
					if (p.X != -std::numeric_limits<float>::infinity() && p.Y != -std::numeric_limits<float>::infinity())
					{
						int colorX = static_cast<int>(p.X + 0.5f);
						int colorY = static_cast<int>(p.Y + 0.5f);

						if ((colorX >= 0 && colorX < (int)nColorWidth) && (colorY >= 0 && colorY < (int)nColorHeight))
						{
							bIsColorValid = true;
							pCachePt->fBGRA = pColorBuffer[colorX + (colorY * nColorWidth)];
							pCachePt->fColorSpaceU = (float)colorX / nColorWidth;
							pCachePt->fColorSpaceV = (float)colorY / nColorHeight;

							pCachePt->fNormal_x = 0.0f;
							pCachePt->fNormal_y = 0.0f;
							pCachePt->fNormal_z = -1.0f;
						}
					}
				}
				if(!bIsColorValid)
				{
					pCachePt->fBGRA.rgbBlue = 0;
					pCachePt->fBGRA.rgbGreen = 0;
					pCachePt->fBGRA.rgbRed = 0;
					pCachePt->fBGRA.rgbReserved = 0;
					pCachePt->fColorSpaceU = -1.0f;
					pCachePt->fColorSpaceV = -1.0f;
				}

				if(pBodyIndexBuffer)
				{
					pCachePt->fBodyIndex = pBodyIndexBuffer[depthIndex];
				}
				else
				{
					pCachePt->fBodyIndex = 0xff;
				}
			}
			pCompositeFrame->m_pointCloudFrame.WriteFrameUnlock();
		}
		else
		{
			std::cerr << "Error : Failed to acquire depth to camera mapping in frameToPointCloud." << std::endl;
		}

		return true;
	}

	bool	CameraSpacePointsToMappableData(NuiCompositeFrame* pCompositeFrame, NuiCLMappableData* pData)
	{
		if(!pData || !pCompositeFrame)
			return false;

		const UINT nFrameWidth = pCompositeFrame->m_cameraMapFrame.GetWidth();
		const UINT nFrameHeight = pCompositeFrame->m_cameraMapFrame.GetHeight();
		const UINT nFramePointsNum = nFrameWidth * nFrameHeight;
		CameraSpacePoint* pDepthToCamera = pCompositeFrame->m_cameraMapFrame.GetBuffer();
		if(!pDepthToCamera)
			return false;

		// OpenCL command queue and device
		cl_int           err = CL_SUCCESS;
		cl_command_queue queue = NuiOpenCLGlobal::instance().clQueue();

		if( nFramePointsNum != pData->PositionStream().size() )
		{
			NuiMappableAccessor::asVectorImpl(pData->PositionStream())->data().resize(nFramePointsNum);
		}

		cl_mem positionsGL = NuiOpenCLBufferFactory::asPosition3fBufferCL(pData->PositionStream());
		// Acquire OpenGL objects before use
		cl_mem glObjs[] = {
			positionsGL
		};

		openclutil::enqueueAcquireHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		clEnqueueWriteBuffer(
			queue,
			positionsGL,
			CL_TRUE,
			0,
			nFramePointsNum * sizeof(SgVec3f),
			pDepthToCamera,
			0,
			NULL,
			NULL
			);
		NUI_CHECK_CL_ERR(err);

		// Release OpenGL objects
		openclutil::enqueueReleaseHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		// Normals
		if (nFramePointsNum != pData->NormalStream().size())
		{
			std::vector<SgVec3f>& clNormals =
				NuiMappableAccessor::asVectorImpl(pData->NormalStream())->data();
			clNormals.resize(nFramePointsNum);
		}

		return true;
	}

	bool	ColorMapToMappableData(NuiCompositeFrame* pCompositeFrame, NuiCLMappableData* pData)
	{
		if(!pData || !pCompositeFrame)
			return false;

		// Patch UV
		const UINT nColorMapWidth = pCompositeFrame->m_colorMapFrame.GetWidth();
		const UINT nColorMapHeight = pCompositeFrame->m_colorMapFrame.GetHeight();
		const UINT nColorMapNum = nColorMapWidth * nColorMapHeight;
		ColorSpacePoint* pDepthToColor = pCompositeFrame->m_colorMapFrame.GetBuffer();
		if(!pDepthToColor)
			return false;

		// OpenCL command queue and device
		cl_int           err = CL_SUCCESS;
		cl_command_queue queue = NuiOpenCLGlobal::instance().clQueue();

		if( nColorMapNum != pData->PatchUVStream().size() )
		{
			NuiMappableAccessor::asVectorImpl(pData->PatchUVStream())->data().resize(nColorMapNum);
		}

		cl_mem uvsGL = NuiOpenCLBufferFactory::asPatch2fBufferCL(pData->PatchUVStream());
		// Acquire OpenGL objects before use
		cl_mem glObjs[] = {
			uvsGL
		};

		openclutil::enqueueAcquireHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		clEnqueueWriteBuffer(
			queue,
			uvsGL,
			CL_TRUE,
			0,
			nColorMapNum * sizeof(SgVec2f),
			pDepthToColor,
			0,
			NULL,
			NULL
			);
		NUI_CHECK_CL_ERR(err);

		// Release OpenGL objects
		openclutil::enqueueReleaseHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		// Colors
		NuiMappableAccessor::asVectorImpl(pData->ColorStream())->data().clear();

		return true;
	}

	bool	ColorTexToMappableData(NuiCompositeFrame* pCompositeFrame, NuiCLMappableData* pData)
	{
		if (!pData || !pCompositeFrame)
			return false;

		// For color texture
		//if(std::abs(m_depthFrame.GetTimeStamp() - m_colorFrame.GetTimeStamp()) < cHalfADepthFrameMs)
		{
			pCompositeFrame->m_colorFrame.ReadFrameLock();
			NuiTextureMappableAccessor::updateImpl(
				pData->ColorTex(),
				pCompositeFrame->m_colorFrame.GetWidth(),
				pCompositeFrame->m_colorFrame.GetHeight(),
				pCompositeFrame->m_colorFrame.GetBuffer()
			);
			pCompositeFrame->m_colorFrame.ReadFrameUnlock();
		}
		return true;
	}

	bool	ColorToMappableData(NuiCompositeFrame* pCompositeFrame, NuiCLMappableData* pData)
	{
		if (!pData || !pCompositeFrame)
			return false;

		// Patch color
		const UINT nColorWidth = pCompositeFrame->m_colorFrame.GetWidth();
		const UINT nColorHeight = pCompositeFrame->m_colorFrame.GetHeight();
		const UINT nColorNum = nColorWidth * nColorHeight;
		BGRQUAD* pColors = pCompositeFrame->m_colorFrame.GetBuffer();
		if (!pColors)
			return false;

		if (nColorNum != pData->ColorStream().size())
		{
			NuiMappableAccessor::asVectorImpl(pData->ColorStream())->data().resize(nColorNum);
		}

		std::vector<SgVec4f>& clColors =
			NuiMappableAccessor::asVectorImpl(pData->ColorStream())->data();

#ifdef WITH_OPENMP
#pragma omp parallel for
#endif
		for (UINT id = 0; id < nColorNum; id++)
		{
			clColors[id] = SgVec4f(pColors[id].rgbRed / 255.0f, pColors[id].rgbGreen / 255.0f, pColors[id].rgbBlue / 255.0f, 1.0f);
		}

		// OpenCL command queue and device
		cl_int           err = CL_SUCCESS;
		cl_command_queue queue = NuiOpenCLGlobal::instance().clQueue();

		cl_mem colorsGL = NuiOpenCLBufferFactory::asColor4fBufferCL(pData->ColorStream());
		// Acquire OpenGL objects before use
		cl_mem glObjs[] = {
			colorsGL
		};

		openclutil::enqueueAcquireHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		clEnqueueWriteBuffer(
			queue,
			colorsGL,
			CL_TRUE,
			0,
			nColorNum * sizeof(SgVec4f),
			NuiMappableAccessor::asVectorImpl(pData->ColorStream())->map(),
			0,
			NULL,
			NULL
		);
		NUI_CHECK_CL_ERR(err);

		// Release OpenGL objects
		openclutil::enqueueReleaseHWObjects(
			sizeof(glObjs) / sizeof(cl_mem), glObjs, 0, nullptr, nullptr);

		return true;
	}

	bool	FrameToMappableData(NuiCompositeFrame* pCompositeFrame, NuiCLMappableData* pData, int indexFlags, bool bOnlyShowBody, float depthThreshold)
	{
		if(!pData || !pCompositeFrame)
			return false;

		const UINT16 minZ = pCompositeFrame->m_depthFrame.GetMinDepth();
		const UINT16 maxZ = pCompositeFrame->m_depthFrame.GetMaxDepth();
		UINT16* pDepthBuffer = pCompositeFrame->m_depthFrame.GetBuffer();
		UINT nWidth = pCompositeFrame->m_cameraMapFrame.GetWidth();
		UINT nHeight = pCompositeFrame->m_cameraMapFrame.GetHeight();
		CameraSpacePoint* pDepthToCamera = pCompositeFrame->m_cameraMapFrame.GetBuffer();

		if (!pDepthToCamera)
		{
			if(!pDepthBuffer)
				return false;

			nWidth = pCompositeFrame->m_depthFrame.GetWidth();
			nHeight = pCompositeFrame->m_depthFrame.GetHeight();

			pDepthToCamera = pCompositeFrame->m_cameraMapFrame.AllocateBuffer(nWidth, nHeight);
			NuiCameraIntrinsics cameraIntrics = pCompositeFrame->m_cameraParams.m_intrinsics;
#ifdef WITH_OPENMP
#pragma omp parallel for
#endif
			for (UINT y = 0; y < nHeight; y++)
			{
				for (UINT x = 0; x < nWidth; x++)
				{
					const UINT id = y * nWidth + x;

					if ((pDepthBuffer[id] > minZ) && (pDepthBuffer[id] < maxZ))
					{

						float dp = pDepthBuffer[id] * 0.001f;
						const float intr_fx_inv = 1 / cameraIntrics.m_fx;
						const float intr_fy_inv = 1 / cameraIntrics.m_fy;
						const float intr_cx = cameraIntrics.m_cx;
						const float intr_cy = cameraIntrics.m_cy;
						pDepthToCamera[id].X = - dp * ((float)x - intr_cx) * intr_fx_inv;
						pDepthToCamera[id].Y = - dp * ((float)y - intr_cy) * intr_fy_inv;
						pDepthToCamera[id].Z = dp;
					}
					else
					{
						pDepthToCamera[id] = { NAN_FLOAT, NAN_FLOAT, NAN_FLOAT };
					}
				}
			}
		}

		if (!CameraSpacePointsToMappableData(pCompositeFrame, pData))
		{
			return false;
		}
		// For color texture
		if (!ColorTexToMappableData(pCompositeFrame, pData) || !ColorMapToMappableData(pCompositeFrame, pData))
		{
			if (!ColorToMappableData(pCompositeFrame, pData))
				return false;
		}

		pData->SetStreamDirty(true);

		// Camera
		pData->SetCameraParams( pCompositeFrame->m_cameraParams );

		// Write Index data
		BYTE* pBodyIndexBuffer = pCompositeFrame->m_bodyIndexFrame.GetBuffer();

		std::vector<unsigned int>& pointIndices =
			NuiMappableAccessor::asVectorImpl(pData->PointIndices())->data();
		pointIndices.clear();

		std::vector<unsigned int>& triangleIndices =
			NuiMappableAccessor::asVectorImpl(pData->TriangleIndices())->data();
		triangleIndices.clear();

		std::vector<unsigned int>& wireframeIndices =
			NuiMappableAccessor::asVectorImpl(pData->WireframeIndices())->data();
		wireframeIndices.clear();

		const bool bNeedPointIndex = (indexFlags & NuiCLMappableData::E_MappableData_Point) ? true : false;
		const bool bNeedTriangleIndex = (indexFlags & NuiCLMappableData::E_MappableData_Triangle) ? true : false;
		const bool bNeedWireframeIndex = (indexFlags & NuiCLMappableData::E_MappableData_Wireframe) ? true : false;

		SgVec3f boundingBoxMin( std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() );
		SgVec3f boundingBoxMax( -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max(), -std::numeric_limits<float>::max() );

#pragma omp parallel for schedule(dynamic)
		for (UINT h = 0; h < nHeight; ++h)
		{
			for (UINT w = 0; w < nWidth; ++w)
			{
				UINT idx1 = w + h * nWidth;

				float rPtZ1 = pDepthToCamera[idx1].Z;
				bool bIsIdx1Valid = (rPtZ1 > 0.0f) && pDepthBuffer && (pDepthBuffer[idx1] > minZ) && (pDepthBuffer[idx1] < maxZ);

				if(!bIsIdx1Valid)
					continue;

				if(pBodyIndexBuffer && bOnlyShowBody && (0xff == pBodyIndexBuffer[idx1]))
					continue;

				// compute bounding box
				if ( pDepthToCamera[idx1].X < boundingBoxMin[0] ) boundingBoxMin[0] = pDepthToCamera[idx1].X;
				if ( pDepthToCamera[idx1].Y < boundingBoxMin[1] ) boundingBoxMin[1] = pDepthToCamera[idx1].Y;
				if ( pDepthToCamera[idx1].Z < boundingBoxMin[2] ) boundingBoxMin[2] = pDepthToCamera[idx1].Z;
				if ( pDepthToCamera[idx1].X > boundingBoxMax[0] ) boundingBoxMax[0] = pDepthToCamera[idx1].X;
				if ( pDepthToCamera[idx1].Y > boundingBoxMax[1] ) boundingBoxMax[1] = pDepthToCamera[idx1].Y;
				if ( pDepthToCamera[idx1].Z > boundingBoxMax[2] ) boundingBoxMax[2] = pDepthToCamera[idx1].Z;

				if(bNeedPointIndex)
				{
					pointIndices.push_back(idx1);
				}

				if(bNeedTriangleIndex || bNeedWireframeIndex)
				{
					if(w == (nWidth-1) || h == (nHeight-1))
						continue;

					UINT idx2 = w + 1 + h * nWidth;
					UINT idx3 = w + (h + 1) * nWidth;
					UINT idx4 = w + 1 + (h + 1) * nWidth;

					float rPtZ2 = pDepthToCamera[idx2].Z;
					bool bIsIdx2Valid = (rPtZ2 > 0)&& pDepthBuffer  && (pDepthBuffer[idx2] > minZ) && (pDepthBuffer[idx2] < maxZ);
					if(!bIsIdx2Valid)
						continue;
					if(pBodyIndexBuffer && bOnlyShowBody && (0xff == pBodyIndexBuffer[idx2]))
						continue;

					float rPtZ3 = pDepthToCamera[idx3].Z;
					bool bIsIdx3Valid = (rPtZ3 > 0) && pDepthBuffer && (pDepthBuffer[idx3] > minZ) && (pDepthBuffer[idx3] < maxZ);
					if(!bIsIdx3Valid)
						continue;
					if(pBodyIndexBuffer && bOnlyShowBody && (0xff == pBodyIndexBuffer[idx3]))
						continue;

					// Build the upper triangle
					if (abs(rPtZ1 - rPtZ2) < depthThreshold &&
						abs(rPtZ1 - rPtZ3) < depthThreshold &&
						abs(rPtZ2 - rPtZ3) < depthThreshold)
					{
						if(bNeedTriangleIndex)
						{
							triangleIndices.push_back(idx1);
							triangleIndices.push_back(idx2);
							triangleIndices.push_back(idx3);
						}

						if(bNeedWireframeIndex)
						{
							wireframeIndices.push_back(idx1);
							wireframeIndices.push_back(idx2);
							wireframeIndices.push_back(idx2);
							wireframeIndices.push_back(idx3);
							wireframeIndices.push_back(idx3);
							wireframeIndices.push_back(idx1);
						}
					}

					float rPtZ4 = pDepthToCamera[idx4].Z;
					bool bIsIdx4Valid = (rPtZ4 > 0) && pDepthBuffer && (pDepthBuffer[idx4] > minZ) && (pDepthBuffer[idx4] < maxZ);
					if(!bIsIdx4Valid)
						continue;
					if(pBodyIndexBuffer && bOnlyShowBody && (0xff == pBodyIndexBuffer[idx4]))
						continue;

					// Build the down triangle
					if (abs(rPtZ4 - rPtZ2) < depthThreshold &&
						abs(rPtZ4 - rPtZ3) < depthThreshold &&
						abs(rPtZ2 - rPtZ3) < depthThreshold)
					{
						if(bNeedTriangleIndex)
						{
							triangleIndices.push_back(idx3);
							triangleIndices.push_back(idx2);
							triangleIndices.push_back(idx4);
						}

						if(bNeedWireframeIndex)
						{
							wireframeIndices.push_back(idx3);
							wireframeIndices.push_back(idx2);
							wireframeIndices.push_back(idx2);
							wireframeIndices.push_back(idx4);
							wireframeIndices.push_back(idx4);
							wireframeIndices.push_back(idx3);
						}
					}
				}
			}
		}
		pData->SetBoundingBox(boundingBoxMin, boundingBoxMax);
		pData->SetIndexingDirty(true);

		return true;
	}

	bool	FrameToMesh(NuiCompositeFrame* pCompositeFrame, NuiMeshShape* pMesh, bool bOnlyShowBody, float depthThreshold)
	{
		if(!pMesh || !pCompositeFrame)
			return false;

		const UINT nFrameWidth = pCompositeFrame->m_cameraMapFrame.GetWidth();
		const UINT nFrameHeight = pCompositeFrame->m_cameraMapFrame.GetHeight();
		const UINT nFramePointsNum = nFrameWidth * nFrameHeight;
		CameraSpacePoint* pDepthToCamera = pCompositeFrame->m_cameraMapFrame.GetBuffer();
		if(!pDepthToCamera)
			return false;

		boost::scoped_array<SgVec3f> points(new SgVec3f[nFramePointsNum]);
		pCompositeFrame->m_cameraMapFrame.ReadFrameLock();
		errno_t err = memcpy_s(points.get(), sizeof(SgVec3f)*nFramePointsNum, pDepthToCamera, sizeof(CameraSpacePoint)*nFramePointsNum);
		pCompositeFrame->m_cameraMapFrame.ReadFrameUnlock();
		if(0 != err)
		{
			std::cerr << "Error : Failed to copy the position buffer in frameToMesh." << std::endl;
			return false;
		}

		// Save color texture
		const UINT nColorWidth = pCompositeFrame->m_colorFrame.GetWidth();
		const UINT nColorHeight = pCompositeFrame->m_colorFrame.GetHeight();
		IplImage*	pTextureImg = cvCreateImage(cvSize(nColorWidth,nColorHeight),IPL_DEPTH_32F ,3);
		pCompositeFrame->m_colorFrame.ReadFrameLock();
		BGRQUAD* pColors = pCompositeFrame->m_colorFrame.GetBuffer();
		if(pColors)
		{
			for (UINT y = 0; y < nColorHeight; y ++)
			{
				for (UINT x = 0; x < nColorWidth; x ++)
				{
					UINT index = x + y * nColorWidth;
					BGRQUAD* pValue = pColors + index;
					CvScalar color = CvScalar(pValue->rgbGreen, pValue->rgbBlue, pValue->rgbRed);
					cvSet2D(pTextureImg, y, x, color);
				}
			}
		}
		pCompositeFrame->m_colorFrame.ReadFrameUnlock();
		std::string textureImagePath = NuiOpenCLGlobal::instance().tmpDir() + "NuiMeshTexture.jpg";
		//cvSaveImage(NuiOpenCLGlobal::instance().tmpDir().c_str(), pTextureImg);
		cvSaveImage(textureImagePath.c_str(), pTextureImg);
		cvReleaseImage(&pTextureImg);

		// Patch UV
		boost::scoped_array<SgVec2f> uvs(NULL);
		const UINT nColorMapWidth = pCompositeFrame->m_colorMapFrame.GetWidth();
		const UINT nColorMapHeight = pCompositeFrame->m_colorMapFrame.GetHeight();
		const UINT nColorMapNum = nColorMapWidth * nColorMapHeight;
		ColorSpacePoint* pDepthToColor = pCompositeFrame->m_colorMapFrame.GetBuffer();
		if(pDepthToColor)
		{
			uvs.reset(new SgVec2f[nColorMapNum]);
			pCompositeFrame->m_colorMapFrame.ReadFrameLock();
			errno_t err = memcpy_s(uvs.get(), sizeof(SgVec2f)*nColorMapNum, pDepthToColor, sizeof(ColorSpacePoint)*nColorMapNum);
			pCompositeFrame->m_colorMapFrame.ReadFrameUnlock();
			if(0 != err)
			{
				std::cerr << "Error : Failed to copy the uv buffer in frameToMesh." << std::endl;
			}
		}
		else
		{
			std::cerr << "Error : Failed to acquire color to camera mapping in frameToMesh." << std::endl;
		}

		// Depth
		boost::scoped_array<UINT16> depths(NULL);
		UINT16* pDepthBuffer = pCompositeFrame->m_depthFrame.GetBuffer();
		if(pDepthBuffer)
		{
			depths.reset(new UINT16[nFramePointsNum]);
			pCompositeFrame->m_depthFrame.ReadFrameLock();
			errno_t err = memcpy_s(depths.get(), sizeof(UINT16)*nFramePointsNum, pDepthBuffer, sizeof(UINT16)*nFramePointsNum);
			pCompositeFrame->m_depthFrame.ReadFrameUnlock();
			if(0 != err)
			{
				std::cerr << "Error : Failed to copy the depth buffer in frameToMesh." << std::endl;
			}
		}

		// Body index
		boost::scoped_array<BYTE> bodyIndices(NULL);
		BYTE* pBodyIndexBuffer = pCompositeFrame->m_bodyIndexFrame.GetBuffer();
		if(pBodyIndexBuffer)
		{
			bodyIndices.reset(new BYTE[nFramePointsNum]);
			pCompositeFrame->m_bodyIndexFrame.ReadFrameLock();
			errno_t err = memcpy_s(bodyIndices.get(), sizeof(BYTE)*nFramePointsNum, pBodyIndexBuffer, sizeof(BYTE)*nFramePointsNum);
			pCompositeFrame->m_bodyIndexFrame.ReadFrameUnlock();
			if(0 != err)
			{
				std::cerr << "Error : Failed to copy the body index buffer in frameToMesh." << std::endl;
			}
		}

		const UINT16 minZ = pCompositeFrame->m_depthFrame.GetMinDepth();
		const UINT16 maxZ = pCompositeFrame->m_depthFrame.GetMaxDepth();

		std::map<UINT, int> indexMap;
		int nVertexIndex = 0;
		for (UINT h = 0; h < (nFrameHeight - 1); ++h)
		{
			for (UINT w = 0; w < (nFrameWidth - 1); ++w)
			{
				UINT idx1 = w + h * nFrameWidth;
				UINT idx2 = w + 1 + h * nFrameWidth;
				UINT idx3 = w + (h + 1) * nFrameWidth;
				UINT idx4 = w + 1 + (h + 1) * nFrameWidth;

				float rPtZ2 = points[idx2][2];
				bool bIsIdx2Valid = (rPtZ2 > 0.0f)&& depths  && (depths[idx2] > minZ) && (depths[idx2] < maxZ);
				if(!bIsIdx2Valid)
					continue;
				if(bodyIndices && bOnlyShowBody && (0xff == bodyIndices[idx2]))
					continue;

				float rPtZ3 = points[idx3][2];
				bool bIsIdx3Valid = (rPtZ3 > 0.0f) && depths && (depths[idx3] > minZ) && (depths[idx3] < maxZ);
				if(!bIsIdx3Valid)
					continue;
				if(bodyIndices && bOnlyShowBody && (0xff == bodyIndices[idx3]))
					continue;

				float rPtZ1 = points[idx1][2];
				bool bIsIdx1Valid = (rPtZ1 > 0.0f) && depths && (depths[idx1] > minZ) && (depths[idx1] < maxZ);
				bool bBodyMask = bodyIndices && bOnlyShowBody && (0xff == bodyIndices[idx1]);
				if(bIsIdx1Valid && !bBodyMask)
				{
					// Build the upper triangle
					if (abs(rPtZ1 - rPtZ2) < depthThreshold &&
						abs(rPtZ1 - rPtZ3) < depthThreshold &&
						abs(rPtZ2 - rPtZ3) < depthThreshold)
					{
						// The first vertex
						std::map<UINT, int>::iterator itr = indexMap.find(idx1);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx1][0] + 0.5f, uvs[idx1][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx1;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx1], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx1, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
						// The second vertex
						itr = indexMap.find(idx2);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx2][0] + 0.5f, uvs[idx2][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx2;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx2], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx2, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
						// The third vertex
						itr = indexMap.find(idx3);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx3][0] + 0.5f, uvs[idx3][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx3;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx3], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx3, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
					}
				}

				float rPtZ4 = points[idx4][2];
				bool bIsIdx4Valid = (rPtZ4 > 0) && depths && (depths[idx4] > minZ) && (depths[idx4] < maxZ);
				bBodyMask = bodyIndices && bOnlyShowBody && (0xff == bodyIndices[idx4]);
				if(bIsIdx4Valid && !bBodyMask)
				{
					// Build the down triangle
					if (abs(rPtZ4 - rPtZ2) < depthThreshold &&
						abs(rPtZ4 - rPtZ3) < depthThreshold &&
						abs(rPtZ2 - rPtZ3) < depthThreshold)
					{
						// The second vertex
						std::map<UINT, int>::iterator itr = indexMap.find(idx2);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx2][0] + 0.5f, uvs[idx2][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx2;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx2], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx2, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
						// The forth vertex
						itr = indexMap.find(idx4);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx4][0] + 0.5f, uvs[idx4][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx4;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx4], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx4, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
						// The third vertex
						itr = indexMap.find(idx3);
						if(itr == indexMap.end())
						{
							SgVec3f color(0.0f, 0.0f, 0.0f);
							SgVec2f uv(uvs[idx3][0] + 0.5f, uvs[idx3][1] + 0.5f);
							if(uv[0] >= 0.0f && uv[0] <= nColorWidth && uv[1] >= 0.0f && uv[1] <= nColorHeight)
							{
								if(pColors)
								{
									BGRQUAD* rgb = pColors + idx3;
									color.setValue((float)(rgb->rgbRed)/255.0f, (float)(rgb->rgbGreen)/255.0f, (float)(rgb->rgbBlue)/255.0f);
								}
								uv.setValue(uv[0]/nColorWidth, 1.0f - uv[1]/nColorHeight);
							}
							else
								uv.setValue(0.0f, 0.0f);
							pMesh->appendPoint(points[idx3], uv, color);
							pMesh->appendTriangleIndex(nVertexIndex);

							indexMap.insert(std::pair<UINT, int>(idx3, nVertexIndex));
							nVertexIndex ++ ;
						}
						else
						{
							pMesh->appendTriangleIndex(itr->second);
						}
					}
				}
			}
		}

		return true;
	}
}

max_stars_repo_name: hustztz/NatureUserInterfaceStudio

max_issues_repo_name: hustztz/NatureUserInterfaceStudio

max_forks_repo_name: hustztz/NatureUserInterfaceStudio


text:
//  Copyright (c) 2007-2014 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_BASE_LCO_FACTORY_OCT_10_2013_1118AM)
#define HPX_BASE_LCO_FACTORY_OCT_10_2013_1118AM

#include <hpx/config.hpp>
#include <hpx/hpx_fwd.hpp>

#include <hpx/runtime/components/unique_component_name.hpp>
#include <hpx/runtime/components/component_factory_base.hpp>
#include <hpx/runtime/components/server/create_component.hpp>
#include <hpx/runtime/components/server/destroy_component.hpp>
#include <hpx/runtime/naming/resolver_client.hpp>
#include <hpx/util/ini.hpp>
#include <hpx/util/one_size_heap_list_base.hpp>
#include <hpx/util/detail/count_num_args.hpp>

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/detail/atomic_count.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace components
{
    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        HPX_EXPORT util::one_size_heap_list_base* create_promise_heap(
            components::component_type type);
    }

    ///////////////////////////////////////////////////////////////////////////
    /// The \a base_lco_factory provides a special implementation of a
    /// component factory for components exposing the base_lco interface.
    ///
    struct base_lco_factory : public component_factory_base
    {
        /// \brief Construct a new factory instance
        ///
        /// \note The contents of both sections has to be cloned in order to
        ///       save the configuration setting for later use.
        base_lco_factory(component_type type)
          : type_(type), heap_(detail::create_promise_heap(type))
        {}

        ///
        ~base_lco_factory() {}

        /// \brief Return the unique identifier of the component type this
        ///        factory is responsible for
        ///
        /// \param locality     [in] The id of the locality this factory
        ///                     is responsible for.
        /// \param agas_client  [in] The AGAS client to use for component id
        ///                     registration (if needed).
        ///
        /// \return Returns the unique identifier of the component type this
        ///         factory instance is responsible for. This function throws
        ///         on any error.
        component_type get_component_type(naming::gid_type const& locality,
            naming::resolver_client& agas_client)
        {
            return type_;
        }

        /// \brief Return the name of the component type this factory is
        ///        responsible for
        ///
        /// \return Returns the name of the component type this factory
        ///         instance is responsible for. This function throws on any
        ///         error.
        std::string get_component_name() const
        {
            return std::string("base_lco_factory for ") +
                get_component_type_name(type_);
        }

        /// \brief  The function \a get_factory_properties is used to
        ///         determine, whether instances of the derived component can
        ///         be created in blocks (i.e. more than one instance at once).
        ///         This function is used by the \a distributing_factory to
        ///         determine a correct allocation strategy
        factory_property get_factory_properties() const
        {
            return factory_none;
        }

        /// \brief Create one or more new component instances.
        ///
        /// \param count  [in] The number of component instances to
        ///               create. The value of this parameter should not
        ///               be zero.
        ///
        /// \return Returns the GID of the first newly created component
        ///         instance. If more than one component instance has been
        ///         created (\a count > 1) the GID's of all new instances are
        ///         sequential in a row.
        naming::gid_type create(std::size_t = 1)
        {
            HPX_THROW_EXCEPTION(bad_request,
                "base_lco_factory::create",
                "this function should be never called");
            return naming::invalid_gid;
        }

        /// \brief Create one new component instance and initialize it using
        ///        the using the given constructor function.
        ///
        /// \param f  [in] The constructor function to call in order to
        ///           initialize the newly allocated object.
        ///
        /// \return   Returns the GID of the first newly created component
        ///           instance.
        naming::gid_type create_with_args(HPX_STD_FUNCTION<void(void*)> const&)
        {
            HPX_THROW_EXCEPTION(bad_request,
                "base_lco_factory::create_with_args",
                "this function should be never called");
            return naming::invalid_gid;
        }

        /// \brief Create one new component instance and initialize it using
        ///        the using the given constructor function. Assign the give
        ///        GID to the new object.
        ///
        /// \param assign_gid [in] The GID to assign to the newly created object.
        /// \param f  [in] The constructor function to call in order to
        ///           initialize the newly allocated object.
        ///
        /// \return   Returns the GID of the first newly created component
        ///           instance (this is the same as assign_gid, if successful).
        naming::gid_type create_with_args(
            naming::gid_type const& assign_gid,
            HPX_STD_FUNCTION<void(void*)> const& f)
        {
            HPX_THROW_EXCEPTION(bad_request,
                "base_lco_factory::create_with_args",
                "this function should be never called");
            return naming::invalid_gid;
        }

    public:
        /// \brief Destroy one or more component instances
        ///
        /// \param gid    [in] The gid of the first component instance to
        ///               destroy.
        /// \param addr   [in] The resolved address of the first component
        ///               instance to destroy.
        void destroy(naming::gid_type const& gid,
            naming::address const& addr)
        {
            server::destroy_base_lco(gid, addr, heap_.get(), type_);
        }

        /// \brief Ask how many instances are alive of the type this factory is
        ///        responsible for
        ///
        /// \return Returns the number of instances of the managed object type
        ///         which are currently alive.
        long instance_count() const
        {
            return 0;
        }

#if defined(HPX_HAVE_SECURITY)
        /// \brief Return the required capabilities necessary to create an
        ///        instance of a component using this factory instance.
        ///
        /// \return Returns required capabilities necessary to create a new
        ///         instance of a component using this factory instance.
        components::security::capability get_required_capabilities() const
        {
            using namespace components::security;
            return traits::capability<>::capability_create_component;
        }
#endif

        boost::shared_ptr<util::one_size_heap_list_base> get_heap() const
        {
            return heap_;
        }

    protected:
        component_type type_;
        boost::shared_ptr<util::one_size_heap_list_base> heap_;
    };
}}

#endif

ext: hpp


text:
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/**
 * implementation for C++ XML generation class
 *
 * The software provided here is released by the Naval Postgraduate
 * School, an agency of the U.S. Department of Navy.  The software
 * bears no warranty, either expressed or implied. NPS does not assume
 * legal liability nor responsibility for a User's use of the software
 * or the results of such use.
 *
 * Please note that within the United States, copyright protection,
 * under Section 105 of the United States Code, Title 17, is not
 * available for any work of the United States Government and/or for
 * any works created by United States Government employees. User
 * acknowledges that this software contains work which was created by
 * NPS government employees and is therefore in the public domain and
 * not subject to copyright.
 */

#include "config.h"

#ifdef HAVE_WINSOCK2_H
#include <winsock2.h>
#endif

#include <errno.h>
#include <unistd.h>

#ifdef HAVE_SQLITE3_H
#include <sqlite3.h>
#endif

#ifdef HAVE_BOOST_VERSION_HPP
#include <boost/version.hpp>
#endif

#ifdef HAVE_PTHREAD
#define MUTEX_INIT(M)   pthread_mutex_init(M,NULL);
#define MUTEX_LOCK(M)   pthread_mutex_lock(M)
#define MUTEX_UNLOCK(M) pthread_mutex_unlock(M)
#else
#define MUTEX_INIT(M)   {}
#define MUTEX_LOCK(M)   {}
#define MUTEX_UNLOCK(M) {}
#endif

#ifdef HAVE_TRE_TRE_H
#include <tre/tre.h>
#endif

#include <iostream>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#include <assert.h>
#include <fcntl.h>
#include <stack>

#include <iostream>
#include <streambuf>

#ifdef _MSC_VER
# include <io.h>
#else
# include <unistd.h>
#endif

using namespace std;

#include "dfxml_writer.h"

static const char *xml_header = "<?xml version='1.0' encoding='UTF-8'?>\n";

// Implementation of mkstemp for windows found on pan-devel mailing
// list archive
// @http://www.mail-archive.com/pan-devel@nongnu.org/msg00294.html
#ifndef _S_IREAD
#define _S_IREAD 256
#endif

#ifndef _S_IWRITE
#define _S_IWRITE 128
#endif

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef _O_SHORT_LIVED
#define _O_SHORT_LIVED 0
#endif

#ifndef HAVE_MKSTEMP
int mkstemp(char *tmpl)
{
   int ret=-1;
   mktemp(tmpl);
   ret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE);
   return ret;
}
#endif

#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifndef _O_SHORT_LIVED
#define _O_SHORT_LIVED 0
#endif

//std::string dfxml_writer::xml_PRId32("%" PRId32); // gets around compiler bug
//std::string dfxml_writer::xml_PRIu32("%" PRIu32); // gets around compiler bug
//std::string dfxml_writer::xml_PRId64("%" PRId64); // gets around compiler bug
//std::string dfxml_writer::xml_PRIu64("%" PRIu64); // gets around compiler bug

static const char *cstr(const string &str){
    return str.c_str();
}

// XML escapes
static string xml_lt("<");
static string xml_gt(">");
static string xml_am("&");
static string xml_ap("'");
static string xml_qu(""");

// % encodings
static string encoding_null("%00");
static string encoding_r("%0D");
static string encoding_n("%0A");
static string encoding_t("%09");

std::string dfxml_writer::xmlescape(const string &xml)
{
    string ret;
    for(string::const_iterator i = xml.begin(); i!=xml.end(); i++){
        switch(*i){
        // XML escapes
        case '>':  ret += xml_gt; break;
        case '<':  ret += xml_lt; break;
        case '&':  ret += xml_am; break;
        case '\'': ret += xml_ap; break;
        case '"':  ret += xml_qu; break;

        // % encodings
        case '\000':  ret += encoding_null; break;      // retain encoded nulls
        case '\r':  ret += encoding_r; break;
        case '\n':  ret += encoding_n; break;
        case '\t':  ret += encoding_t; break;
        default:
            ret += *i;
        }
    }
    return ret;
}

/**
 * Strip an XML string as necessary for a tag name.
 */

std::string dfxml_writer::xmlstrip(const string &xml)
{
    string ret;
    for(string::const_iterator i = xml.begin(); i!=xml.end(); i++){
        if(isprint(*i) && !strchr("<>\r\n&'\"",*i)){
            ret += isspace(*i) ? '_' : tolower(*i);
        }
    }
    return ret;
}

/**
 * xmlmap:
 * Turns a map into a blob of XML.
 */

std::string dfxml_writer::xmlmap(const dfxml_writer::strstrmap_t &m,const std::string &outer,const std::string &attrs)
{
    std::stringstream ss;
    ss << "<" << outer;
    if(attrs.size()>0) ss << " " << attrs;
    ss << ">";
    for(std::map<std::string,std::string>::const_iterator it=m.begin();it!=m.end();it++){
        ss << "<" << (*it).first  << ">" << xmlescape((*it).second) << "</" << (*it).first << ">";
    }
    ss << "</" << outer << ">";
    return ss.str();
}

/* This goes to stdout */
dfxml_writer::dfxml_writer():M(),outf(),out(&cout),tags(),tag_stack(),tempfilename(),tempfile_template("/tmp/xml_XXXXXXXX"),
           t0(),t_last_timestamp(),make_dtd(false),outfilename(),oneline()
{
#ifdef HAVE_PTHREAD
    pthread_mutex_init(&M,NULL);
#endif
    gettimeofday(&t0,0);
    gettimeofday(&t_last_timestamp,0);
    *out << xml_header;
}

/* This should be rewritten so that the temp file is done on close, not on open */
dfxml_writer::dfxml_writer(const std::string &outfilename_,bool makeDTD):
    M(),outf(outfilename_.c_str(),ios_base::out),
    out(),tags(),tag_stack(),tempfilename(),tempfile_template(outfilename_+"_tmp_XXXXXXXX"),
    t0(),t_last_timestamp(),make_dtd(false),outfilename(outfilename_),oneline()
{
    MUTEX_INIT(&M);
    gettimeofday(&t0,0);
    gettimeofday(&t_last_timestamp,0);
    if(!outf.is_open()){
        perror(outfilename_.c_str());
        exit(1);
    }
    out = &outf;                                                // use this one instead
    *out << xml_header;
}

void dfxml_writer::set_tempfile_template(const std::string &temp)
{
    tempfile_template = temp;
}

void dfxml_writer::close()
{
    MUTEX_LOCK(&M);
    outf.close();
    if(make_dtd){
        /* If we are making the DTD, then we should close the file,
         * scan the output file for the tags, write to a temp file, and then
         * close the temp file and have it overwrite the outfile.
         */

        std::ifstream in(cstr(tempfilename));
        if(!in.is_open()){
            cerr << tempfilename << strerror(errno) << ":Cannot re-open for input\n";
            exit(1);
        }
        outf.open(cstr(outfilename),ios_base::out);
        if(!outf.is_open()){
            cerr << outfilename << " " << strerror(errno)
                 << ": Cannot open for output; will not delete " << tempfilename << "\n";
            exit(1);
        }
        // copy over first line --- the XML header
        std::string line;
        getline(in,line);
        outf << line;

        write_dtd();                    // write the DTD
        while(!in.eof()){
            getline(in,line);
            outf << line << endl;
        }
        in.close();
        unlink(cstr(tempfilename));
        outf.close();
    }
    MUTEX_UNLOCK(&M);
}

void dfxml_writer::write_dtd()
{
    *out << "<!DOCTYPE fiwalk\n";
    *out << "[\n";
    for(set<string>::const_iterator it = tags.begin(); it != tags.end(); it++){
        *out << "<!ELEMENT " << *it << "ANY >\n";
    }
    *out << "<!ATTLIST volume startsector CDATA #IMPLIED>\n";
    *out << "<!ATTLIST run start CDATA #IMPLIED>\n";
    *out << "<!ATTLIST run len CDATA #IMPLIED>\n";
    *out << "]>\n";
}

/**
 * make sure that a tag is valid and, if so, add it to the list of tags we use
 */
void dfxml_writer::verify_tag(string tag)
{
    if(tag[0]=='/') tag = tag.substr(1);
    if(tag.find(" ") != string::npos){
        cerr << "tag '" << tag << "' contains space. Cannot continue.\n";
        exit(1);
    }
    tags.insert(tag);
}

void dfxml_writer::puts(const string &v)
{
    *out << v;
}

void dfxml_writer::spaces()
{
    for(unsigned int i=0;i<tag_stack.size() && !oneline;i++){
        *out << "  ";
    }
}

void dfxml_writer::tagout(const string &tag,const string &attribute)
{
    verify_tag(tag);
    *out << "<" << tag;
    if(attribute.size()>0) *out << " " << attribute;
    *out << ">";
}

#if (!defined(HAVE_VASPRINTF)) || defined(_WIN32)
#ifndef _WIN32
#define ms_printf __print
#define __MINGW_ATTRIB_NONNULL(x)
#endif
extern "C" {
    /**
     * We do not have vasprintf.
     * We have determined that vsnprintf() does not perform properly on windows.
     * So we just allocate a huge buffer and then strdup() and hope!
     */
    int vasprintf(char **ret,const char *fmt,va_list ap)
        __attribute__((__format__(ms_printf, 2, 0)))
        __MINGW_ATTRIB_NONNULL(2) ;
    int vasprintf(char **ret,const char *fmt,va_list ap)
    {
        /* Figure out how long the result will be */
        char buf[65536];
        int size = vsnprintf(buf,sizeof(buf),fmt,ap);
        if(size<0) return size;
        /* Now allocate the memory */
        *ret = strcpy((char *) malloc(strlen(buf)+1), buf);
        return size;
    }
}
#endif

void dfxml_writer::printf(const char *fmt,...)
{
    va_list ap;
    va_start(ap, fmt);

    /** printf to stream **/
    char *ret = 0;
    if(vasprintf(&ret,fmt,ap) < 0){
        *out << "dfxml_writer::xmlprintf: " << strerror(errno);
        exit(EXIT_FAILURE);
    }
    *out << ret;
    free(ret);
    /** end printf to stream **/

    va_end(ap);
}

void dfxml_writer::push(const string &tag,const string &attribute)
{
    spaces();
    tag_stack.push(tag);
    tagout(tag,attribute);
    if(!oneline) *out << '\n';
}

void dfxml_writer::pop()
{
    assert(tag_stack.size()>0);
    string tag = tag_stack.top();
    tag_stack.pop();
    spaces();
    tagout("/"+tag,"");
    *out << '\n';
}

void dfxml_writer::set_oneline(bool v)
{
    if(v==true) spaces();
    if(v==false) *out << "\n";
    oneline = v;
}

void dfxml_writer::cpuid(uint32_t op, unsigned long *eax, unsigned long *ebx,
                unsigned long *ecx, unsigned long *edx) {
#if defined(HAVE_ASM_CPUID) && defined(__i386__)
#if defined(__PIC__)
    __asm__ __volatile__("pushl %%ebx      \n\t" /* save %ebx */
                         "cpuid            \n\t"
                         "movl %%ebx, %1   \n\t" /* save what cpuid just put in %ebx */
                         "popl %%ebx       \n\t" /* restore the old %ebx */
                         : "=a"(*eax), "=r"(*ebx), "=c"(*ecx), "=d"(*edx)
                         : "a"(op)
                         : "cc");
#else
    __asm__ __volatile__("cpuid"
                         : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
                         : "a"(op)
                         : "cc");
#endif
#endif
}

void dfxml_writer::add_cpuid()
{
#if defined(__i386__)
#ifndef __WORDSIZE
#define __WORDSIZE 32
#endif
#define BFIX(val, base, end) ((val << (__WORDSIZE-end-1)) >> (__WORDSIZE-end+base-1))
    char buf[256];
    unsigned long eax=0, ebx=0, ecx=0, edx=0; // =0 avoids a compiler warning
    cpuid(0, &eax, &ebx, &ecx, &edx);

    snprintf(buf,sizeof(buf),"%.4s%.4s%.4s", (char *)&ebx, (char *)&edx, (char *)&ecx);
    push("cpuid");
    xmlout("identification",buf);

    cpuid(1, &eax, &ebx, &ecx, &edx);
    xmlout("family", (int64_t) BFIX(eax, 8, 11));
    xmlout("model", (int64_t) BFIX(eax, 4, 7));
    xmlout("stepping", (int64_t) BFIX(eax, 0, 3));
    xmlout("efamily", (int64_t) BFIX(eax, 20, 27));
    xmlout("emodel", (int64_t) BFIX(eax, 16, 19));
    xmlout("brand", (int64_t) BFIX(ebx, 0, 7));
    xmlout("clflush_size", (int64_t) BFIX(ebx, 8, 15) * 8);
    xmlout("nproc", (int64_t) BFIX(ebx, 16, 23));
    xmlout("apicid", (int64_t) BFIX(ebx, 24, 31));

    cpuid(0x80000006, &eax, &ebx, &ecx, &edx);
    xmlout("L1_cache_size", (int64_t) BFIX(ecx, 16, 31) * 1024);
    pop();
#undef BFIX
#endif
}

void dfxml_writer::add_DFXML_execution_environment(const std::string &command_line)
{

    push("execution_environment");
#if defined(HAVE_ASM_CPUID) && defined(__i386__)
    add_cpuid();
#endif

#ifdef HAVE_SYS_UTSNAME_H
    struct utsname name;
    if(uname(&name)==0){
        xmlout("os_sysname",name.sysname);
        xmlout("os_release",name.release);
        xmlout("os_version",name.version);
        xmlout("host",name.nodename);
        xmlout("arch",name.machine);
    }
#else
#ifdef UNAMES
    xmlout("os_sysname",UNAMES,"",false);
#endif
#ifdef HAVE_GETHOSTNAME
    {
        char hostname[1024];
        if(gethostname(hostname,sizeof(hostname))==0){
            xmlout("host",hostname);
        }
    }
#endif
#endif

    xmlout("command_line", command_line); // quote it!
#ifdef HAVE_GETUID
    xmlprintf("uid","","%d",getuid());
#ifdef HAVE_GETPWUID
    xmlout("username",getpwuid(getuid())->pw_name);
#endif
#endif

#define TM_FORMAT "%Y-%m-%dT%H:%M:%SZ"
    char buf[256];
    time_t t = time(0);
    strftime(buf,sizeof(buf),TM_FORMAT,gmtime(&t));
    xmlout("start_time",buf);
    pop();                      // <execution_environment>
}

#ifdef WIN32
#include "psapi.h"
#endif

void dfxml_writer::add_rusage()
{
#ifdef WIN32
    /* Note: must link -lpsapi for this */
    PROCESS_MEMORY_COUNTERS_EX pmc;
    memset(&pmc,0,sizeof(pmc));
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc));
    push("PROCESS_MEMORY_COUNTERS");
    xmlout("cb",(int64_t)pmc.cb);
    xmlout("PageFaultCount",(int64_t)pmc.PageFaultCount);
    xmlout("WorkingSetSize",(int64_t)pmc.WorkingSetSize);
    xmlout("QuotaPeakPagedPoolUsage",(int64_t)pmc.QuotaPeakPagedPoolUsage);
    xmlout("QuotaPagedPoolUsage",(int64_t)pmc.QuotaPagedPoolUsage);
    xmlout("QuotaPeakNonPagedPoolUsage",(int64_t)pmc.QuotaPeakNonPagedPoolUsage);
    xmlout("PagefileUsage",(int64_t)pmc.PagefileUsage);
    xmlout("PeakPagefileUsage",(int64_t)pmc.PeakPagefileUsage);
    xmlout("PrivateUsage",(int64_t)pmc.PrivateUsage);
    pop();
#endif
#ifdef HAVE_GETRUSAGE
    struct rusage ru;
    memset(&ru,0,sizeof(ru));
    if(getrusage(RUSAGE_SELF,&ru)==0){
        push("rusage");
        xmlout("utime",ru.ru_utime);
        xmlout("stime",ru.ru_stime);
        xmloutl("maxrss",(long)ru.ru_maxrss);
        xmloutl("minflt",(long)ru.ru_minflt);
        xmloutl("majflt",(long)ru.ru_majflt);
        xmloutl("nswap",(long)ru.ru_nswap);
        xmloutl("inblock",(long)ru.ru_inblock);
        xmloutl("oublock",(long)ru.ru_oublock);

        struct timeval t1;
        gettimeofday(&t1,0);
        struct timeval t;

        t.tv_sec = t1.tv_sec - t0.tv_sec;
        if(t1.tv_usec > t0.tv_usec){
            t.tv_usec = t1.tv_usec - t0.tv_usec;
        } else {
            t.tv_sec--;
            t.tv_usec = (t1.tv_usec+1000000) - t0.tv_usec;
        }
        xmlout("clocktime",t);
        pop();
    }
#endif
}

void dfxml_writer::add_timestamp(const std::string &name)
{
    struct timeval t1;
    gettimeofday(&t1,0);
    struct timeval t;

    // timestamp delta against t_last_timestamp
    t.tv_sec = t1.tv_sec - t_last_timestamp.tv_sec;
    if(t1.tv_usec > t_last_timestamp.tv_usec){
        t.tv_usec = t1.tv_usec - t_last_timestamp.tv_usec;
    } else {
        t.tv_sec--;
        t.tv_usec = (t1.tv_usec+1000000) - t_last_timestamp.tv_usec;
    }
    char delta[16];
    snprintf(delta, 16, "%d.%06d", (int)t.tv_sec, (int)t.tv_usec);

    // reset t_last_timestamp for the next invocation
    gettimeofday(&t_last_timestamp,0);

    // timestamp total
    t.tv_sec = t1.tv_sec - t0.tv_sec;
    if(t1.tv_usec > t0.tv_usec){
        t.tv_usec = t1.tv_usec - t0.tv_usec;
    } else {
        t.tv_sec--;
        t.tv_usec = (t1.tv_usec+1000000) - t0.tv_usec;
    }
    char total[16];
    snprintf(total, 16, "%d.%06d", (int)t.tv_sec, (int)t.tv_usec);

    // prepare attributes
    std::stringstream ss;
    ss << "name='" << name
       << "' delta='" << delta
       << "' total='" << total
       << "'";

    // add named timestamp
    xmlout("timestamp", "",ss.str(), true);
}

/****************************************************************
 *** THESE ARE THE ONLY THREADSAFE ROUTINES
 ****************************************************************/
void dfxml_writer::comment(const string &comment_)
{
    MUTEX_LOCK(&M);
    *out << "<!-- " << comment_ << " -->\n";
    out->flush();
    MUTEX_UNLOCK(&M);
}

void dfxml_writer::xmlprintf(const std::string &tag,const std::string &attribute, const char *fmt,...)
{
    MUTEX_LOCK(&M);
    spaces();
    tagout(tag,attribute);
    va_list ap;
    va_start(ap, fmt);

    /** printf to stream **/
    char *ret = 0;
    if(vasprintf(&ret,fmt,ap) < 0){
        cerr << "dfxml_writer::xmlprintf: " << strerror(errno) << "\n";
        exit(EXIT_FAILURE);
    }
    *out << ret;
    free(ret);
    /** end printf to stream **/

    va_end(ap);
    tagout("/"+tag,"");
    *out << '\n';
    out->flush();
    MUTEX_UNLOCK(&M);
}

void dfxml_writer::xmlout(const string &tag,const string &value,const string &attribute,bool escape_value)
{
    MUTEX_LOCK(&M);
    spaces();
    if(value.size()==0){
        if(tag.size()) tagout(tag,attribute+"/");
    } else {
        if(tag.size()) tagout(tag,attribute);
        *out << (escape_value ? xmlescape(value) : value);
        if(tag.size()) tagout("/"+tag,"");
    }
    *out << "\n";
    out->flush();
    MUTEX_UNLOCK(&M);
}

#ifdef HAVE_LIBEWF_H
#include <libewf.h>
#endif

#if defined(HAVE_EXIV2) && defined(HAVE_EXIV2_IMAGE_HPP)
#ifdef DFXML_GNUC_HAS_DIAGNOSTIC_PRAGMA
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Weffc++"
#endif
#include <exiv2/image.hpp>
#include <exiv2/exif.hpp>
#include <exiv2/error.hpp>
#endif

#ifdef HAVE_HASHDB
#include <hashdb.hpp>
#endif

#ifdef HAVE_AFFLIB_AFFLIB_H
//#pragma GCC diagnostic ignored "-Wreserved-user-defined-literal"               // required for C11
#include <afflib/afflib.h>
#endif

/* These support Digital Forensics XML and require certain variables to be defined */
void dfxml_writer::add_DFXML_build_environment()
{
    /* __DATE__ formats as: Apr 30 2011 */
    struct tm tm;
    memset(&tm,0,sizeof(tm));
    push("build_environment");
#ifdef __GNUC__
    // See http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
    xmlprintf("compiler","","%d.%d.%d (%s)",__GNUC__, __GNUC_MINOR__,__GNUC_PATCHLEVEL__,__VERSION__);
#endif
#ifdef CPPFLAGS
    xmlout("CPPFLAGS",CPPFLAGS,"",true);
#endif
#ifdef CFLAGS
    xmlout("CFLAGS",CFLAGS,"",true);
#endif
#ifdef CXXFLAGS
    xmlout("CXXFLAGS",CXXFLAGS,"",true);
#endif
#ifdef LDFLAGS
    xmlout("LDFLAGS",LDFLAGS,"",true);
#endif
#ifdef LIBS
    xmlout("LIBS",LIBS,"",true);
#endif
#if defined(__DATE__) && defined(__TIME__) && defined(HAVE_STRPTIME)
    if(strptime(__DATE__,"%b %d %Y",&tm)){
        char buf[64];
        snprintf(buf,sizeof(buf),"%4d-%02d-%02dT%s",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,__TIME__);
        xmlout("compilation_date",buf);
    }
#endif
#ifdef BOOST_VERSION
    {
        char buf[64];
        snprintf(buf,sizeof(buf),"%d",BOOST_VERSION);
        xmlout("library", "", std::string("name=\"boost\" version=\"") + buf + "\"",false);
    }
#endif
#ifdef HAVE_LIBTSK3
    xmlout("library", "", std::string("name=\"tsk\" version=\"") + tsk_version_get_str() + "\"",false);
#endif
#ifdef HAVE_LIBAFFLIB
    xmlout("library", "", std::string("name=\"afflib\" version=\"") + af_version() +"\"",false);
#endif
#ifdef HAVE_LIBEWF
    xmlout("library", "", std::string("name=\"libewf\" version=\"") + libewf_get_version() + "\"",false);
#endif
#ifdef HAVE_EXIV2
    xmlout("library", "", std::string("name=\"exiv2\" version=\"") + Exiv2::version() + "\"",false);
#endif
#if defined(HAVE_LIBTRE) && defined(HAVE_TRE_VERSION) && defined(HAVE_TRE_TRE_H)
    xmlout("library", "", std::string("name=\"tre\" version=\"") + tre_version() + "\"",false);
#endif
#ifdef HAVE_HASHDB
    xmlout("library", "", std::string("name=\"hashdb\" version=\"") + hashdb_version() + "\"",false);
#endif
#ifdef SQLITE_VERSION
    xmlout("library", "", "name=\"sqlite\" version=\"" SQLITE_VERSION "\" source_id=\"" SQLITE_SOURCE_ID "\"",false);
#endif
#ifdef HAVE_GNUEXIF
    // gnuexif does not have a programmatically obtainable version.
    xmlout("library","","name=\"gnuexif\" version=\"?\"",false);
#endif
#ifdef GIT_COMMIT
    xmlout("git", "", "commit=\"" GIT_COMMIT "\"",false);
#endif
    pop();
}

ext: cpp

max_stars_repo_name: thinkmoore/das

max_issues_repo_name: thinkmoore/das

max_forks_repo_name: thinkmoore/das


text:
#include <iostream>
#include <string>
#include <vector>

#include <boost/lockfree/queue.hpp>

#include "test/timed-throughput-fixture.h"
#include "test/timed-throughput.h"
#include "util/parse-cmd-line.h"
#include "util/util.h"

using boost::lockfree::queue;
using std::string;
using std::vector;
using test::timed_throughput;
using test::timed_throughput_fixture;
using util::CmdLineOpts;

#define MAX(a, b) ((a) > (b) ? (a) : (b))

typedef timed_throughput_fixture<queue<int>, int,
                                 queue<int>, int> Fixture;

int main(int argc, char **argv) {
  CmdLineOpts opts;
  if (parseCmdLineOpts(argc, argv, opts) != 0)
    return 1;

  if (opts.use_large_test) {
    std::cerr << "Large tests not supported" << std::endl;
    return 1;
  }

  int max_num_threads = MAX(opts.num_producers, opts.num_consumers);
  boost::lockfree::queue<int> small_queue(max_num_threads);
  int small_item = 0;

  Fixture fixture(&small_queue, &small_item, &small_queue, &small_item);
  if (fixture.run(argc, argv))
    return 0;
  else
    return 1;
}

ext: cc

max_stars_repo_name: cookyt/parallel-multi-queue

max_issues_repo_name: cookyt/parallel-multi-queue

max_forks_repo_name: cookyt/parallel-multi-queue


text:
#ifndef RenderUtilities_h
#define RenderUtilities_h

#include "PngWrapper.hpp"

#include <Eigen/Dense>

class Camera;

uint8_t * render_scene(uint16_t width, uint16_t height,
                       const Eigen::Matrix<float, 3, Eigen::Dynamic>& vertices,
                       const Eigen::Matrix<float, 3, Eigen::Dynamic>& normals,
                       const Camera & camera, const Eigen::Vector3f & light_source);

PngWrapper * normals_as_png(uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals);
/*
 * Implement Lambertian colouring as per https://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html
 * @param width The with of the image
 * @param height The height of the imahe
 * @param vertices A width x height array of Vertex coordinates in global space
 * @param normals A width x height array of surface normals in global space
 * @param camera The Camera for which to render
 * @param light_source THe global position of the light source
 */
PngWrapper * scene_as_png(uint16_t width, uint16_t height,
                          const Eigen::Matrix<float,3,Eigen::Dynamic>& vertices,
                          const Eigen::Matrix<float,3,Eigen::Dynamic>& normals,
                          const Camera & camera,
                          const Eigen::Vector3f & light_source);

void save_normals_as_colour_png( std::string filename, uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals );
void save_rendered_scene_as_png( std::string filename, uint16_t width, uint16_t height, const Eigen::Matrix<float,3,Eigen::Dynamic>& vertices, const Eigen::Matrix<float,3,Eigen::Dynamic>& normals, const Camera & camera, const Eigen::Vector3f & light_source);

#endif // RenderUtilities_h

max_stars_repo_name: justanhduc/ray-casting

max_issues_repo_name: justanhduc/ray-casting

max_forks_repo_name: justanhduc/ray-casting


text:
// Copyright Jim Bosch 2010-2012.
// Copyright Stefan Seefeld 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef boost_python_numpy_ndarray_hpp_
#define boost_python_numpy_ndarray_hpp_

/**
 *  @brief Object manager and various utilities for numpy.ndarray.
 */

#include <boost/python.hpp>
#include <boost/python/detail/type_traits.hpp>
#include <boost/python/numpy/config.hpp>
#include <boost/python/numpy/dtype.hpp>
#include <boost/python/numpy/numpy_object_mgr_traits.hpp>
#include <boost/utility/enable_if.hpp>

#include <vector>

namespace boost {
namespace python {
namespace numpy {

/**
 *  @brief A boost.python "object manager" (subclass of object) for
 * numpy.ndarray.
 *
 *  @todo This could have a lot more functionality (like
 * boost::python::numeric::array). Right now all that exists is what was needed
 * to move raw data between C++ and Python.
 */

class BOOST_NUMPY_DECL ndarray : public object {

  /**
   *  @brief An internal struct that's byte-compatible with PyArrayObject.
   *
   *  This is just a hack to allow inline access to this stuff while hiding
   * numpy/arrayobject.h from the user.
   */
  struct array_struct {
    PyObject_HEAD char *data;
    int nd;
    Py_intptr_t *shape;
    Py_intptr_t *strides;
    PyObject *base;
    PyObject *descr;
    int flags;
    PyObject *weakreflist;
  };

  /// @brief Return the held Python object as an array_struct.
  array_struct *get_struct() const {
    return reinterpret_cast<array_struct *>(this->ptr());
  }

public:
  /**
   *  @brief Enum to represent (some) of Numpy's internal flags.
   *
   *  These don't match the actual Numpy flag values; we can't get those without
   * including numpy/arrayobject.h or copying them directly.  That's very
   * unfortunate.
   *
   *  @todo I'm torn about whether this should be an enum.  It's very convenient
   * to not make these simple integer values for overloading purposes, but the
   * need to define every possible combination and custom bitwise operators is
   * ugly.
   */
  enum bitflag {
    NONE = 0x0,
    C_CONTIGUOUS = 0x1,
    F_CONTIGUOUS = 0x2,
    V_CONTIGUOUS = 0x1 | 0x2,
    ALIGNED = 0x4,
    WRITEABLE = 0x8,
    BEHAVED = 0x4 | 0x8,
    CARRAY_RO = 0x1 | 0x4,
    CARRAY = 0x1 | 0x4 | 0x8,
    CARRAY_MIS = 0x1 | 0x8,
    FARRAY_RO = 0x2 | 0x4,
    FARRAY = 0x2 | 0x4 | 0x8,
    FARRAY_MIS = 0x2 | 0x8,
    UPDATE_ALL = 0x1 | 0x2 | 0x4,
    VARRAY = 0x1 | 0x2 | 0x8,
    ALL = 0x1 | 0x2 | 0x4 | 0x8
  };

  BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(ndarray, object);

  /// @brief Return a view of the scalar with the given dtype.
  ndarray view(dtype const &dt) const;

  /// @brief Copy the array, cast to a specified type.
  ndarray astype(dtype const &dt) const;

  /// @brief Copy the scalar (deep for all non-object fields).
  ndarray copy() const;

  /// @brief Return the size of the nth dimension. raises IndexError if k not in
  /// [-get_nd() : get_nd()-1 ]
  Py_intptr_t shape(int n) const;

  /// @brief Return the stride of the nth dimension. raises IndexError if k not
  /// in [-get_nd() : get_nd()-1]
  Py_intptr_t strides(int n) const;

  /**
   *  @brief Return the array's raw data pointer.
   *
   *  This returns char so stride math works properly on it.  It's pretty much
   *  expected that the user will have to reinterpret_cast it.
   */
  char *get_data() const { return get_struct()->data; }

  /// @brief Return the array's data-type descriptor object.
  dtype get_dtype() const;

  /// @brief Return the object that owns the array's data, or None if the array
  /// owns its own data.
  object get_base() const;

  /// @brief Set the object that owns the array's data.  Use with care.
  void set_base(object const &base);

  /// @brief Return the shape of the array as an array of integers (length ==
  /// get_nd()).
  Py_intptr_t const *get_shape() const { return get_struct()->shape; }

  /// @brief Return the stride of the array as an array of integers (length ==
  /// get_nd()).
  Py_intptr_t const *get_strides() const { return get_struct()->strides; }

  /// @brief Return the number of array dimensions.
  int get_nd() const { return get_struct()->nd; }

  /// @brief Return the array flags.
  bitflag get_flags() const;

  /// @brief Reverse the dimensions of the array.
  ndarray transpose() const;

  /// @brief Eliminate any unit-sized dimensions.
  ndarray squeeze() const;

  /// @brief Equivalent to self.reshape(*shape) in Python.
  ndarray reshape(python::tuple const &shape) const;

  /**
   *  @brief If the array contains only a single element, return it as an array
   * scalar; otherwise return the array.
   *
   *  @internal This is simply a call to PyArray_Return();
   */
  object scalarize() const;
};

/**
 *  @brief Construct a new array with the given shape and data type, with data
 * initialized to zero.
 */
BOOST_NUMPY_DECL ndarray zeros(python::tuple const &shape, dtype const &dt);
BOOST_NUMPY_DECL ndarray zeros(int nd, Py_intptr_t const *shape,
                               dtype const &dt);

/**
 *  @brief Construct a new array with the given shape and data type, with data
 * left uninitialized.
 */
BOOST_NUMPY_DECL ndarray empty(python::tuple const &shape, dtype const &dt);
BOOST_NUMPY_DECL ndarray empty(int nd, Py_intptr_t const *shape,
                               dtype const &dt);

/**
 *  @brief Construct a new array from an arbitrary Python sequence.
 *
 *  @todo This does't seem to handle ndarray subtypes the same way that
 * "numpy.array" does in Python.
 */
BOOST_NUMPY_DECL ndarray array(object const &obj);
BOOST_NUMPY_DECL ndarray array(object const &obj, dtype const &dt);

namespace detail {

BOOST_NUMPY_DECL ndarray from_data_impl(void *data, dtype const &dt,
                                        std::vector<Py_intptr_t> const &shape,
                                        std::vector<Py_intptr_t> const &strides,
                                        object const &owner, bool writeable);

template <typename Container>
ndarray
from_data_impl(void *data, dtype const &dt, Container shape, Container strides,
               object const &owner, bool writeable,
               typename boost::enable_if<boost::python::detail::is_integral<
                   typename Container::value_type>>::type *enabled = NULL) {
  std::vector<Py_intptr_t> shape_(shape.begin(), shape.end());
  std::vector<Py_intptr_t> strides_(strides.begin(), strides.end());
  return from_data_impl(data, dt, shape_, strides_, owner, writeable);
}

BOOST_NUMPY_DECL ndarray from_data_impl(void *data, dtype const &dt,
                                        object const &shape,
                                        object const &strides,
                                        object const &owner, bool writeable);

} // namespace detail

/**
 *  @brief Construct a new ndarray object from a raw pointer.
 *
 *  @param[in] data    Raw pointer to the first element of the array.
 *  @param[in] dt      Data type descriptor.  Often retrieved with
 * dtype::get_builtin().
 *  @param[in] shape   Shape of the array as STL container of integers; must
 * have begin() and end().
 *  @param[in] strides Shape of the array as STL container of integers; must
 * have begin() and end().
 *  @param[in] owner   An arbitray Python object that owns that data pointer.
 * The array object will keep a reference to the object, and decrement it's
 * reference count when the array goes out of scope.  Pass None at your own
 * peril.
 *
 *  @todo Should probably take ranges of iterators rather than actual container
 * objects.
 */
template <typename Container>
inline ndarray from_data(void *data, dtype const &dt, Container shape,
                         Container strides, python::object const &owner) {
  return numpy::detail::from_data_impl(data, dt, shape, strides, owner, true);
}

/**
 *  @brief Construct a new ndarray object from a raw pointer.
 *
 *  @param[in] data    Raw pointer to the first element of the array.
 *  @param[in] dt      Data type descriptor.  Often retrieved with
 * dtype::get_builtin().
 *  @param[in] shape   Shape of the array as STL container of integers; must
 * have begin() and end().
 *  @param[in] strides Shape of the array as STL container of integers; must
 * have begin() and end().
 *  @param[in] owner   An arbitray Python object that owns that data pointer.
 * The array object will keep a reference to the object, and decrement it's
 * reference count when the array goes out of scope.  Pass None at your own
 * peril.
 *
 *  This overload takes a const void pointer and sets the "writeable" flag of
 * the array to false.
 *
 *  @todo Should probably take ranges of iterators rather than actual container
 * objects.
 */
template <typename Container>
inline ndarray from_data(void const *data, dtype const &dt, Container shape,
                         Container strides, python::object const &owner) {
  return numpy::detail::from_data_impl(const_cast<void *>(data), dt, shape,
                                       strides, owner, false);
}

/**
 *  @brief Transform an arbitrary object into a numpy array with the given
 * requirements.
 *
 *  @param[in] obj     An arbitrary python object to convert.  Arrays that meet
 * the requirements will be passed through directly.
 *  @param[in] dt      Data type descriptor.  Often retrieved with
 * dtype::get_builtin().
 *  @param[in] nd_min  Minimum number of dimensions.
 *  @param[in] nd_max  Maximum number of dimensions.
 *  @param[in] flags   Bitwise OR of flags specifying additional requirements.
 */
BOOST_NUMPY_DECL ndarray from_object(object const &obj, dtype const &dt,
                                     int nd_min, int nd_max,
                                     ndarray::bitflag flags = ndarray::NONE);

BOOST_NUMPY_DECL inline ndarray
from_object(object const &obj, dtype const &dt, int nd,
            ndarray::bitflag flags = ndarray::NONE) {
  return from_object(obj, dt, nd, nd, flags);
}

BOOST_NUMPY_DECL inline ndarray
from_object(object const &obj, dtype const &dt,
            ndarray::bitflag flags = ndarray::NONE) {
  return from_object(obj, dt, 0, 0, flags);
}

BOOST_NUMPY_DECL ndarray from_object(object const &obj, int nd_min, int nd_max,
                                     ndarray::bitflag flags = ndarray::NONE);

BOOST_NUMPY_DECL inline ndarray
from_object(object const &obj, int nd, ndarray::bitflag flags = ndarray::NONE) {
  return from_object(obj, nd, nd, flags);
}

BOOST_NUMPY_DECL inline ndarray
from_object(object const &obj, ndarray::bitflag flags = ndarray::NONE) {
  return from_object(obj, 0, 0, flags);
}

BOOST_NUMPY_DECL inline ndarray::bitflag operator|(ndarray::bitflag a,
                                                   ndarray::bitflag b) {
  return ndarray::bitflag(int(a) | int(b));
}

BOOST_NUMPY_DECL inline ndarray::bitflag operator&(ndarray::bitflag a,
                                                   ndarray::bitflag b) {
  return ndarray::bitflag(int(a) & int(b));
}

} // namespace numpy

namespace converter {

NUMPY_OBJECT_MANAGER_TRAITS(numpy::ndarray);

}
} // namespace python
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "FiniteElementFunction.h"
#include "form/RefElement.h"
#include "tensor/EigenMap.h"

#include <Eigen/Core>

#include <cassert>
#include <cstdio>

namespace tndm {

template <std::size_t D>
Managed<Matrix<double>>
FiniteElementFunction<D>::evaluationMatrix(std::vector<std::array<double, D>> const& points) const {
    return refElement_->evaluateBasisAt(points, {1, 0});
}

template <std::size_t D>
Managed<Tensor<double, 3u>> FiniteElementFunction<D>::gradientEvaluationTensor(
    std::vector<std::array<double, D>> const& points) const {
    return refElement_->evaluateGradientAt(points, {2, 0, 1});
}

template <std::size_t D>
TensorBase<Matrix<double>> FiniteElementFunction<D>::mapResultInfo(std::size_t numPoints) const {
    return TensorBase<Matrix<double>>(numPoints, numQuantities());
}

template <std::size_t D>
void FiniteElementFunction<D>::map(std::size_t eleNo, Matrix<double> const& evalMatrix,
                                   Tensor<double, 2u>& result) const {
    assert(eleNo < numElements());
    assert(result.shape(0) == evalMatrix.shape(0));
    assert(result.shape(1) == numQuantities());
    assert(evalMatrix.shape(1) == numBasisFunctions());

    auto mat = data_.subtensor(slice{}, slice{}, eleNo);
    EigenMap(result) = EigenMap(evalMatrix) * EigenMap(mat);
}

template <std::size_t D>
TensorBase<Tensor<double, 3u>>
FiniteElementFunction<D>::gradientResultInfo(std::size_t numPoints) const {
    return TensorBase<Tensor<double, 3u>>(numPoints, numQuantities(), D);
}

template <std::size_t D>
void FiniteElementFunction<D>::gradient(std::size_t eleNo, Tensor<double, 3u> const& evalTensor,
                                        Tensor<double, 3u> const& jInvAtP,
                                        Tensor<double, 3u>& result) const {
    assert(eleNo < numElements());
    assert(result.shape(0) == evalTensor.shape(0));
    assert(result.shape(1) == numQuantities());
    assert(result.shape(2) == D);
    assert(evalTensor.shape(1) == numBasisFunctions());
    assert(evalTensor.shape(2) == D);
    assert(jInvAtP.shape(0) == D);
    assert(jInvAtP.shape(1) == D);
    assert(jInvAtP.shape(2) == result.shape(0));

    auto mat = data_.subtensor(slice{}, slice{}, eleNo);
    for (std::ptrdiff_t j = 0; j < evalTensor.shape(2); ++j) {
        auto d_j = evalTensor.subtensor(slice{}, slice{}, j);
        auto result_j = result.subtensor(slice{}, slice{}, j);
        EigenMap(result_j) = EigenMap(d_j) * EigenMap(mat);
    }

    for (std::ptrdiff_t q = 0; q < result.shape(0); ++q) {
        auto jInvAtP_q = jInvAtP.subtensor(slice{}, slice{}, q);
        auto result_q = result.subtensor(q, slice{}, slice{});
        EigenMap(result_q) = EigenMap(result_q) * EigenMap(jInvAtP_q);
    }
}

template <std::size_t D> std::string FiniteElementFunction<D>::name(std::size_t q) const {
    assert(q < numQuantities());
    if (!names_.empty()) {
        return names_[q];
    }
    char buf[100];
    snprintf(buf, sizeof(buf), "q%lu", q);
    return std::string(buf);
}

template class FiniteElementFunction<1ul>;
template class FiniteElementFunction<2ul>;
template class FiniteElementFunction<3ul>;

} // namespace tndm

max_stars_repo_name: NicoSchlw/tandem

max_issues_repo_name: NicoSchlw/tandem

max_forks_repo_name: NicoSchlw/tandem


text:
/*
	Copyright (C) 2003-2013 by David White <davewx7@gmail.com>

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GRAPHICAL_FONT_HPP_INCLUDED
#define GRAPHICAL_FONT_HPP_INCLUDED

#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>

#include <string>
#include <vector>

#include "geometry.hpp"
#include "texture.hpp"
#include "variant.hpp"

class graphical_font;
typedef boost::shared_ptr<graphical_font> graphical_font_ptr;
typedef boost::shared_ptr<const graphical_font> const_graphical_font_ptr;

class graphical_font
{
public:
	static void init(variant node);
	static void init_for_locale(const std::string& locale);
	static const_graphical_font_ptr get(const std::string& id);
	explicit graphical_font(variant node);
	const std::string& id() const { return id_; }
	rect draw(int x, int y, const std::string& text, int size=2) const;
	rect dimensions(const std::string& text, int size=2) const;

private:
	rect do_draw(int x, int y, const std::string& text, bool draw_text, int size) const;

	std::string id_;

	graphics::texture texture_;
	//hashmap to map characters to rectangles in the texture
	typedef boost::unordered_map<unsigned int, rect> char_rect_map;
	char_rect_map char_rect_map_;
	int kerning_;
};

#endif

max_stars_repo_name: sweetkristas/anura

max_issues_repo_name: sweetkristas/anura

max_forks_repo_name: sweetkristas/anura


text:
/**
 * Author: Junjie Shi, Ardalan Naseri
 *
 * This file is responsible for inferring the relationship between a pair of individuals.
 *
 */

#include <algorithm>
#include <iostream>
#include <unordered_set>

#include <boost/functional/hash.hpp>

#include "parser.hpp"
#include "mapper.hpp"
#include "classifier.hpp"

// Unadjusted thresholds
static double FOURTH_START_ORIGINAL = 1 / std::pow(2, 11.0 / 2);
static double THIRD_START_ORIGINAL = 1 / std::pow(2, 9.0 / 2);
static double SECOND_START_ORIGINAL = 1 / std::pow(2, 7.0 / 2);
static double PO_FS_START_ORIGINAL = 1 / std::pow(2, 5.0 / 2);
static double MZ_START_ORIGNAL = 1 / std::pow(2, 3.0 / 2);
static double FS_START_ORIGINAL = 0.1;

// Current thresholds used for inference
double FOURTH_START = 1 / std::pow(2, 11.0 / 2);
double THIRD_START = 1 / std::pow(2, 9.0 / 2);
double SECOND_START = 1 / std::pow(2, 7.0 / 2);
double PO_FS_START = 1 / std::pow(2, 5.0 / 2);
double MZ_START = 1 / std::pow(2, 3.0 / 2);
double FS_START = 0.1;

// Expected kinship coefficent for full-siblings
#define PO_FS_START_EXPECTED 0.25

const int NUM_TYPES = 7;
const std::vector<std::string> TYPES {"MZ", "PO", "FS", "2nd", "3rd", "4th", "UN"};

// Sum of kinship coefficients of all recorded full-siblings
static double FS_TOTAL_KINSHIP_COEFFICIENTS = 0;
// Number of pairs of full-siblings currently recorded
static int NUM_FS = 0;
// Number of pairs of full-siblings recorded at last adjustment
static int PREV_ADJUSTED_NUM_FS = 0;

// Mininum number of pairs of full-siblings needed to be recorded between two
// consecutive adjustment.
#define MIN_ADJUSTING_INTERVAL 50

//#define MIN_ADJUSTING_INTERVAL 10

// Maximum number of pairs of full-siblings that will be recorded.
#define MAX_NUM_FS 1000

/**
 * Record an identified full-sibling pair. Add their kinship coefficient to
 * FS_TOTAL_KINSHIP_COEFFICIENTS. If MAX_NUM_FS pairs of
 * full siblings have already been recorded, then no-op.
 *
 * @param stats a struct pair_stats that contains total IBD1 and total IBD2
 *     of the pair.
 *
 */
void
add_full_sibling(const struct pair_stats &stats)
{

// CHANGED! Commented out
    if (NUM_FS > MAX_NUM_FS) {
        return;
    }

    ++NUM_FS;
    FS_TOTAL_KINSHIP_COEFFICIENTS += compute_kinship_coefficient(
        stats.total_ibd1, stats.total_ibd2
    );
}

/**
 *
 * @return number of pairs of full-siblings that have been recorded.
 *
*/
int
get_num_full_siblings() {
    return NUM_FS;
}

/**
 * Adjust kinship coefficient and IBD2 thresholds. No-op if there are fewer than
 * MIN_NUM_FS pairs of full-siblings, or fewer than MIN_ADJUSTING_INTERVAL pairs
 * of full-siblings have been recorded since last adjustment, or there more more
 * than MAX_NUM_FS pairs of full-siblings.
 *
 */
void
shift_boundary()
{

    if (NUM_FS - PREV_ADJUSTED_NUM_FS < MIN_ADJUSTING_INTERVAL ||
        NUM_FS < MIN_NUM_FS || NUM_FS > MAX_NUM_FS) {
        return;
    }

/**
    if (NUM_FS - PREV_ADJUSTED_NUM_FS < MIN_ADJUSTING_INTERVAL ||
        NUM_FS < MIN_NUM_FS) {
        return;
    }
**/

    double mean = FS_TOTAL_KINSHIP_COEFFICIENTS / NUM_FS;
    double shift = mean / PO_FS_START_EXPECTED;

    if ( shift > 1){
	shift = 1;
	}
    std::cout << "Shifting factor is " << shift << std::endl;

    FOURTH_START = FOURTH_START_ORIGINAL * shift;
    THIRD_START = THIRD_START_ORIGINAL * shift;
    SECOND_START = SECOND_START_ORIGINAL * shift;
    PO_FS_START = PO_FS_START_ORIGINAL * shift;
    MZ_START = MZ_START_ORIGNAL * shift;
    FS_START = FS_START_ORIGINAL * shift;

    PREV_ADJUSTED_NUM_FS = NUM_FS;
}

max_stars_repo_name: ZhiGroup/RAFFI

max_issues_repo_name: ZhiGroup/RAFFI

max_forks_repo_name: ZhiGroup/RAFFI


text:
// Copyright DEWETRON GmbH 2019

#include "sdk_csv_utils.h"

#include <boost/algorithm/hex.hpp>

#include <algorithm>
#include <limits>
#include <cctype>
#include <cstdlib>
#include <sstream>

void ltrim(std::string& s)
{
    auto it = std::find_if(s.begin(), s.end(),
        [](char c) {
            return !isspace(c);
        });
    s.erase(s.begin(), it);
}

void rtrim(std::string& s)
{
    auto it = std::find_if(s.rbegin(), s.rend(),
        [](char c)
        {
            return !isspace(c);
        }
    );
    s.erase(it.base(), s.end());
}

void trim(std::string& s)
{
    ltrim(s);
    rtrim(s);
}

bool isSpace(const std::string& str)
{
    for (const auto& ch : str)
    {
        if (!isspace(ch))
        {
            return false;
        }
    }
    return true;
}

std::vector<std::string> CSVNumberReader::parseLine(std::istream& input)
{
    std::vector<std::string> r;
    char ch;
    std::string cur_field;
    while (input.get(ch))
    {
        switch (ch)
        {
            case '\n':
                r.push_back(std::move(cur_field));
                return r;
            case '\r':
                r.push_back(std::move(cur_field));
                if (input.peek() == '\n')
                {
                    input.get(ch);
                }
                return r;
            case ';':
            case ',':
                r.push_back(std::move(cur_field));
                cur_field.clear();
                break;
            default:
                cur_field.push_back(ch);
                break;
        }
    }
    if (!cur_field.empty())
    {
        r.push_back(std::move(cur_field));
    }
    return r;
}

bool CSVNumberReader::parse(std::istream& input)
{
    m_columns = 0;
    m_headers.clear();
    m_values.clear();

    bool success = true;
    while (input)
    {
        const auto& fields = parseLine(input);

        // skip empty lines
        if (fields.empty() || (fields.size() == 1 && isSpace(fields.front())))
        {
            continue;
        }

        m_columns = std::max(m_columns, fields.size());

        std::vector<double> values;
        bool all_valid = true;
        values.reserve(fields.size());
        for (const auto& field : fields)
        {
            char* endptr;
            double val = strtod(field.c_str(), &endptr);
            if (endptr == field.c_str())
            {
                values.push_back(std::numeric_limits<double>::quiet_NaN());
                if (!isSpace(field))
                {
                    all_valid = false;
                }
            }
            else
            {
                values.push_back(val);
            }
        }
        if (all_valid)
        {
            m_values.push_back(std::move(values));
        }
        else
        {
            // we have no valid data => this is a header line
            if (m_values.empty() && m_headers.empty())
            {
                for (const auto& field : fields)
                {
                    std::string f = field;
                    trim(f);
                    m_headers.push_back(f);
                }
            }
            else
            {
                success = false;
                break;
            }
        }
    }
    return success;
}

std::vector<std::string> tokenize(const std::string& str, const std::string& delimiters)
{
    std::vector<std::string> tokens;

    std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    std::string::size_type pos = str.find_first_of(delimiters, lastPos);

    while (std::string::npos != pos || std::string::npos != lastPos)
    {
        tokens.emplace_back(str.substr(lastPos, pos - lastPos));

        // skip delimiters
        lastPos = str.find_first_not_of(delimiters, pos);

        // find next begin
        pos = str.find_first_of(delimiters, lastPos);
    }

    return tokens;
}

std::vector<uint8_t> AsciiHexToBits(const std::string& input)
{
    std::vector<uint8_t> result;
    result.reserve(1 + (input.length() / 2));
    boost::algorithm::unhex(input, std::back_inserter(result));
    return result;
}

bool CSVMessageReader::parse(std::istream& input)
{
    m_headers.clear();
    m_values.clear();

    std::string line;
    auto line_count = 0u;
    while (input && std::getline(input, line))
    {
        ++line_count;
        const auto& fields = tokenize(line, ",; \t\r");

        // skip empty lines
        if (fields.empty() || (fields.size() == 1 && isSpace(fields.front())))
        {
            continue;
        }

        Entry entry;
        if (fields.size() >= 2)
        {
            char* endptr;
            entry.m_time = strtod(fields[0].c_str(), &endptr);
            auto is_valid = endptr != fields[0].c_str();

            if (is_valid)
            {
                std::for_each(fields.begin() + 1, fields.end(),
                    [&entry]
                    (const std::string& val)
                    {
                        auto v = AsciiHexToBits(val);
                        std::copy(v.begin(), v.end(), std::back_inserter(entry.m_message));
                    });
                m_values.emplace_back(entry);
            }
            else if (line_count == 1)
            {
                std::copy(fields.begin(), fields.end(), std::back_inserter(m_headers));
            }
        }
    }

    return (m_values.size() + 1 <= line_count);
}

max_stars_repo_name: HpLightcorner/OXYGEN-SDK

max_issues_repo_name: HpLightcorner/OXYGEN-SDK

max_forks_repo_name: HpLightcorner/OXYGEN-SDK


text:
/*!
@file
Defines `boost::hana::detail::minimal::Comparable`.

@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_DETAIL_MINIMAL_COMPARABLE_HPP
#define BOOST_HANA_DETAIL_MINIMAL_COMPARABLE_HPP

#include <boost/hana/comparable/equal_mcd.hpp>
#include <boost/hana/comparable/not_equal_mcd.hpp>
#include <boost/hana/core/datatype.hpp>

namespace boost { namespace hana {
namespace detail { namespace minimal {
    template <typename mcd = hana::Comparable::equal_mcd>
    struct Comparable { };

    template <typename mcd, typename = operators<hana::Comparable>>
    struct comparable_impl {
        int value;
        using hana_datatype = Comparable<mcd>;
    };

    template <typename mcd>
    struct make_comparable_impl {
        constexpr auto operator()(int i) const
        { return comparable_impl<mcd>{i}; }
    };

    template <typename mcd = hana::Comparable::equal_mcd>
    constexpr make_comparable_impl<mcd> comparable{};
}} // end namespace detail::minimal

template <>
struct Comparable::instance<
    detail::minimal::Comparable<Comparable::equal_mcd>,
    detail::minimal::Comparable<Comparable::equal_mcd>
> : Comparable::equal_mcd
{
    static constexpr bool equal_impl(
        detail::minimal::comparable_impl<Comparable::equal_mcd> x,
        detail::minimal::comparable_impl<Comparable::equal_mcd> y
    )
    { return x.value == y.value; }
};

template <>
struct Comparable::instance<
    detail::minimal::Comparable<Comparable::not_equal_mcd>,
    detail::minimal::Comparable<Comparable::not_equal_mcd>
> : Comparable::not_equal_mcd
{
    static constexpr bool not_equal_impl(
        detail::minimal::comparable_impl<Comparable::not_equal_mcd> x,
        detail::minimal::comparable_impl<Comparable::not_equal_mcd> y
    )
    { return x.value != y.value; }
};
}} // end namespace boost::hana

#endif // !BOOST_HANA_DETAIL_MINIMAL_COMPARABLE_HPP

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
//=======================================================================
// Copyright (c) 2014 Piotr Smulewicz
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "test_utils/sample_graph.hpp"

#include "paal/data_structures/facility_location/k_median_solution.hpp"
#include "paal/data_structures/voronoi/voronoi.hpp"
#include "paal/local_search/facility_location/facility_location_solution_adapter.hpp"

#include <boost/test/unit_test.hpp>

using namespace paal::data_structures;
using namespace paal::local_search;

BOOST_AUTO_TEST_CASE(k_median_solutionAdapterTest) {
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();

    const int k = 2;
    typedef voronoi<decltype(gm)> voronoi;
    typedef paal::data_structures::voronoi_traits<voronoi> VT;
    typedef typename VT::GeneratorsSet GSet;
    typedef typename VT::VerticesSet VSet;
    voronoi vor(GSet{ SGM::A, SGM::B },
                VSet{ SGM::A, SGM::B, SGM::C, SGM::D, SGM::E }, gm);

    typedef paal::data_structures::k_median_solution<voronoi> Sol;

    Sol sol(std::move(vor), GSet{ SGM::C, SGM::D, SGM::E }, k);
    facility_location_solution_adapter<Sol> sa(sol);
    auto &realSol = sa.getfacility_location_solution();

    realSol.add_facility(SGM::C);
    realSol.rem_facility(SGM::A);
    realSol.add_facility(SGM::A);
    realSol.rem_facility(SGM::C);
    realSol.add_facility(SGM::D);
    realSol.rem_facility(SGM::A);
}

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
#pragma once

#include "textureInfo.hpp"
#include <string>
#include <boost/serialization/access.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/version.hpp>

class Texture
{
public:
    explicit Texture(const TextureInfo &textureInfo);
    const std::string &getName() const;
    const std::string &getFilename() const;
    int getWidth() const;
    int getHeight() const;
    int getTileWidth() const;
    int getTileHeight() const;
    float getTileWidthGL() const;
    float getTileHeightGL() const;
    TextureInfo getTextureInfo() const;
    void setName(const std::string &name);
    void setFilename(const std::string &filename);
    void setWidth(int value);
    void setHeight(int value);
    void setTileWidth(int value);
    void setTileHeight(int value);
private:
    friend class boost::serialization::access;
    std::string name;
    std::string filename;
    int width;
    int height;
    int tileWidth;
    int tileHeight;
    float tileWidthGL;
    float tileHeightGL;
    void updateTileWidthGL();
    void updateTileHeightGL();
    Texture() {}; //Needed for deserialization
    //Serialization method
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        /*if(version > 0)
            ar & name;*/
        ar & name;
        ar & filename;
        ar & width;
        ar & height;
        ar & tileWidth;
        ar & tileHeight;
        ar & tileWidthGL;
        ar & tileHeightGL;
    }
};
BOOST_CLASS_VERSION(Texture, 0)

max_stars_repo_name: jeremydumais/TheWarrior

max_issues_repo_name: jeremydumais/TheWarrior

max_forks_repo_name: jeremydumais/TheWarrior


text:
#include "stdafx.h"
#include "../Paragraph.h"
#include "CommandManagerMock.h"
#include <boost/test/tools/output_test_stream.hpp>

BOOST_AUTO_TEST_SUITE(CParagraph)
	BOOST_AUTO_TEST_CASE(can_set_text_and_then_undo_and_then_redo_that_command)
	{
		boost::test_tools::output_test_stream output;
		CommandManagerMock manager(output);

		Paragraph paragraph("hello", manager);
		BOOST_CHECK_EQUAL(paragraph.GetText(), "hello");

		paragraph.SetText("world");
		BOOST_CHECK(output.is_equal("Command executed"));
		BOOST_CHECK_EQUAL(paragraph.GetText(), "world");

		manager.Undo();
		BOOST_CHECK(output.is_equal("Command unexecuted"));
		BOOST_CHECK_EQUAL(paragraph.GetText(), "hello");

		manager.Redo();
		BOOST_CHECK(output.is_equal("Command reexecuted"));
		BOOST_CHECK_EQUAL(paragraph.GetText(), "world");
	}
BOOST_AUTO_TEST_SUITE_END()