<commit_before>/***********************************************************************************
**
** GumpSecureTrading.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "GumpSecureTrading.h"
#include "../SelectedObject.h"
#include "../ClickObject.h"
#include "../OrionUO.h"
#include "../Game objects/GameWorld.h"
#include "../Game objects/GamePlayer.h"
#include "../Game objects/ObjectOnCursor.h"
#include "../Managers/FontsManager.h"
#include "../Managers/MouseManager.h"
#include "../Managers/ConfigManager.h"
#include "../Managers/PacketManager.h"
#include "../Network/Packets.h"
#include "../PressedObject.h"
#include "../ToolTip.h"
//----------------------------------------------------------------------------------
CGumpSecureTrading::CGumpSecureTrading(uint serial, short x, short y, uint id, uint id2)
: CGump(GT_TRADE, serial, x, y), m_ID2(id2), m_StateMy(false), m_StateOpponent(false),
m_TextRenderer(), m_MyCheck(NULL), m_OpponentCheck(NULL), m_MyDataBox(NULL),
m_OpponentDataBox(NULL)
{
	m_ID = id;
}
//----------------------------------------------------------------------------------
CGumpSecureTrading::~CGumpSecureTrading()
{
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::CalculateGumpState()
{
	CGump::CalculateGumpState();

	if (g_GumpPressed && g_PressedObject.LeftObject() != NULL && g_PressedObject.LeftObject()->IsText())
	{
		g_GumpMovingOffset.Reset();

		g_GumpTranslate.X = (float)m_X;
		g_GumpTranslate.Y = (float)m_Y;
	}

	if (g_GumpTranslate.X || g_GumpTranslate.Y)
		m_WantRedraw = true;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::InitToolTip()
{
	if (g_ConfigManager.UseToolTips || g_PacketManager.ClientVersion >= CV_308Z)
	{
		uint id = g_SelectedObject.Serial;

		CGameObject *obj = g_World->FindWorldObject(id);

		if (obj != NULL && obj->ClilocMessage.length())
			g_ToolTip.Set(obj->ClilocMessage);
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::PrepareContent()
{
	if (m_MyCheck != NULL)
	{
		if (m_StateMy)
		{
			if (m_MyCheck->Graphic != 0x0869)
			{
				m_MyCheck->Graphic = 0x0869;
				m_MyCheck->GraphicSelected = 0x086A;
				m_MyCheck->GraphicPressed = 0x086A;
				m_WantRedraw = true;
			}
		}
		else if (m_MyCheck->Graphic != 0x0867)
		{
			m_MyCheck->Graphic = 0x0867;
			m_MyCheck->GraphicSelected = 0x0868;
			m_MyCheck->GraphicPressed = 0x0868;
			m_WantRedraw = true;
		}
	}

	if (m_OpponentCheck != NULL)
	{
		if (m_StateOpponent)
		{
			if (m_OpponentCheck->Graphic != 0x0869)
			{
				m_OpponentCheck->Graphic = 0x0869;
				m_WantRedraw = true;
			}
		}
		else if (m_OpponentCheck->Graphic != 0x0867)
		{
			m_OpponentCheck->Graphic = 0x0867;
			m_WantRedraw = true;
		}
	}

	if (m_TextRenderer.CalculatePositions(false))
		m_WantRedraw = true;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::UpdateContent()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return; //Объект, к которому привязан гамп - исчез

	if (m_Items == NULL)
	{
		Add(new CGUIGumppic(0x0866, 0, 0)); //Trade Gump

		Add(new CGUIColoredPolygone(0, 0, 45, 90, 110, 60, 0xFF000001));

		Add(new CGUIColoredPolygone(0, 0, 192, 70, 110, 60, 0xFF000001));

		if (m_StateMy)
			m_MyCheck = (CGUIButton*)Add(new CGUIButton(ID_GST_CHECKBOX, 0x0869, 0x086A, 0x086A, 52, 29));
		else
			m_MyCheck = (CGUIButton*)Add(new CGUIButton(ID_GST_CHECKBOX, 0x0867, 0x0868, 0x0868, 52, 29));

		CGUIText *text = (CGUIText*)Add(new CGUIText(0x0386, 84, 40));
		text->CreateTextureA(1, g_Player->Name);

		if (m_StateOpponent)
			m_OpponentCheck = (CGUIGumppic*)Add(new CGUIGumppic(0x0869, 266, 160));
		else
			m_OpponentCheck = (CGUIGumppic*)Add(new CGUIGumppic(0x0867, 266, 160));

		int fontWidth = 260 - g_FontManager.GetWidthA(1, m_Text.c_str(), m_Text.length());

		text = (CGUIText*)Add(new CGUIText(0x0386, fontWidth, 170));
		text->CreateTextureA(1, m_Text);

		Add(new CGUIShader(g_ColorizerShader, true));

		Add(new CGUIScissor(true, 0, 0, 45, 70, 110, 80));
		m_MyDataBox = (CGUIDataBox*)Add(new CGUIDataBox());
		Add(new CGUIScissor(false));

		Add(new CGUIScissor(true, 0, 0, 192, 70, 110, 80));
		m_OpponentDataBox = (CGUIDataBox*)Add(new CGUIDataBox());
		Add(new CGUIScissor(false));

		Add(new CGUIShader(g_ColorizerShader, false));
	}
	else
	{
		m_MyDataBox->Clear();
		m_OpponentDataBox->Clear();
	}

	uint ignoreSerial = 0;

	if (g_ObjectInHand != NULL)
		ignoreSerial = g_ObjectInHand->Serial;

	//Отрисовка нашего товара (при наличии товара)
	CGameObject *container = g_World->FindWorldObject(m_ID);

	if (container != NULL && container->m_Items != NULL)
	{
		QFOR(item, container->m_Items, CGameItem*)
		{
			if (item->Serial == ignoreSerial)
				continue;

			bool doubleDraw = false;
			ushort graphic = item->GetDrawGraphic(doubleDraw);

			CGUITilepicHightlighted *dataObject = (CGUITilepicHightlighted*)m_MyDataBox->Add(new CGUITilepicHightlighted(item->Serial, graphic, item->Color, 0x0035, 45 + item->X, 70 + item->Y, doubleDraw));
			dataObject->PartialHue = IsPartialHue(g_Orion.GetStaticFlags(graphic));

			if (dataObject->Y >= 150)
				dataObject->Y = 120;

			if (dataObject->X >= 155)
				dataObject->X = 125;
		}
	}

	//Отрисовка нашего опонента (при наличии товара)
	container = g_World->FindWorldObject(m_ID2);
	if (container != NULL && container->m_Items != NULL)
	{
		QFOR(item, container->m_Items, CGameItem*)
		{
			bool doubleDraw = false;
			ushort graphic = item->GetDrawGraphic(doubleDraw);

			CGUITilepicHightlighted *dataObject = (CGUITilepicHightlighted*)m_OpponentDataBox->Add(new CGUITilepicHightlighted(item->Serial, graphic, item->Color, 0x0035, 192 + item->X, 70 + item->Y, doubleDraw));
			dataObject->PartialHue = IsPartialHue(g_Orion.GetStaticFlags(graphic));

			if (dataObject->Y >= 150)
				dataObject->Y = 120;

			if (dataObject->X >= 302)
				dataObject->X = 272;
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::Draw()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return; //Объект, к которому привязан гамп - исчез

	if (g_GumpPressed)
		m_WantRedraw = true;

	CGump::Draw();

	glTranslatef(g_GumpTranslate.X, g_GumpTranslate.Y, 0.0f);

	g_FontColorizerShader->Use();

	m_TextRenderer.Draw();

	UnuseShader();

	glTranslatef(-g_GumpTranslate.X, -g_GumpTranslate.Y, 0.0f);
}
//----------------------------------------------------------------------------------
CRenderObject *CGumpSecureTrading::Select()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return NULL; //Объект, к которому привязан гамп - исчез

	CRenderObject *selected = CGump::Select();

	WISP_GEOMETRY::CPoint2Di oldPos = g_MouseManager.Position;
	g_MouseManager.Position = WISP_GEOMETRY::CPoint2Di(oldPos.X - (int)g_GumpTranslate.X, oldPos.Y - (int)g_GumpTranslate.Y);

	m_TextRenderer.Select(this);

	g_MouseManager.Position = oldPos;

	return selected;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::GUMP_BUTTON_EVENT_C
{
	if (serial == ID_GST_CHECKBOX) //Изменение состояния чекбокса
	{
		m_StateMy = !m_StateMy;

		SendTradingResponse(2);
	}
	else
	{
		if (!g_ClickObject.Enabled && (g_PacketManager.ClientVersion < CV_308Z || !g_TooltipsEnabled))
		{
			CGameObject *clickTarget = g_World->FindWorldObject(serial);

			if (clickTarget == NULL)
				return;

			g_ClickObject.Init(clickTarget);
			g_ClickObject.Timer = g_Ticks + DCLICK_DELAY;
			g_ClickObject.X = g_MouseManager.Position.X - m_X;
			g_ClickObject.Y = g_MouseManager.Position.Y - m_Y;
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::OnLeftMouseButtonUp()
{
	CGump::OnLeftMouseButtonUp();

	if (g_ObjectInHand != NULL)
	{
		int x = m_X;
		int y = m_Y;

		if (g_Orion.PolygonePixelsInXY(x + 45, y + 70, 110, 80))
		{
			if (GetTopObjDistance(g_Player, g_World->FindWorldObject(m_ID2)) < 3)
			{
				x = g_MouseManager.Position.X - x - 45;
				y = g_MouseManager.Position.Y - y - 70;

				bool doubleDraw = false;
				ushort graphic = g_ObjectInHand->GetDrawGraphic(doubleDraw);

				CGLTexture *th = g_Orion.ExecuteStaticArt(graphic);

				if (th != NULL)
				{
					x -= (th->Width / 2);
					y -= (th->Height / 2);

					if (x + th->Width > 110)
						x = 110 - th->Width;

					if (y + th->Height > 80)
						y = 80 - th->Height;
				}

				if (x < 0)
					x = 0;

				if (y < 0)
					y = 0;

				g_Orion.DropItem(m_ID, x, y, 0);
			}
			else
				g_Orion.PlaySoundEffect(0x0051);
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::SendTradingResponse(int code)
{
	//Ответ на трэйд окно
	CPacketTradeResponse(this, code).Send();

	if (code == 1) //Закрываем окно
		m_RemoveMark = true;
}
//----------------------------------------------------------------------------------
<commit_msg>Исправил появление черных квадратов в окне трэйда на новых клиентах.<commit_after>/***********************************************************************************
**
** GumpSecureTrading.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "GumpSecureTrading.h"
#include "../SelectedObject.h"
#include "../ClickObject.h"
#include "../OrionUO.h"
#include "../Game objects/GameWorld.h"
#include "../Game objects/GamePlayer.h"
#include "../Game objects/ObjectOnCursor.h"
#include "../Managers/FontsManager.h"
#include "../Managers/MouseManager.h"
#include "../Managers/ConfigManager.h"
#include "../Managers/PacketManager.h"
#include "../Network/Packets.h"
#include "../PressedObject.h"
#include "../ToolTip.h"
//----------------------------------------------------------------------------------
CGumpSecureTrading::CGumpSecureTrading(uint serial, short x, short y, uint id, uint id2)
: CGump(GT_TRADE, serial, x, y), m_ID2(id2), m_StateMy(false), m_StateOpponent(false),
m_TextRenderer(), m_MyCheck(NULL), m_OpponentCheck(NULL), m_MyDataBox(NULL),
m_OpponentDataBox(NULL)
{
	m_ID = id;
}
//----------------------------------------------------------------------------------
CGumpSecureTrading::~CGumpSecureTrading()
{
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::CalculateGumpState()
{
	CGump::CalculateGumpState();

	if (g_GumpPressed && g_PressedObject.LeftObject() != NULL && g_PressedObject.LeftObject()->IsText())
	{
		g_GumpMovingOffset.Reset();

		g_GumpTranslate.X = (float)m_X;
		g_GumpTranslate.Y = (float)m_Y;
	}

	if (g_GumpTranslate.X || g_GumpTranslate.Y)
		m_WantRedraw = true;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::InitToolTip()
{
	if (g_ConfigManager.UseToolTips || g_PacketManager.ClientVersion >= CV_308Z)
	{
		uint id = g_SelectedObject.Serial;

		CGameObject *obj = g_World->FindWorldObject(id);

		if (obj != NULL && obj->ClilocMessage.length())
			g_ToolTip.Set(obj->ClilocMessage);
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::PrepareContent()
{
	if (m_MyCheck != NULL)
	{
		if (m_StateMy)
		{
			if (m_MyCheck->Graphic != 0x0869)
			{
				m_MyCheck->Graphic = 0x0869;
				m_MyCheck->GraphicSelected = 0x086A;
				m_MyCheck->GraphicPressed = 0x086A;
				m_WantRedraw = true;
			}
		}
		else if (m_MyCheck->Graphic != 0x0867)
		{
			m_MyCheck->Graphic = 0x0867;
			m_MyCheck->GraphicSelected = 0x0868;
			m_MyCheck->GraphicPressed = 0x0868;
			m_WantRedraw = true;
		}
	}

	if (m_OpponentCheck != NULL)
	{
		if (m_StateOpponent)
		{
			if (m_OpponentCheck->Graphic != 0x0869)
			{
				m_OpponentCheck->Graphic = 0x0869;
				m_WantRedraw = true;
			}
		}
		else if (m_OpponentCheck->Graphic != 0x0867)
		{
			m_OpponentCheck->Graphic = 0x0867;
			m_WantRedraw = true;
		}
	}

	if (m_TextRenderer.CalculatePositions(false))
		m_WantRedraw = true;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::UpdateContent()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return; //Объект, к которому привязан гамп - исчез

	if (m_Items == NULL)
	{
		Add(new CGUIGumppic(0x0866, 0, 0)); //Trade Gump

		if (g_PacketManager.ClientVersion < CV_500A)
		{
			Add(new CGUIColoredPolygone(0, 0, 45, 90, 110, 60, 0xFF000001));

			Add(new CGUIColoredPolygone(0, 0, 192, 70, 110, 60, 0xFF000001));
		}

		if (m_StateMy)
			m_MyCheck = (CGUIButton*)Add(new CGUIButton(ID_GST_CHECKBOX, 0x0869, 0x086A, 0x086A, 52, 29));
		else
			m_MyCheck = (CGUIButton*)Add(new CGUIButton(ID_GST_CHECKBOX, 0x0867, 0x0868, 0x0868, 52, 29));

		CGUIText *text = (CGUIText*)Add(new CGUIText(0x0386, 84, 40));
		text->CreateTextureA(1, g_Player->Name);

		if (m_StateOpponent)
			m_OpponentCheck = (CGUIGumppic*)Add(new CGUIGumppic(0x0869, 266, 160));
		else
			m_OpponentCheck = (CGUIGumppic*)Add(new CGUIGumppic(0x0867, 266, 160));

		int fontWidth = 260 - g_FontManager.GetWidthA(1, m_Text.c_str(), m_Text.length());

		text = (CGUIText*)Add(new CGUIText(0x0386, fontWidth, 170));
		text->CreateTextureA(1, m_Text);

		Add(new CGUIShader(g_ColorizerShader, true));

		Add(new CGUIScissor(true, 0, 0, 45, 70, 110, 80));
		m_MyDataBox = (CGUIDataBox*)Add(new CGUIDataBox());
		Add(new CGUIScissor(false));

		Add(new CGUIScissor(true, 0, 0, 192, 70, 110, 80));
		m_OpponentDataBox = (CGUIDataBox*)Add(new CGUIDataBox());
		Add(new CGUIScissor(false));

		Add(new CGUIShader(g_ColorizerShader, false));
	}
	else
	{
		m_MyDataBox->Clear();
		m_OpponentDataBox->Clear();
	}

	uint ignoreSerial = 0;

	if (g_ObjectInHand != NULL)
		ignoreSerial = g_ObjectInHand->Serial;

	//Отрисовка нашего товара (при наличии товара)
	CGameObject *container = g_World->FindWorldObject(m_ID);

	if (container != NULL && container->m_Items != NULL)
	{
		QFOR(item, container->m_Items, CGameItem*)
		{
			if (item->Serial == ignoreSerial)
				continue;

			bool doubleDraw = false;
			ushort graphic = item->GetDrawGraphic(doubleDraw);

			CGUITilepicHightlighted *dataObject = (CGUITilepicHightlighted*)m_MyDataBox->Add(new CGUITilepicHightlighted(item->Serial, graphic, item->Color, 0x0035, 45 + item->X, 70 + item->Y, doubleDraw));
			dataObject->PartialHue = IsPartialHue(g_Orion.GetStaticFlags(graphic));

			if (dataObject->Y >= 150)
				dataObject->Y = 120;

			if (dataObject->X >= 155)
				dataObject->X = 125;
		}
	}

	//Отрисовка нашего опонента (при наличии товара)
	container = g_World->FindWorldObject(m_ID2);
	if (container != NULL && container->m_Items != NULL)
	{
		QFOR(item, container->m_Items, CGameItem*)
		{
			bool doubleDraw = false;
			ushort graphic = item->GetDrawGraphic(doubleDraw);

			CGUITilepicHightlighted *dataObject = (CGUITilepicHightlighted*)m_OpponentDataBox->Add(new CGUITilepicHightlighted(item->Serial, graphic, item->Color, 0x0035, 192 + item->X, 70 + item->Y, doubleDraw));
			dataObject->PartialHue = IsPartialHue(g_Orion.GetStaticFlags(graphic));

			if (dataObject->Y >= 150)
				dataObject->Y = 120;

			if (dataObject->X >= 302)
				dataObject->X = 272;
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::Draw()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return; //Объект, к которому привязан гамп - исчез

	if (g_GumpPressed)
		m_WantRedraw = true;

	CGump::Draw();

	glTranslatef(g_GumpTranslate.X, g_GumpTranslate.Y, 0.0f);

	g_FontColorizerShader->Use();

	m_TextRenderer.Draw();

	UnuseShader();

	glTranslatef(-g_GumpTranslate.X, -g_GumpTranslate.Y, 0.0f);
}
//----------------------------------------------------------------------------------
CRenderObject *CGumpSecureTrading::Select()
{
	CGameObject *selobj = g_World->FindWorldObject(m_Serial);

	if (selobj == NULL)
		return NULL; //Объект, к которому привязан гамп - исчез

	CRenderObject *selected = CGump::Select();

	WISP_GEOMETRY::CPoint2Di oldPos = g_MouseManager.Position;
	g_MouseManager.Position = WISP_GEOMETRY::CPoint2Di(oldPos.X - (int)g_GumpTranslate.X, oldPos.Y - (int)g_GumpTranslate.Y);

	m_TextRenderer.Select(this);

	g_MouseManager.Position = oldPos;

	return selected;
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::GUMP_BUTTON_EVENT_C
{
	if (serial == ID_GST_CHECKBOX) //Изменение состояния чекбокса
	{
		m_StateMy = !m_StateMy;

		SendTradingResponse(2);
	}
	else
	{
		if (!g_ClickObject.Enabled && (g_PacketManager.ClientVersion < CV_308Z || !g_TooltipsEnabled))
		{
			CGameObject *clickTarget = g_World->FindWorldObject(serial);

			if (clickTarget == NULL)
				return;

			g_ClickObject.Init(clickTarget);
			g_ClickObject.Timer = g_Ticks + DCLICK_DELAY;
			g_ClickObject.X = g_MouseManager.Position.X - m_X;
			g_ClickObject.Y = g_MouseManager.Position.Y - m_Y;
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::OnLeftMouseButtonUp()
{
	CGump::OnLeftMouseButtonUp();

	if (g_ObjectInHand != NULL)
	{
		int x = m_X;
		int y = m_Y;

		if (g_Orion.PolygonePixelsInXY(x + 45, y + 70, 110, 80))
		{
			if (GetTopObjDistance(g_Player, g_World->FindWorldObject(m_ID2)) < 3)
			{
				x = g_MouseManager.Position.X - x - 45;
				y = g_MouseManager.Position.Y - y - 70;

				bool doubleDraw = false;
				ushort graphic = g_ObjectInHand->GetDrawGraphic(doubleDraw);

				CGLTexture *th = g_Orion.ExecuteStaticArt(graphic);

				if (th != NULL)
				{
					x -= (th->Width / 2);
					y -= (th->Height / 2);

					if (x + th->Width > 110)
						x = 110 - th->Width;

					if (y + th->Height > 80)
						y = 80 - th->Height;
				}

				if (x < 0)
					x = 0;

				if (y < 0)
					y = 0;

				g_Orion.DropItem(m_ID, x, y, 0);
			}
			else
				g_Orion.PlaySoundEffect(0x0051);
		}
	}
}
//----------------------------------------------------------------------------------
void CGumpSecureTrading::SendTradingResponse(int code)
{
	//Ответ на трэйд окно
	CPacketTradeResponse(this, code).Send();

	if (code == 1) //Закрываем окно
		m_RemoveMark = true;
}
//----------------------------------------------------------------------------------
<|endoftext|>


<commit_before>// Quantum Fourier transform
// Source: ./examples/qft.cpp
#include <cmath>
#include <iostream>
#include <vector>

#include "qpp.h"

int main() {
    using namespace qpp;
    std::vector<idx> qubits{1, 0, 1, 1, 0}; // initial state
    ket psi = mket(qubits);
    ket result = psi;
    idx n = qubits.size();                                  // number of qubits
    idx D = static_cast<idx>(std::llround(std::pow(2, n))); // dimension
    std::cout << ">> QFT on N = " << n << " qubits. ";
    std::cout << "The sequence of applied gates is:\n";
    for (idx i = 0; i < n; ++i) {
        std::cout << "H" << i << " ";
        result = apply(result, gt.H, {i}); // apply Hadamard on qubit i
        // apply controlled rotations
        for (idx j = 2; j <= n - i; ++j) {
            cmat Rj(2, 2);
            idx pow_j = static_cast<idx>(std::llround(std::pow(2, j)));
            Rj << 1, 0, 0, omega(pow_j);
            result = applyCTRL(result, Rj, {i + j - 1}, {i});
            std::cout << "R" << j << "(" << i + j - 1 << ", " << i << ") ";
        }
        std::cout << '\n';
    }
    // we have the qubits in reversed order, we must swap them
    for (idx i = 0; i < n / 2; ++i) {
        std::cout << "SWAP(" << i << ", " << n - i - 1 << ")\n";
        result = apply(result, gt.SWAP, {i, n - i - 1});
    }
    // check that we got the Fourier transform, compute the norm difference
    if (n < 14) { // otherwise not enough memory for computing gt.Fd(D) * psi
        std::cout << ">> Norm difference: " << norm(result - gt.Fd(D) * psi)
                  << '\n';
    }
}
<commit_msg>formatting<commit_after>// Quantum Fourier transform
// Source: ./examples/qft.cpp
#include <cmath>
#include <iostream>
#include <vector>

#include "qpp.h"

int main() {
    using namespace qpp;
    std::vector<idx> qubits{1, 0, 1, 1, 0}; // initial state
    ket psi = mket(qubits);
    ket result = psi;

    idx n = qubits.size();                                  // number of qubits
    idx D = static_cast<idx>(std::llround(std::pow(2, n))); // dimension
    std::cout << ">> QFT on n = " << n << " qubits. ";

    std::cout << "The sequence of applied gates is:\n";
    for (idx i = 0; i < n; ++i) {
        std::cout << "H" << i << " ";
        result = apply(result, gt.H, {i}); // apply Hadamard on qubit i
        // apply controlled rotations
        for (idx j = 2; j <= n - i; ++j) {
            cmat Rj(2, 2);
            idx pow_j = static_cast<idx>(std::llround(std::pow(2, j)));
            Rj << 1, 0, 0, omega(pow_j);
            result = applyCTRL(result, Rj, {i + j - 1}, {i});
            std::cout << "R" << j << "(" << i + j - 1 << ", " << i << ") ";
        }
        std::cout << '\n';
    }

    // we have the qubits in reversed order, we must swap them
    for (idx i = 0; i < n / 2; ++i) {
        std::cout << "SWAP(" << i << ", " << n - i - 1 << ")\n";
        result = apply(result, gt.SWAP, {i, n - i - 1});
    }

    // check that we got the Fourier transform, compute the norm difference
    if (n < 14) { // otherwise not enough memory for computing gt.Fd(D) * psi
        std::cout << ">> Norm difference: " << norm(result - gt.Fd(D) * psi)
                  << '\n';
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *   Email: russ@q12.org   Web: www.q12.org                              *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

// if the dDEBUG_ALLOC macro is defined, the following tests are performed in
// the default allocator:
//   - size > 0 for alloc and realloc
//   - realloc and free operate on uncorrupted blocks
//   - realloc and free with the correct sizes
//   - on exit, report of block allocation statistics
//   - on exit, report of unfreed blocks and if they are corrupted
// the allocator will also call Debug() when it allocates a block with
// sequence number `seqstop' or pointer value `ptrstop'. these variables
// are global and can be set in the debugger.

#include <malloc.h>
#include "ode/memory.h"
#include "ode/error.h"

#ifdef dDEBUG_ALLOC

#include <string.h>

// when debugging, this is a header that it put at start of all blocks.
// it contains `padding', which are PADSIZE elements of known value just
// before the user memory starts. another PADSIZE padding elements are put
// at the end of the user memory. the idea is that if the user accidentally
// steps outside the allocated memory, it can hopefully be detected by
// examining the padding elements.

#define PADSIZE 10
struct blockHeader {
  long pad1;			// protective padding
  long seq;			// sequence number
  long size;			// data size
  blockHeader *next,*prev;	// next & previous blocks
  long pad[PADSIZE];		// protective padding
};

// compute the memory block size, including padding. the user memory block is
// rounded up to a multiple of 4 bytes, to get alignment for the padding at
// the end of the block.

#define BSIZE(size) (((((size)-1) | 3)+1) + sizeof(blockHeader) + \
  PADSIZE * sizeof(long))

static blockHeader dummyblock = {0,0,0,&dummyblock,&dummyblock,
				 {0,0,0,0,0,0,0,0,0,0}};
static blockHeader *firstblock = &dummyblock;
static long num_blocks_alloced = 0;
static long num_bytes_alloced = 0;
static long total_num_blocks_alloced = 0;
static long total_num_bytes_alloced = 0;
static long max_blocks_alloced = 0;
static long max_bytes_alloced = 0;

long seqstop = 0;
void *ptrstop = 0;

static int checkBlockOk (void *ptr, int fatal)
{
  blockHeader *b = ((blockHeader*) ptr) - 1;
  int i,ok = 1;
  if (b->pad1 != (long)0xdeadbeef || b->seq < 0 || b->size < 0) ok = 0;
  if (ok) {
    for (i=0; i<PADSIZE; i++) if (b->pad[i] != (long)0xdeadbeef) ok = 0;
  }
  if (ok) {
    long *endpad = (long*) (((char*)ptr) + (((b->size-1) | 3)+1));
    for (i=0; i<PADSIZE; i++) if (endpad[i] != (long)0xdeadbeef) ok = 0;
  }
  if (!ok && fatal)
    dDebug (0,"corrupted memory block found, ptr=%p, size=%d, "
	    "seq=%ld", ptr,b->size,b->seq);
  return ok;
}

#endif

static dAllocFunction *allocfn = 0;
static dReallocFunction *reallocfn = 0;
static dFreeFunction *freefn = 0;

void dSetAllocHandler (dAllocFunction *fn)
{
  allocfn = fn;
}

void dSetReallocHandler (dReallocFunction *fn)
{
  reallocfn = fn;
}

void dSetFreeHandler (dFreeFunction *fn)
{
  freefn = fn;
}

void * dAlloc (int size)
{
#ifdef dDEBUG_ALLOC
  if (size < 1) dDebug (0,"bad block size to Alloc()");

  num_blocks_alloced++;
  num_bytes_alloced += size;
  total_num_blocks_alloced++;
  total_num_bytes_alloced += size;
  if (num_blocks_alloced > max_blocks_alloced)
    max_blocks_alloced = num_blocks_alloced;
  if (num_bytes_alloced > max_bytes_alloced)
    max_bytes_alloced = num_bytes_alloced;

  if (total_num_blocks_alloced == seqstop)
    dDebug (0,"ALLOCATOR TRAP ON SEQUENCE NUMBER %d",seqstop);
  long size2 = BSIZE(size);
  blockHeader *b = (blockHeader*) malloc (size2);
  if (b+1 == ptrstop)
    dDebug (0,"ALLOCATOR TRAP ON BLOCK POINTER %p",ptrstop);
  for (unsigned int i=0; i < (size2/sizeof(long)); i++)
    ((long*)b)[i] = 0xdeadbeef;
  b->seq = total_num_blocks_alloced;
  b->size = size;
  b->next = firstblock->next;
  b->prev = firstblock;
  firstblock->next->prev = b;
  firstblock->next = b;
  return b + 1;
#else
  if (allocfn) return allocfn (size); else return malloc (size);
#endif
}

void * dRealloc (void *ptr, int oldsize, int newsize)
{
#ifdef dDEBUG_ALLOC
  if (ptr==0) dDebug (0,"Realloc() called with ptr==0");
  checkBlockOk (ptr,1);
  blockHeader *b = ((blockHeader*) ptr) - 1;
  if (b->size != oldsize)
    dDebug (0,"Realloc(%p,%d,%d) has bad old size, good size "
	    "is %ld, seq=%ld",ptr,oldsize,newsize,b->size,b->seq);
  void *p = dAlloc (newsize);
  if (oldsize>=1) memcpy (p,ptr,oldsize);
  dFree (ptr,oldsize);
  return p;
#else
  if (reallocfn) return reallocfn (ptr,oldsize,newsize);
  else return realloc (ptr,newsize);
#endif
}

void dFree (void *ptr, int size)
{
  if (!ptr) return;
#ifdef dDEBUG_ALLOC
  checkBlockOk (ptr,1);
  blockHeader *b = ((blockHeader*) ptr) - 1;
  if (b->size != size)
    dDebug (0,"Free(%p,%d) has bad size, good size "
	    "is %ld, seq=%ld",ptr,size,b->size,b->seq);
  num_blocks_alloced--;
  num_bytes_alloced -= b->size;
  if (num_blocks_alloced < 0 || num_bytes_alloced < 0)
    dDebug (0,"Free called too many times");

  b->next->prev = b->prev;
  b->prev->next = b->next;
  memset (b,0,BSIZE(b->size));

  free (b);
#else
  if (freefn) freefn (ptr,size); else free (ptr);
#endif
}

void * dAllocNoFree (int size)
{
  if (allocfn) return allocfn (size); else return malloc (size);
}

#ifdef dDEBUG_ALLOC

#include <stdio.h>

static void printReport()
{
  fprintf (stderr,"\nALLOCATOR REPORT\n");
  fprintf (stderr,"\tblocks still allocated:  %ld\n",num_blocks_alloced);
  fprintf (stderr,"\tbytes still allocated:   %ld\n",num_bytes_alloced);
  fprintf (stderr,"\ttotal blocks allocated:  %ld\n",total_num_blocks_alloced);
  fprintf (stderr,"\ttotal bytes allocated:   %ld\n",total_num_bytes_alloced);
  fprintf (stderr,"\tmax blocks allocated:    %ld\n",max_blocks_alloced);
  fprintf (stderr,"\tmax bytes allocated:     %ld\n",max_bytes_alloced);

  blockHeader *b = firstblock;
  do {
    if (b != &dummyblock) {
      int ok = checkBlockOk (b+1,0);
      fprintf (stderr,"\tUNFREED: %p, size=%ld, seq=%ld (%s)\n",b+1,
	       b->size,b->seq, ok ? "ok" : "CORUPTED");
    }
    b = b->prev;
  }
  while (b != firstblock);
  fprintf (stderr,"\n");
}

struct dMemoryReportPrinter {
  ~dMemoryReportPrinter() { printReport(); }
} _dReportPrinter;

#endif
<commit_msg>dAllocDontReport() system<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *   Email: russ@q12.org   Web: www.q12.org                              *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

// if the dDEBUG_ALLOC macro is defined, the following tests are performed in
// the default allocator:
//   - size > 0 for alloc and realloc
//   - realloc and free operate on uncorrupted blocks
//   - realloc and free with the correct sizes
//   - on exit, report of block allocation statistics
//   - on exit, report of unfreed blocks and if they are corrupted
// the allocator will also call Debug() when it allocates a block with
// sequence number `seqstop' or pointer value `ptrstop'. these variables
// are global and can be set in the debugger.

#include <malloc.h>
#include "ode/memory.h"
#include "ode/error.h"

#ifdef dDEBUG_ALLOC

#include <string.h>

// when debugging, this is a header that it put at start of all blocks.
// it contains `padding', which are PADSIZE elements of known value just
// before the user memory starts. another PADSIZE padding elements are put
// at the end of the user memory. the idea is that if the user accidentally
// steps outside the allocated memory, it can hopefully be detected by
// examining the padding elements.

#define PADSIZE 10
struct blockHeader {
  long pad1;			// protective padding
  long seq;			// sequence number
  long size;			// data size
  long flags;			// bit 0 = ignore this block in final report
  blockHeader *next,*prev;	// next & previous blocks
  long pad[PADSIZE];		// protective padding
};

// compute the memory block size, including padding. the user memory block is
// rounded up to a multiple of 4 bytes, to get alignment for the padding at
// the end of the block.

#define BSIZE(size) (((((size)-1) | 3)+1) + sizeof(blockHeader) + \
  PADSIZE * sizeof(long))

static blockHeader dummyblock = {0,0,0,0,&dummyblock,&dummyblock,
				 {0,0,0,0,0,0,0,0,0,0}};
static blockHeader *firstblock = &dummyblock;
static long num_blocks_alloced = 0;
static long num_bytes_alloced = 0;
static long total_num_blocks_alloced = 0;
static long total_num_bytes_alloced = 0;
static long max_blocks_alloced = 0;
static long max_bytes_alloced = 0;

long seqstop = 0;
void *ptrstop = 0;

static int checkBlockOk (void *ptr, int fatal)
{
  if (ptr==0) dDebug (0,"0 passed to checkBlockOk()");
  blockHeader *b = ((blockHeader*) ptr) - 1;
  int i,ok = 1;
  if (b->pad1 != (long)0xdeadbeef || b->seq < 0 || b->size < 0) ok = 0;
  if (ok) {
    for (i=0; i<PADSIZE; i++) if (b->pad[i] != (long)0xdeadbeef) ok = 0;
  }
  if (ok) {
    long *endpad = (long*) (((char*)ptr) + (((b->size-1) | 3)+1));
    for (i=0; i<PADSIZE; i++) if (endpad[i] != (long)0xdeadbeef) ok = 0;
  }
  if (!ok && fatal)
    dDebug (0,"corrupted memory block found, ptr=%p, size=%d, "
	    "seq=%ld", ptr,b->size,b->seq);
  return ok;
}

#endif

static dAllocFunction *allocfn = 0;
static dReallocFunction *reallocfn = 0;
static dFreeFunction *freefn = 0;

void dSetAllocHandler (dAllocFunction *fn)
{
  allocfn = fn;
}

void dSetReallocHandler (dReallocFunction *fn)
{
  reallocfn = fn;
}

void dSetFreeHandler (dFreeFunction *fn)
{
  freefn = fn;
}

void * dAlloc (int size)
{
#ifdef dDEBUG_ALLOC
  if (size < 1) dDebug (0,"bad block size to Alloc()");

  num_blocks_alloced++;
  num_bytes_alloced += size;
  total_num_blocks_alloced++;
  total_num_bytes_alloced += size;
  if (num_blocks_alloced > max_blocks_alloced)
    max_blocks_alloced = num_blocks_alloced;
  if (num_bytes_alloced > max_bytes_alloced)
    max_bytes_alloced = num_bytes_alloced;

  if (total_num_blocks_alloced == seqstop)
    dDebug (0,"ALLOCATOR TRAP ON SEQUENCE NUMBER %d",seqstop);
  long size2 = BSIZE(size);
  blockHeader *b = (blockHeader*) malloc (size2);
  if (b+1 == ptrstop)
    dDebug (0,"ALLOCATOR TRAP ON BLOCK POINTER %p",ptrstop);
  for (unsigned int i=0; i < (size2/sizeof(long)); i++)
    ((long*)b)[i] = 0xdeadbeef;
  b->seq = total_num_blocks_alloced;
  b->size = size;
  b->flags = 0;
  b->next = firstblock->next;
  b->prev = firstblock;
  firstblock->next->prev = b;
  firstblock->next = b;
  return b + 1;
#else
  if (allocfn) return allocfn (size); else return malloc (size);
#endif
}

void * dRealloc (void *ptr, int oldsize, int newsize)
{
#ifdef dDEBUG_ALLOC
  if (ptr==0) dDebug (0,"Realloc() called with ptr==0");
  checkBlockOk (ptr,1);
  blockHeader *b = ((blockHeader*) ptr) - 1;
  if (b->size != oldsize)
    dDebug (0,"Realloc(%p,%d,%d) has bad old size, good size "
	    "is %ld, seq=%ld",ptr,oldsize,newsize,b->size,b->seq);
  void *p = dAlloc (newsize);
  blockHeader *newb = ((blockHeader*) p) - 1;
  newb->flags = b->flags;
  if (oldsize>=1) memcpy (p,ptr,oldsize);
  dFree (ptr,oldsize);
  return p;
#else
  if (reallocfn) return reallocfn (ptr,oldsize,newsize);
  else return realloc (ptr,newsize);
#endif
}

void dFree (void *ptr, int size)
{
  if (!ptr) return;
#ifdef dDEBUG_ALLOC
  checkBlockOk (ptr,1);
  blockHeader *b = ((blockHeader*) ptr) - 1;
  if (b->size != size)
    dDebug (0,"Free(%p,%d) has bad size, good size "
	    "is %ld, seq=%ld",ptr,size,b->size,b->seq);
  num_blocks_alloced--;
  num_bytes_alloced -= b->size;
  if (num_blocks_alloced < 0 || num_bytes_alloced < 0)
    dDebug (0,"Free called too many times");

  b->next->prev = b->prev;
  b->prev->next = b->next;
  memset (b,0,BSIZE(b->size));

  free (b);
#else
  if (freefn) freefn (ptr,size); else free (ptr);
#endif
}

void dAllocDontReport (void *ptr)
{
#ifdef dDEBUG_ALLOC
  checkBlockOk (ptr,1);
  blockHeader *b = ((blockHeader*) ptr) - 1;
  b->flags |= 1;
#endif
}

#ifdef dDEBUG_ALLOC

#include <stdio.h>

static void printReport()
{
  // subtract the "dont report" blocks from the totals
  blockHeader *b = firstblock;
  do {
    if (b != &dummyblock && (b->flags & 1)) {
      num_blocks_alloced--;
      num_bytes_alloced -= b->size;
      if (!checkBlockOk (b+1,0))
	fprintf (stderr,"\tCORRUPTED: %p, size=%ld, seq=%ld\n",b+1,
		 b->size,b->seq);
    }
    b = b->prev;
  }
  while (b != firstblock);

  fprintf (stderr,"\nALLOCATOR REPORT\n");
  fprintf (stderr,"\tblocks still allocated:  %ld\n",num_blocks_alloced);
  fprintf (stderr,"\tbytes still allocated:   %ld\n",num_bytes_alloced);
  fprintf (stderr,"\ttotal blocks allocated:  %ld\n",total_num_blocks_alloced);
  fprintf (stderr,"\ttotal bytes allocated:   %ld\n",total_num_bytes_alloced);
  fprintf (stderr,"\tmax blocks allocated:    %ld\n",max_blocks_alloced);
  fprintf (stderr,"\tmax bytes allocated:     %ld\n",max_bytes_alloced);

  b = firstblock;
  do {
    if (b != &dummyblock && (b->flags & 1)==0) {
      int ok = checkBlockOk (b+1,0);
      fprintf (stderr,"\tUNFREED: %p, size=%ld, seq=%ld (%s)\n",b+1,
	       b->size,b->seq, ok ? "ok" : "CORUPTED");
    }
    b = b->prev;
  }
  while (b != firstblock);
  fprintf (stderr,"\n");
}

struct dMemoryReportPrinter {
  ~dMemoryReportPrinter() { printReport(); }
} _dReportPrinter;

#endif
<|endoftext|>


<commit_before>//
// Created by Vadim N. on 04/04/2015.
//

#include <ostream>

#include "Model"

using namespace ymir;

/**
 * \brief Main function of a script for generation of pre-selected receptors. It has
 * a strict order of input arguments in console:
 * argv[0] - name of the script (default);
 * argv[1] - path to a model;
 * argv[2] - number of immune receptors to generate;
 * argv[3] - path to an output file;
 * argv[4] - output sequence type: 0 for all, 1 for coding, 2 for noncoding.
 */
