<commit_before>// Copyright (c) 2014 Jrmy Ansel
// Licensed under the MIT license. See LICENSE.txt

#include "common.h"
#include "DeviceResources.h"
#include "Direct3DTexture.h"
#include "TextureSurface.h"
#include "MipmapSurface.h"
#include <comdef.h>

char* convertFormat(char* src, DWORD width, DWORD height, DXGI_FORMAT format)
{
	int length = width * height;
	char* buffer = new char[length * 4];

	if (format == DXGI_FORMAT_B8G8R8A8_UNORM)
	{
		memcpy(buffer, src, length * 4);
	}
	else if (format == DXGI_FORMAT_B4G4R4A4_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB4G4R4A4toB8G8R8A8(color16);
		}
	}
	else if (format == DXGI_FORMAT_B5G5R5A1_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB5G5R5A1toB8G8R8A8(color16);
		}
	}
	else if (format == DXGI_FORMAT_B5G6R5_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB5G6R5toB8G8R8A8(color16);
		}
	}
	else
	{
		memset(buffer, 0, length * 4);
	}

	return buffer;
}

Direct3DTexture::Direct3DTexture(DeviceResources* deviceResources, TextureSurface* surface)
{
	this->_refCount = 1;
	this->_deviceResources = deviceResources;

	this->_surface = surface;
}

Direct3DTexture::~Direct3DTexture()
{
}

HRESULT Direct3DTexture::QueryInterface(
	REFIID riid,
	LPVOID* obp
	)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tE_NOINTERFACE");
	LogText(str.str());
#endif

	return E_NOINTERFACE;
}

ULONG Direct3DTexture::AddRef()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	this->_refCount++;

#if LOGGER
	str.str("");
	str << "\t" << this->_refCount;
	LogText(str.str());
#endif

	return this->_refCount;
}

ULONG Direct3DTexture::Release()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	this->_refCount--;

#if LOGGER
	str.str("");
	str << "\t" << this->_refCount;
	LogText(str.str());
#endif

	if (this->_refCount == 0)
	{
		delete this;
		return 0;
	}

	return this->_refCount;
}

HRESULT Direct3DTexture::Initialize(
	LPDIRECT3DDEVICE lpD3DDevice,
	LPDIRECTDRAWSURFACE lpDDSurface)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}

HRESULT Direct3DTexture::GetHandle(
	LPDIRECT3DDEVICE lpDirect3DDevice,
	LPD3DTEXTUREHANDLE lpHandle)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	if (lpHandle == nullptr)
	{
#if LOGGER
		str.str("\tDDERR_INVALIDPARAMS");
		LogText(str.str());
#endif

		return DDERR_INVALIDPARAMS;
	}

	*lpHandle = (D3DTEXTUREHANDLE)this;

	return D3D_OK;
}

HRESULT Direct3DTexture::PaletteChanged(
	DWORD dwStart,
	DWORD dwCount)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}

HRESULT Direct3DTexture::Load(
	LPDIRECT3DTEXTURE lpD3DTexture)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	str << " " << lpD3DTexture;
	LogText(str.str());
#endif

	if (lpD3DTexture == nullptr)
	{
#if LOGGER
		str.str("\tDDERR_INVALIDPARAMS");
		LogText(str.str());
#endif

		return DDERR_INVALIDPARAMS;
	}

	Direct3DTexture* d3dTexture = (Direct3DTexture*)lpD3DTexture;
	TextureSurface* surface = d3dTexture->_surface;

	if (d3dTexture->_textureView)
	{
#if LOGGER
		str.str("\tretrieve existing texture");
		LogText(str.str());
#endif

		*&this->_textureView = d3dTexture->_textureView.Get();
		this->_textureView->AddRef();
		return D3D_OK;
	}

#if LOGGER
	str.str("\tcreate new texture");
	LogText(str.str());
#endif

#if LOGGER
	str.str("");
	str << "\t" << surface->_pixelFormat.dwRGBBitCount;
	str << " " << (void*)surface->_pixelFormat.dwRBitMask;
	str << " " << (void*)surface->_pixelFormat.dwGBitMask;
	str << " " << (void*)surface->_pixelFormat.dwBBitMask;
	str << " " << (void*)surface->_pixelFormat.dwRGBAlphaBitMask;
	LogText(str.str());
#endif

	DWORD bpp = surface->_pixelFormat.dwRGBBitCount == 32 ? 4 : 2;

	DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;

	if (bpp == 4)
	{
		format = DXGI_FORMAT_B8G8R8A8_UNORM;
	}
	else
	{
		DWORD alpha = surface->_pixelFormat.dwRGBAlphaBitMask;

		if (alpha == 0x0000F000)
		{
			format = DXGI_FORMAT_B4G4R4A4_UNORM;
		}
		else if (alpha == 0x00008000)
		{
			format = DXGI_FORMAT_B5G5R5A1_UNORM;
		}
		else
		{
			format = DXGI_FORMAT_B5G6R5_UNORM;
		}
	}

	D3D11_TEXTURE2D_DESC textureDesc;
	textureDesc.Width = surface->_width;
	textureDesc.Height = surface->_height;
	textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	textureDesc.Usage = D3D11_USAGE_IMMUTABLE;
	textureDesc.CPUAccessFlags = 0;
	textureDesc.MiscFlags = 0;
	textureDesc.MipLevels = surface->_mipmapCount;
	textureDesc.ArraySize = 1;
	textureDesc.SampleDesc.Count = 1;
	textureDesc.SampleDesc.Quality = 0;
	textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

	D3D11_SUBRESOURCE_DATA* textureData = new D3D11_SUBRESOURCE_DATA[textureDesc.MipLevels];
	char** buffers = new char*[textureDesc.MipLevels];

	buffers[0] = convertFormat(surface->_buffer, surface->_width, surface->_height, format);

	textureData[0].pSysMem = buffers[0];
	textureData[0].SysMemPitch = surface->_width * 4;
	textureData[0].SysMemSlicePitch = 0;

	MipmapSurface* mipmap = surface->_mipmap;
	for (DWORD i = 1; i < textureDesc.MipLevels; i++)
	{
		buffers[i] = convertFormat(mipmap->_buffer, mipmap->_width, mipmap->_height, format);

		textureData[i].pSysMem = buffers[i];
		textureData[i].SysMemPitch = mipmap->_width * 4;
		textureData[i].SysMemSlicePitch = 0;

		mipmap = mipmap->_mipmap;
	}

	ComPtr<ID3D11Texture2D> texture;
	HRESULT hr = this->_deviceResources->_d3dDevice->CreateTexture2D(&textureDesc, textureData, &texture);

	for (DWORD i = 0; i < textureDesc.MipLevels; i++)
	{
		delete[] buffers[i];
	}

	delete[] buffers;
	delete[] textureData;

	if (FAILED(hr))
	{
		static bool messageShown = false;

		if (!messageShown)
		{
			MessageBox(nullptr, _com_error(hr).ErrorMessage(), __FUNCTION__, MB_ICONERROR);
		}

		messageShown = true;

#if LOGGER
		str.str("\tD3DERR_TEXTURE_LOAD_FAILED");
		LogText(str.str());
#endif

		return D3DERR_TEXTURE_LOAD_FAILED;
	}

	D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc{};
	textureViewDesc.Format = textureDesc.Format;
	textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	textureViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
	textureViewDesc.Texture2D.MostDetailedMip = 0;

	if (FAILED(this->_deviceResources->_d3dDevice->CreateShaderResourceView(texture, &textureViewDesc, &d3dTexture->_textureView)))
	{
#if LOGGER
		str.str("\tD3DERR_TEXTURE_LOAD_FAILED");
		LogText(str.str());
#endif

		return D3DERR_TEXTURE_LOAD_FAILED;
	}

	*&this->_textureView = d3dTexture->_textureView.Get();
	this->_textureView->AddRef();

	return D3D_OK;
}

HRESULT Direct3DTexture::Unload()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}
<commit_msg>Add support for 16-bpp in texture loading<commit_after>// Copyright (c) 2014 Jrmy Ansel
// Licensed under the MIT license. See LICENSE.txt

#include "common.h"
#include "DeviceResources.h"
#include "Direct3DTexture.h"
#include "TextureSurface.h"
#include "MipmapSurface.h"
#include <comdef.h>

char* convertFormat(char* src, DWORD width, DWORD height, DXGI_FORMAT format)
{
	int length = width * height;
	char* buffer = new char[length * 4];

	if (format == DXGI_FORMAT_B8G8R8A8_UNORM)
	{
		memcpy(buffer, src, length * 4);
	}
	else if (format == DXGI_FORMAT_B4G4R4A4_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB4G4R4A4toB8G8R8A8(color16);
		}
	}
	else if (format == DXGI_FORMAT_B5G5R5A1_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB5G5R5A1toB8G8R8A8(color16);
		}
	}
	else if (format == DXGI_FORMAT_B5G6R5_UNORM)
	{
		unsigned short* srcBuffer = (unsigned short*)src;
		unsigned int* destBuffer = (unsigned int*)buffer;

		for (int i = 0; i < length; ++i)
		{
			unsigned short color16 = srcBuffer[i];

			destBuffer[i] = convertColorB5G6R5toB8G8R8A8(color16);
		}
	}
	else
	{
		memset(buffer, 0, length * 4);
	}

	return buffer;
}

Direct3DTexture::Direct3DTexture(DeviceResources* deviceResources, TextureSurface* surface)
{
	this->_refCount = 1;
	this->_deviceResources = deviceResources;

	this->_surface = surface;
}

Direct3DTexture::~Direct3DTexture()
{
}

HRESULT Direct3DTexture::QueryInterface(
	REFIID riid,
	LPVOID* obp
	)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tE_NOINTERFACE");
	LogText(str.str());
#endif

	return E_NOINTERFACE;
}

ULONG Direct3DTexture::AddRef()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	this->_refCount++;

#if LOGGER
	str.str("");
	str << "\t" << this->_refCount;
	LogText(str.str());
#endif

	return this->_refCount;
}

ULONG Direct3DTexture::Release()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	this->_refCount--;

#if LOGGER
	str.str("");
	str << "\t" << this->_refCount;
	LogText(str.str());
#endif

	if (this->_refCount == 0)
	{
		delete this;
		return 0;
	}

	return this->_refCount;
}

HRESULT Direct3DTexture::Initialize(
	LPDIRECT3DDEVICE lpD3DDevice,
	LPDIRECTDRAWSURFACE lpDDSurface)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}

