<commit_before>/************************************************************************
	filename: 	TLListHeader.cpp
	created:	14/6/2004
	author:		Paul D Turner

	purpose:	Implementation of Taharez MultiColumn list header widget.
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

    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; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "TLListHeader.h"
#include "CEGUIWindowManager.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
// type names for the component widgets
const utf8 TLListHeader::SegmentWidgetType[]	= "Taharez ListHeaderSegment";

/*************************************************************************
	Constructor
*************************************************************************/
TLListHeader::TLListHeader(const String& type, const String& name) :
	ListHeader(type, name)
{
}

/*************************************************************************
	Destructor
*************************************************************************/
TLListHeader::~TLListHeader(void)
{
}

/*************************************************************************
	Render the widget.
*************************************************************************/
void TLListHeader::drawSelf(float z)
{
}

/*************************************************************************
	Create and return a pointer to a new ListHeaderSegment based object.
*************************************************************************/
ListHeaderSegment* TLListHeader::createNewSegment(const String& name) const
{
	return (ListHeaderSegment*)WindowManager::getSingleton().createWindow(SegmentWidgetType, name);
}

/*************************************************************************
	Cleanup and destroy the given ListHeaderSegment that was created
	via the createNewSegment method.
*************************************************************************/
void TLListHeader::destroyListSegment(ListHeaderSegment* segment) const
{
	delete	segment;
}

//////////////////////////////////////////////////////////////////////////
/*************************************************************************

	Factory Methods

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
	Create, initialise and return a TLListHeader
*************************************************************************/
Window* TLListHeaderFactory::createWindow(const String& name)
{
	TLListHeader* wnd = new TLListHeader(d_type, name);
	wnd->initialise();

	return wnd;
}

} // End of  CEGUI namespace section
<commit_msg>Bug fix: header segments incorrectly destroyed.<commit_after>/************************************************************************
	filename: 	TLListHeader.cpp
	created:	14/6/2004
	author:		Paul D Turner

	purpose:	Implementation of Taharez MultiColumn list header widget.
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

    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; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "TLListHeader.h"
#include "CEGUIWindowManager.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
// type names for the component widgets
const utf8 TLListHeader::SegmentWidgetType[]	= "Taharez ListHeaderSegment";

/*************************************************************************
	Constructor
*************************************************************************/
TLListHeader::TLListHeader(const String& type, const String& name) :
	ListHeader(type, name)
{
}

/*************************************************************************
	Destructor
*************************************************************************/
TLListHeader::~TLListHeader(void)
{
}

/*************************************************************************
	Render the widget.
*************************************************************************/
void TLListHeader::drawSelf(float z)
{
}

/*************************************************************************
	Create and return a pointer to a new ListHeaderSegment based object.
*************************************************************************/
ListHeaderSegment* TLListHeader::createNewSegment(const String& name) const
{
	return (ListHeaderSegment*)WindowManager::getSingleton().createWindow(SegmentWidgetType, name);
}

/*************************************************************************
	Cleanup and destroy the given ListHeaderSegment that was created
	via the createNewSegment method.
*************************************************************************/
void TLListHeader::destroyListSegment(ListHeaderSegment* segment) const
{
	WindowManager::getSingleton().destroyWindow(segment);
}