int main(int argc, char* argv[]) {
    std::string model_path(argv[1]), out_file_path(argv[3]);
    size_t count = std::stoi(argv[2]);
    SequenceCodingType coding_type = SequenceCodingType::ALL;
    if (argc >= 5) {
        switch (std::stoi(argv[4])) {
            case 0: {
                coding_type = SequenceCodingType::ALL;
                break;
            }
            case 1: {
                coding_type = SequenceCodingType::CODING;
                break;
            }
            case 2: {
                coding_type = SequenceCodingType::NONCODING;
                break;
            }
            default: {
                coding_type = SequenceCodingType::ALL;
            }
        }
    }

    std::cout << "Model path:\t" << model_path << std::endl;
    std::cout << "Output file:\t" << out_file_path << std::endl;
    std::cout << "Number of clonotypes:\t" << (size_t) count << std::endl;
    std::cout << std::endl;

    ProbabilisticAssemblingModel model(model_path);

    if (model.status()) {
        std::cout << std::endl;

        size_t to_generate, generated = 0;
        size_t block_size = 100000;
        RepertoireWriter writer;
        while (generated < count) {
            to_generate = std::min(count - generated, block_size);
            generated += to_generate;
            Cloneset gen_rep = model.generateSequences(to_generate, coding_type);
            if (!writer.write(out_file_path, gen_rep, model.gene_segments(), generated != to_generate)) {
                std::cout << "Problems in writing the output file. Terminating..." << std::endl;
            }
            std::cout << "Generated " << (size_t) generated << "/" << (size_t) count << std::endl;
        }
    } else {
        std::cout << "Problems with the model. Terminating..." << std::endl;
    }

    return 0;
}<commit_msg>add sequence coding type dependent generating<commit_after>//
// Created by Vadim N. on 04/04/2015.
//