HRESULT Direct3DTexture::GetHandle(
	LPDIRECT3DDEVICE lpDirect3DDevice,
	LPD3DTEXTUREHANDLE lpHandle)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

	if (lpHandle == nullptr)
	{
#if LOGGER
		str.str("\tDDERR_INVALIDPARAMS");
		LogText(str.str());
#endif

		return DDERR_INVALIDPARAMS;
	}

	*lpHandle = (D3DTEXTUREHANDLE)this;

	return D3D_OK;
}

HRESULT Direct3DTexture::PaletteChanged(
	DWORD dwStart,
	DWORD dwCount)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}

HRESULT Direct3DTexture::Load(
	LPDIRECT3DTEXTURE lpD3DTexture)
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	str << " " << lpD3DTexture;
	LogText(str.str());
#endif

	if (lpD3DTexture == nullptr)
	{
#if LOGGER
		str.str("\tDDERR_INVALIDPARAMS");
		LogText(str.str());
#endif

		return DDERR_INVALIDPARAMS;
	}

	Direct3DTexture* d3dTexture = (Direct3DTexture*)lpD3DTexture;
	TextureSurface* surface = d3dTexture->_surface;

	if (d3dTexture->_textureView)
	{
#if LOGGER
		str.str("\tretrieve existing texture");
		LogText(str.str());
#endif

		*&this->_textureView = d3dTexture->_textureView.Get();
		this->_textureView->AddRef();
		return D3D_OK;
	}

#if LOGGER
	str.str("\tcreate new texture");
	LogText(str.str());
#endif

#if LOGGER
	str.str("");
	str << "\t" << surface->_pixelFormat.dwRGBBitCount;
	str << " " << (void*)surface->_pixelFormat.dwRBitMask;
	str << " " << (void*)surface->_pixelFormat.dwGBitMask;
	str << " " << (void*)surface->_pixelFormat.dwBBitMask;
	str << " " << (void*)surface->_pixelFormat.dwRGBAlphaBitMask;
	LogText(str.str());
#endif

	DWORD bpp = surface->_pixelFormat.dwRGBBitCount == 32 ? 4 : 2;

	DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;

	if (bpp == 4)
	{
		format = DXGI_FORMAT_B8G8R8A8_UNORM;
	}
	else
	{
		DWORD alpha = surface->_pixelFormat.dwRGBAlphaBitMask;

		if (alpha == 0x0000F000)
		{
			format = DXGI_FORMAT_B4G4R4A4_UNORM;
		}
		else if (alpha == 0x00008000)
		{
			format = DXGI_FORMAT_B5G5R5A1_UNORM;
		}
		else
		{
			format = DXGI_FORMAT_B5G6R5_UNORM;
		}
	}

	D3D11_TEXTURE2D_DESC textureDesc;
	textureDesc.Width = surface->_width;
	textureDesc.Height = surface->_height;
	textureDesc.Format = this->_deviceResources->_are16BppTexturesSupported || format == DXGI_FORMAT_B8G8R8A8_UNORM ? format : DXGI_FORMAT_B8G8R8A8_UNORM;
	textureDesc.Usage = D3D11_USAGE_IMMUTABLE;
	textureDesc.CPUAccessFlags = 0;
	textureDesc.MiscFlags = 0;
	textureDesc.MipLevels = surface->_mipmapCount;
	textureDesc.ArraySize = 1;
	textureDesc.SampleDesc.Count = 1;
	textureDesc.SampleDesc.Quality = 0;
	textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

	D3D11_SUBRESOURCE_DATA* textureData = new D3D11_SUBRESOURCE_DATA[textureDesc.MipLevels];

	bool useBuffers = !this->_deviceResources->_are16BppTexturesSupported && format != DXGI_FORMAT_B8G8R8A8_UNORM;
	char** buffers = nullptr;

	if (useBuffers)
	{
		buffers = new char*[textureDesc.MipLevels];
		buffers[0] = convertFormat(surface->_buffer, surface->_width, surface->_height, format);
	}

	textureData[0].pSysMem = useBuffers ? buffers[0] : surface->_buffer;
	textureData[0].SysMemPitch = surface->_width * (useBuffers ? 4 : bpp);
	textureData[0].SysMemSlicePitch = 0;

	MipmapSurface* mipmap = surface->_mipmap;
	for (DWORD i = 1; i < textureDesc.MipLevels; i++)
	{
		if (useBuffers)
		{
			buffers[i] = convertFormat(mipmap->_buffer, mipmap->_width, mipmap->_height, format);
		}

		textureData[i].pSysMem = useBuffers ? buffers[i] : mipmap->_buffer;
		textureData[i].SysMemPitch = mipmap->_width * (useBuffers ? 4 : bpp);
		textureData[i].SysMemSlicePitch = 0;

		mipmap = mipmap->_mipmap;
	}

	ComPtr<ID3D11Texture2D> texture;
	HRESULT hr = this->_deviceResources->_d3dDevice->CreateTexture2D(&textureDesc, textureData, &texture);

	if (useBuffers)
	{
		for (DWORD i = 0; i < textureDesc.MipLevels; i++)
		{
			delete[] buffers[i];
		}

		delete[] buffers;
	}

	delete[] textureData;

	if (FAILED(hr))
	{
		static bool messageShown = false;

		if (!messageShown)
		{
			MessageBox(nullptr, _com_error(hr).ErrorMessage(), __FUNCTION__, MB_ICONERROR);
		}

		messageShown = true;

#if LOGGER
		str.str("\tD3DERR_TEXTURE_LOAD_FAILED");
		LogText(str.str());
#endif

		return D3DERR_TEXTURE_LOAD_FAILED;
	}

	D3D11_SHADER_RESOURCE_VIEW_DESC textureViewDesc{};
	textureViewDesc.Format = textureDesc.Format;
	textureViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	textureViewDesc.Texture2D.MipLevels = textureDesc.MipLevels;
	textureViewDesc.Texture2D.MostDetailedMip = 0;

	if (FAILED(this->_deviceResources->_d3dDevice->CreateShaderResourceView(texture, &textureViewDesc, &d3dTexture->_textureView)))
	{
#if LOGGER
		str.str("\tD3DERR_TEXTURE_LOAD_FAILED");
		LogText(str.str());
#endif

		return D3DERR_TEXTURE_LOAD_FAILED;
	}

	*&this->_textureView = d3dTexture->_textureView.Get();
	this->_textureView->AddRef();

	return D3D_OK;
}

HRESULT Direct3DTexture::Unload()
{
#if LOGGER
	std::ostringstream str;
	str << this << " " << __FUNCTION__;
	LogText(str.str());
#endif

#if LOGGER
	str.str("\tDDERR_UNSUPPORTED");
	LogText(str.str());
#endif

	return DDERR_UNSUPPORTED;
}
<|endoftext|>


<commit_before>#include "util.h"
#include <cstdarg>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>

int64_t currentTime()
{
  struct timeval tv;
  gettimeofday(&tv, 0);
  return tv.tv_sec * 1000000l + tv.tv_usec;
}

int parseCmdLineSimple(int argc, char** argv, const char* fmt, ...)
{
  int nArgs = strlen(fmt);
  if( argc != 1 + nArgs )
  {
    printf("parseCmdLineSimple: expected %d arguments, got %d\n", nArgs, argc);
    exit(1);
  }

  va_list args;
  va_start(args, fmt);
  int iArg = 1;
  for( const char *f = fmt; *f; ++f )
  {
    switch( *f )
    {
      case 's': *(va_arg(args, char**)) = strdup(argv[iArg]); break;
      default:
        printf("parseCmdLineSimple: bad format character '%c'\n", *f);
        exit(1);
    }
    ++iArg;
  }
  va_end(args);
  return 1;
}

<commit_msg>adding integer argument parsing<commit_after>#include "util.h"
#include <cstdarg>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>

int64_t currentTime()
{
  struct timeval tv;
  gettimeofday(&tv, 0);
  return tv.tv_sec * 1000000l + tv.tv_usec;
}

int parseCmdLineSimple(int argc, char** argv, const char* fmt, ...)
{
  int nArgs = strlen(fmt);
  if( argc != 1 + nArgs )
  {
    printf("parseCmdLineSimple: expected %d arguments, got %d\n", nArgs, argc);
    exit(1);
  }

  va_list args;
  va_start(args, fmt);
  int iArg = 1;
  for( const char *f = fmt; *f; ++f )
  {
    switch( *f )
    {
      case 's': *(va_arg(args, char**)) = strdup(argv[iArg]); break;
      case 'i': *(va_arg(args, int*))   = atoi(argv[iArg]); break;
      default:
        printf("parseCmdLineSimple: bad format character '%c'\n", *f);
        exit(1);
    }
    ++iArg;
  }
  va_end(args);
  return 1;
}

<|endoftext|>


<commit_before><commit_msg>Only select scalable fonts. Fixed-size fonts don't work with FT_Set_Char_Size in SkFontHost_FreeType.cpp.<commit_after><|endoftext|>


<commit_before>#include <openssl/aes.h>
#include <utils.h>
#include "Crypto.h"

Crypto::Crypto()
{
  m_encodeContext = EVP_CIPHER_CTX_new();
  m_decodeContext = EVP_CIPHER_CTX_new();
  EVP_CIPHER_CTX_init(m_encodeContext);
  EVP_CIPHER_CTX_init(m_decodeContext);
}

Crypto::~Crypto()
{
  EVP_CIPHER_CTX_free(m_encodeContext);
  EVP_CIPHER_CTX_free(m_decodeContext);
}

bool Crypto::init(const std::wstring& keydata)
{
  std::string l_keydata = StrWide2MB(keydata);
  int i, nrounds = 5;
  BYTE key[32], iv[32];

  /*
   * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
   * nrounds is the number of times the we hash the material. More rounds are more secure but
   * slower. Salt not used.
   */
  i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr,
                     (const unsigned char*)l_keydata.c_str(), l_keydata.size(),
                     nrounds, key, iv);
  if (i != 32) return false;

  EVP_CIPHER_CTX_cleanup(m_encodeContext);
  EVP_CIPHER_CTX_cleanup(m_decodeContext);
  EVP_CIPHER_CTX_init(m_encodeContext);
  EVP_CIPHER_CTX_init(m_decodeContext);
  EVP_EncryptInit_ex(m_encodeContext, EVP_aes_256_cbc(), nullptr, key, iv);
  EVP_DecryptInit_ex(m_decodeContext, EVP_aes_256_cbc(), nullptr, key, iv);

  return true;
}