//////////////////////////////////////////////////////////////////////////
/*************************************************************************

	Factory Methods

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
	Create, initialise and return a TLListHeader
*************************************************************************/
Window* TLListHeaderFactory::createWindow(const String& name)
{
	TLListHeader* wnd = new TLListHeader(d_type, name);
	wnd->initialise();

	return wnd;
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include "consoleUtil.h"
#include "Deck.h"
#include "TexasHoldem.h"
#include "poker.h"
#include <windows.h>
#include <conio.h>

using namespace std;

#define		CONS_WD		80
#define		TABLE_X		10
#define		TABLE_Y		(COM_Y+PLAYER_HT+1)
#define		TABLE_HT		3
#define		TABLE_WD		(2+2*5+1*4+2)
#define		PLAYER_HT	4
#define		PLAYER_WD	(1+8+1)		//	" COMPUTER ", "  HUMAN   "
#define		COM_X			(TABLE_X + (TABLE_WD - PLAYER_WD) / 2)
#define		COM_Y			2
#define		COM_BET_X	(COM_X + PLAYER_WD + 1)
#define		COM_BET_Y	(COM_Y + 1)
#define		MAN_X			COM_X
#define		MAN_Y			(TABLE_Y+TABLE_HT+1)
#define		MAN_BET_X	(MAN_X + PLAYER_WD + 1)
#define		MAN_BET_Y	(MAN_Y + 1)
#define		POT_X			(TABLE_X + TABLE_WD + 1)
#define		POT_Y			(TABLE_Y + 1)
#define		MENU_X		2
#define		MENU_Y		(MAN_Y+PLAYER_HT+1)
#define		N_MENU		3		//	j[I
#define		MENU_FOLD	0
#define		MENU_CC		1		//	Check/Call
#define		MENU_RAISE	2
#define		KEY_SPECIAL	0xe0
#define		KEY_LEFT		0x4b
#define		KEY_RIGHT	0x4d
#define		ACT_FOLD		1
#define		ACT_CC			2		//	Check/Call
#define		ACT_RAISE	3

TexasHoldem g_table;
int	g_comIX;
int	g_manIX;

int	g_menuIX;			//	IĂ郁j[IX
const char *g_menu[] = {
	"Fold", "Check/Call", "Raise"
};

int getChar()
{
	int ch = _getch();
	if( ch == KEY_SPECIAL ) {		//	L[Ȃǂ̏ꍇ
		ch = _getch();
		if( ch == KEY_LEFT )
			return VK_LEFT;
		if( ch == KEY_RIGHT )
			return VK_RIGHT;
		return 0;
	} else
		return ch;
}

void draw_card(int x, int y, Card c)
{
	if( c.m_suit == Card::SPADES || c.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(x, y);
	coutW(c.toStringW());
}

void draw_com(bool open = false);
void draw_com(bool open)
{
	setCursorPos(COM_X, COM_Y);
	setColor(COL_BLACK, COL_YELLOW);
	cout << " COMPUTER ";
	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(COM_X, COM_Y+1);
	cout << "chip:" << g_table.chip(g_comIX);
	if( g_comIX == g_table.dealerIX() ) {
		setCursorPos(COM_X - 2, COM_Y);
		cout << "D";
	}
	if( g_comIX == g_table.BBIX() ) {
		setCursorPos(COM_X - 3, COM_Y + 1);
		cout << "BB";
	}
	if( g_comIX == g_table.SBIX() ) {
		setCursorPos(COM_X - 3, COM_Y + 1);
		cout << "SB";
	}
	setCursorPos(COM_BET_X, COM_BET_Y);
	cout << "bet:" << g_table.bet(g_comIX) << "      ";
	if( open ) {
		Card c1, c2;
		g_table.getHoleCards(g_comIX, c1, c2);
		draw_card(COM_X, COM_Y+2, c1);
		draw_card(COM_X+3, COM_Y+2, c2);
	} else {
		setColor(COL_BLACK, COL_CYAN);
		setCursorPos(COM_X, COM_Y+2);
		cout << "  ";
		setCursorPos(COM_X+3, COM_Y+2);
		cout << "  ";
	}
}
void draw_human()
{
	setCursorPos(MAN_X, MAN_Y);
	setColor(COL_BLACK, COL_YELLOW);
	cout << "  HUMAN   ";
	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(MAN_X, MAN_Y+1);
	cout << "chip:" << g_table.chip(g_manIX);
	setCursorPos(MAN_BET_X, MAN_BET_Y);
	cout << "bet:" << g_table.bet(g_manIX) << "      ";
	if( g_manIX == g_table.dealerIX() ) {
		setCursorPos(MAN_X - 2, MAN_Y);
		cout << "D";
	}
	if( g_manIX == g_table.BBIX() ) {
		setCursorPos(MAN_X - 3, MAN_Y + 1);
		cout << "BB";
	}
	if( g_manIX == g_table.SBIX() ) {
		setCursorPos(MAN_X - 3, MAN_Y + 1);
		cout << "SB";
	}
	Card c1, c2;
	g_table.getHoleCards(g_manIX, c1, c2);
	if( c1.m_suit == Card::SPADES || c1.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(MAN_X, MAN_Y+2);
	coutW(c1.toStringW());
	//cout << " ";
	if( c2.m_suit == Card::SPADES || c2.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(MAN_X+3, MAN_Y+2);
	coutW(c2.toStringW());
	//cout << "?? ??";
}
void draw_table()
{
	setColor(COL_WHITE, COL_DARK_GREEN);
	for(int k = 0; k < TABLE_HT; ++k) {
		setCursorPos(TABLE_X, k + TABLE_Y);
		for(int i = 0; i < TABLE_WD; ++i)
			cout << " ";
	}
	const std::vector<Card> &cc = g_table.communityCards();
	for (int i = 0; i < (int)cc.size(); ++i) {
		//setCursorPos(TABLE_X + 2 + i * 3, TABLE_Y + 1);
		draw_card(TABLE_X + 2 + i * 3, TABLE_Y + 1, cc[i]);
	}

	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(POT_X, POT_Y);
	cout << "Pot:" << g_table.pot() << "        ";
}
void show_message(const char *ptr)
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	cout << ptr;
}
void clear_menu()
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	for (int i = 0; i < CONS_WD; ++i) {
		cout << " ";
	}
}
void draw_menu()
{
	setCursorPos(MENU_X, MENU_Y);
	for (int i = 0; i < N_MENU; ++i) {
		if( i == g_menuIX )
			setColor(COL_BLACK, COL_WHITE);
		else
			setColor(COL_GRAY, COL_BLACK);
		cout << "[" << g_menu[i] << "]";
		setColor(COL_GRAY, COL_BLACK);
		cout << " ";
	}
}
void print_result(const uint odr[])
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	if( odr[g_manIX] > odr[g_comIX] ) {
		cout << "+++ You Win +++";
		g_table.winner(g_manIX);
	} else if( odr[g_manIX] < odr[g_comIX] ) {
		cout << "--- Com Win ---";
		g_table.winner(g_comIX);
	} else {
		cout << "=== Split ===";
		std::vector<int> v;
		v.push_back(g_manIX);
		v.push_back(g_comIX);
		g_table.split(v);
	}
	cout << " (Push Any Key)";
}
//	vtbvAtbvA^[Ao[̏
//	SR[Freturn true;
//	lȊOS~肽Freturn false;
bool turn()
{
	int pix = g_table.dealerIX() + 1;		//	݂̎
	if( g_table.turn() == TexasHoldem::PRE_FLOP )
		pix += 2;
	for (;;) {
		draw_com();
		draw_human();
		draw_table();
		int act = 0;
		while( pix >= g_table.nPlayer() )
			pix -= g_table.nPlayer();
		if( pix == g_manIX ) {
			g_menuIX = MENU_CC;		//	Check/Call
			for (;;) {
				draw_menu();
				int ch = _getch();
				if( ch == 'Q' || ch == 'q' )
					return 0;
				if( ch == KEY_SPECIAL ) {		//	L[Ȃǂ̏ꍇ
					ch = _getch();
					if( ch == KEY_LEFT && g_menuIX != 0 )
						--g_menuIX;
					else if( ch == KEY_RIGHT && g_menuIX < N_MENU - 1)
						++g_menuIX;
				}
				if( ch == '\r' || ch == '\n' ) {	//	j[m
					break;
				}
			}
			clear_menu();
			switch( g_menuIX ) {
				case MENU_FOLD:
					act = ACT_FOLD;
					break;
				case MENU_CC: {
					act = ACT_CC;
					break;
				}
				case MENU_RAISE:
					act = ACT_RAISE;
					break;
			}
		} else {
			Sleep(500);
			act = ACT_CC;
		}
		switch( act ) {
			case ACT_CC: {
				int b = g_table.call() - g_table.bet(pix);
				if( b != 0 ) {
					g_table.addBet(pix, b);
				}
				break;
			}
		}
		if( g_table.allCalled() )
			return true;
		++pix;
	}
}
int main()
{
	g_table.addPlayer(Player("YOU", 200));
	g_manIX = 0;
	g_table.addPlayer(Player("COM", 200, /*comp:*/true));
	g_comIX = 1;
	g_table.setDealer();
	setColor(COL_BLACK, COL_WHITE);
	setCursorPos(5, 0);
	cout << "*** Texas Hold'em Poker ***";
	for (;;) {
		g_table.dealHoleCards();
		if( turn() ) {
			//	܂QlȏcĂꍇ
			g_table.dealFlop();
			if( turn() ) {
				//	܂QlȏcĂꍇ
				g_table.dealTurn();
				if( turn() ) {
					//	܂QlȏcĂꍇ
					g_table.dealTurn();
					turn();
				}
			}
		}
		draw_com(/*open:*/true);
		//	Z
		uint odr[2];		//	undone: RlȏΉ
		uint hand[2];
		std::vector<Card> v;
		for (int i = 0; i < g_table.nPlayer(); ++i) {
			g_table.playersCard(i, v);
			hand[i] = checkHand(v, odr[i]);
		}
		setColor(COL_GRAY, COL_BLACK);
		setCursorPos(COM_X, COM_Y + 3);
		cout << handName[hand[g_comIX]];
		setCursorPos(MAN_X, MAN_Y + 3);
		cout << handName[hand[g_manIX]];
		print_result(odr);
		getChar();
		clear_menu();
		draw_com(/*open:*/true);
		draw_human();
		draw_table();
		show_message("Push Enter Key");
		getChar();
		clear_menu();
		g_table.forwardDealer();
	}
	//getchar();
	return 0;
}
/*
 e[uőR~jeBJ[hɍ킹
 fB[}[N\
 BB, SB }[N\
 `bv𐳂\
 pot \
 evC[̃xbgz\
  mt19937 ɕύX
 J[h\Fwiɍ or Ԃŕ`
 ĂJ[h̓VAŕ\
 j[f[^
 EL[Ńj[I\
 Ƃ肠 Check/Call Őɐi߂悤ɂ
 R[Ã^[ɐi
 R~jeBJ[h𐳂\
 FR[Ɏ`bvĂȂ
 FZɃRs[^̎DI[vȂ
 ZFʕ\
 lԂ̎ԂłȂƂ́Aj[悢
 ʕ\
 PQ[I̐Z
 ̃Q[ɐi񂾎AfB[i܂Ȃ
 FQQ[ڂɐisĂ܂
 FfB[[}[NȂ
 FZ̓xbgl\悢
 tH[h
 ㉺L[ŃCYzݒ\
 [AllIn] j[ǉ
*/
<commit_msg>ディーラーマークが消えない<commit_after>#include "consoleUtil.h"
#include "Deck.h"
#include "TexasHoldem.h"
#include "poker.h"
#include <windows.h>
#include <conio.h>

using namespace std;

#define		CONS_WD		80
#define		TABLE_X		10
#define		TABLE_Y		(COM_Y+PLAYER_HT+1)
#define		TABLE_HT		3
#define		TABLE_WD		(2+2*5+1*4+2)
#define		PLAYER_HT	4
#define		PLAYER_WD	(1+8+1)		//	" COMPUTER ", "  HUMAN   "
#define		COM_X			(TABLE_X + (TABLE_WD - PLAYER_WD) / 2)
#define		COM_Y			2
#define		COM_BET_X	(COM_X + PLAYER_WD + 1)
#define		COM_BET_Y	(COM_Y + 1)
#define		MAN_X			COM_X
#define		MAN_Y			(TABLE_Y+TABLE_HT+1)
#define		MAN_BET_X	(MAN_X + PLAYER_WD + 1)
#define		MAN_BET_Y	(MAN_Y + 1)
#define		POT_X			(TABLE_X + TABLE_WD + 1)
#define		POT_Y			(TABLE_Y + 1)
#define		MENU_X		2
#define		MENU_Y		(MAN_Y+PLAYER_HT+1)
#define		N_MENU		3		//	j[I
#define		MENU_FOLD	0
#define		MENU_CC		1		//	Check/Call
#define		MENU_RAISE	2
#define		KEY_SPECIAL	0xe0
#define		KEY_LEFT		0x4b
#define		KEY_RIGHT	0x4d
#define		ACT_FOLD		1
#define		ACT_CC			2		//	Check/Call
#define		ACT_RAISE	3

TexasHoldem g_table;
int	g_comIX;
int	g_manIX;

int	g_menuIX;			//	IĂ郁j[IX
const char *g_menu[] = {
	"Fold", "Check/Call", "Raise"
};

int getChar()
{
	int ch = _getch();
	if( ch == KEY_SPECIAL ) {		//	L[Ȃǂ̏ꍇ
		ch = _getch();
		if( ch == KEY_LEFT )
			return VK_LEFT;
		if( ch == KEY_RIGHT )
			return VK_RIGHT;
		return 0;
	} else
		return ch;
}

void draw_card(int x, int y, Card c)
{
	if( c.m_suit == Card::SPADES || c.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(x, y);
	coutW(c.toStringW());
}

void draw_com(bool open = false);
void draw_com(bool open)
{
	setCursorPos(COM_X, COM_Y);
	setColor(COL_BLACK, COL_YELLOW);
	cout << " COMPUTER ";
	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(COM_X, COM_Y+1);
	cout << "chip:" << g_table.chip(g_comIX);
		setCursorPos(COM_X - 2, COM_Y);
	if( g_comIX == g_table.dealerIX() ) {
		cout << "D";
	} else
		cout << " ";
	if( g_comIX == g_table.BBIX() ) {
		setCursorPos(COM_X - 3, COM_Y + 1);
		cout << "BB";
	}
	if( g_comIX == g_table.SBIX() ) {
		setCursorPos(COM_X - 3, COM_Y + 1);
		cout << "SB";
	}
	setCursorPos(COM_BET_X, COM_BET_Y);
	cout << "bet:" << g_table.bet(g_comIX) << "      ";
	if( open ) {
		Card c1, c2;
		g_table.getHoleCards(g_comIX, c1, c2);
		draw_card(COM_X, COM_Y+2, c1);
		draw_card(COM_X+3, COM_Y+2, c2);
	} else {
		setColor(COL_BLACK, COL_CYAN);
		setCursorPos(COM_X, COM_Y+2);
		cout << "  ";
		setCursorPos(COM_X+3, COM_Y+2);
		cout << "  ";
	}
}
void draw_human()
{
	setCursorPos(MAN_X, MAN_Y);
	setColor(COL_BLACK, COL_YELLOW);
	cout << "  HUMAN   ";
	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(MAN_X, MAN_Y+1);
	cout << "chip:" << g_table.chip(g_manIX);
	setCursorPos(MAN_BET_X, MAN_BET_Y);
	cout << "bet:" << g_table.bet(g_manIX) << "      ";
	setCursorPos(MAN_X - 2, MAN_Y);
	if( g_manIX == g_table.dealerIX() ) {
		cout << "D";
	} else
		cout << " ";
	if( g_manIX == g_table.BBIX() ) {
		setCursorPos(MAN_X - 3, MAN_Y + 1);
		cout << "BB";
	}
	if( g_manIX == g_table.SBIX() ) {
		setCursorPos(MAN_X - 3, MAN_Y + 1);
		cout << "SB";
	}
	Card c1, c2;
	g_table.getHoleCards(g_manIX, c1, c2);
	if( c1.m_suit == Card::SPADES || c1.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(MAN_X, MAN_Y+2);
	coutW(c1.toStringW());
	//cout << " ";
	if( c2.m_suit == Card::SPADES || c2.m_suit == Card::CLUBS )
		setColor(COL_BLACK, COL_WHITE);
	else
		setColor(COL_RED, COL_WHITE);
	setCursorPos(MAN_X+3, MAN_Y+2);
	coutW(c2.toStringW());
	//cout << "?? ??";
}
void draw_table()
{
	setColor(COL_WHITE, COL_DARK_GREEN);
	for(int k = 0; k < TABLE_HT; ++k) {
		setCursorPos(TABLE_X, k + TABLE_Y);
		for(int i = 0; i < TABLE_WD; ++i)
			cout << " ";
	}
	const std::vector<Card> &cc = g_table.communityCards();
	for (int i = 0; i < (int)cc.size(); ++i) {
		//setCursorPos(TABLE_X + 2 + i * 3, TABLE_Y + 1);
		draw_card(TABLE_X + 2 + i * 3, TABLE_Y + 1, cc[i]);
	}

	setColor(COL_GRAY, COL_BLACK);
	setCursorPos(POT_X, POT_Y);
	cout << "Pot:" << g_table.pot() << "        ";
}
void show_message(const char *ptr)
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	cout << ptr;
}
void clear_menu()
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	for (int i = 0; i < CONS_WD; ++i) {
		cout << " ";
	}
}
void draw_menu()
{
	setCursorPos(MENU_X, MENU_Y);
	for (int i = 0; i < N_MENU; ++i) {
		if( i == g_menuIX )
			setColor(COL_BLACK, COL_WHITE);
		else
			setColor(COL_GRAY, COL_BLACK);
		cout << "[" << g_menu[i] << "]";
		setColor(COL_GRAY, COL_BLACK);
		cout << " ";
	}
}
void print_result(const uint odr[])
{
	setCursorPos(MENU_X, MENU_Y);
	setColor(COL_GRAY, COL_BLACK);
	if( odr[g_manIX] > odr[g_comIX] ) {
		cout << "+++ You Win +++";
		g_table.winner(g_manIX);
	} else if( odr[g_manIX] < odr[g_comIX] ) {
		cout << "--- Com Win ---";
		g_table.winner(g_comIX);
	} else {
		cout << "=== Split ===";
		std::vector<int> v;
		v.push_back(g_manIX);
		v.push_back(g_comIX);
		g_table.split(v);
	}
	cout << " (Push Any Key)";
}
//	vtbvAtbvA^[Ao[̏
//	SR[Freturn true;
//	lȊOS~肽Freturn false;
bool turn()
{
	int pix = g_table.dealerIX() + 1;		//	݂̎
	if( g_table.turn() == TexasHoldem::PRE_FLOP )
		pix += 2;
	for (;;) {
		draw_com();
		draw_human();
		draw_table();
		int act = 0;
		while( pix >= g_table.nPlayer() )
			pix -= g_table.nPlayer();
		if( pix == g_manIX ) {
			g_menuIX = MENU_CC;		//	Check/Call
			for (;;) {
				draw_menu();
				int ch = _getch();
				if( ch == 'Q' || ch == 'q' )
					return 0;
				if( ch == KEY_SPECIAL ) {		//	L[Ȃǂ̏ꍇ
					ch = _getch();
					if( ch == KEY_LEFT && g_menuIX != 0 )
						--g_menuIX;
					else if( ch == KEY_RIGHT && g_menuIX < N_MENU - 1)
						++g_menuIX;
				}
				if( ch == '\r' || ch == '\n' ) {	//	j[m
					break;
				}
			}
			clear_menu();
			switch( g_menuIX ) {
				case MENU_FOLD:
					act = ACT_FOLD;
					break;
				case MENU_CC: {
					act = ACT_CC;
					break;
				}
				case MENU_RAISE:
					act = ACT_RAISE;
					break;
			}
		} else {
			Sleep(500);
			act = ACT_CC;
		}
		switch( act ) {
			case ACT_CC: {
				int b = g_table.call() - g_table.bet(pix);
				if( b != 0 ) {
					g_table.addBet(pix, b);
				}
				break;
			}
		}
		if( g_table.allCalled() )
			return true;
		++pix;
	}
}
int main()
{
	g_table.addPlayer(Player("YOU", 200));
	g_manIX = 0;
	g_table.addPlayer(Player("COM", 200, /*comp:*/true));
	g_comIX = 1;
	g_table.setDealer();
	setColor(COL_BLACK, COL_WHITE);
	setCursorPos(5, 0);
	cout << "*** Texas Hold'em Poker ***";
	for (;;) {
		g_table.dealHoleCards();
		if( turn() ) {
			//	܂QlȏcĂꍇ
			g_table.dealFlop();
			if( turn() ) {
				//	܂QlȏcĂꍇ
				g_table.dealTurn();
				if( turn() ) {
					//	܂QlȏcĂꍇ
					g_table.dealTurn();
					turn();
				}
			}
		}
		draw_com(/*open:*/true);
		//	Z
		uint odr[2];		//	undone: RlȏΉ
		uint hand[2];
		std::vector<Card> v;
		for (int i = 0; i < g_table.nPlayer(); ++i) {
			g_table.playersCard(i, v);
			hand[i] = checkHand(v, odr[i]);
		}
		setColor(COL_GRAY, COL_BLACK);
		setCursorPos(COM_X, COM_Y + 3);
		cout << handName[hand[g_comIX]];
		setCursorPos(MAN_X, MAN_Y + 3);
		cout << handName[hand[g_manIX]];
		print_result(odr);
		getChar();
		clear_menu();
		draw_com(/*open:*/true);
		draw_human();
		draw_table();
		show_message("Push Enter Key");
		getChar();
		clear_menu();
		g_table.forwardDealer();
	}
	//getchar();
	return 0;
}
/*
 e[uőR~jeBJ[hɍ킹
 fB[}[N\
 BB, SB }[N\
 `bv𐳂\
 pot \
 evC[̃xbgz\
  mt19937 ɕύX
 J[h\Fwiɍ or Ԃŕ`
 ĂJ[h̓VAŕ\
 j[f[^
 EL[Ńj[I\
 Ƃ肠 Check/Call Őɐi߂悤ɂ
 R[Ã^[ɐi
 R~jeBJ[h𐳂\
 FR[Ɏ`bvĂȂ
 FZɃRs[^̎DI[vȂ
 ZFʕ\
 lԂ̎ԂłȂƂ́Aj[悢
 ʕ\
 PQ[I̐Z
 ̃Q[ɐi񂾎AfB[i܂Ȃ
 FQQ[ڂɐisĂ܂
 FfB[[}[NȂ
 FZ̓xbgl\悢
 tH[h
 ㉺L[ŃCYzݒ\
 [AllIn] j[ǉ
*/
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Copyright (C) 2008,  Simon Kagstrom
 *
 * Filename:      memory.cc
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Memory insns
 *
 * $Id:$
 *
 ********************************************************************/

class LoadXX : public Instruction
{
public:
  LoadXX(const char *what, uint32_t address, int opcode,
	 MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : Instruction(address, opcode, rs, rt, R_ZERO, extra)
  {
    this->bc = what;
  }

  bool pass1()
  {
    return true;
  }

  bool pass2()
  {
    emit->bc_pushaddress( this->rs, this->extra );
    /* Either a call to a subroutine or a regular function call */
    if ( config->optimizePartialMemoryOps &&
         this->opcode != OP_LWL && this->opcode != OP_LWR)
      emit->bc_jsr("__CIBYL_memoryRead%s", this->bc);
    else
      emit->bc_invokestatic("CRunTime/memoryRead%s(I)I", this->bc);
    emit->bc_popregister( this->rt );
    return true;
  }

  int fillDestinations(int *p)
  {
    if ( config->optimizePartialMemoryOps )
      return this->addToRegisterUsage(this->rt, p) + this->addToRegisterUsage(R_MADR, p);

    return this->addToRegisterUsage(this->rt, p);
  }

  int fillSources(int *p)
  {
    return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_MEM, p);
  };

  virtual size_t bytecodeSize(void)
  {
    return 13;
  };
protected:
  const char *bc;
};

class StoreXX : public Instruction
{
public:
  StoreXX(const char *what, uint32_t address, int opcode,
	  MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : Instruction(address, opcode, rs, rt, R_ZERO, extra)
  {
    this->bc = what;
  }

  bool pass1()
  {
    return true;
  }

  bool pass2()
  {
    if (config->traceStores)
      this->traceStore();

    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_pushregister( this->rt );
    emit->bc_invokestatic("CRunTime/memoryWrite%s(II)V", this->bc);
    return true;
  }

  int fillSources(int *p)
  {
    return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(this->rt, p) + this->addToRegisterUsage(R_MEM, p);
  };
protected:

  void traceStore()
  {
    emit->bc_pushconst( this->address );
    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_pushregister( this->rt );

    emit->bc_invokestatic("CRunTime/memoryWrite%sPc(III)V", this->bc);
  }

  const char *bc;
};

class LoadXXSigned : public LoadXX
{
public:
  LoadXXSigned(const char *what, const char *convert, uint32_t address, int opcode,
	       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX(what, address, opcode, rs, rt, extra)
  {
    this->convert = convert;
  }

  bool pass2()
  {
    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_invokestatic("CRunTime/memoryRead%s(I)I", this->bc);
    emit->bc_generic_insn( this->convert );
    emit->bc_popregister( this->rt );
    return true;
  }
private:
  const char *convert;
};

class Lw : public LoadXX
{
public:
  Lw(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX("", address, opcode, rs, rt, extra)
  {
  }

  bool pass2()
  {
    /* Skip stores to RA */
    if (this->rt == R_RA)
      return true;

    if (this->prefix)
      this->prefix->pass2();
    emit->bc_pushregister( R_MEM );
    emit->bc_pushindex( this->rs, this->extra );
    emit->bc_iaload();
    emit->bc_popregister( this->rt );
    return true;
  }

  virtual size_t bytecodeSize(void)
  {
    return 11;
  };
};

class PartialLoad : public LoadXX
{
protected:
  PartialLoad(int word_size, bool is_signed,  const char *what, uint32_t address, int opcode,
              MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX(what, address, opcode, rs, rt, extra)
  {
    this->word_size = word_size;
    this->is_signed = is_signed;

    panic_if(this->word_size != 8 && this->word_size != 16,
             "Emitting load of invalid length %d\n", this->word_size);
  }

  bool pass2()
  {
    JavaMethod *mt = controller->getMethodByAddress(this->getAddress());

    panic_if(!mt,
             "No method for instruction at 0x%x\n",
             this->getAddress());

    if ( config->optimizePartialMemoryOps ||
         !config->optimizeInlines)
      return LoadXX::pass2();
    if (mt->getBytecodeSize() > 32768)
      {
        static JavaMethod *warn_method = NULL;

        /* Bytecode size too large to allow for direct inlining,
         * reverting to normal */
        if (warn_method != mt)
          emit->warning("Bytecode size for %s (%d) too large for inlining of lb/lh\n",
                        mt->getName(), mt->getBytecodeSize());
        warn_method = mt;
        return LoadXX::pass2();
      }

    int b_v = 3; /* Assume lb(u) */
    unsigned int mask_val = 0xff;

    if (this->word_size == 16)
      {
        b_v = 2;
        mask_val = 0xffff;
      }
    /* Maybe skip ra */
    if (this->rt == R_RA)
      return true;
    if (this->prefix)
      this->prefix->pass2();

    emit->bc_pushregister(R_MEM);
    emit->bc_pushindex(this->rs, this->extra);
    emit->bc_iaload();

    /* b = 3 - (address & 3) */
    emit->bc_pushconst(b_v);
    emit->bc_pushregister(this->rs);
    if (this->extra != 0)
      {
        emit->bc_pushconst(extra);
        emit->bc_iadd();
      }
    emit->bc_pushconst(b_v);
    emit->bc_iand();
    emit->bc_isub();

    /* b = b * 8 */
    emit->bc_pushconst(3);
    emit->bc_ishl();

    /* out = (val >>> b) & 0xff */
    emit->bc_iushr();
    if (this->word_size == 8 && this->is_signed) /* lb */
      emit->bc_i2b();
    else if (this->word_size == 16 && !this->is_signed) /* lhu */
      emit->bc_i2c();
    else if (this->word_size == 16 && this->is_signed) /* lh */
      emit->bc_i2s();
    else /* lbu */
      {
        emit->bc_pushconst(mask_val);
        emit->bc_iand();
      }
    emit->bc_popregister( this->rt );

    return true;
  }

  virtual size_t bytecodeSize(void)
  {
    return 24;
  };
protected:
  int word_size;
  bool is_signed;
};

class PartialStore : public StoreXX
{
protected:
  PartialStore(int word_size,  const char *what, uint32_t address, int opcode,
               MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX(what, address, opcode, rs, rt, extra)
  {
    this->word_size = word_size;

    panic_if(this->word_size != 8 && this->word_size != 16,
             "Emitting store of invalid length %d\n", this->word_size);
  }

  bool pass2()
  {
    JavaMethod *mt = controller->getMethodByAddress(this->getAddress());

    panic_if(!mt,
             "No method for instruction at 0x%x\n",
             this->getAddress());

    if ( config->optimizePartialMemoryOps ||
         !config->optimizeInlines)
      return StoreXX::pass2();
    if (mt->getBytecodeSize() > 32768)
      {
        static JavaMethod *warn_method = NULL;

        /* Bytecode size too large to allow for direct inlining,
         * reverting to normal */
        if (warn_method != mt)
          emit->warning("Bytecode size for %s (%d) too large for inlining of sb/sh\n",
                        mt->getName(), mt->getBytecodeSize());
        warn_method = mt;
        return StoreXX::pass2();
      }

    int b_v = 3; /* Assume lb(u) */
    unsigned int mask_val = 0xff;

    if (this->word_size == 16)
      {
        b_v = 2;
        mask_val = 0xffff;
      }
    /* Maybe skip ra */
    if (this->rt == R_RA)
      return true;
    if (this->prefix)
      this->prefix->pass2();

    emit->bc_pushregister(R_MEM);
    emit->bc_pushindex(this->rs, this->extra);
    emit->bc_dup2();
    emit->bc_iaload();

    emit->bc_pushconst(mask_val);

    /* b = 3 - (address & 3) */
    emit->bc_pushconst(b_v);
    emit->bc_pushregister(this->rs);
    if (this->extra != 0)
      {
        emit->bc_pushconst(extra);
        emit->bc_iadd();
      }
    emit->bc_pushconst(b_v);
    emit->bc_iand();
    emit->bc_isub();

    /* b = b * 8 */
    emit->bc_pushconst(3);
    emit->bc_ishl();
    emit->bc_dup_x2(); /* Insert beneath the top of the stack */

    /* ~(0xff << b) */
    emit->bc_ishl();
    emit->bc_pushconst(-1);
    emit->bc_ixor();

    /* cur &= ~(0xff << b) */
    emit->bc_iand();

    /* cur |= ((rt & 0xff) << b) */
    emit->bc_swap();
    emit->bc_pushregister( this->rt );
    emit->bc_pushconst(mask_val);
    emit->bc_iand();
    emit->bc_swap();
    emit->bc_ishl();
    emit->bc_ior();

    /* Store back, index and CRunTime.memory is on the stack (dup2) */
    emit->bc_iastore();

    return true;
  }

  virtual size_t bytecodeSize(void)
  {
    return 32;
  };
protected:
  int word_size;
  bool is_signed;
};

class Lbu : public PartialLoad
{
public:
  Lbu(uint32_t address, int opcode,
      MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(8, false, "ByteUnsigned", address, opcode, rs, rt, extra)
  {
  }
};

class Lb : public PartialLoad
{
public:
  Lb(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(8, true, "Byte", address, opcode, rs, rt, extra)
  {
  }
};

class Lhu : public PartialLoad
{
public:
  Lhu(uint32_t address, int opcode,
      MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(16, false, "ShortUnsigned", address, opcode, rs, rt, extra)
  {
  }
};

class Lh : public PartialLoad
{
public:
  Lh(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(16, true, "Short", address, opcode, rs, rt, extra)
  {
  }
};

class Sb : public PartialStore
{
public:
  Sb(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialStore(8, "Byte", address, opcode, rs, rt, extra)
  {
  }
};

class Sh : public PartialStore
{
public:
  Sh(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialStore(16, "Short", address, opcode, rs, rt, extra)
  {
  }
};

class Sw : public StoreXX
{
public:
  Sw(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX("Word", address, opcode, rs, rt, extra)
  {
  }

  bool pass2()
  {
    /* Skip stores to RA */
    if (this->rt == R_RA)
      return true;

    if (config->traceStores)
      this->traceStore();

    if (this->prefix)
      this->prefix->pass2();
    emit->bc_pushregister( R_MEM );
    emit->bc_pushindex( this->rs, this->extra );
    emit->bc_pushregister( this->rt );
    emit->bc_iastore();
    return true;
  }

  virtual size_t bytecodeSize(void)
  {
    return 11;
  };
};

class LWc1 : public LoadXX
{
public:
  LWc1(uint32_t address, int opcode,
       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX("", address, opcode, rs, rt, extra)
  {
    panic_if(rt < R_F0 || rt > R_F31,
             "LWc1 at 0x%x called with non-float %d as argument\n", this->address, rt);
  }

  bool pass2()
  {
    emit->warning("Instruction LWc1 not yet implemented\n");
    return true;
  }
};

class SWc1 : public StoreXX
{
public:
  SWc1(uint32_t address, int opcode,
       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX("", address, opcode, rs, rt, extra)
  {
    panic_if(rt < R_F0 || rt > R_F31,
             "SWc1 at 0x%x called with non-float %d as argument\n", this->address, rt);
  }

  bool pass2()
  {
    emit->warning("Instruction SWc1 not yet implemented\n");
    return true;
  }
};
<commit_msg>Fixed function name (the bytecode size was completely wrong here...)<commit_after>/*********************************************************************
 *
 * Copyright (C) 2008,  Simon Kagstrom
 *
 * Filename:      memory.cc
 * Author:        Simon Kagstrom <simon.kagstrom@gmail.com>
 * Description:   Memory insns
 *
 * $Id:$
 *
 ********************************************************************/

class LoadXX : public Instruction
{
public:
  LoadXX(const char *what, uint32_t address, int opcode,
	 MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : Instruction(address, opcode, rs, rt, R_ZERO, extra)
  {
    this->bc = what;
  }

  bool pass1()
  {
    return true;
  }

  bool pass2()
  {
    emit->bc_pushaddress( this->rs, this->extra );
    /* Either a call to a subroutine or a regular function call */
    if ( config->optimizePartialMemoryOps &&
         this->opcode != OP_LWL && this->opcode != OP_LWR)
      emit->bc_jsr("__CIBYL_memoryRead%s", this->bc);
    else
      emit->bc_invokestatic("CRunTime/memoryRead%s(I)I", this->bc);
    emit->bc_popregister( this->rt );
    return true;
  }

  int fillDestinations(int *p)
  {
    if ( config->optimizePartialMemoryOps )
      return this->addToRegisterUsage(this->rt, p) + this->addToRegisterUsage(R_MADR, p);

    return this->addToRegisterUsage(this->rt, p);
  }

  int fillSources(int *p)
  {
    return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_MEM, p);
  };

  virtual size_t getBytecodeSize(void)
  {
    return 13;
  };
protected:
  const char *bc;
};

class StoreXX : public Instruction
{
public:
  StoreXX(const char *what, uint32_t address, int opcode,
	  MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : Instruction(address, opcode, rs, rt, R_ZERO, extra)
  {
    this->bc = what;
  }

  bool pass1()
  {
    return true;
  }

  bool pass2()
  {
    if (config->traceStores)
      this->traceStore();

    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_pushregister( this->rt );
    emit->bc_invokestatic("CRunTime/memoryWrite%s(II)V", this->bc);
    return true;
  }

  int fillSources(int *p)
  {
    return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(this->rt, p) + this->addToRegisterUsage(R_MEM, p);
  };
protected:

  void traceStore()
  {
    emit->bc_pushconst( this->address );
    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_pushregister( this->rt );

    emit->bc_invokestatic("CRunTime/memoryWrite%sPc(III)V", this->bc);
  }

  const char *bc;
};

class LoadXXSigned : public LoadXX
{
public:
  LoadXXSigned(const char *what, const char *convert, uint32_t address, int opcode,
	       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX(what, address, opcode, rs, rt, extra)
  {
    this->convert = convert;
  }

  bool pass2()
  {
    emit->bc_pushaddress( this->rs, this->extra );
    emit->bc_invokestatic("CRunTime/memoryRead%s(I)I", this->bc);
    emit->bc_generic_insn( this->convert );
    emit->bc_popregister( this->rt );
    return true;
  }
private:
  const char *convert;
};

class Lw : public LoadXX
{
public:
  Lw(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX("", address, opcode, rs, rt, extra)
  {
  }

  bool pass2()
  {
    /* Skip stores to RA */
    if (this->rt == R_RA)
      return true;

    if (this->prefix)
      this->prefix->pass2();
    emit->bc_pushregister( R_MEM );
    emit->bc_pushindex( this->rs, this->extra );
    emit->bc_iaload();
    emit->bc_popregister( this->rt );
    return true;
  }

  virtual size_t getBytecodeSize(void)
  {
    return 11;
  };
};

class PartialLoad : public LoadXX
{
protected:
  PartialLoad(int word_size, bool is_signed,  const char *what, uint32_t address, int opcode,
              MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX(what, address, opcode, rs, rt, extra)
  {
    this->word_size = word_size;
    this->is_signed = is_signed;

    panic_if(this->word_size != 8 && this->word_size != 16,
             "Emitting load of invalid length %d\n", this->word_size);
  }

  bool pass2()
  {
    JavaMethod *mt = controller->getMethodByAddress(this->getAddress());

    panic_if(!mt,
             "No method for instruction at 0x%x\n",
             this->getAddress());

    if ( config->optimizePartialMemoryOps ||
         !config->optimizeInlines)
      return LoadXX::pass2();
    if (mt->getBytecodeSize() > 32768)
      {
        static JavaMethod *warn_method = NULL;

        /* Bytecode size too large to allow for direct inlining,
         * reverting to normal */
        if (warn_method != mt)
          emit->warning("Bytecode size for %s (%d) too large for inlining of lb/lh\n",
                        mt->getName(), mt->getBytecodeSize());
        warn_method = mt;
        return LoadXX::pass2();
      }

    int b_v = 3; /* Assume lb(u) */
    unsigned int mask_val = 0xff;

    if (this->word_size == 16)
      {
        b_v = 2;
        mask_val = 0xffff;
      }
    /* Maybe skip ra */
    if (this->rt == R_RA)
      return true;
    if (this->prefix)
      this->prefix->pass2();

    emit->bc_pushregister(R_MEM);
    emit->bc_pushindex(this->rs, this->extra);
    emit->bc_iaload();

    /* b = 3 - (address & 3) */
    emit->bc_pushconst(b_v);
    emit->bc_pushregister(this->rs);
    if (this->extra != 0)
      {
        emit->bc_pushconst(extra);
        emit->bc_iadd();
      }
    emit->bc_pushconst(b_v);
    emit->bc_iand();
    emit->bc_isub();

    /* b = b * 8 */
    emit->bc_pushconst(3);
    emit->bc_ishl();

    /* out = (val >>> b) & 0xff */
    emit->bc_iushr();
    if (this->word_size == 8 && this->is_signed) /* lb */
      emit->bc_i2b();
    else if (this->word_size == 16 && !this->is_signed) /* lhu */
      emit->bc_i2c();
    else if (this->word_size == 16 && this->is_signed) /* lh */
      emit->bc_i2s();
    else /* lbu */
      {
        emit->bc_pushconst(mask_val);
        emit->bc_iand();
      }
    emit->bc_popregister( this->rt );

    return true;
  }

  virtual size_t getBytecodeSize(void)
  {
    return 24;
  };
protected:
  int word_size;
  bool is_signed;
};

class PartialStore : public StoreXX
{
protected:
  PartialStore(int word_size,  const char *what, uint32_t address, int opcode,
               MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX(what, address, opcode, rs, rt, extra)
  {
    this->word_size = word_size;

    panic_if(this->word_size != 8 && this->word_size != 16,
             "Emitting store of invalid length %d\n", this->word_size);
  }

  bool pass2()
  {
    JavaMethod *mt = controller->getMethodByAddress(this->getAddress());

    panic_if(!mt,
             "No method for instruction at 0x%x\n",
             this->getAddress());

    if ( config->optimizePartialMemoryOps ||
         !config->optimizeInlines)
      return StoreXX::pass2();
    if (mt->getBytecodeSize() > 32768)
      {
        static JavaMethod *warn_method = NULL;

        /* Bytecode size too large to allow for direct inlining,
         * reverting to normal */
        if (warn_method != mt)
          emit->warning("Bytecode size for %s (%d) too large for inlining of sb/sh\n",
                        mt->getName(), mt->getBytecodeSize());
        warn_method = mt;
        return StoreXX::pass2();
      }

    int b_v = 3; /* Assume lb(u) */
    unsigned int mask_val = 0xff;

    if (this->word_size == 16)
      {
        b_v = 2;
        mask_val = 0xffff;
      }
    /* Maybe skip ra */
    if (this->rt == R_RA)
      return true;
    if (this->prefix)
      this->prefix->pass2();

    emit->bc_pushregister(R_MEM);
    emit->bc_pushindex(this->rs, this->extra);
    emit->bc_dup2();
    emit->bc_iaload();

    emit->bc_pushconst(mask_val);

    /* b = 3 - (address & 3) */
    emit->bc_pushconst(b_v);
    emit->bc_pushregister(this->rs);
    if (this->extra != 0)
      {
        emit->bc_pushconst(extra);
        emit->bc_iadd();
      }
    emit->bc_pushconst(b_v);
    emit->bc_iand();
    emit->bc_isub();

    /* b = b * 8 */
    emit->bc_pushconst(3);
    emit->bc_ishl();
    emit->bc_dup_x2(); /* Insert beneath the top of the stack */

    /* ~(0xff << b) */
    emit->bc_ishl();
    emit->bc_pushconst(-1);
    emit->bc_ixor();

    /* cur &= ~(0xff << b) */
    emit->bc_iand();

    /* cur |= ((rt & 0xff) << b) */
    emit->bc_swap();
    emit->bc_pushregister( this->rt );
    emit->bc_pushconst(mask_val);
    emit->bc_iand();
    emit->bc_swap();
    emit->bc_ishl();
    emit->bc_ior();

    /* Store back, index and CRunTime.memory is on the stack (dup2) */
    emit->bc_iastore();

    return true;
  }

  virtual size_t getBytecodeSize(void)
  {
    return 32;
  };
protected:
  int word_size;
  bool is_signed;
};

class Lbu : public PartialLoad
{
public:
  Lbu(uint32_t address, int opcode,
      MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(8, false, "ByteUnsigned", address, opcode, rs, rt, extra)
  {
  }
};

class Lb : public PartialLoad
{
public:
  Lb(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(8, true, "Byte", address, opcode, rs, rt, extra)
  {
  }
};

class Lhu : public PartialLoad
{
public:
  Lhu(uint32_t address, int opcode,
      MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(16, false, "ShortUnsigned", address, opcode, rs, rt, extra)
  {
  }
};

class Lh : public PartialLoad
{
public:
  Lh(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialLoad(16, true, "Short", address, opcode, rs, rt, extra)
  {
  }
};

class Sb : public PartialStore
{
public:
  Sb(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialStore(8, "Byte", address, opcode, rs, rt, extra)
  {
  }
};

class Sh : public PartialStore
{
public:
  Sh(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : PartialStore(16, "Short", address, opcode, rs, rt, extra)
  {
  }
};

class Sw : public StoreXX
{
public:
  Sw(uint32_t address, int opcode,
     MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX("Word", address, opcode, rs, rt, extra)
  {
  }

  bool pass2()
  {
    /* Skip stores to RA */
    if (this->rt == R_RA)
      return true;

    if (config->traceStores)
      this->traceStore();

    if (this->prefix)
      this->prefix->pass2();
    emit->bc_pushregister( R_MEM );
    emit->bc_pushindex( this->rs, this->extra );
    emit->bc_pushregister( this->rt );
    emit->bc_iastore();
    return true;
  }

  virtual size_t getBytecodeSize(void)
  {
    return 11;
  };
};

class LWc1 : public LoadXX
{
public:
  LWc1(uint32_t address, int opcode,
       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : LoadXX("", address, opcode, rs, rt, extra)
  {
    panic_if(rt < R_F0 || rt > R_F31,
             "LWc1 at 0x%x called with non-float %d as argument\n", this->address, rt);
  }

  bool pass2()
  {
    emit->warning("Instruction LWc1 not yet implemented\n");
    return true;
  }
};

class SWc1 : public StoreXX
{
public:
  SWc1(uint32_t address, int opcode,
       MIPS_register_t rs, MIPS_register_t rt, int32_t extra) : StoreXX("", address, opcode, rs, rt, extra)
  {
    panic_if(rt < R_F0 || rt > R_F31,
             "SWc1 at 0x%x called with non-float %d as argument\n", this->address, rt);
  }

  bool pass2()
  {
    emit->warning("Instruction SWc1 not yet implemented\n");
    return true;
  }
};
<|endoftext|>


<commit_before>#include "consolidator.h"

#include "options.h"

#include "taco/text-formats/constraint_set_seq_parser.h"
#include "taco/text-formats/feature_structure_seq_parser.h"

#include <boost/lexical_cast.hpp>

#include <algorithm>

namespace taco {
namespace tool {
namespace m1 {

Consolidator::Consolidator(
    const Options &options,
    Vocabulary &symbol_set,
    Vocabulary &feature_set,
    Vocabulary &value_set,
    ConstraintTableWriter &table_writer,
    ConstraintMapWriter &map_writer)
    : options_(options)
    , next_id_(1)
    , batch_(feature_set)
    , symbol_set_(symbol_set)
    , feature_set_(feature_set)
    , value_set_(value_set)
    , table_writer_(table_writer)
    , map_writer_(map_writer)
    , batch_start_(-1)
    , batch_end_(-1)
    , num_conflict_reports_(0) {
}

void Consolidator::ProcessEntry(const ConstraintExtractParser::Entry &entry,
                                int line_num) {
  // Determine if this entry begins a new batch.
  if (batch_.IsEmpty()) {
    batch_.set_lhs(entry.lhs);
    batch_.set_rhs(entry.rhs);
    batch_start_ = line_num;
  } else if (entry.lhs != batch_.lhs() ||
             entry.rhs.size() != batch_.rhs().size() ||
             !std::equal(entry.rhs.begin(), entry.rhs.end(),
                         batch_.rhs().begin())) {
    batch_end_ = line_num - 1;
    ProcessBatch();
    batch_.Clear();
    batch_.set_lhs(entry.lhs);
    batch_.set_rhs(entry.rhs);
    batch_start_ = line_num;
    batch_end_ = -1;
  }

  // Parse the sequence of constraint sets.
  cs_seq_.clear();
  {
    ConstraintSetSeqParser end;
    ConstraintSetSeqParser p(entry.constraint_sets, feature_set_, value_set_);
    while (p != end) {
      cs_seq_.push_back(*p++);
    }
  }

  // Add the sequence pair to the batch.
  batch_.Add(cs_seq_);
}

void Consolidator::RepeatPrevious() {
  batch_.RepeatPrevious();
}

void Consolidator::Finish(int line_num) {
  batch_end_ = line_num;
  ProcessBatch();
  batch_.Clear();
  batch_start_ = -1;
  batch_end_ = -1;
}

void Consolidator::ReportConflict() {
  // FIXME Use tool's Warn()
  std::cerr << "Conflict: start = " << batch_start_
            << ", end = " << batch_end_ << std::endl;
  ++num_conflict_reports_;
}

void Consolidator::ProcessBatch() {
  ++stats_.num_target_sides;
  ++stats_.target_side_counts[batch_.Size()];
  if (!batch_.HasCandidates()) {
    return;
  }
  stats_.num_pre_merge_winners += batch_.CountWinners(options_.majority);
  stats_.weighted_pre_merge_winners += (batch_.CountWinners(options_.majority) * batch_.Size());
  batch_.Consolidate(cs_seq_, options_.majority, options_.minority);
  stats_.num_post_merge_winners += cs_seq_.size();
  stats_.weighted_post_merge_winners += (cs_seq_.size() * batch_.Size());
  if (cs_seq_.empty()) {
    if (options_.max_conflict_reports == -1 ||
        num_conflict_reports_ < options_.max_conflict_reports) {
      ReportConflict();
    }
    return;
  }
  std::vector<unsigned int> ids;
  CSVec::const_iterator p = cs_seq_.begin();
  CSVec::const_iterator p_end = cs_seq_.end();
  while (p != p_end) {
    unsigned int &id = id_map_[*p];
    if (!id) {
      id = next_id_++;
      table_writer_.Write(id, **p);
    }
    ids.push_back(id);
    ++p;
  }
  CreateKey(batch_.lhs(), batch_.rhs(), symbol_set_, tmp_key_);
  map_writer_.Write(tmp_key_, ids);
}

void Consolidator::CreateKey(const std::string &lhs,
                             const std::vector<std::string> &rhs,
                             const Vocabulary &symbol_set,
                             std::string &key) {
  key = boost::lexical_cast<std::string>(symbol_set.Lookup(lhs));
  for (std::vector<std::string>::const_iterator p = rhs.begin();
       p != rhs.end(); ++p) {
    key += "-";
    key += boost::lexical_cast<std::string>(symbol_set.Lookup(*p));
  }
}

}  // namespace m1
}  // namespace tool
}  // namespace taco
<commit_msg>Add missing #include<commit_after>#include "consolidator.h"

#include "options.h"

#include "taco/text-formats/constraint_set_seq_parser.h"
#include "taco/text-formats/feature_structure_seq_parser.h"

#include <boost/lexical_cast.hpp>

#include <algorithm>
#include <iostream>

namespace taco {
namespace tool {
namespace m1 {

Consolidator::Consolidator(
    const Options &options,
    Vocabulary &symbol_set,
    Vocabulary &feature_set,
    Vocabulary &value_set,
    ConstraintTableWriter &table_writer,
    ConstraintMapWriter &map_writer)
    : options_(options)
    , next_id_(1)
    , batch_(feature_set)
    , symbol_set_(symbol_set)
    , feature_set_(feature_set)
    , value_set_(value_set)
    , table_writer_(table_writer)
    , map_writer_(map_writer)
    , batch_start_(-1)
    , batch_end_(-1)
    , num_conflict_reports_(0) {
}

void Consolidator::ProcessEntry(const ConstraintExtractParser::Entry &entry,
                                int line_num) {
  // Determine if this entry begins a new batch.
  if (batch_.IsEmpty()) {
    batch_.set_lhs(entry.lhs);
    batch_.set_rhs(entry.rhs);
    batch_start_ = line_num;
  } else if (entry.lhs != batch_.lhs() ||
             entry.rhs.size() != batch_.rhs().size() ||
             !std::equal(entry.rhs.begin(), entry.rhs.end(),
                         batch_.rhs().begin())) {
    batch_end_ = line_num - 1;
    ProcessBatch();
    batch_.Clear();
    batch_.set_lhs(entry.lhs);
    batch_.set_rhs(entry.rhs);
    batch_start_ = line_num;
    batch_end_ = -1;
  }

  // Parse the sequence of constraint sets.
  cs_seq_.clear();
  {
    ConstraintSetSeqParser end;
    ConstraintSetSeqParser p(entry.constraint_sets, feature_set_, value_set_);
    while (p != end) {
      cs_seq_.push_back(*p++);
    }
  }

  // Add the sequence pair to the batch.
  batch_.Add(cs_seq_);
}

void Consolidator::RepeatPrevious() {
  batch_.RepeatPrevious();
}

void Consolidator::Finish(int line_num) {
  batch_end_ = line_num;
  ProcessBatch();
  batch_.Clear();
  batch_start_ = -1;
  batch_end_ = -1;
}

void Consolidator::ReportConflict() {
  // FIXME Use tool's Warn()
  std::cerr << "Conflict: start = " << batch_start_
            << ", end = " << batch_end_ << std::endl;
  ++num_conflict_reports_;
}

void Consolidator::ProcessBatch() {
  ++stats_.num_target_sides;
  ++stats_.target_side_counts[batch_.Size()];
  if (!batch_.HasCandidates()) {
    return;
  }
  stats_.num_pre_merge_winners += batch_.CountWinners(options_.majority);
  stats_.weighted_pre_merge_winners += (batch_.CountWinners(options_.majority) * batch_.Size());
  batch_.Consolidate(cs_seq_, options_.majority, options_.minority);
  stats_.num_post_merge_winners += cs_seq_.size();
  stats_.weighted_post_merge_winners += (cs_seq_.size() * batch_.Size());
  if (cs_seq_.empty()) {
    if (options_.max_conflict_reports == -1 ||
        num_conflict_reports_ < options_.max_conflict_reports) {
      ReportConflict();
    }
    return;
  }
  std::vector<unsigned int> ids;
  CSVec::const_iterator p = cs_seq_.begin();
  CSVec::const_iterator p_end = cs_seq_.end();
  while (p != p_end) {
    unsigned int &id = id_map_[*p];
    if (!id) {
      id = next_id_++;
      table_writer_.Write(id, **p);
    }
    ids.push_back(id);
    ++p;
  }
  CreateKey(batch_.lhs(), batch_.rhs(), symbol_set_, tmp_key_);
  map_writer_.Write(tmp_key_, ids);
}

void Consolidator::CreateKey(const std::string &lhs,
                             const std::vector<std::string> &rhs,
                             const Vocabulary &symbol_set,
                             std::string &key) {
  key = boost::lexical_cast<std::string>(symbol_set.Lookup(lhs));
  for (std::vector<std::string>::const_iterator p = rhs.begin();
       p != rhs.end(); ++p) {
    key += "-";
    key += boost::lexical_cast<std::string>(symbol_set.Lookup(*p));
  }
}

}  // namespace m1
}  // namespace tool
}  // namespace taco
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "AnnPhysicsEngine.hpp"
#include "AnnLogger.hpp"

using namespace Annwvyn;

AnnPhysicsEngine::AnnPhysicsEngine(Ogre::SceneNode * rootNode,
								   std::shared_ptr<AnnPlayer> player,
								   AnnGameObjectList & objects,
								   AnnTriggerObjectList & triggers) : AnnSubSystem("PhysicsEngie"),
	Broadphase(nullptr),
	CollisionConfiguration(nullptr),
	Solver(nullptr),
	DynamicsWorld(nullptr),
	debugDrawer(nullptr),
	playerRigidBodyState(nullptr),
	gameObjects(objects),
	triggerObjects(triggers),
	playerObject(player),
	defaultGravity(0, -9.81f, 0)
{
	//Initialize the Bullet world
	Broadphase = std::make_unique<btDbvtBroadphase>();
	CollisionConfiguration = std::make_unique<btDefaultCollisionConfiguration>();
	Dispatcher = std::make_unique<btCollisionDispatcher>(CollisionConfiguration.get());
	Solver = std::make_unique<btSequentialImpulseConstraintSolver>();
	DynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>(Dispatcher.get(), Broadphase.get(), Solver.get(), CollisionConfiguration.get());
	AnnDebug() << "btDiscreteDynamicsWorld instantiated";

	//Set gravity vector
	DynamicsWorld->setGravity(defaultGravity.getBtVector());
	AnnDebug() << "Gravity vector " << defaultGravity;

	debugPhysics = false;//by default
	debugDrawer = new BtOgre::DebugDrawer(rootNode, DynamicsWorld.get());
	DynamicsWorld->setDebugDrawer(debugDrawer);
}

AnnPhysicsEngine::~AnnPhysicsEngine()
{
}

void AnnPhysicsEngine::addPlayerPhysicalBodyToDynamicsWorld()
{
	// TODO define name for the bullet's collision masks
	DynamicsWorld->addRigidBody(playerObject->getBody(), MASK(0), MASK(1));
}

void AnnPhysicsEngine::createPlayerPhysicalVirtualBody(Ogre::SceneNode* node)
{
	AnnDebug() << "createPlayerPhysicalVirtualBody";

	//Create (new) a rigid body state through BtOgre
	if (playerRigidBodyState) delete playerRigidBodyState;
	playerRigidBodyState = new BtOgre::RigidBodyState(node);

	//Get inertia vector
	btVector3 inertia;
	playerObject->getShape()->calculateLocalInertia(playerObject->getMass(), inertia);

	//Set the body to the player
	auto body = new btRigidBody(
		playerObject->getMass(),
		playerRigidBodyState,
		playerObject->getShape(),
		inertia);
	playerObject->setBody(body);
}

void AnnPhysicsEngine::createVirtualBodyShape(float radius)
{
	//remove the diameter of the two half sphere on top and bottom of the capsule
	playerObject->setShape(new btCapsuleShape(radius, playerObject->getEyesHeight() - 2 * radius));
}

btDiscreteDynamicsWorld* AnnPhysicsEngine::getWorld()
{
	return DynamicsWorld.get();
}

void AnnPhysicsEngine::step(float delta)
{
	//AnnDebug() << "sepSimulation with delta = " << delta;
	DynamicsWorld->stepSimulation(delta, 10, 1.0f / 240.0f);
}

void AnnPhysicsEngine::stepDebugDrawer()
{
	if (debugPhysics)
		debugDrawer->step();
}

void AnnPhysicsEngine::processCollisionTesting()
{
	auto nbManifold = DynamicsWorld->getDispatcher()->getNumManifolds();
	for (auto i{ 0 }; i < nbManifold; ++i)
	{
		auto contactManifold = DynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
		if (contactManifold->getNumContacts() > 0)
			AnnGetEventManager()->detectedCollision(contactManifold->getBody0()->getUserPointer(),
													contactManifold->getBody1()->getUserPointer());
	}
}

void AnnPhysicsEngine::removeRigidBody(btRigidBody* body)
{
	AnnDebug() << "Removing " << body << " Form physics simulation";
	if (body)
		DynamicsWorld->removeRigidBody(body);
}

void AnnPhysicsEngine::setDebugPhysics(bool state)
{
	debugPhysics = state;
	debugDrawer->setDebugMode(int(state));
	debugDrawer->step();
}

void AnnPhysicsEngine::processTriggersContacts()
{
	for (auto trigger : triggerObjects)
	{
		trigger->setContactInformation(trigger->computeVolumetricTest(playerObject));
		if (!trigger->lastFrameContactWithPlayer && trigger->contactWithPlayer ||
			trigger->lastFrameContactWithPlayer && !trigger->contactWithPlayer)
			AnnGetEventManager()->spatialTrigger(trigger);
	}
}

void AnnPhysicsEngine::changeGravity(AnnVect3 gravity)
{
	DynamicsWorld->setGravity(gravity.getBtVector());
}

void AnnPhysicsEngine::resetGravity()
{
	changeGravity(defaultGravity);
}

void AnnPhysicsEngine::update()
{
	processTriggersContacts();
	stepDebugDrawer();
	step(AnnGetEngine()->getFrameTime());
	processCollisionTesting();
}

void AnnPhysicsEngine::toggleDebugPhysics()
{
	setDebugPhysics(!debugPhysics);
}

void AnnPhysicsEngine::initPlayerRoomscalePhysics(Ogre::SceneNode* playerAnchorNode)
{
	playerObject->setMode(ROOMSCALE);
	AnnDebug() << "Initializing player's physics in roomscale mode";
	AnnDebug() << "Player can walk around";
	playerObject->setRoomRefNode(playerAnchorNode);
}

void AnnPhysicsEngine::initPlayerStandingPhysics(Ogre::SceneNode* node)
{
	playerObject->setMode(STANDING);
	AnnDebug() << "Initializing player's physics  in standing mode";
	AnnDebug() << "Capsule rigidbody : " << playerObject->getMass() << "Kg" << playerObject->getEyesHeight();
	createVirtualBodyShape();
	createPlayerPhysicalVirtualBody(node);
	addPlayerPhysicalBodyToDynamicsWorld();
}<commit_msg>remove useless comment<commit_after>#include "stdafx.h"
#include "AnnPhysicsEngine.hpp"
#include "AnnLogger.hpp"

using namespace Annwvyn;

AnnPhysicsEngine::AnnPhysicsEngine(Ogre::SceneNode * rootNode,
								   std::shared_ptr<AnnPlayer> player,
								   AnnGameObjectList & objects,
								   AnnTriggerObjectList & triggers) : AnnSubSystem("PhysicsEngie"),
	Broadphase(nullptr),
	CollisionConfiguration(nullptr),
	Solver(nullptr),
	DynamicsWorld(nullptr),
	debugDrawer(nullptr),
	playerRigidBodyState(nullptr),
	gameObjects(objects),
	triggerObjects(triggers),
	playerObject(player),
	defaultGravity(0, -9.81f, 0)
{
	//Initialize the Bullet world
	Broadphase = std::make_unique<btDbvtBroadphase>();
	CollisionConfiguration = std::make_unique<btDefaultCollisionConfiguration>();
	Dispatcher = std::make_unique<btCollisionDispatcher>(CollisionConfiguration.get());
	Solver = std::make_unique<btSequentialImpulseConstraintSolver>();
	DynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>(Dispatcher.get(), Broadphase.get(), Solver.get(), CollisionConfiguration.get());
	AnnDebug() << "btDiscreteDynamicsWorld instantiated";

	//Set gravity vector
	DynamicsWorld->setGravity(defaultGravity.getBtVector());
	AnnDebug() << "Gravity vector " << defaultGravity;

	debugPhysics = false;//by default
	debugDrawer = new BtOgre::DebugDrawer(rootNode, DynamicsWorld.get());
	DynamicsWorld->setDebugDrawer(debugDrawer);
}

AnnPhysicsEngine::~AnnPhysicsEngine()
{
}

void AnnPhysicsEngine::addPlayerPhysicalBodyToDynamicsWorld()
{
	// TODO define name for the bullet's collision masks
	DynamicsWorld->addRigidBody(playerObject->getBody(), MASK(0), MASK(1));
}

void AnnPhysicsEngine::createPlayerPhysicalVirtualBody(Ogre::SceneNode* node)
{
	AnnDebug() << "createPlayerPhysicalVirtualBody";

	//Create (new) a rigid body state through BtOgre
	if (playerRigidBodyState) delete playerRigidBodyState;
	playerRigidBodyState = new BtOgre::RigidBodyState(node);

	//Get inertia vector
	btVector3 inertia;
	playerObject->getShape()->calculateLocalInertia(playerObject->getMass(), inertia);

	//Set the body to the player
	auto body = new btRigidBody(
		playerObject->getMass(),
		playerRigidBodyState,
		playerObject->getShape(),
		inertia);
	playerObject->setBody(body);
}

void AnnPhysicsEngine::createVirtualBodyShape(float radius)
{
	//remove the diameter of the two half sphere on top and bottom of the capsule
	playerObject->setShape(new btCapsuleShape(radius, playerObject->getEyesHeight() - 2 * radius));
}

btDiscreteDynamicsWorld* AnnPhysicsEngine::getWorld()
{
	return DynamicsWorld.get();
}

void AnnPhysicsEngine::step(float delta)
{
	DynamicsWorld->stepSimulation(delta, 10, 1.0f / 240.0f);
}

void AnnPhysicsEngine::stepDebugDrawer()
{
	if (debugPhysics)
		debugDrawer->step();
}

void AnnPhysicsEngine::processCollisionTesting()
{
	auto nbManifold = DynamicsWorld->getDispatcher()->getNumManifolds();
	for (auto i{ 0 }; i < nbManifold; ++i)
	{
		auto contactManifold = DynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
		if (contactManifold->getNumContacts() > 0)
			AnnGetEventManager()->detectedCollision(contactManifold->getBody0()->getUserPointer(),
													contactManifold->getBody1()->getUserPointer());
	}
}

void AnnPhysicsEngine::removeRigidBody(btRigidBody* body)
{
	AnnDebug() << "Removing " << body << " Form physics simulation";
	if (body)
		DynamicsWorld->removeRigidBody(body);
}

void AnnPhysicsEngine::setDebugPhysics(bool state)
{
	debugPhysics = state;
	debugDrawer->setDebugMode(int(state));
	debugDrawer->step();
}

void AnnPhysicsEngine::processTriggersContacts()
{
	for (auto trigger : triggerObjects)
	{
		trigger->setContactInformation(trigger->computeVolumetricTest(playerObject));
		if (!trigger->lastFrameContactWithPlayer && trigger->contactWithPlayer ||
			trigger->lastFrameContactWithPlayer && !trigger->contactWithPlayer)
			AnnGetEventManager()->spatialTrigger(trigger);
	}
}

void AnnPhysicsEngine::changeGravity(AnnVect3 gravity)
{
	DynamicsWorld->setGravity(gravity.getBtVector());
}

void AnnPhysicsEngine::resetGravity()
{
	changeGravity(defaultGravity);
}

void AnnPhysicsEngine::update()
{
	processTriggersContacts();
	stepDebugDrawer();
	step(AnnGetEngine()->getFrameTime());
	processCollisionTesting();
}

void AnnPhysicsEngine::toggleDebugPhysics()
{
	setDebugPhysics(!debugPhysics);
}

void AnnPhysicsEngine::initPlayerRoomscalePhysics(Ogre::SceneNode* playerAnchorNode)
{
	playerObject->setMode(ROOMSCALE);
	AnnDebug() << "Initializing player's physics in roomscale mode";
	AnnDebug() << "Player can walk around";
	playerObject->setRoomRefNode(playerAnchorNode);
}

void AnnPhysicsEngine::initPlayerStandingPhysics(Ogre::SceneNode* node)
{
	playerObject->setMode(STANDING);
	AnnDebug() << "Initializing player's physics  in standing mode";
	AnnDebug() << "Capsule rigidbody : " << playerObject->getMass() << "Kg" << playerObject->getEyesHeight();
	createVirtualBodyShape();
	createPlayerPhysicalVirtualBody(node);
	addPlayerPhysicalBodyToDynamicsWorld();
}<|endoftext|>


<commit_before>
#include "includes.h"

void test_pad2(int n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad2(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad3(int n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad3(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad6(std::size_t n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad6(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad9(std::size_t n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad9(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

TEST_CASE("pad2", "[fmt_helper]")
{
    test_pad2(0, "00");
    test_pad2(3, "03");
    test_pad2(23, "23");
    test_pad2(123, "123");
    test_pad2(1234, "1234");
    test_pad2(-5, "-5");
}

TEST_CASE("pad3", "[fmt_helper]")
{
    test_pad3(0, "000");
    test_pad3(3, "003");
    test_pad3(23, "023");
    test_pad3(123, "123");
    test_pad3(1234, "1234");
    test_pad3(-5, "-05");
}

TEST_CASE("pad6", "[fmt_helper]")
{
    test_pad6(0, "000000");
    test_pad6(3, "000003");
    test_pad6(23, "000023");
    test_pad6(123, "000123");
    test_pad6(1234, "001234");
    test_pad6(12345, "012345");
    test_pad6(123456, "123456");
}

TEST_CASE("pad9", "[fmt_helper]")
{
    test_pad9(0,"000000000");
    test_pad9(3, "000000003");
    test_pad9(23, "000000023");
    test_pad9(123, "000000123");
    test_pad9(1234, "000001234");
    test_pad9(12345, "000012345");
    test_pad9(123456, "000123456");
    test_pad9(1234567, "001234567");
    test_pad9(12345678, "012345678");
    test_pad9(123456789, "123456789");
    test_pad9(1234567891, "1234567891");
}
<commit_msg>Fixed fmt_helper tests<commit_after>
#include "includes.h"

void test_pad2(int n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad2(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad3(uint32_t n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad3(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad6(std::size_t n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad6(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

void test_pad9(std::size_t n, const char *expected)
{
    fmt::memory_buffer buf;
    spdlog::details::fmt_helper::pad9(n, buf);
    REQUIRE(fmt::to_string(buf) == expected);
}

TEST_CASE("pad2", "[fmt_helper]")
{
    test_pad2(0, "00");
    test_pad2(3, "03");
    test_pad2(23, "23");
    test_pad2(123, "123");
    test_pad2(1234, "1234");
    test_pad2(-5, "-5");
}

TEST_CASE("pad3", "[fmt_helper]")
{
    test_pad3(0, "000");
    test_pad3(3, "003");
    test_pad3(23, "023");
    test_pad3(123, "123");
    test_pad3(1234, "1234");
}

TEST_CASE("pad6", "[fmt_helper]")
{
    test_pad6(0, "000000");
    test_pad6(3, "000003");
    test_pad6(23, "000023");
    test_pad6(123, "000123");
    test_pad6(1234, "001234");
    test_pad6(12345, "012345");
    test_pad6(123456, "123456");
}

TEST_CASE("pad9", "[fmt_helper]")
{
    test_pad9(0, "000000000");
    test_pad9(3, "000000003");
    test_pad9(23, "000000023");
    test_pad9(123, "000000123");
    test_pad9(1234, "000001234");
    test_pad9(12345, "000012345");
    test_pad9(123456, "000123456");
    test_pad9(1234567, "001234567");
    test_pad9(12345678, "012345678");
    test_pad9(123456789, "123456789");
    test_pad9(1234567891, "1234567891");
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/compositor/test/test_compositor_host.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/rect.h"

namespace ui {

class TestCompositorHostOzone : public TestCompositorHost {
 public:
  TestCompositorHostOzone(const gfx::Rect& bounds);
  virtual ~TestCompositorHostOzone();

 private:
  // Overridden from TestCompositorHost:
  virtual void Show() OVERRIDE;
  virtual ui::Compositor* GetCompositor() OVERRIDE;

  void Draw();

  gfx::Rect bounds_;

  scoped_ptr<ui::Compositor> compositor_;

  DISALLOW_COPY_AND_ASSIGN(TestCompositorHostOzone);
};

TestCompositorHostOzone::TestCompositorHostOzone(const gfx::Rect& bounds)
    : bounds_(bounds) {}

TestCompositorHostOzone::~TestCompositorHostOzone() {}

void TestCompositorHostOzone::Show() {
  // Ozone should rightly have a backing native framebuffer
  // An in-memory array draw into by OSMesa is a reasonble
  // fascimile of a dumb framebuffer at present.
  // GLSurface will allocate the array so long as it is provided
  // with a non-0 widget.
  // TODO(rjkroege): Use a "real" ozone widget when it is
  // available: http://crbug.com/255128
  compositor_.reset(new ui::Compositor(1));
  compositor_->SetScaleAndSize(1.0f, bounds_.size());
}

ui::Compositor* TestCompositorHostOzone::GetCompositor() {
  return compositor_.get();
}

void TestCompositorHostOzone::Draw() {
  if (compositor_.get())
    compositor_->Draw();
}

// static
TestCompositorHost* TestCompositorHost::Create(const gfx::Rect& bounds) {
  return new TestCompositorHostOzone(bounds);
}

}  // namespace ui
<commit_msg>Fix build of TestCompositorHostOzone<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/compositor/test/test_compositor_host.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/rect.h"

namespace ui {

class TestCompositorHostOzone : public TestCompositorHost {
 public:
  TestCompositorHostOzone(const gfx::Rect& bounds);
  virtual ~TestCompositorHostOzone();

 private:
  // Overridden from TestCompositorHost:
  virtual void Show() OVERRIDE;
  virtual ui::Compositor* GetCompositor() OVERRIDE;

  void Draw();

  gfx::Rect bounds_;

  scoped_ptr<ui::Compositor> compositor_;

  DISALLOW_COPY_AND_ASSIGN(TestCompositorHostOzone);
};

TestCompositorHostOzone::TestCompositorHostOzone(const gfx::Rect& bounds)
    : bounds_(bounds) {}

TestCompositorHostOzone::~TestCompositorHostOzone() {}

void TestCompositorHostOzone::Show() {
  // Ozone should rightly have a backing native framebuffer
  // An in-memory array draw into by OSMesa is a reasonble
  // fascimile of a dumb framebuffer at present.
  // GLSurface will allocate the array so long as it is provided
  // with a non-0 widget.
  // TODO(rjkroege): Use a "real" ozone widget when it is
  // available: http://crbug.com/255128
  compositor_.reset(new ui::Compositor(false, 1));
  compositor_->SetScaleAndSize(1.0f, bounds_.size());
}

ui::Compositor* TestCompositorHostOzone::GetCompositor() {
  return compositor_.get();
}

void TestCompositorHostOzone::Draw() {
  if (compositor_.get())
    compositor_->Draw();
}

// static
TestCompositorHost* TestCompositorHost::Create(const gfx::Rect& bounds) {
  return new TestCompositorHostOzone(bounds);
}

}  // namespace ui
<|endoftext|>


<commit_before>/** \file    map_ddc_and_rvk_to_ixtheo_notations.cc
 *  \brief   Map certain DDC and RVK categories to ixTheo notations and add them to field 652a.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2015-2018, Library of the University of Tübingen

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

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

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

#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <cctype>
#include <cstdlib>
#include "MarcRecord.h"
#include "MarcReader.h"
#include "MarcWriter.h"
#include "StringUtil.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << ::progname << " [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map "
              << "rvk_to_ixtheo_notations_map\n";
    std::exit(EXIT_FAILURE);
}

/** \class IxTheoMapper
 *  \brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation.
 */
class IxTheoMapper {
    std::string from_hierarchy_;
    std::string to_ix_theo_notation_;
    std::vector<std::string> exclusions_;
public:
    explicit IxTheoMapper(const std::vector<std::string> &map_file_line);

    /** \brief Returns an IxTheo notation if we can match "hierarchy_classification".  O/w we return the empty string. */
    std::string map(const std::string &hierarchy_classification) const;
};

IxTheoMapper::IxTheoMapper(const std::vector<std::string> &map_file_line) {
    if (map_file_line.size() < 2)
        throw std::runtime_error("in IxTheoMapper::IxTheoMapper: need at least 2 elements in \"map_file_line\"!");
    from_hierarchy_ = map_file_line[0];
    to_ix_theo_notation_ = map_file_line[1];
    std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_));
}

std::string IxTheoMapper::map(const std::string &hierarchy_classification) const {
    if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_))
        return "";

    for (const auto &exclusion : exclusions_) {
        if (StringUtil::StartsWith(hierarchy_classification, exclusion))
            return "";
    }

    return to_ix_theo_notation_;
}

void LoadCSVFile(const std::string &filename, std::vector<IxTheoMapper> * const mappers) {
    DSVReader csv_reader(filename);
    std::vector<std::string> csv_values;
    while (csv_reader.readLine(&csv_values))
        mappers->emplace_back(csv_values);

    std::cerr << "Read " << mappers->size() << " mappings from \"" << filename << "\".\n";
}

void UpdateIxTheoNotations(const std::vector<IxTheoMapper> &mappers, const std::vector<std::string> &orig_values,
                           std::string * const ixtheo_notations_list)
{
    std::vector<std::string> ixtheo_notations_vector;
    StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector);
    std::set<std::string> previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()),
                                                        std::make_move_iterator(ixtheo_notations_vector.end()));

    for (const auto &mapper : mappers) {
        for (const auto &orig_value : orig_values) {
            const std::string mapped_value(mapper.map(orig_value));
            if (not mapped_value.empty()
                and previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end())
            {
                if (not ixtheo_notations_list->empty())
                    *ixtheo_notations_list += ':';
                *ixtheo_notations_list += mapped_value;
                previously_assigned_notations.insert(mapped_value);
            }
        }
    }
}

void ProcessRecords(const bool verbose, MarcReader * const marc_reader, MarcWriter * const marc_writer,
                    const std::vector<IxTheoMapper> &ddc_to_ixtheo_notation_mappers,
                    const std::vector<IxTheoMapper> &/*rvk_to_ixtheo_notation_mappers*/)
{
    unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0);
    while (MarcRecord record = marc_reader->read()) {
        ++count;

        std::string ixtheo_notations_list(record.extractFirstSubfield("652", 'a'));
        if (not ixtheo_notations_list.empty()) {
            ++records_with_ixtheo_notations;
            marc_writer->write(record);
            continue;
        }

        std::vector<std::string> ddc_values;
        if (record.extractSubfield("082", 'a', &ddc_values) == 0) {
            marc_writer->write(record);
            continue;
        }

        // "K" stands for children's literature and "B" stands for fiction, both of which we don't want to
        // import into IxTheo;
        if (std::find(ddc_values.cbegin(), ddc_values.cend(), "K") != ddc_values.cend()
            or std::find(ddc_values.cbegin(), ddc_values.cend(), "B") != ddc_values.cend())
        {
            ++skipped_group_count;
            marc_writer->write(record);
            continue;
        }

        // Many DDC's have superfluous backslashes which are non-standard and need to be removed before further
        // processing can take place:
        for (auto &ddc_value : ddc_values)
            StringUtil::RemoveChars("/", &ddc_value);

        UpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list);
        if (verbose and not ixtheo_notations_list.empty()) {
            std::cout << record.getControlNumber() << ": " << StringUtil::Join(ddc_values, ',') << " -> " << ixtheo_notations_list << '\n';
        }

/*
        std::vector<std::string> rvk_values;
        int _084_index(record.getFieldIndex("084"));
        if (_084_index != -1) {
            const std::vector<std::string> &fields(record.getFields());
            while (_084_index < static_cast<ssize_t>(dir_entries.size()) and dir_entries[_084_index].getTag() == "084") {
                const Subfields subfields(fields[_084_index]);
                if (subfields.hasSubfieldWithValue('2', "rvk"))
                    rvk_values.emplace_back(subfields.getFirstSubfieldValue('a'));
                ++_084_index;
            }
        }
        UpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list);
*/

        if (not ixtheo_notations_list.empty()) {
            ++records_with_new_notations;
            record.insertField("652", "  ""\x1F""a" + ixtheo_notations_list + "\x1F""bDDCoderRVK");
        }

        marc_writer->write(record);
    }

    std::cout << ::progname << ": Read " << count << " records.\n";
    std::cout << ::progname << ": " << records_with_ixtheo_notations << " records had Ixtheo notations.\n";
    std::cout << ::progname << ": " << records_with_new_notations << " records received new Ixtheo notations.\n";
    std::cout << ::progname << ": " << skipped_group_count
              << " records where skipped because they were in a group that we are not interested in.\n";
}

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc != 5 and argc != 6)
        Usage();

    bool verbose(false);
    if (argc == 6) {
        if (std::strcmp(argv[1], "--verbose") != 0)
            Usage();
        verbose = true;
    }

    std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(argv[verbose ? 2 : 1], MarcReader::BINARY));
    std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(argv[verbose ? 3 : 2], MarcWriter::BINARY));

    try {
        std::vector<IxTheoMapper> ddc_to_ixtheo_notation_mappers;
        LoadCSVFile(argv[verbose ? 4 : 3], &ddc_to_ixtheo_notation_mappers);

        std::vector<IxTheoMapper> rvk_to_ixtheo_notation_mappers;
//      LoadCSVFile(argv[verbose ? 5 : 4], &rvk_to_ixtheo_notation_mappers);

        ProcessRecords(verbose, marc_reader.get(), marc_writer.get(), ddc_to_ixtheo_notation_mappers,
                       rvk_to_ixtheo_notation_mappers);
    } catch (const std::exception &x) {
        logger->error("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>New API: map_ddc_and_rvk...<commit_after>/** \file    map_ddc_and_rvk_to_ixtheo_notations.cc
 *  \brief   Map certain DDC and RVK categories to ixTheo notations and add them to field 652a.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2015-2018, Library of the University of Tübingen

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

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

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

#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <cctype>
#include <cstdlib>
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map "
              << "rvk_to_ixtheo_notations_map\n";
    std::exit(EXIT_FAILURE);
}

/** \class IxTheoMapper
 *  \brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation.
 */
class IxTheoMapper {
    std::string from_hierarchy_;
    std::string to_ix_theo_notation_;
    std::vector<std::string> exclusions_;
public:
    explicit IxTheoMapper(const std::vector<std::string> &map_file_line);

    /** \brief Returns an IxTheo notation if we can match "hierarchy_classification".  O/w we return the empty string. */
    std::string map(const std::string &hierarchy_classification) const;
};

IxTheoMapper::IxTheoMapper(const std::vector<std::string> &map_file_line) {
    if (map_file_line.size() < 2)
        throw std::runtime_error("in IxTheoMapper::IxTheoMapper: need at least 2 elements in \"map_file_line\"!");
    from_hierarchy_ = map_file_line[0];
    to_ix_theo_notation_ = map_file_line[1];
    std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_));
}

std::string IxTheoMapper::map(const std::string &hierarchy_classification) const {
    if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_))
        return "";

    for (const auto &exclusion : exclusions_) {
        if (StringUtil::StartsWith(hierarchy_classification, exclusion))
            return "";
    }

    return to_ix_theo_notation_;
}

void LoadCSVFile(const std::string &filename, std::vector<IxTheoMapper> * const mappers) {
    DSVReader csv_reader(filename);
    std::vector<std::string> csv_values;
    while (csv_reader.readLine(&csv_values))
        mappers->emplace_back(csv_values);

    std::cerr << "Read " << mappers->size() << " mappings from \"" << filename << "\".\n";
}

void UpdateIxTheoNotations(const std::vector<IxTheoMapper> &mappers, const std::vector<std::string> &orig_values,
                           std::string * const ixtheo_notations_list)
{
    std::vector<std::string> ixtheo_notations_vector;
    StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector);
    std::set<std::string> previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()),
                                                        std::make_move_iterator(ixtheo_notations_vector.end()));

    for (const auto &mapper : mappers) {
        for (const auto &orig_value : orig_values) {
            const std::string mapped_value(mapper.map(orig_value));
            if (not mapped_value.empty()
                and previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end())
            {
                if (not ixtheo_notations_list->empty())
                    *ixtheo_notations_list += ':';
                *ixtheo_notations_list += mapped_value;
                previously_assigned_notations.insert(mapped_value);
            }
        }
    }
}

void ProcessRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,
                    const std::vector<IxTheoMapper> &ddc_to_ixtheo_notation_mappers,
                    const std::vector<IxTheoMapper> &/*rvk_to_ixtheo_notation_mappers*/)
{
    unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0);
    while (MARC::Record record = marc_reader->read()) {
        ++count;

        std::string ixtheo_notations_list(record.getFirstSubfieldValue("652", 'a'));
        if (not ixtheo_notations_list.empty()) {
            ++records_with_ixtheo_notations;
            marc_writer->write(record);
            continue;
        }

        std::vector<std::string> ddc_values(record.getSubfieldValues("082", 'a'));
        if (ddc_values.empty()) {
            marc_writer->write(record);
            continue;
        }

        // "K" stands for children's literature and "B" stands for fiction, both of which we don't want to
        // import into IxTheo;
        if (std::find(ddc_values.cbegin(), ddc_values.cend(), "K") != ddc_values.cend()
            or std::find(ddc_values.cbegin(), ddc_values.cend(), "B") != ddc_values.cend())
        {
            ++skipped_group_count;
            marc_writer->write(record);
            continue;
        }

        // Many DDC's have superfluous backslashes which are non-standard and need to be removed before further
        // processing can take place:
        for (auto &ddc_value : ddc_values)
            StringUtil::RemoveChars("/", &ddc_value);

        UpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list);
        if (not ixtheo_notations_list.empty())
            LOG_DEBUG(record.getControlNumber() + ": " + StringUtil::Join(ddc_values, ',') + " -> " + ixtheo_notations_list);

/*
        std::vector<std::string> rvk_values;
        int _084_index(record.getFieldIndex("084"));
        if (_084_index != -1) {
            const std::vector<std::string> &fields(record.getFields());
            while (_084_index < static_cast<ssize_t>(dir_entries.size()) and dir_entries[_084_index].getTag() == "084") {
                const Subfields subfields(fields[_084_index]);
                if (subfields.hasSubfieldWithValue('2', "rvk"))
                    rvk_values.emplace_back(subfields.getFirstSubfieldValue('a'));
                ++_084_index;
            }
        }
        UpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list);
*/

        if (not ixtheo_notations_list.empty()) {
            ++records_with_new_notations;
            record.insertField("652", "  ""\x1F""a" + ixtheo_notations_list + "\x1F""bDDCoderRVK");
        }

        marc_writer->write(record);
    }

    std::cout << ::progname << ": Read " << count << " records.\n";
    std::cout << ::progname << ": " << records_with_ixtheo_notations << " records had Ixtheo notations.\n";
    std::cout << ::progname << ": " << records_with_new_notations << " records received new Ixtheo notations.\n";
    std::cout << ::progname << ": " << skipped_group_count
              << " records where skipped because they were in a group that we are not interested in.\n";
}

} // unnamed namespace

int Main(int argc, char **argv) {
    if (argc < 5)
        Usage();

    auto marc_reader(MARC::Reader::Factory(argv[1]));
    auto marc_writer(MARC::Writer::Factory(argv[2]));

    std::vector<IxTheoMapper> ddc_to_ixtheo_notation_mappers;
    LoadCSVFile(argv[3], &ddc_to_ixtheo_notation_mappers);

    std::vector<IxTheoMapper> rvk_to_ixtheo_notation_mappers;
    // The RVK notations were never provided to us by the librarians
    // So, we don't  use it at the moment
    //LoadCSVFile(argv[4], &rvk_to_ixtheo_notation_mappers);

    ProcessRecords(marc_reader.get(), marc_writer.get(), ddc_to_ixtheo_notation_mappers,
                   rvk_to_ixtheo_notation_mappers);
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef __CALLBACK_ENGINE_HPP_INCLUDED
#define __CALLBACK_ENGINE_HPP_INCLUDED

#include "cpp/ylikuutio/common/any_value.hpp"

// Include standard headers
#include <queue>         // std::queue
#include <stdint.h>      // uint32_t etc.
#include <string>        // std::string
#include <unordered_map> // std::unordered_map
#include <vector>        // std::vector

namespace model
{
    class World;
}

// callback typedefs in alphabetical order.
typedef void (*VoidToVoidCallback)(void);
typedef void (*AnyValueToVoidCallback)(AnyValue);
typedef AnyValue (*VoidToAnyValueCallback)(void);
typedef AnyValue (*AnyValueToAnyValueCallback)(AnyValue);

namespace callback_system
{
    class CallbackObject;

    class CallbackEngine
    {
        // `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.
        // `CallbackEngine` provides a way to create callback chains.
        //
        // Hierarchy of callbacks:
        //
        //     CallbackEngine
        //           ^
        //     CallbackObject
        //           ^
        //   CallbackParameter
        //
        // How to use.
        // 1. Create a new `CallbackEngine`. No callbacks have been
        //    defined yet. Calling `CallbackEngine.execute()` at this
        //    point will simply go through an empty vector and
        //    practically won't do anything interesting.
        // 2. Create a new `CallbackObject`, give pointer to the
        //    recently created `CallbackEngine` as input parameter.
        // 3. If the callback has parameter[s], create a new
        //    `CallbackParameter` for each parameter, give `CallbackObject`
        //    as input parameter for the `CallbackParameter` constructor.

        public:
            // constructor.
            CallbackEngine();

            // destructor.
            ~CallbackEngine();

            // execute all callbacks.
            AnyValue execute();

            friend class CallbackObject;

        private:
            // this method sets a callback object pointer.
            void set_callback_object_pointer(uint32_t childID, void* parent_pointer);

            // getter functions for callbacks and callback objects.
            bool get_bool(std::string name);
            float get_float(std::string name);
            double get_double(std::string name);
            int32_t get_int32_t(std::string name);
            uint32_t get_uint32_t(std::string name);
            void* get_void_pointer(std::string name);

            // setter functions for callbacks and callback objects.
            void set_bool(std::string name, bool value);
            void set_float(std::string name, float value);
            void set_double(std::string name, double value);
            void set_int32_t(std::string name, int32_t value);
            void set_uint32_t(std::string name, uint32_t value);
            void set_void_pointer(std::string name, void* value);
            void set_world_pointer(std::string name, model::World* value);

            std::vector<void*> callback_object_pointer_vector;
            std::queue<uint32_t> free_callback_objectID_queue;

            // A hash map used to store variables.
            std::unordered_map<std::string, AnyValue> anyvalue_hashmap;
    };
}

#endif
<commit_msg>Added `#include`.<commit_after>#ifndef __CALLBACK_ENGINE_HPP_INCLUDED
#define __CALLBACK_ENGINE_HPP_INCLUDED

#include "cpp/ylikuutio/common/any_value.hpp"
#include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <queue>         // std::queue
#include <stdint.h>      // uint32_t etc.
#include <string>        // std::string
#include <unordered_map> // std::unordered_map
#include <vector>        // std::vector

namespace model
{
    class World;
}

// callback typedefs in alphabetical order.
typedef void (*VoidToVoidCallback)(void);
typedef void (*AnyValueToVoidCallback)(AnyValue);
typedef AnyValue (*VoidToAnyValueCallback)(void);
typedef AnyValue (*AnyValueToAnyValueCallback)(AnyValue);

namespace callback_system
{
    class CallbackObject;

    class CallbackEngine
    {
        // `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.
        // `CallbackEngine` provides a way to create callback chains.
        //
        // Hierarchy of callbacks:
        //
        //     CallbackEngine
        //           ^
        //     CallbackObject
        //           ^
        //   CallbackParameter
        //
        // How to use.
        // 1. Create a new `CallbackEngine`. No callbacks have been
        //    defined yet. Calling `CallbackEngine.execute()` at this
        //    point will simply go through an empty vector and
        //    practically won't do anything interesting.
        // 2. Create a new `CallbackObject`, give pointer to the
        //    recently created `CallbackEngine` as input parameter.
        // 3. If the callback has parameter[s], create a new
        //    `CallbackParameter` for each parameter, give `CallbackObject`
        //    as input parameter for the `CallbackParameter` constructor.

        public:
            // constructor.
            CallbackEngine();

            // destructor.
            ~CallbackEngine();

            // execute all callbacks.
            AnyValue execute();

            friend class CallbackObject;

        private:
            // this method sets a callback object pointer.
            void set_callback_object_pointer(uint32_t childID, void* parent_pointer);

            // getter functions for callbacks and callback objects.
            bool get_bool(std::string name);
            float get_float(std::string name);
            double get_double(std::string name);
            int32_t get_int32_t(std::string name);
            uint32_t get_uint32_t(std::string name);
            void* get_void_pointer(std::string name);

            // setter functions for callbacks and callback objects.
            void set_bool(std::string name, bool value);
            void set_float(std::string name, float value);
            void set_double(std::string name, double value);
            void set_int32_t(std::string name, int32_t value);
            void set_uint32_t(std::string name, uint32_t value);
            void set_void_pointer(std::string name, void* value);
            void set_world_pointer(std::string name, model::World* value);

            std::vector<void*> callback_object_pointer_vector;
            std::queue<uint32_t> free_callback_objectID_queue;

            // A hash map used to store variables.
            std::unordered_map<std::string, AnyValue> anyvalue_hashmap;
    };
}

#endif
<|endoftext|>