#include <ostream>

#include "Model"

using namespace ymir;

/**
 * \brief Main function of a script for generation of pre-selected receptors. It has
 * a strict order of input arguments in console:
 * argv[0] - name of the script (default);
 * argv[1] - path to a model;
 * argv[2] - number of immune receptors to generate;
 * argv[3] - path to an output file;
 * argv[4] - output sequence type: 0 for all, 1 for coding, 2 for noncoding.
 */
int main(int argc, char* argv[]) {
    std::string model_path(argv[1]), out_file_path(argv[3]);
    size_t count = std::stoi(argv[2]);
    SequenceCodingType coding_type = SequenceCodingType::ALL;
    if (argc >= 5) {
        switch (std::stoi(argv[4])) {
            case 0: {
                coding_type = SequenceCodingType::ALL;
                break;
            }
            case 1: {
                coding_type = SequenceCodingType::CODING;
                break;
            }
            case 2: {
                coding_type = SequenceCodingType::NONCODING;
                break;
            }
            default: {
                coding_type = SequenceCodingType::ALL;
            }
        }
    }

    std::cout << "Model path:\t" << model_path << std::endl;
    std::cout << "Output file:\t" << out_file_path << std::endl;
    std::cout << "Number of clonotypes:\t" << (size_t) count << std::endl;
    std::cout << std::endl;

    ProbabilisticAssemblingModel model(model_path);

    if (model.status()) {
        std::cout << std::endl;

        size_t to_generate, generated = 0, generated_coding = 0, generated_noncoding = 0;
        size_t block_size = 100000;
        RepertoireWriter writer;
        bool first_iter = false;
        while (generated < count) {
            to_generate = std::min(count - generated, block_size);
            ClonesetView gen_rep = model.generateSequences(to_generate);

            if (coding_type == SequenceCodingType::CODING) {
                gen_rep = gen_rep.coding();
                if (gen_rep.size() > to_generate) {
                    gen_rep = gen_rep.head(to_generate);
                }
                generated_coding += gen_rep.size();
            } else if (coding_type == SequenceCodingType::NONCODING) {
                gen_rep = gen_rep.noncoding();
                if (gen_rep.size() > to_generate) {
                    gen_rep = gen_rep.head(to_generate);
                }
                generated_noncoding += gen_rep.size();
            } else {
                generated_coding += gen_rep.coding().size();
                generated_noncoding += gen_rep.noncoding().size();
            }

            generated = generated_coding + generated_noncoding;
            if (!writer.write(out_file_path, gen_rep, model.gene_segments(), first_iter)) {
                std::cout << "Problems occurred while writing the output file. Terminating..." << std::endl;
                break;
            }
            std::cout << "Generated " << (size_t) generated << "/" << (size_t) count << std::endl;
            std::cout << "\t- " << (size_t) generated_coding << " coding sequences" << std::endl;
            std::cout << "\t- " << (size_t) generated_noncoding << " noncoding sequences" << std::endl;

            first_iter = true;
        }
    } else {
        std::cout << "Problems with the model. Terminating..." << std::endl;
    }

    return 0;
}<|endoftext|>


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