void Crypto::encrypt(const std::vector<BYTE>& plain, std::vector<BYTE>& cipher)
{
  /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
  int c_len = plain.size() + AES_BLOCK_SIZE, f_len = 0;
  BYTE* ciphertext = new BYTE[c_len];

  /* allows reusing of 'e' for multiple encryption cycles */
  EVP_EncryptInit_ex(m_encodeContext, nullptr, nullptr, nullptr, nullptr);

  /* update ciphertext, c_len is filled with the length of ciphertext
     generated, *len is the size of plaintext in bytes */
  EVP_EncryptUpdate(m_encodeContext, ciphertext, &c_len, plain.data(),
                    plain.size());

  /* update ciphertext with the final remaining bytes */
  EVP_EncryptFinal_ex(m_encodeContext, ciphertext + c_len, &f_len);

  cipher.clear();
  for (int i = 0; i < c_len + f_len; i++) cipher.push_back(ciphertext[i]);
  delete[] ciphertext;
}

void Crypto::decrypt(const std::vector<BYTE>& cipher, std::vector<BYTE>& plain)
{
  /* plaintext will always be equal to or lesser than length of ciphertext*/
  int p_len = cipher.size(), f_len = 0;
  BYTE* plaintext = new BYTE[p_len];

  EVP_DecryptInit_ex(m_decodeContext, nullptr, nullptr, nullptr, nullptr);
  EVP_DecryptUpdate(m_decodeContext, plaintext, &p_len, cipher.data(),
                    cipher.size());
  EVP_DecryptFinal_ex(m_decodeContext, plaintext + p_len, &f_len);

  plain.clear();
  for (int i = 0; i < p_len + f_len; i++) plain.push_back(plaintext[i]);
  delete[] plaintext;
}
<commit_msg>Creation is an initialization.<commit_after>#include <openssl/aes.h>
#include <utils.h>
#include "Crypto.h"

Crypto::Crypto():
  m_encodeContext(nullptr),
  m_decodeContext(nullptr)
{
  m_encodeContext = EVP_CIPHER_CTX_new();
  m_decodeContext = EVP_CIPHER_CTX_new();
  EVP_CIPHER_CTX_init(m_encodeContext);
  EVP_CIPHER_CTX_init(m_decodeContext);
}

Crypto::~Crypto()
{
  EVP_CIPHER_CTX_free(m_encodeContext);
  EVP_CIPHER_CTX_free(m_decodeContext);
}

bool Crypto::init(const std::wstring& keydata)
{
  std::string l_keydata = StrWide2MB(keydata);
  int i, nrounds = 5;
  BYTE key[32], iv[32];

  /*
   * Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the supplied key material.
   * nrounds is the number of times the we hash the material. More rounds are more secure but
   * slower. Salt not used.
   */
  i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr,
                     (const unsigned char*)l_keydata.c_str(), l_keydata.size(),
                     nrounds, key, iv);
  if (i != 32) return false;

  EVP_CIPHER_CTX_cleanup(m_encodeContext);
  EVP_CIPHER_CTX_cleanup(m_decodeContext);
  EVP_CIPHER_CTX_init(m_encodeContext);
  EVP_CIPHER_CTX_init(m_decodeContext);
  EVP_EncryptInit_ex(m_encodeContext, EVP_aes_256_cbc(), nullptr, key, iv);
  EVP_DecryptInit_ex(m_decodeContext, EVP_aes_256_cbc(), nullptr, key, iv);

  return true;
}

void Crypto::encrypt(const std::vector<BYTE>& plain, std::vector<BYTE>& cipher)
{
  /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
  int c_len = plain.size() + AES_BLOCK_SIZE, f_len = 0;
  BYTE* ciphertext = new BYTE[c_len];

  /* allows reusing of 'e' for multiple encryption cycles */
  EVP_EncryptInit_ex(m_encodeContext, nullptr, nullptr, nullptr, nullptr);

  /* update ciphertext, c_len is filled with the length of ciphertext
     generated, *len is the size of plaintext in bytes */
  EVP_EncryptUpdate(m_encodeContext, ciphertext, &c_len, plain.data(),
                    plain.size());

  /* update ciphertext with the final remaining bytes */
  EVP_EncryptFinal_ex(m_encodeContext, ciphertext + c_len, &f_len);

  cipher.clear();
  for (int i = 0; i < c_len + f_len; i++) cipher.push_back(ciphertext[i]);
  delete[] ciphertext;
}

void Crypto::decrypt(const std::vector<BYTE>& cipher, std::vector<BYTE>& plain)
{
  /* plaintext will always be equal to or lesser than length of ciphertext*/
  int p_len = cipher.size(), f_len = 0;
  BYTE* plaintext = new BYTE[p_len];

  EVP_DecryptInit_ex(m_decodeContext, nullptr, nullptr, nullptr, nullptr);
  EVP_DecryptUpdate(m_decodeContext, plaintext, &p_len, cipher.data(),
                    cipher.size());
  EVP_DecryptFinal_ex(m_decodeContext, plaintext + p_len, &f_len);

  plain.clear();
  for (int i = 0; i < p_len + f_len; i++) plain.push_back(plaintext[i]);
  delete[] plaintext;
}
<|endoftext|>


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

#include "pck_packer.h"

#include "core/io/file_access_pack.h" // PACK_HEADER_MAGIC, PACK_FORMAT_VERSION
#include "core/os/file_access.h"
#include "core/version.h"

static uint64_t _align(uint64_t p_n, int p_alignment) {

	if (p_alignment == 0)
		return p_n;

	uint64_t rest = p_n % p_alignment;
	if (rest == 0)
		return p_n;
	else
		return p_n + (p_alignment - rest);
};

static void _pad(FileAccess *p_file, int p_bytes) {

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

		p_file->store_8(0);
	};
};

void PCKPacker::_bind_methods() {

	ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start, DEFVAL(0));
	ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file);
	ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush, DEFVAL(false));
};

Error PCKPacker::pck_start(const String &p_file, int p_alignment) {

	file = FileAccess::open(p_file, FileAccess::WRITE);

	ERR_FAIL_COND_V_MSG(!file, ERR_CANT_CREATE, "Can't open file to write: " + String(p_file) + ".");

	alignment = p_alignment;

	file->store_32(PACK_HEADER_MAGIC);
	file->store_32(PACK_FORMAT_VERSION);
	file->store_32(VERSION_MAJOR);
	file->store_32(VERSION_MINOR);
	file->store_32(VERSION_PATCH);

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

		file->store_32(0); // reserved
	};

	files.clear();

	return OK;
};

Error PCKPacker::add_file(const String &p_file, const String &p_src) {

	FileAccess *f = FileAccess::open(p_src, FileAccess::READ);
	if (!f) {
		return ERR_FILE_CANT_OPEN;
	};

	File pf;
	pf.path = p_file;
	pf.src_path = p_src;
	pf.size = f->get_len();
	pf.offset_offset = 0;

	files.push_back(pf);

	f->close();
	memdelete(f);

	return OK;
};

Error PCKPacker::flush(bool p_verbose) {

	ERR_FAIL_COND_V_MSG(!file, ERR_INVALID_PARAMETER, "File must be opened before use.");

	// write the index

	file->store_32(files.size());

	for (int i = 0; i < files.size(); i++) {

		file->store_pascal_string(files[i].path);
		files.write[i].offset_offset = file->get_position();
		file->store_64(0); // offset
		file->store_64(files[i].size); // size

		// # empty md5
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
	};

	uint64_t ofs = file->get_position();
	ofs = _align(ofs, alignment);

	_pad(file, ofs - file->get_position());

	const uint32_t buf_max = 65536;
	uint8_t *buf = memnew_arr(uint8_t, buf_max);

	int count = 0;
	for (int i = 0; i < files.size(); i++) {

		FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ);
		uint64_t to_write = files[i].size;
		while (to_write > 0) {

			int read = src->get_buffer(buf, MIN(to_write, buf_max));
			file->store_buffer(buf, read);
			to_write -= read;
		};

		uint64_t pos = file->get_position();
		file->seek(files[i].offset_offset); // go back to store the file's offset
		file->store_64(ofs);
		file->seek(pos);

		ofs = _align(ofs + files[i].size, alignment);
		_pad(file, ofs - pos);

		src->close();
		memdelete(src);
		count += 1;
		if (p_verbose) {
			if (count % 100 == 0) {
				printf("%i/%i (%.2f)\r", count, files.size(), float(count) / files.size() * 100);
				fflush(stdout);
			};
		};
	};

	if (p_verbose)
		printf("\n");

	file->close();
	memdelete_arr(buf);

	return OK;
};

PCKPacker::PCKPacker() {

	file = NULL;
};

PCKPacker::~PCKPacker() {
	if (file != NULL) {
		memdelete(file);
	};
	file = NULL;
};
<commit_msg>Fixes leak when pck_start multiple times<commit_after>/*************************************************************************/
/*  pck_packer.cpp                                                       */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "pck_packer.h"

#include "core/io/file_access_pack.h" // PACK_HEADER_MAGIC, PACK_FORMAT_VERSION
#include "core/os/file_access.h"
#include "core/version.h"

static uint64_t _align(uint64_t p_n, int p_alignment) {

	if (p_alignment == 0)
		return p_n;

	uint64_t rest = p_n % p_alignment;
	if (rest == 0)
		return p_n;
	else
		return p_n + (p_alignment - rest);
};

static void _pad(FileAccess *p_file, int p_bytes) {

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

		p_file->store_8(0);
	};
};

void PCKPacker::_bind_methods() {

	ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start, DEFVAL(0));
	ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file);
	ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush, DEFVAL(false));
};

Error PCKPacker::pck_start(const String &p_file, int p_alignment) {

	if (file != NULL) {
		memdelete(file);
	}

	file = FileAccess::open(p_file, FileAccess::WRITE);

	ERR_FAIL_COND_V_MSG(!file, ERR_CANT_CREATE, "Can't open file to write: " + String(p_file) + ".");

	alignment = p_alignment;

	file->store_32(PACK_HEADER_MAGIC);
	file->store_32(PACK_FORMAT_VERSION);
	file->store_32(VERSION_MAJOR);
	file->store_32(VERSION_MINOR);
	file->store_32(VERSION_PATCH);

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

		file->store_32(0); // reserved
	};

	files.clear();

	return OK;
};

Error PCKPacker::add_file(const String &p_file, const String &p_src) {

	FileAccess *f = FileAccess::open(p_src, FileAccess::READ);
	if (!f) {
		return ERR_FILE_CANT_OPEN;
	};

	File pf;
	pf.path = p_file;
	pf.src_path = p_src;
	pf.size = f->get_len();
	pf.offset_offset = 0;

	files.push_back(pf);

	f->close();
	memdelete(f);

	return OK;
};