#if DEVICE_SERIAL && DEVICE_SERIAL_FC

#include "CyH4TransportDriver.h"

namespace ble {
namespace vendor {
namespace cypress_ble {

CyH4TransportDriver::CyH4TransportDriver(PinName tx, PinName rx, PinName cts, PinName rts, int baud, PinName bt_host_wake_name, PinName bt_device_wake_name, uint8_t host_wake_irq, uint8_t dev_wake_irq) :
    uart(tx, rx, baud), cts(cts), rts(rts),
    bt_host_wake_name(bt_host_wake_name),
    bt_device_wake_name(bt_device_wake_name),
    bt_host_wake(bt_host_wake_name, PIN_INPUT, PullNone, 0),
    bt_device_wake(bt_device_wake_name, PIN_OUTPUT, PullNone, 1),
    host_wake_irq_event(host_wake_irq),
    dev_wake_irq_event(dev_wake_irq)
{
    enabled_powersave = true;
}

CyH4TransportDriver::CyH4TransportDriver(PinName tx, PinName rx, PinName cts, PinName rts, int baud) :
    uart(tx, rx, baud),
    cts(cts),
    rts(rts),
    bt_host_wake_name(NC),
    bt_device_wake_name(NC),
    bt_host_wake(bt_host_wake_name),
    bt_device_wake(bt_device_wake_name)
{
    enabled_powersave = false;
    sleep_manager_lock_deep_sleep();
    holding_deep_sleep_lock = true;
}

CyH4TransportDriver::~CyH4TransportDriver()
{
    if (holding_deep_sleep_lock)
    {
       sleep_manager_unlock_deep_sleep();
       holding_deep_sleep_lock = false;
    }
}

void CyH4TransportDriver::bt_host_wake_rise_irq_handler(void)
{
    if (host_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
        if(bt_host_wake_active == true)
        {
            /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
            sleep_manager_unlock_deep_sleep();
            bt_host_wake_active = false;
        }
    } else {
        /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
        sleep_manager_lock_deep_sleep();
        bt_host_wake_active = true;
    }
}

void CyH4TransportDriver::bt_host_wake_fall_irq_handler(void)
{
    if (host_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
        /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
        sleep_manager_lock_deep_sleep();
        bt_host_wake_active = true;
    } else {
        if(bt_host_wake_active == true)
        {
            /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
            sleep_manager_unlock_deep_sleep();
            bt_host_wake_active = false;
        }
    }
}

void CyH4TransportDriver::initialize()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
	InterruptIn *host_wake_pin;
#endif

    sleep_manager_lock_deep_sleep();

    uart.format(
        /* bits */ 8,
        /* parity */ SerialBase::None,
        /* stop bit */ 1
    );

    uart.set_flow_control(
        /* flow */ SerialBase::RTSCTS,
        /* rts */ rts,
        /* cts */ cts
    );

    uart.attach(
        callback(this, &CyH4TransportDriver::on_controller_irq),
        SerialBase::RxIrq
    );

    sleep_manager_unlock_deep_sleep();

#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (bt_host_wake_name != NC) {
        //Register IRQ for Host WAKE
        host_wake_pin = new InterruptIn(bt_host_wake_name);
        host_wake_pin->fall(callback(this, &CyH4TransportDriver::bt_host_wake_fall_irq_handler));
        host_wake_pin->rise(callback(this, &CyH4TransportDriver::bt_host_wake_rise_irq_handler));
    }
#endif
    if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
       if (bt_device_wake_name != NC)
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
    } else {
       if (bt_device_wake_name != NC)
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
    }
    sleep_manager_unlock_deep_sleep();
    rtos::ThisThread::sleep_for(500);
}

void CyH4TransportDriver::terminate() {  }

uint16_t CyH4TransportDriver::write(uint8_t type, uint16_t len, uint8_t *pData)
{
    uint16_t i = 0;

    sleep_manager_lock_deep_sleep();
    assert_bt_dev_wake();

    while (i < len + 1) {
        uint8_t to_write = i == 0 ? type : pData[i - 1];
        while (uart.writeable() == 0);
        uart.putc(to_write);
        ++i;
    }

    deassert_bt_dev_wake();
    sleep_manager_unlock_deep_sleep();
    return len;
}

void CyH4TransportDriver::on_controller_irq()
{
    sleep_manager_lock_deep_sleep();

    while (uart.readable()) {
        uint8_t char_received = uart.getc();
        on_data_received(&char_received, 1);
    }

    sleep_manager_unlock_deep_sleep();
}

void CyH4TransportDriver::assert_bt_dev_wake()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (enabled_powersave) {
        if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
        } else {
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
        }
    }
#endif
}

void CyH4TransportDriver::deassert_bt_dev_wake()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (enabled_powersave) {
        wait_us(5000); /* remove and replace when uart tx transmit complete api is available */
        //De-assert bt_device_wake
        if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
        } else {
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
        }
    }
#endif
}

void CyH4TransportDriver::update_uart_baud_rate(int baud)
{
    uart.baud(baud);
}

bool CyH4TransportDriver::get_enabled_powersave()
{
    return (enabled_powersave);
}

uint8_t CyH4TransportDriver::get_host_wake_irq_event()
{
    return (host_wake_irq_event);
}

uint8_t CyH4TransportDriver::get_dev_wake_irq_event()
{
    return (dev_wake_irq_event);
}

} // namespace cypress_ble
} // namespace vendor
} // namespace ble

ble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_default_h4_transport_driver()
{
#if (defined(CYBSP_BT_HOST_WAKE) && defined(CYBSP_BT_DEVICE_WAKE))
    static ble::vendor::cypress_ble::CyH4TransportDriver s_transport_driver(
       /* TX */ CYBSP_BT_UART_TX, /* RX */ CYBSP_BT_UART_RX,
       /* cts */ CYBSP_BT_UART_CTS, /* rts */ CYBSP_BT_UART_RTS, DEF_BT_BAUD_RATE,
       CYBSP_BT_HOST_WAKE, CYBSP_BT_DEVICE_WAKE
    );

#else
    static ble::vendor::cypress_ble::CyH4TransportDriver s_transport_driver(
        /* TX */ CYBSP_BT_UART_TX, /* RX */ CYBSP_BT_UART_RX,
        /* cts */ CYBSP_BT_UART_CTS, /* rts */ CYBSP_BT_UART_RTS, DEF_BT_BAUD_RATE);
#endif
    return s_transport_driver;
}

MBED_WEAK
ble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_h4_transport_driver()
{
    return (ble_cordio_get_default_h4_transport_driver());
}

#endif
<commit_msg>Address ARM Code review feedback.<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2017-2017 ARM Limited
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#if DEVICE_SERIAL && DEVICE_SERIAL_FC

#include "CyH4TransportDriver.h"

namespace ble {
namespace vendor {
namespace cypress_ble {

CyH4TransportDriver::CyH4TransportDriver(PinName tx, PinName rx, PinName cts, PinName rts, int baud, PinName bt_host_wake_name, PinName bt_device_wake_name, uint8_t host_wake_irq, uint8_t dev_wake_irq) :
    uart(tx, rx, baud), cts(cts), rts(rts),
    bt_host_wake_name(bt_host_wake_name),
    bt_device_wake_name(bt_device_wake_name),
    bt_host_wake(bt_host_wake_name, PIN_INPUT, PullNone, 0),
    bt_device_wake(bt_device_wake_name, PIN_OUTPUT, PullNone, 1),
    host_wake_irq_event(host_wake_irq),
    dev_wake_irq_event(dev_wake_irq)
{
    enabled_powersave = true;
    bt_host_wake_active = false;
}

CyH4TransportDriver::CyH4TransportDriver(PinName tx, PinName rx, PinName cts, PinName rts, int baud) :
    uart(tx, rx, baud),
    cts(cts),
    rts(rts),
    bt_host_wake_name(NC),
    bt_device_wake_name(NC),
    bt_host_wake(bt_host_wake_name),
    bt_device_wake(bt_device_wake_name)
{
    enabled_powersave = false;
    bt_host_wake_active = false;
    sleep_manager_lock_deep_sleep();
    holding_deep_sleep_lock = true;
}

CyH4TransportDriver::~CyH4TransportDriver()
{
    if (holding_deep_sleep_lock)
    {
       sleep_manager_unlock_deep_sleep();
       holding_deep_sleep_lock = false;
    }
}

void CyH4TransportDriver::bt_host_wake_rise_irq_handler(void)
{
    if (host_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
        if(bt_host_wake_active == true)
        {
            /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
            sleep_manager_unlock_deep_sleep();
            bt_host_wake_active = false;
        }
    } else {
        /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
        sleep_manager_lock_deep_sleep();
        bt_host_wake_active = true;
    }
}

void CyH4TransportDriver::bt_host_wake_fall_irq_handler(void)
{
    if (host_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
        /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
        sleep_manager_lock_deep_sleep();
        bt_host_wake_active = true;
    } else {
        if(bt_host_wake_active == true)
        {
            /* lock PSoC 6 DeepSleep entry as long as host_wake is asserted */
            sleep_manager_unlock_deep_sleep();
            bt_host_wake_active = false;
        }
    }
}

void CyH4TransportDriver::initialize()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
	InterruptIn *host_wake_pin;
#endif

    sleep_manager_lock_deep_sleep();

    uart.format(
        /* bits */ 8,
        /* parity */ SerialBase::None,
        /* stop bit */ 1
    );

    uart.set_flow_control(
        /* flow */ SerialBase::RTSCTS,
        /* rts */ rts,
        /* cts */ cts
    );

    uart.attach(
        callback(this, &CyH4TransportDriver::on_controller_irq),
        SerialBase::RxIrq
    );

    sleep_manager_unlock_deep_sleep();

#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (bt_host_wake_name != NC) {
        //Register IRQ for Host WAKE
        host_wake_pin = new InterruptIn(bt_host_wake_name);
        host_wake_pin->fall(callback(this, &CyH4TransportDriver::bt_host_wake_fall_irq_handler));
        host_wake_pin->rise(callback(this, &CyH4TransportDriver::bt_host_wake_rise_irq_handler));
    }
#endif
    if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
       if (bt_device_wake_name != NC)
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
    } else {
       if (bt_device_wake_name != NC)
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
    }
    sleep_manager_unlock_deep_sleep();
    rtos::ThisThread::sleep_for(500);
}

void CyH4TransportDriver::terminate() {  }

uint16_t CyH4TransportDriver::write(uint8_t type, uint16_t len, uint8_t *pData)
{
    uint16_t i = 0;

    sleep_manager_lock_deep_sleep();
    assert_bt_dev_wake();

    while (i < len + 1) {
        uint8_t to_write = i == 0 ? type : pData[i - 1];
        while (uart.writeable() == 0);
        uart.putc(to_write);
        ++i;
    }

    deassert_bt_dev_wake();
    sleep_manager_unlock_deep_sleep();
    return len;
}

void CyH4TransportDriver::on_controller_irq()
{
    sleep_manager_lock_deep_sleep();

    while (uart.readable()) {
        uint8_t char_received = uart.getc();
        on_data_received(&char_received, 1);
    }

    sleep_manager_unlock_deep_sleep();
}