Error PCKPacker::flush(bool p_verbose) {

	ERR_FAIL_COND_V_MSG(!file, ERR_INVALID_PARAMETER, "File must be opened before use.");

	// write the index

	file->store_32(files.size());

	for (int i = 0; i < files.size(); i++) {

		file->store_pascal_string(files[i].path);
		files.write[i].offset_offset = file->get_position();
		file->store_64(0); // offset
		file->store_64(files[i].size); // size

		// # empty md5
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
	};

	uint64_t ofs = file->get_position();
	ofs = _align(ofs, alignment);

	_pad(file, ofs - file->get_position());

	const uint32_t buf_max = 65536;
	uint8_t *buf = memnew_arr(uint8_t, buf_max);

	int count = 0;
	for (int i = 0; i < files.size(); i++) {

		FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ);
		uint64_t to_write = files[i].size;
		while (to_write > 0) {

			int read = src->get_buffer(buf, MIN(to_write, buf_max));
			file->store_buffer(buf, read);
			to_write -= read;
		};

		uint64_t pos = file->get_position();
		file->seek(files[i].offset_offset); // go back to store the file's offset
		file->store_64(ofs);
		file->seek(pos);

		ofs = _align(ofs + files[i].size, alignment);
		_pad(file, ofs - pos);

		src->close();
		memdelete(src);
		count += 1;
		if (p_verbose) {
			if (count % 100 == 0) {
				printf("%i/%i (%.2f)\r", count, files.size(), float(count) / files.size() * 100);
				fflush(stdout);
			};
		};
	};

	if (p_verbose)
		printf("\n");

	file->close();
	memdelete_arr(buf);

	return OK;
};

PCKPacker::PCKPacker() {

	file = NULL;
};

PCKPacker::~PCKPacker() {
	if (file != NULL) {
		memdelete(file);
	};
	file = NULL;
};
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <gst/gst.h>
#include "ServerMethods.hpp"
#include <MediaSet.hpp>
#include <string>
#include <EventHandler.hpp>
#include <KurentoException.hpp>
#include <jsonrpc/JsonRpcUtils.hpp>
#include <jsonrpc/JsonRpcConstants.hpp>

#include <sstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#define GST_CAT_DEFAULT kurento_server_methods
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoServerMethods"

#define SESSION_ID "sessionId"
#define OBJECT "object"
#define SUBSCRIPTION "subscription"

#define REQUEST_TIMEOUT 20000 /* 20 seconds */

namespace kurento
{

ServerMethods::ServerMethods (const boost::property_tree::ptree &config) :
  config (config)
{
  // TODO: Use config to load more factories
  moduleManager.loadModulesFromDirectories ("");

  cache = std::shared_ptr<RequestCache> (new RequestCache (REQUEST_TIMEOUT) );

  handler.setPreProcess (std::bind (&ServerMethods::preProcess, this,
                                    std::placeholders::_1,
                                    std::placeholders::_2) );
  handler.setPostProcess (std::bind (&ServerMethods::postProcess, this,
                                     std::placeholders::_1,
                                     std::placeholders::_2) );

  handler.addMethod ("create", std::bind (&ServerMethods::create, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this,
                     std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("release", std::bind (&ServerMethods::release,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("ref", std::bind (&ServerMethods::ref,
                                       this, std::placeholders::_1,
                                       std::placeholders::_2) );
  handler.addMethod ("unref", std::bind (&ServerMethods::unref,
                                         this, std::placeholders::_1,
                                         std::placeholders::_2) );
  handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("describe", std::bind (&ServerMethods::describe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
}

ServerMethods::~ServerMethods()
{
}

static void
requireParams (const Json::Value &params)
{
  if (params == Json::Value::null) {
    throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                                  "'params' is requiered");
  }
}

static std::string
generateUUID ()
{
  std::stringstream ss;
  boost::uuids::uuid uuid = boost::uuids::random_generator() ();

  ss << uuid;

  return ss.str();
}

void
ServerMethods::process (const std::string &request, std::string &response)
{
  handler.process (request, response);
}

void
ServerMethods::keepAliveSession (const std::string &sessionId)
{
  MediaSet::getMediaSet()->keepAliveSession (sessionId);
}

bool
ServerMethods::preProcess (const Json::Value &request, Json::Value &response)
{
  std::string sessionId;
  std::string resp;
  int requestId;

  try {
    Json::Reader reader;
    Json::Value params;

    JsonRpc::getValue (request, JSON_RPC_ID, requestId);
    JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
    JsonRpc::getValue (params, SESSION_ID, sessionId);

    resp = cache->getCachedResponse (sessionId, requestId);

    GST_DEBUG ("Cached response: %s", resp.c_str() );

    /* update response with the one we got from cache */
    reader.parse (resp, response);

    return false;
  } catch (...) {
    /* continue processing */
    return true;
  }
}

void
ServerMethods::postProcess (const Json::Value &request, Json::Value &response)
{
  Json::FastWriter writer;
  std::string sessionId;
  std::string resp;
  int requestId;

  try {
    Json::Reader reader;

    JsonRpc::getValue (request, JSON_RPC_ID, requestId);

    try {
      Json::Value result;

      JsonRpc::getValue (response, JSON_RPC_RESULT, result);
      JsonRpc::getValue (result, SESSION_ID, sessionId);
    } catch (JsonRpc::CallException &ex) {
      Json::Value params;

      JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
      JsonRpc::getValue (params, SESSION_ID, sessionId);
    }

    /* CacheException will be triggered if this response is not cached */
    cache->getCachedResponse (sessionId, requestId);
  } catch (JsonRpc::CallException &e) {
    /* We could not get some of the required parameters. Ignore */
  } catch (CacheException &e) {
    /* Cache response */
    resp = writer.write (response);

    GST_DEBUG ("Caching: %s", resp.c_str() );
    cache->addResponse (sessionId, requestId, resp);
  }
}

void
ServerMethods::describe (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string subscription;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }

  response[SESSION_ID] = sessionId;
  response["type"] = obj->getType ();
}

void
ServerMethods::keepAlive (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->keepAliveSession (sessionId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::release (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    MediaSet::getMediaSet()->release (objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::ref (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string objectId;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->ref (sessionId, objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::unref (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string objectId;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->unref (sessionId, objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response)
{
  std::string subscription;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SUBSCRIPTION, subscription);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  MediaSet::getMediaSet()->removeEventHandler (sessionId, objectId, subscription);
}

void
ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                     const std::string &sessionId,
                                     const  std::string &subscriptionId,
                                     std::shared_ptr<EventHandler> handler)
{
  MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(),
      subscriptionId, handler);
}

std::string
ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                    const std::string &sessionId, const std::string &eventType,
                                    std::shared_ptr<EventHandler> handler)
{
  std::string subscriptionId;

  if (!obj->connect (eventType, handler) ) {
    throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
  }

  subscriptionId = generateUUID();

  registerEventHandler (obj, sessionId, subscriptionId, handler);

  return subscriptionId;
}

void
ServerMethods::subscribe (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string eventType;
  std::string handlerId;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, "type", eventType);
  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  try {
    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

    try {
      handlerId = eventSubscriptionHandler (obj, sessionId, eventType, params);
    } catch (std::bad_function_call &e) {
      throw KurentoException (NOT_IMPLEMENTED,
                              "Current transport does not support events");
    }

    if (handlerId == "") {
      throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
    }
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }

  response[SESSION_ID] = sessionId;
  response["value"] = handlerId;
}

void
ServerMethods::invoke (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string sessionId;
  std::string operation;
  Json::Value operationParams;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, "operation", operation);
  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    JsonRpc::getValue (params, "operationParams", operationParams);
  } catch (JsonRpc::CallException e) {
    /* operationParams is optional at this point */
  }

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  try {
    Json::Value value;

    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

    if (!obj) {
      throw KurentoException (MEDIA_OBJECT_NOT_FOUND, "Object not found");
    }

    obj->invoke (obj, operation, operationParams, value);

    response["value"] = value;
    response[SESSION_ID] = sessionId;
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::create (const Json::Value &params,
                       Json::Value &response)
{
  std::string type;
  std::shared_ptr<Factory> factory;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, "type", type);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  factory = moduleManager.getFactory (type);

  if (factory) {
    try {
      std::shared_ptr <MediaObjectImpl> object;

      object = std::dynamic_pointer_cast<MediaObjectImpl> (
                 factory->createObject (config, sessionId, params["constructorParams"]) );

      response["value"] = object->getId();
      response[SESSION_ID] = sessionId;
    } catch (KurentoException &ex) {
      Json::Value data;
      data["code"] = ex.getCode();
      data["message"] = ex.getMessage();

      JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                                ex.what(), data);
      throw e;
    }
  } else {
    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              "Class '" + type + "' does not exist");
    // TODO: Define error data and code
    throw e;
  }

}

ServerMethods::StaticConstructor ServerMethods::staticConstructor;

ServerMethods::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<commit_msg>Use environment variable KURENTO_MODULES_PATH to load plugins<commit_after>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <gst/gst.h>
#include "ServerMethods.hpp"
#include <MediaSet.hpp>
#include <string>
#include <EventHandler.hpp>
#include <KurentoException.hpp>
#include <jsonrpc/JsonRpcUtils.hpp>
#include <jsonrpc/JsonRpcConstants.hpp>

#include <sstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#define GST_CAT_DEFAULT kurento_server_methods
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoServerMethods"

#define SESSION_ID "sessionId"
#define OBJECT "object"
#define SUBSCRIPTION "subscription"

#define REQUEST_TIMEOUT 20000 /* 20 seconds */

static const std::string KURENTO_MODULES_PATH = "KURENTO_MODULES_PATH";

namespace kurento
{

ServerMethods::ServerMethods (const boost::property_tree::ptree &config) :
  config (config)
{
  std::string path;
  char *env_path = getenv (KURENTO_MODULES_PATH.c_str() );

  if (env_path != NULL) {
    path = env_path;
  }

  moduleManager.loadModulesFromDirectories (path);

  cache = std::shared_ptr<RequestCache> (new RequestCache (REQUEST_TIMEOUT) );

  handler.setPreProcess (std::bind (&ServerMethods::preProcess, this,
                                    std::placeholders::_1,
                                    std::placeholders::_2) );
  handler.setPostProcess (std::bind (&ServerMethods::postProcess, this,
                                     std::placeholders::_1,
                                     std::placeholders::_2) );

  handler.addMethod ("create", std::bind (&ServerMethods::create, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this,
                     std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("release", std::bind (&ServerMethods::release,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("ref", std::bind (&ServerMethods::ref,
                                       this, std::placeholders::_1,
                                       std::placeholders::_2) );
  handler.addMethod ("unref", std::bind (&ServerMethods::unref,
                                         this, std::placeholders::_1,
                                         std::placeholders::_2) );
  handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("describe", std::bind (&ServerMethods::describe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
}

ServerMethods::~ServerMethods()
{
}

static void
requireParams (const Json::Value &params)
{
  if (params == Json::Value::null) {
    throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                                  "'params' is requiered");
  }
}

static std::string
generateUUID ()
{
  std::stringstream ss;
  boost::uuids::uuid uuid = boost::uuids::random_generator() ();

  ss << uuid;

  return ss.str();
}

void
ServerMethods::process (const std::string &request, std::string &response)
{
  handler.process (request, response);
}

void
ServerMethods::keepAliveSession (const std::string &sessionId)
{
  MediaSet::getMediaSet()->keepAliveSession (sessionId);
}

bool
ServerMethods::preProcess (const Json::Value &request, Json::Value &response)
{
  std::string sessionId;
  std::string resp;
  int requestId;

  try {
    Json::Reader reader;
    Json::Value params;

    JsonRpc::getValue (request, JSON_RPC_ID, requestId);
    JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
    JsonRpc::getValue (params, SESSION_ID, sessionId);

    resp = cache->getCachedResponse (sessionId, requestId);

    GST_DEBUG ("Cached response: %s", resp.c_str() );

    /* update response with the one we got from cache */
    reader.parse (resp, response);

    return false;
  } catch (...) {
    /* continue processing */
    return true;
  }
}

void
ServerMethods::postProcess (const Json::Value &request, Json::Value &response)
{
  Json::FastWriter writer;
  std::string sessionId;
  std::string resp;
  int requestId;

  try {
    Json::Reader reader;

    JsonRpc::getValue (request, JSON_RPC_ID, requestId);

    try {
      Json::Value result;

      JsonRpc::getValue (response, JSON_RPC_RESULT, result);
      JsonRpc::getValue (result, SESSION_ID, sessionId);
    } catch (JsonRpc::CallException &ex) {
      Json::Value params;

      JsonRpc::getValue (request, JSON_RPC_PARAMS, params);
      JsonRpc::getValue (params, SESSION_ID, sessionId);
    }

    /* CacheException will be triggered if this response is not cached */
    cache->getCachedResponse (sessionId, requestId);
  } catch (JsonRpc::CallException &e) {
    /* We could not get some of the required parameters. Ignore */
  } catch (CacheException &e) {
    /* Cache response */
    resp = writer.write (response);

    GST_DEBUG ("Caching: %s", resp.c_str() );
    cache->addResponse (sessionId, requestId, resp);
  }
}

void
ServerMethods::describe (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string subscription;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }

  response[SESSION_ID] = sessionId;
  response["type"] = obj->getType ();
}

void
ServerMethods::keepAlive (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->keepAliveSession (sessionId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::release (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    MediaSet::getMediaSet()->release (objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::ref (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string objectId;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->ref (sessionId, objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::unref (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string subscription;
  std::string objectId;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  try {
    MediaSet::getMediaSet()->unref (sessionId, objectId);
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response)
{
  std::string subscription;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, OBJECT, objectId);
  JsonRpc::getValue (params, SUBSCRIPTION, subscription);
  JsonRpc::getValue (params, SESSION_ID, sessionId);

  MediaSet::getMediaSet()->removeEventHandler (sessionId, objectId, subscription);
}

void
ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                     const std::string &sessionId,
                                     const  std::string &subscriptionId,
                                     std::shared_ptr<EventHandler> handler)
{
  MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(),
      subscriptionId, handler);
}

std::string
ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                    const std::string &sessionId, const std::string &eventType,
                                    std::shared_ptr<EventHandler> handler)
{
  std::string subscriptionId;

  if (!obj->connect (eventType, handler) ) {
    throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
  }

  subscriptionId = generateUUID();

  registerEventHandler (obj, sessionId, subscriptionId, handler);

  return subscriptionId;
}

void
ServerMethods::subscribe (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string eventType;
  std::string handlerId;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, "type", eventType);
  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  try {
    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

    try {
      handlerId = eventSubscriptionHandler (obj, sessionId, eventType, params);
    } catch (std::bad_function_call &e) {
      throw KurentoException (NOT_IMPLEMENTED,
                              "Current transport does not support events");
    }

    if (handlerId == "") {
      throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
    }
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }

  response[SESSION_ID] = sessionId;
  response["value"] = handlerId;
}

void
ServerMethods::invoke (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObjectImpl> obj;
  std::string sessionId;
  std::string operation;
  Json::Value operationParams;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, "operation", operation);
  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    JsonRpc::getValue (params, "operationParams", operationParams);
  } catch (JsonRpc::CallException e) {
    /* operationParams is optional at this point */
  }

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  try {
    Json::Value value;

    obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId);

    if (!obj) {
      throw KurentoException (MEDIA_OBJECT_NOT_FOUND, "Object not found");
    }

    obj->invoke (obj, operation, operationParams, value);

    response["value"] = value;
    response[SESSION_ID] = sessionId;
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }
}

void
ServerMethods::create (const Json::Value &params,
                       Json::Value &response)
{
  std::string type;
  std::shared_ptr<Factory> factory;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, "type", type);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  factory = moduleManager.getFactory (type);

  if (factory) {
    try {
      std::shared_ptr <MediaObjectImpl> object;

      object = std::dynamic_pointer_cast<MediaObjectImpl> (
                 factory->createObject (config, sessionId, params["constructorParams"]) );

      response["value"] = object->getId();
      response[SESSION_ID] = sessionId;
    } catch (KurentoException &ex) {
      Json::Value data;
      data["code"] = ex.getCode();
      data["message"] = ex.getMessage();

      JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                                ex.what(), data);
      throw e;
    }
  } else {
    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              "Class '" + type + "' does not exist");
    // TODO: Define error data and code
    throw e;
  }

}

ServerMethods::StaticConstructor ServerMethods::staticConstructor;

ServerMethods::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* kurento */
<|endoftext|>


<commit_before>#ifndef JEZUK_DOM_SimpleDOM_EVENT_IMPL_H
#define JEZUK_DOM_SimpleDOM_EVENT_IMPL_H

////////////////////////////
// C++ Event implementation
////////////////////////////

#include <DOM/Events/Event.hpp>
#include <DOM/DOMException.hpp>
#include <XML/XMLCharacterClasses.hpp>

#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN
#   define __UNDEF_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef __UNDEF_LEAN_AND_MEAN
#   undef WIN32_LEAN_AND_MEAN
#   undef __UNDEF_LEAN_AND_MEAN
# endif
#else
# include <sys/time.h>
#endif
//#include <iostream>

namespace Arabica
{
namespace SimpleDOM
{

////////////////////////////////////////////////////////////////////
template<class string_type, class string_adaptor_type> class EventTargetImpl;

template<class stringT, class string_adaptorT>
class EventImpl : virtual public Arabica::DOM::Events::Event_impl<stringT, string_adaptorT>
{
  public:
    typedef Arabica::DOM::Node_impl<stringT, string_adaptorT> DOMNode_implT;
    typedef Arabica::DOM::Text_impl<stringT, string_adaptorT> DOMText_implT;
    typedef Arabica::DOM::Document_impl<stringT, string_adaptorT> DOMDocument_implT;
    typedef Arabica::DOM::NamedNodeMap_impl<stringT, string_adaptorT> DOMNamedNodeMap_implT;
    typedef Arabica::DOM::NodeList_impl<stringT, string_adaptorT> DOMNodeList_implT;
    typedef Arabica::DOM::Events::Event<stringT, string_adaptorT> EventT;
    typedef Arabica::DOM::Events::EventTarget<stringT, string_adaptorT> EventTargetT;
    typedef EventImpl<stringT, string_adaptorT> EventImplT;

    EventImpl() : timeStamp_(0), stopped_(false), defaultsPrevented_(false), refCount_(0)
    {
        //std::cout << std::endl << "born " << this << std::endl;
        timeStamp_ = timeStamp();
    } // EventImpl

    virtual ~EventImpl()
    {
        //std::cout << std::endl << "die  " << this << std::endl;
    }

    virtual stringT getType() const
    {
      return type_;
    }

    virtual EventTargetT getTarget() const
    {
      return target_;
    }

    virtual EventTargetT getCurrentTarget() const
    {
      return currTarget_;
    }

    virtual typename EventT::Phase getEventPhase() const
    {
      return phase_;
    }

    virtual bool getBubbles() const
    {
      return canBubble_;
    }

    virtual bool getCancelable() const
    {
      return canCancel_;
    }

    virtual long getTimeStamp() const
    {
      return timeStamp_;
    }

    virtual void stopPropagation()
    {
      if (canCancel_)
        stopped_ = true;
    }

    virtual void preventDefault()
    {
      defaultsPrevented_ = true;
    }

    virtual void initEvent(const stringT& eventTypeArg, bool canBubble, bool cancelable)
    {
      type_ = eventTypeArg;
      canBubble_ = canBubble;
      canCancel_ = cancelable;
    }

    ///////////////////////////////////////////////////////
    // Ref counting
    virtual void addRef()
    {
      ++refCount_;
    } // addRef

    virtual void releaseRef()
    {
      if(--refCount_ == 0)
        delete this;
    } // releaseRef

  protected:

    virtual unsigned long long timeStamp()
    {
      unsigned long long time = 0;
#ifdef _WIN32
      FILETIME tv;
      GetSystemTimeAsFileTime(&tv);
      time = (((uint64_t) tv.dwHighDateTime) << 32) + tv.dwLowDateTime;
      time /= 10000;
#else
      struct timeval tv;
      gettimeofday(&tv, NULL);
      time += tv.tv_sec * 1000;
      time += tv.tv_usec / 1000;
#endif
      return time;
    }

    stringT type_;
    EventTargetT target_;
    EventTargetT currTarget_;
    typename EventT::Phase phase_;
    unsigned long long timeStamp_;
    bool canBubble_;
    bool canCancel_;
    bool stopped_;
    bool defaultsPrevented_;
    unsigned long refCount_;

    friend class EventTargetImpl<stringT, string_adaptorT>;
}; // class EventImpl

} // namespace SimpleDOM
} // namespace Arabica

#endif // JEZUK_DOM_SimpleDOM_EVENTTARGET_H
// end of file
<commit_msg>Replaced uint64_t by __int64 for better support on windows<commit_after>#ifndef JEZUK_DOM_SimpleDOM_EVENT_IMPL_H
#define JEZUK_DOM_SimpleDOM_EVENT_IMPL_H

////////////////////////////
// C++ Event implementation
////////////////////////////

#include <DOM/Events/Event.hpp>
#include <DOM/DOMException.hpp>
#include <XML/XMLCharacterClasses.hpp>

#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN
#   define __UNDEF_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef __UNDEF_LEAN_AND_MEAN
#   undef WIN32_LEAN_AND_MEAN
#   undef __UNDEF_LEAN_AND_MEAN
# endif
#else
# include <sys/time.h>
#endif
//#include <iostream>

namespace Arabica
{
namespace SimpleDOM
{

////////////////////////////////////////////////////////////////////
template<class string_type, class string_adaptor_type> class EventTargetImpl;

template<class stringT, class string_adaptorT>
class EventImpl : virtual public Arabica::DOM::Events::Event_impl<stringT, string_adaptorT>
{
  public:
    typedef Arabica::DOM::Node_impl<stringT, string_adaptorT> DOMNode_implT;
    typedef Arabica::DOM::Text_impl<stringT, string_adaptorT> DOMText_implT;
    typedef Arabica::DOM::Document_impl<stringT, string_adaptorT> DOMDocument_implT;
    typedef Arabica::DOM::NamedNodeMap_impl<stringT, string_adaptorT> DOMNamedNodeMap_implT;
    typedef Arabica::DOM::NodeList_impl<stringT, string_adaptorT> DOMNodeList_implT;
    typedef Arabica::DOM::Events::Event<stringT, string_adaptorT> EventT;
    typedef Arabica::DOM::Events::EventTarget<stringT, string_adaptorT> EventTargetT;
    typedef EventImpl<stringT, string_adaptorT> EventImplT;

    EventImpl() : timeStamp_(0), stopped_(false), defaultsPrevented_(false), refCount_(0)
    {
        //std::cout << std::endl << "born " << this << std::endl;
        timeStamp_ = timeStamp();
    } // EventImpl

    virtual ~EventImpl()
    {
        //std::cout << std::endl << "die  " << this << std::endl;
    }

    virtual stringT getType() const
    {
      return type_;
    }

    virtual EventTargetT getTarget() const
    {
      return target_;
    }

    virtual EventTargetT getCurrentTarget() const
    {
      return currTarget_;
    }

    virtual typename EventT::Phase getEventPhase() const
    {
      return phase_;
    }

    virtual bool getBubbles() const
    {
      return canBubble_;
    }

    virtual bool getCancelable() const
    {
      return canCancel_;
    }

    virtual long getTimeStamp() const
    {
      return timeStamp_;
    }

    virtual void stopPropagation()
    {
      if (canCancel_)
        stopped_ = true;
    }

    virtual void preventDefault()
    {
      defaultsPrevented_ = true;
    }

    virtual void initEvent(const stringT& eventTypeArg, bool canBubble, bool cancelable)
    {
      type_ = eventTypeArg;
      canBubble_ = canBubble;
      canCancel_ = cancelable;
    }

    ///////////////////////////////////////////////////////
    // Ref counting
    virtual void addRef()
    {
      ++refCount_;
    } // addRef

    virtual void releaseRef()
    {
      if(--refCount_ == 0)
        delete this;
    } // releaseRef

  protected:

    virtual unsigned long long timeStamp()
    {
      unsigned long long time = 0;
#ifdef _WIN32
      FILETIME tv;
      GetSystemTimeAsFileTime(&tv);
      time = (((__int64) tv.dwHighDateTime) << 32) + tv.dwLowDateTime;
      time /= 10000;
#else
      struct timeval tv;
      gettimeofday(&tv, NULL);
      time += tv.tv_sec * 1000;
      time += tv.tv_usec / 1000;
#endif
      return time;
    }

    stringT type_;
    EventTargetT target_;
    EventTargetT currTarget_;
    typename EventT::Phase phase_;
    unsigned long long timeStamp_;
    bool canBubble_;
    bool canCancel_;
    bool stopped_;
    bool defaultsPrevented_;
    unsigned long refCount_;

    friend class EventTargetImpl<stringT, string_adaptorT>;
}; // class EventImpl

} // namespace SimpleDOM
} // namespace Arabica

#endif // JEZUK_DOM_SimpleDOM_EVENTTARGET_H
// end of file
<|endoftext|>


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

#pragma once

#ifndef NAZARA_ENUMS_UTILITY_HPP
#define NAZARA_ENUMS_UTILITY_HPP

namespace Nz
{
	enum AnimationType
	{
		AnimationType_Skeletal,
		AnimationType_Static,

		AnimationType_Max = AnimationType_Static
	};

	enum BlendFunc
	{
		BlendFunc_DestAlpha,
		BlendFunc_DestColor,
		BlendFunc_SrcAlpha,
		BlendFunc_SrcColor,
		BlendFunc_InvDestAlpha,
		BlendFunc_InvDestColor,
		BlendFunc_InvSrcAlpha,
		BlendFunc_InvSrcColor,
		BlendFunc_One,
		BlendFunc_Zero,

		BlendFunc_Max = BlendFunc_Zero
	};

	enum BufferAccess
	{
		BufferAccess_DiscardAndWrite,
		BufferAccess_ReadOnly,
		BufferAccess_ReadWrite,
		BufferAccess_WriteOnly,

		BufferAccess_Max = BufferAccess_WriteOnly
	};

	enum BufferType
	{
		BufferType_Index,
		BufferType_Vertex,

		BufferType_Max = BufferType_Vertex
	};

	enum BufferUsage
	{
		BufferUsage_Dynamic,
		BufferUsage_Static,

		BufferUsage_Max = BufferUsage_Static
	};

	enum ComponentType
	{
		ComponentType_Color,
		ComponentType_Double1,
		ComponentType_Double2,
		ComponentType_Double3,
		ComponentType_Double4,
		ComponentType_Float1,
		ComponentType_Float2,
		ComponentType_Float3,
		ComponentType_Float4,
		ComponentType_Int1,
		ComponentType_Int2,
		ComponentType_Int3,
		ComponentType_Int4,
		ComponentType_Quaternion,

		ComponentType_Max = ComponentType_Quaternion
	};

	enum CubemapFace
	{
		// Cette énumération est prévue pour remplacer l'argument "z" des méthodes de Image contenant un cubemap
		// L'ordre est X, -X, Y, -Y, Z, -Z
		CubemapFace_PositiveX = 0,
		CubemapFace_PositiveY = 2,
		CubemapFace_PositiveZ = 4,
		CubemapFace_NegativeX = 1,
		CubemapFace_NegativeY = 3,
		CubemapFace_NegativeZ = 5,

		CubemapFace_Max = CubemapFace_NegativeZ
	};

	enum DataStorageFlags
	{
		DataStorage_Hardware = 0x1,
		DataStorage_Software = 0x2,

		DataStorage_Both = DataStorage_Hardware | DataStorage_Software,

		DataStorage_Max = DataStorage_Software*2-1
	};

	enum FaceFilling
	{
		FaceFilling_Fill,
		FaceFilling_Line,
		FaceFilling_Point,

		FaceFilling_Max = FaceFilling_Point
	};

	enum FaceSide
	{
		FaceSide_Back,
		FaceSide_Front,
		FaceSide_FrontAndBack,

		FaceSide_Max = FaceSide_FrontAndBack
	};

	enum ImageType
	{
		ImageType_1D,
		ImageType_1D_Array,
		ImageType_2D,
		ImageType_2D_Array,
		ImageType_3D,
		ImageType_Cubemap,

		ImageType_Max = ImageType_Cubemap
	};

	enum NodeType
	{
		NodeType_Default,  // Node
		NodeType_Scene,    // SceneNode (Graphics)
		NodeType_Skeletal, ///TODO

		NodeType_Max = NodeType_Skeletal
	};

	enum PixelFormatContent
	{
		PixelFormatContent_Undefined = -1,

		PixelFormatContent_ColorRGBA,
		PixelFormatContent_DepthStencil,
		PixelFormatContent_Stencil,

		PixelFormatContent_Max = PixelFormatContent_Stencil
	};

	enum PixelFormatType
	{
		PixelFormatType_Undefined = -1,

		PixelFormatType_A8,              // 1*uint8
		PixelFormatType_BGR8,            // 3*uint8
		PixelFormatType_BGRA8,           // 4*uint8
		PixelFormatType_DXT1,
		PixelFormatType_DXT3,
		PixelFormatType_DXT5,
		PixelFormatType_L8,              // 1*uint8
		PixelFormatType_LA8,             // 2*uint8
		PixelFormatType_R8,              // 1*uint8
		PixelFormatType_R8I,             // 1*int8
		PixelFormatType_R8UI,            // 1*uint8
		PixelFormatType_R16,             // 1*uint16
		PixelFormatType_R16F,            // 1*half
		PixelFormatType_R16I,            // 1*int16
		PixelFormatType_R16UI,           // 1*uint16
		PixelFormatType_R32F,            // 1*float
		PixelFormatType_R32I,            // 1*uint16
		PixelFormatType_R32UI,           // 1*uint32
		PixelFormatType_RG8,             // 2*int8
		PixelFormatType_RG8I,            // 2*int8
		PixelFormatType_RG8UI,           // 2*uint8
		PixelFormatType_RG16,            // 2*uint16
		PixelFormatType_RG16F,           // 2*half
		PixelFormatType_RG16I,           // 2*int16
		PixelFormatType_RG16UI,          // 2*uint16
		PixelFormatType_RG32F,           // 2*float
		PixelFormatType_RG32I,           // 2*uint16
		PixelFormatType_RG32UI,          // 2*uint32
		PixelFormatType_RGB5A1,          // 3*uint5 + alpha bit
		PixelFormatType_RGB8,            // 3*uint8
		PixelFormatType_RGB16F,          // 3*half
		PixelFormatType_RGB16I,          // 4*int16
		PixelFormatType_RGB16UI,         // 4*uint16
		PixelFormatType_RGB32F,          // 3*float
		PixelFormatType_RGB32I,          // 4*int32
		PixelFormatType_RGB32UI,         // 4*uint32
		PixelFormatType_RGBA4,           // 4*uint4
		PixelFormatType_RGBA8,           // 4*uint8
		PixelFormatType_RGBA16F,         // 4*half
		PixelFormatType_RGBA16I,         // 4*int16
		PixelFormatType_RGBA16UI,        // 4*uint16
		PixelFormatType_RGBA32F,         // 4*float
		PixelFormatType_RGBA32I,         // 4*int32
		PixelFormatType_RGBA32UI,        // 4*uint32
		PixelFormatType_Depth16,
		PixelFormatType_Depth24,
		PixelFormatType_Depth24Stencil8,
		PixelFormatType_Depth32,
		PixelFormatType_Stencil1,
		PixelFormatType_Stencil4,
		PixelFormatType_Stencil8,
		PixelFormatType_Stencil16,

		PixelFormatType_Max = PixelFormatType_Stencil16
	};

	enum PixelFormatSubType
	{
		PixelFormatSubType_Compressed, // Opaque
		PixelFormatSubType_Double,     // F64
		PixelFormatSubType_Float,      // F32
		PixelFormatSubType_Half,       // F16
		PixelFormatSubType_Int,        //   Signed integer
		PixelFormatSubType_Unsigned,   // Unsigned integer

		PixelFormatSubType_Max = PixelFormatSubType_Unsigned
	};

	enum PixelFlipping
	{
		PixelFlipping_Horizontally,
		PixelFlipping_Vertically,

		PixelFlipping_Max = PixelFlipping_Vertically
	};

	enum PrimitiveMode
	{
		PrimitiveMode_LineList,
		PrimitiveMode_LineStrip,
		PrimitiveMode_PointList,
		PrimitiveMode_TriangleList,
		PrimitiveMode_TriangleStrip,
		PrimitiveMode_TriangleFan,

		PrimitiveMode_Max = PrimitiveMode_TriangleFan
	};

	enum RendererComparison
	{
		RendererComparison_Always,
		RendererComparison_Equal,
		RendererComparison_Greater,
		RendererComparison_GreaterOrEqual,
		RendererComparison_Less,
		RendererComparison_LessOrEqual,
		RendererComparison_Never,
		RendererComparison_NotEqual,

		RendererComparison_Max = RendererComparison_NotEqual
	};

	enum RendererParameter
	{
		RendererParameter_Blend,
		RendererParameter_ColorWrite,
		RendererParameter_DepthBuffer,
		RendererParameter_DepthWrite,
		RendererParameter_FaceCulling,
		RendererParameter_ScissorTest,
		RendererParameter_StencilTest,

		RendererParameter_Max = RendererParameter_StencilTest
	};

	enum SamplerFilter
	{
		SamplerFilter_Unknown = -1,

		SamplerFilter_Bilinear,
		SamplerFilter_Nearest,
		SamplerFilter_Trilinear,

		SamplerFilter_Default,

		SamplerFilter_Max = SamplerFilter_Default
	};

	enum SamplerWrap
	{
		SamplerWrap_Unknown = -1,

		SamplerWrap_Clamp,
		SamplerWrap_MirroredRepeat,
		SamplerWrap_Repeat,

		SamplerWrap_Default,

		SamplerWrap_Max = SamplerWrap_Repeat
	};

	enum StencilOperation
	{
		StencilOperation_Decrement,
		StencilOperation_DecrementNoClamp,
		StencilOperation_Increment,
		StencilOperation_IncrementNoClamp,
		StencilOperation_Invert,
		StencilOperation_Keep,
		StencilOperation_Replace,
		StencilOperation_Zero,

		StencilOperation_Max = StencilOperation_Zero
	};

	enum TextAlign
	{
		TextAlign_Left,
		TextAlign_Middle,
		TextAlign_Right,

		TextAlign_Max = TextAlign_Right
	};

	enum TextStyleFlags
	{
		TextStyle_Regular = 0x0,

		TextStyle_Bold          = 0x1,
		TextStyle_Italic        = 0x2,
		TextStyle_StrikeThrough = 0x4,
		TextStyle_Underlined    = 0x8,

		TextStyle_Max = TextStyle_Underlined*2-1
	};

	enum VertexComponent
	{
		VertexComponent_Unused = -1,

		// Nous nous limitons à 16 composants de sommets car c'est le minimum supporté par le GPU
		VertexComponent_InstanceData0,
		VertexComponent_InstanceData1,
		VertexComponent_InstanceData2,
		VertexComponent_InstanceData3,
		VertexComponent_InstanceData4,
		VertexComponent_InstanceData5,
		VertexComponent_Color,
		VertexComponent_Normal,
		VertexComponent_Position,
		VertexComponent_Tangent,
		VertexComponent_TexCoord,
		VertexComponent_Userdata0,
		VertexComponent_Userdata1,
		VertexComponent_Userdata2,
		VertexComponent_Userdata3,
		VertexComponent_Userdata4,

		VertexComponent_FirstInstanceData = VertexComponent_InstanceData0,
		VertexComponent_FirstVertexData = VertexComponent_Color,
		VertexComponent_LastInstanceData = VertexComponent_InstanceData5,
		VertexComponent_LastVertexData = VertexComponent_Userdata4,

		VertexComponent_Max = VertexComponent_Userdata4
	};

	enum VertexLayout
	{
		// Déclarations destinées au rendu
		VertexLayout_XY,
		VertexLayout_XY_Color,
		VertexLayout_XY_UV,
		VertexLayout_XYZ,
		VertexLayout_XYZ_Color,
		VertexLayout_XYZ_Color_UV,
		VertexLayout_XYZ_Normal,
		VertexLayout_XYZ_Normal_UV,
		VertexLayout_XYZ_Normal_UV_Tangent,
		VertexLayout_XYZ_Normal_UV_Tangent_Skinning,
		VertexLayout_XYZ_UV,

		// Déclarations destinées à l'instancing
		VertexLayout_Matrix4,

		VertexLayout_Max = VertexLayout_Matrix4
	};

	enum WindowCursor
	{
		WindowCursor_None,
		WindowCursor_Default,

		WindowCursor_Crosshair,
		WindowCursor_Hand,
		WindowCursor_Help,
		WindowCursor_Move,
		WindowCursor_Pointer,
		WindowCursor_Progress,
		WindowCursor_ResizeE,
		WindowCursor_ResizeN,
		WindowCursor_ResizeNE,
		WindowCursor_ResizeNW,
		WindowCursor_ResizeS,
		WindowCursor_ResizeSE,
		WindowCursor_ResizeSW,
		WindowCursor_ResizeW,
		WindowCursor_Text,
		WindowCursor_Wait,

		WindowCursor_Max = WindowCursor_Wait
	};

	enum WindowEventType
	{
		WindowEventType_GainedFocus,
		WindowEventType_LostFocus,
		WindowEventType_KeyPressed,
		WindowEventType_KeyReleased,
		WindowEventType_MouseButtonDoubleClicked,
		WindowEventType_MouseButtonPressed,
		WindowEventType_MouseButtonReleased,
		WindowEventType_MouseEntered,
		WindowEventType_MouseLeft,
		WindowEventType_MouseMoved,
		WindowEventType_MouseWheelMoved,
		WindowEventType_Moved,
		WindowEventType_Quit,
		WindowEventType_Resized,
		WindowEventType_TextEntered,

		WindowEventType_Max = WindowEventType_TextEntered
	};

	enum WindowStyleFlags
	{
		WindowStyle_None       = 0x0,  ///< Window has no border nor titlebar.
		WindowStyle_Fullscreen = 0x1,  ///< At the window creation, the OS tries to set it in fullscreen.

		WindowStyle_Closable   = 0x2,  ///< Allows the window to be closed by a button in the titlebar, generating a Quit event.
		WindowStyle_Resizable  = 0x4,  ///< Allows the window to be resized by dragging its corners or by a button of the titlebar.
		WindowStyle_Titlebar   = 0x8,  ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled.

		WindowStyle_Threaded   = 0x10, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window.

		WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar,
		WindowStyle_Max = WindowStyle_Titlebar*2-1
	};
}

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

#pragma once

#ifndef NAZARA_ENUMS_UTILITY_HPP
#define NAZARA_ENUMS_UTILITY_HPP

namespace Nz
{
	enum AnimationType
	{
		AnimationType_Skeletal,
		AnimationType_Static,

		AnimationType_Max = AnimationType_Static
	};

	enum BlendFunc
	{
		BlendFunc_DestAlpha,
		BlendFunc_DestColor,
		BlendFunc_SrcAlpha,
		BlendFunc_SrcColor,
		BlendFunc_InvDestAlpha,
		BlendFunc_InvDestColor,
		BlendFunc_InvSrcAlpha,
		BlendFunc_InvSrcColor,
		BlendFunc_One,
		BlendFunc_Zero,

		BlendFunc_Max = BlendFunc_Zero
	};

	enum BufferAccess
	{
		BufferAccess_DiscardAndWrite,
		BufferAccess_ReadOnly,
		BufferAccess_ReadWrite,
		BufferAccess_WriteOnly,

		BufferAccess_Max = BufferAccess_WriteOnly
	};

	enum BufferType
	{
		BufferType_Index,
		BufferType_Vertex,

		BufferType_Max = BufferType_Vertex
	};

	enum BufferUsage
	{
		BufferUsage_Dynamic,
		BufferUsage_Static,

		BufferUsage_Max = BufferUsage_Static
	};

	enum ComponentType
	{
		ComponentType_Color,
		ComponentType_Double1,
		ComponentType_Double2,
		ComponentType_Double3,
		ComponentType_Double4,
		ComponentType_Float1,
		ComponentType_Float2,
		ComponentType_Float3,
		ComponentType_Float4,
		ComponentType_Int1,
		ComponentType_Int2,
		ComponentType_Int3,
		ComponentType_Int4,
		ComponentType_Quaternion,

		ComponentType_Max = ComponentType_Quaternion
	};

	enum CubemapFace
	{
		// Cette énumération est prévue pour remplacer l'argument "z" des méthodes de Image contenant un cubemap
		// L'ordre est X, -X, Y, -Y, Z, -Z
		CubemapFace_PositiveX = 0,
		CubemapFace_PositiveY = 2,
		CubemapFace_PositiveZ = 4,
		CubemapFace_NegativeX = 1,
		CubemapFace_NegativeY = 3,
		CubemapFace_NegativeZ = 5,

		CubemapFace_Max = CubemapFace_NegativeZ
	};

	enum DataStorageFlags
	{
		DataStorage_Hardware = 0x1,
		DataStorage_Software = 0x2,

		DataStorage_Both = DataStorage_Hardware | DataStorage_Software,

		DataStorage_Max = DataStorage_Software*2-1
	};

	enum FaceFilling
	{
		FaceFilling_Fill,
		FaceFilling_Line,
		FaceFilling_Point,

		FaceFilling_Max = FaceFilling_Point
	};

	enum FaceSide
	{
		FaceSide_Back,
		FaceSide_Front,
		FaceSide_FrontAndBack,

		FaceSide_Max = FaceSide_FrontAndBack
	};

	enum ImageType
	{
		ImageType_1D,
		ImageType_1D_Array,
		ImageType_2D,
		ImageType_2D_Array,
		ImageType_3D,
		ImageType_Cubemap,

		ImageType_Max = ImageType_Cubemap
	};

	enum NodeType
	{
		NodeType_Default,  // Node
		NodeType_Scene,    // SceneNode (Graphics)
		NodeType_Skeletal, ///TODO

		NodeType_Max = NodeType_Skeletal
	};

	enum PixelFormatContent
	{
		PixelFormatContent_Undefined = -1,

		PixelFormatContent_ColorRGBA,
		PixelFormatContent_DepthStencil,
		PixelFormatContent_Stencil,

		PixelFormatContent_Max = PixelFormatContent_Stencil
	};

	enum PixelFormatType
	{
		PixelFormatType_Undefined = -1,

		PixelFormatType_A8,              // 1*uint8
		PixelFormatType_BGR8,            // 3*uint8
		PixelFormatType_BGRA8,           // 4*uint8
		PixelFormatType_DXT1,
		PixelFormatType_DXT3,
		PixelFormatType_DXT5,
		PixelFormatType_L8,              // 1*uint8
		PixelFormatType_LA8,             // 2*uint8
		PixelFormatType_R8,              // 1*uint8
		PixelFormatType_R8I,             // 1*int8
		PixelFormatType_R8UI,            // 1*uint8
		PixelFormatType_R16,             // 1*uint16
		PixelFormatType_R16F,            // 1*half
		PixelFormatType_R16I,            // 1*int16
		PixelFormatType_R16UI,           // 1*uint16
		PixelFormatType_R32F,            // 1*float
		PixelFormatType_R32I,            // 1*uint16
		PixelFormatType_R32UI,           // 1*uint32
		PixelFormatType_RG8,             // 2*int8
		PixelFormatType_RG8I,            // 2*int8
		PixelFormatType_RG8UI,           // 2*uint8
		PixelFormatType_RG16,            // 2*uint16
		PixelFormatType_RG16F,           // 2*half
		PixelFormatType_RG16I,           // 2*int16
		PixelFormatType_RG16UI,          // 2*uint16
		PixelFormatType_RG32F,           // 2*float
		PixelFormatType_RG32I,           // 2*uint16
		PixelFormatType_RG32UI,          // 2*uint32
		PixelFormatType_RGB5A1,          // 3*uint5 + alpha bit
		PixelFormatType_RGB8,            // 3*uint8
		PixelFormatType_RGB16F,          // 3*half
		PixelFormatType_RGB16I,          // 4*int16
		PixelFormatType_RGB16UI,         // 4*uint16
		PixelFormatType_RGB32F,          // 3*float
		PixelFormatType_RGB32I,          // 4*int32
		PixelFormatType_RGB32UI,         // 4*uint32
		PixelFormatType_RGBA4,           // 4*uint4
		PixelFormatType_RGBA8,           // 4*uint8
		PixelFormatType_RGBA16F,         // 4*half
		PixelFormatType_RGBA16I,         // 4*int16
		PixelFormatType_RGBA16UI,        // 4*uint16
		PixelFormatType_RGBA32F,         // 4*float
		PixelFormatType_RGBA32I,         // 4*int32
		PixelFormatType_RGBA32UI,        // 4*uint32
		PixelFormatType_Depth16,
		PixelFormatType_Depth24,
		PixelFormatType_Depth24Stencil8,
		PixelFormatType_Depth32,
		PixelFormatType_Stencil1,
		PixelFormatType_Stencil4,
		PixelFormatType_Stencil8,
		PixelFormatType_Stencil16,

		PixelFormatType_Max = PixelFormatType_Stencil16
	};

	enum PixelFormatSubType
	{
		PixelFormatSubType_Compressed, // Opaque
		PixelFormatSubType_Double,     // F64
		PixelFormatSubType_Float,      // F32
		PixelFormatSubType_Half,       // F16
		PixelFormatSubType_Int,        //   Signed integer
		PixelFormatSubType_Unsigned,   // Unsigned integer

		PixelFormatSubType_Max = PixelFormatSubType_Unsigned
	};

	enum PixelFlipping
	{
		PixelFlipping_Horizontally,
		PixelFlipping_Vertically,

		PixelFlipping_Max = PixelFlipping_Vertically
	};

	enum PrimitiveMode
	{
		PrimitiveMode_LineList,
		PrimitiveMode_LineStrip,
		PrimitiveMode_PointList,
		PrimitiveMode_TriangleList,
		PrimitiveMode_TriangleStrip,
		PrimitiveMode_TriangleFan,

		PrimitiveMode_Max = PrimitiveMode_TriangleFan
	};

	enum RendererComparison
	{
		RendererComparison_Always,
		RendererComparison_Equal,
		RendererComparison_Greater,
		RendererComparison_GreaterOrEqual,
		RendererComparison_Less,
		RendererComparison_LessOrEqual,
		RendererComparison_Never,
		RendererComparison_NotEqual,

		RendererComparison_Max = RendererComparison_NotEqual
	};

	enum RendererParameter
	{
		RendererParameter_Blend,
		RendererParameter_ColorWrite,
		RendererParameter_DepthBuffer,
		RendererParameter_DepthWrite,
		RendererParameter_FaceCulling,
		RendererParameter_ScissorTest,
		RendererParameter_StencilTest,

		RendererParameter_Max = RendererParameter_StencilTest
	};

	enum SamplerFilter
	{
		SamplerFilter_Unknown = -1,

		SamplerFilter_Bilinear,
		SamplerFilter_Nearest,
		SamplerFilter_Trilinear,

		SamplerFilter_Default,

		SamplerFilter_Max = SamplerFilter_Default
	};

	enum SamplerWrap
	{
		SamplerWrap_Unknown = -1,

		SamplerWrap_Clamp,
		SamplerWrap_MirroredRepeat,
		SamplerWrap_Repeat,

		SamplerWrap_Default,

		SamplerWrap_Max = SamplerWrap_Repeat
	};

	enum StencilOperation
	{
		StencilOperation_Decrement,
		StencilOperation_DecrementNoClamp,
		StencilOperation_Increment,
		StencilOperation_IncrementNoClamp,
		StencilOperation_Invert,
		StencilOperation_Keep,
		StencilOperation_Replace,
		StencilOperation_Zero,

		StencilOperation_Max = StencilOperation_Zero
	};

	enum TextAlign
	{
		TextAlign_Left,
		TextAlign_Middle,
		TextAlign_Right,

		TextAlign_Max = TextAlign_Right
	};

	enum TextStyleFlags
	{
		TextStyle_Regular = 0x0,

		TextStyle_Bold          = 0x1,
		TextStyle_Italic        = 0x2,
		TextStyle_StrikeThrough = 0x4,
		TextStyle_Underlined    = 0x8,

		TextStyle_Max = TextStyle_Underlined*2-1
	};

	enum VertexComponent
	{
		VertexComponent_Unused = -1,

		// Nous nous limitons à 16 composants de sommets car c'est le minimum supporté par le GPU
		VertexComponent_InstanceData0,
		VertexComponent_InstanceData1,
		VertexComponent_InstanceData2,
		VertexComponent_InstanceData3,
		VertexComponent_InstanceData4,
		VertexComponent_InstanceData5,
		VertexComponent_Color,
		VertexComponent_Normal,
		VertexComponent_Position,
		VertexComponent_Tangent,
		VertexComponent_TexCoord,
		VertexComponent_Userdata0,
		VertexComponent_Userdata1,
		VertexComponent_Userdata2,
		VertexComponent_Userdata3,
		VertexComponent_Userdata4,

		VertexComponent_FirstInstanceData = VertexComponent_InstanceData0,
		VertexComponent_FirstVertexData = VertexComponent_Color,
		VertexComponent_LastInstanceData = VertexComponent_InstanceData5,
		VertexComponent_LastVertexData = VertexComponent_Userdata4,

		VertexComponent_Max = VertexComponent_Userdata4
	};

	enum VertexLayout
	{
		// Déclarations destinées au rendu
		VertexLayout_XY,
		VertexLayout_XY_Color,
		VertexLayout_XY_UV,
		VertexLayout_XYZ,
		VertexLayout_XYZ_Color,
		VertexLayout_XYZ_Color_UV,
		VertexLayout_XYZ_Normal,
		VertexLayout_XYZ_Normal_UV,
		VertexLayout_XYZ_Normal_UV_Tangent,
		VertexLayout_XYZ_Normal_UV_Tangent_Skinning,
		VertexLayout_XYZ_UV,

		// Déclarations destinées à l'instancing
		VertexLayout_Matrix4,

		VertexLayout_Max = VertexLayout_Matrix4
	};

	enum WindowCursor
	{
		WindowCursor_None,
		WindowCursor_Default,

		WindowCursor_Crosshair,
		WindowCursor_Hand,
		WindowCursor_Help,
		WindowCursor_Move,
		WindowCursor_Pointer,
		WindowCursor_Progress,
		WindowCursor_ResizeE,
		WindowCursor_ResizeN,
		WindowCursor_ResizeNE,
		WindowCursor_ResizeNW,
		WindowCursor_ResizeS,
		WindowCursor_ResizeSE,
		WindowCursor_ResizeSW,
		WindowCursor_ResizeW,
		WindowCursor_Text,
		WindowCursor_Wait,

		WindowCursor_Max = WindowCursor_Wait
	};

	enum WindowEventType
	{
		WindowEventType_GainedFocus,
		WindowEventType_LostFocus,
		WindowEventType_KeyPressed,
		WindowEventType_KeyReleased,
		WindowEventType_MouseButtonDoubleClicked,
		WindowEventType_MouseButtonPressed,
		WindowEventType_MouseButtonReleased,
		WindowEventType_MouseEntered,
		WindowEventType_MouseLeft,
		WindowEventType_MouseMoved,
		WindowEventType_MouseWheelMoved,
		WindowEventType_Moved,
		WindowEventType_Quit,
		WindowEventType_Resized,
		WindowEventType_TextEntered,

		WindowEventType_Max = WindowEventType_TextEntered
	};

	enum WindowStyleFlags
	{
		WindowStyle_None       = 0x0,  ///< Window has no border nor titlebar.
		WindowStyle_Fullscreen = 0x1,  ///< At the window creation, the OS tries to set it in fullscreen.

		WindowStyle_Closable   = 0x2,  ///< Allows the window to be closed by a button in the titlebar, generating a Quit event.
		WindowStyle_Resizable  = 0x4,  ///< Allows the window to be resized by dragging its corners or by a button of the titlebar.
		WindowStyle_Titlebar   = 0x8,  ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled.

		WindowStyle_Threaded   = 0x10, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window.

		WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar,
		WindowStyle_Max = WindowStyle_Threaded*2-1
	};
}

#endif // NAZARA_ENUMS_UTILITY_HPP
<|endoftext|>