void CyH4TransportDriver::assert_bt_dev_wake()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (enabled_powersave) {
        if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
        } else {
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
        }
    }
#endif
}

void CyH4TransportDriver::deassert_bt_dev_wake()
{
#if (defined(MBED_TICKLESS) && DEVICE_SLEEP && DEVICE_LPTICKER)
    if (enabled_powersave) {
        wait_us(5000); /* remove and replace when uart tx transmit complete api is available */
        //De-assert bt_device_wake
        if (dev_wake_irq_event == WAKE_EVENT_ACTIVE_LOW) {
           bt_device_wake = WAKE_EVENT_ACTIVE_HIGH;
        } else {
           bt_device_wake = WAKE_EVENT_ACTIVE_LOW;
        }
    }
#endif
}

void CyH4TransportDriver::update_uart_baud_rate(int baud)
{
    uart.baud(baud);
}

bool CyH4TransportDriver::get_enabled_powersave()
{
    return (enabled_powersave);
}

uint8_t CyH4TransportDriver::get_host_wake_irq_event()
{
    return (host_wake_irq_event);
}

uint8_t CyH4TransportDriver::get_dev_wake_irq_event()
{
    return (dev_wake_irq_event);
}

} // namespace cypress_ble
} // namespace vendor
} // namespace ble

ble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_default_h4_transport_driver()
{
#if (defined(CYBSP_BT_HOST_WAKE) && defined(CYBSP_BT_DEVICE_WAKE))
    static ble::vendor::cypress_ble::CyH4TransportDriver s_transport_driver(
       /* TX */ CYBSP_BT_UART_TX, /* RX */ CYBSP_BT_UART_RX,
       /* cts */ CYBSP_BT_UART_CTS, /* rts */ CYBSP_BT_UART_RTS, DEF_BT_BAUD_RATE,
       CYBSP_BT_HOST_WAKE, CYBSP_BT_DEVICE_WAKE
    );

#else
    static ble::vendor::cypress_ble::CyH4TransportDriver s_transport_driver(
        /* TX */ CYBSP_BT_UART_TX, /* RX */ CYBSP_BT_UART_RX,
        /* cts */ CYBSP_BT_UART_CTS, /* rts */ CYBSP_BT_UART_RTS, DEF_BT_BAUD_RATE);
#endif
    return s_transport_driver;
}

MBED_WEAK
ble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_h4_transport_driver()
{
    return (ble_cordio_get_default_h4_transport_driver());
}

#endif
<|endoftext|>


<commit_before>#include <cmath>

namespace planning {

inline double huber(double x, double k) {
  constexpr double half = 0.5;
  const double abs_x = std::abs(x);
  if (abs_x < k) {
    return (x * x) * half;
  } else {
    return k * (abs_x - (k * half));
  }
}

inline double square(double x) {
  return x * x;
}

inline double quad_hinge(double x, double k) {
  return square(std::max(x - k, 0.0));
}

}  // namespace planning
<commit_msg>Add huber hinge cost<commit_after>#include <cmath>

namespace planning {

inline double huber(double x, double k) {
  constexpr double half = 0.5;
  const double abs_x = std::abs(x);
  if (abs_x < k) {
    return (x * x) * half;
  } else {
    return k * (abs_x - (k * half));
  }
}

inline double square(double x) {
  return x * x;
}

inline double quad_hinge(double x, double k) {
  return square(std::max(x - k, 0.0));
}

inline double huber_hinge(double x, double hinge_k, double huber_k) {
  return huber(std::max(x - hinge_k, 0.0), huber_k);
}

}  // namespace planning
<|endoftext|>


<commit_before>/* Rapicorn Examples
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#include <rapicorn/rapicorn.hh>

namespace {
using namespace Rapicorn;

static bool
custom_commands (Window             &window,
                 const String       &command,
                 const StringVector &args)
{
  if (command == "testdump")
    {
      Root &root = window.root();
      TestStream *tstream = TestStream::create_test_stream();
      root.get_test_dump (*tstream);
      printout ("%s", tstream->string().c_str());
      delete tstream;
    }
  else
    printout ("%s(): custom command: %s(%s) (window: %s)\n", __func__,
              command.c_str(), string_join (",", args).c_str(), window.root().name().c_str());
  return true;
}

#include "../rapicorn-core/tests/testpixs.c" // alpha_rle alpha_raw rgb_rle rgb_raw

extern "C" int
main (int   argc,
      char *argv[])
{
  /* initialize Rapicorn and its gtk backend */
  Application::init_with_x11 (&argc, &argv, "TourTest");
  /* initialization acquired global Rapicorn mutex */

  /* register builtin images */
  Application::pixstream ("testimage-alpha-rle", alpha_rle);
  Application::pixstream ("testimage-alpha-raw", alpha_raw);
  Application::pixstream ("testimage-rgb-rle", rgb_rle);
  Application::pixstream ("testimage-rgb-raw", rgb_raw);

  /* load GUI definition file, relative to argv[0] */
  Application::auto_load ("RapicornTest", "tour.xml", argv[0]);

  /* create root item */
  Window window = Application::create_window ("tour-dialog");
  window.commands += custom_commands;

  window.show();

  Application::execute_loops();

  return 0;
}

} // anon
<commit_msg>tour.cc: added comment demonstrating TestStream filter<commit_after>/* Rapicorn Examples
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#include <rapicorn/rapicorn.hh>

namespace {
using namespace Rapicorn;

static bool
custom_commands (Window             &window,
                 const String       &command,
                 const StringVector &args)
{
  if (command == "testdump")
    {
      Root &root = window.root();
      TestStream *tstream = TestStream::create_test_stream();
      // tstream->filter_matched_nodes ("Button");
      root.get_test_dump (*tstream);
      printout ("%s", tstream->string().c_str());
      delete tstream;
    }
  else
    printout ("%s(): custom command: %s(%s) (window: %s)\n", __func__,
              command.c_str(), string_join (",", args).c_str(), window.root().name().c_str());
  return true;
}

#include "../rapicorn-core/tests/testpixs.c" // alpha_rle alpha_raw rgb_rle rgb_raw

extern "C" int
main (int   argc,
      char *argv[])
{
  /* initialize Rapicorn and its gtk backend */
  Application::init_with_x11 (&argc, &argv, "TourTest");
  /* initialization acquired global Rapicorn mutex */

  /* register builtin images */
  Application::pixstream ("testimage-alpha-rle", alpha_rle);
  Application::pixstream ("testimage-alpha-raw", alpha_raw);
  Application::pixstream ("testimage-rgb-rle", rgb_rle);
  Application::pixstream ("testimage-rgb-raw", rgb_raw);

  /* load GUI definition file, relative to argv[0] */
  Application::auto_load ("RapicornTest", "tour.xml", argv[0]);

  /* create root item */
  Window window = Application::create_window ("tour-dialog");
  window.commands += custom_commands;

  window.show();

  Application::execute_loops();

  return 0;
}

} // anon
<|endoftext|>


<commit_before>/* Rapicorn Examples
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#include <rapicorn.hh>

namespace {
using namespace Rapicorn;

static bool
custom_commands (Wind0wIface      &wind0w,
                 const String     &command,
                 const StringList &args)
{
  if (command == "testdump")
    {
      WindowImpl &window = wind0w.impl();
      TestStream *tstream = TestStream::create_test_stream();
      // tstream->filter_matched_nodes ("Button");
      window.get_test_dump (*tstream);
      printout ("%s", tstream->string().c_str());
      delete tstream;
    }
  else
    printout ("%s(): custom command: %s(%s) (wind0w: %s)\n", __func__,
              command.c_str(), string_join (",", args).c_str(), wind0w.impl().name().c_str());
  return true;
}

#include "../rcore/tests/testpixs.c" // alpha_rle alpha_raw rgb_rle rgb_raw

extern "C" int
main (int   argc,
      char *argv[])
{
  /* initialize Rapicorn and its gtk backend */
  Application_SmartHandle smApp = init_app (String ("Rapicorn/") + RAPICORN__FILE__, &argc, argv);
  ApplicationImpl &app = ApplicationImpl::the(); // FIXME: use Application_SmartHandle once C++ bindings are ready

  /* register builtin images */
  ApplicationIface::pixstream ("testimage-alpha-rle", alpha_rle);
  ApplicationIface::pixstream ("testimage-alpha-raw", alpha_raw);
  ApplicationIface::pixstream ("testimage-rgb-rle", rgb_rle);
  ApplicationIface::pixstream ("testimage-rgb-raw", rgb_raw);

  /* load GUI definition file, relative to argv[0] */
  app.auto_load ("RapicornTest", "tour.xml", argv[0]);

  /* create window item */
  Wind0wIface &wind0w = *app.create_wind0w ("tour-dialog");
  wind0w.sig_commands += custom_commands;

  wind0w.show();

  app.execute_loops();

  return 0;
}

} // anon
<commit_msg>EXAMPLES: fixed tour example to use IDL interfaces<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include <rapicorn.hh>

namespace {
using namespace Rapicorn;

static bool
custom_commands (Wind0w           &window,
                 const String     &command,
                 const StringList &args)
{
  if (command == "testdump")
    {
      // tstream->filter_matched_nodes ("Button");
      String s = window.test_dump();
      printout ("%s", s.c_str());
    }
  else
    printout ("%s(): custom command: %s(%s) (Window: %s)\n", __func__,
              command.c_str(), string_join (",", args).c_str(), window.name().c_str());
  return true;
}

#include "../rcore/tests/testpixs.c" // alpha_rle alpha_raw rgb_rle rgb_raw

extern "C" int
main (int   argc,
      char *argv[])
{
  // initialize Rapicorn
  Application app = init_app (String ("Rapicorn/") + RAPICORN__FILE__, &argc, argv);

#if 0 // FIMXE: test builtin images
  ApplicationIface::pixstream ("testimage-alpha-rle", alpha_rle);
  ApplicationIface::pixstream ("testimage-alpha-raw", alpha_raw);
  ApplicationIface::pixstream ("testimage-rgb-rle", rgb_rle);
  ApplicationIface::pixstream ("testimage-rgb-raw", rgb_raw);
#endif

  // load GUI definition file, relative to argv[0]
  app.auto_load ("RapicornTest", "tour.xml", argv[0]);

  // create window, handle commands
  Wind0w window = app.create_wind0w ("tour-dialog");
  window.commands += custom_commands;

  // display window and enter main event loop
  window.show();
  return app.run_and_exit();
}

} // anon
<|endoftext|>


<commit_before>#pragma once

#include "../../std/target_os.hpp"
#include "../../base/logging.hpp"

#include "../../base/logging.hpp"

#if defined(OMIM_OS_WINDOWS)
  #include "../../std/windows.hpp"
  #include <gl/gl.h>
  #define GL_GLEXT_PROTOTYPES
  #include "../../3party/GL/glext.h"

#elif defined(OMIM_OS_BADA)
  #include <FGraphicsOpengl.h>
  using namespace Osp::Graphics::Opengl;
  #define OMIM_GL_ES

#elif defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  #include <TargetConditionals.h>

  #ifdef OMIM_OS_IPHONE
    #define USE_OPENGLES20_IF_AVAILABLE 1
    #include <OpenGLES/ES2/gl.h>
    #define OMIM_GL_ES
  #else
    #include <OpenGL/gl.h>
    #include <OpenGL/glext.h>
  #endif

#elif defined(OMIM_OS_ANDROID)

  #include <GLES2/gl2.h>

  #define OMIM_GL_ES

#elif defined(OMIM_OS_MAEMO)
  #define USE_OPENGLES20_IF_AVAILABLE 1
  #include <GLES2/gl2.h>
  #include <GLES2/gl2ext.h>
  #define OMIM_GL_ES

#else
  #define GL_GLEXT_PROTOTYPES
  #include <GL/gl.h>
  #include <GL/glext.h>

#endif

#ifdef OMIM_OS_WINDOWS
  #define OPENGL_CALLING_CONVENTION __stdcall
#else
  #define OPENGL_CALLING_CONVENTION
#endif

#include "../../base/src_point.hpp"
#include "../../std/exception.hpp"

namespace graphics
{
  namespace gl
  {
    // basic opengl functions and constants
    extern void (OPENGL_CALLING_CONVENTION * glEnableFn)(GLenum cap);
    extern void (OPENGL_CALLING_CONVENTION * glDisableFn)(GLenum cap);
    extern void (OPENGL_CALLING_CONVENTION * glAlphaFuncFn)(GLenum func, GLclampf ref);
    extern void (OPENGL_CALLING_CONVENTION * glEnableClientStateFn) (GLenum array);
    extern void (OPENGL_CALLING_CONVENTION * glVertexPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glNormalPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glTexCoordPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);

    /// this is a quickfix for sharpness of straight texts and symbols.
    /// should be refactored to something more consistent.
    extern void (OPENGL_CALLING_CONVENTION * glUseSharpGeometryFn) (GLboolean flag);

    extern const GLenum GL_VERTEX_ARRAY_MWM;
    extern const GLenum GL_TEXTURE_COORD_ARRAY_MWM;
    extern const GLenum GL_NORMAL_ARRAY_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glMatrixModeFn) (GLenum mode);
    extern void (OPENGL_CALLING_CONVENTION * glLoadIdentityFn)();
    extern void (OPENGL_CALLING_CONVENTION * glLoadMatrixfFn) (const GLfloat *m);

    extern void (OPENGL_CALLING_CONVENTION * glOrthoFn) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
    extern void (OPENGL_CALLING_CONVENTION * glDrawElementsFn) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
    extern void (OPENGL_CALLING_CONVENTION * glFlushFn)();

    extern const GLenum GL_MODELVIEW_MWM;
    extern const GLenum GL_PROJECTION_MWM;

    extern const GLenum GL_ALPHA_TEST_MWM;

    /// information about supported extensions

    extern bool g_isMapBufferSupported;
    extern bool g_isBufferObjectsSupported;
    extern bool g_isFramebufferSupported;
    extern bool g_isRenderbufferSupported;
    extern bool g_isSeparateBlendFuncSupported;

    // buffer objects extensions

    extern const int GL_WRITE_ONLY_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glBindBufferFn) (GLenum target, GLuint buffer);
    extern void (OPENGL_CALLING_CONVENTION * glGenBuffersFn) (GLsizei n, GLuint *buffers);
    extern void (OPENGL_CALLING_CONVENTION * glBufferDataFn) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
    extern void (OPENGL_CALLING_CONVENTION * glBufferSubDataFn) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteBuffersFn) (GLsizei n, const GLuint *buffers);
    extern void * (OPENGL_CALLING_CONVENTION * glMapBufferFn) (GLenum target, GLenum access);
    extern GLboolean (OPENGL_CALLING_CONVENTION * glUnmapBufferFn) (GLenum target);

    // framebuffers extensions

    extern const int GL_FRAMEBUFFER_BINDING_MWM;
    extern const int GL_FRAMEBUFFER_MWM;
    extern const int GL_FRAMEBUFFER_UNSUPPORTED_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_MWM;
    extern const int GL_FRAMEBUFFER_COMPLETE_MWM;
    extern const int GL_DEPTH_ATTACHMENT_MWM;
    extern const int GL_COLOR_ATTACHMENT0_MWM;
    extern const int GL_RENDERBUFFER_MWM;
    extern const int GL_RENDERBUFFER_BINDING_MWM;
    extern const int GL_DEPTH_COMPONENT16_MWM;
    extern const int GL_DEPTH_COMPONENT24_MWM;
    extern const int GL_RGBA8_MWM;
    extern const int GL_RGBA4_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glBindFramebufferFn) (GLenum target, GLuint framebuffer);
    extern void (OPENGL_CALLING_CONVENTION * glFramebufferTexture2DFn) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
    extern void (OPENGL_CALLING_CONVENTION * glFramebufferRenderbufferFn) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
    extern void (OPENGL_CALLING_CONVENTION * glGenFramebuffersFn) (GLsizei n, GLuint *framebuffers);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteFramebuffersFn) (GLsizei n, const GLuint *framebuffers);
    extern GLenum (OPENGL_CALLING_CONVENTION * glCheckFramebufferStatusFn) (GLenum target);
    extern void (OPENGL_CALLING_CONVENTION * glDiscardFramebufferFn)(GLenum target, GLsizei numAttachments, GLenum const * attachments);

    // renderbuffer extensions

    extern void (OPENGL_CALLING_CONVENTION * glGenRenderbuffersFn) (GLsizei n, GLuint *renderbuffers);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteRenderbuffersFn) (GLsizei n, const GLuint *renderbuffers);
    extern void (OPENGL_CALLING_CONVENTION * glBindRenderbufferFn) (GLenum target, GLuint renderbuffer);
    extern void (OPENGL_CALLING_CONVENTION * glRenderbufferStorageFn) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);

    // separate alpha blending extension

    extern void (OPENGL_CALLING_CONVENTION * glBlendFuncSeparateFn) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);

    extern void (OPENGL_CALLING_CONVENTION * glActiveTextureFn) (GLenum texture);
    extern GLint (OPENGL_CALLING_CONVENTION * glGetAttribLocationFn) (GLuint program, const GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetActiveAttribFn)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
    extern GLint (OPENGL_CALLING_CONVENTION * glGetUniformLocationFn)(GLuint program, const GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetActiveUniformFn)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetProgramInfoLogFn)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
    extern void (OPENGL_CALLING_CONVENTION * glGetProgramivFn)(GLuint program, GLenum pname, GLint *params);
    extern void (OPENGL_CALLING_CONVENTION * glLinkProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glAttachShaderFn)(GLuint program, GLuint shader);
    extern GLuint (OPENGL_CALLING_CONVENTION * glCreateProgramFn)(void);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glVertexAttribPointerFn)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glEnableVertexAttribArrayFn)(GLuint index);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix4fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix3fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix2fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniform4iFn)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
    extern void (OPENGL_CALLING_CONVENTION * glUniform3iFn)(GLint location, GLint v0, GLint v1, GLint v2);
    extern void (OPENGL_CALLING_CONVENTION * glUniform2iFn)(GLint location, GLint v0, GLint v1);
    extern void (OPENGL_CALLING_CONVENTION * glUniform1iFn)(GLint location, GLint v0);
    extern void (OPENGL_CALLING_CONVENTION * glUniform4fFn)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
    extern void (OPENGL_CALLING_CONVENTION * glUniform3fFn)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
    extern void (OPENGL_CALLING_CONVENTION * glUniform2fFn)(GLint location, GLfloat v0, GLfloat v1);
    extern void (OPENGL_CALLING_CONVENTION * glUniform1fFn)(GLint location, GLfloat v0);
    extern void (OPENGL_CALLING_CONVENTION * glUseProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glGetShaderInfoLogFn)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
    extern void (OPENGL_CALLING_CONVENTION * glGetShaderivFn)(GLuint shader, GLenum pname, GLint *params);
    extern void (OPENGL_CALLING_CONVENTION * glCompileShaderFn)(GLuint shader);
    extern void (OPENGL_CALLING_CONVENTION * glShaderSourceFn)(GLuint shader, GLsizei count, const GLchar ** string, const GLint * length);
    extern GLuint (OPENGL_CALLING_CONVENTION * glCreateShaderFn)(GLenum type);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteShaderFn)(GLuint shader);

    /// This flag controls, whether OpenGL resources should delete themselves upon destruction.
    /// Sounds odd, but in EGL there are cases when the only function one should call to finish
    /// its work with resources is eglTerminate, which by itself internally deletes all OpenGL resources.
    /// In this case we should set this variable to true to correctly deletes all our wrapper
    /// classes without calls to glDeleteXXX.

    extern bool g_hasContext;

    /// This flag controls, whether the OGLCHECK macroses should log OGL calls.
    /// This is for debugging purpose only.

    extern bool g_doLogOGLCalls;

    /// each platform should have an implementation of this function
    /// to check extensions support and initialize function pointers.
    void InitExtensions();

    /// Does we have an extension with the specified name?
    bool HasExtension(char const * name);

    void DumpGLInformation();

    /// return false to terminate program
    /// @throws platform_unsupported - is the platform we are running on is unsupported.
    void CheckExtensionSupport();

    struct platform_unsupported : public exception
    {
      string m_reason;
      const char * what() const throw();
      platform_unsupported(char const * reason);
      ~platform_unsupported() throw();
    };

    void CheckError(my::SrcPoint const & srcPt);
    void CheckEGLError(my::SrcPoint const & srcPt);

  }
}

//#define OMIM_GL_ENABLE_TRACE 1

#ifdef DEBUG
  #ifdef OMIM_GL_ENABLE_TRACE
    #define OGLCHECK(f) do { if (graphics::gl::g_doLogOGLCalls) LOG(LDEBUG, (#f)); if (graphics::gl::g_hasContext) {f; graphics::gl::CheckError(SRC());} else LOG(LDEBUG, ("no OGL context. skipping OGL call")); } while(false)
    #define OGLCHECKAFTER if (graphics::gl::g_doLogOGLCalls) LOG(LDEBUG, ("OGLCHECKAFTER")); graphics::gl::CheckError(SRC())
    #define EGLCHECK do { LOG(LDEBUG, ("EGLCHECK")); graphics::gl::CheckEGLError(SRC()); } while(false)
  #else
    #define OGLCHECK(f) do { if (graphics::gl::g_hasContext) {f; graphics::gl::CheckError(SRC());} else LOG(LDEBUG, ("no OGL context. skipping OGL call.")); } while(false)
    #define OGLCHECKAFTER graphics::gl::CheckError(SRC())
    #define EGLCHECK do { graphics::gl::CheckEGLError(SRC()); } while(false)
  #endif

#else
#define OGLCHECK(f) do {if (graphics::gl::g_hasContext) {f;} else LOG(LDEBUG, ("no OGL context. skipping OGL call."));} while (false)
#define OGLCHECKAFTER
#define EGLCHECK
#endif
<commit_msg>[android] Fixed missing OpenGL calling convention for armeabi-v7a-hard<commit_after>#pragma once

#include "../../std/target_os.hpp"
#include "../../base/logging.hpp"

#include "../../base/logging.hpp"

#if defined(OMIM_OS_WINDOWS)
  #include "../../std/windows.hpp"
  #include <gl/gl.h>
  #define GL_GLEXT_PROTOTYPES
  #include "../../3party/GL/glext.h"

#elif defined(OMIM_OS_BADA)
  #include <FGraphicsOpengl.h>
  using namespace Osp::Graphics::Opengl;
  #define OMIM_GL_ES

#elif defined(OMIM_OS_MAC) || defined(OMIM_OS_IPHONE)
  #include <TargetConditionals.h>

  #ifdef OMIM_OS_IPHONE
    #define USE_OPENGLES20_IF_AVAILABLE 1
    #include <OpenGLES/ES2/gl.h>
    #define OMIM_GL_ES
  #else
    #include <OpenGL/gl.h>
    #include <OpenGL/glext.h>
  #endif

#elif defined(OMIM_OS_ANDROID)

  #include <GLES2/gl2.h>

  #define OMIM_GL_ES

#elif defined(OMIM_OS_MAEMO)
  #define USE_OPENGLES20_IF_AVAILABLE 1
  #include <GLES2/gl2.h>
  #include <GLES2/gl2ext.h>
  #define OMIM_GL_ES

#else
  #define GL_GLEXT_PROTOTYPES
  #include <GL/gl.h>
  #include <GL/glext.h>

#endif

#if defined(OMIM_OS_WINDOWS)
  #define OPENGL_CALLING_CONVENTION __stdcall
#elif defined(OMIM_OS_ANDROID)
  #define OPENGL_CALLING_CONVENTION __NDK_FPABI__
#else
  #define OPENGL_CALLING_CONVENTION
#endif

#include "../../base/src_point.hpp"
#include "../../std/exception.hpp"

namespace graphics
{
  namespace gl
  {
    // basic opengl functions and constants
    extern void (OPENGL_CALLING_CONVENTION * glEnableFn)(GLenum cap);
    extern void (OPENGL_CALLING_CONVENTION * glDisableFn)(GLenum cap);
    extern void (OPENGL_CALLING_CONVENTION * glAlphaFuncFn)(GLenum func, GLclampf ref);
    extern void (OPENGL_CALLING_CONVENTION * glEnableClientStateFn) (GLenum array);
    extern void (OPENGL_CALLING_CONVENTION * glVertexPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glNormalPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glTexCoordPointerFn) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);

    /// this is a quickfix for sharpness of straight texts and symbols.
    /// should be refactored to something more consistent.
    extern void (OPENGL_CALLING_CONVENTION * glUseSharpGeometryFn) (GLboolean flag);

    extern const GLenum GL_VERTEX_ARRAY_MWM;
    extern const GLenum GL_TEXTURE_COORD_ARRAY_MWM;
    extern const GLenum GL_NORMAL_ARRAY_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glMatrixModeFn) (GLenum mode);
    extern void (OPENGL_CALLING_CONVENTION * glLoadIdentityFn)();
    extern void (OPENGL_CALLING_CONVENTION * glLoadMatrixfFn) (const GLfloat *m);

    extern void (OPENGL_CALLING_CONVENTION * glOrthoFn) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
    extern void (OPENGL_CALLING_CONVENTION * glDrawElementsFn) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
    extern void (OPENGL_CALLING_CONVENTION * glFlushFn)();

    extern const GLenum GL_MODELVIEW_MWM;
    extern const GLenum GL_PROJECTION_MWM;

    extern const GLenum GL_ALPHA_TEST_MWM;

    /// information about supported extensions

    extern bool g_isMapBufferSupported;
    extern bool g_isBufferObjectsSupported;
    extern bool g_isFramebufferSupported;
    extern bool g_isRenderbufferSupported;
    extern bool g_isSeparateBlendFuncSupported;

    // buffer objects extensions

    extern const int GL_WRITE_ONLY_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glBindBufferFn) (GLenum target, GLuint buffer);
    extern void (OPENGL_CALLING_CONVENTION * glGenBuffersFn) (GLsizei n, GLuint *buffers);
    extern void (OPENGL_CALLING_CONVENTION * glBufferDataFn) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
    extern void (OPENGL_CALLING_CONVENTION * glBufferSubDataFn) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteBuffersFn) (GLsizei n, const GLuint *buffers);
    extern void * (OPENGL_CALLING_CONVENTION * glMapBufferFn) (GLenum target, GLenum access);
    extern GLboolean (OPENGL_CALLING_CONVENTION * glUnmapBufferFn) (GLenum target);

    // framebuffers extensions

    extern const int GL_FRAMEBUFFER_BINDING_MWM;
    extern const int GL_FRAMEBUFFER_MWM;
    extern const int GL_FRAMEBUFFER_UNSUPPORTED_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_MWM;
    extern const int GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_MWM;
    extern const int GL_FRAMEBUFFER_COMPLETE_MWM;
    extern const int GL_DEPTH_ATTACHMENT_MWM;
    extern const int GL_COLOR_ATTACHMENT0_MWM;
    extern const int GL_RENDERBUFFER_MWM;
    extern const int GL_RENDERBUFFER_BINDING_MWM;
    extern const int GL_DEPTH_COMPONENT16_MWM;
    extern const int GL_DEPTH_COMPONENT24_MWM;
    extern const int GL_RGBA8_MWM;
    extern const int GL_RGBA4_MWM;

    extern void (OPENGL_CALLING_CONVENTION * glBindFramebufferFn) (GLenum target, GLuint framebuffer);
    extern void (OPENGL_CALLING_CONVENTION * glFramebufferTexture2DFn) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
    extern void (OPENGL_CALLING_CONVENTION * glFramebufferRenderbufferFn) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
    extern void (OPENGL_CALLING_CONVENTION * glGenFramebuffersFn) (GLsizei n, GLuint *framebuffers);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteFramebuffersFn) (GLsizei n, const GLuint *framebuffers);
    extern GLenum (OPENGL_CALLING_CONVENTION * glCheckFramebufferStatusFn) (GLenum target);
    extern void (OPENGL_CALLING_CONVENTION * glDiscardFramebufferFn)(GLenum target, GLsizei numAttachments, GLenum const * attachments);

    // renderbuffer extensions

    extern void (OPENGL_CALLING_CONVENTION * glGenRenderbuffersFn) (GLsizei n, GLuint *renderbuffers);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteRenderbuffersFn) (GLsizei n, const GLuint *renderbuffers);
    extern void (OPENGL_CALLING_CONVENTION * glBindRenderbufferFn) (GLenum target, GLuint renderbuffer);
    extern void (OPENGL_CALLING_CONVENTION * glRenderbufferStorageFn) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);

    // separate alpha blending extension

    extern void (OPENGL_CALLING_CONVENTION * glBlendFuncSeparateFn) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);

    extern void (OPENGL_CALLING_CONVENTION * glActiveTextureFn) (GLenum texture);
    extern GLint (OPENGL_CALLING_CONVENTION * glGetAttribLocationFn) (GLuint program, const GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetActiveAttribFn)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
    extern GLint (OPENGL_CALLING_CONVENTION * glGetUniformLocationFn)(GLuint program, const GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetActiveUniformFn)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
    extern void (OPENGL_CALLING_CONVENTION * glGetProgramInfoLogFn)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
    extern void (OPENGL_CALLING_CONVENTION * glGetProgramivFn)(GLuint program, GLenum pname, GLint *params);
    extern void (OPENGL_CALLING_CONVENTION * glLinkProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glAttachShaderFn)(GLuint program, GLuint shader);
    extern GLuint (OPENGL_CALLING_CONVENTION * glCreateProgramFn)(void);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glVertexAttribPointerFn)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
    extern void (OPENGL_CALLING_CONVENTION * glEnableVertexAttribArrayFn)(GLuint index);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix4fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix3fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniformMatrix2fvFn)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
    extern void (OPENGL_CALLING_CONVENTION * glUniform4iFn)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
    extern void (OPENGL_CALLING_CONVENTION * glUniform3iFn)(GLint location, GLint v0, GLint v1, GLint v2);
    extern void (OPENGL_CALLING_CONVENTION * glUniform2iFn)(GLint location, GLint v0, GLint v1);
    extern void (OPENGL_CALLING_CONVENTION * glUniform1iFn)(GLint location, GLint v0);
    extern void (OPENGL_CALLING_CONVENTION * glUniform4fFn)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
    extern void (OPENGL_CALLING_CONVENTION * glUniform3fFn)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
    extern void (OPENGL_CALLING_CONVENTION * glUniform2fFn)(GLint location, GLfloat v0, GLfloat v1);
    extern void (OPENGL_CALLING_CONVENTION * glUniform1fFn)(GLint location, GLfloat v0);
    extern void (OPENGL_CALLING_CONVENTION * glUseProgramFn)(GLuint program);
    extern void (OPENGL_CALLING_CONVENTION * glGetShaderInfoLogFn)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
    extern void (OPENGL_CALLING_CONVENTION * glGetShaderivFn)(GLuint shader, GLenum pname, GLint *params);
    extern void (OPENGL_CALLING_CONVENTION * glCompileShaderFn)(GLuint shader);
    extern void (OPENGL_CALLING_CONVENTION * glShaderSourceFn)(GLuint shader, GLsizei count, const GLchar ** string, const GLint * length);
    extern GLuint (OPENGL_CALLING_CONVENTION * glCreateShaderFn)(GLenum type);
    extern void (OPENGL_CALLING_CONVENTION * glDeleteShaderFn)(GLuint shader);

    /// This flag controls, whether OpenGL resources should delete themselves upon destruction.
    /// Sounds odd, but in EGL there are cases when the only function one should call to finish
    /// its work with resources is eglTerminate, which by itself internally deletes all OpenGL resources.
    /// In this case we should set this variable to true to correctly deletes all our wrapper
    /// classes without calls to glDeleteXXX.

    extern bool g_hasContext;

    /// This flag controls, whether the OGLCHECK macroses should log OGL calls.
    /// This is for debugging purpose only.

    extern bool g_doLogOGLCalls;

    /// each platform should have an implementation of this function
    /// to check extensions support and initialize function pointers.
    void InitExtensions();

    /// Does we have an extension with the specified name?
    bool HasExtension(char const * name);

    void DumpGLInformation();

    /// return false to terminate program
    /// @throws platform_unsupported - is the platform we are running on is unsupported.
    void CheckExtensionSupport();

    struct platform_unsupported : public exception
    {
      string m_reason;
      const char * what() const throw();
      platform_unsupported(char const * reason);
      ~platform_unsupported() throw();
    };

    void CheckError(my::SrcPoint const & srcPt);
    void CheckEGLError(my::SrcPoint const & srcPt);

  }
}

//#define OMIM_GL_ENABLE_TRACE 1

#ifdef DEBUG
  #ifdef OMIM_GL_ENABLE_TRACE
    #define OGLCHECK(f) do { if (graphics::gl::g_doLogOGLCalls) LOG(LDEBUG, (#f)); if (graphics::gl::g_hasContext) {f; graphics::gl::CheckError(SRC());} else LOG(LDEBUG, ("no OGL context. skipping OGL call")); } while(false)
    #define OGLCHECKAFTER if (graphics::gl::g_doLogOGLCalls) LOG(LDEBUG, ("OGLCHECKAFTER")); graphics::gl::CheckError(SRC())
    #define EGLCHECK do { LOG(LDEBUG, ("EGLCHECK")); graphics::gl::CheckEGLError(SRC()); } while(false)
  #else
    #define OGLCHECK(f) do { if (graphics::gl::g_hasContext) {f; graphics::gl::CheckError(SRC());} else LOG(LDEBUG, ("no OGL context. skipping OGL call.")); } while(false)
    #define OGLCHECKAFTER graphics::gl::CheckError(SRC())
    #define EGLCHECK do { graphics::gl::CheckEGLError(SRC()); } while(false)
  #endif

#else
#define OGLCHECK(f) do {if (graphics::gl::g_hasContext) {f;} else LOG(LDEBUG, ("no OGL context. skipping OGL call."));} while (false)
#define OGLCHECKAFTER
#define EGLCHECK
#endif
<|endoftext|>