blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5b4e0d164c08236f9ca0d2f1de37c3d985413660 | 42a799a12ffd61672ac432036b6fc8a8f3b36891 | /cpp/IGC_Tron/IGC_Tron/OGLRenderer.cpp | 8fce5199de746be9731fafb68934a9f42fe0d190 | [] | no_license | timotheehub/igctron | 34c8aa111dbcc914183d5f6f405e7a07b819e12e | e608de209c5f5bd0d315a5f081bf0d1bb67fe097 | refs/heads/master | 2020-02-26T16:18:33.624955 | 2010-04-08T16:09:10 | 2010-04-08T16:09:10 | 71,101,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,558 | cpp | /**************************************************************************/
/* This file is part of IGC Tron */
/* (c) IGC Software 2009 - 2010 */
/* Author : Pierre-Yves GATOUILLAT */
/**************************************************************************/
/* This program is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation, either version 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 General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/**************************************************************************/
/***********************************************************************************/
/** INCLUSIONS **/
/***********************************************************************************/
#include <typeinfo>
#include "OGLRenderer.h"
#include "X11Window.h"
#include "W32Window.h"
#include "IRenderer.h"
#include "Engine.h"
#ifdef _WIN32
#include <windows.h>
#endif
/***********************************************************************************/
/** DEBUG **/
/***********************************************************************************/
#include "Debug.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/***********************************************************************************/
namespace IGC
{
/***********************************************************************************/
/** CONSTRUCTEURS / DESTRUCTEUR **/
/***********************************************************************************/
OGLRenderer::OGLRenderer( Engine* _engine ) : IRenderer( _engine )
{
#ifdef _WIN32
hDC = 0;
hRC = 0;
#endif
glRenderTexture = 0;
glFontList = 0;
}
OGLRenderer::~OGLRenderer()
{
}
/***********************************************************************************/
/** ACCESSEURS **/
/***********************************************************************************/
void OGLRenderer::setFont( GLuint _glFontList )
{
glFontList = _glFontList;
}
/***********************************************************************************/
/** METHODES PUBLIQUES **/
/***********************************************************************************/
void OGLRenderer::initialize()
{
#ifdef _WIN32
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support IWindow
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
32, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
_assert( typeid( *engine->getWindow() ) == typeid( W32Window ), __FILE__, __LINE__,
"OGLRenderer::initialize() : Invalid window type, W32Window needed." );
W32Window* window = (W32Window*)engine->getWindow();
HWND hWnd = window->getHandle();
hDC = GetDC( hWnd );
_assert( hDC != 0, __FILE__, __LINE__,
"OGLRenderer::initialize() : Unable to create a GL Device Context." );
GLuint pf = ChoosePixelFormat( hDC, &pfd );
_assert( pf != 0, __FILE__, __LINE__,
"OGLRenderer::initialize() : Unable to find a suitable Pixel Format." );
_assert( SetPixelFormat( hDC, pf, &pfd ) == TRUE, __FILE__, __LINE__,
"OGLRenderer::initialize() : Unable to set the Pixel Format." );
hRC = wglCreateContext( hDC );
_assert( pf != 0, __FILE__, __LINE__,
"OGLRenderer::initialize() : Unable to create a GL Rendering Context." );
_assert( wglMakeCurrent( hDC, hRC ) == TRUE, __FILE__, __LINE__,
"OGLRenderer::initialize() : Unable to activate the GL Rendering Context." );
#else
_assert( typeid( *engine->getWindow() ) == typeid( X11Window ), __FILE__, __LINE__,
"OGLRenderer::initialize() : Invalid window type, X11Window needed." );
X11Window* window = (X11Window*)engine->getWindow();
Display* dpy = window->getDisplay();
XVisualInfo* vi = window->getVisualInfo();
::Window win = window->getWindow();
ctx = glXCreateContext( dpy, vi, 0, GL_TRUE );
glXMakeCurrent( dpy, win, ctx );
window->updateGeometry();
#endif
width = engine->getWindow()->getInnerWidth();
height = engine->getWindow()->getInnerHeight();
glFlush();
glewInit();
glShadeModel( GL_SMOOTH );
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClearDepth( 1.0f );
glEnable( GL_DEPTH_TEST );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
/*glEnable( GL_TEXTURE_2D );
glGenTextures( 1, &glRenderTexture );
glBindTexture( GL_TEXTURE_2D, glRenderTexture );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL );
glHostTextureData = malloc( width * height * sizeof(uint) );*/
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, 1.0f, 0.1f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}
void OGLRenderer::finalize()
{
//glDeleteTextures( 1, &glRenderTexture );
//free( glHostTextureData );
#ifdef _WIN32
wglMakeCurrent( NULL, NULL );
if ( hRC != 0 )
wglDeleteContext( hRC );
W32Window* window = (W32Window*)engine->getWindow();
HWND hWnd = window->getHandle();
if ( hDC != 0 )
ReleaseDC( hWnd, hDC );
#else
if ( ctx )
{
X11Window* window = (X11Window*)engine->getWindow();
Display* dpy = window->getDisplay();
glXMakeCurrent( dpy, None, NULL );
glXDestroyContext( dpy, ctx );
}
#endif
}
void OGLRenderer::update()
{
/*glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, 1.0f, 0.1f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, glRenderTexture );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, glHostTextureData );
glColor3f( 1.0f, 1.0f, 1.0f );
glBegin( GL_QUADS );
glTexCoord2f( 0.0f, 0.0f );
glVertex3f( -1.0f, 1.0f, -1.0f );
glTexCoord2f( 1.0f, 0.0f );
glVertex3f( 1.0f, 1.0f, -1.0f );
glTexCoord2f( 1.0f, 1.0f );
glVertex3f( 1.0f, -1.0f, -1.0f );
glTexCoord2f( 0.0f, 1.0f );
glVertex3f( -1.0f, -1.0f, -1.0f );
glEnd();
glBindTexture( GL_TEXTURE_2D, 0 );
glDisable( GL_TEXTURE_2D );*/
#ifdef _WIN32
SwapBuffers( hDC );
#else
X11Window* window = (X11Window*)engine->getWindow();
window->swapBuffers();
#endif
}
void OGLRenderer::setTransparency( bool _value )
{
if ( _value )
{
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_BLEND );
}
else
{
glDisable( GL_BLEND );
}
}
void OGLRenderer::clear( float _r, float _g, float _b, float _depth )
{
glClearColor( _r, _g, _b, 1.0f );
glClearDepth( _depth );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}
void OGLRenderer::drawText( const char* _text, int _x, int _y, float _r, float _g, float _b, float _a )
{
glDisable( GL_TEXTURE_2D );
glDisable( GL_DEPTH_TEST );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, 1.0f, 0.1f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef( 0.0f, 0.0f, -1.0f );
GLfloat inv_width = 2.0f / (GLfloat)width;
GLfloat inv_height = 2.0f / (GLfloat)height;
GLfloat offset = 16.0f * inv_height;
glColor4f( _r, _g, _b, _a );
glRasterPos2f( inv_width * (GLfloat)_x - 1.0f, 1.0f - offset - inv_height * (GLfloat)_y );
glPushAttrib( GL_LIST_BIT );
glListBase( glFontList - 32 );
glCallLists( strlen( _text ), GL_UNSIGNED_BYTE, _text );
glPopAttrib();
glEnable( GL_DEPTH_TEST );
}
void OGLRenderer::drawImage( int _x0, int _y0, int _x1, int _y1, float _px, float _py, float _sx, float _sy, float _r, float _g, float _b, float _a )
{
glDisable( GL_DEPTH_TEST );
glEnable( GL_TEXTURE_2D );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, 1.0f, 0.1f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
GLfloat inv_width = 2.0f / (GLfloat)width;
GLfloat inv_height = 2.0f / (GLfloat)height;
glColor4f( _r, _g, _b, _a );
glBegin( GL_QUADS );
glTexCoord2f( _px, _py + _sy );
glVertex3f( inv_width * (GLfloat)_x0 - 1.0f, 1.0f - inv_height * (GLfloat)_y1, -1.0f );
glTexCoord2f( _px + _sx, _py + _sy );
glVertex3f( inv_width * (GLfloat)_x1 - 1.0f, 1.0f - inv_height * (GLfloat)_y1, -1.0f );
glTexCoord2f( _px + _sx, _py );
glVertex3f( inv_width * (GLfloat)_x1 - 1.0f, 1.0f - inv_height * (GLfloat)_y0, -1.0f );
glTexCoord2f( _px, _py );
glVertex3f( inv_width * (GLfloat)_x0 - 1.0f, 1.0f - inv_height * (GLfloat)_y0, -1.0f );
glEnd();
glEnable( GL_DEPTH_TEST );
}
void OGLRenderer::resizeScene(int newWidth, int newHeight)
{
if (height == 0) /* Prevent A Divide By Zero If The Window Is Too Small */
height = 1;
width = newWidth;
height = newHeight;
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 90.0f, 1.0f, 0.1f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}
}
| [
"fenrhil@de5929ad-f5d8-47c6-8969-ac6c484ef978",
"raoul12@de5929ad-f5d8-47c6-8969-ac6c484ef978",
"[email protected]"
] | [
[
[
1,
165
],
[
167,
168
],
[
170,
177
],
[
182,
195
],
[
197,
197
],
[
199,
264
],
[
278,
286
],
[
290,
312
],
[
315,
315
],
[
348,
367
]
],
[
[
166,
166
],
[
169,
169
],
[
178,
181
],
[
196,
196
],
[
198,
198
],
[
265,
277
],
[
287,
287
],
[
289,
289
],
[
316,
318
],
[
320,
344
],
[
346,
347
]
],
[
[
288,
288
],
[
313,
314
],
[
319,
319
],
[
345,
345
]
]
] |
dfe2108d6d770078c0a31e321ea77b2909d1e968 | 4d91ca4dcaaa9167928d70b278b82c90fef384fa | /DistributionWizard/DistributionCreator/DistributionCreator/Diagnostics.cpp | 21ad8fc04e5a8b463e0b6b9cdba73508ec67e531 | [] | no_license | dannydraper/CedeCryptClassic | 13ef0d5f03f9ff3a9a1fe4a8113e385270536a03 | 5f14e3c9d949493b2831710e0ce414a1df1148ec | refs/heads/master | 2021-01-17T13:10:51.608070 | 2010-10-01T10:09:15 | 2010-10-01T10:09:15 | 63,413,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,237 | cpp | // This work is dedicated to the Lord our God. King of Heaven, Lord of Heaven's Armies.
#include "Diagnostics.h"
Diagnostics::Diagnostics ()
{
}
Diagnostics::~Diagnostics ()
{
}
void Diagnostics::Initialise (HWND hWnd)
{
SetParentHWND (hWnd);
SetBgColor (GetSysColor (COLOR_BTNFACE));
SetParentHWND (hWnd);
SetCaption (TEXT ("Communicator Diagnostics"));
SetWindowStyle (FS_STYLESTANDARD);
CreateAppWindow ("COMMDiagnosticsClass", 70, 0, 600, 350, true);
//m_uihandler.SetWindowProperties (0, 70, 40, 443, RGB (200, 200, 200));
//SetWindowPosition (FS_TOPLEFT);
//Show ();
}
void Diagnostics::OnCreate (HWND hWnd)
{
m_header.SetBitmapResources (IDB_DIAGHEADER);
m_header.SetBitmapProperties (0, 0, 591, 41);
m_header.SetProperties (hWnd, CID_HEADER, 1, 1, 591, 41);
m_uihandler.AddDirectControl (&m_header);
HFONT hfDefault = (HFONT) GetStockObject (DEFAULT_GUI_FONT);
m_hwnddiaglist = CreateWindow ("listbox", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, 1, 43, 591, 283, hWnd, (HMENU) ID_DIAGLIST, GetModuleHandle (NULL), NULL) ;
SendMessage (m_hwnddiaglist, WM_SETFONT, (WPARAM) hfDefault, MAKELPARAM (FALSE, 0));
OutputInt ("Diagnostics Ready: ", 0);
}
void Diagnostics::OutputInt (LPCSTR lpszText, int iValue)
{
char szInteger[SIZE_INTEGER];
ZeroMemory (szInteger, SIZE_INTEGER);
sprintf_s (szInteger, SIZE_INTEGER, "%d", iValue);
char szText[SIZE_STRING];
ZeroMemory (szText, SIZE_STRING);
strcpy_s (szText, SIZE_STRING, lpszText);
strcat_s (szText, SIZE_STRING, szInteger);
SendMessage (m_hwnddiaglist, LB_ADDSTRING, 0, (LPARAM) (LPCTSTR) &szText);
int lCount = SendMessage (m_hwnddiaglist, LB_GETCOUNT, 0, 0);
SendMessage (m_hwnddiaglist, LB_SETCURSEL, lCount-1, 0);
}
void Diagnostics::OutputText (LPCSTR lpszText)
{
char szText[SIZE_STRING];
ZeroMemory (szText, SIZE_STRING);
strcpy_s (szText, SIZE_STRING, lpszText);
SendMessage (m_hwnddiaglist, LB_ADDSTRING, 0, (LPARAM) (LPCTSTR) &szText);
int lCount = SendMessage (m_hwnddiaglist, LB_GETCOUNT, 0, 0);
SendMessage (m_hwnddiaglist, LB_SETCURSEL, lCount-1, 0);
}
void Diagnostics::OutputText (LPCSTR lpszName, LPCSTR lpszValue)
{
char szText[SIZE_STRING*2];
ZeroMemory (szText, SIZE_STRING*2);
strcat_s (szText, SIZE_STRING*2, lpszName);
strcat_s (szText, SIZE_STRING*2, lpszValue);
SendMessage (m_hwnddiaglist, LB_ADDSTRING, 0, (LPARAM) (LPCTSTR) &szText);
int lCount = SendMessage (m_hwnddiaglist, LB_GETCOUNT, 0, 0);
SendMessage (m_hwnddiaglist, LB_SETCURSEL, lCount-1, 0);
}
void Diagnostics::OnCommand (HWND hWnd, WPARAM wParam, LPARAM lParam)
{
}
void Diagnostics::OnUICommand (HWND hWnd, WPARAM wParam, LPARAM lParam)
{
}
void Diagnostics::OnTimer (WPARAM wParam)
{
m_uihandler.NotifyTimer (wParam);
}
void Diagnostics::OnPaint (HWND hWnd)
{
m_uihandler.PaintControls (hWnd);
}
void Diagnostics::OnMouseMove (HWND hWnd, int mouseXPos, int mouseYPos)
{
m_uihandler.NotifyMouseMove (mouseXPos, mouseYPos);
}
void Diagnostics::OnLButtonDown (HWND hWnd)
{
m_uihandler.NotifyMouseDown ();
}
void Diagnostics::OnLButtonUp (HWND hWnd)
{
m_uihandler.NotifyMouseUp ();
} | [
"ddraper@f12373e4-23ff-6a4a-9817-e77f09f3faef"
] | [
[
[
1,
115
]
]
] |
8b5b3cbce994ac7519afcca035ad8e336c9bf1fe | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/tlclasses/CQuest.h | 54990f818253205cff1532bdc42d4041f14f85d2 | [] | no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h | #pragma once
#include "CRunicCore.h"
#include "CLevelTemplateData.h"
#include "CQuestDialog.h"
#include "CQuestRewards.h"
#include "CQuestRequirements.h"
namespace TLAPI
{
struct CQuestManager;
#pragma pack(1)
struct CQuest : CRunicCore
{
PVOID unk0;
CLevelTemplateData *pCLevelTemplateData;
u32 unk1[6];
wstring dungeon; // "RANDOMDUNGEON"
wstring unk2; // ""
wstring unk21; // ""
wstring location; // "MEDIA/QUESTS/VASMANRANDOM/ANOTHERPIECECAVES.DAT"
wstring name; // "ANOTHERPIECECAVES"
wstring displayName; // "|cFFFFBA00Another Piece|u"
CList<CQuestDialog *> CQuestDialogList0;
CList<CQuestDialog *> CQuestDialogList1;
u32 unk4[25];
CQuestRewards *pCQuestRewards;
u32 unk5[27];
u64 guid;
CQuestManager *pCQuestManager;
CResourceManager *pCResourceManager;
CQuestRequirements *pCQuestRequirements;
};
#pragma pack()
};
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
] | [
[
[
1,
51
]
]
] |
9ef4c26f73eaeb69d5c66277cf69caf44cc8116f | b3aa9f23d68b70de141a8b5566b5f07198587e37 | /KalahPlayer/Main.cpp | 883e324ed36cfa7f9f13aa31a5ce19cc925d0ccd | [] | no_license | heemoona/kalah-player-agent | 275fe8574aa8725636387c604b744445e55f8d3f | 033c49b15f84eff188012b700322839061c0b991 | refs/heads/master | 2021-01-10T10:38:57.311125 | 2008-05-17T12:06:35 | 2008-05-17T12:06:35 | 55,122,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,550 | cpp | #include "Definitions.h"
#include "KalahGame.h"
#include "RandomKalahPlayer.h"
#include "OmerMark_AlphaBetaKalahPlayer.h"
#include "OmerMark_Heuristics_Enhanced2.h"
#include "GameTimer.h"
#include <iostream>
#include <cstdlib>
using namespace std;
// Game parameters defaults
const int default_board_size(3); // Board size - number of houses per player's row
const int default_stones_in_house(3); // Initial number of stones per house
const double default_time_per_move(0.1); // Time per player's turn (in seconds)
const double default_time_for_constructing(1); // Time for player's constructor
const double default_time_for_initialization(10); // Time for player's initGame
// Globals for replacing default values with command line parameters
int board_size(default_board_size);
int stones_in_house(default_stones_in_house);
double time_per_move(default_time_per_move);
// Parse command line
// -size Board size
// -stones Initial stones in house
// -time Time per game move
bool ProcessCommandLine(int argc, char **argv);
// Output command line parameters' description
void PrintHelpMessage(char **argv);
int main(int argc, char **argv)
{
// Read game parameters from command line, if any
// Game uses defaults for any command line parameter not specified
if(!ProcessCommandLine(argc, argv))
{
PrintHelpMessage(argv);
return 1;
};
// Randomizing
srand((unsigned int)time(0));
// Game/move parameters
GameTimer::TimeParams tp;
tp.timePerGame_limit = false;
tp.timePerMove_limit = true;
tp.timePerMove = time_per_move;
// Players construction
// (initialization with game parameters is done as the first task
// of KalahGame::playGame)
bool Player1_bad_init(false), Player2_bad_init(false);
// Time limits for construction, using timer's move limit
GameTimer::TimeParams init_tp;
init_tp.timePerGame_limit = false;
init_tp.timePerMove_limit = true;
init_tp.timePerMove = default_time_for_constructing;
GameTimer init_timer(init_tp);
Definitions::PlayerColor color1 = Definitions::WHITE;
Definitions::PlayerColor color2 = Definitions::BLACK;
vector<int> results(2);
cout << "[Board = \t" << board_size << ", Stones = \t" << \
stones_in_house << ", Time = \t" << time_per_move << "\t]" << endl;
bool toggle_move = false;
for (int i=0; i<20; ++i)
{
toggle_move = !toggle_move;
// Constructing first player
// It is white and will play first
Player *p1;
Player *p2;
if (toggle_move)
{
init_timer.startMoveTimer();
p1 = new OmerMarkAlphaBetaKalahPlayer(color1, tp, new OmerMark_Heuristics_Simple());
(dynamic_cast<OmerMarkAlphaBetaKalahPlayer*>(p1))->setName("Simple");
if(init_timer.isMoveTimePassed())
Player1_bad_init = true;
// Constructing second player
// It is black and will play second
init_timer.startMoveTimer();
p2 = new OmerMarkAlphaBetaKalahPlayer(color2, tp, new OmerMark_Heuristics_Enhanced2(10,0.5));
(dynamic_cast<OmerMarkAlphaBetaKalahPlayer*>(p2))->setName("Enhanced++");
if(init_timer.isMoveTimePassed())
Player2_bad_init = true;
}
else
{
init_timer.startMoveTimer();
p1 = new OmerMarkAlphaBetaKalahPlayer(color1, tp, new OmerMark_Heuristics_Enhanced2(10,0.5));
(dynamic_cast<OmerMarkAlphaBetaKalahPlayer*>(p1))->setName("Enhanced++");
if(init_timer.isMoveTimePassed())
Player1_bad_init = true;
// Constructing second player
// It is black and will play second
init_timer.startMoveTimer();
p2 = new OmerMarkAlphaBetaKalahPlayer(color2, tp, new OmerMark_Heuristics_Simple());
(dynamic_cast<OmerMarkAlphaBetaKalahPlayer*>(p2))->setName("Simple ");
if(init_timer.isMoveTimePassed())
Player2_bad_init = true;
}
// Check whether any player used too much time during construction
if(Player1_bad_init || Player2_bad_init)
{
vector<string> playersNames;
playersNames.push_back(p1->getName());
playersNames.push_back(p2->getName());
// Compute game results (premature termination - technical lose)
Game::GameRes gameRes;
gameRes.players_result.resize(2);
if(Player1_bad_init)
// Player 1 timeout
gameRes.players_result[0] = Game::GameRes::TIMEOUT;
else
// Player 1 OK, player 2 timeout ==> Player 1 wins
gameRes.players_result[0] = Game::GameRes::WIN;
if(Player2_bad_init)
// Player 2 timeout
gameRes.players_result[1] = Game::GameRes::TIMEOUT;
else
// Player 2 OK, player 1 timeout ==> Player 2 wins
gameRes.players_result[1] = Game::GameRes::WIN;
delete p1;
delete p2;
// Output game result to the console
cout << Game::ResultToString(gameRes, playersNames) << endl;
// Exit program
return 0;
}
// Players' construction went fine, start a game
vector<Player*> players;
players.push_back(p1);
players.push_back(p2);
// Initialize game
KalahGame kg(players, default_time_for_initialization,
tp, board_size, stones_in_house);
// Play game
kg.playGame();
cout << kg.ResultToString() << endl;
for (int j=0; j<2; ++j)
{
int k = j;
if (!toggle_move)
k = 1-k;
// Output game result to the console
if (kg.getPlayerResult(j) == Game::GameRes::ILLEGAL_MOVE)
results[k] -= 5;
if (kg.getPlayerResult(j) == Game::GameRes::NORMAL_WIN)
results[k] += 1;
if (kg.getPlayerResult(j) == Game::GameRes::WIN)
results[k] += 1;
if (kg.getPlayerResult(j) == Game::GameRes::DRAW)
results[k] += 1;
if (kg.getPlayerResult(j) == Game::GameRes::TIMEOUT)
results[k] -= 3;
}
}
cout << "[Simple \t" << results[0] << "\tEnhanced\t" << results[1] << "]" << endl << endl;
return 0;
};
bool ProcessCommandLine(int argc, char **argv)
{
bool errorEncountered(false);
for(int i(1); (i < argc) && !errorEncountered; ++i)
{
if(string(argv[i]) == "-h")
{
errorEncountered = true;
}
else if(string(argv[i]) == "-size")
{
errno = 0;
board_size = atoi(argv[++i]);
if(board_size < 1)
errorEncountered = true;
}
else if (string(argv[i]) == "-stones")
{
errno = 0;
stones_in_house = atoi(argv[++i]);
if(stones_in_house < 0)
errorEncountered = true;
}
else if(string(argv[i]) == "-time")
{
errno = 0;
time_per_move = atof(argv[++i]);
if(time_per_move <= 0)
errorEncountered = true;
}
else
{
errorEncountered = true;
};
if(errno != 0)
errorEncountered = true;
};
return !errorEncountered;
};
void PrintHelpMessage(char **argv)
{
cout << "Arguments for " << argv[0] << " :" << endl;
cout
<< "\t -size <board size> (default: 6)" << endl
<< "\t -stones <initial stones in each house> (default: 3)" << endl
<< "\t -time <time limit per move, in seconds> (default: 1.0)" << endl
;
};
| [
"Mr.Hellmaker@a6ee2c79-0d4a-0410-b19e-35e742fabaac"
] | [
[
[
1,
241
]
]
] |
4946882b00c8c7e93d58c02c5aec16355ddf4f35 | 4f89f1c71575c7a5871b2a00de68ebd61f443dac | /lib/boost/gil/extension/sdl/sdl_window_base.hpp | 38ba446f6f01d70f512dc086f48d427c3524642d | [] | no_license | inayatkh/uniclop | 1386494231276c63eb6cdbe83296cdfd0692a47c | 487a5aa50987f9406b3efb6cdc656d76f15957cb | refs/heads/master | 2021-01-10T09:43:09.416338 | 2009-09-03T16:26:15 | 2009-09-03T16:26:15 | 50,645,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,386 | hpp | // Copyright 2007 Christian Henning.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/*************************************************************************************************/
#ifndef SDL_WINDOW_BASE_HPP
#define SDL_WINDOW_BASE_HPP
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <SDL.h>
#include "sdl_events.hpp"
#include "message_queue.h"
namespace boost
{
namespace gil
{
namespace sdl
{
typedef detail::sdl_event_base sdl_event_t;
typedef ogx::message_queue< sdl_event_t > queue_t;
class sdl_window_base
{
protected:
sdl_window_base( int width
, int height )
: _queue( NULL )
, _surface_init( false )
, _width ( width )
, _height( height )
{
if ( !_surface_init )
{
_screen = SDL_SetVideoMode( _width
, _height
, 32
, SDL_SWSURFACE );
if ( _screen == NULL )
{
throw std::runtime_error( "Couldn't create SDL window" );
}
_surface_init = true;
}
}
void lock()
{
if ( _screen && SDL_MUSTLOCK( _screen ))
{
if ( SDL_LockSurface( _screen ) < 0 )
{
return;
}
}
}
void unlock()
{
if ( _screen && SDL_MUSTLOCK( _screen ))
{
SDL_UnlockSurface( _screen );
}
// Tell SDL to update the whole screen
SDL_UpdateRect( _screen
, 0
, 0
, _width
, _height );
}
queue_t* get_queue()
{
return _queue;
}
private:
void set_queue( queue_t& queue )
{
_queue = &queue;
}
friend class sdl_service;
protected:
bool _surface_init;
int _width;
int _height;
SDL_Surface* _screen;
private:
queue_t* _queue;
};
}
}
} // namespace boost::gil::sdl
#endif // SDL_WINDOW_BASE_HPP
| [
"rodrigo.benenson@gmailcom"
] | [
[
[
1,
117
]
]
] |
661a92d6ab171514c1c2ca9acf8a4bf6b2fcb093 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataWorkingDirBrowser.h | bf6b272699fc4191dd84144198562e126e9d14dc | [] | no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | h | #ifndef PRORATAWORKDIR_H
#define PRORATAWORKDIR_H
#include <QPushButton>
#include <QGroupBox>
#include <QLineEdit>
#include <QLabel>
#include <QLayout>
#include <QFileDialog>
#include <QSizePolicy>
#include <QMessageBox>
#include <QComboBox>
#include "proRataPreProcess.h"
#include "proRataDTASelect.h"
#include "proRataConfigBrowser.h"
#include "proRataRaw2MzXMLBrowser.h"
class ProRataPreProcessWizard;
class ProRataDTASelect;
class ProRataConfigBrowser;
class ProRataRaw2MzXMLBrowser;
class ProRataWorkingDirBrowser : public QWidget
{
Q_OBJECT
public:
ProRataWorkingDirBrowser( QWidget* parent = 0, Qt::WFlags fl = 0 );
~ProRataWorkingDirBrowser();
const QString & getWorkingDirectory()
{ return qsWorkingDirectory; }
bool isValid();
public slots:
void getDirectory();
void validate();
protected:
void buildUI();
QWidget *qwParent;
QGroupBox* qgbInputBox;
QLabel* qlDirectoryLabel;
QLineEdit* qleDirectoryEntry;
QPushButton* qpbDirectoryBrowser;
QHBoxLayout* qhbMainLayout;
QGridLayout* qgbInputBoxLayout;
QString qsWorkingDirectory;
bool bValidity;
friend class ProRataPreProcessWizard;
friend class ProRataDTASelect;
friend class ProRataConfigBrowser;
friend class ProRataRaw2MzXMLBrowser;
};
#endif // PRORATAWORKDIR_H
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
] | [
[
[
1,
63
]
]
] |
53401a745a0a87642915bdd2aa4e0dc71abea92f | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /pyplusplus_dev/unittests/data/ctypes/function_ptr_as_variable/function_ptr_as_variable.cpp | 0c9c2a587adcf8c099a4029178af14431f57b7e5 | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 142 | cpp | #include "function_ptr_as_variable.h"
EXPORT_SYMBOL int execute_callback(struct info* info, int v) {
return info->do_smth_fun(v);
}
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
5
]
]
] |
e1b2ee6b9e505a58ead6ea3fb646a631b706b728 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /branches/engine/2.4/src/SeedHash.cpp | 914f17d49df2fcad1cc85f16160bb762d1ec8e8d | [] | no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,913 | cpp | //
// File : $RCSfile: $
// $Workfile: SeedHash.cpp $
// Version : $Revision: 10 $
// $Author: Aviad $
// $Date: 23/08/04 21:44 $
// Description :
// Concrete and interface classes for a hash-table of positions
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors appliy.
// see http://www.cs.huji.ac.il/labs/compbio/LibB/LICENSE
//
#include "SeedHash.h"
#include "AssignmentFormat.h"
#include "persistance/TextWriter.h"
#include "persistance/StrOutputStream.h"
using namespace Persistance;
//
// AssgKey
SeedHash::AssgKey::AssgKey (const Str& data,
const Langauge& langauge)
: _assg (data, langauge.code ())
{
char buffer [8096];
Persistance::FixedBufferOutputStream output (buffer, sizeof (buffer));
{ Persistance::TextWriter textWriter (&output, false);
textWriter << AssignmentFormat (_assg, langauge);
}
_hash = defaultHashFunction ( buffer, output.getSize ());
}
SeedHash::AssgKey::AssgKey (const Assignment& assg,
const Langauge& langauge)
: _assg (assg)
{
char buffer [8096];
Persistance::FixedBufferOutputStream output (buffer, sizeof (buffer));
{ Persistance::TextWriter textWriter (&output, false);
textWriter << AssignmentFormat (_assg, langauge);
}
_hash = defaultHashFunction ( buffer, output.getSize ());
}
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
] | [
[
[
1,
67
]
]
] |
00ba7f1a1e6ad0104384be58359fdd9bc46ba2d8 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/audio/MglMp3Dshow.h | 7f202f3f87144078ef8f24b5f2e97bb14948f351 | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 403 | h | //////////////////////////////////////////////////////////
//
// CMglMp3Dshow
// - エラー処理付き
//
//////////////////////////////////////////////////////////
#ifndef __MglMp3Dshow_H__
#define __MglMp3Dshow_H__
#include "MglDirectShowBase.h"
#include "MglBgmBase.h"
// クラス宣言
class DLL_EXP CMglMp3Dshow : public CMglDirectShowBase
{
};
#endif//__MglMp3Dshow_H__
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | [
[
[
1,
19
]
]
] |
e36d423d848c7933d83f92fb1fea23a407863aaa | 0dba4a3016f3ad5aa22b194137a72efbc92ab19e | /a2e/src/camera.cpp | d07047f1608c5bbee5a91e7b4668b14ce38738c2 | [] | no_license | BackupTheBerlios/albion2 | 11e89586c3a2d93821b6a0d3332c1a7ef1af6abf | bc3d9ba9cf7b8f7579a58bc190a4abb32b30c716 | refs/heads/master | 2020-12-30T10:23:18.448750 | 2007-01-26T23:58:42 | 2007-01-26T23:58:42 | 39,515,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,994 | cpp | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "camera.h"
/*! there is no function currently
*/
camera::camera(engine* e) {
camera::position = new vertex3();
camera::rotation = new vertex3();
camera::direction = new vertex3();
up_down = 0.0f;
camera::cam_input = true;
camera::mouse_input = true;
rotation_speed = 100.0f;
cam_speed = 1.0f;
camera::flip = e->get_ext()->is_fbo_support();
// get classes
camera::e = e;
camera::c = e->get_core();
camera::m = e->get_msg();
camera::evt = e->get_event();
}
/*! there is no function currently
*/
camera::~camera() {
m->print(msg::MDEBUG, "camera.cpp", "freeing camera stuff");
delete camera::position;
delete camera::rotation;
delete camera::direction;
m->print(msg::MDEBUG, "camera.cpp", "camera stuff freed");
}
/*! runs the camera (expected to be called every draw)
*/
void camera::run() {
// if camera class input flag is set, then ...
if(camera::cam_input) {
// ... recalculate the cameras position
if(evt->is_key_right()) {
position->x += (float)sin((rotation->y - 90.0f) * PIOVER180) * cam_speed;
position->z += (float)cos((rotation->y - 90.0f) * PIOVER180) * cam_speed;
}
if(evt->is_key_left()) {
position->x -= (float)sin((rotation->y - 90.0f) * PIOVER180) * cam_speed;
position->z -= (float)cos((rotation->y - 90.0f) * PIOVER180) * cam_speed;
}
if(evt->is_key_up()) {
if(!flip) {
position->x += (float)sin(rotation->y * PIOVER180) * cam_speed;
position->y -= (float)sin(rotation->x * PIOVER180) * cam_speed;
position->z += (float)cos(rotation->y * PIOVER180) * cam_speed;
}
else {
position->x += (float)sin(rotation->y * PIOVER180) * cam_speed;
position->y += (float)sin((360.0f - rotation->x) * PIOVER180) * cam_speed;
position->z += (float)cos(rotation->y * PIOVER180) * cam_speed;
}
}
if(evt->is_key_down()) {
if(!flip) {
position->x -= (float)sin(rotation->y * PIOVER180) * cam_speed;
position->y += (float)sin(rotation->x * PIOVER180) * cam_speed;
position->z -= (float)cos(rotation->y * PIOVER180) * cam_speed;
}
else {
position->x -= (float)sin(rotation->y * PIOVER180) * cam_speed;
position->y -= (float)sin((360.0f - rotation->x) * PIOVER180) * cam_speed;
position->z -= (float)cos(rotation->y * PIOVER180) * cam_speed;
}
}
}
if(camera::mouse_input) {
// calculate the rotation via the current mouse cursor position
int cursor_pos_x = 0;
int cursor_pos_y = 0;
SDL_GetMouseState((int*)&cursor_pos_x, (int*)&cursor_pos_y);
float xpos = (1.0f / (float)e->get_screen()->w) * (float)cursor_pos_x;
float ypos = (1.0f / (float)e->get_screen()->h) * (float)cursor_pos_y;
if(xpos != 0.5f || ypos != 0.5f) {
rotation->x += (0.5f - ypos) * rotation_speed;
rotation->y += (0.5f - xpos) * rotation_speed;
SDL_WarpMouse(e->get_screen()->w/2, e->get_screen()->h/2);
}
}
if(rotation->x > 360.0f) {
rotation->x -= 360.0f;
}
else if(rotation->x < 0.0f) {
rotation->x += 360.0f;
}
if(rotation->y > 360.0f) {
rotation->y -= 360.0f;
}
else if(rotation->y < 0.0f) {
rotation->y += 360.0f;
}
// rotate
if(!flip) {
glRotatef(360.0f - rotation->x, 1.0f, 0.0f, 0.0f);
glRotatef(360.0f - rotation->y, 0.0f, 1.0f, 0.0f);
}
else {
glRotatef(rotation->x, 1.0f, 0.0f, 0.0f);
glRotatef(360.0f - rotation->y, 0.0f, 1.0f, 0.0f);
}
if(flip) position->y *= -1.0f;
// reposition / "rotate"
e->set_position(camera::position->x, camera::position->y, camera::position->z);
e->set_rotation(camera::rotation->x, camera::rotation->y);
if(flip) position->y *= -1.0f;
}
/*! sets the position of the camera
* @param x x coordinate
* @param y y coordinate
* @param z z coordinate
*/
void camera::set_position(float x, float y, float z) {
camera::position->x = x;
camera::position->y = y;
camera::position->z = z;
camera::position->y *= -1.0f;
}
/*! sets the rotation of the camera
* @param x x rotation
* @param y y rotation
* @param z z rotation
*/
void camera::set_rotation(float x, float y, float z) {
camera::rotation->x = x;
camera::rotation->y = y;
camera::rotation->z = z;
}
/*! returns the position of the camera
*/
vertex3* camera::get_position() {
return camera::position;
}
/*! returns the rotation of the camera
*/
vertex3* camera::get_rotation() {
return camera::rotation;
}
/*! if cam_input is set true then arrow key input and (auto-)reposition
*! stuff is done automatically in the camera class. otherwise you have
*! to do it yourself.
* @param state the cam_input state
*/
void camera::set_cam_input(bool state) {
camera::cam_input = state;
}
/*! if mouse_input is set true then the cameras rotation is controlled via
*! the mouse - furthermore the mouse cursor is reset to (0.5, 0.5) every cycle.
*! if it's set to false nothing (no rotation) happens.
* @param state the cam_input state
*/
void camera::set_mouse_input(bool state) {
camera::mouse_input = state;
}
/*! returns the cam_input bool
*/
bool camera::get_cam_input() {
return camera::cam_input;
}
/*! returns the mouse_input bool
*/
bool camera::get_mouse_input() {
return camera::mouse_input;
}
/*! sets the cameras rotation speed to speed
* @param speed the new rotation speed
*/
void camera::set_rotation_speed(float speed) {
camera::rotation_speed = speed;
}
/*! returns cameras rotation speed
*/
float camera::get_rotation_speed() {
return camera::rotation_speed;
}
/*! sets the cameras speed to speed
* @param speed the new camera speed
*/
void camera::set_cam_speed(float speed) {
camera::cam_speed = speed;
}
/*! returns cameras speed
*/
float camera::get_cam_speed() {
return camera::cam_speed;
}
void camera::set_flip(bool state) {
flip = state;
}
bool camera::get_flip() {
return flip;
}
/*! returns the cameras direction
*/
vertex3* camera::get_direction() {
direction->x = (float)sin(rotation->y * PIOVER180);
direction->y = (float)sin(rotation->x * PIOVER180);
direction->z = (float)cos(rotation->y * PIOVER180);
return camera::direction;
}
| [
"[email protected]"
] | [
[
[
1,
254
]
]
] |
6c4953553f93f95e0218fdb41c73bf391e4704cf | 3eae1d8c99d08bca129aceb7c2269bd70e106ff0 | /trunk/Codes/CLR/Libraries/SPOT/spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID.cpp | eb509fa66e2d7aecf8d39ba5ab50025b7a79d587 | [] | no_license | yuaom/miniclr | 9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082 | 4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1 | refs/heads/master | 2023-06-07T09:10:33.703929 | 2010-12-27T14:41:18 | 2010-12-27T14:41:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "SPOT.h"
HRESULT Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_OEM___STATIC__U1( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
//stack.SetResult( OEM_Model_SKU.OEM, DATATYPE_U1 );
TINYCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_Model___STATIC__U1( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
//stack.SetResult( OEM_Model_SKU.Model, DATATYPE_U1 );
TINYCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_spot_native_Microsoft_SPOT_Hardware_SystemInfo__SystemID::get_SKU___STATIC__U2( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
//stack.SetResult( OEM_Model_SKU.SKU, DATATYPE_U2 );
TINYCLR_NOCLEANUP_NOLABEL();
}
| [
"[email protected]"
] | [
[
[
1,
36
]
]
] |
b2e2563c646cf56cf89f924088fefe6a829f411d | 81344a13313d27b6af140bc8c9b77c9c2e81fee2 | /wjg/Services/StdAfx.cpp | 8c55c2b8f461afcd197a4f476a4531d9362fa7f9 | [] | no_license | radtek/aitop | 169912e43a6d2bc4018219634d13dc786fa28a31 | a2a89859d0d912b0844593972a2310798573219f | refs/heads/master | 2021-01-01T03:57:19.378394 | 2008-06-17T16:03:19 | 2008-06-17T16:03:19 | 58,142,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Services.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
76b7720085abfd8e9b7d8770ee7c063c71e63d87 | 66b680ade6dce8bd79925d6b69064ea52202f7a9 | /uss/src/daemon/uss_daemon.cpp | 87cc80664be965765b3cd607e986d6365ab5eb71 | [] | no_license | tobib/hetsched | 8c177341ddc26afc10ffe3b501f26a1f69bba766 | b3d17cab5b31279285a429b312771df9ae0989d0 | refs/heads/master | 2020-04-15T17:05:47.005652 | 2011-11-28T16:11:34 | 2011-11-28T16:11:34 | 2,868,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,236 | cpp | #include "./uss_daemon.h"
#include "./uss_comm_controller.h"
#include "./uss_registration_controller.h"
#include "./uss_scheduler.h"
#include "./uss_device_controller.h"
#include "../common/uss_tools.h"
using namespace std;
static volatile int daemon_exit = 0;
static void int_sighandler(int sig)
{
if(sig == SIGINT){printf("signal INT recieved cleanup\n"); daemon_exit = 1;}
}
void user_sighandler(int sig, siginfo_t *si, void *ucontext)
{
/*
*do nothing with USR signal! just wake up main thread
*
if(sig == SIGUSR1){printf("uss_daemon signal user1 recieved\n");}
if(sig == SIGUSR2){printf("uss_daemon signal user2 recieved\n");}
*/
}
#if(BENCHMARK_DAEMON_CPUTIME == 1)
/*BENCHMARK to calculate the CPU time this P from state to stop
*[additionally take time from main T and compare to P]
*state:
*(0) benchmark_daemon_cputime_state is initialized with 0
*(1) first registration comes in [START]
* => start measurement
*(2) last job/handle is removed [STOP]
* => end measurement, print cpu time in nano seconds and stop daemon
*/
int benchmark_daemon_cputime_state = 0;
clockid_t selected_clockid;
struct timespec time_start;
struct timespec process_cputime_start;
struct timespec thread_cputime_start;
struct timespec time_stop;
struct timespec process_cputime_stop;
struct timespec thread_cputime_stop;
#endif
void print_complete_status(uss_registration_controller *rc, uss_scheduler *sched)
{
type_reg_pending_table_iterator it1 = rc->reg_pending_table.begin();
printf("---------------------------------------------------------------------------\n");
printf("reg pending table: ");
for(; it1 != rc->reg_pending_table.end(); it1++)
{
printf(" %i ", (*it1).first);
}
printf("\n reg table: ");
type_reg_table_iterator it2 = rc->reg_table.begin();
for(; it2 != rc->reg_table.end(); it2++)
{
printf(" %i ", (*it2).first);
}
printf("\n addr table: ");
type_addr_table_iterator it3 = rc->addr_table.begin();
for(; it3 != rc->addr_table.end(); it3++)
{
#if(USS_FIFO == 1)
printf(" %ld ", (*it3).first.fifo);
#endif
}
printf("\n");
sched->print_queues();
printf("\n---------------------------------------------------------------------------\n");
}
/*
* free this process from constraints
*/
void daemonize()
{
/*
* make the process a child of the init process
* -> child process is guaranteed not to be a process group leader
*/
switch(fork())
{
case -1: _exit(EXIT_FAILURE);
case 0: break;
default: _exit(EXIT_SUCCESS);
}
/*
* free process of any association with a controlling terminal
*/
if(setsid() == -1) {_exit(EXIT_FAILURE);}
/*
* ensure that the process isn't session leader
*/
switch(fork())
{
case -1: _exit(EXIT_FAILURE);
case 0: break;
default: _exit(EXIT_SUCCESS);
}
/*
* clear file mode creation mask
*/
umask(0);
/*
* change to USS directory
*/
chdir(USS_DIRECTORY);
return;
}
/***************************************\
* MAIN THREAD ! (daemon thread) *
\***************************************/
int main ()
{
//
//set properties for a daemon
//
#if(USS_DAEMONIZE == 1)
daemonize();
#endif
int ret;
//set timing interval
struct timespec user_param_sched_interval;
user_param_sched_interval.tv_sec = USS_SCHED_INTERVAL_SEC;
user_param_sched_interval.tv_nsec = USS_SCHED_INTERVAL_NSEC;
#if(USS_DAEMON_DEBUG == 1)
printf("\nUSER SPACE SCHEDULER - daemon starting \n");
printf("---------------------------------------------------------------------------\n");
int display_counter = 0;
#endif
#if(USS_FIFO == 1)
//make thread "immune" to SIGPIPE signals => such fails are handled by errno status
sigset_t immune_set;
sigemptyset(&immune_set);
sigaddset(&immune_set, (SIGPIPE));
pthread_sigmask(SIG_BLOCK, &immune_set, NULL);
#elif(USS_RTSIG == 1)
//make thread "immune" to realtime signals => all later thread inherit this mask!
sigset_t immune_set;
sigemptyset(&immune_set);
sigaddset(&immune_set, (SIGRTMIN+0));
sigaddset(&immune_set, (SIGRTMIN+1));
pthread_sigmask(SIG_BLOCK, &immune_set, NULL);
#endif
//
//enable default signal handles (clean termination)
//
struct sigaction sa_basic;
sa_basic.sa_flags = 0;
sa_basic.sa_handler = int_sighandler;
sigemptyset(&sa_basic.sa_mask);
ret = sigaction(SIGINT, &sa_basic, NULL);
if(ret == -1) {printf("dderror: signal int not established\n"); exit(1);}
//
//enable special signal handler to wake up this thread
//
struct sigaction sa_user;
sa_user.sa_flags = SA_SIGINFO;
sa_user.sa_sigaction = user_sighandler;
sigemptyset(&sa_user.sa_mask);
//sigaddset(&sa_user.sa_mask, SIGUSR1);
ret = sigaction(SIGUSR1, &sa_user, NULL);
if(ret == -1) {printf("dderror: signal usr1 not established\n"); exit(1);}
//
//create instances of controllers
//
uss_comm_controller cc;
uss_registration_controller rc(&cc);
#if(USS_DAEMON_DEBUG == 1)
printf("registration controller | started | new thread listening for registrations \n");
printf("---------------------------------------------------------------------------\n");
printf("communication controller | started \n");
printf("---------------------------------------------------------------------------\n");
#endif
//create a thread that listens for incoming registrations
//
pthread_t reg_thread;
pthread_create(®_thread, NULL, start_handle_incoming_registrations, &rc);
//
//create instance of scheduling class
//
uss_scheduler sched(&cc, &rc);
uss_device_controller dc(&sched);
#if(USS_DAEMON_DEBUG == 1)
printf("communication controller | started \n");
printf("---------------------------------------------------------------------------\n");
printf("device controller | started | %i accelerators given to scheduler\n", dc.get_nof_accelerators());
printf("---------------------------------------------------------------------------\n");
#endif
#if(BENCHMARK_LOAD_BALANCER == 1)
struct timeval lbtstart, lbtcurrent;
gettimeofday(&lbtstart, NULL);
#endif
//
//MAIN LOOP
//
/*invocation of the scheduler is controlled by a user defined
*time interval
*-> this main loop does actions and then waits for this time
*/
struct timespec request, remain;
request = user_param_sched_interval;
int s, handle, accepted;
while(!daemon_exit)
{
//
//check if we have been wakend up by new registration or unreg
//
//printf(" rc.nof_new_regs() = %i\n", rc.nof_new_regs());
while(rc.get_nof_new_regs() > 0)
{
#if(BENCHMARK_DAEMON_CPUTIME == 1)
if(benchmark_daemon_cputime_state == 0)
{
benchmark_daemon_cputime_state = 1;
//start (real) time
if(clock_gettime(CLOCK_MONOTONIC, &time_start) != 0) {dexit("clock_gettime failed");}
//start cputime for whole process
if(clock_getcpuclockid(getpid(), &selected_clockid) != 0) {dexit("clock_getcpuclockid failed");}
if(clock_gettime(selected_clockid, &process_cputime_start) != 0) {dexit("clock_gettime failed");}
//start cputime for daemon thread only
if(pthread_getcpuclockid(pthread_self(), &selected_clockid) != 0) {dexit("clock_getcpuclockid failed");}
if(clock_gettime(selected_clockid, &thread_cputime_start) != 0) {dexit("clock_gettime failed");}
}
#endif
//fetch any one new handle
handle = rc.get_new_reg();
#if(USS_DAEMON_DEBUG == 1)
printf("[main thread] now working on new_reg with handle = %i\n", handle);
#endif
//the status of add_job() tells us if sched accepted this new reg
accepted = sched.add_job(handle, rc.get_msai(handle));
//work on cond variable of this handle's entry in reg_table so that T can terminate
rc.finish_registration(handle, accepted);
//printf("[main thread] leave new_reg\n");
}
//
//do default periodic tick
//
sched.periodic_tick();
#if(BENCHMARK_LOAD_BALANCER == 1)
long s, m;
gettimeofday(&lbtcurrent, NULL);
s = lbtcurrent.tv_sec - lbtstart.tv_sec;
if(lbtcurrent.tv_usec > lbtstart.tv_usec)
m = lbtcurrent.tv_usec - lbtstart.tv_usec;
else
m = lbtcurrent.tv_usec;
printf("%ld.%ld", s, m );
uss_rq_matrix_iterator e = sched.rq_matrix.begin();
for(; e != sched.rq_matrix.end(); e++)
{
printf(" %i ",(*e).second.nof_all_handles);
}
printf("\n");
#endif
//
//do load balance every Xth time
//
//sched.load_balancing();
//
//print complete status every second
//
#if(USS_DAEMON_DEBUG == 1)
display_counter++;
if(display_counter == 25)
{print_complete_status(&rc, &sched); display_counter = 0;}
#endif
//
//erase old handles
//
sched.remove_finished_jobs();
#if(BENCHMARK_DAEMON_CPUTIME == 1)
if(benchmark_daemon_cputime_state == 1 && sched.tokill_list.size() == 0 && sched.se_table.size() == 0)
{
//start (real) time
if(clock_gettime(CLOCK_MONOTONIC, &time_stop) != 0) {dexit("clock_gettime failed");}
//stop time for whole process
if(clock_getcpuclockid(getpid(), &selected_clockid) != 0) {dexit("clock_getcpuclockid failed");}
if(clock_gettime(selected_clockid, &process_cputime_stop) != 0) {dexit("clock_gettime failed");}
//stop time for daemon thread only
if(pthread_getcpuclockid(pthread_self(), &selected_clockid) != 0) {dexit("clock_getcpuclockid failed");}
if(clock_gettime(selected_clockid, &thread_cputime_stop) != 0) {dexit("clock_gettime failed");}
//final and sole output of daemon in this mode should be [nano seconds]
uint64_t time_stop_ns = time_stop.tv_sec*(1000000000) + time_stop.tv_nsec;
uint64_t time_start_ns = time_start.tv_sec*(1000000000) + time_start.tv_nsec;
uint64_t process_cputime_stop_ns = process_cputime_stop.tv_sec*(1000000000) + process_cputime_stop.tv_nsec;
uint64_t process_cputime_start_ns = process_cputime_start.tv_sec*(1000000000) + process_cputime_start.tv_nsec;
uint64_t thread_cputime_stop_ns = thread_cputime_stop.tv_sec*(1000000000) + thread_cputime_stop.tv_nsec;
uint64_t thread_cputime_start_ns = thread_cputime_start.tv_sec*(1000000000) + thread_cputime_start.tv_nsec;
printf("%lld %lld %lld",
(long long int)(time_stop_ns - time_start_ns),
(long long int)(process_cputime_stop_ns - process_cputime_start_ns),
(long long int)(thread_cputime_stop_ns - thread_cputime_start_ns));
exit(0);
}
#endif
//
//sleep for time interval
//
/*this controls the periodic tick and thus equals the interval
*the scheduler can update itself or perform operations
*
*nanosleep can be interrupted by a new registration and will sleep
*for another full interval
*(note that there are few interrupts that really receive the main thread)
*
*(!) although nanosleep allows nanosecond precision
* precision depends on system-scheduler and clock previsions
*/
s = nanosleep(&request, &remain);
if(s == -1 && errno != EINTR) {printf("dderror: starting nanosleep\n");}
}//end main loop
exit(0);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
355
]
]
] |
b78cc2feabebce257cbb1496cefb189086cb6dbd | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Source/System/State/NVidia/Cgfx/OSGCgfxRenderPassChunk.h | 4d96d56a6c7fcfd7961f0bb72ce49d9c02b4557c | [] | no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,957 | h | /*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: [email protected], [email protected], [email protected] *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
#ifndef _OSGCGFXRENDERPASSCHUNK_H_
#define _OSGCGFXRENDERPASSCHUNK_H_
#ifdef __sgi
#pragma once
#endif
#include "OSGCgfxRenderPassChunkBase.h"
#include <Cg/cg.h>
#include <Cg/cgGL.h>
OSG_BEGIN_NAMESPACE
/*! \brief CgfxRenderPassChunk class. See \ref
PageStateCgfxRenderPassChunk for a description.
*/
class OSG_STATE_DLLMAPPING CgfxRenderPassChunk : public CgfxRenderPassChunkBase
{
protected:
/*========================== PUBLIC =================================*/
public:
typedef CgfxRenderPassChunkBase Inherited;
typedef CgfxRenderPassChunk Self;
/*---------------------------------------------------------------------*/
/*! \name Chunk Class Access */
/*! \{ */
virtual const StateChunkClass *getClass(void) const;
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Static Chunk Class Access */
/*! \{ */
static UInt32 getStaticClassId(void);
static const StateChunkClass * getStaticClass (void);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Sync */
/*! \{ */
virtual void changed(ConstFieldMaskArg whichField,
UInt32 origin,
BitVector details );
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Output */
/*! \{ */
virtual void dump( UInt32 uiIndent = 0,
const BitVector bvFlags = 0) const;
/*! \} */
virtual void activate (DrawEnv *pEnv,
UInt32 index = 0);
virtual void changeFrom (DrawEnv *pEnv,
StateChunk *pOld,
UInt32 index = 0);
virtual void deactivate (DrawEnv *pEnv,
UInt32 index = 0);
void setCGTechnique(CGtechnique tech);
const CGtechnique getCGTechnique(void);
void setCGPass(CGpass renderPass);
void setCGEffect(CGeffect *effect);
const CGpass getCGPass(void);
std::string getPassName(void);
void setPassName(std::string name);
void setSemanticBitVector(OSG::BitVector bitVec);
/*========================= PROTECTED ===============================*/
protected:
// Variables should all be in CgfxRenderPassChunkBase.
/*---------------------------------------------------------------------*/
/*! \name Constructors */
/*! \{ */
CgfxRenderPassChunk(void);
CgfxRenderPassChunk(const CgfxRenderPassChunk &source);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Destructors */
/*! \{ */
virtual ~CgfxRenderPassChunk(void);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Init */
/*! \{ */
static void initMethod(InitPhase ePhase);
CGtechnique _mTechnique;
CGpass _mPass;
CGeffect *_mEffect;
// only one pass per chunk. To ensure that the proper pass is being grabbed from the
// technique, each pass must have a unique name (naming is taken care of in CgfxMaterial)
std::string _mName;
// bit vector used to determine which matricies to update (modelview, etc...)
OSG::BitVector _mSemanticBV;
void updateGLMatricies(DrawEnv *pEnv);
// These must be the same as the semantic effect params in cgfxmaterial!
enum SemanticEffectParameters{ CGFX_MODELVIEWPROJECTION_PARAMETER = 1,
CGFX_MODELVIEW_PARAMETER = 2,
CGFX_MODELINVERSETRANSPOSE_PARAMETER = 3,
CGFX_MODELTRANSPOSE_PARAMETER = 4,
CGFX_WORLDVIEWPROJECTION_PARAMETER = 5,
CGFX_WORLD_PARAMETER = 6,
CGFX_WORLDINVERSETRANSPOSE_PARAMETER = 7,
CGFX_VIEWINVERSE_PARAMETER = 8,
CGFX_VIEW_PARAMETER = 9,
CGFX_VIEWTRANSPOSE_PARAMETER = 10,
CGFX_VIEWINVERSETRANSPOSE_PARAMETER = 11 };
/*! \} */
/*========================== PRIVATE ================================*/
private:
friend class FieldContainer;
friend class CgfxRenderPassChunkBase;
// prohibit default functions (move to 'public' if you need one)
void operator =(const CgfxRenderPassChunk &source);
// class. Used for indexing in State
static StateChunkClass _class;
};
typedef CgfxRenderPassChunk *CgfxRenderPassChunkP;
OSG_END_NAMESPACE
#include "OSGCgfxRenderPassChunkBase.inl"
#include "OSGCgfxRenderPassChunk.inl"
#endif /* _OSGCGFXRENDERPASSCHUNK_H_ */
| [
"[email protected]"
] | [
[
[
1,
198
]
]
] |
3cbc49b099c828e72a59167caacff090986b64a7 | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /Graph/Graph3/MainFrm.cpp | 96aea57e5ff3eb2d64f6559abb0e1ce66db4efd1 | [] | no_license | cloudlander/legacy | a073013c69e399744de09d649aaac012e17da325 | 89acf51531165a29b35e36f360220eeca3b0c1f6 | refs/heads/master | 2022-04-22T14:55:37.354762 | 2009-04-11T13:51:56 | 2009-04-11T13:51:56 | 256,939,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "Graph3.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_CREATE()
ON_WM_SETFOCUS()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
// create a view to occupy the client area of the frame
if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
{
TRACE0("Failed to create view window\n");
return -1;
}
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
cs.lpszClass = AfxRegisterWndClass(0);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
void CMainFrame::OnSetFocus(CWnd* pOldWnd)
{
// forward focus to the view window
m_wndView.SetFocus();
}
BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
// let the view have first crack at the command
if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
return TRUE;
// otherwise, do default handling
return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
| [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
] | [
[
[
1,
102
]
]
] |
cbed55667e3014bd8e4292548f8a74a954139314 | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXBitmapButton.h | cfe63fd986c724c32f70726bbfc9e82f2abff5c2 | [] | no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 36,781 | h | // ==========================================================================
// Class Specification : COXBitmapButton
// ==========================================================================
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
// Properties:
// NO Abstract class (does not have any objects)
// YES Derived from CButton
// YES Is a Cwnd.
// YES Two stage creation (constructor & Create())
// YES Has a message map
// YES Needs a resource (template)
// NO Persistent objects (saveable on disk)
// NO Uses exceptions
// //////////////////////////////////////////////////////////////////////////
// Desciption :
// This class implements an owner drawn button for which you only have to
// provide one bitmap or icon. The other bitmaps and icons are computed dynamically
// (pressed, inactive (grayed), disabled etc).
// To use it just link your button (BS_OWNERDRAW) with an COXBitmapButton object
// and call the function LoadBitmap() to supply a bitmap or icon from resource.
// A special look ('track look') is provided as well. This looks like the
// buttons in the toolbar of the MS Internet Explorer 3.0.
// When the mouse is not over the button, the button looks flat and the
// image is shown inactively (in gray scale).
// When the user moves the mouse over the button it shows a normal 3D button
// and the image has its original colors.
// A disabled button, always has a flat, disabled look (even when the mouse is over
// the button)
// A second special look ('hyper look') is provided as well.
// In this mode the original image is shown always. So this look does not have
// a button look : just a (transparant) image.
// By default it uses a cursor in the form of a hand.
// It also uses the pseudo disable mode. This means that the button
// is not actually disabled, but the user cannot click it.
// This gives the possibility to use another cursor when the button is
// (pseudo) disabled : a hand with a stop sign.
// You can add text to the image and set its alignment
// Support for tooltips is also available. The text can be get and set by using
// GetText(), SetText(), GetToolTipText(), SetToolTipText()
// Remark:
// The buttons used with this class must have the BS_OWNERDRAW style.
// The BS_BITMAP style is not supported,
// Windows version previous than 4.0 do not support the disabled look.
// This class has been reworked so that it works with 256-color bitmaps
// (not 256-color icons)
// The images are internally stored as DDB (device dependant bitmaps)
// together with the palette (of the original resource)
// The class uses the one palette when drawing itself.
// To assure nice cooperation with other controls or graphic elements
// you should use one palette for all items within a dialog, formview etc.
// This file uses resources. (E.g. Bitmap IDC_OX_HAND_CURSOR)
// The reserved ID ranges are : 23460 -> 23479 and 53460 -> 53479
/////////////////////////////////////////////////////////////////////////////
/*
Next new features were added to the control:
1) You can set vertical and horizontal alignment of text and image within control
using next functions:
void SetHorizontalAlignment(DWORD nAlignment = BS_CENTER);
// --- In : nAlignment : The horizontal alignment of the image
// (BS_LEFT, BS_CENTER or BS_RIGHT)
void SetVerticalAlignment(DWORD nAlignment = BS_VCENTER);
// --- In : nAlignment : The vertical alignment of the image
// (BS_TOP, BS_VCENTER or BS_BOTTOM)
Vertical and horizontal alignment can be retrieved using next functions:
DWORD GetHorizontalAlignment() const;
// --- Returns: The horizontal alignment of the image (BS_LEFT, BS_CENTER or BS_RIGHT)
DWORD GetVerticalAlignment() const;
// --- Returns: The vertical alignment of the image (BS_TOP, BS_VCENTER or BS_BOTTOM)
Below table show you the positions that text and image take depending on vertical
and horizontal alignment:
BS_LEFT|BS_TOP BS_CENTER|BS_TOP BS_RIGHT|BS_TOP
--------- --------- ---------
|Image | | Image | | Image|
| | | | | |
|Text | | Text | | Text|
--------- --------- ---------
BS_LEFT|BS_VCENTER BS_CENTER|BS_VCENTER BS_RIGHT|BS_VCENTER
------------ ------------ ------------
| | | | | |
|Text Image| |Image Text| |Image Text|
| | | | | |
------------ ------------ ------------
BS_LEFT|BS_BOTTOM BS_CENTER|BS_BOTTOM BS_RIGHT|BS_BOTTOM
--------- --------- ---------
|Text | | Text | | Text|
| | | | | |
|Image | | Image | | Image|
--------- --------- ---------
2) Now we support BS_MULTILINE style to display any text associated with the control
3) There were added new extended styles to COXBitmapButton control:
OXBB_EX_DROPDOWN
OXBB_EX_DROPDOWNRIGHT
OXBB_EX_DROPDOWNNOARROW
OXBB_EX_TOGGLE
OXBB_EX_TOGGLE3STATE
New styles can be set/retrieved using next functions:
void SetStyleEx(DWORD dwStyleEx);
// --- In : dwStyleEx - extended COXBitmapButton style to set
DWORD GetStyleEx();
// --- Returns: extended COXBitmapButton style
Next helper functions let you define whether different extended styles were applied
to a button or not:
BOOL IsDropDownButton();
// --- Returns: TRUE if OXBB_EX_DROPDOWN extended style is set
BOOL IsToggleButton();
// --- Returns: TRUE if OXBB_EX_TOGGLE extended style is set
Below you will find full description of these new extended styles:
1. Toggle buttons. You can make any COXBitmapButton to be toggle by calling
next function:
SetStyleEx(OXBB_EX_TOGGLE);
Such button can be in two state: unchecked & checked. To switch between these state
just left click on control or press space button on a keyboard while control has focus.
In conjunction with OXBB_EX_TOGGLE you can use OXBB_EX_TOGGLE3STATE extended
style. If you set extended style calling:
SetStyleEx(OXBB_EX_TOGGLE|OXBB_EX_TOGGLE3STATE);
then button can be set in indeterminate state. If button is in checked state and user
left click on control or press space button on a keyboard while control has focus then
indeterminate state will be set.
To implement Toggle buttons new extended states were introduced:
OXBB_STATE_CHECKED
OXBB_STATE_INDETERMINATE
Button's extendended state can be set/retrieved using next functions:
void SetStateEx(DWORD dwStateEx);
// --- In : dwStateEx - extended COXBitmapButton state to set
DWORD GetStateEx();
// --- Returns: extended COXBitmapButton state
Next helper functions let you define whether a button is in any of extended state
or not:
BOOL IsChecked();
// --- Returns: TRUE if button is toggle and has OXBB_STATE_CHECKED state set
BOOL IsIndeterminate();
// --- Returns: TRUE if button is toggle and has OXBB_STATE_INDETERMINATE state set
When Toggle button changes its state OXBBN_TOGGLE notification is sent to the
control's parent window. If you handle this notification you have to set return value
to non-zero if you don't want control to call next virtual function:
virtual void OnToggle();
that is defined specifically to be overwritten in derived class. Default implementation
of this function does nothing.
Next function was introduced to be specifically used in DoDataExchange function
of any Dialog or FormView based application:
void AFXAPI DDX_Toggle(CDataExchange *pDX, int nIDC, int& value);
Parameter value can be one of the next:
0 - unchecked
1 - checked
2 - indeterminate
2. Dropdown buttons. Such buttons can be used to display different picker controls
or menus (COXColorPickerButton is an example of such control). You can make any
COXBitmapButton to be dropdown by calling next function:
SetStyleEx(OXBB_EX_DROPDOWN);
We draw dropdown arrow on the right side of the button and by default it is down
oriented. This dropdown button can be right oriented if you call next function:
SetStyleEx(OXBB_EX_DROPDOWN|OXBB_EX_DROPDOWNRIGHT);
Or if you prefer you can set dropdown button that doesn't draw dropdown arrow calling:
SetStyleEx(OXBB_EX_DROPDOWN|OXBB_EX_DROPDOWNNOARROW);
In derived classes you can provide your own dropdown arrow drawing routine by
overwriting next virtual function:
virtual void DrawDropDownArrow(CDC* pDC, UINT nState, CRect arrowRect);
// nState is itemState element of LPDRAWITEMSTRUCT that is used in DrawItem
// function
When dropdown event happens (in result of left clicking or pressing space button)
OXBBN_DROPDOWN notification is sent to the control's parent window. If you handle this
notification you have to set return value to non-zero if you don't want control to
call next virtual function:
virtual void OnDropDown();
that is defined specifically to be overwritten in derived class (we overwrite this
function in COXColorPickerButton class). Default implementation of this function
does nothing.
4) There were introduced next function the primary purpose of which is to simplify
process of creating derived COXBitmapButton classes that provide additional
drawing routines:
virtual CSize GetReservedSpace();
// --- In :
// --- Out :
// --- Returns: size of reserved space (from the bottom and right) that shouldn't be
// filled withh button's image or text
// --- Effect: helper function
If you derive your own class and overwrite this function then don't forget to call
parent implementation of this function before seting any values, e.g.:
CSize CMyBitmapButton::GetReservedSpace()
{
CSize sizeReserved=COXBitmapButton::GetReservedSpace();
.........................
return sizeReserved;
}
*/
/////////////////////////////////////////////////////////////////////////////
#ifndef __OXBITMAPBUTTON_H__
#define __OXBITMAPBUTTON_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
#include "OXMainRes.h"
#include "OXToolTipCtrl.h"
// The maximum number of images we have to build per bitmap button
#define OX_MAX_IMAGE_COUNT 5
// special extended style
#define OXBB_EX_DROPDOWN 0x00000001
#define OXBB_EX_TOGGLE 0x00000002
#define OXBB_EX_DROPDOWNRIGHT 0x00010000
#define OXBB_EX_DROPDOWNNOARROW 0x00020000
#define OXBB_EX_TOGGLE3STATE 0x00040000
// special state
#define OXBB_STATE_CHECKED 0x00000001
#define OXBB_STATE_INDETERMINATE 0x00000002
// tooltip ID
#define OXBB_TOOLTIP_ID 1000
BOOL CALLBACK CallbackDrawState(HDC hdc, LPARAM lData, WPARAM wData, int cx, int cy);
BOOL CALLBACK CallbackGrayString(HDC hdc, LPARAM lData, int nCount);
// Next function was introduced to be specifically used in DoDataExchange function
// of any Dialog or FormView based application for Toogle buttons. Parameter value
// can be one of the next:
// 0 - unchecked
// 1 - checked
// 2 - indeterminate
OX_API_DECL void AFXAPI DDX_Toggle(CDataExchange *pDX, int nIDC, int& value);
class OX_CLASS_DECL COXBitmapButton : public CButton
{
DECLARE_DYNAMIC(COXBitmapButton);
// Data members -------------------------------------------------------------
public:
protected:
// control to play AVI file if any was loaded
CAnimateCtrl m_animateCtrl;
// TRUE if currently playing AVI file
BOOL m_bPlaying;
CImageList m_imageList;
CPalette m_palette;
COLORREF m_textColor;
CFont m_textFont;
COXToolTipCtrl m_toolTip;
BOOL m_bTrackLook;
BOOL m_bMouseOverButton;
BOOL m_bMouseDown;
BOOL m_bAutoDestroyMenu;
BOOL m_bHyperLook;
CImageList m_backgroundImage;
BOOL m_bBackgroundGrabbed;
UINT m_nDefaultCursorID;
HCURSOR m_hDefaultCursor;
UINT m_nDisabledCursorID;
HCURSOR m_hDisabledCursor;
BOOL m_bPseudoDisableMode;
BOOL m_bEnabled;
BOOL m_bHasTabStop;
BOOL m_bDrawDropdownSeparator;
CPoint m_ptImageOffset;
CPoint m_ptTextOffset;
CPoint m_ptOuterFocusOffset;
CPoint m_ptInnerFocusOffset;
CSize m_hyperFocusSize;
CPoint m_ptDownOffset;
CPoint m_ptCheckedOffset;
CPoint m_ptHyperOffset;
CPoint m_ptArrowOffset;
static const int m_nNormalImageIndex;
static const int m_nInactiveImageIndex;
static const int m_nDisabledImageIndex;
static COLORREF m_defaultButtonColor;
DWORD m_dwStyleEx;
int m_nDropDownArrowWidth;
DWORD m_dwStateEx;
private:
// Member functions ---------------------------------------------------------
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect: Constructs the object
COXBitmapButton();
// --- In : lpszBitmapResource - bitmap resource string
// nIDBitmapResource - bitmap resource ID
// bResize - whether to resize the button to
// fit the size of bitmap and text
// crMask - mask color to use for the bitmap
// (this color of the bitmap will be
// shown transparently)
// --- Out :
// --- Returns: TRUE if bitmap was loaded successfully
// --- Effect: loads the bitmap from resource
BOOL LoadBitmap(LPCTSTR lpszBitmapResource, BOOL bResize = TRUE,
COLORREF crMask = CLR_NONE);
inline BOOL LoadBitmap(UINT nIDBitmapResource, BOOL bResize = TRUE,
COLORREF crMask = CLR_NONE) {
return LoadBitmap(MAKEINTRESOURCE(nIDBitmapResource),bResize,crMask);
}
// --- In : lpszBitmapResource - bitmap resource string
// nIDBitmapResource - bitmap resource ID
// crMask - mask color to use for the bitmap
// (this color of the bitmap will be
// shown transparently)
// --- Out :
// --- Returns: TRUE if bitmap was loaded successfully
// --- Effect: loads the bitmap from resource
BOOL LoadInactiveBitmap(LPCTSTR lpszBitmapResource);
inline BOOL LoadInactiveBitmap(UINT nIDBitmapResource) {
return LoadInactiveBitmap(MAKEINTRESOURCE(nIDBitmapResource));
}
// --- In : lpszBitmapResource - bitmap resource string
// nIDBitmapResource - bitmap resource ID
// crMask - mask color to use for the bitmap
// (this color of the bitmap will be
// shown transparently)
// --- Out :
// --- Returns: TRUE if bitmap was loaded successfully
// --- Effect: loads the bitmap from resource
BOOL LoadDisabledBitmap(LPCTSTR lpszBitmapResource);
inline BOOL LoadDisabledBitmap(UINT nIDBitmapResource) {
return LoadDisabledBitmap(MAKEINTRESOURCE(nIDBitmapResource));
}
// --- In : lpszIconResource - icon resource string
// nIDIconResource - icon resource ID
// bResize - whether to resize the button to
// fit the size of bitmap and text
// nWidth - width of the icon
// nHeight - height of the icon
// --- Out :
// --- Returns: TRUE if icon was loaded successfully
// --- Effect: loads the icon from resource
BOOL LoadIcon(LPCTSTR lpszIconResource, BOOL bResize = TRUE,
UINT nWidth = 0, UINT nHeight = 0);
inline BOOL LoadIcon(UINT nIDIconResource, BOOL bResize = TRUE,
UINT nWidth = 0, UINT nHeight = 0) {
return LoadIcon(MAKEINTRESOURCE(nIDIconResource),bResize,nWidth,nHeight);
}
// --- In : lpszIconResource - icon resource string
// nIDIconResource - icon resource ID
// nWidth - width of the icon
// nHeight - height of the icon
// --- Out :
// --- Returns: TRUE if icon was loaded successfully
// --- Effect: loads the icon from resource
BOOL LoadInactiveIcon(LPCTSTR lpszIconResource, UINT nWidth = 0, UINT nHeight = 0);
inline BOOL LoadInactiveIcon(UINT nIDIconResource,UINT nWidth = 0, UINT nHeight = 0) {
return LoadInactiveIcon(MAKEINTRESOURCE(nIDIconResource),nWidth,nHeight);
}
// --- In : lpszIconResource - icon resource string
// nIDIconResource - icon resource ID
// nWidth - width of the icon
// nHeight - height of the icon
// --- Out :
// --- Returns: TRUE if icon was loaded successfully
// --- Effect: loads the icon from resource
BOOL LoadDisabledIcon(LPCTSTR lpszIconResource, UINT nWidth = 0, UINT nHeight = 0);
inline BOOL LoadDisabledIcon(UINT nIDIconResource, UINT nWidth = 0, UINT nHeight = 0) {
return LoadDisabledIcon(MAKEINTRESOURCE(nIDIconResource),nWidth,nHeight);
}
// --- In : nIDAviResource - AVI resource ID
// lpszFileName - the name of the AVI file
// bResize - whether to resize the button to
// fit the size of bitmap and text
// --- Out :
// --- Returns: TRUE if AVI was loaded successfully
// --- Remarks: you have to set either ID or FileName, if both are not NULL
// then we use lpszFileName as valid parameter
//
// Animation controls can play only simple AVI clips. Specifically,
// the clips to be played by an animation control must meet the following
// requirements:
// - There must be exactly one video stream and it must have at least
// one frame.
// - There can be at most two streams in the file (typically the other
// stream, if present, is an audio stream, although the animation
// control ignores audio information).
// - The clip must either be uncompressed or compressed with RLE8
// compression.
// - No palette changes are allowed in the video stream.
BOOL LoadAvi(UINT nIDAviResource, LPCTSTR lpszFileName = NULL, BOOL bResize = TRUE);
// --- In : bResize - whether to resize the button to
// fit the size of bitmap and text
// --- Out :
// --- Returns: TRUE if successful or FALSE otherwise
// --- Effect: remove any images (bitmaps, icons or avi) previously set to control
BOOL RemoveImage(BOOL bResize = TRUE);
////////////////////////////
// --- In :
// --- Out :
// --- Returns: The palette of the bitmap button
// This object is valid after a successful LoadBitmap or LoadIcon
// --- Effect:
CPalette* GetPalette();
// --- In :
// --- Out :
// --- Returns:
// --- Effect: Sizes the button to fit its contents (image and text)
virtual void SizeToContent();
// --- In :
// --- Out :
// --- Returns: Whether the track look mode is enabled
// --- Effect:
BOOL GetTrackLook() const;
// --- In : bTrackLook : Whether enable or disable the track look mode
// --- Out :
// --- Returns: Whether is was successful or not
// --- Effect:
BOOL SetTrackLook(BOOL bTrackLook = TRUE);
// --- In : nAlignment : The horizontal alignment of the image and text
// (BS_LEFT, BS_CENTER or BS_RIGHT)
// --- Out :
// --- Returns:
// --- Effect:
void SetHorizontalAlignment(DWORD nAlignment = BS_CENTER);
// --- In :
// --- Out :
// --- Returns: The horizontal alignment of the image and text
// (BS_LEFT, BS_CENTER or BS_RIGHT)
// --- Effect:
DWORD GetHorizontalAlignment() const;
// --- In : nAlignment : The vertical alignment of the image and text
// (BS_TOP, BS_VCENTER or BS_BOTTOM)
// --- Out :
// --- Returns:
// --- Effect:
void SetVerticalAlignment(DWORD nAlignment = BS_VCENTER);
// --- In :
// --- Out :
// --- Returns: The vertical alignment of the image and text
// (BS_TOP, BS_VCENTER or BS_BOTTOM)
// --- Effect:
DWORD GetVerticalAlignment() const;
// --- In :
// --- Out :
// --- Returns: The current text color
// --- Effect:
COLORREF GetTextColor() const;
// --- In : textColor : The new text color
// --- Out :
// --- Returns:
// --- Effect:
void SetTextColor(COLORREF textColor);
// --- In :
// --- Out :
// --- Returns: The current text font
// --- Effect:
CFont* GetTextFont();
// --- In : pTextFont : The new text font
// --- Out :
// --- Returns:
// --- Effect: A copy of the font will be made and stored internally
void SetTextFont(CFont* pTextFont);
// --- In :
// --- Out :
// --- Returns: The text of this button
// (window text upto but not including the first '\n")
// --- Effect:
CString GetText() const;
// --- In : pszText : The new button text
// --- Out :
// --- Returns:
// --- Effect: Sets the new text of this button
// (window text upto but not including the first '\n")
void SetText(LPCTSTR pszText);
// --- In :
// --- Out :
// --- Returns: The tool tip text of this button
// (window text starting from but not including the first '\n")
// --- Effect:
CString GetToolTipText() const;
// --- In : pszToolTipText : The new tool tip text
// --- Out :
// --- Returns:
// --- Effect: Sets the new text of the tool tip
// (window text starting from but not including the first '\n")
void SetToolTipText(LPCTSTR pszToolTipText);
// --- In :
// --- Out :
// --- Returns: Whether tooltip is enabled for this window
// --- Effect:
BOOL GetToolTip() const;
// --- In :
// --- Out :
// --- Returns: Whether the function was successful
// --- Effect: Enable tooltip for this window
BOOL SetToolTip(BOOL bEnable = TRUE);
// --- In :
// --- Out :
// --- Returns: The size of button in pixels when it fits its entire contents
// --- Effect:
virtual CSize GetFitButtonSize();
// --- In :
// --- Out :
// --- Returns: The present size of the button in pixels
// --- Effect:
CSize GetButtonSize() const;
// --- In :
// --- Out :
// --- Returns: The present size of the image in pixels
// --- Effect:
CSize GetImageSize() const;
// --- In :
// --- Out :
// --- Returns: The size of the text in pixels
// --- Effect:
CSize GetTextSize(BOOL bCompact=FALSE);
// --- In :
// --- Out :
// --- Returns: Whether the hyper look mode is enabled
// --- Effect:
BOOL GetHyperLook() const;
// --- In : bHyperLook : Whether enable or disable the hyper look mode
// --- Out :
// --- Returns: Whether is was successful or not
// --- Effect:
BOOL SetHyperLook(BOOL bHyperLook = TRUE);
// --- In :
// --- Out :
// --- Returns: Whether is was successful or not
// --- Effect: This functions deletes an old copy of the button background
// and grabs a new one.
// This function can be useful when you change the background
// during the lifetime of a bitmap button
BOOL RegrabBackground();
// --- In : nCursorID : The new cursor ID to use (0 resets to default cursor)
// --- Out :
// --- Returns: Whether the function was successful (the resource was found)
// --- Effect: Sets the default cursor of this window
// Possible values are : IDC_OX_HAND_CURSOR and IDC_OX_NO_HAND_CURSOR
BOOL SetDefaultCursor(UINT nCursorID = 0);
// --- In :
// --- Out :
// --- Returns: The ID of the current default cursor (0 when none is set)
// --- Effect:
UINT GetDefaultCursor() const;
// --- In : nCursorID : The new cursor ID to use (0 resets to default cursor)
// --- Out :
// --- Returns: Whether the function was successful (the resource was found)
// --- Effect: Sets the default cursor of this window
// Possible values are : IDC_OX_HAND_CURSOR and IDC_OX_NO_HAND_CURSOR
// The pseudo-disable mode must be activated before the
// disabled cursor will be shown
BOOL SetDisabledCursor(UINT nCursorID = 0);
// --- In :
// --- Out :
// --- Returns: The ID of the current default cursor (0 when none is set)
// --- Effect:
UINT GetDisabledCursor() const;
// --- In :
// --- Out :
// --- Returns: Whether the pseudo-disable mode is active
// --- Effect:
BOOL GetPseudoDisableMode() const;
// --- In : bPseudoDisableMode : Whether use pseudo-disable mode or not
// --- Out :
// --- Returns: Whether is was successful or not
// --- Effect: In pseudo disable mode the control is visually disabled
// but not really disabled according to Windows.
// This provides the opportunity to receive messages
// even when the window is (psudo)disabled.
// This mode must be set for the disabled cursor to work.
BOOL SetPseudoDisableMode(BOOL bPseudoDisableMode = TRUE);
// --- In :
// --- Out :
// --- Returns: Whether this window is enabled or not
// --- Effect: This function also works when in pseudo-disable mode
BOOL IsWindowEnabled() const;
// --- In : bEnable : Whether to enable (TRUE) or disable (FALSE) this window
// --- Out :
// --- Returns: The old state before the requested state was set
// --- Effect: This function also works when in pseudo-disable mode
BOOL EnableWindow(BOOL bEnable = TRUE);
// --- In :
// --- Out :
// --- Returns: Whether the background was grabbed again
// --- Effect: This functions grabs the image that is currently painted
// on the rect used by the bitmap button
// When this function is called during OnEraseBkgnd() it will
// grab the background of the button
BOOL AdjustBackground();
// --- In : dwStyleEx - extended COXBitmapButton style to set
// bRedraw - flag that specifies whether the control should
// be redrawn or not
// --- Out :
// --- Returns:
// --- Effect: This functions sets extended style of COXBitmapButton control.
void SetStyleEx(DWORD dwStyleEx, BOOL bRedraw=TRUE);
// --- In :
// --- Out :
// --- Returns: extended COXBitmapButton style
// --- Effect:
DWORD GetStyleEx();
// --- In :
// --- Out :
// --- Returns: TRUE if OXBB_EX_DROPDOWN extended style is set
// --- Effect: helper function
BOOL IsDropDownButton();
// --- In :
// --- Out :
// --- Returns: TRUE if OXBB_EX_TOGGLE extended style is set
// --- Effect: helper function
BOOL IsToggleButton();
// --- In : dwStateEx - extended COXBitmapButton state to set
// bRedraw - flag that specifies whether the control should
// be redrawn or not
// --- Out :
// --- Returns:
// --- Effect: This functions sets extended state of COXBitmapButton control.
void SetStateEx(DWORD dwStateEx, BOOL bRedraw=TRUE);
// --- In :
// --- Out :
// --- Returns: extended COXBitmapButton state
// --- Effect:
DWORD GetStateEx();
// --- In :
// --- Out :
// --- Returns: TRUE if button is toggle and has OXBB_STATE_CHECKED state set
// --- Effect: helper function
BOOL IsChecked();
// --- In :
// --- Out :
// --- Returns: TRUE if button is toggle and has OXBB_STATE_INDETERMINATE state set
// --- Effect: helper function
BOOL IsIndeterminate();
// --- In :
// --- Out :
// --- Returns: size of reserved space (from the bottom and right) that shouldn't be
// filled with button's image or text
// --- Effect: helper function
virtual CSize GetReservedSpace();
#ifdef _DEBUG
// --- In :
// --- Out :
// --- Returns:
// --- Effect: AssertValid performs a validity check on this object
// by checking its internal state.
// In the Debug version of the library, AssertValid may assert and
// thus terminate the program.
virtual void AssertValid() const;
// --- In : dc : The diagnostic dump context for dumping, usually afxDump.
// --- Out :
// --- Returns:
// --- Effect: Dumps the contents of the object to a CDumpContext object.
// It provides diagnostic services for yourself and
// other users of your class.
// Note The Dump function does not print a newline character
// at the end of its output.
virtual void Dump(CDumpContext& dc) const;
#endif
// --- Returns: image offset from the control border
// --- Effect:
inline CPoint GetImageOffset() { return m_ptImageOffset; }
// --- In : image offset from the control border
// --- Effect: set image offset
inline void SetImageOffset(CPoint ptImageOffset) { m_ptImageOffset=ptImageOffset; }
// --- Returns: text offset from the control border
// --- Effect:
inline CPoint GetTextOffset() { return m_ptTextOffset; }
// --- In : text offset from the control border
// --- Effect: set text offset
inline void SetTextOffset(CPoint ptTextOffset) { m_ptTextOffset=ptTextOffset; }
// --- Returns: outer focus rectangle offset from the control border
// --- Effect:
inline CPoint GetOuterFocusOffset() { return m_ptOuterFocusOffset; }
// --- In : outer focus rectangle offset from the control border
// --- Effect: set outer focus rectangle offset
inline void SetOuterFocusOffset(CPoint ptOuterFocusOffset) {
m_ptOuterFocusOffset=ptOuterFocusOffset; }
// --- Returns: inner focus rectangle offset from the control border
// --- Effect:
inline CPoint GetInnerFocusOffset() { return m_ptInnerFocusOffset; }
// --- In : inner focus rectangle offset from the control border
// --- Effect: set inner focus rectangle offset
inline void SetInnerFocusOffset(CPoint ptInnerFocusOffset) {
m_ptInnerFocusOffset=ptInnerFocusOffset; }
// --- Returns: focus rectangle size in hyper look mode
// --- Effect:
inline CSize GetHyperFocusSize() { return m_hyperFocusSize; }
// --- In : focus rectangle size in hyper look mode
// --- Effect: set focus rectangle size in hyper look mode
inline void SetHyperFocusSize(CSize hyperFocusSize) {
m_hyperFocusSize=hyperFocusSize; }
// --- Returns: offset used to show button face in pressed down state
// --- Effect:
inline CPoint GetPressedDownOffset() { return m_ptDownOffset; }
// --- In : offset used to show button face in pressed down state
// --- Effect: set offset used to show button face in pressed down state
inline void SetPressedDownOffset(CPoint ptDownOffset) {
m_ptDownOffset=ptDownOffset; }
// --- Returns: offset used to show button face in checked state
// --- Effect:
inline CPoint GetCheckedOffset() { return m_ptCheckedOffset; }
// --- In : offset used to show button face in checked state
// --- Effect: set offset used to show button face in checked state
inline void SetCheckedOffset(CPoint ptCheckedOffset) {
m_ptCheckedOffset=ptCheckedOffset; }
// --- Returns: offset used to show button face when the mouse
// is over the button and hyper look and track look are set.
// --- Effect:
inline CPoint GetHyperOffset() { return m_ptHyperOffset; }
// --- In : offset used to show button face when the mouse
// is over the button and hyper look and track look are set.
// --- Effect: set offset used to show button face when the mouse
// is over the button and hyper look and track look are set.
inline void SetHyperOffset(CPoint ptHyperOffset) { m_ptHyperOffset=ptHyperOffset; }
// --- Returns: dropdown arrow rectangle offset from the control border
// --- Effect:
inline CPoint GetArrowOffset() { return m_ptArrowOffset; }
// --- In : dropdown arrow rectangle offset from the control border
// --- Effect: set dropdown arrow rectangle offset from the control border
inline void SetArrowOffset(CPoint ptArrowOffset) { m_ptArrowOffset=ptArrowOffset; }
// --- In : bDrawDropdownSeparator - if TRUE then a separator will be drawn
// between button's image and/or text
// and dropdown mark
// --- Out :
// --- Returns:
// --- Effect: Sets the flag that specifies if dropdown separator will be
// drawn or not
inline void SetDrawDropdownSeparator(BOOL bDrawDropdownSeparator) {
m_bDrawDropdownSeparator=bDrawDropdownSeparator;
}
// --- In : bDrawDropdownSeparator - if TRUE then a separator will be drawn
// between button's image and/or text
// and dropdown mark
// --- Out :
// --- Returns: TRUE if a separator will be drawn between button's image and/or
// text and dropdown mark
// --- Effect: Retrieves the flag that specifies if dropdown separator will be
// drawn or not
inline BOOL IsDrawingDropdownSeparator() const { return m_bDrawDropdownSeparator; }
// --- In :
// --- Out :
// --- Returns:
// --- Effect: Destructor of the object
virtual ~COXBitmapButton();
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXBitmapButton)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
protected:
HMENU m_hMenu;
virtual void DistributeSpace(UINT nState, CRect itemRect,
CRect& buttonRect, CRect& imageRect, CRect& textRect);
virtual void SelectPalette(CDC* pDC, UINT nState, CRect buttonRect,
CPalette*& pOldPalette);
virtual void DrawButton(CDC* pDC, UINT nState, CRect buttonRect);
virtual void DrawImage(CDC* pDC, UINT nState, CImageList* pImageList,
CRect imageRect);
virtual void DrawText(CDC* pDC, UINT nState, CString sText, CRect textRect);
virtual void DrawFocusRectangle(CDC* pDC, UINT nState, CRect buttonRect,
CRect bitmapRect);
virtual void RestorePalette(CDC* pDC, UINT nState, CRect buttonRect,
CPalette* pOldPalette);
BOOL BuildGrayBitmap(LPCTSTR lpszBitmapResource, COLORREF crMask,
CBitmap* pGrayBitmap);
BOOL BuildGrayIcon(LPCTSTR lpszIconResource, HICON* phIcon);
BOOL MakeGray(LPBITMAPINFOHEADER pBitmapInfoHeader, COLORREF crMask = CLR_NONE);
BOOL BuildDisabledImage(HICON hSourceIcon, CSize imageSize, HICON& hDestIcon);
static BOOL GetBitmapPalette(LPCTSTR lpszBitmapResource, CPalette& palette);
static BOOL GetIconPalette(LPCTSTR lpszIconResource, CPalette& palette);
static BOOL GetImagePalette(LPBITMAPINFOHEADER pBitmapInfoHeader, CPalette& palette);
void CheckTrackLook(CPoint point);
void PostCheckTrackLook();
static CString GetSubString(LPCTSTR pszFullString, int nSubIndex, TCHAR cDelimiter);
static CString RemoveAmpersand(LPCTSTR pszText);
static BOOL LoadBitmap(LPCTSTR lpszBitmapResource, CBitmap& bitmap,
CPalette& palette);
virtual int GetDropDownArrowWidth();
virtual void DrawDropDownArrow(CDC* pDC, UINT nState, CRect arrowRect);
virtual void OnDropDown();
virtual void OnToggle();
// --- In :
// --- Out :
// --- Returns: TRUE if OXBB_STATE_CHECKED is set in result of this function,
// or FALSE otherwise
// --- Effect: toggle between checked and unchecked state
BOOL Toggle();
// --- In :
// --- Out :
// --- Returns: TRUE if OXBB_EX_DROPDOWN extended style is set and
// OXBB_EX_DROPDOWNNOARROW is not (i.e. dropdown arrow will be drawn)
// --- Effect: helper function
BOOL HasDropDownArrow();
//{{AFX_MSG(COXBitmapButton)
afx_msg void OnSysColorChange();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
afx_msg void OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnMove(int x, int y);
afx_msg void OnEnable(BOOL bEnable);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
//}}AFX_MSG
afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnCheckTrackLook(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnClick(WPARAM wParam, LPARAM lParam);
virtual afx_msg BOOL OnClicked();
DECLARE_MESSAGE_MAP()
private:
public:
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
};
#endif // __OXBITMAPBUTTON_H__
// ==========================================================================
| [
"[email protected]"
] | [
[
[
1,
1055
]
]
] |
f5e3e3587e377111838f02d9ea816568a3bec2d3 | 198faaa66e25fb612798ee7eecd1996f77f56cf8 | /Console/SettingsHandler.cpp | 0d1f629727ca12a4ed30d6bfd267b301e7085140 | [] | no_license | atsuoishimoto/console2-ime-old | bb83043d942d91b1835acefa94ce7e1f679a9e41 | 85e7909761fde64e4de3687e49b1e1457d1571dd | refs/heads/master | 2021-01-17T17:21:35.221688 | 2011-05-27T04:06:14 | 2011-05-27T04:06:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70,956 | cpp | #include "stdafx.h"
#include "resource.h"
#include "XmlHelper.h"
#include "SettingsHandler.h"
using namespace boost::algorithm;
//////////////////////////////////////////////////////////////////////////////
extern shared_ptr<ImageHandler> g_imageHandler;
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void SettingsBase::AddTextNode(CComPtr<IXMLDOMDocument>& pDoc, CComPtr<IXMLDOMElement>& pElement, const CComBSTR& bstrText)
{
CComPtr<IXMLDOMText> pDomText;
CComPtr<IXMLDOMNode> pDomTextOut;
pDoc->createTextNode(bstrText, &pDomText);
pElement->appendChild(pDomText, &pDomTextOut);
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ConsoleSettings::ConsoleSettings()
: strShell(L"")
, strInitialDir(L"")
, dwRefreshInterval(100)
, dwChangeRefreshInterval(10)
, dwRows(25)
, dwColumns(80)
, dwBufferRows(200)
, dwBufferColumns(80)
, bStartHidden(false)
, bSaveSize(false)
{
defaultConsoleColors[0] = 0x000000;
defaultConsoleColors[1] = 0x800000;
defaultConsoleColors[2] = 0x008000;
defaultConsoleColors[3] = 0x808000;
defaultConsoleColors[4] = 0x000080;
defaultConsoleColors[5] = 0x800080;
defaultConsoleColors[6] = 0x008080;
defaultConsoleColors[7] = 0xC0C0C0;
defaultConsoleColors[8] = 0x808080;
defaultConsoleColors[9] = 0xFF0000;
defaultConsoleColors[10]= 0x00FF00;
defaultConsoleColors[11]= 0xFFFF00;
defaultConsoleColors[12]= 0x0000FF;
defaultConsoleColors[13]= 0xFF00FF;
defaultConsoleColors[14]= 0x00FFFF;
defaultConsoleColors[15]= 0xFFFFFF;
::CopyMemory(consoleColors, defaultConsoleColors, sizeof(COLORREF)*16);
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ConsoleSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pConsoleElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"console"), pConsoleElement))) return false;
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"shell"), strShell, wstring(L""));
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"init_dir"), strInitialDir, wstring(L""));
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"refresh"), dwRefreshInterval, 100);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"change_refresh"), dwChangeRefreshInterval, 10);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"rows"), dwRows, 25);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"columns"), dwColumns, 80);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"buffer_rows"), dwBufferRows, 0);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"buffer_columns"), dwBufferColumns, 0);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"start_hidden"), bStartHidden, false);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"save_size"), bSaveSize, false);
for (DWORD i = 0; i < 16; ++i)
{
CComPtr<IXMLDOMElement> pFontColorElement;
if (FAILED(XmlHelper::GetDomElement(pConsoleElement, CComBSTR(str(wformat(L"colors/color[%1%]") % i).c_str()), pFontColorElement))) continue;
DWORD id;
XmlHelper::GetAttribute(pFontColorElement, CComBSTR(L"id"), id, i);
XmlHelper::GetRGBAttribute(pFontColorElement, consoleColors[id], consoleColors[i]);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ConsoleSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pConsoleElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"console"), pConsoleElement))) return false;
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"shell"), strShell);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"init_dir"), strInitialDir);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"refresh"), dwRefreshInterval);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"change_refresh"), dwChangeRefreshInterval);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"rows"), dwRows);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"columns"), dwColumns);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"buffer_rows"), dwBufferRows);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"buffer_columns"), dwBufferColumns);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"start_hidden"), bStartHidden);
XmlHelper::SetAttribute(pConsoleElement, CComBSTR(L"save_size"), bSaveSize);
for (DWORD i = 0; i < 16; ++i)
{
CComPtr<IXMLDOMElement> pFontColorElement;
if (FAILED(XmlHelper::GetDomElement(pConsoleElement, CComBSTR(str(wformat(L"colors/color[%1%]") % i).c_str()), pFontColorElement))) continue;
XmlHelper::SetAttribute(pFontColorElement, CComBSTR(L"id"), i);
XmlHelper::SetRGBAttribute(pFontColorElement, consoleColors[i]);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ConsoleSettings& ConsoleSettings::operator=(const ConsoleSettings& other)
{
strShell = other.strShell;
strInitialDir = other.strInitialDir;
dwRefreshInterval = other.dwRefreshInterval;
dwChangeRefreshInterval = other.dwChangeRefreshInterval;
dwRows = other.dwRows;
dwColumns = other.dwColumns;
dwBufferRows = other.dwBufferRows;
dwBufferColumns = other.dwBufferColumns;
bStartHidden = other.bStartHidden;
bSaveSize = other.bSaveSize;
::CopyMemory(consoleColors, other.consoleColors, sizeof(COLORREF)*16);
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
FontSettings::FontSettings()
: strName(L"Courier New")
, dwSize(10)
, bBold(false)
, bItalic(false)
, fontSmoothing(fontSmoothDefault)
, bUseColor(false)
, crFontColor(0)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool FontSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pFontElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/font"), pFontElement))) return false;
int nFontSmoothing;
XmlHelper::GetAttribute(pFontElement, CComBSTR(L"name"), strName, wstring(L"Courier New"));
XmlHelper::GetAttribute(pFontElement, CComBSTR(L"size"), dwSize, 10);
XmlHelper::GetAttribute(pFontElement, CComBSTR(L"bold"), bBold, false);
XmlHelper::GetAttribute(pFontElement, CComBSTR(L"italic"), bItalic, false);
XmlHelper::GetAttribute(pFontElement, CComBSTR(L"smoothing"), nFontSmoothing, 0);
fontSmoothing = static_cast<FontSmoothing>(nFontSmoothing);
CComPtr<IXMLDOMElement> pColorElement;
if (FAILED(XmlHelper::GetDomElement(pFontElement, CComBSTR(L"color"), pColorElement))) return false;
XmlHelper::GetAttribute(pColorElement, CComBSTR(L"use"), bUseColor, false);
XmlHelper::GetRGBAttribute(pColorElement, crFontColor, RGB(0, 0, 0));
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool FontSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pFontElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/font"), pFontElement))) return false;
XmlHelper::SetAttribute(pFontElement, CComBSTR(L"name"), strName);
XmlHelper::SetAttribute(pFontElement, CComBSTR(L"size"), dwSize);
XmlHelper::SetAttribute(pFontElement, CComBSTR(L"bold"), bBold);
XmlHelper::SetAttribute(pFontElement, CComBSTR(L"italic"), bItalic);
XmlHelper::SetAttribute(pFontElement, CComBSTR(L"smoothing"), static_cast<int>(fontSmoothing));
CComPtr<IXMLDOMElement> pColorElement;
if (FAILED(XmlHelper::GetDomElement(pFontElement, CComBSTR(L"color"), pColorElement))) return false;
XmlHelper::SetAttribute(pColorElement, CComBSTR(L"use"), bUseColor);
XmlHelper::SetRGBAttribute(pColorElement, crFontColor);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
FontSettings& FontSettings::operator=(const FontSettings& other)
{
strName = other.strName;
dwSize = other.dwSize;
bBold = other.bBold;
bItalic = other.bItalic;
fontSmoothing = other.fontSmoothing;
bUseColor = other.bUseColor;
crFontColor = other.crFontColor;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
WindowSettings::WindowSettings()
: strTitle(L"Console")
, strIcon(L"")
, bUseTabIcon(false)
, bUseConsoleTitle(false)
, bShowCommand(true)
, bShowCommandInTabs(true)
, bUseTabTitles(false)
, dwTrimTabTitles(0)
, dwTrimTabTitlesRight(0)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool WindowSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pWindowElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/window"), pWindowElement))) return false;
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"title"), strTitle, wstring(L"Console"));
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"icon"), strIcon, wstring(L""));
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"use_tab_icon"), bUseTabIcon, false);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"use_console_title"), bUseConsoleTitle, false);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"show_cmd"), bShowCommand, true);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"show_cmd_tabs"), bShowCommandInTabs, true);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"use_tab_title"), bUseTabTitles, false);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"trim_tab_titles"), dwTrimTabTitles, 0);
XmlHelper::GetAttribute(pWindowElement, CComBSTR(L"trim_tab_titles_right"), dwTrimTabTitlesRight, 0);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool WindowSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pWindowElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/window"), pWindowElement))) return false;
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"title"), strTitle);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"icon"), strIcon);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"use_tab_icon"), bUseTabIcon);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"use_console_title"), bUseConsoleTitle);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"show_cmd"), bShowCommand);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"show_cmd_tabs"), bShowCommandInTabs);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"use_tab_title"), bUseTabTitles);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"trim_tab_titles"), dwTrimTabTitles);
XmlHelper::SetAttribute(pWindowElement, CComBSTR(L"trim_tab_titles_right"), dwTrimTabTitlesRight);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
WindowSettings& WindowSettings::operator=(const WindowSettings& other)
{
strTitle = other.strTitle;
strIcon = other.strIcon;
bUseTabIcon = other.bUseTabIcon;
bUseConsoleTitle = other.bUseConsoleTitle;
bShowCommand = other.bShowCommand;
bShowCommandInTabs = other.bShowCommandInTabs;
bUseTabTitles = other.bUseTabTitles;
dwTrimTabTitles = other.dwTrimTabTitles;
dwTrimTabTitlesRight= other.dwTrimTabTitlesRight;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ControlsSettings::ControlsSettings()
: bShowMenu(true)
, bShowToolbar(true)
, bShowStatusbar(true)
, bShowTabs(true)
, bHideSingleTab(false)
, bTabsOnBottom(false)
, bShowScrollbars(true)
, bFlatScrollbars(false)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ControlsSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pCtrlsElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/controls"), pCtrlsElement))) return false;
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"show_menu"), bShowMenu, true);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"show_toolbar"), bShowToolbar, true);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"show_statusbar"), bShowStatusbar, true);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"show_tabs"), bShowTabs, true);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"hide_single_tab"), bHideSingleTab, false);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"tabs_on_bottom"), bTabsOnBottom, false);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"show_scrollbars"), bShowScrollbars, true);
XmlHelper::GetAttribute(pCtrlsElement, CComBSTR(L"flat_scrollbars"), bFlatScrollbars, false);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ControlsSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pCtrlsElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/controls"), pCtrlsElement))) return false;
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"show_menu"), bShowMenu);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"show_toolbar"), bShowToolbar);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"show_statusbar"), bShowStatusbar);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"show_tabs"), bShowTabs);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"hide_single_tab"), bHideSingleTab);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"tabs_on_bottom"), bTabsOnBottom);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"show_scrollbars"), bShowScrollbars);
XmlHelper::SetAttribute(pCtrlsElement, CComBSTR(L"flat_scrollbars"), bFlatScrollbars);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ControlsSettings& ControlsSettings::operator=(const ControlsSettings& other)
{
bShowMenu = other.bShowMenu;
bShowToolbar = other.bShowToolbar;
bShowStatusbar = other.bShowStatusbar;
bShowTabs = other.bShowTabs;
bHideSingleTab = other.bHideSingleTab;
bTabsOnBottom = other.bTabsOnBottom;
bShowScrollbars = other.bShowScrollbars;
bFlatScrollbars = other.bFlatScrollbars;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
StylesSettings::StylesSettings()
: bCaption(true)
, bResizable(true)
, bTaskbarButton(true)
, bBorder(true)
, dwInsideBorder(2)
, bTrayIcon(false)
, crSelectionColor(RGB(255, 255, 255))
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool StylesSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pStylesElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/styles"), pStylesElement))) return false;
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"caption"), bCaption, true);
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"resizable"), bResizable, true);
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"taskbar_button"), bTaskbarButton, true);
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"border"), bBorder, true);
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"inside_border"), dwInsideBorder, 2);
XmlHelper::GetAttribute(pStylesElement, CComBSTR(L"tray_icon"), bTrayIcon, false);
CComPtr<IXMLDOMElement> pSelColorElement;
if (FAILED(XmlHelper::GetDomElement(pStylesElement, CComBSTR(L"selection_color"), pSelColorElement))) return false;
XmlHelper::GetRGBAttribute(pSelColorElement, crSelectionColor, RGB(255, 255, 255));
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool StylesSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pStylesElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/styles"), pStylesElement))) return false;
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"caption"), bCaption);
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"resizable"), bResizable);
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"taskbar_button"), bTaskbarButton);
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"border"), bBorder);
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"inside_border"), dwInsideBorder);
XmlHelper::SetAttribute(pStylesElement, CComBSTR(L"tray_icon"), bTrayIcon);
CComPtr<IXMLDOMElement> pSelColorElement;
if (FAILED(XmlHelper::GetDomElement(pStylesElement, CComBSTR(L"selection_color"), pSelColorElement))) return false;
XmlHelper::SetRGBAttribute(pSelColorElement, crSelectionColor);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
StylesSettings& StylesSettings::operator=(const StylesSettings& other)
{
bCaption = other.bCaption;
bResizable = other.bResizable;
bTaskbarButton = other.bTaskbarButton;
bBorder = other.bBorder;
dwInsideBorder = other.dwInsideBorder;
bTrayIcon = other.bTrayIcon;
crSelectionColor= other.crSelectionColor;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
PositionSettings::PositionSettings()
: nX(-1)
, nY(-1)
, bSavePosition(false)
, zOrder(zorderNormal)
, dockPosition(dockNone)
, nSnapDistance(-1)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool PositionSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pPositionElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/position"), pPositionElement))) return false;
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"x"), nX, -1);
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"y"), nY, -1);
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"save_position"), bSavePosition, false);
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"z_order"), reinterpret_cast<int&>(zOrder), static_cast<int>(zorderNormal));
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"dock"), reinterpret_cast<int&>(dockPosition), static_cast<int>(dockNone));
XmlHelper::GetAttribute(pPositionElement, CComBSTR(L"snap"), nSnapDistance, -1);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool PositionSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pPositionElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/position"), pPositionElement))) return false;
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"x"), nX);
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"y"), nY);
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"save_position"), bSavePosition);
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"z_order"), static_cast<int>(zOrder));
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"dock"), static_cast<int>(dockPosition));
XmlHelper::SetAttribute(pPositionElement, CComBSTR(L"snap"), nSnapDistance);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
PositionSettings& PositionSettings::operator=(const PositionSettings& other)
{
nX = other.nX;
nY = other.nY;
bSavePosition = other.bSavePosition;
zOrder = other.zOrder;
dockPosition = other.dockPosition;
nSnapDistance = other.nSnapDistance;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TransparencySettings::TransparencySettings()
: transType(transNone)
, byActiveAlpha(255)
, byInactiveAlpha(255)
, crColorKey(RGB(0, 0, 0))
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TransparencySettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pTransElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/transparency"), pTransElement))) return false;
XmlHelper::GetAttribute(pTransElement, CComBSTR(L"type"), reinterpret_cast<DWORD&>(transType), static_cast<DWORD>(transNone));
XmlHelper::GetAttribute(pTransElement, CComBSTR(L"active_alpha"), byActiveAlpha, 255);
XmlHelper::GetAttribute(pTransElement, CComBSTR(L"inactive_alpha"), byInactiveAlpha, 255);
XmlHelper::GetRGBAttribute(pTransElement, crColorKey, RGB(0, 0, 0));
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TransparencySettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pTransElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"appearance/transparency"), pTransElement))) return false;
XmlHelper::SetAttribute(pTransElement, CComBSTR(L"type"), reinterpret_cast<DWORD&>(transType));
XmlHelper::SetAttribute(pTransElement, CComBSTR(L"active_alpha"), byActiveAlpha);
XmlHelper::SetAttribute(pTransElement, CComBSTR(L"inactive_alpha"), byInactiveAlpha);
XmlHelper::SetRGBAttribute(pTransElement, crColorKey);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TransparencySettings& TransparencySettings::operator=(const TransparencySettings& other)
{
transType = other.transType;
byActiveAlpha = other.byActiveAlpha;
byInactiveAlpha = other.byInactiveAlpha;
crColorKey = other.crColorKey;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
AppearanceSettings::AppearanceSettings()
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool AppearanceSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
fontSettings.Load(pSettingsRoot);
windowSettings.Load(pSettingsRoot);
controlsSettings.Load(pSettingsRoot);
stylesSettings.Load(pSettingsRoot);
positionSettings.Load(pSettingsRoot);
transparencySettings.Load(pSettingsRoot);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool AppearanceSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
fontSettings.Save(pSettingsRoot);
windowSettings.Save(pSettingsRoot);
controlsSettings.Save(pSettingsRoot);
stylesSettings.Save(pSettingsRoot);
positionSettings.Save(pSettingsRoot);
transparencySettings.Save(pSettingsRoot);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
AppearanceSettings& AppearanceSettings::operator=(const AppearanceSettings& other)
{
fontSettings = other.fontSettings;
windowSettings = other.windowSettings;
controlsSettings = other.controlsSettings;
stylesSettings = other.stylesSettings;
positionSettings = other.positionSettings;
transparencySettings= other.transparencySettings;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
CopyPasteSettings::CopyPasteSettings()
: bCopyOnSelect(false)
, bClearOnCopy(true)
, bNoWrap(false)
, bTrimSpaces(false)
, copyNewlineChar(newlineCRLF)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool CopyPasteSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pCopyPasteElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/copy_paste"), pCopyPasteElement))) return false;
int nNewlineChar;
XmlHelper::GetAttribute(pCopyPasteElement, CComBSTR(L"copy_on_select"), bCopyOnSelect, false);
XmlHelper::GetAttribute(pCopyPasteElement, CComBSTR(L"clear_on_copy"), bClearOnCopy, true);
XmlHelper::GetAttribute(pCopyPasteElement, CComBSTR(L"no_wrap"), bNoWrap, false);
XmlHelper::GetAttribute(pCopyPasteElement, CComBSTR(L"trim_spaces"), bTrimSpaces, false);
XmlHelper::GetAttribute(pCopyPasteElement, CComBSTR(L"copy_newline_char"), nNewlineChar, 0);
copyNewlineChar = static_cast<CopyNewlineChar>(nNewlineChar);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool CopyPasteSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pCopyPasteElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/copy_paste"), pCopyPasteElement))) return false;
XmlHelper::SetAttribute(pCopyPasteElement, CComBSTR(L"copy_on_select"), bCopyOnSelect);
XmlHelper::SetAttribute(pCopyPasteElement, CComBSTR(L"clear_on_copy"), bClearOnCopy);
XmlHelper::SetAttribute(pCopyPasteElement, CComBSTR(L"no_wrap"), bNoWrap);
XmlHelper::SetAttribute(pCopyPasteElement, CComBSTR(L"trim_spaces"), bTrimSpaces);
XmlHelper::SetAttribute(pCopyPasteElement, CComBSTR(L"copy_newline_char"), static_cast<int>(copyNewlineChar));
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
CopyPasteSettings& CopyPasteSettings::operator=(const CopyPasteSettings& other)
{
bCopyOnSelect = other.bCopyOnSelect;
bClearOnCopy = other.bClearOnCopy;
bNoWrap = other.bNoWrap;
bTrimSpaces = other.bTrimSpaces;
copyNewlineChar = other.copyNewlineChar;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ScrollSettings::ScrollSettings()
: dwPageScrollRows(0)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ScrollSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pScrollElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/scroll"), pScrollElement))) return false;
XmlHelper::GetAttribute(pScrollElement, CComBSTR(L"page_scroll_rows"), dwPageScrollRows, 0);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool ScrollSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pScrollElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/scroll"), pScrollElement))) return false;
XmlHelper::SetAttribute(pScrollElement, CComBSTR(L"page_scroll_rows"), dwPageScrollRows);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
ScrollSettings& ScrollSettings::operator=(const ScrollSettings& other)
{
dwPageScrollRows= other.dwPageScrollRows;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TabHighlightSettings::TabHighlightSettings()
: dwFlashes(0)
, bStayHighlighted(false)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TabHighlightSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pTabElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/tab_highlight"), pTabElement))) return false;
XmlHelper::GetAttribute(pTabElement, CComBSTR(L"flashes"), dwFlashes, 0);
XmlHelper::GetAttribute(pTabElement, CComBSTR(L"stay_highligted"), bStayHighlighted, false);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TabHighlightSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pTabElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/tab_highlight"), pTabElement))) return false;
XmlHelper::SetAttribute(pTabElement, CComBSTR(L"flashes"), dwFlashes);
XmlHelper::SetAttribute(pTabElement, CComBSTR(L"stay_highligted"), bStayHighlighted);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TabHighlightSettings& TabHighlightSettings::operator=(const TabHighlightSettings& other)
{
dwFlashes = other.dwFlashes;
bStayHighlighted= other.bStayHighlighted;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
AnimateSettings::AnimateSettings()
: dwType(animTypeNone)
, dwHorzDirection(animDirNone)
, dwVertDirection(animDirNone)
, dwTime(0)
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool AnimateSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pAnimateElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/animate"), pAnimateElement))) return false;
XmlHelper::GetAttribute(pAnimateElement, CComBSTR(L"type"), dwType, animTypeNone);
XmlHelper::GetAttribute(pAnimateElement, CComBSTR(L"horz_direction"), dwHorzDirection, animDirNone);
XmlHelper::GetAttribute(pAnimateElement, CComBSTR(L"vert_direction"), dwVertDirection, animDirNone);
XmlHelper::GetAttribute(pAnimateElement, CComBSTR(L"time"), dwTime, 200);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool AnimateSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
CComPtr<IXMLDOMElement> pAnimateElement;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"behavior/animate"), pAnimateElement))) return false;
XmlHelper::SetAttribute(pAnimateElement, CComBSTR(L"type"), dwType);
XmlHelper::SetAttribute(pAnimateElement, CComBSTR(L"horz_direction"), dwHorzDirection);
XmlHelper::SetAttribute(pAnimateElement, CComBSTR(L"vert_direction"), dwVertDirection);
XmlHelper::SetAttribute(pAnimateElement, CComBSTR(L"time"), dwTime);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
AnimateSettings& AnimateSettings::operator=(const AnimateSettings& other)
{
dwType = other.dwType;
dwHorzDirection = other.dwHorzDirection;
dwVertDirection = other.dwVertDirection;
dwTime = other.dwTime;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
BehaviorSettings::BehaviorSettings()
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool BehaviorSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
copyPasteSettings.Load(pSettingsRoot);
scrollSettings.Load(pSettingsRoot);
tabHighlightSettings.Load(pSettingsRoot);
// animateSettings.Load(pSettingsRoot);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool BehaviorSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
copyPasteSettings.Save(pSettingsRoot);
scrollSettings.Save(pSettingsRoot);
tabHighlightSettings.Save(pSettingsRoot);
// animateSettings.Save(pSettingsRoot);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
BehaviorSettings& BehaviorSettings::operator=(const BehaviorSettings& other)
{
copyPasteSettings = other.copyPasteSettings;
scrollSettings = other.scrollSettings;
tabHighlightSettings= other.tabHighlightSettings;
// animateSettings = other.animateSettings;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
HotKeys::HotKeys()
: bUseScrollLock(false)
{
commands.push_back(shared_ptr<CommandData>(new CommandData(L"settings", ID_EDIT_SETTINGS, L"Settings dialog")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"help", ID_HELP, L"Help")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"exit", ID_APP_EXIT, L"Exit Console")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab1", ID_NEW_TAB_1, L"New Tab 1")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab2", ID_NEW_TAB_1 + 1, L"New Tab 2")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab3", ID_NEW_TAB_1 + 2, L"New Tab 3")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab4", ID_NEW_TAB_1 + 3, L"New Tab 4")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab5", ID_NEW_TAB_1 + 4, L"New Tab 5")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab6", ID_NEW_TAB_1 + 5, L"New Tab 6")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab7", ID_NEW_TAB_1 + 6, L"New Tab 7")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab8", ID_NEW_TAB_1 + 7, L"New Tab 8")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab9", ID_NEW_TAB_1 + 8, L"New Tab 9")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"newtab10", ID_NEW_TAB_1 + 9, L"New Tab 10")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab1", ID_SWITCH_TAB_1, L"Switch to tab 1")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab2", ID_SWITCH_TAB_1 + 1,L"Switch to tab 2")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab3", ID_SWITCH_TAB_1 + 2,L"Switch to tab 3")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab4", ID_SWITCH_TAB_1 + 3,L"Switch to tab 4")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab5", ID_SWITCH_TAB_1 + 4,L"Switch to tab 5")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab6", ID_SWITCH_TAB_1 + 5,L"Switch to tab 6")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab7", ID_SWITCH_TAB_1 + 6,L"Switch to tab 7")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab8", ID_SWITCH_TAB_1 + 7,L"Switch to tab 8")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab9", ID_SWITCH_TAB_1 + 8,L"Switch to tab 9")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"switchtab10", ID_SWITCH_TAB_1 + 9,L"Switch to tab 10")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"nexttab", ID_NEXT_TAB, L"Next tab")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"prevtab", ID_PREV_TAB, L"Previous tab")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"closetab", ID_FILE_CLOSE_TAB, L"Close tab")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"renametab", ID_EDIT_RENAME_TAB, L"Rename tab")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"copy", ID_EDIT_COPY, L"Copy selection")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"clear_selection",ID_EDIT_CLEAR_SELECTION, L"Clear selection")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"paste", ID_EDIT_PASTE, L"Paste")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"stopscroll", ID_EDIT_STOP_SCROLLING, L"Stop scrolling")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollrowup", ID_SCROLL_UP, L"Scroll buffer row up")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollrowdown", ID_SCROLL_DOWN, L"Scroll buffer row down")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollpageup", ID_SCROLL_PAGE_UP, L"Scroll buffer page up")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollpagedown", ID_SCROLL_PAGE_DOWN, L"Scroll buffer page down")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollcolleft", ID_SCROLL_LEFT, L"Scroll buffer column left")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollcolright", ID_SCROLL_RIGHT, L"Scroll buffer column right")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollpageleft", ID_SCROLL_PAGE_LEFT, L"Scroll buffer page left")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"scrollpageright", ID_SCROLL_PAGE_RIGHT, L"Scroll buffer page right")));
commands.push_back(shared_ptr<CommandData>(new CommandData(L"dumpbuffer", IDC_DUMP_BUFFER, L"Dump screen buffer")));
// global commands
commands.push_back(shared_ptr<CommandData>(new CommandData(L"activate", IDC_GLOBAL_ACTIVATE, L"Activate Console (global)", true)));
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool HotKeys::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pHotkeysElement;
CComPtr<IXMLDOMNodeList> pHotKeyNodes;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"hotkeys"), pHotkeysElement))) return false;
XmlHelper::GetAttribute(pHotkeysElement, CComBSTR(L"use_scroll_lock"), bUseScrollLock, false);
hr = pHotkeysElement->selectNodes(CComBSTR(L"hotkey"), &pHotKeyNodes);
if (FAILED(hr)) return false;
long lListLength;
pHotKeyNodes->get_length(&lListLength);
for (long i = 0; i < lListLength; ++i)
{
CComPtr<IXMLDOMNode> pHotKeyNode;
CComPtr<IXMLDOMElement> pHotKeyElement;
pHotKeyNodes->get_item(i, &pHotKeyNode);
if (FAILED(pHotKeyNode.QueryInterface(&pHotKeyElement))) continue;
wstring strCommand(L"");
bool bShift;
bool bCtrl;
bool bAlt;
bool bExtended;
DWORD dwKeyCode;
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"command"), strCommand, wstring(L""));
CommandNameIndex::iterator it = commands.get<command>().find(strCommand);
if (it == commands.get<command>().end()) continue;
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"shift"), bShift, false);
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"ctrl"), bCtrl, false);
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"alt"), bAlt, false);
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"extended"), bExtended, false);
XmlHelper::GetAttribute(pHotKeyElement, CComBSTR(L"code"), dwKeyCode, 0);
if (bShift) (*it)->accelHotkey.fVirt |= FSHIFT;
if (bCtrl) (*it)->accelHotkey.fVirt |= FCONTROL;
if (bAlt) (*it)->accelHotkey.fVirt |= FALT;
(*it)->accelHotkey.fVirt|= FVIRTKEY;
(*it)->accelHotkey.key = static_cast<WORD>(dwKeyCode);
(*it)->accelHotkey.cmd = (*it)->wCommandID;
(*it)->bExtended = bExtended;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool HotKeys::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pHotkeysElement;
CComPtr<IXMLDOMNodeList> pHotKeyChildNodes;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"hotkeys"), pHotkeysElement))) return false;
XmlHelper::SetAttribute(pHotkeysElement, CComBSTR(L"use_scroll_lock"), bUseScrollLock);
if (FAILED(pHotkeysElement->get_childNodes(&pHotKeyChildNodes))) return false;
long lListLength;
pHotKeyChildNodes->get_length(&lListLength);
for (long i = lListLength - 1; i >= 0; --i)
{
CComPtr<IXMLDOMNode> pHotKeyChildNode;
CComPtr<IXMLDOMNode> pRemovedHotKeyNode;
if (FAILED(pHotKeyChildNodes->get_item(i, &pHotKeyChildNode))) continue;
hr = pHotkeysElement->removeChild(pHotKeyChildNode, &pRemovedHotKeyNode);
}
CComPtr<IXMLDOMDocument> pSettingsDoc;
CommandsSequence::iterator itCommand;
CommandsSequence::iterator itLastCommand = commands.end();
--itLastCommand;
pHotkeysElement->get_ownerDocument(&pSettingsDoc);
for (itCommand = commands.begin(); itCommand != commands.end(); ++itCommand)
{
CComPtr<IXMLDOMElement> pNewHotkeyElement;
CComPtr<IXMLDOMNode> pNewHotkeyOut;
bool bAttrVal;
pSettingsDoc->createElement(CComBSTR(L"hotkey"), &pNewHotkeyElement);
bAttrVal = ((*itCommand)->accelHotkey.fVirt & FCONTROL) ? true : false;
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"ctrl"), bAttrVal);
bAttrVal = ((*itCommand)->accelHotkey.fVirt & FSHIFT) ? true : false;
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"shift"), bAttrVal);
bAttrVal = ((*itCommand)->accelHotkey.fVirt & FALT) ? true : false;
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"alt"), bAttrVal);
bAttrVal = ((*itCommand)->bExtended) ? true : false;
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"extended"), bAttrVal);
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"code"), (*itCommand)->accelHotkey.key);
XmlHelper::SetAttribute(pNewHotkeyElement, CComBSTR(L"command"), (*itCommand)->strCommand);
pHotkeysElement->appendChild(pNewHotkeyElement, &pNewHotkeyOut);
// this is just for pretty printing
if (itCommand == itLastCommand)
{
SettingsBase::AddTextNode(pSettingsDoc, pHotkeysElement, CComBSTR(L"\n\t"));
}
else
{
SettingsBase::AddTextNode(pSettingsDoc, pHotkeysElement, CComBSTR(L"\n\t\t"));
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
HotKeys& HotKeys::operator=(const HotKeys& other)
{
bUseScrollLock = other.bUseScrollLock;
commands.clear();
commands.insert(commands.begin(), other.commands.begin(), other.commands.end());
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
MouseSettings::MouseSettings()
: commands()
{
commands.push_back(shared_ptr<CommandData>(new CommandData(cmdCopy, L"copy", L"Copy/clear selection")));
commands.push_back(shared_ptr<CommandData>(new CommandData(cmdSelect, L"select", L"Select text")));
commands.push_back(shared_ptr<CommandData>(new CommandData(cmdPaste, L"paste", L"Paste text")));
commands.push_back(shared_ptr<CommandData>(new CommandData(cmdDrag, L"drag", L"Drag window")));
commands.push_back(shared_ptr<CommandData>(new CommandData(cmdMenu, L"menu", L"Context menu")));
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool MouseSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pActionsElement;
CComPtr<IXMLDOMNodeList> pActionNodes;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"mouse/actions"), pActionsElement))) return false;
hr = pActionsElement->selectNodes(CComBSTR(L"action"), &pActionNodes);
if (FAILED(hr)) return false;
long lListLength;
pActionNodes->get_length(&lListLength);
for (long i = 0; i < lListLength; ++i)
{
CComPtr<IXMLDOMNode> pActionNode;
CComPtr<IXMLDOMElement> pActionElement;
pActionNodes->get_item(i, &pActionNode);
if (FAILED(pActionNode.QueryInterface(&pActionElement))) continue;
wstring strName;
DWORD dwButton;
bool bUseCtrl;
bool bUseShift;
bool bUseAlt;
XmlHelper::GetAttribute(pActionElement, CComBSTR(L"name"), strName, L"");
XmlHelper::GetAttribute(pActionElement, CComBSTR(L"button"), dwButton, 0);
XmlHelper::GetAttribute(pActionElement, CComBSTR(L"ctrl"), bUseCtrl, false);
XmlHelper::GetAttribute(pActionElement, CComBSTR(L"shift"), bUseShift, false);
XmlHelper::GetAttribute(pActionElement, CComBSTR(L"alt"), bUseAlt, false);
typedef Commands::index<commandName>::type CommandNameIndex;
CommandNameIndex::iterator it = commands.get<commandName>().find(strName);
if (it == commands.get<commandName>().end()) continue;
(*it)->action.clickType = clickSingle;
(*it)->action.button = static_cast<Button>(dwButton);
if (bUseCtrl) (*it)->action.modifiers |= mkCtrl;
if (bUseShift) (*it)->action.modifiers |= mkShift;
if (bUseAlt) (*it)->action.modifiers |= mkAlt;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool MouseSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pMouseActionsElement;
CComPtr<IXMLDOMNodeList> pMouseActionsChildNodes;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"mouse/actions"), pMouseActionsElement))) return false;
if (FAILED(pMouseActionsElement->get_childNodes(&pMouseActionsChildNodes))) return false;
long lListLength;
pMouseActionsChildNodes->get_length(&lListLength);
for (long i = lListLength - 1; i >= 0; --i)
{
CComPtr<IXMLDOMNode> pMouseActionsChildNode;
CComPtr<IXMLDOMNode> pRemovedMouseActionsNode;
if (FAILED(pMouseActionsChildNodes->get_item(i, &pMouseActionsChildNode))) continue;
hr = pMouseActionsElement->removeChild(pMouseActionsChildNode, &pRemovedMouseActionsNode);
}
CComPtr<IXMLDOMDocument> pSettingsDoc;
CommandsSequence::iterator itCommand;
CommandsSequence::iterator itLastCommand = commands.end();
--itLastCommand;
pMouseActionsElement->get_ownerDocument(&pSettingsDoc);
for (itCommand = commands.begin(); itCommand != commands.end(); ++itCommand)
{
CComPtr<IXMLDOMElement> pNewMouseActionsElement;
CComPtr<IXMLDOMNode> pNewMouseActionsOut;
bool bVal;
pSettingsDoc->createElement(CComBSTR(L"action"), &pNewMouseActionsElement);
bVal = ((*itCommand)->action.modifiers & mkCtrl) ? true : false;
XmlHelper::SetAttribute(pNewMouseActionsElement, CComBSTR(L"ctrl"), bVal);
bVal = ((*itCommand)->action.modifiers & mkShift) ? true : false;
XmlHelper::SetAttribute(pNewMouseActionsElement, CComBSTR(L"shift"), bVal);
bVal = ((*itCommand)->action.modifiers & mkAlt) ? true : false;
XmlHelper::SetAttribute(pNewMouseActionsElement, CComBSTR(L"alt"), bVal);
XmlHelper::SetAttribute(pNewMouseActionsElement, CComBSTR(L"button"), static_cast<int>((*itCommand)->action.button));
XmlHelper::SetAttribute(pNewMouseActionsElement, CComBSTR(L"name"), (*itCommand)->strCommand);
pMouseActionsElement->appendChild(pNewMouseActionsElement, &pNewMouseActionsOut);
// this is just for pretty printing
if (itCommand == itLastCommand)
{
SettingsBase::AddTextNode(pSettingsDoc, pMouseActionsElement, CComBSTR(L"\n\t\t"));
}
else
{
SettingsBase::AddTextNode(pSettingsDoc, pMouseActionsElement, CComBSTR(L"\n\t\t\t"));
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
MouseSettings& MouseSettings::operator=(const MouseSettings& other)
{
commands.clear();
commands.insert(commands.begin(), other.commands.begin(), other.commands.end());
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TabSettings::TabSettings()
: strDefaultShell(L"")
, strDefaultInitialDir(L"")
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TabSettings::Load(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMNodeList> pTabNodes;
hr = pSettingsRoot->selectNodes(CComBSTR(L"tabs/tab"), &pTabNodes);
if (FAILED(hr)) return false;
long lListLength;
pTabNodes->get_length(&lListLength);
for (long i = 0; i < lListLength; ++i)
{
CComPtr<IXMLDOMNode> pTabNode;
CComPtr<IXMLDOMElement> pTabElement;
pTabNodes->get_item(i, &pTabNode);
if (FAILED(pTabNode.QueryInterface(&pTabElement))) continue;
shared_ptr<TabData> tabData(new TabData(strDefaultShell, strDefaultInitialDir));
CComPtr<IXMLDOMElement> pConsoleElement;
CComPtr<IXMLDOMElement> pCursorElement;
CComPtr<IXMLDOMElement> pBackgroundElement;
XmlHelper::GetAttribute(pTabElement, CComBSTR(L"title"), tabData->strTitle, L"Console");
XmlHelper::GetAttribute(pTabElement, CComBSTR(L"icon"), tabData->strIcon, L"");
XmlHelper::GetAttribute(pTabElement, CComBSTR(L"use_default_icon"), tabData->bUseDefaultIcon, false);
tabDataVector.push_back(tabData);
if (SUCCEEDED(XmlHelper::GetDomElement(pTabElement, CComBSTR(L"console"), pConsoleElement)))
{
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"shell"), tabData->strShell, strDefaultShell);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"init_dir"), tabData->strInitialDir, strDefaultInitialDir);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"run_as_user"), tabData->bRunAsUser, false);
XmlHelper::GetAttribute(pConsoleElement, CComBSTR(L"user"), tabData->strUser, L"");
}
if (SUCCEEDED(XmlHelper::GetDomElement(pTabElement, CComBSTR(L"cursor"), pCursorElement)))
{
XmlHelper::GetAttribute(pCursorElement, CComBSTR(L"style"), tabData->dwCursorStyle, 0);
XmlHelper::GetRGBAttribute(pCursorElement, tabData->crCursorColor, RGB(255, 255, 255));
}
if (SUCCEEDED(XmlHelper::GetDomElement(pTabElement, CComBSTR(L"background"), pBackgroundElement)))
{
DWORD dwBackgroundImageType = 0;
XmlHelper::GetAttribute(pBackgroundElement, CComBSTR(L"type"), dwBackgroundImageType, 0);
tabData->backgroundImageType = static_cast<BackgroundImageType>(dwBackgroundImageType);
if (tabData->backgroundImageType == bktypeNone)
{
XmlHelper::GetRGBAttribute(pBackgroundElement, tabData->crBackgroundColor, RGB(0, 0, 0));
}
else
{
tabData->crBackgroundColor = RGB(0, 0, 0);
// load image settings and let ImageHandler return appropriate bitmap
CComPtr<IXMLDOMElement> pImageElement;
CComPtr<IXMLDOMElement> pTintElement;
if (FAILED(XmlHelper::GetDomElement(pTabElement, CComBSTR(L"background/image"), pImageElement))) return false;
if (SUCCEEDED(XmlHelper::GetDomElement(pTabElement, CComBSTR(L"background/image/tint"), pTintElement)))
{
XmlHelper::GetRGBAttribute(pTintElement, tabData->imageData.crTint, RGB(0, 0, 0));
XmlHelper::GetAttribute(pTintElement, CComBSTR(L"opacity"), tabData->imageData.byTintOpacity, 0);
}
if (tabData->backgroundImageType == bktypeImage)
{
DWORD dwImagePosition = 0;
XmlHelper::GetAttribute(pImageElement, CComBSTR(L"file"), tabData->imageData.strFilename, wstring(L""));
XmlHelper::GetAttribute(pImageElement, CComBSTR(L"relative"), tabData->imageData.bRelative, false);
XmlHelper::GetAttribute(pImageElement, CComBSTR(L"extend"), tabData->imageData.bExtend, false);
XmlHelper::GetAttribute(pImageElement, CComBSTR(L"position"), dwImagePosition, 0);
tabData->imageData.imagePosition = static_cast<ImagePosition>(dwImagePosition);
}
}
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool TabSettings::Save(const CComPtr<IXMLDOMElement>& pSettingsRoot)
{
HRESULT hr = S_OK;
CComPtr<IXMLDOMElement> pTabsElement;
CComPtr<IXMLDOMNodeList> pTabChildNodes;
if (FAILED(XmlHelper::GetDomElement(pSettingsRoot, CComBSTR(L"tabs"), pTabsElement))) return false;
if (FAILED(pTabsElement->get_childNodes(&pTabChildNodes))) return false;
long lListLength;
pTabChildNodes->get_length(&lListLength);
for (long i = lListLength - 1; i >= 0; --i)
{
CComPtr<IXMLDOMNode> pTabChildNode;
CComPtr<IXMLDOMNode> pRemovedTabNode;
if (FAILED(pTabChildNodes->get_item(i, &pTabChildNode))) continue;
hr = pTabsElement->removeChild(pTabChildNode, &pRemovedTabNode);
}
CComPtr<IXMLDOMDocument> pSettingsDoc;
TabDataVector::iterator itTab;
TabDataVector::iterator itLastTab = tabDataVector.end() - 1;
pTabsElement->get_ownerDocument(&pSettingsDoc);
for (itTab = tabDataVector.begin(); itTab != tabDataVector.end(); ++itTab)
{
CComPtr<IXMLDOMElement> pNewTabElement;
CComPtr<IXMLDOMNode> pNewTabOut;
pSettingsDoc->createElement(CComBSTR(L"tab"), &pNewTabElement);
// set tab attributes
if ((*itTab)->strTitle.length() > 0)
{
XmlHelper::SetAttribute(pNewTabElement, CComBSTR(L"title"), (*itTab)->strTitle);
}
if ((*itTab)->strIcon.length() > 0)
{
XmlHelper::SetAttribute(pNewTabElement, CComBSTR(L"icon"), (*itTab)->strIcon);
}
XmlHelper::SetAttribute(pNewTabElement, CComBSTR(L"use_default_icon"), (*itTab)->bUseDefaultIcon);
// add <console> tag
CComPtr<IXMLDOMElement> pNewConsoleElement;
CComPtr<IXMLDOMNode> pNewConsoleOut;
pSettingsDoc->createElement(CComBSTR(L"console"), &pNewConsoleElement);
XmlHelper::SetAttribute(pNewConsoleElement, CComBSTR(L"shell"), (*itTab)->strShell);
XmlHelper::SetAttribute(pNewConsoleElement, CComBSTR(L"init_dir"), (*itTab)->strInitialDir);
XmlHelper::SetAttribute(pNewConsoleElement, CComBSTR(L"run_as_user"), (*itTab)->bRunAsUser);
XmlHelper::SetAttribute(pNewConsoleElement, CComBSTR(L"user"), (*itTab)->strUser);
SettingsBase::AddTextNode(pSettingsDoc, pNewTabElement, CComBSTR(L"\n\t\t\t"));
pNewTabElement->appendChild(pNewConsoleElement, &pNewConsoleOut);
// add <cursor> tag
CComPtr<IXMLDOMElement> pNewCursorElement;
CComPtr<IXMLDOMNode> pNewCursorOut;
pSettingsDoc->createElement(CComBSTR(L"cursor"), &pNewCursorElement);
XmlHelper::SetAttribute(pNewCursorElement, CComBSTR(L"style"), (*itTab)->dwCursorStyle);
XmlHelper::SetAttribute(pNewCursorElement, CComBSTR(L"r"), GetRValue((*itTab)->crCursorColor));
XmlHelper::SetAttribute(pNewCursorElement, CComBSTR(L"g"), GetGValue((*itTab)->crCursorColor));
XmlHelper::SetAttribute(pNewCursorElement, CComBSTR(L"b"), GetBValue((*itTab)->crCursorColor));
SettingsBase::AddTextNode(pSettingsDoc, pNewTabElement, CComBSTR(L"\n\t\t\t"));
pNewTabElement->appendChild(pNewCursorElement, &pNewCursorOut);
// add <background> tag
CComPtr<IXMLDOMElement> pNewBkElement;
CComPtr<IXMLDOMNode> pNewBkOut;
pSettingsDoc->createElement(CComBSTR(L"background"), &pNewBkElement);
XmlHelper::SetAttribute(pNewBkElement, CComBSTR(L"type"), (*itTab)->backgroundImageType);
XmlHelper::SetAttribute(pNewBkElement, CComBSTR(L"r"), GetRValue((*itTab)->crBackgroundColor));
XmlHelper::SetAttribute(pNewBkElement, CComBSTR(L"g"), GetGValue((*itTab)->crBackgroundColor));
XmlHelper::SetAttribute(pNewBkElement, CComBSTR(L"b"), GetBValue((*itTab)->crBackgroundColor));
// add <image> tag
CComPtr<IXMLDOMElement> pNewImageElement;
CComPtr<IXMLDOMNode> pNewImageOut;
pSettingsDoc->createElement(CComBSTR(L"image"), &pNewImageElement);
if ((*itTab)->backgroundImageType == bktypeImage)
{
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"file"), (*itTab)->imageData.strFilename);
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"relative"), (*itTab)->imageData.bRelative ? true : false);
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"extend"), (*itTab)->imageData.bExtend ? true : false);
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"position"), static_cast<DWORD>((*itTab)->imageData.imagePosition));
}
else
{
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"file"), wstring(L""));
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"relative"), false);
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"extend"), false);
XmlHelper::SetAttribute(pNewImageElement, CComBSTR(L"position"), 0);
}
// add <tint> tag
CComPtr<IXMLDOMElement> pNewTintElement;
CComPtr<IXMLDOMNode> pNewTintOut;
pSettingsDoc->createElement(CComBSTR(L"tint"), &pNewTintElement);
XmlHelper::SetAttribute(pNewTintElement, CComBSTR(L"opacity"), (*itTab)->imageData.byTintOpacity);
XmlHelper::SetAttribute(pNewTintElement, CComBSTR(L"r"), GetRValue((*itTab)->imageData.crTint));
XmlHelper::SetAttribute(pNewTintElement, CComBSTR(L"g"), GetGValue((*itTab)->imageData.crTint));
XmlHelper::SetAttribute(pNewTintElement, CComBSTR(L"b"), GetBValue((*itTab)->imageData.crTint));
SettingsBase::AddTextNode(pSettingsDoc, pNewImageElement, CComBSTR(L"\n\t\t\t\t\t"));
pNewImageElement->appendChild(pNewTintElement, &pNewTintOut);
SettingsBase::AddTextNode(pSettingsDoc, pNewImageElement, CComBSTR(L"\n\t\t\t\t"));
SettingsBase::AddTextNode(pSettingsDoc, pNewBkElement, CComBSTR(L"\n\t\t\t\t"));
pNewBkElement->appendChild(pNewImageElement, &pNewImageOut);
SettingsBase::AddTextNode(pSettingsDoc, pNewBkElement, CComBSTR(L"\n\t\t\t"));
SettingsBase::AddTextNode(pSettingsDoc, pNewTabElement, CComBSTR(L"\n\t\t\t"));
pNewTabElement->appendChild(pNewBkElement, &pNewBkOut);
SettingsBase::AddTextNode(pSettingsDoc, pNewTabElement, CComBSTR(L"\n\t\t"));
pTabsElement->appendChild(pNewTabElement, &pNewTabOut);
// this is just for pretty printing
if (itTab == itLastTab)
{
SettingsBase::AddTextNode(pSettingsDoc, pTabsElement, CComBSTR(L"\n\t"));
}
else
{
SettingsBase::AddTextNode(pSettingsDoc, pTabsElement, CComBSTR(L"\n\t\t"));
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void TabSettings::SetDefaults(const wstring& defaultShell, const wstring& defaultInitialDir)
{
strDefaultShell = defaultShell;
strDefaultInitialDir= defaultInitialDir;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
SettingsHandler::SettingsHandler()
: m_pSettingsDocument()
, m_strSettingsPath(L"")
, m_strSettingsFileName(L"")
, m_settingsDirType(dirTypeExe)
, m_consoleSettings()
, m_appearanceSettings()
, m_behaviorSettings()
, m_hotKeys()
, m_mouseSettings()
, m_tabSettings()
{
}
SettingsHandler::~SettingsHandler()
{
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool SettingsHandler::LoadSettings(const wstring& strSettingsFileName)
{
HRESULT hr = S_OK;
size_t pos = strSettingsFileName.rfind(L'\\');
if (pos == wstring::npos)
{
// no path, first try with user's APPDATA dir
wchar_t wszAppData[32767];
::ZeroMemory(wszAppData, sizeof(wszAppData));
::GetEnvironmentVariable(L"APPDATA", wszAppData, _countof(wszAppData));
m_strSettingsFileName = strSettingsFileName;
if (wszAppData == NULL)
{
hr = E_FAIL;
}
else
{
m_strSettingsPath = wstring(wszAppData) + wstring(L"\\Console\\");
m_settingsDirType = dirTypeUser;
hr = XmlHelper::OpenXmlDocument(
GetSettingsFileName(),
m_pSettingsDocument,
m_pSettingsRoot);
}
if (FAILED(hr))
{
m_strSettingsPath = Helpers::GetModulePath(NULL);
m_settingsDirType = dirTypeExe;
hr = XmlHelper::OpenXmlDocument(
GetSettingsFileName(),
m_pSettingsDocument,
m_pSettingsRoot);
if (FAILED(hr)) return false;
}
}
else
{
// settings file name with a path
m_strSettingsPath = strSettingsFileName.substr(0, pos+1);
m_strSettingsFileName = strSettingsFileName.substr(pos+1);
wchar_t wszAppData[32767];
::ZeroMemory(wszAppData, sizeof(wszAppData));
::GetEnvironmentVariable(L"APPDATA", wszAppData, _countof(wszAppData));
if (equals(m_strSettingsPath, wstring(wszAppData) + wstring(L"\\Console\\"), is_iequal()))
{
m_settingsDirType = dirTypeUser;
}
else if (equals(m_strSettingsPath, Helpers::GetModulePath(NULL), is_iequal()))
{
m_settingsDirType = dirTypeExe;
}
else
{
m_settingsDirType = dirTypeCustom;
}
hr = XmlHelper::OpenXmlDocument(
strSettingsFileName,
m_pSettingsDocument,
m_pSettingsRoot);
if (FAILED(hr)) return false;
}
// load settings' sections
m_consoleSettings.Load(m_pSettingsRoot);
m_appearanceSettings.Load(m_pSettingsRoot);
m_behaviorSettings.Load(m_pSettingsRoot);
m_hotKeys.Load(m_pSettingsRoot);
m_mouseSettings.Load(m_pSettingsRoot);
m_tabSettings.SetDefaults(m_consoleSettings.strShell, m_consoleSettings.strInitialDir);
m_tabSettings.Load(m_pSettingsRoot);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool SettingsHandler::SaveSettings()
{
m_consoleSettings.Save(m_pSettingsRoot);
m_appearanceSettings.Save(m_pSettingsRoot);
m_behaviorSettings.Save(m_pSettingsRoot);
m_hotKeys.Save(m_pSettingsRoot);
m_mouseSettings.Save(m_pSettingsRoot);
m_tabSettings.Save(m_pSettingsRoot);
HRESULT hr = m_pSettingsDocument->save(CComVariant(GetSettingsFileName().c_str()));
return SUCCEEDED(hr) ? true : false;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void SettingsHandler::SetUserDataDir(SettingsDirType settingsDirType)
{
if (settingsDirType == dirTypeExe)
{
m_strSettingsPath = Helpers::GetModulePath(NULL);
}
else if (settingsDirType == dirTypeUser)
{
wchar_t wszAppData[32767];
::ZeroMemory(wszAppData, sizeof(wszAppData));
::GetEnvironmentVariable(L"APPDATA", wszAppData, _countof(wszAppData));
m_strSettingsPath = wstring(wszAppData) + wstring(L"\\Console\\");
::CreateDirectory(m_strSettingsPath.c_str(), NULL);
}
m_settingsDirType = settingsDirType;
}
//////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | [
[
[
1,
1899
]
]
] |
c56a74a3357c5da23ff5271e58fa6ca228699ebc | 032ea9816579a9869070a285d0224f95ba6a767b | /3dProject/trunk/Necromancer.cpp | f90fbfb89e5604224ecab814bea93979f6198df8 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | sennheiser1986/oglproject | 3577bae81c0e0b75001bde57b8628d59c8a5c3cf | d975ed5a4392036dace4388e976b88fc4280a116 | refs/heads/master | 2021-01-13T17:05:14.740056 | 2010-06-01T15:48:38 | 2010-06-01T15:48:38 | 39,767,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | cpp | /*
* 3dProject
* Geert d'Hoine
* (c) 2010
*/
#include <iostream>
#include "Necromancer.h"
using namespace std;
Necromancer::Necromancer(void)
{
}
Necromancer::~Necromancer(void)
{
}
Necromancer::Necromancer(float xIn, float yIn, float zIn)
: Hunter(xIn, yIn, zIn) {
init();
}
void Necromancer::init() {
model = MD2Model::load("usmc.md2");
model->setAnimation("run");
previousAnimTime = clock();
speed = 2;
setHeight(15);
setWidth(10);
}
void Necromancer::draw() {
glPushMatrix();
glTranslatef(x, y+8.5, z);
if(isHit()) {
glEnable(GL_COLOR_MATERIAL);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(getWidth(), 32,32);
glColor3f(1.0f, 1.0f, 1.0f);
glDisable(GL_COLOR_MATERIAL);
} else {
glRotatef(-90, 1, 0, 0);
glRotatef(yaw + 90, 0.0f, 0.0f, 1.0f);
glScalef(0.35f, 0.35f, 0.35f);
clock_t currentTime = clock();
float timeDiff = (float)(currentTime - previousAnimTime) / CLOCKS_PER_SEC;
model->advance(timeDiff);
previousAnimTime = currentTime;
model->draw();
}
glPopMatrix();
}
| [
"fionnghall@444a4038-2bd8-11df-954b-21e382534593"
] | [
[
[
1,
57
]
]
] |
c9ce910cb3a6a203b04169be6382fb1a27a3affb | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/messages/messages_sender.hpp | a44f203262d113b54dd32308c41ee13e8ba37a3d | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 747 | hpp | #ifndef MESSAGES_SENDER_HPP
#define MESSAGES_SENDER_HPP
#include <string>
#include "core/buffer/buffer_fwd.hpp"
#include "messages_writers.hpp"
class messages_sender {
buffer_ptr_c_t buffer_ptr_c;
public:
messages_sender(buffer_ptr_c_t const& buffer_ptr_c);
~messages_sender();
messages_sender const& operator()(std::string const& value, msg_dests const& dests) const;
template <typename manipulator_t>
inline messages_sender const& operator()(std::string const& value, manipulator_t const& manipulator) const {
return operator()(value, msg_dests() + manipulator);
}
};
/*
Можно использовать так:
todo: написать :)
*/
#endif // MESSAGES_SENDER_HPP
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
24
]
]
] |
e25d1dc021bdef7e34964b5e25f2f3b59e239f2b | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/SystemTray.h | 130b428c2a05624238326696403f19092009ddda | [] | no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,255 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#ifndef _INCLUDED_SYSTEMTRAY_H_
#define _INCLUDED_SYSTEMTRAY_H_
#ifdef NOTIFYICONDATA_V1_SIZE // If NOTIFYICONDATA_V1_SIZE, then we can use fun stuff
#define SYSTEMTRAY_USEW2K
#else
#define NIIF_NONE 0
#endif
// #include <afxwin.h>
#include <afxtempl.h>
#include <afxdisp.h> // COleDateTime
/////////////////////////////////////////////////////////////////////////////
// CSystemTray window
class CSystemTray : public CWnd
{
// Construction/destruction
public:
CSystemTray();
CSystemTray(CWnd* pWnd, UINT uCallbackMessage, LPCTSTR szTip, HICON icon, UINT uID,
BOOL bhidden = FALSE,
LPCTSTR szBalloonTip = NULL, LPCTSTR szBalloonTitle = NULL,
DWORD dwBalloonIcon = NIIF_NONE, UINT uBalloonTimeout = 10);
virtual ~CSystemTray();
DECLARE_DYNAMIC(CSystemTray)
// Operations
public:
BOOL Enabled() { return m_bEnabled; }
BOOL Visible() { return !m_bHidden; }
// Create the tray icon
BOOL Create(CWnd* pParent, UINT uCallbackMessage, LPCTSTR szTip, HICON icon, UINT uID,
BOOL bHidden = FALSE,
LPCTSTR szBalloonTip = NULL, LPCTSTR szBalloonTitle = NULL,
DWORD dwBalloonIcon = NIIF_NONE, UINT uBalloonTimeout = 10,
BOOL bShowToolTip = TRUE);
// Change or retrieve the Tooltip text
BOOL SetTooltipText(LPCTSTR pszTooltipText);
BOOL SetTooltipText(UINT nID);
CString GetTooltipText() const;
// Change or retrieve the icon displayed
BOOL SetIcon(HICON hIcon);
BOOL SetIcon(LPCTSTR lpszIconName);
BOOL SetIcon(UINT nIDResource);
BOOL SetStandardIcon(LPCTSTR lpIconName);
BOOL SetStandardIcon(UINT nIDResource);
HICON GetIcon() const;
void SetFocus();
BOOL HideIcon();
BOOL ShowIcon();
BOOL AddIcon();
BOOL RemoveIcon();
BOOL MoveToRight();
BOOL ShowBalloon(LPCTSTR szText, LPCTSTR szTitle = NULL,
DWORD dwIcon = NIIF_NONE, UINT uTimeout = 10);
// For icon animation
BOOL SetIconList(UINT uFirstIconID, UINT uLastIconID);
BOOL SetIconList(HICON* pHIconList, UINT nNumIcons);
BOOL Animate(UINT nDelayMilliSeconds, int nNumSeconds = -1);
BOOL StepAnimation();
BOOL StopAnimation();
// Change menu default item
void GetMenuDefaultItem(UINT& uItem, BOOL& bByPos);
BOOL SetMenuDefaultItem(UINT uItem, BOOL bByPos);
// Change or retrieve the window to send notification messages to
BOOL SetNotificationWnd(CWnd* pNotifyWnd);
CWnd* GetNotificationWnd() const;
// Change or retrieve the window to send menu commands to
BOOL SetTargetWnd(CWnd* pTargetWnd);
CWnd* GetTargetWnd() const;
// Change or retrieve notification messages sent to the window
BOOL SetCallbackMessage(UINT uCallbackMessage);
UINT GetCallbackMessage() const;
UINT_PTR GetTimerID() const { return m_nTimerID; }
// Static functions
public:
static void MinimiseToTray(CWnd* pWnd, BOOL bForceAnimation = FALSE);
static void MaximiseFromTray(CWnd* pWnd, BOOL bForceAnimation = FALSE);
public:
// Default handler for tray notification message
virtual LRESULT OnTrayNotification(WPARAM uID, LPARAM lEvent);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSystemTray)
protected:
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
protected:
void Initialise();
void InstallIconPending();
virtual void CustomizeMenu(CMenu*) {} // Used for customizing the menu
// Implementation
protected:
NOTIFYICONDATA m_tnd;
BOOL m_bEnabled; // does O/S support tray icon?
BOOL m_bHidden; // Has the icon been hidden?
BOOL m_bRemoved; // Has the icon been removed?
BOOL m_bShowIconPending; // Show the icon once tha taskbar has been created
BOOL m_bWin2K; // Use new W2K features?
CWnd* m_pTargetWnd; // Window that menu commands are sent
CArray<HICON, HICON> m_IconList;
UINT_PTR m_uIDTimer;
INT_PTR m_nCurrentIcon;
COleDateTime m_StartTime;
UINT m_nAnimationPeriod;
HICON m_hSavedIcon;
UINT m_DefaultMenuItemID;
BOOL m_DefaultMenuItemByPos;
UINT m_uCreationFlags;
// Static data
protected:
static BOOL RemoveTaskbarIcon(CWnd* pWnd);
static const UINT m_nTimerID;
static UINT m_nMaxTooltipLength;
static const UINT m_nTaskbarCreatedMsg;
static CWnd m_wndInvisible;
static BOOL GetW2K();
#ifndef _WIN32_WCE
static void GetTrayWndRect(LPRECT lprect);
static BOOL GetDoWndAnimation();
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CSystemTray)
afx_msg void OnTimer(UINT nIDEvent);
//}}AFX_MSG
#ifndef _WIN32_WCE
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
#endif
LRESULT OnTaskbarCreated(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
#endif
/////////////////////////////////////////////////////////////////////////////
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
186
]
]
] |
57b5f5f95cae52c9d42320433e02be38b98be648 | 3187b0dd0d7a7b83b33c62357efa0092b3943110 | /src/dlib/gui_widgets/base_widgets_abstract.h | 397e7f8a221153d8b1cb87d542e70102b3c28b4b | [
"BSL-1.0"
] | permissive | exi/gravisim | 8a4dad954f68960d42f1d7da14ff1ca7a20e92f2 | 361e70e40f58c9f5e2c2f574c9e7446751629807 | refs/heads/master | 2021-01-19T17:45:04.106839 | 2010-10-22T09:11:24 | 2010-10-22T09:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,149 | h | // Copyright (C) 2005 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_BASE_WIDGETs_ABSTRACT_
#ifdef DLIB_BASE_WIDGETs_ABSTRACT_
#include "fonts_abstract.h"
#include "drawable_abstract.h"
#include "../gui_core.h"
#include <string>
namespace dlib
{
/*!
GENERAL REMARKS
This file contains objects that are useful for creating complex drawable
widgets.
THREAD SAFETY
All objects and functions defined in this file are thread safe. You may
call them from any thread without serializing access to them.
EVENT HANDLERS
If you derive from any of the drawable objects and redefine any of the on_*()
event handlers then you should ensure that your version calls the same event
handler in the base object so that the base class part of your object will also
be able to process the event.
Also note that all event handlers, including the user registered callback
functions, are executed in the event handling thread.
!*/
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class dragable
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class dragable : public drawable
{
/*!
INITIAL VALUE
dragable_area() == an initial value for its type
WHAT THIS OBJECT REPRESENTS
This object represents a drawable object that is dragable by the mouse.
You use it by inheriting from it and defining the draw() method and any
of the on_*() event handlers you need.
This object is dragable by the user when is_enabled() == true and
not dragable otherwise.
!*/
public:
dragable(
drawable_window& w,
unsigned long events = 0
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
- This object will not receive any events or draw() requests until
enable_events() is called
- the events flags are passed on to the drawable object's
constructor.
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~dragable(
) = 0;
/*!
ensures
- all resources associated with *this have been released
!*/
rectangle dragable_area (
) const;
/*!
ensures
- returns the area that this dragable can be dragged around in.
!*/
void set_dragable_area (
const rectangle& area
);
/*!
ensures
- #dragable_area() == area
!*/
protected:
// does nothing by default
virtual void on_drag (
){}
/*!
requires
- enable_events() has been called
- is_enabled() == true
- is_hidden() == false
- mutex drawable::m is locked
- is called when the user drags this object
- get_rect() == the rectangle that defines the new position
of this object.
ensures
- does not change the state of mutex drawable::m.
!*/
private:
// restricted functions
dragable(dragable&); // copy constructor
dragable& operator=(dragable&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class mouse_over_event
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class mouse_over_event : public drawable
{
/*!
INITIAL VALUE
is_mouse_over() == false
WHAT THIS OBJECT REPRESENTS
This object represents a drawable object with the additoin of two events
that will alert you when the mouse enters or leaves your drawable object.
You use it by inheriting from it and defining the draw() method and any
of the on_*() event handlers you need.
!*/
public:
mouse_over_event(
drawable_window& w,
unsigned long events = 0
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
- #*this will not receive any events or draw() requests until
enable_events() is called
- the events flags are passed on to the drawable object's
constructor.
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~mouse_over_event(
) = 0;
/*!
ensures
- all resources associated with *this have been released
!*/
protected:
bool is_mouse_over (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- if (the mouse is currently over this widget) then
- returns true
- else
- returns false
!*/
// does nothing by default
virtual void on_mouse_over (
){}
/*!
requires
- enable_events() has been called
- mutex drawable::m is locked
- is_enabled() == true
- is_hidden() == false
- is called whenever this object transitions from the state where
is_mouse_over() == false to is_mouse_over() == true
ensures
- does not change the state of mutex drawable::m.
!*/
// does nothing by default
virtual void on_mouse_not_over (
){}
/*!
requires
- enable_events() has been called
- mutex drawable::m is locked
- is_enabled() == true
- is_hidden() == false
- is called whenever this object transitions from the state where
is_mouse_over() == true to is_mouse_over() == false
ensures
- does not change the state of mutex drawable::m.
!*/
private:
// restricted functions
mouse_over_event(mouse_over_event&); // copy constructor
mouse_over_event& operator=(mouse_over_event&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class button_action
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class button_action : public mouse_over_event
{
/*!
INITIAL VALUE
is_depressed() == false
WHAT THIS OBJECT REPRESENTS
This object represents the clicking action of a push button. It provides
simple callbacks that can be used to make various kinds of button
widgets.
You use it by inheriting from it and defining the draw() method and any
of the on_*() event handlers you need.
!*/
public:
button_action(
drawable_window& w,
unsigned long events = 0
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
- #*this will not receive any events or draw() requests until
enable_events() is called
- the events flags are passed on to the drawable object's
constructor.
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~button_action(
) = 0;
/*!
ensures
- all resources associated with *this have been released
!*/
protected:
bool is_depressed (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- if (this button is currently in a depressed state) then
- the user has left clicked on this drawable and is still
holding the left mouse button down over it.
- returns true
- else
- returns false
!*/
// does nothing by default
virtual void on_button_down (
){}
/*!
requires
- enable_events() has been called
- mutex drawable::m is locked
- is_enabled() == true
- is_hidden() == false
- the area in parent_window() defined by get_rect() has been invalidated.
(This means you don't have to call invalidate_rectangle())
- is called whenever this object transitions from the state where
is_depressed() == false to is_depressed() == true
ensures
- does not change the state of mutex drawable::m.
!*/
// does nothing by default
virtual void on_button_up (
bool mouse_over
){}
/*!
requires
- enable_events() has been called
- mutex drawable::m is locked
- is_enabled() == true
- is_hidden() == false
- the area in parent_window() defined by get_rect() has been invalidated.
(This means you don't have to call invalidate_rectangle())
- is called whenever this object transitions from the state where
is_depressed() == true to is_depressed() == false
- if (the mouse was over this button when this event occurred) then
- mouse_over == true
- else
- mouse_over == false
ensures
- does not change the state of mutex drawable::m.
!*/
private:
// restricted functions
button_action(button_action&); // copy constructor
button_action& operator=(button_action&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class arrow_button
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class arrow_button : public button_action
{
/*!
INITIAL VALUE
direction() == a value given to the constructor.
WHAT THIS OBJECT REPRESENTS
This object represents a push button with an arrow in the middle.
When this object is disabled it means it will not respond to user clicks.
!*/
public:
enum arrow_direction
{
UP,
DOWN,
LEFT,
RIGHT
};
arrow_button(
drawable_window& w,
arrow_direction dir
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #direction() == dir
- #parent_window() == w
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~arrow_button(
);
/*!
ensures
- all resources associated with *this have been released
!*/
arrow_direction direction (
) const;
/*!
ensures
- returns the direction that this arrow_button's arrow points
!*/
void set_direction (
arrow_direction new_direction
);
/*!
ensures
- #direction() == new_direction
!*/
void set_size (
unsigned long width_,
unsigned long height_
);
/*!
ensures
- #width() == width_
- #height() == height_
- #top() == top()
- #left() == left()
- i.e. The location of the upper left corner of this button stays the
same but its width and height are modified
!*/
bool is_depressed (
) const;
/*!
ensures
- if (this button is currently in a depressed state) then
- the user has left clicked on this drawable and is still
holding the left mouse button down over it.
- returns true
- else
- returns false
!*/
template <
typename T
>
void set_button_down_handler (
T& object,
void (T::*event_handler)()
);
/*!
requires
- event_handler is a valid pointer to a member function in T
ensures
- The event_handler function is called whenever this object transitions
from the state where is_depressed() == false to is_depressed() == true
- any previous calls to this function are overridden by this new call.
(i.e. you can only have one event handler associated with this
event at a time)
throws
- std::bad_alloc
!*/
template <
typename T
>
void set_button_up_handler (
T& object,
void (T::*event_handler)(bool mouse_over)
);
/*!
requires
- event_handler is a valid pointer to a member function in T
ensures
- The event_handler function is called whenever this object transitions
from the state where is_depressed() == true to is_depressed() == false.
furthermore:
- if (the mouse was over this button when this event occurred) then
- mouse_over == true
- else
- mouse_over == false
- any previous calls to this function are overridden by this new call.
(i.e. you can only have one event handler associated with this
event at a time)
throws
- std::bad_alloc
!*/
private:
// restricted functions
arrow_button(arrow_button&); // copy constructor
arrow_button& operator=(arrow_button&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class scroll_bar
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class scroll_bar : public drawable
{
/*!
INITIAL VALUE
orientation() == a value given to the constructor.
max_slider_pos() == 0
slider_pos() == 0
jump_size() == 10
WHAT THIS OBJECT REPRESENTS
This object represents a scroll bar. The slider_pos() of the scroll bar
ranges from 0 to max_slider_pos(). The 0 position of the scroll_bar is
in the top or left side of the scroll_bar depending on its orientation.
When this object is disabled it means it will not respond to user clicks.
!*/
public:
enum bar_orientation
{
HORIZONTAL,
VERTICAL
};
scroll_bar(
drawable_window& w,
bar_orientation orientation
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #orientation() == orientation
- #parent_window() == w
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~scroll_bar(
);
/*!
ensures
- all resources associated with *this have been released
!*/
bar_orientation orientation (
) const;
/*!
ensures
- returns the orientation of this scroll_bar
!*/
void set_orientation (
bar_orientation new_orientation
);
/*!
ensures
- #orientation() == new_orientation
!*/
void set_length (
unsigned long length,
);
/*!
ensures
- if (orientation() == HORIZONTAL) then
- #width() == max(length,1)
- else
- #height() == max(length,1)
!*/
long max_slider_pos (
) const;
/*!
ensures
- returns the maximum value that slider_pos() can take.
!*/
void set_max_slider_pos (
long mpos
);
/*!
ensures
- if (mpos < 0) then
- #max_slider_pos() == 0
- else
- #max_slider_pos() == mpos
- if (slider_pos() > #max_slider_pos()) then
- #slider_pos() == #max_slider_pos()
- else
- #slider_pos() == slider_pos()
!*/
void set_slider_pos (
unsigned long pos
);
/*!
ensures
- if (pos < 0) then
- #slider_pos() == 0
- else if (pos > max_slider_pos()) then
- #slider_pos() == max_slider_pos()
- else
- #slider_pos() == pos
!*/
long slider_pos (
) const;
/*!
ensures
- returns the current position of the slider box within the scroll bar.
!*/
long jump_size (
) const;
/*!
ensures
- returns the number of positions that the slider bar will jump when the
user clicks on the empty gaps above or below the slider bar.
(note that the slider will jump less than the jump size if it hits the
end of the scroll bar)
!*/
void set_jump_size (
long js
);
/*!
ensures
- if (js < 1) then
- #jump_size() == 1
- else
- #jump_size() == js
!*/
template <
typename T
>
void set_scroll_handler (
T& object,
void (T::*event_handler)()
);
/*!
requires
- event_handler is a valid pointer to a member function in T
ensures
- The event_handler function is called whenever the user causes the slider box
to move.
- This event is NOT triggered by calling set_slider_pos()
- any previous calls to this function are overridden by this new call.
(i.e. you can only have one event handler associated with this
event at a time)
throws
- std::bad_alloc
!*/
private:
// restricted functions
scroll_bar(scroll_bar&); // copy constructor
scroll_bar& operator=(scroll_bar&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class widget_group
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class widget_group : public drawable
{
/*!
INITIAL VALUE
size() == 0
get_rect().is_empty() == true
left() == 0
top() == 0
WHAT THIS OBJECT REPRESENTS
This object represents a grouping of drawable widgets. It doesn't draw
anything itself, rather it lets you manipulate the position, enabled
status, and visibility of a set of widgets as a group.
!*/
public:
widget_group(
drawable_window& w
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~widget_group(
);
/*!
ensures
- all resources associated with *this have been released.
!*/
void empty (
);
/*!
ensures
- #size() == 0
!*/
void fit_to_contents (
);
/*!
ensures
- does not change the position of this object.
(i.e. the upper left corner of get_rect() remains at the same position)
- if (size() == 0) then
- #get_rect().is_empty() == true
- else
- #get_rect() will be the smallest rectangle that contains all the
widgets in this group and the upper left corner of get_rect().
!*/
unsigned long size (
) const;
/*!
ensures
- returns the number of widgets currently in *this.
!*/
void add (
drawable& widget,
unsigned long x,
unsigned long y
);
/*!
ensures
- #is_member(widget) == true
- if (is_member(widget) == false) then
- #size() == size() + 1
- else
- #size() == size()
- The following conditions apply to this function as well as to all of the
following functions so long as is_member(widget) == true:
enable(), disable(), hide(), show(), set_z_order(), and set_pos().
- #widget.left() == left()+x
- #widget.width() == widget.width()
- #widget.top() == top()+y
- #widget.height() == widget.height()
- #widget.is_hidden() == is_hidden()
- #widget.is_enabled() == is_enabled()
- #widget.z_order() == z_order()
throws
- std::bad_alloc
!*/
bool is_member (
const drawable& widget
) const;
/*!
ensures
- returns true if widget is currently in this object, returns false otherwise.
!*/
void remove (
const drawable& widget
);
/*!
ensures
- #is_member(widget) == false
- if (is_member(widget) == true) then
- #size() == size() - 1
- else
- #size() == size()
!*/
protected:
// this object doesn't draw anything but also isn't abstract
void draw (
const canvas& c
) const {}
private:
// restricted functions
widget_group(widget_group&); // copy constructor
widget_group& operator=(widget_group&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class image_widget
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class image_widget : public dragable
{
/*!
INITIAL VALUE
dragable_area() == an initial value for its type.
This object isn't displaying anything.
WHAT THIS OBJECT REPRESENTS
This object represents a dragable image. You give it an image to display
by calling set_image().
Also note that initially the dragable area is empty so it won't be
dragable unless you call set_dragable_area() to some non-empty region.
The image is drawn such that:
- the pixel img[0][0] is the upper left corner of the image.
- the pixel img[img.nr()-1][0] is the lower left corner of the image.
- the pixel img[0][img.nc()-1] is the upper right corner of the image.
- the pixel img[img.nr()-1][img.nc()-1] is the lower right corner of the image.
!*/
public:
image_widget(
drawable_window& w
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~image_widget(
);
/*!
ensures
- all resources associated with *this have been released
!*/
template <
typename image_type
>
void set_image (
const image_type& img
);
/*!
requires
- image_type == an implementation of array2d/array2d_kernel_abstract.h
- pixel_traits<typename image_type::type> must be defined
ensures
- #width() == img.nc()
- #height() == img.nr()
- #*this widget is now displaying the given image img.
!*/
private:
// restricted functions
image_widget(image_widget&); // copy constructor
image_widget& operator=(image_widget&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// class tooltip
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class tooltip : public mouse_over_event
{
/*!
INITIAL VALUE
- text() == ""
- the tooltip is inactive until the text is changed to
a non-empty string.
WHAT THIS OBJECT REPRESENTS
This object represents a region on a window where if the user
hovers the mouse over this region a tooltip with a message
appears.
!*/
public:
tooltip(
drawable_window& w
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~tooltip(
);
/*!
ensures
- all resources associated with *this have been released
!*/
void set_size (
long width_,
long height_
);
/*!
ensures
- #width() == width_
- #height() == height_
- #top() == top()
- #left() == left()
- i.e. The location of the upper left corner of this widget stays the
same but its width and height are modified
!*/
void set_text (
const std::string& str
);
/*!
ensures
- #text() == str
- activates the tooltip. i.e. after this function the tooltip
will display on the screen when the user hovers the mouse over it
!*/
const std::string text (
) const;
/*!
ensures
- returns the text that is displayed inside this
tooltip
!*/
private:
// restricted functions
tooltip(tooltip&); // copy constructor
tooltip& operator=(tooltip&); // assignment operator
};
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// popup menu stuff
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
class menu_item
{
/*!
WHAT THIS OBJECT REPRESENTS
This is an abstract class that defines the interface a
menu item in a popup_menu must implement.
Note that a menu_item is drawn as 3 separate pieces:
---------------------------------
| left | middle | right |
---------------------------------
Also note that derived classes must be copyable via
their copy constructors.
!*/
public:
virtual ~menu_item() {}
virtual void on_click (
) const {}
/*!
requires
- the mutex drawable::m is locked
- if (has_click_event()) then
- this function is called when the user clicks on this menu_item
!*/
virtual bool has_click_event (
) const { return false; }
/*!
ensures
- if (this menu_item wants to receive on_click events) then
- returns true
- else
- returns false
!*/
virtual unichar get_hot_key (
) const { return 0; }
/*!
ensures
- if (this menu item has a keyboard hot key) then
- returns the unicode value of the key
- else
- returns 0
!*/
virtual rectangle get_left_size (
) const { return rectangle(); } // return empty rect by default
/*!
ensures
- returns the dimensions of the left part of the menu_item
!*/
virtual rectangle get_middle_size (
) const = 0;
/*!
ensures
- returns the dimensions of the middle part of the menu_item
!*/
virtual rectangle get_right_size (
) const { return rectangle(); } // return empty rect by default
/*!
ensures
- returns the dimensions of the right part of the menu_item
!*/
virtual void draw_background (
const canvas& c,
const rectangle& rect,
const bool enabled,
const bool is_selected
) const {}
/*!
requires
- the mutex drawable::m is locked
requires
- c == the canvas to draw on
- rect == the rectangle in which we are to draw the background
- enabled == true if the menu_item is to be drawn enabled
- is_selected == true if the menu_item is to be drawn selected
ensures
- draws the background of the menu_item on the canvas c at the location
given by rect.
!*/
virtual void draw_left (
const canvas& c,
const rectangle& rect,
const bool enabled,
const bool is_selected
) const {}
/*!
requires
- the mutex drawable::m is locked
requires
- c == the canvas to draw on
- rect == the rectangle in which we are to draw the background
- enabled == true if the menu_item is to be drawn enabled
- is_selected == true if the menu_item is to be drawn selected
ensures
- draws the left part of the menu_item on the canvas c at the location
given by rect.
!*/
virtual void draw_middle (
const canvas& c,
const rectangle& rect,
const bool enabled,
const bool is_selected
) const = 0;
/*!
requires
- the mutex drawable::m is locked
requires
- c == the canvas to draw on
- rect == the rectangle in which we are to draw the background
- enabled == true if the menu_item is to be drawn enabled
- is_selected == true if the menu_item is to be drawn selected
ensures
- draws the middle part of the menu_item on the canvas c at the location
given by rect.
!*/
virtual void draw_right (
const canvas& c,
const rectangle& rect,
const bool enabled,
const bool is_selected
) const {}
/*!
requires
- the mutex drawable::m is locked
requires
- c == the canvas to draw on
- rect == the rectangle in which we are to draw the background
- enabled == true if the menu_item is to be drawn enabled
- is_selected == true if the menu_item is to be drawn selected
ensures
- draws the right part of the menu_item on the canvas c at the location
given by rect.
!*/
};
// ----------------------------------------------------------------------------------------
class menu_item_text : public menu_item
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a simple text menu item
!*/
public:
template <
typename T
>
menu_item_text (
const std::string& str,
T& object,
void (T::*on_click_handler)(),
unichar hotkey = 0
);
/*!
ensures
- The text of this menu item will be str
- the on_click_handler function is called on object when this menu_item
clicked by the user.
- #get_hot_key() == hotkey
!*/
};
// ----------------------------------------------------------------------------------------
class menu_item_submenu : public menu_item
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a simple text item intended to be used with
submenus inside a popup_menu.
!*/
public:
menu_item_submenu (
const std::string& str,
unichar hotkey = 0
);
/*!
ensures
- The text of this menu item will be str
clicked by the user.
- #get_hot_key() == hotkey
!*/
};
// ----------------------------------------------------------------------------------------
class menu_item_separator : public menu_item
{
/*!
WHAT THIS OBJECT REPRESENTS
This object is a horizontal separator in a popup menu
!*/
};
// ----------------------------------------------------------------------------------------
class popup_menu : public base_window
{
/*!
INITIAL VALUE
- size() == 0
WHAT THIS OBJECT REPRESENTS
This object represents a popup menu window capable of containing
menu_item objects.
!*/
public:
popup_menu (
);
/*!
ensures
- #*this is properly initialized
throws
- std::bad_alloc
- dlib::thread_error
- dlib::gui_error
!*/
void clear (
);
/*!
ensures
- #*this has its initial value
throws
- std::bad_alloc
if this exception is thrown then *this is unusable
until clear() is called and succeeds
!*/
template <
typename menu_item_type
>
unsigned long add_menu_item (
const menu_item_type& new_item
);
/*!
requires
- menu_item_type == a type that inherits from menu_item
ensures
- adds new_item onto the bottom of this popup_menu.
- returns size()
(This is also the index by which this item can be
referenced by the enable_menu_item() and disable_menu_item()
functions.)
!*/
template <
typename menu_item_type
>
unsigned long add_submenu (
const menu_item_type& new_item,
popup_menu& submenu
);
/*!
requires
- menu_item_type == a type that inherits from menu_item
ensures
- adds new_item onto the bottom of this popup_menu.
- when the user puts the mouse above this menu_item the given
submenu popup_menu will be displayed.
- returns size()
(This is also the index by which this item can be
referenced by the enable_menu_item() and disable_menu_item()
functions.)
!*/
void enable_menu_item (
unsigned long idx
);
/*!
requires
- idx < size()
ensures
- the menu_item in this with the index idx has been enabled
!*/
void disable_menu_item (
unsigned long idx
);
/*!
requires
- idx < size()
ensures
- the menu_item in this with the index idx has been disabled
!*/
unsigned long size (
) const;
/*!
ensures
- returns the number of menu_item objects in this popup_menu
!*/
template <typename T>
void set_on_hide_handler (
T& object,
void (T::*event_handler)()
);
/*!
ensures
- the event_handler function is called on object when this popup_menu
hides itself due to an action by the user.
- Note that you can register multiple handlers for this event.
!*/
void select_first_item (
);
/*!
ensures
- causes this popup menu to highlight the first
menu item that it contains which has a click event
and is enabled.
!*/
bool forwarded_on_keydown (
unsigned long key,
bool is_printable,
unsigned long state
);
/*!
requires
- key, is_printable, and state are the variables from the
base_window::on_keydown() event
ensures
- forwards this keyboard event to this popup window so that it
may deal with keyboard events from other windows.
- if (this popup_menu uses the keyboard event) then
- returns true
- else
- returns false
!*/
private:
// restricted functions
popup_menu(popup_menu&); // copy constructor
popup_menu& operator=(popup_menu&); // assignment operator
};
// ----------------------------------------------------------------------------------------
class zoomable_region : public drawable
{
/*
INITIAL VALUE
- min_zoom_scale() == 0.15
- max_zoom_scale() == 1.0
- zoom_increment() == 0.02
- zoom_scale() == 1.0
WHAT THIS OBJECT REPRESENTS
This object represents a 2D Cartesian graph that you can zoom into and
out of. It is a graphical a widget that draws a rectangle with
a horizontal and vertical scroll bar that allow the user to scroll
around on a Cartesian graph that is much larger than the actual
area occupied by this object on the screen. It also allows
the user to zoom in and out.
To use this object you inherit from it and make use of its public and
protected member functions. It provides functions for converting between
pixel locations and the points in our 2D Cartesian graph so that when the
user is scrolling/zooming the widget you can still determine where
things are to be placed on the screen and what screen pixels correspond
to in the Cartesian graph.
Note that the Cartesian graph in this object is bounded by the point
(0,0), corresponding to the upper left corner when we are zoomed all
the way out, and max_graph_point() which corresponds to the lower right
corner when zoomed all the way out. The value of max_graph_point() is
determined automatically from the size of this object's on screen
rectangle and the value of min_zoom_scale() which determines how far
out you can zoom.
Also note that while vector<double> is used to represent graph points
the z field is always ignored by this object.
*/
public:
zoomable_region (
drawable_window& w,
unsigned long events = 0
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
- This object will not receive any events or draw() requests until
enable_events() is called
- the events flags are passed on to the drawable object's
constructor.
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~zoomable_region (
) = 0;
/*!
ensures
- all resources associated with *this have been released
!*/
void set_zoom_increment (
double zi
);
/*!
ensures
- #zoom_increment() == zi
!*/
double zoom_increment (
) const;
/*!
ensures
- returns the amount by which zoom_scale() is changed when the user
zooms in or out by using the mouse wheel.
!*/
void set_max_zoom_scale (
double ms
);
/*!
ensures
- #max_zoom_scale() == ms
!*/
void set_min_zoom_scale (
double ms
);
/*!
ensures
- #min_zoom_scale() == ms
!*/
double min_zoom_scale (
) const;
/*!
ensures
- returns the minimum allowed value of zoom_scale()
!*/
double max_zoom_scale (
) const;
/*!
ensures
- returns the maximum allowed value of zoom_scale()
!*/
void set_size (
long width,
long height
);
/*!
ensures
- #width() == width_
- #height() == height_
- #top() == top()
- #left() == left()
- i.e. The location of the upper left corner of this button stays the
same but its width and height are modified
!*/
protected:
rectangle display_rect (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns the rectangle on the screen that contains the Cartesian
graph in this widget. I.e. this is the area of this widget minus
the area taken up by the scroll bars and border decorations.
!*/
point graph_to_gui_space (
const vector<double>& graph_point
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns the location of the pixel on the screen that corresponds
to the given point in Cartesian graph space
!*/
vector<double> gui_to_graph_space (
const point& pixel_point
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns the point in Cartesian graph space that corresponds to the given
pixel location
!*/
vector<double> max_graph_point (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns the pixel farthest from the graph point (0,0) that is still
in the graph. I.e. returns the point in graph space that corresponds
to the lower right corner of the display_rect() when we are zoomed
all the way out.
!*/
double zoom_scale (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns a double Z that represents the current zoom.
- Smaller values of Z represent the user zooming out.
- Bigger values of Z represent the user zooming in.
- The default unzoomed case is when Z == 1
- objects should be drawn such that they are zoom_scale()
times their normal size
!*/
void set_zoom_scale (
double new_scale
);
/*!
requires
- mutex drawable::m is locked
ensures
- if (min_zoom_scale() <= new_scale && new_scale <= max_zoom_scale()) then
- #zoom_scale() == new_scale
- invalidates the display_rect() so that it will be redrawn
- else
- #zoom_scale() == zoom_scale()
I.e. this function has no effect
!*/
void center_display_at_graph_point (
const vector<double>& graph_point
);
/*!
requires
- mutex drawable::m is locked
ensures
- causes the given graph point to be centered in the display
if possible
- invalidates the display_rect() so that it will be redrawn
!*/
// ---------------------------- event handlers ----------------------------
// The following event handlers are used in this object. So if you
// use any of them in your derived object you should pass the events
// back to it so that they still operate unless you wish to hijack the
// event for your own reasons (e.g. to override the mouse drag this object
// performs)
void on_wheel_down ();
void on_wheel_up ();
void on_mouse_move ( unsigned long state, long x, long y);
void on_mouse_up ( unsigned long btn, unsigned long state, long x, long y);
void on_mouse_down ( unsigned long btn, unsigned long state, long x, long y, bool is_double_click);
void draw ( const canvas& c) const;
private:
// restricted functions
zoomable_region(zoomable_region&); // copy constructor
zoomable_region& operator=(zoomable_region&); // assignment operator
};
// ----------------------------------------------------------------------------------------
class scrollable_region : public drawable
{
/*!
INITIAL VALUE
- horizontal_scroll_pos() == 0
- horizontal_scroll_increment() == 1
- vertical_scroll_pos() == 0
- vertical_scroll_increment() == 1
- total_rect().empty() == true
WHAT THIS OBJECT REPRESENTS
This object represents a 2D region of arbitrary size that is displayed
within a possibly smaller scrollable gui widget. That is, it is a
graphical a widget that draws a rectangle with a horizontal and vertical
scroll bar that allow the user to scroll around on a region that is much
larger than the actual area occupied by this object on the screen.
To use this object you inherit from it and make use of its public and
protected member functions. It provides a function, total_rect(), that
tells you where the 2D region is on the screen. You draw your stuff
inside total_rect() as you would normally except that you only modify
pixels that are also inside display_rect().
!*/
public:
scrollable_region (
drawable_window& w,
unsigned long events = 0
);
/*!
ensures
- #*this is properly initialized
- #*this has been added to window w
- #parent_window() == w
- This object will not receive any events or draw() requests until
enable_events() is called
- the events flags are passed on to the drawable object's
constructor.
throws
- std::bad_alloc
- dlib::thread_error
!*/
virtual ~scrollable_region (
) = 0;
/*!
ensures
- all resources associated with *this have been released
!*/
void set_size (
unsigned long width,
unsigned long height
);
/*!
ensures
- #width() == width_
- #height() == height_
- #top() == top()
- #left() == left()
- i.e. The location of the upper left corner of this button stays the
same but its width and height are modified
!*/
long horizontal_scroll_pos (
) const;
/*!
ensures
- returns the current position of the horizontal scroll bar.
0 means it is at the far left while bigger values represent
scroll positions closer to the right.
!*/
long vertical_scroll_pos (
) const;
/*!
ensures
- returns the current position of the vertical scroll bar.
0 means it is at the top and bigger values represent scroll positions
closer to the bottom.
!*/
void set_horizontal_scroll_pos (
long pos
);
/*!
ensures
- if (pos is a valid horizontal scroll position) then
- #horizontal_scroll_pos() == pos
- else
- #horizontal_scroll_pos() == the valid scroll position closest to pos
!*/
void set_vertical_scroll_pos (
long pos
);
/*!
ensures
- if (pos is a valid vertical scroll position) then
- #vertical_scroll_pos() == pos
- else
- #vertical_scroll_pos() == the valid scroll position closest to pos
!*/
unsigned long horizontal_scroll_increment (
) const;
/*!
ensures
- returns the number of pixels that total_rect() is moved by when
the horizontal scroll bar moves by one position
!*/
unsigned long vertical_scroll_increment (
) const;
/*!
ensures
- returns the number of pixels that total_rect() is moved by when
the vertical scroll bar moves by one position
!*/
void set_horizontal_scroll_increment (
unsigned long inc
);
/*!
ensures
- #horizontal_scroll_increment() == inc
!*/
void set_vertical_scroll_increment (
unsigned long inc
);
/*!
ensures
- #vertical_scroll_increment() == inc
!*/
protected:
rectangle display_rect (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns the rectangle on the screen that contains the scrollable
area in this widget. I.e. this is the area of this widget minus
the area taken up by the scroll bars and border decorations.
!*/
void set_total_rect_size (
unsigned long width,
unsigned long height
);
/*!
requires
- mutex drawable::m is locked
ensures
- #total_rect().width() == width
- #total_rect().height() == height
!*/
const rectangle& total_rect (
) const;
/*!
requires
- mutex drawable::m is locked
ensures
- returns a rectangle that represents the entire scrollable
region inside this widget, even the parts that are outside
this->rect.
!*/
void scroll_to_rect (
const rectangle& r
);
/*!
requires
- mutex drawable::m is locked
ensures
- adjusts the scroll bars of this object so that the rectangle
r is displayed in the display_rect() (or as close to being
displayed as possible if r is outside of total_rect())
!*/
// ---------------------------- event handlers ----------------------------
// The following event handlers are used in this object. So if you
// use any of them in your derived object you should pass the events
// back to it so that they still operate unless you wish to hijack the
// event for your own reasons (e.g. to override the mouse wheel action
// this object performs)
void on_wheel_down ();
void on_wheel_up ();
void draw (const canvas& c) const;
private:
// restricted functions
scrollable_region(scrollable_region&); // copy constructor
scrollable_region& operator=(scrollable_region&); // assignment operator
};
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_BASE_WIDGETs_ABSTRACT_
| [
"[email protected]"
] | [
[
[
1,
1735
]
]
] |
89f1e134d0aaba40beb5b3961aa67c7cb5062955 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/test/test/test_tools_test.cpp | 455cb9f8072bebc90d3ed5df163a88b79c156557 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,648 | cpp | // (C) Copyright Gennadiy Rozental 2001-2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 54633 $
//
// Description : tests all Test Tools but output_test_stream
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/output_test_stream.hpp>
#include <boost/test/execution_monitor.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#include <boost/test/output/compiler_log_formatter.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
// Boost
#include <boost/bind.hpp>
// STL
#include <iostream>
#include <iomanip>
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable: 4702) // unreachable code
#endif
using namespace boost::unit_test;
using namespace boost::test_tools;
//____________________________________________________________________________//
#define CHECK_CRITICAL_TOOL_USAGE( tool_usage ) \
{ \
bool throw_ = false; \
try { \
tool_usage; \
} catch( boost::execution_aborted const& ) { \
throw_ = true; \
} \
\
BOOST_CHECK_MESSAGE( throw_, "not aborted" ); \
} \
/**/
//____________________________________________________________________________//
class bool_convertible
{
struct Tester {};
public:
operator Tester*() const { return static_cast<Tester*>( 0 ) + 1; }
};
//____________________________________________________________________________//
struct shorten_lf : public boost::unit_test::output::compiler_log_formatter
{
void print_prefix( std::ostream& output, boost::unit_test::const_string, std::size_t line )
{
output << line << ": ";
}
};
//____________________________________________________________________________//
std::string match_file_name( "./test_files/test_tools_test.pattern" );
std::string save_file_name( "test_tools_test.pattern" );
output_test_stream& ots()
{
static boost::shared_ptr<output_test_stream> inst;
if( !inst ) {
inst.reset(
framework::master_test_suite().argc <= 1
? new output_test_stream( runtime_config::save_pattern() ? save_file_name : match_file_name, !runtime_config::save_pattern() )
: new output_test_stream( framework::master_test_suite().argv[1], !runtime_config::save_pattern() ) );
}
return *inst;
}
//____________________________________________________________________________//
#define TEST_CASE( name ) \
void name ## _impl(); \
void name ## _impl_defer(); \
\
BOOST_AUTO_TEST_CASE( name ) \
{ \
test_case* impl = make_test_case( &name ## _impl, #name ); \
\
unit_test_log.set_stream( ots() ); \
unit_test_log.set_threshold_level( log_nothing ); \
unit_test_log.set_formatter( new shorten_lf ); \
framework::run( impl ); \
\
unit_test_log.set_threshold_level( \
runtime_config::log_level() != invalid_log_level \
? runtime_config::log_level() \
: log_all_errors ); \
unit_test_log.set_format( runtime_config::log_format());\
unit_test_log.set_stream( std::cout ); \
BOOST_CHECK( ots().match_pattern() ); \
} \
\
void name ## _impl() \
{ \
unit_test_log.set_threshold_level( log_all_errors ); \
\
name ## _impl_defer(); \
\
unit_test_log.set_threshold_level( log_nothing ); \
} \
\
void name ## _impl_defer() \
/**/
//____________________________________________________________________________//
TEST_CASE( test_BOOST_WARN )
{
unit_test_log.set_threshold_level( log_warnings );
BOOST_WARN( sizeof(int) == sizeof(short) );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_WARN( sizeof(unsigned char) == sizeof(char) );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK )
{
// check correct behavior in if clause
if( true )
BOOST_CHECK( true );
// check correct behavior in else clause
if( false )
{}
else
BOOST_CHECK( true );
bool_convertible bc;
BOOST_CHECK( bc );
int i=2;
BOOST_CHECK( false );
BOOST_CHECK( 1==2 );
BOOST_CHECK( i==1 );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_CHECK( i==2 );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_REQUIRE )
{
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( true ) );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( false ) );
int j = 3;
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( j > 5 ) );
unit_test_log.set_threshold_level( log_successful_tests );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( j < 5 ) );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_WARN_MESSAGE )
{
BOOST_WARN_MESSAGE( sizeof(int) == sizeof(short), "memory won't be used efficiently" );
int obj_size = 33;
BOOST_WARN_MESSAGE( obj_size <= 8,
"object size " << obj_size << " is too big to be efficiently passed by value" );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_WARN_MESSAGE( obj_size > 8, "object size " << obj_size << " is too small" );
}
//____________________________________________________________________________//
boost::test_tools::predicate_result
test_pred1()
{
boost::test_tools::predicate_result res( false );
res.message() << "Some explanation";
return res;
}
TEST_CASE( test_BOOST_CHECK_MESSAGE )
{
BOOST_CHECK_MESSAGE( 2+2 == 5, "Well, may be that what I believe in" );
BOOST_CHECK_MESSAGE( test_pred1(), "Checking predicate failed" );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_CHECK_MESSAGE( 2+2 == 4, "Could it fail?" );
int i = 1;
int j = 2;
std::string msg = "some explanation";
BOOST_CHECK_MESSAGE( i > j, "Comparing " << i << " and " << j << ": " << msg );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_REQUIRE_MESSAGE )
{
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_MESSAGE( false, "Here we should stop" ) );
unit_test_log.set_threshold_level( log_successful_tests );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_MESSAGE( true, "That's OK" ) );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_ERROR )
{
BOOST_ERROR( "Fail to miss an error" );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_FAIL )
{
CHECK_CRITICAL_TOOL_USAGE( BOOST_FAIL( "No! No! Show must go on." ) );
}
//____________________________________________________________________________//
struct my_exception {
explicit my_exception( int ec = 0 ) : m_error_code( ec ) {}
int m_error_code;
};
bool is_critical( my_exception const& ex ) { return ex.m_error_code < 0; }
TEST_CASE( test_BOOST_CHECK_THROW )
{
int i=0;
BOOST_CHECK_THROW( i++, my_exception );
unit_test_log.set_threshold_level( log_warnings );
BOOST_WARN_THROW( i++, my_exception );
unit_test_log.set_threshold_level( log_all_errors );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_THROW( i++, my_exception ) );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_CHECK_THROW( throw my_exception(), my_exception ); // unreachable code warning is expected
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_EXCEPTION )
{
BOOST_CHECK_EXCEPTION( throw my_exception( 1 ), my_exception, is_critical ); // unreachable code warning is expected
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_CHECK_EXCEPTION( throw my_exception( -1 ), my_exception, is_critical ); // unreachable code warning is expected
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_NO_THROW )
{
int i=0;
BOOST_CHECK_NO_THROW( i++ );
BOOST_CHECK_NO_THROW( throw my_exception() ); // unreachable code warning is expected
}
//____________________________________________________________________________//
struct B {
B( int i ) : m_i( i ) {}
int m_i;
};
bool operator==( B const& b1, B const& b2 ) { return b1.m_i == b2.m_i; }
std::ostream& operator<<( std::ostream& str, B const& b ) { return str << "B(" << b.m_i << ")"; }
//____________________________________________________________________________//
struct C {
C( int i, int id ) : m_i( i ), m_id( id ) {}
int m_i;
int m_id;
};
boost::test_tools::predicate_result
operator==( C const& c1, C const& c2 )
{
boost::test_tools::predicate_result res( c1.m_i == c2.m_i && c1.m_id == c2.m_id );
if( !res ) {
if( c1.m_i != c2.m_i )
res.message() << "Index mismatch";
else
res.message() << "Id mismatch";
}
return res;
}
std::ostream& operator<<( std::ostream& str, C const& c ) { return str << "C(" << c.m_i << ',' << c.m_id << ")"; }
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_EQUAL )
{
int i=1;
int j=2;
BOOST_CHECK_EQUAL( i, j );
BOOST_CHECK_EQUAL( ++i, j );
BOOST_CHECK_EQUAL( i++, j );
char const* str1 = "test1";
char const* str2 = "test12";
BOOST_CHECK_EQUAL( str1, str2 );
unit_test_log.set_threshold_level( log_successful_tests );
BOOST_CHECK_EQUAL( i+1, j );
char const* str3 = "1test1";
BOOST_CHECK_EQUAL( str1, str3+1 );
unit_test_log.set_threshold_level( log_all_errors );
str1 = NULL;
str2 = NULL;
BOOST_CHECK_EQUAL( str1, str2 );
str1 = "test";
str2 = NULL;
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_EQUAL( str1, str2 ) );
B b1(1);
B b2(2);
unit_test_log.set_threshold_level( log_warnings );
BOOST_WARN_EQUAL( b1, b2 );
unit_test_log.set_threshold_level( log_all_errors );
C c1( 0, 100 );
C c2( 0, 101 );
C c3( 1, 102 );
BOOST_CHECK_EQUAL( c1, c3 );
BOOST_CHECK_EQUAL( c1, c2 );
char ch1 = -2;
char ch2 = -3;
BOOST_CHECK_EQUAL(ch1, ch2);
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_LOGICAL_EXPR )
{
int i=1;
int j=2;
BOOST_CHECK_NE( i, j );
BOOST_CHECK_NE( ++i, j );
BOOST_CHECK_LT( i, j );
BOOST_CHECK_GT( i, j );
BOOST_CHECK_LE( i, j );
BOOST_CHECK_GE( i, j );
++i;
BOOST_CHECK_LE( i, j );
BOOST_CHECK_GE( j, i );
char const* str1 = "test1";
char const* str2 = "test1";
BOOST_CHECK_NE( str1, str2 );
}
//____________________________________________________________________________//
bool is_even( int i ) { return i%2 == 0; }
int foo( int arg, int mod ) { return arg % mod; }
bool moo( int arg1, int arg2, int mod ) { return ((arg1+arg2) % mod) == 0; }
BOOST_TEST_DONT_PRINT_LOG_VALUE( std::list<int> )
boost::test_tools::predicate_result
compare_lists( std::list<int> const& l1, std::list<int> const& l2 )
{
if( l1.size() != l2.size() ) {
boost::test_tools::predicate_result res( false );
res.message() << "Different sizes [" << l1.size() << "!=" << l2.size() << "]";
return res;
}
return true;
}
TEST_CASE( test_BOOST_CHECK_PREDICATE )
{
BOOST_CHECK_PREDICATE( is_even, (14) );
int i = 17;
BOOST_CHECK_PREDICATE( is_even, (i) );
using std::not_equal_to;
BOOST_CHECK_PREDICATE( not_equal_to<int>(), (i)(17) );
int j=15;
BOOST_CHECK_PREDICATE( boost::bind( is_even, boost::bind( &foo, _1, _2 ) ), (i)(j) );
unit_test_log.set_threshold_level( log_warnings );
BOOST_WARN_PREDICATE( moo, (12)(i)(j) );
unit_test_log.set_threshold_level( log_all_errors );
std::list<int> l1, l2, l3;
l1.push_back( 1 );
l3.push_back( 1 );
l1.push_back( 2 );
l3.push_back( 3 );
BOOST_CHECK_PREDICATE( compare_lists, (l1)(l2) );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_REQUIRE_PREDICATE )
{
int arg1 = 1;
int arg2 = 2;
using std::less_equal;
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_PREDICATE( less_equal<int>(), (arg1)(arg2) ) );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_PREDICATE( less_equal<int>(), (arg2)(arg1) ) );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_EQUAL_COLLECTIONS )
{
unit_test_log.set_threshold_level( log_all_errors );
int pattern [] = { 1, 2, 3, 4, 5, 6, 7 };
std::list<int> testlist;
testlist.push_back( 1 );
testlist.push_back( 2 );
testlist.push_back( 4 ); // 3
testlist.push_back( 4 );
testlist.push_back( 5 );
testlist.push_back( 7 ); // 6
testlist.push_back( 7 );
BOOST_CHECK_EQUAL_COLLECTIONS( testlist.begin(), testlist.end(), pattern, pattern+7 );
BOOST_CHECK_EQUAL_COLLECTIONS( testlist.begin(), testlist.end(), pattern, pattern+2 );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_CHECK_BITWISE_EQUAL )
{
BOOST_CHECK_BITWISE_EQUAL( 0x16, 0x16 );
BOOST_CHECK_BITWISE_EQUAL( (char)0x06, (char)0x16 );
unit_test_log.set_threshold_level( log_warnings );
BOOST_WARN_BITWISE_EQUAL( (char)0x26, (char)0x04 );
unit_test_log.set_threshold_level( log_all_errors );
CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_BITWISE_EQUAL( (char)0x26, (int)0x26 ) );
}
//____________________________________________________________________________//
struct A {
friend std::ostream& operator<<( std::ostream& str, A const& a ) { str << "struct A"; return str;}
};
TEST_CASE( test_BOOST_TEST_MESSAGE )
{
unit_test_log.set_threshold_level( log_messages );
BOOST_TEST_MESSAGE( "still testing" );
BOOST_TEST_MESSAGE( "1+1=" << 2 );
int i = 2;
BOOST_TEST_MESSAGE( i << "+" << i << "=" << (i+i) );
A a = A();
BOOST_TEST_MESSAGE( a );
#if BOOST_TEST_USE_STD_LOCALE
BOOST_TEST_MESSAGE( std::hex << std::showbase << 20 );
#else
BOOST_TEST_MESSAGE( "0x14" );
#endif
BOOST_TEST_MESSAGE( std::setw( 4 ) << 20 );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_TEST_CHECKPOINT )
{
BOOST_TEST_CHECKPOINT( "Going to do a silly things" );
throw "some error";
}
//____________________________________________________________________________//
bool foo() { throw 1; return true; }
TEST_CASE( test_BOOST_TEST_PASSPOINT )
{
BOOST_CHECK( foo() );
}
//____________________________________________________________________________//
TEST_CASE( test_BOOST_IS_DEFINED )
{
#define SYMBOL1
#define SYMBOL2 std::cout
#define ONE_ARG( arg ) arg
#define TWO_ARG( arg1, arg2 ) BOOST_JOIN( arg1, arg2 )
BOOST_CHECK( BOOST_IS_DEFINED(SYMBOL1) );
BOOST_CHECK( BOOST_IS_DEFINED(SYMBOL2) );
BOOST_CHECK( !BOOST_IS_DEFINED( SYMBOL3 ) );
BOOST_CHECK( BOOST_IS_DEFINED( ONE_ARG(arg1) ) );
BOOST_CHECK( !BOOST_IS_DEFINED( ONE_ARG1(arg1) ) );
BOOST_CHECK( BOOST_IS_DEFINED( TWO_ARG(arg1,arg2) ) );
BOOST_CHECK( !BOOST_IS_DEFINED( TWO_ARG1(arg1,arg2) ) );
}
//____________________________________________________________________________//
// !! CHECK_SMALL
// EOF
| [
"metrix@Blended.(none)"
] | [
[
[
1,
571
]
]
] |
d22b287ccdde27a9387a78d7860cd70cf5279193 | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Cliente/Contenedor.cpp | f0791816727724fb6aed5090480c338723160b02 | [] | no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 401 | cpp | #include "Contenedor.h"
Contenedor::Contenedor(void)
{
}
Contenedor::~Contenedor(void)
{
for (list<ElementoGrafico*>::iterator it = this->elementos.begin();
it != this->elementos.end(); it++) {
delete(*it);
}
this->elementos.clear();
}
void Contenedor::agregarElementoGrafico(ElementoGrafico* elemento) {
this->elementos.push_back(elemento);
this->hayCambios = true;
}
| [
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296"
] | [
[
[
1,
19
]
]
] |
2d35b36591080ec638b75d0eac29645da90b5b5e | f95341dd85222aa39eaa225262234353f38f6f97 | /DesktopX/Plugins/DXCanvas/Sources/CanvasPath.h | de08d1f716647ecfc715d151f4d3c5a76ffd69dd | [] | no_license | Templier/threeoaks | 367b1a0a45596b8fe3607be747b0d0e475fa1df2 | 5091c0f54bd0a1b160ddca65a5e88286981c8794 | refs/heads/master | 2020-06-03T11:08:23.458450 | 2011-10-31T04:33:20 | 2011-10-31T04:33:20 | 32,111,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,253 | h | ///////////////////////////////////////////////////////////////////////////////////////////////
//
// Canvas Plugin for DesktopX
//
// Copyright (c) 2008-2010, Julien Templier
// All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////////////////////
// * $LastChangedRevision$
// * $LastChangedDate$
// * $LastChangedBy$
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include <cairo.h>
#include <cairo-win32.h>
//////////////////////////////////////////////////////////////////////////
// Encapsulate mapping text onto a path
//
// FIXNME: "corruption" when filing disjointed segments, as the characters might
// end up being stretched a lot.
class CanvasPath {
private:
typedef double parametrization_t;
/* Simple struct to hold a path and its parametrization */
typedef struct {
cairo_path_t *path;
parametrization_t *parametrization;
} parametrized_path_t;
typedef void (*transform_point_func_t) (void *closure, double *x, double *y);
static parametrization_t* parametrize_path(cairo_path_t *path);
static void transform_path(cairo_path_t *path, transform_point_func_t f, void *closure);
static void point_on_path (parametrized_path_t *param, double *x, double *y);
static double two_points_distance (cairo_path_data_t *a, cairo_path_data_t *b);
static double curve_length (double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3);
public:
static void map_path_onto (cairo_t *cr, cairo_path_t *path, float x, float y);
}; | [
"julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d"
] | [
[
[
1,
71
]
]
] |
11217b9827f991bb20b762ed2aa6721fd4b36310 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /GameServer/WorldKernel/MapList.h | c263bbd3fef95bfe5db017fe06e68e2f7039a852 | [] | no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | #pragma once
//#pragma warning(disable:4786)
#include "define.h"
#include "windows.h"
#include <time.h>
//#include <vector>
struct CMapSt
{
OBJID idMap;
OBJID idxMapGroup;
int nPortalX;
int nPortalY;
CMapSt() { idMap = ID_NONE; }
OBJID GetID() { return idMap; }
};
class IDatabase;
class CMapList
{
public:
CMapList();
virtual ~CMapList();
static CMapList* CreateNew() { return new CMapList; }
bool Create(IDatabase* pDb);
ULONG Release() { delete this; return 0; }
public:
PROCESS_ID GetMapProcessID(OBJID idMap);
CMapSt* GetMap(OBJID idMap);
protected:
typedef std::vector<CMapSt*> MAP_SET;
MAP_SET m_setMap;
}; | [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
] | [
[
[
1,
37
]
]
] |
020c6de31a330d8298bd64b66354b7050af82246 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Agent/ConvexAgent/CapsuleTriangle/hkpCapsuleTriangleAgent.h | eb1d62f2bcc06d7879947905dcc9fdd3f22c1bc3 | [] | no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,748 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_Capsule_TRIANGLE_AGENT_H
#define HK_COLLIDE2_Capsule_TRIANGLE_AGENT_H
#include <Physics/Collide/Agent/Util/LinearCast/hkpIterativeLinearCastAgent.h>
#include <Physics/Collide/Dispatch/hkpCollisionDispatcher.h>
#include <Physics/Collide/Util/hkpCollideTriangleUtil.h>
class hkpCollisionDispatcher;
/// This agent handles collisions between hkCapsules and hkTriangles.
class hkpCapsuleTriangleAgent : public hkpIterativeLinearCastAgent
{
public:
static void HK_CALL initAgentFunc (hkpCollisionDispatcher::AgentFuncs& f);
static void HK_CALL initAgentFuncInverse(hkpCollisionDispatcher::AgentFuncs& f);
///Registers this agent with the collision dispatcher.
static void HK_CALL registerAgent(hkpCollisionDispatcher* dispatcher);
///Registers this agent with the collision dispatcher. Does not register bridge agent.
static void HK_CALL registerAgent2(hkpCollisionDispatcher* dispatcher);
// hkpCollisionAgent interface implementation.
virtual inline void processCollision(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& result);
// hkpCollisionAgent interface implementation.
virtual void getClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& pointDetails);
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetClosestPoints( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, class hkpCdPointCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void getPenetrations(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
static void HK_CALL staticGetPenetrations(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector );
// hkpCollisionAgent interface implementation.
virtual void cleanup(hkCollisionConstraintOwner& constraintOwner);
protected:
friend class hkpCapsuleConvexWelderAgent;
/// Constructor, called by the agent creation functions.
HK_FORCE_INLINE hkpCapsuleTriangleAgent( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr );
/// Agent creation function used by the hkpCollisionDispatcher.
static hkpCollisionAgent* HK_CALL createCapsuleTriangleAgent(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
/// Agent creation function used by the hkpCollisionDispatcher.
static hkpCollisionAgent* HK_CALL createTriangleCapsuleAgent( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpContactMgr* mgr);
private:
/// Returns two candidates of the manifold. If searchManifold = true than an additional third point might be returned
/// Non-inlined version for hkpCapsuleConvexWelderAgent
static void HK_CALL getClosestPointsPublic( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCollideTriangleUtil::PointTriangleDistanceCache& cache, int searchManifold, hkContactPoint* points );
/// Returns two candidates of the manifold. If searchManifold = true than an additional third point might be returned
/// \param featureOutput if non-null, it should point to an array of three FeatureOutputs to which feature information about the collision will be written.
static HK_FORCE_INLINE void HK_CALL getClosestPointsInl( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCollideTriangleUtil::PointTriangleDistanceCache& cache, int searchManifold, hkContactPoint* points , hkpFeatureOutput* featureOutput = HK_NULL);
public:
enum ClosestPointResult
{
ST_CP_MISS,
ST_CP_HIT,
};
private:
static HK_FORCE_INLINE ClosestPointResult getClosestPointInternal( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCollideTriangleUtil::PointTriangleDistanceCache& m_cache, hkContactPoint& cpoint);
public:
static ClosestPointResult HK_CALL getClosestPoint( const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCollideTriangleUtil::PointTriangleDistanceCache& m_cache, hkContactPoint& cpoint);
protected:
hkContactPointId m_contactPointId[3];
hkpCollideTriangleUtil::PointTriangleDistanceCache m_triangleCache;
};
#endif // HK_COLLIDE2_Capsule_TRIANGLE_AGENT_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
] | [
[
[
1,
107
]
]
] |
5baa83a167033354dad1a14156c32483fa9c7e2a | 1e62164424822d8df6b628cbc4cad9a4fe76cf38 | /Source Code/IterativeClosestPoint/IterativeClosestPoint/MyAlign.h | da6ff9d89f80efa469070b3a4321a95f38ff1471 | [] | no_license | truongngoctuan/lv2007tm | b41b8cd54360a6dd966f158a7434cfe853627df0 | 9fa1af79f265dd589e8300017ab857fcfe4fe846 | refs/heads/master | 2021-01-10T01:58:50.292831 | 2011-07-30T13:43:17 | 2011-07-30T13:43:17 | 48,728,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | h | #pragma once
#include <string>
#include "common/MeshModel.h"
#include "io_base/baseio.h"
#include "align_plugin/editalign.h"
class MyAlign
{
public:
BaseMeshIOPlugin baseIOPlugin;
EditAlignPlugin editAlignPlugin;
int nNode;
public:
MyAlign(void);
~MyAlign(void);
bool AddNode(std::string strFile, std::string strName);
bool Align(std::string strFixName, std::string strMovName, std::string strPair);
bool FinalizeICP();
bool FinalizeICP2();
bool SetBaseNode(std::string strName);
void PrintResult(std::string strResultDir);
void Export();
static __declspec(dllexport) bool Auto(std::string strScriptFile, std::string strResultDir);
};
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
02a17d450802844ce7d3c97339070cae9728418c | fb7d4d40bf4c170328263629acbd0bbc765c34aa | /SpaceBattle/SpaceBattleLib/GeneratedCode/Vue/Implementation/VueGestionTirImpl.h | 69449301940dee5b61bde946aeb52f0a49007d4d | [] | no_license | bvannier/SpaceBattle | e146cda9bac1608141ad8377620623514174c0cb | 6b3e1a8acc5d765223cc2b135d2b98c8400adf06 | refs/heads/master | 2020-05-18T03:40:16.782219 | 2011-11-28T22:49:36 | 2011-11-28T22:49:36 | 2,659,535 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 891 | h | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#pragma once
#define WANTDLLEXP
#ifdef WANTDLLEXP //exportation dll
#define DLL __declspec( dllexport )
#define EXTERNC extern "C"
#else
#define DLL //standard
#define EXTERNC
#endif
#include "VueGestionTir.h"
using namespace VueInterfaces;
#include<vector>
namespace VueImplementation
{
class VueGestionTirImpl : public VueGestionTir
{
private :
protected :
public :
private :
protected :
public :
virtual void update();
};
EXTERNC DLL void VUEGESTIONTIRIMPL_update(VueGestionTirImpl*);
}
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
5593d7106c021c98a3377818a52f0b26671b291d | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/PRatio/peakPicker.cpp | 28b386b9912e551b6c5e76f5c4942c5916592ab0 | [] | no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,849 | cpp | #include "peakPicker.h"
PeakPicker::PeakPicker()
{
iRightValley = 0;
iLeftValley = 0;
dPeakHeightPPC = 0;
bPeakValidity = false;
iChroLength = 0;
fLeftMS2Time = 0;
fRightMS2Time = 0;
iNumberofScansShifted = 0;
}
PeakPicker::~PeakPicker()
{
// destructor
}
bool PeakPicker::process( const vector< float > & vfMS2TimeInput,
const vector< float > & vfRetentionTimeInput,
vector< double > & vdTreatmentChroInput,
vector< double > & vdReferenceChroInput
)
{
iChroLength = vfRetentionTimeInput.size();
if ( iChroLength <= ProRataConfig::getPeakPickerWindowSize() )
{
cout << "ERROR! The input chromatograms have too few MS1 scans!" << endl;
return false;
}
if( vdTreatmentChroInput.size() != iChroLength || vdReferenceChroInput.size() != iChroLength )
{
cout << "ERROR! the input chromatograms are in different length!" << endl;
return false;
}
if ( ( ProRataConfig::getPeakPickerWindowSize() % 2) == 0 )
{
cout << "ERROR! The window size for Sav-Gol smoothing has to be odd! " << endl;
return false;
}
if ( ProRataConfig::getPeakPickerWindowSize() < 3 )
{
cout << "ERROR! The window size for Sav-Gol smoothing is too small! " << endl;
return false;
}
vfRetentionTime = vfRetentionTimeInput;
// set the earliest MS2 time and the last MS2 scan time
// used for initialize left valley and right valley
fLeftMS2Time = *( min_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) );
fRightMS2Time = *( max_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) );
// the fLeftMS2Time and fRightMS2Time have to be within the RT range
if( fLeftMS2Time < vfRetentionTime.front() )
fLeftMS2Time = vfRetentionTime.front();
if( fRightMS2Time > vfRetentionTime.back() )
fRightMS2Time = vfRetentionTime.back();
if( (ProRataConfig::getLeftPeakShift() < 0.001) && (ProRataConfig::getRightPeakShift() < 0.001) )
{
iNumberofScansShifted = 0;
// compute the final vdCovarianceChro
computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput );
// compute the final peak
findPeak();
return true;
}
/*
* detect peak shift
*/
int i;
// the calcuated peak height in PPC for all tested peak shift
// vector< double > vdPeakHeight;
// vector< int > viScanShift;
map< int, double > mScanShift2Height;
// scans that shifts left is negative and scans that shifts right is positive
for( i = 0; i < vfRetentionTime.size() - 3; i++ )
{
if( (vfRetentionTime[i] - vfRetentionTime[0]) >= ProRataConfig::getLeftPeakShift() - 0.001)
break;
}
int iScanShiftLeft = -i;
for( i = (vfRetentionTime.size() - 1); i > 2; i-- )
{
if( (vfRetentionTime.back() - vfRetentionTime[i]) >= ProRataConfig::getRightPeakShift() - 0.001)
break;
}
int iScanShiftRight = vfRetentionTime.size() - i - 1;
double dMaxPeakHeight = -100;
for( i = iScanShiftLeft; i < ( iScanShiftRight + 1 ); ++i )
{
// viScanShift.push_back( i );
computeCovarianceChro( i, vdTreatmentChroInput, vdReferenceChroInput );
findPeak();
mScanShift2Height[i] = dPeakHeightPPC;
if( dPeakHeightPPC > dMaxPeakHeight )
dMaxPeakHeight = dPeakHeightPPC;
// vdPeakHeight.push_back( dPeakHeightPPC );
}
if( mScanShift2Height[ 0 ] > dMaxPeakHeight*0.9 )
{
iNumberofScansShifted = 0;
}
else
{
iNumberofScansShifted = 0;
bool bIsMaxFound = false;
if( abs( iScanShiftLeft ) > iScanShiftRight )
{
for( i = 0; i > ( iScanShiftLeft - 1 ); --i )
{
if( mScanShift2Height[i] > dMaxPeakHeight*0.95 )
{
iNumberofScansShifted = i;
bIsMaxFound = true;
break;
}
}
if( !bIsMaxFound )
{
for( i = 0; i < iScanShiftRight + 1 ; ++i )
{
if( mScanShift2Height[i] > dMaxPeakHeight*0.95 )
{
iNumberofScansShifted = i;
break;
}
}
}
}
else
{
for( i = 0; i < iScanShiftRight + 1 ; ++i )
{
if( mScanShift2Height[i] > dMaxPeakHeight*0.95 )
{
iNumberofScansShifted = i;
bIsMaxFound = true;
break;
}
}
if( !bIsMaxFound )
{
for( i = 0; i > ( iScanShiftLeft - 1 ); --i )
{
if( mScanShift2Height[i] > dMaxPeakHeight*0.95 )
{
iNumberofScansShifted = i;
break;
}
}
}
}
}
// compute the final vdCovarianceChro
computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput );
// compute the final peak
findPeak();
// actually change the input vdReferenceChroInput
shiftChro( iNumberofScansShifted, vdReferenceChroInput );
// cout << "bPeakValidity = " << boolalpha << bPeakValidity << endl;
return true;
}
void PeakPicker::computeCovarianceChro( int iScanShiftReference,
vector< double > vdTreatmentChroInput,
vector< double > vdReferenceChroInput )
{
vdCovarianceChro.clear();
vdCovarianceChro.resize( iChroLength, 0.0 );
// ensure all input chromatograms have the right length
if( vdTreatmentChroInput.size() != iChroLength || vdReferenceChroInput.size() != iChroLength )
return;
// shift vdReferenceChro for the iScanShiftReference number of scans
shiftChro( iScanShiftReference, vdReferenceChroInput );
// compute noise level for treatment chro
double dNoiseTreatmentChro = (*( min_element(vdTreatmentChroInput.begin(),
vdTreatmentChroInput.end() ) ));
dNoiseTreatmentChro = dNoiseTreatmentChro - 1;
if( dNoiseTreatmentChro < 0 )
dNoiseTreatmentChro = 0;
// compute noise level for reference chro
double dNoiseReferenceChro = (*( min_element(vdReferenceChroInput.begin(),
vdReferenceChroInput.end() ) ));
dNoiseReferenceChro = dNoiseReferenceChro - 1;
if( dNoiseReferenceChro < 0 )
dNoiseReferenceChro = 0;
vector<double>::iterator itr;
// substract the noise for treatment chro
for( itr = vdTreatmentChroInput.begin(); itr != vdTreatmentChroInput.end(); itr++ )
*(itr) = *(itr) - dNoiseTreatmentChro;
// substract the noise for reference chro
for( itr = vdReferenceChroInput.begin(); itr != vdReferenceChroInput.end(); itr++ )
*(itr) = *(itr) - dNoiseReferenceChro;
// Construct covariance chromatogram
transform( vdTreatmentChroInput.begin(), vdTreatmentChroInput.end(), vdReferenceChroInput.begin(),
vdCovarianceChro.begin(), multiplies<double>() );
Smoother smootherCovariance( ProRataConfig::getPeakPickerWindowSize(), ProRataConfig::getPeakPickerFOrder() );
smootherCovariance.smoothen( vdCovarianceChro );
}
void PeakPicker::shiftChro( int iScanShift, vector< double > & vdChro )
{
// no shift
if( iScanShift == 0 )
return;
// check input validity
if( abs( iScanShift ) > vdChro.size() - 3 || vdChro.size() < 3 )
return;
double dTempIntensity = 0;
// shift left
if( iScanShift < 0 )
{
dTempIntensity = vdChro.back();
vdChro.erase( vdChro.begin(), vdChro.begin() + abs( iScanShift ) );
vdChro.insert( vdChro.end(), abs( iScanShift ), dTempIntensity );
}
// shift right
if( iScanShift > 0 )
{
dTempIntensity = vdChro.front();
vdChro.erase( ( vdChro.end() - iScanShift ) , vdChro.end() );
vdChro.insert( vdChro.begin(), iScanShift, dTempIntensity );
}
}
void PeakPicker::findPeak()
{
int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2;
// initialize iRightValley;
for( iRightValley = ( iChroLength - 2 ) ; iRightValley > ProRataConfig::getPeakPickerWindowSize(); --iRightValley )
{
if ( vfRetentionTime[ iRightValley ] < fRightMS2Time )
break;
}
++iRightValley;
// initialize iLeftValley
for( iLeftValley = 1 ; iLeftValley < (iChroLength - ProRataConfig::getPeakPickerWindowSize() - 1); ++iLeftValley )
{
if ( vfRetentionTime[ iLeftValley ] > fLeftMS2Time )
break;
}
--iLeftValley;
// compute iLeftValley and iRightValley
iRightValley = findNextRightValley( iRightValley );
iLeftValley = findNextLeftValley( iLeftValley );
double dCovarianceCutOff = median( vdCovarianceChro );
vector<double>::iterator itrBegin = vdCovarianceChro.begin();
double dHalfPeakIntensity = ( *(max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) - dCovarianceCutOff ) * 0.5 ;
double dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff;
double dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff;
bool bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset );
bool bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) );
bool bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) );
while ( bMoveLeftValley || bMoveRightValley )
{
if ( bMoveLeftValley && ( bMoveLeftOrRight || !bMoveRightValley ) )
iLeftValley = findNextLeftValley( iLeftValley );
if ( (!bMoveLeftValley || !bMoveLeftOrRight ) && bMoveRightValley )
iRightValley = findNextRightValley( iRightValley );
dHalfPeakIntensity = ( *(max_element(itrBegin + iLeftValley, itrBegin + iRightValley +1 ) ) - dCovarianceCutOff ) * 0.5 ;
dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff;
dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff;
bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset ) ;
bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) ) ;
bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) );
}
// compute bPeakValidity
bool bIsPeakBelowNoise = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) ) < dCovarianceCutOff;
float fPeakWidth = vfRetentionTime[ iRightValley ] - vfRetentionTime[ iLeftValley ];
// float fChroDuration = vfRetentionTime.back() - vfRetentionTime.front() ;
// minimal peak width = 0.1 min
// maximal peak width = 8 min
bool bIsPeakTooSmall = fPeakWidth < ( 0.1 );
bool bIsPeakTooBroad = fPeakWidth > ( 8 );
if ( bIsPeakBelowNoise || bIsPeakTooSmall || bIsPeakTooBroad )
bPeakValidity = false;
else
bPeakValidity = true;
// compute dPeakHeightPPC
dPeakHeightPPC = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1) ) ) -
( ( vdCovarianceChro.at(iLeftValley) + vdCovarianceChro.at(iRightValley) )/2 );
}
double PeakPicker::median( vector<double> vdData )
{
if( vdData.size() < 1 )
return 0;
sort( vdData.begin(), vdData.end() );
return *( vdData.begin() + (vdData.size() / 2 ) );
}
int PeakPicker::findNextLeftValley( int iCurrentLeftValley )
{
double dCurrentMinimumIntensity;
double dCurrentValleyIntensity;
int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2;
bool bIsTrueValley = false;
int iValleyMinusOffset;
int iValleyPlusOffset;
vector<double>::iterator itrBegin;
itrBegin = vdCovarianceChro.begin();
while ( (iCurrentLeftValley > iOffset ) && ( !bIsTrueValley ) )
{
iCurrentLeftValley--;
dCurrentValleyIntensity = *( itrBegin + iCurrentLeftValley );
iValleyMinusOffset = max( 0, iCurrentLeftValley - iOffset );
iValleyPlusOffset = min( iChroLength -1,iCurrentLeftValley + iOffset );
// Add one, because
// min_element finds the smallest element in the range [first, last).
// Note the last element is not included.
dCurrentMinimumIntensity = *( min_element(itrBegin + iValleyMinusOffset,
itrBegin + iValleyPlusOffset + 1 ) );
if ( dCurrentMinimumIntensity >= dCurrentValleyIntensity )
bIsTrueValley = true;
}
return iCurrentLeftValley;
}
int PeakPicker::findNextRightValley( int iCurrentRightValley )
{
double dCurrentMinimumIntensity;
double dCurrentValleyIntensity;
int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2;
bool bIsTrueValley = false;
int iValleyMinusOffset;
int iValleyPlusOffset;
vector<double>::iterator itrBegin;
itrBegin = vdCovarianceChro.begin();
while ( (iCurrentRightValley < ( iChroLength - iOffset - 1 )) &&
(!bIsTrueValley) )
{
iCurrentRightValley++;
dCurrentValleyIntensity = *( itrBegin + iCurrentRightValley );
iValleyMinusOffset = max( 0, iCurrentRightValley - iOffset );
iValleyPlusOffset = min( iChroLength - 1, iCurrentRightValley + iOffset ) ;
dCurrentMinimumIntensity = *( min_element(itrBegin + iValleyMinusOffset,
itrBegin + iValleyPlusOffset + 1 ) );
if ( dCurrentMinimumIntensity >= dCurrentValleyIntensity )
bIsTrueValley = true;
}
return iCurrentRightValley;
}
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
] | [
[
[
1,
432
]
]
] |
17242171645e784a3ffd2026f1eb0815a5cc8792 | e2f961659b90ff605798134a0a512f9008c1575b | /SPE/spe7/4a/MODEL_GRID.INC | 37279d248828bf96eb23268cf40ff4d80c06e8af | [] | no_license | bs-eagle/test-models | 469fe485a0d9aec98ad06d39b75901c34072cf60 | d125060649179b8e4012459c0a62905ca5235ba7 | refs/heads/master | 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,958 | inc | COORD
0 0 1094.232 0 0 1100.328
91.44 0 1094.232 91.44 0 1100.328
182.88 0 1094.232 182.88 0 1100.328
274.32 0 1094.232 274.32 0 1100.328
365.76 0 1094.232 365.76 0 1100.328
457.2 0 1094.232 457.2 0 1100.328
548.64 0 1094.232 548.64 0 1100.328
640.08 0 1094.232 640.08 0 1100.328
731.52 0 1094.232 731.52 0 1100.328
822.96 0 1094.232 822.96 0 1100.328
0 188.976 1094.232 0 188.976 1100.328
91.44 188.976 1094.232 91.44 188.976 1100.328
182.88 188.976 1094.232 182.88 188.976 1100.328
274.32 188.976 1094.232 274.32 188.976 1100.328
365.76 188.976 1094.232 365.76 188.976 1100.328
457.2 188.976 1094.232 457.2 188.976 1100.328
548.64 188.976 1094.232 548.64 188.976 1100.328
640.08 188.976 1094.232 640.08 188.976 1100.328
731.52 188.976 1094.232 731.52 188.976 1100.328
822.96 188.976 1094.232 822.96 188.976 1100.328
0 310.896 1094.232 0 310.896 1100.328
91.44 310.896 1094.232 91.44 310.896 1100.328
182.88 310.896 1094.232 182.88 310.896 1100.328
274.32 310.896 1094.232 274.32 310.896 1100.328
365.76 310.896 1094.232 365.76 310.896 1100.328
457.2 310.896 1094.232 457.2 310.896 1100.328
548.64 310.896 1094.232 548.64 310.896 1100.328
640.08 310.896 1094.232 640.08 310.896 1100.328
731.52 310.896 1094.232 731.52 310.896 1100.328
822.96 310.896 1094.232 822.96 310.896 1100.328
0 371.856 1094.232 0 371.856 1100.328
91.44 371.856 1094.232 91.44 371.856 1100.328
182.88 371.856 1094.232 182.88 371.856 1100.328
274.32 371.856 1094.232 274.32 371.856 1100.328
365.76 371.856 1094.232 365.76 371.856 1100.328
457.2 371.856 1094.232 457.2 371.856 1100.328
548.64 371.856 1094.232 548.64 371.856 1100.328
640.08 371.856 1094.232 640.08 371.856 1100.328
731.52 371.856 1094.232 731.52 371.856 1100.328
822.96 371.856 1094.232 822.96 371.856 1100.328
0 402.336 1094.232 0 402.336 1100.328
91.44 402.336 1094.232 91.44 402.336 1100.328
182.88 402.336 1094.232 182.88 402.336 1100.328
274.32 402.336 1094.232 274.32 402.336 1100.328
365.76 402.336 1094.232 365.76 402.336 1100.328
457.2 402.336 1094.232 457.2 402.336 1100.328
548.64 402.336 1094.232 548.64 402.336 1100.328
640.08 402.336 1094.232 640.08 402.336 1100.328
731.52 402.336 1094.232 731.52 402.336 1100.328
822.96 402.336 1094.232 822.96 402.336 1100.328
0 420.624 1094.232 0 420.624 1100.328
91.44 420.624 1094.232 91.44 420.624 1100.328
182.88 420.624 1094.232 182.88 420.624 1100.328
274.32 420.624 1094.232 274.32 420.624 1100.328
365.76 420.624 1094.232 365.76 420.624 1100.328
457.2 420.624 1094.232 457.2 420.624 1100.328
548.64 420.624 1094.232 548.64 420.624 1100.328
640.08 420.624 1094.232 640.08 420.624 1100.328
731.52 420.624 1094.232 731.52 420.624 1100.328
822.96 420.624 1094.232 822.96 420.624 1100.328
0 451.104 1094.232 0 451.104 1100.328
91.44 451.104 1094.232 91.44 451.104 1100.328
182.88 451.104 1094.232 182.88 451.104 1100.328
274.32 451.104 1094.232 274.32 451.104 1100.328
365.76 451.104 1094.232 365.76 451.104 1100.328
457.2 451.104 1094.232 457.2 451.104 1100.328
548.64 451.104 1094.232 548.64 451.104 1100.328
640.08 451.104 1094.232 640.08 451.104 1100.328
731.52 451.104 1094.232 731.52 451.104 1100.328
822.96 451.104 1094.232 822.96 451.104 1100.328
0 512.064 1094.232 0 512.064 1100.328
91.44 512.064 1094.232 91.44 512.064 1100.328
182.88 512.064 1094.232 182.88 512.064 1100.328
274.32 512.064 1094.232 274.32 512.064 1100.328
365.76 512.064 1094.232 365.76 512.064 1100.328
457.2 512.064 1094.232 457.2 512.064 1100.328
548.64 512.064 1094.232 548.64 512.064 1100.328
640.08 512.064 1094.232 640.08 512.064 1100.328
731.52 512.064 1094.232 731.52 512.064 1100.328
822.96 512.064 1094.232 822.96 512.064 1100.328
0 633.984 1094.232 0 633.984 1100.328
91.44 633.984 1094.232 91.44 633.984 1100.328
182.88 633.984 1094.232 182.88 633.984 1100.328
274.32 633.984 1094.232 274.32 633.984 1100.328
365.76 633.984 1094.232 365.76 633.984 1100.328
457.2 633.984 1094.232 457.2 633.984 1100.328
548.64 633.984 1094.232 548.64 633.984 1100.328
640.08 633.984 1094.232 640.08 633.984 1100.328
731.52 633.984 1094.232 731.52 633.984 1100.328
822.96 633.984 1094.232 822.96 633.984 1100.328
0 822.96 1094.232 0 822.96 1100.328
91.44 822.96 1094.232 91.44 822.96 1100.328
182.88 822.96 1094.232 182.88 822.96 1100.328
274.32 822.96 1094.232 274.32 822.96 1100.328
365.76 822.96 1094.232 365.76 822.96 1100.328
457.2 822.96 1094.232 457.2 822.96 1100.328
548.64 822.96 1094.232 548.64 822.96 1100.328
640.08 822.96 1094.232 640.08 822.96 1100.328
731.52 822.96 1094.232 731.52 822.96 1100.328
822.96 822.96 1094.232 822.96 822.96 1100.328
/
ZCORN
324*6.096
648*12.192
648*18.288
648*24.384
648*30.48
648*39.624
324*54.864
/
PORO
486*0.2
/
NTG
486*1
/
PERMX
486*3000
/
PERMY
486*3000
/
PERMZ
486*300
/
TOPS
81*1094.232
/
| [
"[email protected]"
] | [
[
[
1,
137
]
]
] |
1cb556f8d8d148e3fc61372f20b7c8f0dc167477 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/CryEngine/CryCommon/physinterface.h | e910f4fe5e00be781d37a0be24a8a19c2c54649e | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88,863 | h | //////////////////////////////////////////////////////////////////////
//
// Physics System Interface
//
// File: physinterface.h
// Description : declarations of all physics interfaces and structures
//
// History:
// -:Created by Anton Knyazev
//
//////////////////////////////////////////////////////////////////////
#ifndef physinterface_h
#define physinterface_h
#if defined(LINUX)
//#include "Stream.h"
//#include "validator.h"
#endif
#include <SerializeFwd.h>
#include "Cry_Geo.h"
//////////////////////////////////////////////////////////////////////////
// Physics defines.
//////////////////////////////////////////////////////////////////////////
typedef int index_t;
//////////////////////////////////////////////////////////////////////////
enum pe_type { PE_NONE=0, PE_STATIC=1, PE_RIGID=2, PE_WHEELEDVEHICLE=3, PE_LIVING=4, PE_PARTICLE=5, PE_ARTICULATED=6, PE_ROPE=7, PE_SOFT=8, PE_AREA=9 };
enum sim_class { SC_STATIC=0, SC_SLEEPING_RIGID=1, SC_ACTIVE_RIGID=2, SC_LIVING=3, SC_INDEPENDENT=4, SC_TRIGGER=6, SC_DELETED=7 };
struct IGeometry;
struct IPhysicalEntity;
struct IGeomManager;
struct IPhysicalWorld;
struct IPhysRenderer;
class ICrySizer;
struct ILog;
struct GeomQuery;
IPhysicalEntity *const WORLD_ENTITY = (IPhysicalEntity*)-10;
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IPhysicsStreamer Interface /////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct IPhysicsStreamer {
virtual int CreatePhysicalEntity(void *pForeignData,int iForeignData,int iForeignFlags) = 0;
virtual int DestroyPhysicalEntity(IPhysicalEntity *pent) = 0;
virtual int CreatePhysicalEntitiesInBox(const Vec3 &boxMin, const Vec3 &boxMax) = 0;
virtual int DestroyPhysicalEntitiesInBox(const Vec3 &boxMin, const Vec3 &boxMax) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// IPhysRenderer Interface /////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct IPhysRenderer {
virtual void DrawGeometry(IGeometry *pGeom, struct geom_world_data *pgwd, int idxColor=0, int bSlowFadein=0, const Vec3 &sweepDir=Vec3(0)) = 0;
virtual void DrawLine(const Vec3& pt0, const Vec3& pt1, int idxColor=0, int bSlowFadein=0) = 0;
virtual const char *GetForeignName(void *pForeignData,int iForeignData,int iForeignFlags) = 0;
virtual void DrawText(const Vec3 &pt, const char *txt, int idxColor, float saturation=0) = 0;
};
class CMemStream { // for "fastload" serialization; hopefully it can be made global for the project
public:
CMemStream(bool swap) {
Prealloc(); m_iPos=0; bDeleteBuf=true; bSwapEndian=swap;
}
CMemStream(void *pbuf, int sz, bool swap) {
m_pBuf=(char*)pbuf; m_nSize=sz; m_iPos=0; bDeleteBuf=false; bSwapEndian=swap;
}
virtual ~CMemStream() {
if (bDeleteBuf)
delete[] m_pBuf;
}
virtual void Prealloc() { m_pBuf = new char[m_nSize=0x1000]; }
void *GetBuf() { return m_pBuf; }
int GetUsedSize() { return m_iPos; }
int GetAllocatedSize() { return m_nSize; }
template<class ftype> void Write(const ftype &op) { Write(&op, sizeof(op)); }
void Write(const void *pbuf, int sz) {
if (m_iPos+sz>m_nSize)
GrowBuf(sz);
if (sz==4)
*(int*)(m_pBuf+m_iPos) = *(int*)pbuf;
else
memcpy(m_pBuf+m_iPos,pbuf,(unsigned int)sz);
m_iPos += sz;
}
virtual void GrowBuf(int sz) {
int prevsz = m_nSize; char *prevbuf = m_pBuf;
m_pBuf = new char[m_nSize = (m_iPos+sz-1 & ~0xFFF)+0x1000];
memcpy(m_pBuf, prevbuf, (unsigned int)prevsz);
delete[] prevbuf;
}
template<class ftype> void Read(ftype &op)
{
ReadRaw(&op, sizeof(op));
#ifdef NEED_ENDIAN_SWAP
if (bSwapEndian)
SwapEndian(op);
#endif
}
template<class ftype> ftype Read()
{
ftype val;
Read(val);
return val;
}
template<class ftype> void ReadType(ftype* op, int count = 1)
{
ReadRaw(op, sizeof(*op)*count);
#ifdef NEED_ENDIAN_SWAP
if (bSwapEndian) while (count-- > 0)
SwapEndian(*op++);
#endif
}
void ReadRaw(void *pbuf, int sz)
{
if (sz==4)
*(int*)pbuf = *(int*)(m_pBuf+m_iPos);
else
memcpy(pbuf,(m_pBuf+m_iPos),(unsigned int)sz);
m_iPos += sz;
}
char *m_pBuf;
int m_iPos,m_nSize;
bool bDeleteBuf;
bool bSwapEndian;
};
class unused_marker {
public:
unused_marker() {}
unused_marker& operator,(float &x) { *(int*)&x = 0xFFBFFFFF; return *this; }
unused_marker& operator,(double &x) { *((int*)&x+1) = 0xFFF7FFFF; return *this; }
unused_marker& operator,(int &x) { x=1<<31; return *this; }
unused_marker& operator,(unsigned int &x) { x=1u<<31; return *this; }
template<class ref> unused_marker& operator,(ref *&x) { x=(ref*)-1; return *this; }
template<class F> unused_marker& operator,(Vec3_tpl<F> &x) { return *this,x.x; }
template<class F> unused_marker& operator,(Quat_tpl<F> &x) { return *this,x.w; }
template<class F> unused_marker& operator,(strided_pointer<F> &x) { return *this,x.data; }
};
inline bool is_unused(const float &x) { return (*(int*)&x & 0xFFA00000) == 0xFFA00000; }
inline bool is_unused(int x) { return x==1<<31; }
inline bool is_unused(unsigned int x) { return x==1u<<31; }
template<class ref> bool is_unused(ref *x) { return x==(ref*)-1; }
template<class ref> bool is_unused(strided_pointer<ref> x) { return is_unused(x.data); }
template<class F> bool is_unused(const Ang3_tpl<F> &x) { return is_unused(x.x); }
template<class F> bool is_unused(const Vec3_tpl<F> &x) { return is_unused(x.x); }
template<class F> bool is_unused(const Quat_tpl<F> &x) { return is_unused(x.w); }
inline bool is_unused(const double &x) { return (*((int*)&x+1) & 0xFFF40000) == 0xFFF40000; }
#define MARK_UNUSED unused_marker(),
#if !defined(VALIDATOR_LOG)
#define VALIDATOR_LOG(pLog,str)
#define VALIDATORS_START
#define VALIDATOR(member)
#define VALIDATOR_NORM(member)
#define VALIDATOR_NORM_MSG(member,msg,member1)
#define VALIDATOR_RANGE(member,minval,maxval)
#define VALIDATOR_RANGE2(member,minval,maxval)
#define VALIDATORS_END
#endif
// in physics interface [almost] all parameters are passed via structures
// this allows having stable interface methods and flexible default arguments system
////////////////////////// Params structures /////////////////////
////////// common params
struct pe_params {
int type;
};
struct pe_params_pos : pe_params { // Sets postion and orientation of entity
enum entype { type_id=0 };
pe_params_pos() {
type=type_id; MARK_UNUSED pos,scale,q,iSimClass; pMtx3x4=0;pMtx3x3=0; bRecalcBounds=1;
}
Vec3 pos;
quaternionf q;
float scale;
Matrix34 *pMtx3x4;
Matrix33 *pMtx3x3; // optional orientation via 3x3 matrix
int iSimClass;
int bRecalcBounds;
VALIDATORS_START
VALIDATOR(pos)
VALIDATOR_NORM_MSG(q,"(perhaps non-uniform scaling was used?)",pos)
VALIDATOR(scale)
VALIDATORS_END
};
struct pe_params_bbox : pe_params {
enum entype { type_id=14 };
pe_params_bbox() { type=type_id; MARK_UNUSED BBox[0],BBox[1]; }
Vec3 BBox[2];
VALIDATORS_START
VALIDATOR(BBox[0])
VALIDATOR(BBox[1])
VALIDATORS_END
};
// If entity represents an interior volume this allows to set outer entity, which will be skipped during tests against
// objects that are inside this entity
struct pe_params_outer_entity : pe_params {
enum entype { type_id=9 };
pe_params_outer_entity() { type=type_id; pOuterEntity=0; pBoundingGeometry=0; }
IPhysicalEntity *pOuterEntity; // outer entity for this one (outer entities can form chains)
IGeometry *pBoundingGeometry; // optional geometry to test containment
};
struct ITetrLattice;
struct pe_params_part : pe_params { // Sets geometrical parameters of entity part
enum entype { type_id=6 };
pe_params_part() {
type=type_id;
MARK_UNUSED pos,q,scale,partid,ipart,mass,density,pPhysGeom,pPhysGeomProxy,idmatBreakable,pLattice,pMatMapping,minContactDist,flagsCond;
pMtx3x4=0;pMtx3x3=0;
bRecalcBBox=1; bAddrefGeoms=0; flagsOR=flagsColliderOR=0; flagsAND=flagsColliderAND=(unsigned)-1;
}
int partid; // partid identifier of part
int ipart; // optionally, part slot number
int bRecalcBBox; // whether entity's bounding box should be recalculated
Vec3 pos;
quaternionf q;
float scale;
Matrix34 *pMtx3x4;
Matrix33 *pMtx3x3; // optional orientation via 3x3 matrix
unsigned int flagsCond; // if partid and ipart are not specified, check for parts with flagsCond set
unsigned int flagsOR,flagsAND; // new flags = (flags & flagsAND) | flagsOR
unsigned int flagsColliderOR,flagsColliderAND;
float mass;
float density;
float minContactDist;
struct phys_geometry *pPhysGeom,*pPhysGeomProxy;
int idmatBreakable;
ITetrLattice *pLattice;
int *pMatMapping;
int nMats;
int bAddrefGeoms;
VALIDATORS_START
VALIDATOR(pos)
VALIDATOR_NORM(q)
VALIDATOR(scale)
VALIDATORS_END
};
struct pe_params_sensors : pe_params { // Attaches optional sensors to entity (sensors raytrace enviroment around entity)
enum entype { type_id=7 };
pe_params_sensors() { type=type_id; nSensors=0; pOrigins=0; pDirections=0; }
int nSensors; // nSensors number of sensors
const Vec3 *pOrigins; // pOrigins sensors origins in entity CS
const Vec3 *pDirections; // pDirections sensors directions (dir*ray length) in entity CS
};
struct pe_simulation_params : pe_params { // Sets gravity and maximum time step
enum entype { type_id=10 };
pe_simulation_params() { type=type_id; MARK_UNUSED maxTimeStep,gravity,minEnergy,damping,iSimClass,
softness,softnessAngular,dampingFreefall,gravityFreefall,mass,density,maxLoggedCollisions; }
int iSimClass;
float maxTimeStep; // maximum time step that entity can accept (larger steps will be split)
float minEnergy; // minimun of kinetic energy below which entity falls asleep (divided by mass!)
float damping;
Vec3 gravity;
float dampingFreefall; // damping and gravity used when there are no collisions,
Vec3 gravityFreefall; // NOTE: if left unused, gravity value will be substituted (if provided)
float mass;
float density;
float softness,softnessAngular;
float softnessGroup,softnessAngularGroup;
int maxLoggedCollisions;
};
struct pe_params_foreign_data : pe_params {
enum entype { type_id=11 };
pe_params_foreign_data() { type=type_id; MARK_UNUSED pForeignData,iForeignData,iForeignFlags; iForeignFlagsAND=-1;iForeignFlagsOR=0; }
void *pForeignData;
int iForeignData;
int iForeignFlags;
int iForeignFlagsAND,iForeignFlagsOR;
};
struct pe_params_buoyancy : pe_params {
enum entype { type_id=12 };
pe_params_buoyancy() {
type=type_id; iMedium=0; MARK_UNUSED waterDensity,kwaterDensity,waterDamping,
waterPlane.n,waterPlane.origin,waterEmin,waterResistance,kwaterResistance,waterFlow,flowVariance;
};
float waterDensity,kwaterDensity;
float waterDamping;
float waterResistance,kwaterResistance;
Vec3 waterFlow;
float flowVariance;
primitives::plane waterPlane;
float waterEmin;
int iMedium; // 0 for water, 1 for air
};
enum phentity_flags {
particle_single_contact=0x01,particle_constant_orientation=0x02,particle_no_roll=0x04,particle_no_path_alignment=0x08,particle_no_spin=0x10,
lef_push_objects=0x01, lef_push_players=0x02, lef_snap_velocities=0x04, lef_loosen_stuck_checks=0x08, lef_report_sliding_contacts=0x10,
rope_findiff_attached_vel=0x01, rope_no_solver=0x02, rope_ignore_attachments=0x4, rope_target_vtx_rel0=0x08, rope_target_vtx_rel1=0x10,
rope_subdivide_segs=0x100,
se_skip_longest_edges=0x01,
ref_use_simple_solver=0x01, ref_no_splashes=0x04, ref_checksum_received=0x04, ref_checksum_outofsync=0x08,
aef_recorded_physics = 0x02,
wwef_fake_inner_wheels = 0x10,
pef_disabled=0x20, pef_never_break=0x40, pef_deforming=0x80, pef_pushable_by_players=0x200,
pef_traceable=0x400, particle_traceable=0x400, rope_traceable=0x400, pef_update=0x800,
pef_monitor_state_changes=0x1000, pef_monitor_collisions=0x2000, pef_monitor_env_changes=0x4000, pef_never_affect_triggers=0x8000,
pef_invisible=0x10000, pef_ignore_ocean=0x20000, pef_fixed_damping=0x40000, pef_custom_poststep=0x80000, pef_monitor_poststep=0x80000,
pef_always_notify_on_deletion=0x100000,
rope_collides=0x200000, rope_collides_with_terrain=0x400000, rope_no_stiffness_when_colliding=0x10000000,
pef_override_impulse_scale=0x200000, pef_players_can_break=0x400000, pef_cannot_squash_players=0x10000000,
pef_ignore_areas=0x800000,
pef_log_state_changes=0x1000000, pef_log_collisions=0x2000000, pef_log_env_changes=0x4000000, pef_log_poststep=0x8000000,
};
struct pe_params_flags : pe_params {
enum entype { type_id=15 };
pe_params_flags() { type=type_id; MARK_UNUSED flags,flagsOR,flagsAND; }
unsigned int flags;
unsigned int flagsOR;
unsigned int flagsAND;
};
struct pe_params_ground_plane : pe_params {
enum entype { type_id=20 };
pe_params_ground_plane() { type=type_id; iPlane=0; MARK_UNUSED ground.origin,ground.n; }
int iPlane; // index of the plane to be set (-1 removes existing planes)
primitives::plane ground;
};
struct pe_params_structural_joint : pe_params {
enum entype { type_id=21 };
pe_params_structural_joint() {
type=type_id; id=0; bReplaceExisting=0;
MARK_UNUSED idx,partid[0],partid[1],pt,n,maxForcePush,maxForcePull,maxForceShift,maxTorqueBend,maxTorqueTwist,
bBreakable,szSensor,bBroken,partidEpicenter;
}
int id,idx;
int bReplaceExisting;
int partid[2];
Vec3 pt;
Vec3 n;
float maxForcePush,maxForcePull,maxForceShift;
float maxTorqueBend,maxTorqueTwist;
int bBreakable;
float szSensor;
int bBroken;
int partidEpicenter;
};
struct pe_params_timeout : pe_params {
enum entype { type_id=23 };
pe_params_timeout() { type=type_id; MARK_UNUSED timeIdle,maxTimeIdle; }
float timeIdle,maxTimeIdle;
};
////////// articulated entity params
enum joint_flags { angle0_locked=1, all_angles_locked=7, angle0_limit_reached=010, angle0_auto_kd=0100, joint_no_gravity=01000,
joint_isolated_accelerations=02000, joint_expand_hinge=04000, angle0_gimbal_locked=010000,
joint_dashpot_reached=0100000, joint_ignore_impulses=0200000 };
struct pe_params_joint : pe_params {
enum entype { type_id=5 };
pe_params_joint() {
type=type_id;
for(int i=0;i<3;i++)
MARK_UNUSED limits[0][i],limits[1][i],qdashpot[i],kdashpot[i],bounciness[i],q[i],qext[i],ks[i],kd[i],qtarget[i];
bNoUpdate=0; pMtx0=0; flagsPivot=3;
MARK_UNUSED flags,q0,pivot,ranimationTimeStep,nSelfCollidingParts,animationTimeStep;
}
unsigned int flags; // should be a combination of angle0,1,2_locked, angle0,1,2_auto_kd, joint_no_gravity
int flagsPivot; // if bit 0 is set, update pivot point in parent frame, if bit 1 - in child
Vec3 pivot; // joint pivot in entity CS
quaternionf q0; // orientation of child in parent coordinates that corresponds to angles (0,0,0)
Matrix33 *pMtx0; // same as 3x3 row major matrix
Vec3 limits[2]; // limits for each angle
Vec3 bounciness; // bounciness for each angle (applied when limit is reached)
Vec3 ks,kd; // stiffness and damping koefficients for each angle angular spring
Vec3 qdashpot; // limit vicinity where joints starts resisting movement
Vec3 kdashpot; // when dashpot is activated, this is roughly the angular speed, stopped in 2 sec
Ang3 q; // angles values
Ang3 qext; // additional angles values (angle[i] = q[i]+qext[i]; only q[i] is taken into account
// while calculating spring torque
Ang3 qtarget;
int op[2]; // body identifiers of parent and child respectively
int nSelfCollidingParts,*pSelfCollidingParts; // part ids of only parts that should be checked for self-collision
int bNoUpdate; // omit recalculation of body parameters after changing this joint
float animationTimeStep; // used to calculate joint velocities of animation
float ranimationTimeStep; // 1/animation time step, can be not specified (specifying just saves extra division operation)
VALIDATORS_START
VALIDATOR(pivot)
VALIDATOR_NORM(q0)
VALIDATOR(q)
VALIDATOR(qext)
VALIDATORS_END
};
struct pe_params_articulated_body : pe_params {
enum entype { type_id=8 };
pe_params_articulated_body() {
type=type_id;
MARK_UNUSED bGrounded,bInheritVel,bCheckCollisions,bCollisionResp,bExpandHinges;
MARK_UNUSED bGrounded,bInheritVel,bCheckCollisions,bCollisionResp, a,wa,w,v,pivot, scaleBounceResponse,posHostPivot,qHostPivot;
MARK_UNUSED bAwake,pHost,nCollLyingMode, gravityLyingMode,dampingLyingMode,minEnergyLyingMode,iSimType,iSimTypeLyingMode,nRoots;
bApply_dqext=0; bRecalcJoints=1;
}
int bGrounded; // whether body's pivot is firmly attached to something or free
int bCheckCollisions;
int bCollisionResp;
Vec3 pivot; // attachment position for grounded bodies
Vec3 a; // acceleration of ground for grounded bodies
Vec3 wa; // angular acceleration of ground for grounded bodies
Vec3 w; // angular velocity of ground for grounded bodies
Vec3 v;
float scaleBounceResponse; // scales impulsive torque that is applied at a joint that has just reached its limit
int bApply_dqext; // adds current dqext to joints velocities. dqext is the speed of external animation and is calculated each time
// qext is set for joint (as difference between new value and current value, multiplied by inverse of animation timestep)
int bAwake;
IPhysicalEntity *pHost;
Vec3 posHostPivot;
quaternionf qHostPivot;
int bInheritVel;
int nCollLyingMode;
Vec3 gravityLyingMode;
float dampingLyingMode;
float minEnergyLyingMode;
int iSimType;
int iSimTypeLyingMode;
int bExpandHinges;
int nRoots; // only used in GetParams
int bRecalcJoints;
};
////////// living entity params
struct pe_player_dimensions : pe_params {
enum entype { type_id=1 };
pe_player_dimensions() : dirUnproj(0,0,1),maxUnproj(0) {
type=type_id; MARK_UNUSED sizeCollider,heightPivot,heightCollider,heightEye,heightHead,headRadius,bUseCapsule;
}
float heightPivot; // offset from central ground position that is considered entity center
float heightEye; // vertical offset of camera
Vec3 sizeCollider; // collision cylinder dimensions
float heightCollider; // vertical offset of collision geometry center
float headRadius;
float heightHead;
Vec3 dirUnproj;
float maxUnproj;
int bUseCapsule;
VALIDATORS_START
VALIDATOR(heightPivot)
VALIDATOR(heightEye)
VALIDATOR_RANGE2(sizeCollider,0,100)
VALIDATORS_END
};
struct pe_player_dynamics : pe_params {
enum entype { type_id=4 };
pe_player_dynamics() {
type=type_id; MARK_UNUSED kInertia,kInertiaAccel,kAirControl,gravity,gravity.z,nodSpeed,mass, bSwimming,surface_idx,bActive,collTypes;
MARK_UNUSED minSlideAngle,maxClimbAngle,maxJumpAngle,minFallAngle,kAirResistance,bNetwork,maxVelGround,timeImpulseRecover,iRequestedTime; }
float kInertia; // inertia koefficient, the more it is, the less inertia is; 0 means no inertia
float kInertiaAccel; // inertia on acceleration
float kAirControl; // air control koefficient 0..1, 1 - special value (total control of movement)
float kAirResistance;
Vec3 gravity; // gravity vector
float nodSpeed;
int bSwimming; // whether entity is swimming (is not bound to ground plane)
float mass; // mass (in kg)
int surface_idx; // surface identifier for collisions
float minSlideAngle; // if surface slope is more than this angle, player starts sliding (angle is in radians)
float maxClimbAngle; // player cannot climb surface which slope is steeper than this angle
float maxJumpAngle; // player is not allowed to jump towards ground if this angle is exceeded
float minFallAngle; // player starts falling when slope is steeper than this
float maxVelGround; // player cannot stand of surfaces that are moving faster than this
float timeImpulseRecover; // forcefully turns on inertia for that duration after receiving an impulse
int collTypes; // entity types to check collisions against
int bNetwork;
int bActive;
int iRequestedTime; // requests that the player rolls back to that time and re-exucutes pending actions during the next step
};
////////// particle entity params
struct pe_params_particle : pe_params {
enum entype { type_id=3 };
pe_params_particle() {
type=type_id;
MARK_UNUSED mass,size,thickness,wspin,accThrust,kAirResistance,kWaterResistance, velocity,heading,accLift,accThrust,gravity,waterGravity;
MARK_UNUSED surface_idx, normal,q0,minBounceVel, flags,pColliderToIgnore, iPierceability, areaCheckPeriod;
}
unsigned int flags; // see entity flags
float mass;
float size; // pseudo-radius
float thickness; // thickness when lying on a surface (if left unused, size will be used)
Vec3 heading; // direction of movement
float velocity; // velocity along "heading"
float kAirResistance; // air resistance koefficient, F = kv
float kWaterResistance; // same for water
float accThrust; // acceleration along direction of movement
float accLift; // acceleration that lifts particle with the current speed
int surface_idx;
Vec3 wspin; // angular velocity
Vec3 gravity;
Vec3 waterGravity;
Vec3 normal;
quaternionf q0; // initial orientation (zero means x along direction of movement, z up)
float minBounceVel;
IPhysicalEntity *pColliderToIgnore; // physical entity to ignore during collisions
int iPierceability;
int areaCheckPeriod; // how often (in frames) world area checks are made
VALIDATORS_START
VALIDATOR(mass)
VALIDATOR(size)
VALIDATOR(thickness)
VALIDATOR_NORM(heading)
VALIDATOR_NORM(normal)
VALIDATOR_NORM(q0)
VALIDATORS_END
};
////////// vehicle entity params
struct pe_params_car : pe_params {
enum entype { type_id=2 };
pe_params_car() {
type=type_id;
MARK_UNUSED engineMaxRPM,iIntegrationType,axleFriction,enginePower,maxSteer,maxTimeStep,minEnergy,damping,brakeTorque;
MARK_UNUSED engineMinRPM,engineShiftUpRPM,engineShiftDownRPM,engineIdleRPM,engineStartRPM,clutchSpeed,nGears,gearRatios,kStabilizer;
MARK_UNUSED slipThreshold,gearDirSwitchRPM,kDynFriction,minBrakingFriction,maxBrakingFriction,steerTrackNeutralTurn,maxGear,minGear,pullTilt;
}
float axleFriction; // friction torque at axes divided by mass of vehicle
float enginePower; // power of engine (about 10,000 - 100,000)
float maxSteer; // maximum steering angle
float engineMaxRPM; // engine torque decreases to 0 after reaching this rotation speed
float brakeTorque;
int iIntegrationType; // for suspensions; 0-explicit Euler, 1-implicit Euler
float maxTimeStep; // maximum time step when vehicle has only wheel contacts
float minEnergy; // minimum awake energy when vehicle has only wheel contacts
float damping; // damping when vehicle has only wheel contacts
float minBrakingFriction; // limits the the tire friction when handbraked
float maxBrakingFriction; // limits the the tire friction when handbraked
float kStabilizer; // stabilizer force, as a multiplier for kStiffness of respective suspensions
int nWheels; // the number of wheels
float engineMinRPM;
float engineShiftUpRPM;
float engineShiftDownRPM;
float engineIdleRPM;
float engineStartRPM;
float clutchSpeed;
int nGears;
float *gearRatios;
int maxGear,minGear;
float slipThreshold;
float gearDirSwitchRPM;
float kDynFriction;
float steerTrackNeutralTurn;
float pullTilt; // tilt angle of pulling force towards ground [rad]
};
struct pe_params_wheel : pe_params {
enum entype { type_id=16 };
pe_params_wheel() {
type=type_id; iWheel=0; MARK_UNUSED bDriving,iAxle,suspLenMax,suspLenInitial,minFriction,maxFriction,surface_idx,bCanBrake,bBlocked,
bRayCast,kStiffness,kDamping,kLatFriction,Tscale;
}
int iWheel;
int bDriving;
int iAxle;
int bCanBrake;
int bBlocked;
float suspLenMax;
float suspLenInitial;
float minFriction;
float maxFriction;
int surface_idx;
int bRayCast;
float kStiffness;
float kDamping;
float kLatFriction;
float Tscale;
};
////////// rope entity params
struct pe_params_rope : pe_params {
enum entype { type_id=13 };
pe_params_rope() {
type=type_id; MARK_UNUSED length,mass,bCheckCollisions,collDist,surface_idx,friction,nSegments,pPoints.data,pVelocities.data;
MARK_UNUSED pEntTiedTo[0],ptTiedTo[0],idPartTiedTo[0],pEntTiedTo[1],ptTiedTo[1],idPartTiedTo[1],stiffnessAnim,maxForce,
flagsCollider,nMaxSubVtx,stiffnessDecayAnim,dampingAnim,bTargetPoseActive,wind,windVariance,airResistance,waterResistance,density,
jointLimit,sensorRadius,frictionPull,stiffness,collisionBBox[0];
bLocalPtTied = 0;
}
float length;
float mass;
int bCheckCollisions;
float collDist;
int surface_idx;
float friction;
float frictionPull;
float stiffness;
float stiffnessAnim;
float stiffnessDecayAnim;
float dampingAnim;
int bTargetPoseActive;
Vec3 wind;
float windVariance;
float airResistance;
float waterResistance;
float density;
float jointLimit;
float sensorRadius;
float maxForce;
int nSegments;
int flagsCollider;
int nMaxSubVtx;
Vec3 collisionBBox[2];
strided_pointer<Vec3> pPoints;
strided_pointer<Vec3> pVelocities;
IPhysicalEntity *pEntTiedTo[2];
int bLocalPtTied;
Vec3 ptTiedTo[2];
int idPartTiedTo[2];
};
////////// soft entity params
struct pe_params_softbody : pe_params {
enum entype { type_id=17 };
pe_params_softbody() { type=type_id; MARK_UNUSED thickness,maxSafeStep,ks,kdRatio,airResistance,wind,windVariance,nMaxIters,
accuracy,friction,impulseScale,explosionScale,collisionImpulseScale,maxCollisionImpulse,collTypes,waterResistance,massDecay; }
float thickness;
float maxSafeStep;
float ks;
float kdRatio;
float friction;
float waterResistance;
float airResistance;
Vec3 wind;
float windVariance;
int nMaxIters;
float accuracy;
float impulseScale;
float explosionScale;
float collisionImpulseScale;
float maxCollisionImpulse;
int collTypes;
float massDecay;
};
/////////// area params
struct pe_params_area : pe_params {
enum entype { type_id=18 };
pe_params_area() { type=type_id; MARK_UNUSED gravity,size,bUniform,damping,falloff0,bUseCallback,pGeom; }
Vec3 gravity;
Vec3 size; // ellipsoidal falloff dimensions; 0,0,0 if no falloff
float falloff0;
int bUniform; // same direction in every point or always point to the center
int bUseCallback;
float damping;
IGeometry *pGeom;
};
////////// water manager params
struct pe_params_waterman : pe_params {
enum entype { type_id=22 };
pe_params_waterman() {
type=type_id; MARK_UNUSED posViewer,nExtraTiles,nCells,tileSize,timeStep,waveSpeed,
dampingCenter,dampingRim,minhSpread,minVel;
}
Vec3 posViewer;
int nExtraTiles;
int nCells;
float tileSize;
float timeStep;
float waveSpeed;
float dampingCenter;
float dampingRim;
float minhSpread;
float minVel;
};
////////////////////////// Action structures /////////////////////
////////// common actions
struct pe_action {
int type;
};
struct pe_action_impulse : pe_action {
enum entype { type_id=2 };
pe_action_impulse() { type=type_id; impulse.Set(0,0,0); MARK_UNUSED point,angImpulse,partid,ipart; iApplyTime=2; iSource=0; }
Vec3 impulse;
Vec3 angImpulse; // optional
Vec3 point; // point of application, in world CS, optional
int partid; // receiver part identifier
int ipart; // alternatively, part index can be used
int iApplyTime; // 0-apply immediately, 1-apply before the next time step, 2-apply after the next time step
int iSource; // reserved for internal use
VALIDATORS_START
VALIDATOR_RANGE2(impulse,0,1E8f)
VALIDATOR_RANGE2(angImpulse,0,1E8f)
VALIDATOR_RANGE2(point,0,1E6f)
VALIDATOR_RANGE(ipart,0,10000)
VALIDATORS_END
};
struct pe_action_reset : pe_action { // Resets dynamic state of an entity
enum entype { type_id=4 };
pe_action_reset() { type=type_id; bClearContacts=1; }
int bClearContacts;
};
enum constrflags { local_frames=1, world_frames=2, constraint_inactive=0x100, constraint_ignore_buddy=0x200 };
struct pe_action_add_constraint : pe_action {
enum entype { type_id=5 };
pe_action_add_constraint() {
type=type_id; pBuddy=0; flags=world_frames;
MARK_UNUSED id,pt[0],pt[1],partid[0],partid[1],qframe[0],qframe[1],xlimits[0],yzlimits[0],
pConstraintEntity,damping,sensorRadius,maxPullForce,maxBendTorque;
}
int id;
IPhysicalEntity *pBuddy;
Vec3 pt[2];
int partid[2];
quaternionf qframe[2];
float xlimits[2];
float yzlimits[2];
unsigned int flags;
float damping;
float sensorRadius;
float maxPullForce,maxBendTorque;
IPhysicalEntity *pConstraintEntity;
};
struct pe_action_update_constraint : pe_action {
enum entype { type_id=6 };
pe_action_update_constraint() { type=type_id; MARK_UNUSED idConstraint,pt[0],pt[1]; flagsOR=0;flagsAND=(unsigned int)-1;bRemove=0; flags=world_frames; }
int idConstraint;
unsigned int flagsOR;
unsigned int flagsAND;
int bRemove;
Vec3 pt[2];
int flags;
};
struct pe_action_register_coll_event : pe_action {
enum entype { type_id=7 };
pe_action_register_coll_event() { type=type_id; MARK_UNUSED vSelf; }
Vec3 pt;
Vec3 n;
Vec3 v, vSelf;
float collMass;
IPhysicalEntity *pCollider;
int partid[2];
int idmat[2];
};
struct pe_action_awake : pe_action {
enum entype { type_id=8 };
pe_action_awake() { type=type_id; bAwake=1; }
int bAwake;
};
struct pe_action_remove_all_parts : pe_action {
enum entype { type_id=9 };
pe_action_remove_all_parts() { type=type_id; }
};
struct pe_action_reset_part_mtx : pe_action {
enum entype { type_id=13 };
pe_action_reset_part_mtx() { type=type_id; MARK_UNUSED ipart,partid; }
int ipart;
int partid;
};
struct pe_action_set_velocity : pe_action {
enum entype { type_id=10 };
pe_action_set_velocity() { type=type_id; MARK_UNUSED ipart,partid,v,w; }
int ipart;
int partid;
Vec3 v,w;
VALIDATORS_START
VALIDATOR_RANGE2(v,0,1E5f)
VALIDATOR_RANGE2(w,0,1E5f)
VALIDATORS_END
};
struct pe_action_notify : pe_action {
enum entype { type_id=14 };
enum encodes { ParentChange=0 };
pe_action_notify() { type=type_id; iCode=ParentChange; }
int iCode;
};
struct pe_action_auto_part_detachment : pe_action {
enum entype { type_id=15 };
pe_action_auto_part_detachment() { type=type_id; MARK_UNUSED threshold,autoDetachmentDist; }
float threshold;
float autoDetachmentDist;
};
struct pe_action_move_parts : pe_action {
enum entype { type_id=16 };
int idStart,idEnd;
int idOffset;
IPhysicalEntity *pTarget;
Matrix34 mtxRel;
pe_action_move_parts() { type=type_id; idStart=0; idEnd=1<<30; idOffset=0; mtxRel.SetIdentity(); pTarget=0; }
};
////////// living entity actions
struct pe_action_move : pe_action { // movement request for living entities
enum entype { type_id=1 };
pe_action_move() { type=type_id; iJump=0; dt=0; MARK_UNUSED dir; }
Vec3 dir; // dir requested velocity vector
int iJump; // jump mode - 1-instant velocity change, 2-just adds to current velocity
float dt; // time interval for this action
VALIDATORS_START
VALIDATOR_RANGE2(dir,0,1000)
VALIDATOR_RANGE(dt,0,2)
VALIDATORS_END
};
////////// vehicle entity actions
struct pe_action_drive : pe_action {
enum entype { type_id=3 };
pe_action_drive() { type=type_id; MARK_UNUSED pedal,dpedal,steer,dsteer,bHandBrake,clutch,iGear; }
float pedal; // engine pedal absolute value
float dpedal; // engine pedal delta
float steer; // steering angle absolute value
float dsteer; // steering angle delta
float clutch;
int bHandBrake;
int iGear;
};
////////// rope entity actions
struct pe_action_target_vtx : pe_action {
enum entype { type_id=12 };
pe_action_target_vtx() { type=type_id; MARK_UNUSED points,nPoints; }
int nPoints;
Vec3 *points;
};
////////// soft entity actions
struct pe_action_attach_points : pe_action {
enum entype { type_id=11 };
pe_action_attach_points() { type=type_id; MARK_UNUSED partid,points; nPoints=1; pEntity=WORLD_ENTITY; }
IPhysicalEntity *pEntity;
int partid;
int *piVtx;
Vec3 *points;
int nPoints;
};
////////////////////////// Status structures /////////////////////
////////// common statuses
struct pe_status {
int type;
};
enum status_pos_flags { status_local=1,status_thread_safe=2,status_addref_geoms=4 };
struct pe_status_pos : pe_status {
enum entype { type_id=1 };
pe_status_pos() { type=type_id; ipart=partid=-1; flags=0; pMtx3x4=0;pMtx3x3=0; iSimClass=0; timeBack=0; }
int partid; // part identifier, -1 for entire entity
int ipart; // optionally, part slot index
unsigned int flags; // status_local if part coordinates should be returned in entity CS rather than world CS
unsigned int flagsOR; // boolean OR for all parts flags of the object (or just flags for the selected part)
unsigned int flagsAND; // boolean AND for all parts flags of the object (or just flags for the selected part)
Vec3 pos; // position of center
Vec3 BBox[2]; // bounding box relative to pos (bbox[0]-min, bbox[1]-max)
quaternionf q;
float scale;
int iSimClass;
Matrix34* pMtx3x4;
Matrix33* pMtx3x3; // optional 3x3 matrix buffer that receives transformation
IGeometry *pGeom,*pGeomProxy;
float timeBack; // can retrieve pervious position; only supported by rigid entities; pos and q; one step back
};
struct pe_status_extent : pe_status { // Caches eForm extent of entity in pGeo
enum entype { type_id=24 };
pe_status_extent() { type=type_id; eForm=EGeomForm(-1); pGeo=0; }
EGeomForm eForm;
GeomQuery* pGeo;
};
struct pe_status_random : pe_status_extent { // Generates random pos on entity, also caches extent
enum entype { type_id=25 };
pe_status_random() { type=type_id; ran.vPos.zero(); ran.vNorm.zero(); }
RandomPos ran;
};
struct pe_status_sensors : pe_status { // Requests status of attached to the entity sensors
enum entype { type_id=18 };
pe_status_sensors() { type=type_id; }
Vec3 *pPoints; // pointer to array of points where sensors touch environment (assigned by physical entity)
Vec3 *pNormals; // pointer to array of surface normals at points where sensors touch environment
unsigned int flags; // bitmask of flags, bit==1 - sensor touched environment
};
struct pe_status_dynamics : pe_status {
enum entype { type_id=8 };
pe_status_dynamics() : v(ZERO),w(ZERO),a(ZERO),wa(ZERO),centerOfMass(ZERO) {
MARK_UNUSED partid,ipart; type=type_id; mass=energy=0; nContacts=0; time_interval=0; submergedFraction=0;
}
int partid;
int ipart;
Vec3 v; // velocity
Vec3 w; // angular velocity
Vec3 a; // linear acceleration
Vec3 wa; // angular acceleration
Vec3 centerOfMass;
float submergedFraction;
float mass;
float energy;
int nContacts;
float time_interval;
};
struct coll_history_item {
Vec3 pt; // collision area center
Vec3 n; // collision normal in entity CS
Vec3 v[2]; // velocities of contacting bodies at the point of impact
float mass[2]; // masses of contacting bodies
float age; // age of collision event
int idCollider; // id of collider (not a pointer, since collider can be destroyed before history item is queried)
int partid[2];
int idmat[2]; // 0-this body material, 1-collider material
};
struct pe_status_collisions : pe_status {
enum entype { type_id=9 };
pe_status_collisions() { type=type_id; age=0; len=1; pHistory=0; bClearHistory=0; }
coll_history_item *pHistory; // pointer to a user-provided array of history items
int len; // length of this array
float age; // maximum age of collision events (older events are ignored)
int bClearHistory;
};
struct pe_status_id : pe_status {
enum entype { type_id=10 };
pe_status_id() { type=type_id; ipart=partid=-1; bUseProxy=1; }
int ipart;
int partid;
int iPrim;
int iFeature;
int bUseProxy;
int id; // usually id means material
};
struct pe_status_timeslices : pe_status {
enum entype { type_id=11 };
pe_status_timeslices() { type=type_id; pTimeSlices=0; sz=1; precision=0.0001f; MARK_UNUSED time_interval; }
float *pTimeSlices;
int sz;
float precision; // time surplus below this threshhold will be discarded
float time_interval; // if unused, time elapsed since the last action will be used
};
struct pe_status_nparts : pe_status {
enum entype { type_id=12 };
pe_status_nparts() { type=type_id; }
};
struct pe_status_awake : pe_status {
enum entype { type_id=7 };
pe_status_awake() { type=type_id; lag=0; }
int lag;
};
struct pe_status_contains_point : pe_status {
enum entype { type_id=13 };
pe_status_contains_point() { type=type_id; }
Vec3 pt;
};
struct pe_status_placeholder : pe_status {
enum entype { type_id=16 };
pe_status_placeholder() { type=type_id; }
IPhysicalEntity *pFullEntity;
};
struct pe_status_sample_contact_area : pe_status {
enum entype { type_id=19 };
pe_status_sample_contact_area() { type=type_id; }
Vec3 ptTest;
Vec3 dirTest;
};
struct pe_status_caps : pe_status {
enum entype { type_id=20 };
pe_status_caps() { type=type_id; }
unsigned int bCanAlterOrientation; // can change orientation that is explicitly set from outside
};
struct pe_status_constraint : pe_status {
enum entype { type_id=26 };
pe_status_constraint() { type=type_id; }
int id;
int flags;
Vec3 pt[2];
Vec3 n;
};
////////// area status
struct pe_status_area : pe_status {
enum entype { type_id=23 };
pe_status_area() { type=type_id; bUniformOnly=false; ctr.zero(); size.zero(); vel.zero(); MARK_UNUSED gravity, pb; pLockUpdate=0; }
// inputs.
Vec3 ctr, size; // query bounds
Vec3 vel;
bool bUniformOnly;
// outputs.
Vec3 gravity;
pe_params_buoyancy pb;
volatile int *pLockUpdate;
};
////////// living entity statuses
struct pe_status_living : pe_status {
enum entype { type_id=2 };
pe_status_living() { type=type_id; }
int bFlying; // whether entity has no contact with ground
float timeFlying; // for how long the entity was flying
Vec3 camOffset; // camera offset
Vec3 vel; // actual velocity (as rate of position change)
Vec3 velUnconstrained; // 'physical' movement velocity
Vec3 velRequested; // velocity requested in the last action
Vec3 velGround; // velocity of the object entity is standing on
float groundHeight; // position where the last contact with the ground occured
Vec3 groundSlope;
int groundSurfaceIdx;
int groundSurfaceIdxAux;
IPhysicalEntity *pGroundCollider;
int iGroundColliderPart;
float timeSinceStanceChange;
int bOnStairs;
int bStuck;
volatile int *pLockStep;
int iCurTime;
int bSquashed;
};
struct pe_status_check_stance : pe_status {
enum entype { type_id=21 };
pe_status_check_stance() : dirUnproj(0,0,1),unproj(0) { type=type_id; MARK_UNUSED pos,q,sizeCollider,heightCollider,bUseCapsule; }
Vec3 pos;
quaternionf q;
Vec3 sizeCollider;
float heightCollider;
Vec3 dirUnproj;
float unproj;
int bUseCapsule;
};
////////// vehicle entity statuses
struct pe_status_vehicle : pe_status {
enum entype { type_id=4 };
pe_status_vehicle() { type=type_id; }
float steer; // current steering angle
float pedal; // current engine pedal
int bHandBrake; // nonzero if handbrake is on
float footbrake; // nonzero if footbrake is pressed (range 0..1)
Vec3 vel;
int bWheelContact; // nonzero if at least one wheel touches ground
int iCurGear;
float engineRPM;
float clutch;
float drivingTorque;
int nActiveColliders;
};
struct pe_status_wheel : pe_status {
enum entype { type_id=5 };
pe_status_wheel() { type=type_id; iWheel=0; MARK_UNUSED partid; }
int iWheel;
int partid;
int bContact; // nonzero if wheel touches ground
Vec3 ptContact; // point where wheel touches ground
float w; // rotation speed
int bSlip;
Vec3 velSlip; // slip velocity
int contactSurfaceIdx;
float friction; // current friction applied
float suspLen; // current suspension spring length
float suspLenFull; // relaxed suspension spring length
float suspLen0; // initial suspension spring length
float r; // wheel radius
float torque; // driving torque
IPhysicalEntity* pCollider;
};
struct pe_status_vehicle_abilities : pe_status {
enum entype { type_id=15 };
pe_status_vehicle_abilities() { type=type_id; MARK_UNUSED steer; }
float steer; // should be set to requested steering angle
Vec3 rotPivot; // returns turning circle center
float maxVelocity; // calculates maximum velocity of forward movement along a plane (steer is ignored)
};
////////// articulated entity statuses
struct pe_status_joint : pe_status {
enum entype { type_id=6 };
pe_status_joint() { type=type_id; MARK_UNUSED partid,idChildBody; }
int idChildBody; // requested joint is identified by child body id
int partid; // ..or, alternatively, by any of parts that belong to it
unsigned int flags; // joint flags
Ang3 q; // current joint angles (controlled by physics)
Ang3 qext; // external angles (from animation)
Ang3 dq; // current joint angular velocities
quaternionf quat0;
};
////////// rope entity statuses
struct pe_status_rope : pe_status {
enum entype { type_id=14 };
pe_status_rope() { type=type_id; pPoints=pVelocities=pVtx=pContactNorms=0; nCollStat=nCollDyn=bTargetPoseActive=0;
pContactEnts=0; stiffnessAnim=timeLastActive=0; nVtx=0; }
int nSegments;
Vec3 *pPoints;
Vec3 *pVelocities;
int nCollStat,nCollDyn;
int bTargetPoseActive;
float stiffnessAnim;
strided_pointer<IPhysicalEntity*> pContactEnts;
int nVtx;
Vec3 *pVtx;
Vec3 *pContactNorms;
float timeLastActive;
};
////////// soft entity statuses
enum ESSVFlags { eSSV_LockPos=1, eSSV_UnlockPos=2 };
struct pe_status_softvtx : pe_status {
enum entype { type_id=17 };
pe_status_softvtx() { type=type_id; pVtx=pNormals=0; pVtxMap=0; flags=0; }
int nVtx;
strided_pointer<Vec3> pVtx;
strided_pointer<Vec3> pNormals;
int *pVtxMap;
int flags;
};
////////// waterman statuses
struct SWaterTileBase {
int bActive;
float *ph;
float *pvel;
};
struct pe_status_waterman : pe_status {
enum entype { type_id=22 };
pe_status_waterman() { type=type_id; }
int bActive;
Matrix33 R;
Vec3 origin;
int nTiles,nCells; // number of tiles and cells in one dimension
SWaterTileBase **pTiles; // nTiles^2 entries
};
////////////////////////// Geometry structures /////////////////////
////////// common geometries
enum geom_flags { geom_colltype0=0x0001, geom_colltype1=0x0002, geom_colltype2=0x0004, geom_colltype3=0x0008, geom_colltype4=0x0010,
geom_colltype5=0x0020, geom_colltype6=0x0040, geom_colltype7=0x0080, geom_colltype8=0x0100, geom_colltype9=0x0200,
geom_colltype10=0x0400,geom_colltype11=0x0800,geom_colltype12=0x1000,geom_colltype13=0x2000,geom_colltype14=0x4000,
geom_colltype_ray=0x8000, geom_floats=0x10000,
geom_proxy=0x20000, geom_structure_changes=0x40000, geom_can_modify=0x80000,
geom_squashy=0x100000, geom_log_interactions=0x200000,
geom_monitor_contacts=0x400000, geom_manually_breakable=0x800000,
geom_no_coll_response=0x1000000, geom_mat_substitutor=0x2000000,
geom_break_approximation=0x4000000,
// mnemonic group names
geom_colltype_player=geom_colltype1, geom_colltype_explosion=geom_colltype2,
geom_colltype_vehicle=geom_colltype3, geom_colltype_foliage=geom_colltype4, geom_colltype_debris=geom_colltype5,
geom_colltype_foliage_proxy=geom_colltype13, geom_colltype_obstruct=geom_colltype14,
geom_colltype_solid=0x0FFF&~geom_colltype_explosion, geom_collides=0xFFFF
};
struct pe_geomparams {
enum entype { type_id=0 };
pe_geomparams() {
type=type_id; density=mass=0; pos.Set(0,0,0); q.SetIdentity(); bRecalcBBox=1;
flags = geom_colltype_solid|geom_colltype_ray|geom_floats|geom_colltype_explosion; flagsCollider = geom_colltype0;
pMtx3x4=0;pMtx3x3=0; scale=1.0f; pLattice=0; pMatMapping=0; nMats=0;
MARK_UNUSED surface_idx,minContactDist,idmatBreakable;
}
int type;
float density; // 0 if mass is used
float mass; // 0 if density is used
Vec3 pos; // offset from object's geometrical pivot
quaternionf q; // orientation relative to object
float scale;
Matrix34 *pMtx3x4;
Matrix33 *pMtx3x3; // optional 3x3 orintation+scale matrix
int surface_idx; // surface identifier (used if corresponding CGeometry does not contain materials)
unsigned int flags,flagsCollider;
float minContactDist;
int idmatBreakable;
ITetrLattice *pLattice;
int *pMatMapping;
int nMats;
int bRecalcBBox;
VALIDATORS_START
VALIDATOR_RANGE(density,-1E8,1E8)
VALIDATOR_RANGE(mass,-1E8,1E8)
VALIDATOR(pos)
VALIDATOR_NORM(q)
VALIDATORS_END
};
////////// articulated entity geometries
struct pe_articgeomparams : pe_geomparams {
enum entype { type_id=2 };
pe_articgeomparams() { type=type_id; idbody=0; }
pe_articgeomparams(pe_geomparams &src) {
type=type_id; density=src.density; mass=src.mass; pos=src.pos; q=src.q; scale=src.scale; surface_idx=src.surface_idx;
pLattice=src.pLattice; pMatMapping=src.pMatMapping; nMats=src.nMats;
pMtx3x4=src.pMtx3x4;pMtx3x3=src.pMtx3x3; flags=src.flags; flagsCollider=src.flagsCollider;
idbody=0; idmatBreakable=src.idmatBreakable; bRecalcBBox=src.bRecalcBBox;
if (!is_unused(src.minContactDist)) minContactDist=src.minContactDist; else MARK_UNUSED minContactDist;
}
int idbody; // id of the subbody this geometry is attached to, the 1st add geometry specifies frame CS of this subbody
};
////////// vehicle entity geometries
const int NMAXWHEELS = 18;
struct pe_cargeomparams : pe_geomparams {
enum entype { type_id=1 };
pe_cargeomparams() : pe_geomparams() { type=type_id; MARK_UNUSED bDriving,minFriction,maxFriction,bRayCast,kLatFriction; bCanBrake=1; }
pe_cargeomparams(pe_geomparams &src) {
type=type_id; density=src.density; mass=src.mass; pos=src.pos; q=src.q; surface_idx=src.surface_idx;
idmatBreakable=src.idmatBreakable; pLattice=src.pLattice; pMatMapping=src.pMatMapping; nMats=src.nMats;
pMtx3x4=src.pMtx3x4;pMtx3x3=src.pMtx3x3; flags=src.flags; flagsCollider=src.flagsCollider;
MARK_UNUSED bDriving,minFriction,maxFriction,bRayCast; bCanBrake=1;
}
int bDriving; // whether wheel is driving, -1 - geometry os not a wheel
int iAxle; // wheel axle, currently not used
int bCanBrake; // whether the wheel is locked during handbrakes
int bRayCast; // whether the wheel use simple raycasting instead of geometry sweep check
Vec3 pivot; // upper suspension point in vehicle CS
float lenMax; // relaxed suspension length
float lenInitial; // current suspension length (assumed to be length in rest state)
float kStiffness; // suspension stiffness, if 0 - calculate from lenMax, lenInitial, and vehicle mass and geometry
float kDamping; // suspension damping, if <0 - calculate as -kdamping*(approximate zero oscillations damping)
float minFriction,maxFriction; // additional friction limits for tire friction
float kLatFriction; // coefficient for lateral friction
};
///////////////// tetrahedra lattice params ////////////////////////
struct pe_tetrlattice_params : pe_params {
enum entype { type_id=19 };
pe_tetrlattice_params() {
type = type_id;
MARK_UNUSED nMaxCracks,maxForcePush,maxForcePull,maxForceShift, maxTorqueTwist,maxTorqueBend,crackWeaken,density;
}
int nMaxCracks;
float maxForcePush,maxForcePull,maxForceShift;
float maxTorqueTwist,maxTorqueBend;
float crackWeaken;
float density;
};
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IGeometry Interface ////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct geom_world_data {
geom_world_data() {
v.Set(0,0,0);
w.Set(0,0,0);
offset.Set(0,0,0);
R.SetIdentity();
centerOfMass.Set(0,0,0);
scale=1.0f; iStartNode=0;
}
Vec3 offset;
Matrix33 R;
float scale;
Vec3 v,w;
Vec3 centerOfMass;
int iStartNode;
};
struct intersection_params {
intersection_params() {
iUnprojectionMode=0;
vrel_min=1E-6f;
time_interval=100.0f;
maxSurfaceGapAngle=1.0f*float(g_PI/180);
pGlobalContacts=0;
minAxisDist=0;
bSweepTest=false;
centerOfRotation.Set(0,0,0);
axisContactNormal.Set(0,0,1);
unprojectionPlaneNormal.Set(0,0,0);
axisOfRotation.Set(0,0,0);
bKeepPrevContacts=false;
bStopAtFirstTri=false;
ptOutsidePivot[0].Set(1E11f,1E11f,1E11f);
ptOutsidePivot[1].Set(1E11f,1E11f,1E11f);
maxUnproj=1E10f;
bNoAreaContacts=false;
bNoBorder=false;
bNoIntersection=0;
bExactBorder=0;
bThreadSafe=bThreadSafeMesh=0;
plock=(volatile int*)&bThreadSafe;
}
int iUnprojectionMode;
Vec3 centerOfRotation;
Vec3 axisOfRotation;
float time_interval;
float vrel_min;
float maxSurfaceGapAngle;
float minAxisDist;
Vec3 unprojectionPlaneNormal;
Vec3 axisContactNormal;
float maxUnproj;
Vec3 ptOutsidePivot[2];
bool bSweepTest;
bool bKeepPrevContacts;
bool bStopAtFirstTri;
bool bNoAreaContacts;
bool bNoBorder;
int bExactBorder;
int bNoIntersection;
int bBothConvex;
int bThreadSafe; // only set if it's known that no other thread will contend for the internal intersection data
int bThreadSafeMesh;
geom_contact *pGlobalContacts;
volatile int *plock;
};
struct phys_geometry {
IGeometry *pGeom;
Vec3 Ibody;
quaternionf q;
Vec3 origin;
float V;
int nRefCount;
int surface_idx;
int *pMatMapping;
int nMats;
void *pForeignData;
AUTO_STRUCT_INFO
};
struct bop_newvtx {
int idx; // vertex index in the resulting A phys mesh
int iBvtx; // -1 if intersection vertex, >=0 if B vertex
int idxTri[2]; // intersecting triangles' foreign indices
};
struct bop_newtri {
int idxNew; // a newly generated foreign index (can be remapped later)
int iop; // triangle source 0=A, 1=B
int idxOrg; // original (triangulated) triangle's foreign index
int iVtx[3]; // for each vertex, existing vertex index if >=0, -(new vertex index+1) if <0
float areaOrg; // original triangle's area
Vec3 area[3]; // areas of compementary triangles for each vertex (divide by original tri area to get barycentric coords)
};
struct bop_vtxweld {
void set(int _ivtxDst,int _ivtxWelded) { ivtxDst=_ivtxDst; ivtxWelded=_ivtxWelded; }
int ivtxDst : 16; // ivtxWelded is getting replaced with ivtxDst
int ivtxWelded : 16;
};
struct bop_TJfix {
void set(int _iACJ,int _iAC, int _iABC,int _iCA, int _iTJvtx) { iACJ=_iACJ;iAC=_iAC;iABC=_iABC;iCA=_iCA;iTJvtx=_iTJvtx; }
// A _____J____ C (ACJ is a thin triangle on top of ABC; J is 'the junction vertex')
// \ . / in ABC: set A->Jnew
// \ . / in ACJ: set J->Jnew, A -> A from original ABC, C -> B from original ABC
// \/
// B
int iABC; // big triangle's foreign idx
int iACJ; // small triangle's foreign idx
int iCA; // CA edge number in ABC
int iAC; // AC edge number in ACJ
int iTJvtx; // J vertex index
};
struct bop_meshupdate_thunk {
bop_meshupdate_thunk() { prevRef=nextRef = this; }
~bop_meshupdate_thunk() { prevRef->nextRef = nextRef; nextRef->prevRef = prevRef; }
virtual void Release() { prevRef=nextRef = this; }
bop_meshupdate_thunk *prevRef,*nextRef;
};
struct bop_meshupdate : bop_meshupdate_thunk {
bop_meshupdate() { Reset(); }
~bop_meshupdate() { Release(); }
void Reset() {
pRemovedVtx=0; pRemovedTri=0; pNewVtx=0; pNewTri=0; pWeldedVtx=0; pTJFixes=0; pMovedBoxes=0;
nRemovedVtx=nRemovedTri=nNewVtx=nNewTri=nWeldedVtx=nTJFixes=nMovedBoxes = 0; next = 0;
pMesh[0]=pMesh[1]=0; relScale=1.0f;
}
virtual void Release();
IGeometry *pMesh[2]; // 0-dst (A), 1-src (B)
int *pRemovedVtx;
int nRemovedVtx;
int *pRemovedTri;
int nRemovedTri;
bop_newvtx *pNewVtx;
int nNewVtx;
bop_newtri *pNewTri;
int nNewTri;
bop_vtxweld *pWeldedVtx;
int nWeldedVtx;
bop_TJfix *pTJFixes;
int nTJFixes;
bop_meshupdate *next;
primitives::box *pMovedBoxes;
int nMovedBoxes;
float relScale;
};
struct trinfo {
trinfo &operator=(trinfo &src) { ibuddy[0]=src.ibuddy[0]; ibuddy[1]=src.ibuddy[1]; ibuddy[2]=src.ibuddy[2]; return *this; }
index_t ibuddy[3];
};
struct mesh_island {
int itri;
int nTris;
int iParent,iChild,iNext;
float V;
Vec3 center;
int bProcessed;
};
struct tri2isle {
unsigned int inext : 16;
unsigned int isle : 15;
unsigned int bFree : 1;
};
struct mesh_data : primitives::primitive {
index_t *pIndices;
char *pMats;
int *pForeignIdx;
strided_pointer<Vec3> pVertices;
Vec3 *pNormals;
int *pVtxMap;
trinfo *pTopology;
int nTris,nVertices;
mesh_island *pIslands;
int nIslands;
tri2isle *pTri2Island;
};
const int BOP_NEWIDX0 = 0x8000000;
enum geomtypes { GEOM_TRIMESH=primitives::triangle::type, GEOM_HEIGHTFIELD=primitives::heightfield::type, GEOM_CYLINDER=primitives::cylinder::type,
GEOM_CAPSULE=primitives::capsule::type, GEOM_RAY=primitives::ray::type, GEOM_SPHERE=primitives::sphere::type,
GEOM_BOX=primitives::box::type, GEOM_VOXELGRID=primitives::voxelgrid::type };
enum foreigntypes { DATA_MESHUPDATE=-1 };
enum meshflags { mesh_shared_vtx=1, mesh_shared_idx=2, mesh_shared_mats=4, mesh_shared_foreign_idx=8, mesh_shared_normals=0x10,
mesh_OBB=0x20, mesh_AABB=0x40, mesh_SingleBB=0x80, mesh_multicontact0=0x100, mesh_multicontact1=0x200,
mesh_multicontact2=0x400, mesh_approx_cylinder=0x800, mesh_approx_box=0x1000, mesh_approx_sphere=0x2000,
mesh_keep_vtxmap=0x8000, mesh_keep_vtxmap_for_saving=0x10000, mesh_no_vtx_merge=0x20000, mesh_AABB_rotated=0x40000,
mesh_VoxelGrid=0x80000, mesh_always_static=0x100000, mesh_approx_capsule=0x200000 };
enum meshAuxData { mesh_data_materials=1, mesh_data_foreign_idx=2, mesh_data_vtxmap=4 };
struct IGeometry {
virtual int GetType() = 0;
virtual int AddRef() = 0;
virtual void Release() = 0;
virtual void Lock(int bWrite=1) = 0;
virtual void Unlock(int bWrite=1) = 0;
virtual void GetBBox(primitives::box *pbox) = 0;
virtual int CalcPhysicalProperties(phys_geometry *pgeom) = 0;
virtual int PointInsideStatus(const Vec3 &pt) = 0;
virtual int Intersect(IGeometry *pCollider, geom_world_data *pdata1,geom_world_data *pdata2, intersection_params *pparams, geom_contact *&pcontacts) = 0;
virtual int FindClosestPoint(geom_world_data *pgwd, int &iPrim,int &iFeature, const Vec3 &ptdst0,const Vec3 &ptdst1,
Vec3 *ptres, int nMaxIters=10) = 0;
virtual void CalcVolumetricPressure(geom_world_data *gwd, const Vec3 &epicenter,float k,float rmin,
const Vec3 ¢erOfMass, Vec3 &P,Vec3 &L) = 0;
virtual float CalculateBuoyancy(const primitives::plane *pplane, const geom_world_data *pgwd, Vec3 &submergedMassCenter) = 0;
virtual void CalculateMediumResistance(const primitives::plane *pplane, const geom_world_data *pgwd, Vec3 &dPres,Vec3 &dLres) = 0;
virtual void DrawWireframe(IPhysRenderer *pRenderer, geom_world_data *gwd, int iLevel, int idxColor) = 0;
virtual int GetPrimitiveId(int iPrim,int iFeature) = 0;
virtual int GetPrimitive(int iPrim, primitives::primitive *pprim) = 0;
virtual int GetForeignIdx(int iPrim) = 0;
virtual Vec3 GetNormal(int iPrim, const Vec3 &pt) = 0;
virtual int GetFeature(int iPrim,int iFeature, Vec3 *pt) = 0;
virtual int IsConvex(float tolerance) = 0;
virtual void PrepareForRayTest(float raylen) = 0;
virtual float BuildOcclusionCubemap(geom_world_data *pgwd, int iMode, int *pGrid0[6],int *pGrid1[6],int nRes, float rmin,float rmax, int nGrow) = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
virtual void Save(CMemStream &stm) = 0;
virtual void Load(CMemStream &stm) = 0;
virtual void Load(CMemStream &stm, strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char *pIds) = 0;
virtual int GetPrimitiveCount() = 0;
virtual const primitives::primitive *GetData() = 0;
virtual void SetData(const primitives::primitive*) = 0;
virtual float GetVolume() = 0;
virtual Vec3 GetCenter() = 0;
virtual int Subtract(IGeometry *pGeom, geom_world_data *pdata1,geom_world_data *pdata2, int bLogUpdates=1) = 0;
virtual int GetSubtractionsCount() = 0;
virtual void *GetForeignData(int iForeignData=0) = 0;
virtual int GetiForeignData() = 0;
virtual void SetForeignData(void *pForeignData, int iForeignData) = 0;
virtual int GetErrorCount() = 0;
virtual void DestroyAuxilaryMeshData(int idata) = 0; // see meshAuxData enum
virtual void RemapForeignIdx(int *pCurForeignIdx, int *pNewForeignIdx, int nTris) = 0;
virtual void AppendVertices(Vec3 *pVtx,int *pVtxMap, int nVtx) = 0;
virtual float ComputeExtent(GeomQuery& geo, EGeomForm eForm) = 0;
virtual void GetRandomPos(RandomPos& ran, GeomQuery& geo, EGeomForm eForm) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IGeometryManager Interface /////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct SMeshBVParams {};
struct SBVTreeParams : SMeshBVParams {
int nMinTrisPerNode,nMaxTrisPerNode;
float favorAABB;
};
struct SVoxGridParams : SMeshBVParams {
Vec3 origin;
Vec3 step;
Vec3i size;
};
struct ITetrLattice {
virtual int SetParams(pe_params *) = 0;
virtual int GetParams(pe_params *) = 0;
virtual void DrawWireframe(IPhysRenderer *pRenderer, geom_world_data *gwd, int idxColor) = 0;
virtual void Release() = 0;
};
struct IBreakableGrid2d {
virtual int *BreakIntoChunks(const vector2df &pt, float r, vector2df *&ptout, int maxPatchTris,float jointhresh,int seed=-1) = 0;
virtual primitives::grid *GetGridData() = 0;
virtual bool IsEmpty() = 0;
virtual void Release() = 0;
};
struct IGeomManager {
virtual void InitGeoman() = 0;
virtual void ShutDownGeoman() = 0;
virtual IGeometry *CreateMesh(strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char *pMats,int *pForeignIdx,int nTris,
int flags, float approx_tolerance=0.05f, int nMinTrisPerNode=2,int nMaxTrisPerNode=4, float favorAABB=1.0f) = 0;
virtual IGeometry *CreateMesh(strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char *pMats,int *pForeignIdx,int nTris,
int flags, float approx_tolerance, SMeshBVParams *pParams) = 0;
virtual IGeometry *CreatePrimitive(int type, const primitives::primitive *pprim) = 0;
virtual void DestroyGeometry(IGeometry *pGeom) = 0;
// defSurfaceIdx will be used (until overwritten in entity part) if the geometry doesn't have per-face materials
virtual phys_geometry *RegisterGeometry(IGeometry *pGeom,int defSurfaceIdx=0, int *pMatMapping=0,int nMats=0) = 0;
virtual int AddRefGeometry(phys_geometry *pgeom) = 0;
virtual int UnregisterGeometry(phys_geometry *pgeom) = 0;
virtual void SetGeomMatMapping(phys_geometry *pgeom, int *pMatMapping, int nMats) = 0;
virtual void SaveGeometry(CMemStream &stm, IGeometry *pGeom) = 0;
virtual IGeometry *LoadGeometry(CMemStream &stm, strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char *pMats) = 0;
virtual void SavePhysGeometry(CMemStream &stm, phys_geometry *pgeom) = 0;
virtual phys_geometry *LoadPhysGeometry(CMemStream &stm, strided_pointer<const Vec3> pVertices,
strided_pointer<unsigned short> pIndices, char *pIds) = 0;
virtual IGeometry *CloneGeometry(IGeometry *pGeom) = 0;
virtual ITetrLattice *CreateTetrLattice(const Vec3 *pt,int npt, const int *pTets,int nTets) = 0;
virtual int RegisterCrack(IGeometry *pGeom, Vec3 *pVtx, int idmat) = 0;
virtual void UnregisterCrack(int id) = 0;
virtual IGeometry *GetCrackGeom(const Vec3 *pt,int idmat, geom_world_data *pgwd) = 0;
virtual IBreakableGrid2d *GenerateBreakableGrid(vector2df *ptsrc,int npt, const vector2di &nCells, int bStatic=1, int seed=-1) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// IPhysUtils Interface /////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct IPhysUtils {
virtual int CoverPolygonWithCircles(strided_pointer<vector2df> pt,int npt,bool bConsecutive, const vector2df ¢er,
vector2df *¢ers,float *&radii, float minCircleRadius) = 0;
virtual int qhull(strided_pointer<Vec3> pts, int npts, index_t*& pTris) = 0;
virtual void DeletePointer(void *pdata) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IPhysicalEntity Interface //////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
enum snapshot_flags { ssf_compensate_time_diff=1, ssf_checksum_only=2, ssf_no_update=4, ssf_from_child_class=8 };
struct IPhysicalEntity {
/*! Retrieves entity type
@returb entity type enum
*/
virtual pe_type GetType() = 0;
virtual int AddRef() = 0;
virtual int Release() = 0;
/*! Sets parameters
@param params pointer to parameters structure
@return nonzero if success
*/
virtual int SetParams(pe_params* params, int bThreadSafe=0) = 0;
virtual int GetParams(pe_params* params) = 0;
/*! Retrieves status
@param status pointer to status structure
@retuan nonzero if success
*/
virtual int GetStatus(pe_status* status) = 0;
/*! Performes action
@param action pointer to action structure
@return nonzero if success
*/
virtual int Action(pe_action*, int bThreadSafe=0) = 0;
/*! Adds geometry
@param pgeom geometry identifier (obtained from RegisterXXX function)
@param params pointer to geometry parameters structure
@param id requested geometry id, if -1 - assign automatically
@return geometry id (0..some number), -1 means error
*/
virtual int AddGeometry(phys_geometry *pgeom, pe_geomparams* params,int id=-1, int bThreadSafe=0) = 0;
/*! Removes geometry
@param params pointer to parameters structure
@return nonzero if success
*/
virtual void RemoveGeometry(int id, int bThreadSafe=0) = 0;
/*! Retrieves foreign data passed during creation (can be pointer to the corresponding engine entity, for instance)
@param iforeigndata requested foreign data type
@return foreign data (void*) if itype==iforeigndata of this entity, 0 otherwise
*/
virtual void *GetForeignData(int itype=0) = 0;
/*! Retrieves iforeigndata of the entity (usually it will be a type identifier for pforeign data
@return iforeigndata
*/
virtual int GetiForeignData() = 0;
/*! Writes state into snapshot
@param stm stream
@param time_back requests previous state (only supported by living entities)
@params flags a combination of snapshot_flags
@return non0 if successful
*/
virtual int GetStateSnapshot(class CStream &stm, float time_back=0, int flags=0) = 0;
virtual int GetStateSnapshot(TSerialize ser, float time_back=0, int flags=0) = 0;
/*! Reads state from snapshot
@param stm stream
@return size of snapshot
*/
virtual int SetStateFromSnapshot(class CStream &stm, int flags=0) = 0;
virtual int SetStateFromSnapshot(TSerialize ser, int flags=0) = 0;
virtual int SetStateFromTypedSnapshot(TSerialize ser, int type, int flags=0) = 0;
virtual int PostSetStateFromSnapshot() = 0;
virtual int GetStateSnapshotTxt(char *txtbuf,int szbuf, float time_back=0) = 0;
virtual void SetStateFromSnapshotTxt(const char *txtbuf,int szbuf) = 0;
virtual unsigned int GetStateChecksum() = 0;
/*! Evolves entity in time. Normally this is called from PhysicalWorld::TimeStep
@param time_interval time step
*/
virtual int DoStep(float time_interval, int iCaller=1) = 0;
/*! Restores previous entity state that corresponds to time -time_interval from now, interpolating when
necessary. This can be used for manual client-server synchronization. Outside of PhysicalWorld::TimeStep
should be called only for living entities
@param time_interval time to trace back
*/
virtual void StepBack(float time_interval) = 0;
/*! Returns physical world this entity belongs to
@return physical world interface
*/
virtual IPhysicalWorld *GetWorld() = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// IPhysicsEventClient Interface //////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
struct IPhysicsEventClient {
virtual void OnBBoxOverlap(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData,
IPhysicalEntity *pCollider, void *pColliderForeignData,int iColliderForeignData) = 0;
virtual void OnStateChange(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, int iOldSimClass,int iNewSimClass) = 0;
virtual void OnCollision(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, coll_history_item *pCollision) = 0;
virtual int OnImpulse(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, pe_action_impulse *impulse) = 0;
virtual void OnPostStep(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, float dt) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// IPhysicalWorld Interface //////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
enum draw_helper_flags { pe_helper_collisions=1, pe_helper_geometry=2, pe_helper_bbox=4, pe_helper_lattice=8 };
enum surface_flags { sf_pierceable_mask=0x0F, sf_max_pierceable=0x0F, sf_important=0x200, sf_manually_breakable=0x400, sf_matbreakable_bit=16 };
#define sf_pierceability(i) (i)
#define sf_matbreakable(i) (((i)+1)<<sf_matbreakable_bit)
enum rwi_flags { rwi_ignore_terrain_holes=0x20, rwi_ignore_noncolliding=0x40, rwi_ignore_back_faces=0x80, rwi_ignore_solid_back_faces=0x100,
rwi_pierceability_mask=0x0F, rwi_pierceability0=0, rwi_stop_at_pierceable=0x0F, rwi_separate_important_hits=sf_important,
rwi_colltype_bit=16, rwi_colltype_any=0x400, rwi_queue=0x800, rwi_force_pierceable_noncoll=0x1000,
rwi_reuse_last_hit=0x2000, rwi_update_last_hit=0x4000, rwi_any_hit=0x8000 };
#define rwi_pierceability(pty) (pty)
enum entity_query_flags { ent_static=1, ent_sleeping_rigid=2, ent_rigid=4, ent_living=8, ent_independent=16, ent_deleted=128, ent_terrain=0x100,
ent_all=ent_static | ent_sleeping_rigid | ent_rigid | ent_living | ent_independent | ent_terrain,
ent_flagged_only = pef_update, ent_skip_flagged = pef_update*2, ent_areas = 32, ent_triggers = 64,
ent_ignore_noncolliding = 0x10000, ent_sort_by_mass = 0x20000, ent_allocate_list = 0x40000,
ent_water = 0x200, ent_no_ondemand_activation = 0x80000 // can only be used in RayWorldIntersection
};
enum phys_locks { PLOCK_WORLD_STEP=1, PLOCK_CALLER0, PLOCK_CALLER1, PLOCK_QUEUE, PLOCK_AREAS };
struct phys_profile_info {
IPhysicalEntity *pEntity;
int nTicks,nCalls;
int nTicksAvg;
float nCallsAvg;
int nTicksPeak,nCallsPeak,peakAge;
int nTicksStep;
int id;
const char *pName;
};
struct SolverSettings {
int nMaxStackSizeMC; // def 8
float maxMassRatioMC; // def 50
int nMaxMCiters; // def 1400
int nMaxMCitersHopeless; // def 400
float accuracyMC; // def 0.005
float accuracyLCPCG; // def 0.005
int nMaxContacts; // def 150
int nMaxPlaneContacts; // def 7
int nMaxPlaneContactsDistress; // def 4
int nMaxLCPCGsubiters; // def 120
int nMaxLCPCGsubitersFinal; // def 250
int nMaxLCPCGmicroiters;
int nMaxLCPCGmicroitersFinal;
int nMaxLCPCGiters; // def 5
float minLCPCGimprovement; // def 0.1
int nMaxLCPCGFruitlessIters; // def 4
float accuracyLCPCGnoimprovement; // def 0.05
float minSeparationSpeed; // def 0.02
float maxvCG;
float maxwCG;
float maxvUnproj;
int bCGUnprojVel;
float maxMCMassRatio;
float maxMCVel;
int maxLCPCGContacts;
};
struct PhysicsVars : SolverSettings {
int bFlyMode;
int iCollisionMode;
int bSingleStepMode;
int bDoStep;
float fixedTimestep;
float timeGranularity;
float maxWorldStep;
int iDrawHelpers;
float maxContactGap;
float maxContactGapPlayer;
float minBounceSpeed;
int bProhibitUnprojection;
int bUseDistanceContacts;
float unprojVelScale;
float maxUnprojVel;
int bEnforceContacts;
int nMaxSubsteps;
int nMaxSurfaces;
Vec3 gravity;
int nGroupDamping;
float groupDamping;
int bBreakOnValidation;
int bLogActiveObjects;
int bMultiplayer;
int bProfileEntities;
int bProfileFunx;
int nGEBMaxCells;
int nMaxEntityCells;
int nMaxAreaCells;
float maxVel;
float maxVelPlayers;
float maxContactGapSimple;
float penaltyScale;
int bSkipRedundantColldet;
int bLimitSimpleSolverEnergy;
int nMaxEntityContacts;
int bLogLatticeTension;
int nMaxLatticeIters;
int bLogStructureChanges;
float tickBreakable;
float approxCapsLen;
int nMaxApproxCaps;
int bPlayersCanBreak;
float lastTimeStep;
int bMultithreaded;
float breakImpulseScale;
float rtimeGranularity;
float massLimitDebris;
int flagsColliderDebris;
int flagsANDDebris;
int maxSplashesPerObj;
float splashDist0,minSplashForce0,minSplashVel0;
float splashDist1,minSplashForce1,minSplashVel1;
int bDebugExplosions;
float timeScalePlayers;
float threadLag;
// net-synchronization related
float netMinSnapDist;
float netVelSnapMul;
float netMinSnapDot;
float netAngSnapMul;
float netSmoothTime;
};
struct ray_hit {
float dist;
IPhysicalEntity *pCollider;
int ipart;
int partid;
int surface_idx;
int idmatOrg; // original material index, not mapped with material mapping
int foreignIdx;
int iNode;
Vec3 pt;
Vec3 n;
int bTerrain;
ray_hit *next; // reserved for internal use
};
struct ray_hit_cached {
ray_hit_cached() { pCollider=0; ipart=0; }
ray_hit_cached(const ray_hit &hit) { pCollider=hit.pCollider; ipart=hit.ipart; iNode=hit.iNode; }
ray_hit_cached &operator=(const ray_hit &hit) { pCollider=hit.pCollider; ipart=hit.ipart; iNode=hit.iNode; return *this; }
IPhysicalEntity *pCollider;
int ipart;
int iNode;
};
#ifndef PWI_NAME_TAG
#define PWI_NAME_TAG "PrimitiveWorldIntersection"
#endif
#ifndef RWI_NAME_TAG
#define RWI_NAME_TAG "RayWorldIntersection"
#endif
struct pe_explosion {
pe_explosion() { nOccRes=0; nGrow=0; rminOcc=0.1f; holeSize=0; explDir.Set(0,0,1); iholeType=0; forceDeformEntities=false; }
Vec3 epicenter;
Vec3 epicenterImp;
float rmin,rmax,r;
float impulsivePressureAtR;
int nOccRes;
int nGrow;
float rminOcc;
float holeSize;
Vec3 explDir;
int iholeType;
bool forceDeformEntities; // force deformation even if breakImpulseScale is zero
// filled as results
IPhysicalEntity **pAffectedEnts;
float *pAffectedEntsExposure;
int nAffectedEnts;
};
struct EventPhys {
EventPhys *next;
int idval;
};
struct EventPhysMono : EventPhys {
IPhysicalEntity *pEntity;
void *pForeignData;
int iForeignData;
};
struct EventPhysStereo : EventPhys {
IPhysicalEntity *pEntity[2];
void *pForeignData[2];
int iForeignData[2];
};
struct EventPhysBBoxOverlap : EventPhysStereo {
enum entype { id=0, flagsCall=0, flagsLog=0 };
EventPhysBBoxOverlap() { idval=id; }
};
struct EventPhysCollision : EventPhysStereo {
enum entype { id=1, flagsCall=pef_monitor_collisions, flagsLog=pef_log_collisions };
EventPhysCollision() { idval=id; pEntContact=0; }
int idCollider;
Vec3 pt;
Vec3 n;
Vec3 vloc[2];
float mass[2];
int partid[2];
int idmat[2];
float penetration;
float normImpulse;
float radius;
void *pEntContact; // reserved for internal use
};
struct EventPhysStateChange : EventPhysMono {
enum entype { id=2, flagsCall=pef_monitor_state_changes, flagsLog=pef_log_state_changes };
EventPhysStateChange() { idval=id; }
int iSimClass[2];
};
struct EventPhysEnvChange : EventPhysMono {
enum entype { id=3, flagsCall=pef_monitor_env_changes, flagsLog=pef_log_env_changes };
enum encode { EntStructureChange=0 };
EventPhysEnvChange() { idval=id; }
int iCode;
IPhysicalEntity *pentSrc;
IPhysicalEntity *pentNew;
};
struct EventPhysPostStep : EventPhysMono {
enum entype { id=4, flagsCall=pef_monitor_poststep, flagsLog=pef_log_poststep };
EventPhysPostStep() { idval=id; }
float dt;
Vec3 pos;
quaternionf q;
int idStep;
};
struct EventPhysUpdateMesh : EventPhysMono {
enum entype { id=5, flagsCall=1, flagsLog=2 };
enum reason { ReasonExplosion, ReasonFracture, ReasonRequest };
EventPhysUpdateMesh() { idval=id; }
int partid;
int bInvalid;
int iReason;
IGeometry *pMesh; // ->GetForeignData(DATA_MESHUPDATE) returns a list of bop_meshupdates
bop_meshupdate *pLastUpdate; // the last mesh update for at moment when the event was generated
};
struct EventPhysCreateEntityPart : EventPhysMono {
enum entype { id=6, flagsCall=1, flagsLog=2 };
enum reason { ReasonMeshSplit, ReasonJointsBroken };
EventPhysCreateEntityPart() { idval=id; }
IPhysicalEntity *pEntNew;
int partidSrc,partidNew;
int nTotParts;
int bInvalid;
int iReason;
Vec3 breakImpulse;
Vec3 breakAngImpulse;
float breakSize;
float cutRadius;
Vec3 cutPtLoc[2];
Vec3 cutDirLoc[2];
IGeometry *pMeshNew;
bop_meshupdate *pLastUpdate;
};
struct EventPhysRemoveEntityParts : EventPhysMono {
enum entype { id=7, flagsCall=1, flagsLog=2 };
EventPhysRemoveEntityParts() { idval=id; }
unsigned int partIds[4];
float massOrg;
};
struct EventPhysJointBroken : EventPhysStereo {
enum entype { id=8, flagsCall=1, flagsLog=2 };
EventPhysJointBroken() { idval=id; }
int idJoint;
int bJoint; // otherwise it's a constraint
int partidEpicenter;
Vec3 pt;
Vec3 n;
int partid[2];
int partmat[2];
IPhysicalEntity *pNewEntity[2];
};
struct EventPhysRWIResult : EventPhysMono {
enum entype { id=9, flagsCall=0,flagsLog=0 };
EventPhysRWIResult() { idval=id; }
ray_hit *pHits;
int nHits,nMaxHits;
int bHitsFromPool; // 1 if hits reside in the internal physics hits pool
};
struct EventPhysPWIResult : EventPhysMono {
enum entype { id=10, flagsCall=0,flagsLog=0 };
EventPhysPWIResult() { idval=id; }
float dist;
Vec3 pt;
Vec3 n;
int idxMat;
};
struct EventPhysArea : EventPhysMono {
enum entype { id=11, flagsCall=0,flagsLog=0 };
EventPhysArea() { idval=id; }
Vec3 pt;
Vec3 ptref,dirref;
pe_params_buoyancy pb;
Vec3 gravity;
IPhysicalEntity *pent;
};
struct EventPhysAreaChange : EventPhysMono {
enum entype { id=12, flagsCall=0,flagsLog=0 };
EventPhysAreaChange() { idval=id; }
Vec3 boxAffected[2];
};
const int EVENT_TYPES_NUM = 13;
struct IPhysicalWorld {
/*! Inits world
@param pconsole pointer of IConsole interace
*/
virtual void Init() = 0;
virtual IGeomManager* GetGeomManager() = 0;
virtual IPhysUtils* GetPhysUtils() = 0;
/*! Shuts the world down
*/
virtual void Shutdown(int bDeleteGeometries = 1) = 0;
/*! Destroys the world
*/
virtual void Release() = 0;
/*! Initializes entity hash grid
@param axisx id of grid x axis (0-world x,1-world y,2-world z)
@param axisy id of grid y axis (0-world x,1-world y,2-world z)
@param origin grid (0,0) in world CS
@param nx number of cells in grid x direciton
@param ny number of cells in grid y direciton
@param stepx cell x dimension
@param stepy cell y dimension
*/
virtual void SetupEntityGrid(int axisz, Vec3 org, int nx,int ny, float stepx,float stepy) = 0;
virtual void DeactivateOnDemandGrid() = 0;
virtual void RegisterBBoxInPODGrid(const Vec3 *BBox) = 0;
virtual int AddRefEntInPODGrid(IPhysicalEntity *pent, const Vec3 *BBox=0) = 0;
/*! Sets heightfield data
@param phf
*/
virtual IPhysicalEntity *SetHeightfieldData(const primitives::heightfield *phf,int *pMatMapping=0,int nMats=0) = 0;
/*! Retrieves heightfield data
@param phf
@return pointer to heightfield entity
*/
virtual IPhysicalEntity *GetHeightfieldData(primitives::heightfield *phf) = 0;
/*! Retrieves pointer to physvars structure
@return pointer to physvar structure
*/
virtual PhysicsVars *GetPhysVars() = 0;
/*! Creates physical entity
@param type entity type
@param params initial params (as in entity SetParams)
@param pforeigndata entity foreign data
@param iforeigndata entity foreign data type identifier
@return pointer to physical entity interface
*/
virtual IPhysicalEntity* CreatePhysicalEntity(pe_type type, pe_params* params=0, void *pforeigndata=0, int iforeigndata=0, int id=-1) = 0;
virtual IPhysicalEntity* CreatePhysicalEntity(pe_type type, float lifeTime, pe_params* params=0, void *pForeignData=0,int iForeignData=0,
int id=-1,IPhysicalEntity *pHostPlaceholder=0) = 0;
virtual IPhysicalEntity *CreatePhysicalPlaceholder(pe_type type, pe_params* params=0, void *pForeignData=0,int iForeignData=0, int id=-1) = 0;
/*! Destroys physical entity
@param pent entity
@param mode 0-normal destroy, 1-suspend, 2-restore from suspended state
@return nonzero if success
*/
virtual int DestroyPhysicalEntity(IPhysicalEntity *pent, int mode=0, int bThreadSafe=0) = 0;
virtual int SetPhysicalEntityId(IPhysicalEntity *pent, int id, int bReplace=1, int bThreadSafe=0) = 0;
virtual int GetPhysicalEntityId(IPhysicalEntity *pent) = 0;
virtual IPhysicalEntity* GetPhysicalEntityById(int id) = 0;
/*! Sets surface parameters
@param surface_idx surface identifier
@param bounciness restitution coefficient (for pair of surfaces k = sum of their coefficients, clamped to [0..1]
@param friction friction coefficient (for pair of surfaces k = sum of their coefficients, clamped to [0..inf)
@param flags bitmask (see surface_flags enum)
@return nonzero if success
*/
virtual int SetSurfaceParameters(int surface_idx, float bounciness,float friction, unsigned int flags=0) = 0;
virtual int GetSurfaceParameters(int surface_idx, float &bounciness,float &friction, unsigned int &flags) = 0;
/*! Perfomes a time step
@param time_interval time interval
@param flags entity types to update (ent_..; ent_deleted to purge deletion physics-on-demand state monitoring)
*/
virtual void TimeStep(float time_interval,int flags=ent_all|ent_deleted) = 0;
/*! Returns current time of the physical world
@return current time
*/
virtual float GetPhysicsTime() = 0;
virtual int GetiPhysicsTime() = 0;
/*! Sets current time of the physical world
@param time new time
*/
virtual void SetPhysicsTime(float time) = 0;
virtual void SetiPhysicsTime(int itime) = 0;
/*! Sets physical time that corresponds to the following server state snapshot
@param time_snapshot physical time of the following server snapshot
*/
virtual void SetSnapshotTime(float time_snapshot,int iType=0) = 0;
virtual void SetiSnapshotTime(int itime_snapshot,int iType=0) = 0;
/*! Retrives list of entities that fall into a box
@param ptmix,ptmax - box corners
@param pList returned pointer to entity list
@param objtypes bitmask 0-static, 1-sleeping, 2-physical, 3-living
@return number of entities
*/
virtual int GetEntitiesInBox(Vec3 ptmin,Vec3 ptmax, IPhysicalEntity **&pList, int objtypes, int szListPrealloc=0) = 0;
/*! Shoots ray into world
@param origin origin
@param dir direction*(ray length)
@param objtypes bitmask 0-terrain 1-static, 2-sleeping, 3-physical, 4-living
@param flags a combination of rwi_flags
@param hits destination hits array
@param nmaxhits size of this array
@param pskipent entity to skip
@param pForeignData data that is returned in EventPhysRWIResult if rwi_queue is specified
@return number of collisions
*/
virtual int RayWorldIntersection(Vec3 org,Vec3 dir, int objtypes, unsigned int flags, ray_hit *hits,int nMaxHits,
IPhysicalEntity **pSkipEnts=0,int nSkipEnts=0, void *pForeignData=0,int iForeignData=0,
const char *pNameTag=RWI_NAME_TAG, ray_hit_cached *phitLast=0, int iCaller=1) = 0;
int RayWorldIntersection(Vec3 org,Vec3 dir, int objtypes, unsigned int flags, ray_hit *hits,int nMaxHits,
IPhysicalEntity *pSkipEnt,IPhysicalEntity *pSkipEntAux=0, void *pForeignData=0,int iForeignData=0)
{
IPhysicalEntity *pSkipEnts[2];
int nSkipEnts = 0;
if (pSkipEnt) pSkipEnts[nSkipEnts++] = pSkipEnt;
if (pSkipEntAux) pSkipEnts[nSkipEnts++] = pSkipEntAux;
return RayWorldIntersection(org,dir,objtypes,flags,hits,nMaxHits, pSkipEnts,nSkipEnts, pForeignData,iForeignData);
}
// Traces ray requests (rwi calls with rwi_queue set); logs and calls EventPhysRWIResult for each
// returns the number of rays traced
virtual int TracePendingRays(int bDoActualTracing=1) = 0;
/*! Freezes (resets velocities of) all physical, living, and detached entities
*/
virtual void ResetDynamicEntities() = 0;
/*! Immediately destroys all physical, living, and detached entities; flushes the deleted entities
All subsequent calls to DestroyPhysicalEntity for non-static entities are ignored until the next
non-static entity is created
*/
virtual void DestroyDynamicEntities() = 0;
/*! Forces deletion of all entities marked as deleted
*/
virtual void PurgeDeletedEntities() = 0;
virtual int GetEntityCount(int iEntType) = 0;
virtual int ReserveEntityCount(int nExtraEnts) = 0;
/*! Simulates physical explosion with k/(r^2) pressure distribution
@param epicenter epicenter used for building the occlusion map
@param epicenterImp epicenter used for applying impulse
@param rmin all r<rmin are set to rmin to avoid singularity in center
@param rmax clamps entities father than rmax
@param r radius at which impulsive pressure is spesified
@param impulsive_pressure_at_r impulsive pressure at r
@param nOccRes resolution of occulision cubemap (0 to skip occlusion test)
@param nGrow inflate dynamic objects' rasterized image by this amount
@params rmin_occ subtract cube with this size (half length of its side) during rasterization
@params pSkipEnts pointer to array of entities to skip
@params nSkipEnts number of entities to skip
*/
virtual void SimulateExplosion(pe_explosion *pexpl, IPhysicalEntity **pSkipEnts=0,int nSkipEnts=0,
int iTypes=ent_rigid|ent_sleeping_rigid|ent_living|ent_independent, int iCaller=1) = 0;
void SimulateExplosion(Vec3 epicenter,Vec3 epicenterImp, float rmin,float rmax, float r,float impulsivePressureAtR,
int nOccRes=0,int nGrow=0,float rminOcc=0.1f, IPhysicalEntity **pSkipEnts=0,int nSkipEnts=0,
int iTypes=ent_rigid|ent_sleeping_rigid|ent_living|ent_independent)
{
pe_explosion expl;
expl.epicenter=epicenter; expl.epicenterImp=epicenterImp; expl.rmin=rmin; expl.rmax=rmax; expl.r=r;
expl.impulsivePressureAtR=impulsivePressureAtR; expl.nOccRes=nOccRes; expl.nGrow=nGrow; expl.rminOcc=rminOcc;
SimulateExplosion(&expl,pSkipEnts,nSkipEnts,iTypes);
}
virtual int DeformPhysicalEntity(IPhysicalEntity *pent, const Vec3 &ptHit,const Vec3 &dirHit,float r, int flags=0) = 0;
virtual void UpdateDeformingEntities(float time_interval=0.01f) = 0;
virtual float CalculateExplosionExposure(pe_explosion *pexpl, IPhysicalEntity *pient) = 0;
/*! Returns fraction of pent (0-1) that was exposed to the last explosion
*/
virtual float IsAffectedByExplosion(IPhysicalEntity *pent, Vec3 *impulse=0) = 0;
virtual int AddExplosionShape(IGeometry *pGeom, float size,int idmat, float probability=1.0f) = 0;
virtual void RemoveExplosionShape(int id) = 0;
virtual void DrawPhysicsHelperInformation(IPhysRenderer *pRenderer,int iCaller=1) = 0;
virtual int CollideEntityWithBeam(IPhysicalEntity *_pent, Vec3 org,Vec3 dir,float r, ray_hit *phit) = 0;
virtual int CollideEntityWithPrimitive(IPhysicalEntity *_pent, int itype, primitives::primitive *pprim, Vec3 dir, ray_hit *phit) = 0;
virtual int RayTraceEntity(IPhysicalEntity *pient, Vec3 origin,Vec3 dir, ray_hit *pHit, pe_params_pos *pp=0) = 0;
// PrimitiveWorldIntersection
// Summary:
// can perform sweep/overlap/or custom intersection check for a given primitive
// for sweep tests, affected entities are selected from the bounding box of the swept volume, so it's ineffective for long sweeps
// Params:
// itype,pprim - primitive type and data (cannot be tri mesh or heightfield)
// sweepDir - self-explanatory
// entTypes - entity types to check; add rwi_queue flag to queue the request
// ppcontact - pointer to the pointer to the resulting contacts array
// geomFlagsAll - flags that must all be present in an entity part
// geomFlagsAny - flags at least one of which must be present in an entity part
// pip - custom intersection parameters, overrides the sweepDir setting if any.
// if not specified, the function performs a simple true/false overlap check if sweepDir is 0, and a sweep check otherwise
// if specified and pip->bThreadSafe==false, the caller must manually release the lock in pip->plock (but only if there were any contacts)
// Returns:
// distance to the first hit for sweep checks and the number of hits for intersection checks (as float)
virtual float PrimitiveWorldIntersection(int itype, primitives::primitive *pprim, const Vec3 &sweepDir=Vec3(ZERO), int entTypes=ent_all,
geom_contact **ppcontact=0, int geomFlagsAll=0,int geomFlagsAny=geom_colltype0|geom_colltype_player, intersection_params *pip=0,
void *pForeignData=0, int iForeignData=0, IPhysicalEntity **pSkipEnts=0,int nSkipEnts=0, const char *pNameTag=PWI_NAME_TAG) = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
virtual void SetPhysicsStreamer(IPhysicsStreamer *pStreamer) = 0;
virtual void SetPhysicsEventClient(IPhysicsEventClient *pEventClient) = 0;
virtual float GetLastEntityUpdateTime(IPhysicalEntity *pent) = 0;
virtual int GetEntityProfileInfo(phys_profile_info *&pList) = 0;
virtual int GetFuncProfileInfo(phys_profile_info *&pList) = 0;
virtual void AddEventClient(int type, int (*func)(const EventPhys*), int bLogged, float priority=1.0f) = 0;
virtual int RemoveEventClient(int type, int (*func)(const EventPhys*), int bLogged) = 0;
virtual void PumpLoggedEvents() = 0;
virtual void ClearLoggedEvents() = 0;
virtual IPhysicalEntity *AddGlobalArea() = 0;
virtual IPhysicalEntity *AddArea(Vec3 *pt,int npt, float zmin,float zmax, const Vec3 &pos=Vec3(0,0,0), const quaternionf &q=quaternionf(IDENTITY),
float scale=1.0f, const Vec3 &normal=Vec3(ZERO), int *pTessIdx=0,int nTessTris=0,Vec3 *pFlows=0) = 0;
virtual IPhysicalEntity *AddArea(IGeometry *pGeom, const Vec3& pos,const quaternionf &q,float scale) = 0;
virtual void RemoveArea(IPhysicalEntity *pArea) = 0;
virtual IPhysicalEntity *AddArea(Vec3 *pt,int npt, float r, const Vec3 &pos=Vec3(0,0,0),const quaternionf &q=quaternionf(IDENTITY),float scale=1) = 0;
// GetNextArea: iterates through all registered areas, if prevarea==0 returns the global area
virtual IPhysicalEntity *GetNextArea(IPhysicalEntity *pPrevArea=0) = 0;
// Checks areas for a given point
virtual int CheckAreas(const Vec3 &ptc, Vec3 &gravity, pe_params_buoyancy *pb, int nMaxBuoys=1, const Vec3 &vec=Vec3(ZERO),
IPhysicalEntity *pent=0, int iCaller=1) = 0;
virtual void SetWaterMat(int imat) = 0;
virtual int GetWaterMat() = 0;
virtual int SetWaterManagerParams(pe_params *params) = 0;
virtual int GetWaterManagerParams(pe_params *params) = 0;
virtual int GetWatermanStatus(pe_status *status) = 0;
virtual void DestroyWaterManager() = 0;
virtual volatile int *GetInternalLock(int idx) = 0; // returns one of phys_lock locks
virtual int SerializeWorld(const char *fname, int bSave) = 0;
virtual int SerializeGeometries(const char *fname, int bSave) = 0;
virtual void SerializeGarbageTypedSnapshot( TSerialize ser, int iSnapshotType, int flags ) = 0;
};
#endif
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
325
],
[
327,
329
],
[
331,
334
],
[
336,
338
],
[
340,
340
],
[
342,
362
],
[
365,
376
],
[
378,
605
],
[
607,
615
],
[
617,
634
],
[
637,
661
],
[
663,
666
],
[
668,
793
],
[
795,
798
],
[
801,
860
],
[
870,
930
],
[
932,
978
],
[
980,
1116
],
[
1118,
1121
],
[
1123,
1124
],
[
1126,
1208
],
[
1210,
1220
],
[
1222,
1320
],
[
1323,
1604
],
[
1606,
1701
],
[
1703,
1775
],
[
1777,
1812
],
[
1814,
1815
],
[
1817,
1821
],
[
1823,
1915
],
[
1928,
2004
],
[
2006,
2024
],
[
2032,
2084
],
[
2086,
2158
],
[
2160,
2301
],
[
2303,
2350
],
[
2352,
2354
],
[
2356,
2377
]
],
[
[
326,
326
],
[
330,
330
],
[
335,
335
],
[
339,
339
],
[
341,
341
],
[
363,
364
],
[
377,
377
],
[
606,
606
],
[
616,
616
],
[
635,
636
],
[
662,
662
],
[
667,
667
],
[
794,
794
],
[
799,
800
],
[
861,
869
],
[
931,
931
],
[
979,
979
],
[
1117,
1117
],
[
1122,
1122
],
[
1125,
1125
],
[
1209,
1209
],
[
1221,
1221
],
[
1321,
1322
],
[
1605,
1605
],
[
1702,
1702
],
[
1776,
1776
],
[
1813,
1813
],
[
1816,
1816
],
[
1822,
1822
],
[
1916,
1927
],
[
2005,
2005
],
[
2025,
2031
],
[
2085,
2085
],
[
2159,
2159
],
[
2302,
2302
],
[
2351,
2351
],
[
2355,
2355
]
]
] |
58060ec35eb4a72dec0a651e9423993f450b5b74 | 8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab | /src-ginga-editing/gingancl-cpp/src/gingancl/model/components/ExecutionObject.cpp | fcc9668da50cb1cc05eac2cbc2f25cf8ea8cbded | [] | no_license | BrunoSSts/ginga-wac | 7436a9815427a74032c9d58028394ccaac45cbf9 | ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c | refs/heads/master | 2020-05-20T22:21:33.645904 | 2011-10-17T12:34:32 | 2011-10-17T12:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,334 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Direitos Autorais Reservados (c) 1989-2007 PUC-Rio/Laboratorio TeleMidia
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licen�a Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribu�do na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
ncl @ telemidia.puc-rio.br
http://www.ncl.org.br
http://www.ginga.org.br
http://www.telemidia.puc-rio.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright: 1989-2007 PUC-RIO/LABORATORIO TELEMIDIA, All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
ncl @ telemidia.puc-rio.br
http://www.ncl.org.br
http://www.ginga.org.br
http://www.telemidia.puc-rio.br
*******************************************************************************/
#include "../../../include/ExecutionObject.h"
#include "../../../include/CompositeExecutionObject.h"
namespace br {
namespace pucrio {
namespace telemidia {
namespace ginga {
namespace ncl {
namespace model {
namespace components {
ExecutionObject::ExecutionObject(string id, Node* node) {
initializeExecutionObject(id, node, NULL);
}
ExecutionObject::ExecutionObject(
string id,
Node* node,
GenericDescriptor* descriptor) {
initializeExecutionObject(
id, node, new CascadingDescriptor(descriptor));
}
ExecutionObject::ExecutionObject(
string id,
Node* node,
CascadingDescriptor* descriptor) {
initializeExecutionObject(id, node, descriptor);
}
ExecutionObject::~ExecutionObject() {
lock();
map<string, FormatterEvent*>::iterator i;
FormatterEvent* event;
map<Node*, Node*>::iterator j;
Node* parentNode;
CompositeExecutionObject* parentObject;
if (transitionTable != NULL) {
transitionTable->clear();
delete transitionTable;
transitionTable = NULL;
}
wholeContent = NULL;
lockEvents();
if (events != NULL) {
i = events->begin();
while (i != events->end()) {
event = i->second;
if (event != NULL) {
delete event;
event = NULL;
}
++i;
}
events->clear();
delete events;
events = NULL;
}
unlockEvents();
if (presentationEvents != NULL) {
presentationEvents->clear();
delete presentationEvents;
presentationEvents = NULL;
}
if (selectionEvents != NULL) {
selectionEvents->clear();
delete selectionEvents;
selectionEvents = NULL;
}
if (otherEvents != NULL) {
otherEvents->clear();
delete otherEvents;
otherEvents = NULL;
}
if (nodeParentTable != NULL) {
j = nodeParentTable->begin();
while (j != nodeParentTable->end()) {
parentNode = j->second;
if (parentTable->count(parentNode) != 0) {
parentObject = (CompositeExecutionObject*)
((*parentTable)[parentNode]);
parentObject->removeExecutionObject(this);
}
++j;
}
nodeParentTable->clear();
delete nodeParentTable;
nodeParentTable = NULL;
}
if (parentTable != NULL) {
parentTable->clear();
delete parentTable;
parentTable = NULL;
}
if (descriptor != NULL) {
delete descriptor;
descriptor = NULL;
}
unlock();
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutexEvent);
}
void ExecutionObject::initializeExecutionObject(
string id, Node* node, CascadingDescriptor* descriptor) {
typeSet.insert("ExecutionObject");
this->id = id;
this->dataObject = node;
this->wholeContent = NULL;
this->startTime = infinity();
this->descriptor = NULL;
this->nodeParentTable = new map<Node*, Node*>;
this->parentTable = new map<Node*, void*>;
this->isItCompiled = false;
this->events = new map<string, FormatterEvent*>;
this->presentationEvents = new vector<FormatterEvent*>;
this->selectionEvents = new set<SelectionEvent*>;
this->otherEvents = new vector<FormatterEvent*>;
this->pauseCount = 0;
this->transitionTable = new vector<EventTransition*>;
this->mainEvent = NULL;
this->descriptor = descriptor;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&mutexEvent, NULL);
}
bool ExecutionObject::instanceOf(string s) {
if(typeSet.empty())
return false;
else
return (typeSet.find(s) != typeSet.end());
}
int ExecutionObject::compareToUsingId(ExecutionObject* object) {
return id.compare(object->getId());
}
Node* ExecutionObject::getDataObject() {
return dataObject;
}
CascadingDescriptor* ExecutionObject::getDescriptor() {
return descriptor;
}
string ExecutionObject::getId() {
return id;
}
void* ExecutionObject::getParentObject() {
return getParentObject(dataObject);
}
void* ExecutionObject::getParentObject(Node* node) {
Node* parentNode;
if (nodeParentTable->count(node) != 0) {
parentNode = (*nodeParentTable)[node];
if (parentTable->count(parentNode) != 0) {
return (*parentTable)[parentNode];
}
}
return NULL;
}
void ExecutionObject::addParentObject(
void* parentObject, Node* parentNode) {
addParentObject(dataObject, parentObject, parentNode);
}
void ExecutionObject::addParentObject(
Node* node,
void* parentObject,
Node* parentNode) {
(*nodeParentTable)[node] = parentNode;
(*parentTable)[parentNode] = parentObject;
}
void ExecutionObject::setDescriptor(
CascadingDescriptor* cascadingDescriptor) {
this->descriptor = cascadingDescriptor;
}
void ExecutionObject::setDescriptor(GenericDescriptor* descriptor) {
CascadingDescriptor* cascade;
cascade = new CascadingDescriptor(descriptor);
this->descriptor = cascade;
}
string ExecutionObject::toString() {
return id;
}
bool ExecutionObject::addEvent(FormatterEvent* event) {
lockEvents();
if (events->count(event->getId()) != 0) {
unlockEvents();
return false;
}
(*events)[event->getId()] = event;
unlockEvents();
if (event->instanceOf("PresentationEvent")) {
addPresentationEvent((PresentationEvent*)event);
} else if (event->instanceOf("SelectionEvent")) {
selectionEvents->insert(((SelectionEvent*)event));
} else {
otherEvents->push_back(event);
}
return true;
}
void ExecutionObject::addPresentationEvent(PresentationEvent* event) {
PresentationEvent* auxEvent;
double begin, auxBegin, end;
int posBeg, posEnd, posMid;
BeginEventTransition* beginTransition;
EndEventTransition* endTransition;
if ((event->getAnchor())->instanceOf("LambdaAnchor")) {
presentationEvents->insert(presentationEvents->begin(), event);
wholeContent = (PresentationEvent*)event;
beginTransition = new BeginEventTransition(0, event);
transitionTable->insert(transitionTable->begin(), beginTransition);
if (event->getEnd() >= 0) {
endTransition = new EndEventTransition(
event->getEnd(), event, beginTransition);
transitionTable->push_back(endTransition);
}
} else {
begin = event->getBegin();
// undefined events are not inserted into transition table
if (PresentationEvent::isUndefinedInstant(begin)) {
return;
}
posBeg = 0;
posEnd = presentationEvents->size() - 1;
while (posBeg <= posEnd) {
posMid = (posBeg + posEnd) / 2;
auxEvent = (PresentationEvent*)((*presentationEvents)[posMid]);
auxBegin = auxEvent->getBegin();
if (begin < auxBegin) {
posEnd = posMid - 1;
} else if (begin > auxBegin) {
posBeg = posMid + 1;
} else {
posBeg = posMid + 1;
break;
}
}
// TODO: verificar se eh (posBeg - 1) ou posBeg
presentationEvents->insert(
(presentationEvents->begin() + posBeg), event);
beginTransition = new BeginEventTransition(begin, event);
addEventTransition(beginTransition);
end = event->getEnd();
if (!PresentationEvent::isUndefinedInstant(end)) {
endTransition = new EndEventTransition(
end, event, beginTransition);
addEventTransition(endTransition);
}
}
}
void ExecutionObject::addEventTransition(EventTransition* transition) {
int beg, end, pos;
EventTransition* auxTransition;
// binary search
beg = 0;
end = transitionTable->size() - 1;
while (beg <= end) {
pos = (beg + end) / 2;
auxTransition = (*transitionTable)[pos];
switch (transition->compareTo(auxTransition)) {
case 0:
// entrada corresponde a um evento que ja' foi inserido
return;
case -1:
end = pos - 1;
break;
case 1:
beg = pos + 1;
break;
}
}
// TODO: verificar se eh (beg - 1) ou beg
transitionTable->insert((transitionTable->begin() + beg), transition);
}
void ExecutionObject::removeEventTransition(PresentationEvent* event) {
int i, size;
vector<EventTransition*>::iterator j;
EventTransition* transition;
EventTransition* endTransition;
size = transitionTable->size();
for (i = 0; i < size; i++) {
transition = (*transitionTable)[i];
if (transition->getEvent() == event) {
if (transition->instanceOf("BeginEventTransition") &&
((BeginEventTransition*)transition)->
getEndTransition() != NULL) {
endTransition = ((BeginEventTransition*)transition)->
getEndTransition();
for (j = transitionTable->begin();
j != transitionTable->end(); ++j) {
if (*j == endTransition) {
transitionTable->erase(j);
break;
}
}
}
for (j = transitionTable->begin();
j != transitionTable->end(); ++j) {
if (*j == transition) {
transitionTable->erase(j);
break;
}
}
break;
}
}
}
int ExecutionObject::compareTo(ExecutionObject* object) {
int ret;
ret = compareToUsingStartTime(object);
if (ret == 0)
return compareToUsingId(object);
else
return ret;
}
int ExecutionObject::compareToUsingStartTime(ExecutionObject* object) {
double thisTime, otherTime;
thisTime = startTime;
otherTime = (object->getExpectedStartTime());
if (thisTime < otherTime)
return -1;
else if (thisTime > otherTime)
return 1;
else
return 0;
}
bool ExecutionObject::containsEvent(FormatterEvent* event) {
bool contains;
lockEvents();
contains = (events->count(event->getId()) != 0);
unlockEvents();
return contains;
}
FormatterEvent* ExecutionObject::getEvent(string id) {
FormatterEvent* ev;
lockEvents();
if (events != NULL && events->count(id) != 0) {
ev = (*events)[id];
unlockEvents();
return ev;
}
unlockEvents();
return NULL;
}
vector<FormatterEvent*>* ExecutionObject::getEvents() {
vector<FormatterEvent*>* eventsVector = NULL;
map<string, FormatterEvent*>::iterator i;
lockEvents();
if (events == NULL || events->empty()) {
unlockEvents();
return NULL;
}
eventsVector = new vector<FormatterEvent*>;
for (i = events->begin(); i != events->end(); ++i) {
eventsVector->push_back(i->second);
}
unlockEvents();
return eventsVector;
}
double ExecutionObject::getExpectedStartTime() {
return startTime;
}
PresentationEvent* ExecutionObject::getWholeContentPresentationEvent() {
return wholeContent;
}
void ExecutionObject::setStartTime(double t) {
startTime = t;
}
void ExecutionObject::updateEventDurations() {
int i, size;
size = presentationEvents->size();
for (i = 0; i < size; i++) {
updateEventDuration(
(PresentationEvent*)((*presentationEvents)[i]));
}
}
void ExecutionObject::updateEventDuration(PresentationEvent* event) {
if (!containsEvent((FormatterEvent*)event)) {
return;
}
double duration;
duration = NaN();
if (descriptor != NULL) {
if (descriptor->instanceOf("CascadingDescriptor")) {
if (!isNaN(
descriptor->getExplicitDuration()) &&
event == wholeContent) {
duration = descriptor->getExplicitDuration();
} else if (event->getDuration() > 0) {
duration = event->getDuration();
} else {
duration = 0;
}
}
} else {
if (event->getDuration() > 0) {
duration = event->getDuration();
} else {
duration = 0;
}
}
if (duration < 0) {
event->setDuration(NaN());
} else {
event->setDuration(duration);
}
}
bool ExecutionObject::removeEvent(FormatterEvent* event) {
if (!containsEvent(event)) {
return false;
}
vector<FormatterEvent*>::iterator i;
set<SelectionEvent*>::iterator j;
if (event->instanceOf("PresentationEvent")) {
for (i = presentationEvents->begin();
i != presentationEvents->end(); ++i) {
if (*i == event) {
presentationEvents->erase(i);
break;
}
}
removeEventTransition((PresentationEvent*)event);
} else if (event->instanceOf("SelectionEvent")) {
j = selectionEvents->find(((SelectionEvent*)event));
if (j != selectionEvents->end()) {
selectionEvents->erase(j);
}
} else {
for (i = otherEvents->begin();
i != otherEvents->end(); ++i) {
if (*i == event) {
otherEvents->erase(i);
break;
}
}
}
lockEvents();
events->erase(events->find(event->getId()));
unlockEvents();
return true;
}
bool ExecutionObject::isCompiled() {
return isItCompiled;
}
void ExecutionObject::setCompiled(bool status) {
isItCompiled = status;
}
void ExecutionObject::removeNode(Node* node) {
Node* parentNode;
if (node != dataObject) {
if (nodeParentTable->count(node) != 0) {
parentNode = (*nodeParentTable)[node];
if (parentTable->count(parentNode) != 0) {
parentTable->erase(parentTable->find(parentNode));
}
nodeParentTable->erase(nodeParentTable->find(node));
}
}
}
vector<Node*>* ExecutionObject::getNodes() {
if (nodeParentTable->empty()) {
return NULL;
}
vector<Node*>* nodes;
map<Node*, Node*>::iterator i;
nodes = new vector<Node*>;
for (i = nodeParentTable->begin(); i != nodeParentTable->end(); ++i) {
nodes->push_back(i->first);
}
if (nodeParentTable->count(dataObject) == 0) {
nodes->push_back(dataObject);
}
return nodes;
}
NodeNesting* ExecutionObject::getNodePerspective() {
return getNodePerspective(dataObject);
}
NodeNesting* ExecutionObject::getNodePerspective(Node* node) {
Node* parentNode;
NodeNesting* perspective;
CompositeExecutionObject* parentObject;
if (nodeParentTable->count(node) == 0) {
if (dataObject == node) {
perspective = new NodeNesting();
} else {
return NULL;
}
} else {
parentNode = (*nodeParentTable)[node];
if (parentTable->count(parentNode) != 0) {
parentObject = (CompositeExecutionObject*)(
(*parentTable)[parentNode]);
perspective = parentObject->getNodePerspective(parentNode);
} else {
return NULL;
}
}
perspective->insertAnchorNode(node);
return perspective;
}
vector<ExecutionObject*>* ExecutionObject::getObjectPerspective() {
return getObjectPerspective(dataObject);
}
vector<ExecutionObject*>* ExecutionObject::getObjectPerspective(
Node* node) {
Node* parentNode;
vector<ExecutionObject*>* perspective = NULL;
CompositeExecutionObject* parentObject;
if (nodeParentTable->count(node) == 0) {
if (dataObject == node) {
perspective = new vector<ExecutionObject*>;
} else {
return NULL;
}
} else {
parentNode = (*nodeParentTable)[node];
if (parentTable->count(parentNode) != 0) {
parentObject = (CompositeExecutionObject*)(
(*parentTable)[parentNode]);
perspective = parentObject->getObjectPerspective(parentNode);
} else {
return NULL;
}
}
if (perspective != NULL) {
perspective->push_back(this);
}
return perspective;
}
vector<Node*>* ExecutionObject::getParentNodes() {
if (nodeParentTable->empty()) {
return NULL;
}
vector<Node*>* parents;
map<Node*, Node*>::iterator i;
parents = new vector<Node*>;
for (i = nodeParentTable->begin(); i != nodeParentTable->end(); ++i) {
parents->push_back(i->second);
}
return parents;
}
FormatterEvent* ExecutionObject::getMainEvent() {
return mainEvent;
}
bool ExecutionObject::prepare(FormatterEvent* event, double offsetTime) {
CompositeExecutionObject* parentObject;
int size;
EventTransition* transition;
map<Node*, void*>::iterator i;
double startTime = 0;
ContentAnchor* contentAnchor;
lock();
if (event == NULL || !containsEvent(event)) {
return false;
}
mainEvent = event;
if (mainEvent->getCurrentState() != EventUtil::ST_SLEEPING) {
return false;
}
if (mainEvent->instanceOf("AnchorEvent")) {
contentAnchor = ((AnchorEvent*)mainEvent)->getAnchor();
if (contentAnchor != NULL &&
contentAnchor->instanceOf("LabeledAnchor")) {
i = parentTable->begin();
while (i != parentTable->end()) {
parentObject = (CompositeExecutionObject*)(i->second);
// register parent as a mainEvent listener
mainEvent->addEventListener(parentObject);
++i;
}
return true;
}
}
if (mainEvent->instanceOf("PresentationEvent")) {
startTime = ((PresentationEvent*)mainEvent)->
getBegin() + offsetTime;
if (startTime > ((PresentationEvent*)mainEvent)->getEnd()) {
return false;
}
}
i = parentTable->begin();
while (i != parentTable->end()) {
parentObject = (CompositeExecutionObject*)(i->second);
// register parent as a mainEvent listener
mainEvent->addEventListener(parentObject);
++i;
}
if (mainEvent == wholeContent && startTime == 0.0) {
startTransitionIndex = 0;
} else {
size = transitionTable->size();
startTransitionIndex = 0;
while (startTransitionIndex < size) {
transition = (*transitionTable)[startTransitionIndex];
if (transition->getTime() >= startTime) {
break;
}
if (transition->instanceOf("BeginEventTransition")) {
transition->getEvent()->
setCurrentState(EventUtil::ST_OCCURRING);
} else {
transition->getEvent()->
setCurrentState(EventUtil::ST_SLEEPING);
transition->getEvent()->incrementOccurrences();
}
startTransitionIndex++;
}
}
FormatterEvent* auxEvent;
AttributionEvent* attributeEvent;
PropertyAnchor* attributeAnchor;
int j;
string value;
if (otherEvents != NULL) {
size = otherEvents->size();
for (j = 0; j < size; j++) {
auxEvent = (*otherEvents)[j];
if (auxEvent->instanceOf("AttributionEvent")) {
attributeEvent = (AttributionEvent*)auxEvent;
attributeAnchor = attributeEvent->getAnchor();
value = attributeAnchor->getPropertyValue();
if (value != "") {
attributeEvent->setValue(value);
}
}
}
}
this->offsetTime = startTime;
currentTransitionIndex = startTransitionIndex;
return true;
}
bool ExecutionObject::start() {
EventTransition* transition;
ContentAnchor* contentAnchor;
if (mainEvent == NULL && wholeContent == NULL) {
return false;
}
if (mainEvent != NULL &&
mainEvent->getCurrentState() != EventUtil::ST_SLEEPING) {
return false;
}
if (mainEvent == NULL) {
prepare(wholeContent, 0.0);
}
if (mainEvent->instanceOf("AnchorEvent")) {
contentAnchor = ((AnchorEvent*)mainEvent)->getAnchor();
if (contentAnchor != NULL &&
contentAnchor->instanceOf("LabeledAnchor")) {
mainEvent->start();
return true;
}
}
while ((unsigned int)currentTransitionIndex <
transitionTable->size()) {
transition = (*transitionTable)[currentTransitionIndex];
if (transition->getTime() <= offsetTime) {
if (transition->instanceOf("BeginEventTransition")) {
transition->getEvent()->start();
}
currentTransitionIndex++;
} else {
break;
}
}
return true;
}
void ExecutionObject::updateTransitionTable(double currentTime) {
EventTransition* transition;
while ((unsigned int)currentTransitionIndex <
transitionTable->size()) {
transition = (*transitionTable)[currentTransitionIndex];
if (transition->getTime() <= currentTime) {
if (transition->instanceOf("BeginEventTransition")) {
transition->getEvent()->start();
} else {
transition->getEvent()->stop();
}
currentTransitionIndex++;
} else {
break;
}
}
}
EventTransition* ExecutionObject::getNextTransition() {
if (mainEvent == NULL ||
mainEvent->getCurrentState() == EventUtil::ST_SLEEPING ||
!mainEvent->instanceOf("PresentationEvent")) {
return NULL;
}
EventTransition* transition;
if ((unsigned int)currentTransitionIndex <
transitionTable->size()) {
transition = transitionTable->at(currentTransitionIndex);
if (IntervalAnchor::isObjectDuration(
((PresentationEvent*)mainEvent)->getEnd()) ||
(transition->getTime() <=
((PresentationEvent*)mainEvent)->getEnd())) {
return transition;
}
}
return NULL;
}
bool ExecutionObject::stop() {
EventTransition* transition;
ContentAnchor* contentAnchor;
vector<EventTransition*>::iterator i;
double endTime;
if (mainEvent == NULL) {
return false;
}
if (mainEvent->getCurrentState() == EventUtil::ST_SLEEPING) {
return false;
}
if (mainEvent->instanceOf("PresentationEvent")) {
endTime = ((PresentationEvent*)mainEvent)->getEnd();
i = transitionTable->begin();
while (i != transitionTable->end()) {
transition = *i;
if (transition->getTime() > endTime) {
transition->getEvent()->setCurrentState(
EventUtil::ST_SLEEPING);
} else if (transition->instanceOf("EndEventTransition")) {
transition->getEvent()->stop();
}
++i;
}
} else if (mainEvent->instanceOf("AnchorEvent")) {
contentAnchor = ((AnchorEvent*)mainEvent)->getAnchor();
if (contentAnchor != NULL &&
contentAnchor->instanceOf("LabeledAnchor")) {
mainEvent->stop();
}
}
currentTransitionIndex = startTransitionIndex;
pauseCount = 0;
return true;
}
bool ExecutionObject::abort() {
int i, size;
EventTransition* transition;
ContentAnchor* contentAnchor;
short objectState;
if (mainEvent == NULL) {
return false;
}
objectState = mainEvent->getCurrentState();
if (objectState == EventUtil::ST_SLEEPING) {
return false;
}
size = transitionTable->size();
if (mainEvent->instanceOf("PresentationEvent")) {
for (i = currentTransitionIndex; i < size; i++) {
transition = (*transitionTable)[i];
if (transition->getTime() > ((PresentationEvent*)mainEvent)->
getEnd()) {
transition->getEvent()->setCurrentState(
EventUtil::ST_SLEEPING);
} else if (transition->instanceOf("EndEventTransition")) {
transition->getEvent()->abort();
}
}
} else if (mainEvent->instanceOf("AnchorEvent")) {
contentAnchor = ((AnchorEvent*)mainEvent)->getAnchor();
if (contentAnchor != NULL &&
contentAnchor->instanceOf("LabeledAnchor")) {
mainEvent->abort();
}
}
currentTransitionIndex = startTransitionIndex;
pauseCount = 0;
return true;
}
bool ExecutionObject::pause() {
FormatterEvent* event;
vector<FormatterEvent*>* evs;
vector<FormatterEvent*>::iterator i;
if (mainEvent == NULL ||
mainEvent->getCurrentState() == EventUtil::ST_SLEEPING) {
return false;
}
evs = getEvents();
if (evs != NULL) {
if (pauseCount == 0) {
i = evs->begin();
while (i != evs->end()) {
event = *i;
if (event->getCurrentState() == EventUtil::ST_OCCURRING) {
event->pause();
}
++i;
}
}
delete evs;
evs = NULL;
}
pauseCount++;
return true;
}
bool ExecutionObject::resume() {
FormatterEvent* event;
vector<FormatterEvent*>* evs;
vector<FormatterEvent*>::iterator i;
if (pauseCount == 0) {
return false;
} else {
pauseCount--;
if (pauseCount > 0) {
return false;
}
}
evs = getEvents();
if (evs != NULL) {
if (pauseCount == 0) {
i = evs->begin();
while (i != evs->end()) {
event = *i;
if (event->getCurrentState() == EventUtil::ST_PAUSED) {
event->resume();
}
++i;
}
}
delete evs;
evs = NULL;
}
return true;
}
bool ExecutionObject::setPropertyValue(
AttributionEvent* event,
string value, Animation* anim) {
if (!containsEvent(event) || value == "") {
cout << "ExecutionObject::setPropertyValue event '";
cout << event->getId() << "' not found!" << endl;
return false;
}
string propName;
FormatterRegion* region;
LayoutRegion* ncmRegion;
bool done = false;
double initTime;
bool changed;
propName = (event->getAnchor())->getPropertyName();
/*cout << "ExecutionObject::setPropertyValue prop '" << propName;
cout << "' value '" << value << "' for '" << getId() << "'";
if (anim != NULL) {
cout << " animDur = '" << anim->getDuration() << "'";
}
cout << " anim = '" << anim << "'" << endl;*/
if (anim == NULL || stof(anim->getDuration()) <= 0.0) {
if (propName == "size") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 2) {
region = descriptor->getFormatterRegion();
ncmRegion = region->getLayoutRegion();
if (isPercentualValue((*params)[0])) {
ncmRegion->setWidth(getPercentualValue(
(*params)[0]), true);
} else {
ncmRegion->setWidth(
(double)(stof((*params)[0])), false);
}
if (isPercentualValue((*params)[1])) {
ncmRegion->setHeight(
getPercentualValue((*params)[1]), true);
} else {
ncmRegion->setHeight(
(double)(stof((*params)[1])), false);
}
delete params;
params = NULL;
region->updateRegionBounds();
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "location") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 2) {
region = descriptor->getFormatterRegion();
ncmRegion = region->getLayoutRegion();
if (isPercentualValue((*params)[0])) {
ncmRegion->setLeft(
getPercentualValue((*params)[0]), true);
} else {
ncmRegion->setLeft(
(double)(stof((*params)[0])), false);
}
if (isPercentualValue((*params)[1])) {
ncmRegion->setTop(
getPercentualValue((*params)[1]), true);
} else {
ncmRegion->setTop((double)(stof((*params)[1])), false);
}
delete params;
params = NULL;
region->updateRegionBounds();
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "bounds") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 4) {
region = descriptor->getFormatterRegion();
ncmRegion = region->getLayoutRegion();
if (ncmRegion->compareWidthSize((*params)[2]) <= 0) {
// first resize the region, then update its location
if (isPercentualValue((*params)[2])) {
ncmRegion->setWidth(getPercentualValue(
(*params)[2]), true);
} else {
ncmRegion->setWidth(
(double)(stof((*params)[2])), false);
}
if (isPercentualValue((*params)[0])) {
ncmRegion->setLeft(getPercentualValue(
(*params)[0]), true);
} else {
ncmRegion->setLeft(
(double)(stof((*params)[0])), false);
}
} else {
// first update and then resize
if (isPercentualValue((*params)[0])) {
ncmRegion->setLeft(getPercentualValue(
(*params)[0]), true);
} else {
ncmRegion->setLeft(
(double)(stof((*params)[0])), false);
}
if (isPercentualValue((*params)[2])) {
ncmRegion->setWidth(getPercentualValue(
(*params)[2]), true);
} else {
ncmRegion->setWidth(
(double)(stof((*params)[2])), false);
}
}
if (ncmRegion->compareHeightSize((*params)[3]) <= 0) {
// first resize the region, then update its location
if (isPercentualValue((*params)[3])) {
ncmRegion->setHeight(getPercentualValue(
(*params)[3]), true);
} else {
ncmRegion->setHeight(
(double)(stof((*params)[3])), false);
}
if (isPercentualValue((*params)[1])) {
ncmRegion->setTop(getPercentualValue(
(*params)[1]), true);
} else {
ncmRegion->setTop(
(double)(stof((*params)[1])), false);
}
} else {
// first update and then resize
if (isPercentualValue((*params)[1])) {
ncmRegion->setTop(getPercentualValue(
(*params)[1]), true);
} else {
ncmRegion->setTop(
(double)(stof((*params)[1])), false);
}
if (isPercentualValue((*params)[3])) {
ncmRegion->setHeight(
getPercentualValue((*params)[3]), true);
} else {
ncmRegion->setHeight(
(double)(stof((*params)[3])), false);
}
}
/*cout << "ExecutionObject::setPropertyValue bounds ";
cout << " to '" << getId() << "' value = '";
cout << value << "'" << endl;*/
delete params;
params = NULL;
region->updateRegionBounds();
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "top" || propName == "left" ||
propName == "bottom" || propName == "right" ||
propName == "width" || propName == "height") {
region = descriptor->getFormatterRegion();
ncmRegion = region->getLayoutRegion();
if (propName == "top") {
if (isPercentualValue(value)) {
ncmRegion->setTop(getPercentualValue(value), true);
} else {
ncmRegion->setTop((double)(stof(value)), false);
}
} else if (propName == "left") {
if (isPercentualValue(value)) {
ncmRegion->setLeft(getPercentualValue(value), true);
} else {
ncmRegion->setLeft((double)(stof(value)), false);
}
} else if (propName == "width") {
if (isPercentualValue(value)) {
ncmRegion->setWidth(getPercentualValue(value), true);
} else {
ncmRegion->setWidth((double)(stof(value)), false);
}
} else if (propName == "height") {
if (isPercentualValue(value)) {
ncmRegion->setHeight(getPercentualValue(value), true);
} else {
ncmRegion->setHeight((double)(stof(value)), false);
}
} else if (propName == "bottom") {
if (isPercentualValue(value)) {
ncmRegion->setBottom(getPercentualValue(value), true);
} else {
ncmRegion->setBottom((double)(stof(value)), false);
}
} else if (propName == "right") {
if (isPercentualValue(value)) {
ncmRegion->setRight(getPercentualValue(value), true);
} else {
ncmRegion->setRight((double)(stof(value)), false);
}
}
region->updateRegionBounds();
event->stop();
return true;
}
} else {
double dur;
dur = stof(anim->getDuration());
initTime = getCurrentTimeMillis();
if (propName == "size") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 2) {
region = descriptor->getFormatterRegion();
pthread_t id1;
pthread_t id2;
struct animeInfo* data1;
struct animeInfo* data2;
data1 = new struct animeInfo;
data1->value = (*params)[0];
data1->region = region;
data1->duration = dur;
data1->propName = "width";
data2 = new struct animeInfo;
data2->value = (*params)[1];
data2->region = region;
data2->duration = dur;
data2->propName = "height";
pthread_create(
&id1, 0, ExecutionObject::animeThread, data1);
pthread_create(
&id2, 0, ExecutionObject::animeThread, data2);
delete params;
params = NULL;
pthread_join(id1, NULL);
pthread_join(id2, NULL);
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "location") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 2) {
region = descriptor->getFormatterRegion();
pthread_t id1;
pthread_t id2;
struct animeInfo* data1;
struct animeInfo* data2;
data1 = new struct animeInfo;
data1->value = (*params)[0];
data1->region = region;
data1->duration = dur;
data1->propName = "left";
data2 = new struct animeInfo;
data2->value = (*params)[1];
data2->region = region;
data2->duration = dur;
data2->propName = "top";
pthread_create(
&id1, 0, ExecutionObject::animeThread, data1);
pthread_create(
&id2, 0, ExecutionObject::animeThread, data2);
delete params;
params = NULL;
pthread_join(id1, NULL);
pthread_join(id2, NULL);
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "bounds") {
value = trim(value);
vector<string>* params;
params = split(value, ",");
if (params->size() == 4) {
region = descriptor->getFormatterRegion();
pthread_t id1;
pthread_t id2;
pthread_t id3;
pthread_t id4;
struct animeInfo* data1;
struct animeInfo* data2;
struct animeInfo* data3;
struct animeInfo* data4;
data1 = new struct animeInfo;
data1->value = (*params)[0];
data1->region = region;
data1->duration = dur;
data1->propName = "left";
data2 = new struct animeInfo;
data2->value = (*params)[1];
data2->region = region;
data2->duration = dur;
data2->propName = "top";
data3 = new struct animeInfo;
data3->value = (*params)[2];
data3->region = region;
data3->duration = dur;
data3->propName = "width";
data4 = new struct animeInfo;
data4->value = (*params)[3];
data4->region = region;
data4->duration = dur;
data4->propName = "height";
pthread_create(
&id1, 0, ExecutionObject::animeThread, data1);
pthread_create(
&id2, 0, ExecutionObject::animeThread, data2);
pthread_create(
&id3, 0, ExecutionObject::animeThread, data3);
pthread_create(
&id4, 0, ExecutionObject::animeThread, data4);
delete params;
params = NULL;
pthread_join(id1, NULL);
pthread_join(id2, NULL);
pthread_join(id3, NULL);
pthread_join(id4, NULL);
event->stop();
return true;
}
delete params;
params = NULL;
} else if (propName == "top" || propName == "left" ||
propName == "bottom" || propName == "right" ||
propName == "width" || propName == "height") {
region = descriptor->getFormatterRegion();
ncmRegion = region->getLayoutRegion();
initTime = getCurrentTimeMillis();
while (!done) {
done = animeStep(
value,
ncmRegion,
initTime,
stof(anim->getDuration()), propName);
region->updateRegionBounds();
}
event->stop();
return true;
}
}
return false;
}
void* ExecutionObject::animeThread(void* ptr) {
struct animeInfo* data;
string value, propName;
FormatterRegion* fRegion;
LayoutRegion* region;
double initTime, dur;
bool done;
data = (struct animeInfo*)ptr;
done = false;
value = data->value;
fRegion = data->region;
dur = data->duration;
propName = data->propName;
delete data;
data = NULL;
initTime = getCurrentTimeMillis();
region = fRegion->getLayoutRegion();
while (!done) {
done = animeStep(value, region, initTime, dur, propName);
fRegion->updateRegionBounds();
}
return NULL;
}
bool ExecutionObject::animeStep(
string value,
LayoutRegion* region,
double initTime,
double dur,
string param) {
LayoutRegion* clone;
double time;
int factor, current, target;
bool percent;
clone = region->cloneRegion();
percent = isPercentualValue(value);
if (percent) {
if (param == "width") {
current = region->getWidthInPixels();
clone->setWidth(getPercentualValue(value), true);
target = clone->getWidthInPixels();
} else if (param == "height") {
current = region->getHeightInPixels();
clone->setHeight(getPercentualValue(value), true);
target = clone->getHeightInPixels();
} else if (param == "left") {
current = region->getLeftInPixels();
clone->setLeft(getPercentualValue(value), true);
target = clone->getLeftInPixels();
} else if (param == "top") {
current = region->getTopInPixels();
clone->setTop(getPercentualValue(value), true);
target = clone->getTopInPixels();
} else if (param == "bottom") {
current = region->getBottomInPixels();
clone->setBottom(getPercentualValue(value), true);
target = clone->getBottomInPixels();
} else if (param == "right") {
current = region->getRightInPixels();
clone->setRight(getPercentualValue(value), true);
target = clone->getRightInPixels();
}
} else {
if (param == "width") {
current = region->getWidthInPixels();
clone->setWidth(stof(value), false);
target = clone->getWidthInPixels();
} else if (param == "height") {
current = region->getHeightInPixels();
clone->setHeight(stof(value), false);
target = clone->getHeightInPixels();
} else if (param == "left") {
current = region->getLeftInPixels();
clone->setLeft(stof(value), false);
target = clone->getLeftInPixels();
} else if (param == "top") {
current = region->getTopInPixels();
clone->setTop(stof(value), false);
target = clone->getTopInPixels();
} else if (param == "bottom") {
current = region->getBottomInPixels();
clone->setBottom(stof(value), false);
target = clone->getBottomInPixels();
} else if (param == "right") {
current = region->getRightInPixels();
clone->setRight(stof(value), false);
target = clone->getRightInPixels();
}
}
/*cout << "ExecutionObject::animeStep value '" << value << "'";
cout << " initTime '" << initTime << "' time '" << time << "'";
cout << " target '" << target << "' current '" << current << "'";
cout << " param '" << param << "'" << endl;*/
if (target > current) {
factor = 1;
} else if (target < current) {
factor = -1;
} else {
//cout << endl << "ExecutionObject::animeStep TRUE 1" << endl;
delete clone;
return true;
}
time = getCurrentTimeMillis();
current = getNextStepValue(
current, target,
factor, time, initTime, (dur * 1000), 1);
if (current < 0) {
if (param == "width") {
region->setWidth(target, false);
} else if (param == "height") {
region->setHeight(target, false);
} else if (param == "left") {
region->setLeft(target, false);
} else if (param == "top") {
region->setTop(target, false);
} else if (param == "bottom") {
region->setBottom(target, false);
} else if (param == "right") {
region->setRight(target, false);
}
delete clone;
return true;
}
//cout << " nextStep '" << current << "'" << endl;
if (param == "width") {
region->setWidth(current, false);
} else if (param == "height") {
region->setHeight(current, false);
} else if (param == "left") {
region->setLeft(current, false);
} else if (param == "top") {
region->setTop(current, false);
} else if (param == "bottom") {
region->setBottom(current, false);
} else if (param == "right") {
region->setRight(current, false);
}
//cout << "ExecutionObject::animeStep FALSE" << endl;
delete clone;
return false;
}
bool ExecutionObject::unprepare() {
if (mainEvent == NULL ||
mainEvent->getCurrentState() != EventUtil::ST_SLEEPING) {
unlock();
return false;
}
map<Node*, void*>::iterator i;
CompositeExecutionObject* parentObject;
i = parentTable->begin();
while (i != parentTable->end()) {
parentObject = (CompositeExecutionObject*)(i->second);
// register parent as a mainEvent listener
mainEvent->removeEventListener(parentObject);
++i;
}
mainEvent = NULL;
unlock();
return true;
}
void ExecutionObject::select(int accessCode, double currentTime) {
int size, selCode;
SelectionEvent* selectionEvent;
IntervalAnchor* intervalAnchor;
set<SelectionEvent*>* selectedEvents;
set<SelectionEvent*>::iterator i;
//simulating some keys of keyboard
if (accessCode == CodeMap::KEY_F1) {
accessCode = CodeMap::KEY_RED;
} else if (accessCode == CodeMap::KEY_F2) {
accessCode = CodeMap::KEY_GREEN;
} else if (accessCode == CodeMap::KEY_F3) {
accessCode = CodeMap::KEY_YELLOW;
} else if (accessCode == CodeMap::KEY_F4) {
accessCode = CodeMap::KEY_BLUE;
} else if (accessCode == CodeMap::KEY_F5) {
accessCode = CodeMap::KEY_MENU;
} else if (accessCode == CodeMap::KEY_F6) {
accessCode = CodeMap::KEY_INFO;
} else if (accessCode == CodeMap::KEY_F7) {
accessCode = CodeMap::KEY_EPG;
} else if (accessCode == CodeMap::KEY_PLUS_SIGN) {
accessCode = CodeMap::KEY_VOLUME_UP;
} else if (accessCode == CodeMap::KEY_MINUS_SIGN) {
accessCode = CodeMap::KEY_VOLUME_DOWN;
} else if (accessCode == CodeMap::KEY_PAGE_UP) {
accessCode = CodeMap::KEY_CHANNEL_UP;
} else if (accessCode == CodeMap::KEY_PAGE_DOWN) {
accessCode = CodeMap::KEY_CHANNEL_DOWN;
} else if (accessCode == CodeMap::KEY_BACKSPACE) {
accessCode = CodeMap::KEY_BACK;
} else if (accessCode == CodeMap::KEY_ESCAPE) {
accessCode = CodeMap::KEY_EXIT;
}
selectedEvents = new set<SelectionEvent*>;
i = selectionEvents->begin();
while (i != selectionEvents->end()) {
selectionEvent = (SelectionEvent*)(*i);
selCode = selectionEvent->getSelectionCode();
if (selCode == accessCode) {
if (selectionEvent->getAnchor()->instanceOf(
"IntervalAnchor")) {
intervalAnchor = (IntervalAnchor*)(
selectionEvent->getAnchor());
if (intervalAnchor->getBegin() <= currentTime
&& currentTime <= intervalAnchor->getEnd()) {
selectedEvents->insert(selectionEvent);
}
} else {
selectedEvents->insert(selectionEvent);
}
}
++i;
}
i = selectedEvents->begin();
while (i != selectedEvents->end()) {
selectionEvent = (*i);
if (!selectionEvent->start()) {
cout << "ExecutionObject::select Warning cant start '";
cout << selectionEvent->getId() << "'" << endl;
}
++i;
}
delete selectedEvents;
selectedEvents = NULL;
}
set<int>* ExecutionObject::getInputEvents() {
set<SelectionEvent*>::iterator i;
set<int>* evs;
SelectionEvent* ev;
int keyCode;
evs = new set<int>;
i = selectionEvents->begin();
while (i != selectionEvents->end()) {
ev = (*i);
keyCode = ev->getSelectionCode();
evs->insert(keyCode);
if (keyCode == CodeMap::KEY_RED) {
evs->insert(CodeMap::KEY_F1);
} else if (keyCode == CodeMap::KEY_GREEN) {
evs->insert(CodeMap::KEY_F2);
} else if (keyCode == CodeMap::KEY_YELLOW) {
evs->insert(CodeMap::KEY_F3);
} else if (keyCode == CodeMap::KEY_BLUE) {
evs->insert(CodeMap::KEY_F4);
} else if (keyCode == CodeMap::KEY_MENU) {
evs->insert(CodeMap::KEY_F5);
} else if (keyCode == CodeMap::KEY_INFO) {
evs->insert(CodeMap::KEY_F6);
} else if (keyCode == CodeMap::KEY_EPG) {
evs->insert(CodeMap::KEY_F7);
} else if (keyCode == CodeMap::KEY_VOLUME_UP) {
evs->insert(CodeMap::KEY_PLUS_SIGN);
} else if (keyCode == CodeMap::KEY_VOLUME_DOWN) {
evs->insert(CodeMap::KEY_MINUS_SIGN);
} else if (keyCode == CodeMap::KEY_CHANNEL_UP) {
evs->insert(CodeMap::KEY_PAGE_UP);
} else if (keyCode == CodeMap::KEY_CHANNEL_DOWN) {
evs->insert(CodeMap::KEY_PAGE_DOWN);
} else if (keyCode == CodeMap::KEY_BACK) {
evs->insert(CodeMap::KEY_BACKSPACE);
} else if (keyCode == CodeMap::KEY_EXIT) {
evs->insert(CodeMap::KEY_ESCAPE);
}
++i;
}
return evs;
}
void ExecutionObject::lock() {
pthread_mutex_lock(&mutex);
}
void ExecutionObject::unlock() {
pthread_mutex_unlock(&mutex);
}
void ExecutionObject::lockEvents() {
pthread_mutex_lock(&mutexEvent);
}
void ExecutionObject::unlockEvents() {
pthread_mutex_unlock(&mutexEvent);
}
}
}
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
1888
]
]
] |
88c964be9152e81e109c6be2d3811fa3bfbbb3c4 | 00a4dc4a9ea1fc6657a81607e285055fc29bda29 | /Engine/source/Stage.h | ab04298d72daf3ee5f12662a346bd7ab333eb5dd | [] | no_license | etgarcia/AS3-for-Airplay-SDK | d5d5e2443879b37aff7486d8f07453769568cbfc | 470f2cc49d19642128f49dcc5618702671a1f851 | refs/heads/master | 2016-09-05T10:21:56.570562 | 2011-01-27T06:25:13 | 2011-01-27T06:25:13 | 1,380,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | h | #pragma once
#include "DisplayObjectContainer.h"
#include "Sprite.h"
#include "BitmapObject.h"
class Stage :
public DisplayObjectContainer
{
public:
Stage();
~Stage(void);
void render();
float getMsPerFrame();
protected:
uint32 stageColor;
uint16 frameRate;
}; | [
"etgarcia@d6d0176c-4ec9-df4c-96f2-63634c7079df"
] | [
[
[
1,
17
]
]
] |
fa88db5d783d5288a76bacbac28b23a0773352b4 | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /branches/CamFighter 1.0/Utils/Filesystem.cpp | 605f23967dba7d575dcba8f92b204dcc3a2cb7a8 | [] | no_license | dogtwelve/fighter3d | 7bb099f0dc396e8224c573743ee28c54cdd3d5a2 | c073194989bc1589e4aa665714c5511f001e6400 | refs/heads/master | 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 112 | cpp | #include "Filesystem.h"
std::string Filesystem::WorkingDirectory = Filesystem::GetSystemWorkingDirectory();
| [
"dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561"
] | [
[
[
1,
3
]
]
] |
ce97c3d6b0e7f77307fb769993d807cad97c5213 | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/objects/components/ICmpOrientation.h | bb304057c643c7c0096d666a00e3fc113bdbae1e | [] | no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | h | /***
* hesperus: ICmpOrientation.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_ICMPORIENTATION
#define H_HESP_ICMPORIENTATION
#include <source/level/objects/base/ObjectComponent.h>
namespace hesp {
//#################### FORWARD DECLARATIONS ####################
typedef shared_ptr<class NUVAxes> NUVAxes_Ptr;
typedef shared_ptr<const class NUVAxes> NUVAxes_CPtr;
class ICmpOrientation : public ObjectComponent
{
//#################### PUBLIC ABSTRACT METHODS ####################
public:
virtual NUVAxes_Ptr nuv_axes() = 0;
virtual NUVAxes_CPtr nuv_axes() const = 0;
//#################### PUBLIC METHODS ####################
public:
std::string group_type() const { return "Orientation"; }
static std::string static_group_type() { return "Orientation"; }
std::string own_type() const { return "Orientation"; }
static std::string static_own_type() { return "Orientation"; }
};
//#################### TYPEDEFS ####################
typedef shared_ptr<ICmpOrientation> ICmpOrientation_Ptr;
typedef shared_ptr<const ICmpOrientation> ICmpOrientation_CPtr;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
3063cbf42cd4c3ef93aa8c8d7b28f11ca0cca33d | 4758b780dad736c20ec46e3e901ecdf5a0921c04 | /vm/client/SourceCode/vmClient.cpp | a9daf59b24f7872ca1cef9244c93a96bb4fd3598 | [] | no_license | arbv/kronos | 8f165515e77851d98b0e60b04d4b64d5bc40f3ea | 4974f865161b78161011cb92223bef45930261d9 | refs/heads/master | 2023-08-19T18:56:36.980449 | 2008-08-23T19:44:08 | 2008-08-23T19:44:08 | 97,011,574 | 1 | 1 | null | 2017-07-12T13:31:54 | 2017-07-12T13:31:54 | null | UTF-8 | C++ | false | false | 3,525 | cpp | #include "preCompiled.h"
#include <winsock2.h>
#include "cO_win32_display.h"
#include "cO_win32_keyboard.h"
#include "cO_tcp.h"
dword connectTo(const char *server, word port)
{
WSADATA data;
word nVersion = MAKEWORD(2,1);
if (WSAStartup(nVersion, &data) != 0)
{
dword dw = WSAGetLastError();
trace("connectTo(WSAStartup): %d [%08X]\n", dw, dw);
return INVALID_SOCKET;
}
HOSTENT *he = gethostbyname(server);
if (he == NULL)
{
long ipAddr = inet_addr(server);
if (ipAddr != INADDR_NONE)
he = gethostbyaddr((const char *)&ipAddr, sizeof(ipAddr), AF_INET);
}
if (he == NULL)
{
// host not found
dword dw = WSAGetLastError();
trace("connectTo(gethost): %d [%08X]\n", dw, dw);
return INVALID_SOCKET;
}
dword so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (so == INVALID_SOCKET)
{
// not enough memory?
dword dw = WSAGetLastError();
trace("connectTo(socket): %d [%08X]\n", dw, dw);
return so;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.S_un.S_addr = *(dword *)(he->h_addr_list[0]);
if (connect(so, (sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR)
{
closesocket(so);
// can not connect to the server
dword dw = WSAGetLastError();
trace("connectTo(connect): %d [%08X]\n", dw, dw);
return INVALID_SOCKET;
}
return so;
}
int atoi(const char *s)
{
int n = 0;
while (*s >= '0' && *s <= '9')
{
n = n*10 + *s++ - '0';
}
return n;
}
char* skipword(const char* pStr)
{
while (pStr != null && *pStr != 0 && *pStr != ' ')
{
if (*pStr == '"')
{
pStr++;
while (*pStr != 0 && *pStr != '"') pStr++;
if (*pStr != '"')
return null;
pStr++;
}
else
pStr++;
}
return (char*)pStr;
}
char* skipspaces(const char* pStr)
{
while (pStr != null && *pStr == ' ')
pStr++;
return (char*)pStr;
}
void ParseArgs(char **psz, word *port)
{
char* pCommandLine = GetCommandLine();
char *p = skipword(pCommandLine);
p = skipspaces(p);
if (p != null && *p != 0)
{
char* q = skipword(p);
if (q != null && *q != 0) { *q = 0; q++; }
if (*p == '"') p++;
if (strlen(p) > 0 && p[strlen(p)-1] == '"') p[strlen(p)-1] = 0;
if (strlen(p) > 0)
*psz = p;
if (q != null && *q != 0) p = skipspaces(q);
else p = null;
}
if (p != null && *p != 0)
{
char* q = skipword(p);
if (q != null && *q != 0) { *q = 0; q++; }
if (*p == '"') p++;
if (strlen(p) > 0 && p[strlen(p)-1] == '"') p[strlen(p)-1] = 0;
if (strlen(p) > 0)
*port = (word)atoi(p);
}
}
int main() // int ac, char *av[])
{
char *szServer = "localhost";
word port = 8086;
ParseArgs(&szServer, &port);
dword so = connectTo(szServer, port);
if (so == INVALID_SOCKET)
return 1;
cO_win32_display d;
cO_win32_keyboard k;
cO_tcp n(so, d);
int ch;
do
{
ch = k.read();
if (ch != 0)
n.write((byte *)&ch, 1);
} while (ch != 0);
return 0;
}
| [
"leo.kuznetsov@4e16752f-1752-0410-94d0-8bc3fbd73b2e"
] | [
[
[
1,
158
]
]
] |
e1dfc9eb2d4ff26db77c822df47822c537c61bc0 | 5efdf4f304c39c1aa8a24ab5a9690afad3340c00 | /src/Keybuffer.h | e158aa319a179821233ffe76471fe90576e1c7e2 | [] | no_license | asquared/hockeyboard | 286f57d8bea282e74425cbe77d915d692398f722 | 06480cb228dcd6d4792964837e20a1dddea89d1b | refs/heads/master | 2016-09-06T11:16:20.947224 | 2011-01-09T21:23:16 | 2011-01-09T21:23:16 | 1,236,086 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | h | #ifndef _keybuffer_h_
#define _keybuffer_h_
#include <string>
class Keybuffer {
private:
std::string buf;
bool enterflag;
public:
Keybuffer();
~Keybuffer() {}
bool enter() { return enterflag; }
char last() { return buf[buf.size()-1]; }
std::string fullbuf() { return buf; }
void add(char key);
void clear() { buf.clear(); }
};
#endif | [
"pymlofy@4cf78214-6c29-4fb8-b038-d2ccc4421ee9"
] | [
[
[
1,
23
]
]
] |
9a28d53a72209e2f79f21489e6102ca0c8c87ef4 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/HUD/ScriptBind_HUD.cpp | cfb1fe60518847cd190e409661ac0f3289b74d2e | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 17,931 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2006.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 14:02:2006 11:29 : Created by AlexL
- 04:04:2006 17:30 : Extended by Jan Müller
*************************************************************************/
#include "StdAfx.h"
#include "ScriptBind_HUD.h"
#include "HUD.h"
#include "IGameObject.h"
#include "Game.h"
#include "GameRules.h"
#include "HUDRadar.h"
#include "HUD/HUDPowerStruggle.h"
#include "HUD/HUDCrosshair.h"
#include "Menus/FlashMenuObject.h"
//------------------------------------------------------------------------
CScriptBind_HUD::CScriptBind_HUD(ISystem *pSystem, IGameFramework *pGameFramework)
: m_pSystem(pSystem),
m_pSS(pSystem->GetIScriptSystem()),
m_pGameFW(pGameFramework)
{
Init(m_pSS, m_pSystem);
SetGlobalName("HUD");
RegisterMethods();
RegisterGlobals();
}
//------------------------------------------------------------------------
CScriptBind_HUD::~CScriptBind_HUD()
{
}
//------------------------------------------------------------------------
void CScriptBind_HUD::RegisterGlobals()
{
m_pSS->SetGlobalValue("MO_DEACTIVATED", CHUDMissionObjective::DEACTIVATED);
m_pSS->SetGlobalValue("MO_COMPLETED", CHUDMissionObjective::COMPLETED);
m_pSS->SetGlobalValue("MO_FAILED", CHUDMissionObjective::FAILED);
m_pSS->SetGlobalValue("MO_ACTIVATED", CHUDMissionObjective::ACTIVATED);
m_pSS->SetGlobalValue("eBLE_Information", eBLE_Information);
m_pSS->SetGlobalValue("eBLE_Currency", eBLE_Currency);
m_pSS->SetGlobalValue("eBLE_Warning", eBLE_Warning);
m_pSS->SetGlobalValue("eBLE_System", eBLE_System);
}
//------------------------------------------------------------------------
void CScriptBind_HUD::RegisterMethods()
{
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CScriptBind_HUD::
SCRIPT_REG_TEMPLFUNC(SetObjectiveStatus,"objective,status,silent");
SCRIPT_REG_TEMPLFUNC(GetObjectiveStatus,"");
SCRIPT_REG_TEMPLFUNC(SetMainObjective, "objective");
SCRIPT_REG_FUNC(GetMainObjective);
SCRIPT_REG_TEMPLFUNC(SetObjectiveEntity,"objective,entity");
SCRIPT_REG_TEMPLFUNC(DrawStatusText, "text");
SCRIPT_REG_TEMPLFUNC(SetUsability, "objId, message");
SCRIPT_REG_FUNC(ReloadLevel);
SCRIPT_REG_FUNC(ReloadLevelSavegame);
SCRIPT_REG_FUNC(TacWarning);
SCRIPT_REG_FUNC(HitIndicator);
SCRIPT_REG_TEMPLFUNC(DamageIndicator, "weaponId, shooterId, direction, onVehicle");
SCRIPT_REG_TEMPLFUNC(EnteredBuyZone, "zoneId, entered");
SCRIPT_REG_TEMPLFUNC(EnteredServiceZone, "zoneId, entered");
SCRIPT_REG_TEMPLFUNC(UpdateBuyList, "");
SCRIPT_REG_TEMPLFUNC(RadarShowVehicleReady, "vehicleId");
SCRIPT_REG_TEMPLFUNC(AddEntityToRadar, "entityId");
SCRIPT_REG_TEMPLFUNC(RemoveEntityFromRadar, "entityId");
SCRIPT_REG_TEMPLFUNC(ShowKillZoneTime, "active, seconds");
SCRIPT_REG_TEMPLFUNC(OnPlayerVehicleBuilt, "vehicleId, playerId");
SCRIPT_REG_FUNC(StartPlayerFallAndPlay);
SCRIPT_REG_TEMPLFUNC(ShowDeathFX, "type");
SCRIPT_REG_TEMPLFUNC(BattleLogEvent, "type, msg, [p1], [p2], [p3], [p4]");
SCRIPT_REG_TEMPLFUNC(OnItemBought, "success, itemName");
SCRIPT_REG_FUNC(FakeDeath);
SCRIPT_REG_TEMPLFUNC(ShowWarningMessage, "warning, text");
SCRIPT_REG_TEMPLFUNC(GetMapGridCoord, "x, y");
SCRIPT_REG_TEMPLFUNC(OpenPDA, "show, buymenu");
SCRIPT_REG_TEMPLFUNC(ShowCaptureProgress, "show");
SCRIPT_REG_TEMPLFUNC(SetCaptureProgress, "progress");
SCRIPT_REG_TEMPLFUNC(SetCaptureContested, "contested");
SCRIPT_REG_TEMPLFUNC(ShowConstructionProgress, "show, queued, constructionTime");
SCRIPT_REG_TEMPLFUNC(ShowReviveCycle, "show");
SCRIPT_REG_TEMPLFUNC(SpawnGroupInvalid, "");
SCRIPT_REG_TEMPLFUNC(SetProgressBar, "show, percent, text");
SCRIPT_REG_TEMPLFUNC(DisplayBigOverlayFlashMessage, "msg, duration, posX, posY, color");
SCRIPT_REG_TEMPLFUNC(FadeOutBigOverlayFlashMessage, "");
SCRIPT_REG_TEMPLFUNC(GetLastInGameSave, "");
#undef SCRIPT_REG_CLASSNAME
}
//------------------------------------------------------------------------
int CScriptBind_HUD::SetObjectiveStatus(IFunctionHandler *pH,const char* pObjectiveID, int status, bool silent)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
CHUDMissionObjective* pObj = pHUD->GetMissionObjectiveSystem().GetMissionObjective(pObjectiveID);
if (pObj)
{
pObj->SetSilent(silent);
pObj->SetStatus((CHUDMissionObjective::HUDMissionStatus)status);
}
else
GameWarning("CScriptBind_HUD::Tried to access non existing MissionObjective '%s'", pObjectiveID);
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_HUD::GetObjectiveStatus(IFunctionHandler* pH, const char* pObjectiveID)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
CHUDMissionObjective* pObj = pHUD->GetMissionObjectiveSystem().GetMissionObjective(pObjectiveID);
if (pObj)
{
return pH->EndFunction(pObj->GetStatus());
}
else
GameWarning("CScriptBind_HUD::Tried to access non existing MissionObjective '%s'", pObjectiveID);
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_HUD::SetMainObjective(IFunctionHandler* pH, const char* pObjectiveID)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD || !pObjectiveID)
return pH->EndFunction();
pHUD->SetMainObjective(pObjectiveID, true);
return pH->EndFunction();
}
//------------------------------------------------------------------------
int CScriptBind_HUD::GetMainObjective(IFunctionHandler* pH)
{
CHUD* pHUD = g_pGame->GetHUD();
if(!pHUD)
return pH->EndFunction();
return pH->EndFunction(pHUD->GetMainObjective());
}
//------------------------------------------------------------------------
int CScriptBind_HUD::SetObjectiveEntity(IFunctionHandler *pH,const char* pObjectiveID, ScriptHandle entityID)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
CHUDMissionObjective* pObj = pHUD->GetMissionObjectiveSystem().GetMissionObjective(pObjectiveID);
if (pObj)
pObj->SetTrackedEntity((EntityId)entityID.n);
else
GameWarning("CScriptBind_HUD::Tried to access non existing MissionObjective '%s'", pObjectiveID);
return pH->EndFunction();
}
int CScriptBind_HUD::SetUsability(IFunctionHandler *pH, int objId, const char *message)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
int usable = (gEnv->pEntitySystem->GetEntity(objId))?1:0;
string textLabel;
bool gotMessage = (message && strlen(message) != 0);
if(gotMessage)
textLabel = message;
string param;
if(usable == 1)
{
if(IVehicle *pVehicle = gEnv->pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(objId))
{
textLabel = "@use_vehicle";
if(IActor *pActor = g_pGame->GetIGameFramework()->GetClientActor())
{
int pteamId=g_pGame->GetGameRules()->GetTeam(pActor->GetEntityId());
int vteamId=g_pGame->GetGameRules()->GetTeam(objId);
if (vteamId && vteamId!=pteamId)
{
usable = 2;
textLabel = "@use_vehicle_locked";
}
}
}
else if(IItem *pItem = gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GetItem(objId))
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetClientActor());
if(pActor)
{
if(!gotMessage)
return pH->EndFunction();
//Offhand controls pick up messages
/*if(!pActor->CheckInventoryRestrictions(pItem->GetEntity()->GetClass()->GetName()))
{
usable = 2;
textLabel = "@inventory_full";
}
else
{
if(!gotMessage)
return pH->EndFunction();
}*/
}
}
else
{
if(gEnv->bMultiplayer && !gotMessage)
usable = 0;
else if(!gotMessage)
textLabel = "@pick_object";
}
}
else
textLabel = ""; //turn off text
pHUD->GetCrosshair()->SetUsability(usable, textLabel.c_str(), (param.empty())?NULL:param.c_str());
return pH->EndFunction();
}
int CScriptBind_HUD::DrawStatusText(IFunctionHandler *pH, const char* pText)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
pHUD->TextMessage(pText);
return pH->EndFunction();
}
//-------------------------------------------------------------------------------------------------
int CScriptBind_HUD::ReloadLevel(IFunctionHandler *pH)
{
string command("map ");
command.append(gEnv->pGame->GetIGameFramework()->GetLevelName());
gEnv->pConsole->ExecuteString(command.c_str());
return pH->EndFunction();
}
int CScriptBind_HUD::ReloadLevelSavegame(IFunctionHandler *pH)
{
gEnv->pGame->InitMapReloading();
return pH->EndFunction();
}
int CScriptBind_HUD::TacWarning(IFunctionHandler *pH)
{
CHUD *pHUD = g_pGame->GetHUD();
if (!pHUD)
return pH->EndFunction();
std::vector<CHUDRadar::RadarEntity> buildings = *(pHUD->GetRadar()->GetBuildings());
for(int i = 0; i < buildings.size(); ++i)
{
IEntity *pEntity = gEnv->pEntitySystem->GetEntity(buildings[i].m_id);
if(!stricmp(pEntity->GetClass()->GetName(), "HQ"))
{
Vec3 pos = pEntity->GetWorldPos();
pos.z += 10;
ISound *pSound = gEnv->pSoundSystem->CreateSound("sounds/interface:multiplayer_interface:mp_tac_alarm_ambience", FLAG_SOUND_3D);
if(pSound)
{
pSound->SetPosition(pos);
pSound->Play();
}
}
}
return pH->EndFunction();
}
int CScriptBind_HUD::EnteredBuyZone(IFunctionHandler *pH, ScriptHandle zoneId, bool entered)
{
// call the hud, tell him we entered a buy zone
// the hud itself needs to keep track of which team owns the zone and enable/disable buying accordingly
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->UpdateBuyZone(entered, (EntityId)zoneId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::EnteredServiceZone(IFunctionHandler *pH, ScriptHandle zoneId, bool entered)
{
// call the hud, tell him we entered a service zone
// the hud itself needs to keep track of which team owns the zone and enable/disable buying accordingly
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->UpdateServiceZone(entered, (EntityId)zoneId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::UpdateBuyList(IFunctionHandler *pH)
{
// something that might have changed item availability happened, so we better update our list
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD && pHUD->GetPowerStruggleHUD())
{
pHUD->GetPowerStruggleHUD()->UpdateBuyList();
pHUD->GetPowerStruggleHUD()->UpdateBuyZone(true, 0);
pHUD->GetPowerStruggleHUD()->UpdateServiceZone(true, 0);
}
return pH->EndFunction();
}
int CScriptBind_HUD::DamageIndicator(IFunctionHandler *pH, ScriptHandle weaponId, ScriptHandle shooterId, Vec3 direction, bool onVehicle)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
{
pHUD->IndicateDamage((EntityId)weaponId.n, direction, onVehicle);
pHUD->ShowTargettingAI((EntityId)shooterId.n);
}
return pH->EndFunction();
}
int CScriptBind_HUD::HitIndicator(IFunctionHandler *pH)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->IndicateHit();
return pH->EndFunction();
}
int CScriptBind_HUD::RadarShowVehicleReady(IFunctionHandler *pH, ScriptHandle vehicleId)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->GetRadar()->ShowEntityTemporarily(EWayPoint, (EntityId)vehicleId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::AddEntityToRadar(IFunctionHandler *pH, ScriptHandle entityId)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->GetRadar()->AddEntityToRadar((EntityId)entityId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::RemoveEntityFromRadar(IFunctionHandler *pH, ScriptHandle entityId)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->GetRadar()->RemoveFromRadar((EntityId)entityId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::ShowKillZoneTime(IFunctionHandler *pH, bool active, int seconds)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->ShowKillAreaWarning(active, seconds);
return pH->EndFunction();
}
int CScriptBind_HUD::StartPlayerFallAndPlay(IFunctionHandler *pH)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->StartPlayerFallAndPlay();
return pH->EndFunction();
}
int CScriptBind_HUD::OnPlayerVehicleBuilt(IFunctionHandler *pH, ScriptHandle playerId, ScriptHandle vehicleId)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->OnPlayerVehicleBuilt((EntityId)playerId.n, (EntityId)vehicleId.n);
return pH->EndFunction();
}
int CScriptBind_HUD::ShowDeathFX(IFunctionHandler *pH, int type)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD)
pHUD->ShowDeathFX(type);
return pH->EndFunction();
}
int CScriptBind_HUD::OnItemBought(IFunctionHandler *pH, bool success, const char* itemName)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD)
pHUD->PlaySound(success?ESound_BuyBeep:ESound_BuyError);
if(success && itemName && pHUD->GetPowerStruggleHUD())
{
pHUD->GetPowerStruggleHUD()->SetLastPurchase(itemName);
}
return pH->EndFunction();
}
int CScriptBind_HUD::BattleLogEvent(IFunctionHandler *pH, int type, const char *msg)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD)
{
string p[4];
for (int i=0;i<pH->GetParamCount()-2;i++)
{
switch(pH->GetParamType(3+i))
{
case svtPointer:
{
ScriptHandle sh;
pH->GetParam(3+i, sh);
if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity((EntityId)sh.n))
p[i]=pEntity->GetName();
}
break;
default:
{
ScriptAnyValue value;
pH->GetParamAny(3+i, value);
switch(value.GetVarType())
{
case svtNumber:
p[i].Format("%g", value.number);
break;
case svtString:
p[i]=value.str;
break;
case svtBool:
p[i]=value.b?"true":"false";
break;
default:
break;
}
}
break;
}
}
pHUD->BattleLogEvent(type, msg, p[0].c_str(), p[1].c_str(), p[2].c_str(), p[3].c_str());
}
return pH->EndFunction();
}
int CScriptBind_HUD::ShowWarningMessage(IFunctionHandler *pH, int message, const char* text)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD)
pHUD->ShowWarningMessage(EWarningMessages(message), text);
return pH->EndFunction();
}
int CScriptBind_HUD::GetMapGridCoord(IFunctionHandler *pH, float x, float y)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD)
{
Vec2i grid=pHUD->GetRadar()->GetMapGridPosition(x, y);
return pH->EndFunction(grid.x, grid.y);
}
return pH->EndFunction();
}
int CScriptBind_HUD::OpenPDA(IFunctionHandler *pH, bool show, bool buyMenu)
{
CHUD *pHUD = g_pGame->GetHUD();
if(!pHUD)
return pH->EndFunction();
pHUD->ShowPDA(show, buyMenu);
return pH->EndFunction();
}
int CScriptBind_HUD::ShowCaptureProgress(IFunctionHandler *pH, bool show)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->ShowCaptureProgress(show);
return pH->EndFunction();
}
int CScriptBind_HUD::SetCaptureProgress(IFunctionHandler *pH, float progress)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->SetCaptureProgress(progress);
return pH->EndFunction();
}
int CScriptBind_HUD::SetCaptureContested(IFunctionHandler *pH, bool contested)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->SetCaptureContested(contested);
return pH->EndFunction();
}
int CScriptBind_HUD::ShowConstructionProgress(IFunctionHandler *pH, bool show, bool queued, float constructionTime)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->GetPowerStruggleHUD()->ShowConstructionProgress(show, queued, constructionTime);
return pH->EndFunction();
}
int CScriptBind_HUD::ShowReviveCycle(IFunctionHandler *pH, bool show)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->ShowReviveCycle(show);
return pH->EndFunction();
}
int CScriptBind_HUD::SpawnGroupInvalid(IFunctionHandler *pH)
{
CHUD *pHUD = g_pGame->GetHUD();
if(pHUD && pHUD->GetPowerStruggleHUD())
pHUD->SpawnPointInvalid();
return pH->EndFunction();
}
int CScriptBind_HUD::FakeDeath(IFunctionHandler *pH)
{
CHUD *pHUD = g_pGame->GetHUD();
if (pHUD && !pHUD->IsFakeDead())
pHUD->FakeDeath();
return pH->EndFunction();
}
int CScriptBind_HUD::SetProgressBar(IFunctionHandler *pH, bool show, int progress, const char *text)
{
if (CHUD *pHUD = g_pGame->GetHUD())
{
if (show)
pHUD->ShowProgress(CLAMP(progress, 0, 100), true, 400, 200, text);
else
pHUD->ShowProgress();
}
return pH->EndFunction();
}
int CScriptBind_HUD::DisplayBigOverlayFlashMessage(IFunctionHandler *pH, const char *msg, float duration, int posX, int posY, Vec3 color)
{
if (CHUD *pHUD = g_pGame->GetHUD())
{
pHUD->DisplayBigOverlayFlashMessage(msg, duration, posX, posY, color);
}
return pH->EndFunction();
}
int CScriptBind_HUD::FadeOutBigOverlayFlashMessage(IFunctionHandler *pH)
{
if (CHUD *pHUD = g_pGame->GetHUD())
{
pHUD->FadeOutBigOverlayFlashMessage();
}
return pH->EndFunction();
}
int CScriptBind_HUD::GetLastInGameSave(IFunctionHandler *pH)
{
string *lastSave = g_pGame->GetMenu()->GetLastInGameSave();
if (lastSave)
{
return pH->EndFunction(lastSave->c_str());
}
return pH->EndFunction();
}
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
22
],
[
24,
65
],
[
67,
75
],
[
77,
79
],
[
81,
85
],
[
87,
89
],
[
91,
93
],
[
95,
95
],
[
103,
151
],
[
162,
191
],
[
194,
194
],
[
199,
199
],
[
202,
209
],
[
214,
215
],
[
217,
220
],
[
223,
226
],
[
230,
300
],
[
311,
320
],
[
322,
364
],
[
374,
405
],
[
407,
411
],
[
417,
488
],
[
500,
502
],
[
504,
511
],
[
513,
517
],
[
529,
531
],
[
533,
537
],
[
539,
540
],
[
552,
563
]
],
[
[
23,
23
],
[
66,
66
],
[
76,
76
],
[
80,
80
],
[
86,
86
],
[
90,
90
],
[
94,
94
],
[
96,
102
],
[
152,
161
],
[
192,
193
],
[
195,
198
],
[
200,
201
],
[
210,
213
],
[
216,
216
],
[
221,
222
],
[
227,
229
],
[
301,
310
],
[
321,
321
],
[
365,
373
],
[
406,
406
],
[
412,
416
],
[
489,
499
],
[
503,
503
],
[
512,
512
],
[
518,
528
],
[
532,
532
],
[
538,
538
],
[
541,
551
],
[
564,
606
]
]
] |
e173189470584213826f0ba972abfb2b4e6e3759 | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/game/WeaponData.h | fdb16b9d8fd32645b92d5023f18c33e537755a85 | [] | no_license | crutchwalkfactory/motocakerteam | 1cce9f850d2c84faebfc87d0adbfdd23472d9f08 | 0747624a575fb41db53506379692973e5998f8fe | refs/heads/master | 2021-01-10T12:41:59.321840 | 2010-12-13T18:19:27 | 2010-12-13T18:19:27 | 46,494,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,964 | h | // WeaponData.h
// 1.0
// This file is part of OpenRedAlert.
//
// OpenRedAlert is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2 of the License.
//
// OpenRedAlert is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OpenRedAlert. If not, see <http://www.gnu.org/licenses/>.
#ifndef WEAPONDATA_H
#define WEAPONDATA_H
#include <string>
#include "SDL/SDL_types.h"
#include "misc/INIFile.h"
using std::string;
/**
* Weapon Statistics
*
* The weapons specified here are attached to the various combat units and buildings.
*/
class WeaponData
{
public:
string getAnim();
void setAnim(string anim);
Uint32 getBurst();
void setBurst(Uint32 burst);
Uint32 getTurboBoost();
void setTurboBoost(Uint32 turboBoost);
Uint32 getSupress();
void setSupress(Uint32 supress);
string getWarhead();
void setWarhead(string warhead);
Uint32 getSpeed();
void setSpeed(Uint32 speed);
string getReport();
void setReport(string report);
Uint32 getRange();
void setRange(Uint32 range);
Uint32 getRof();
void setRof(Uint32 rof);
string getProjectile();
void setProjectile(string projectile);
Uint32 getDamage();
void setDamage(Uint32 damage);
Uint32 getCharges();
void setCharges(Uint32 charges);
Uint32 getCamera();
void setCamera(Uint32 camera);
static WeaponData* loadWeaponData(INIFile* file, string name);
void print();
private:
/** animation to display as a firing effect*/
string anim;
/** number of rapid succession shots from this weapon (def=1)*/
Uint32 burst;
/** Reveals area around firer (def=no)?*/
Uint32 camera;
/** Does it have charge-up-before-firing logic (def=no)?*/
Uint32 charges;
/** the amount of damage (unattenuated) dealt with every bullet*/
Uint32 damage;
/** projectile characteristic to use*/
string projectile;
/** delay between shots [15 = 1 second at middle speed setting]*/
Uint32 rof;
/** maximum cell range*/
Uint32 range;
/** sound to play when firing*/
string report;
/** speed of projectile to target (100 is maximum)*/
Uint32 speed;
/** warhead to attach to projectile*/
string warhead;
/** Should nearby friendly buildings be scanned for and if found, discourage firing on target (def=no)?*/
Uint32 supress;
/** Should the weapon get a boosted speed bonus when firing upon aircraft?*/
Uint32 turboBoost;
};
#endif //WEAPONDATA_H
| [
"[email protected]"
] | [
[
[
1,
122
]
]
] |
ba990072297270df3f652812ba78dccecd27108d | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/framework/XMLSchemaDescription.hpp | aeb3f1c29bd5f4d80e767bcd980df89ec874269f | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,290 | hpp | /*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Log: XMLSchemaDescription.hpp,v $
* Revision 1.4 2004/09/08 13:55:59 peiyongz
* Apache License Version 2.0
*
* Revision 1.3 2003/10/14 15:17:47 peiyongz
* Implementation of Serialization/Deserialization
*
* Revision 1.2 2003/07/31 17:03:19 peiyongz
* locationHint incrementally added
*
* Revision 1.1 2003/06/20 18:37:39 peiyongz
* Stateless Grammar Pool :: Part I
*
* $Id: XMLSchemaDescription.hpp,v 1.4 2004/09/08 13:55:59 peiyongz Exp $
*
*/
#if !defined(XMLSCHEMADESCRIPTION_HPP)
#define XMLSCHEMADESCRIPTION_HPP
#include <xercesc/framework/XMLGrammarDescription.hpp>
#include <xercesc/util/RefArrayVectorOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
typedef const XMLCh* const LocationHint;
class XMLPARSER_EXPORT XMLSchemaDescription : public XMLGrammarDescription
{
public :
// -----------------------------------------------------------------------
/** @name Virtual destructor for derived classes */
// -----------------------------------------------------------------------
//@{
/**
* virtual destructor
*
*/
virtual ~XMLSchemaDescription();
//@}
// -----------------------------------------------------------------------
/** @name Implementation of Grammar Description Interface */
// -----------------------------------------------------------------------
//@{
/**
* getGrammarType
*
*/
virtual Grammar::GrammarType getGrammarType() const
{
return Grammar::SchemaGrammarType;
}
//@}
// -----------------------------------------------------------------------
/** @name The SchemaDescription Interface */
// -----------------------------------------------------------------------
//@{
enum ContextType
{
CONTEXT_INCLUDE,
CONTEXT_REDEFINE,
CONTEXT_IMPORT,
CONTEXT_PREPARSE,
CONTEXT_INSTANCE,
CONTEXT_ELEMENT,
CONTEXT_ATTRIBUTE,
CONTEXT_XSITYPE,
CONTEXT_UNKNOWN
};
/**
* getContextType
*
*/
virtual ContextType getContextType() const = 0;
/**
* getTargetNamespace
*
*/
virtual const XMLCh* getTargetNamespace() const = 0;
/**
* getLocationHints
*
*/
virtual RefArrayVectorOf<XMLCh>* getLocationHints() const = 0;
/**
* getTriggeringComponent
*
*/
virtual const QName* getTriggeringComponent() const = 0;
/**
* getenclosingElementName
*
*/
virtual const QName* getEnclosingElementName() const = 0;
/**
* getAttributes
*
*/
virtual const XMLAttDef* getAttributes() const = 0;
/**
* setContextType
*
*/
virtual void setContextType(ContextType) = 0;
/**
* setTargetNamespace
*
*/
virtual void setTargetNamespace(const XMLCh* const) = 0;
/**
* setLocationHints
*
*/
virtual void setLocationHints(const XMLCh* const) = 0;
/**
* setTriggeringComponent
*
*/
virtual void setTriggeringComponent(QName* const) = 0;
/**
* getenclosingElementName
*
*/
virtual void setEnclosingElementName(QName* const) = 0;
/**
* setAttributes
*
*/
virtual void setAttributes(XMLAttDef* const) = 0;
//@}
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(XMLSchemaDescription)
protected :
// -----------------------------------------------------------------------
/** Hidden Constructors */
// -----------------------------------------------------------------------
//@{
XMLSchemaDescription(MemoryManager* const memMgr = XMLPlatformUtils::fgMemoryManager);
//@}
private :
// -----------------------------------------------------------------------
/** name Unimplemented copy constructor and operator= */
// -----------------------------------------------------------------------
//@{
XMLSchemaDescription(const XMLSchemaDescription& );
XMLSchemaDescription& operator=(const XMLSchemaDescription& );
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
] | [
[
[
1,
191
]
]
] |
edcf05aa5a971e16104009f51ec51f2ee362a46e | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/list_resource.inl | 25829a4368f11b6701763ba8333bc7fee473f492 | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | inl | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__LIST_RESOURCE_INL
#define AOSLCPP_AOSL__LIST_RESOURCE_INL
// Begin prologue.
//
//
// End prologue.
#include "aosl/resource.hpp"
#include "aosl/resource.inl"
namespace aosl
{
// List_resource
//
inline
const List_resource::ResourceSequence& List_resource::
resource () const
{
return this->resource_;
}
inline
List_resource::ResourceSequence& List_resource::
resource ()
{
return this->resource_;
}
inline
void List_resource::
resource (const ResourceSequence& s)
{
this->resource_ = s;
}
}
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__LIST_RESOURCE_INL
| [
"klaim@localhost"
] | [
[
[
1,
53
]
]
] |
474ad905e90f80c8995f754d34807bf16f574f72 | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /big.cpp | 5d48c0085c96147d3562fe4db756176ae172e4bb | [] | no_license | cnsuhao/kgui-1 | d0a7d1e11cc5c15d098114051fabf6218f26fb96 | ea304953c7f5579487769258b55f34a1c680e3ed | refs/heads/master | 2021-05-28T22:52:18.733717 | 2011-03-10T03:10:47 | 2011-03-10T03:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,681 | cpp | /**********************************************************************************/
/* kGUI - big.cpp */
/* */
/* Programmed by Kevin Pickell */
/* */
/* http://code.google.com/p/kgui/ */
/* */
/* kGUI 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; version 2. */
/* */
/* kGUI is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* http://www.gnu.org/licenses/lgpl.txt */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with kGUI; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* */
/**********************************************************************************/
/*! @file big.cpp
@brief This is the BigFile class. A big file is essentially a file that contains
many other files inside of it. The files can be encrypted if desired using the
kGUIProt class. */
#include "kgui.h"
/* todo: if waste>10% then compress and rebuild file */
extern long MS_FileTime(const char *fn);
BigFile::BigFile()
{
m_dirloaded=false;
m_numdirblocks=0;
m_dirchanged=false;
m_dirblocks.Alloc(16);
m_dirblocks.SetGrow(true);
m_dirblocks.SetGrowSize(16);
m_hash.Init(16,sizeof(BigFileEntry *));
m_numentries=0;
m_entries.Init(1024,-1);
}
BigFile::~BigFile()
{
UpdateDir(); /* if any pending changes then write them now */
FreeDirBlocks(); /* only allocated if opened in edit mode */
}
BigFileEntry *BigFile::Locate(const char *fn)
{
BigFileEntry **pbfe;
pbfe=(BigFileEntry **)m_hash.Find(fn);
if(!pbfe)
return 0;
return(pbfe[0]);
}
void BigFile::FreeDirBlocks(void)
{
unsigned int b;
DIRINFO_DEF di;
for(b=0;b<m_numdirblocks;++b)
{
di=m_dirblocks.GetEntry(b);
delete []di.data;
}
m_numdirblocks=0;
m_dirloaded=false;
}
/* if edit flag is set then keep directory blocks in memory */
/* since they are written out as a large block for encryption */
void BigFile::Load(bool edit)
{
long doffset;
long deoffset;
char sentinel[4];
DataHandle section;
DIRINFO_DEF di;
UpdateDir(); /* if any pending changes then write them now */
FreeDirBlocks();
m_numentries=0;
m_dirloaded=true;
m_edit=edit;
m_hash.Init(16,sizeof(BigFileEntry *)); /* re-init */
m_empty=false;
m_bad=false;
/* since encryption is based on a specific size chunk, the bigfile */
/* is processed in chunks */
SetOpenLock(true); /* no root file access, only via area sections */
CopyArea(§ion,0,12,GetTime());
if(section.Open()==false)
{
m_empty=true;
return;
}
section.Read(&sentinel,(unsigned long)4);
if(!(sentinel[0]=='B' && sentinel[1]=='I' && sentinel[2]=='G' && sentinel[3]=='F'))
{
m_bad=true;
section.Close(); /* bad file type, or wrong encryption */
return;
}
/* read in the current end of file position */
section.Read(&m_curend,(unsigned long)4);
section.Read(&m_curwaste,(unsigned long)4);
section.Close();
/* load directory blocks and add entries to the hash table */
doffset=12;
do
{
char *dirblock;
unsigned long dirsize;
BigFileEntry *bfe;
BIGENTRY_DEF *be;
/* load a directory block */
CopyArea(§ion,doffset,sizeof(m_lastheader),GetTime());
section.Open();
section.Read(&m_lastheader,(unsigned long)sizeof(m_lastheader));
section.Close();
/* load the directory block */
dirsize=m_lastheader.blocksize-sizeof(m_lastheader);
CopyArea(§ion,doffset+sizeof(m_lastheader),dirsize,GetTime());
section.Open();
dirblock=new char[m_lastheader.blocksize];
memcpy(dirblock,&m_lastheader,sizeof(m_lastheader));
section.Read(dirblock+sizeof(m_lastheader),dirsize);
section.Close();
/* save block in memory if opened for edit */
if(edit==true)
{
di.changed=false;
di.size=m_lastheader.blocksize;
di.offset=doffset;
di.data=dirblock;
m_dirblocks.SetEntry(m_numdirblocks,di);
++m_numdirblocks;
}
be=(BIGENTRY_DEF *)(dirblock+sizeof(m_lastheader));
deoffset=doffset+sizeof(m_lastheader);
for(unsigned int i=0;i<m_lastheader.numfiles;++i)
{
if(be->nameoffset) /* 0=deleted */
{
/* check for any corruption */
assert((be->nameoffset>=sizeof(BIGHEADER_DEF)) && (be->nameoffset<=m_lastheader.blocksize),"Name offset error!");
assert((be->dataoffset<=m_curend),"Data offset is past end of file!");
bfe=m_entries.GetEntryPtr(m_numentries++);
bfe->m_name.SetString(dirblock+be->nameoffset);
bfe->m_dirblocknum=m_numdirblocks-1; /* only valid in edit mode */
bfe->m_diroffset=deoffset;
bfe->m_offset=be->dataoffset;
bfe->m_time=be->time;
bfe->m_crc=be->crc;
bfe->m_size=be->size;
assert(m_curend>=(bfe->m_offset+bfe->m_size),"Internal Error!");
/* add this filename to the hash table */
m_hash.Add(dirblock+be->nameoffset,&bfe);
}
deoffset+=sizeof(BIGENTRY_DEF);
++be;
}
if(edit==false)
delete []dirblock; /* delete and re-allocate just incase size changes from block to block */
doffset=m_lastheader.nextblock;
}while(doffset);
}
/* calculate the crc for a buffer */
unsigned long BigFile::CrcBuffer(long startcrc,const unsigned char *buf,unsigned long buflen)
{
unsigned long crc;
unsigned char byte;
unsigned long i;
crc=startcrc;
for(i=0;i<buflen;++i)
{
byte=*(buf++)&0xff;
crc=byte^(crc<<6);
crc^=crc>>24;
crc&=0xffffff;
}
return(crc);
}
bool BigFile::CheckDuplicate(DataHandle *af)
{
unsigned int e;
unsigned long crc;
unsigned long long fs;
BigFileEntry *bfe;
unsigned char crcbuf[4096];
/* calc CRC on file */
crc=0;
af->Open();
fs=af->GetSize();
while(fs>sizeof(crcbuf))
{
af->Read(crcbuf,(unsigned long)sizeof(crcbuf));
crc=CrcBuffer(crc,crcbuf,sizeof(crcbuf));
fs-=sizeof(crcbuf);
};
/* read remainder */
if(fs>0)
{
af->Read(crcbuf,(unsigned long)fs);
crc=CrcBuffer(crc,crcbuf,(unsigned long)fs);
}
af->Close();
fs=af->GetSize();
for(e=0;e<m_numentries;++e)
{
bfe=m_entries.GetEntryPtr(e);
if(bfe->m_crc==crc && bfe->m_size==fs)
return(true); /* duplicate!!! */
}
return(false);
}
/* fn is the full path name, addfn is the shorter name to use */
bool BigFile::AddFile(const char *fn,DataHandle *af,bool updatedir)
{
BigFileEntry *bfe;
BIGENTRY_DEF de;
unsigned char copybuf[4096];
long crc;
DataHandle section;
DIRINFO_DEF di;
char *dirblock;
unsigned long asize=af->GetLoadableSize();
long ft=af->GetTime();
unsigned long wasize;
printf("Adding file '%s\n",af->GetFilename()->GetString());
assert(m_edit==true,"BigFile not opened for write, use Load(true)");
if(m_empty==true)
{
/* generate a blank directory header for this file */
m_curend=FIRSTDBLOCKSIZE+12;
m_curwaste=0;
/* write in sections since if big file is encrypted then each section */
/* is encrypted seperately */
CopyArea(§ion,0,12,GetTime());
if(section.OpenWrite("wb")==false)
{
printf("Error making new file '%s'\n",(GetFilename()->GetString()));
return(false);
}
section.Write("BIGF",4);
section.Write(&m_curend,4);
section.Write(&m_curwaste,4);
section.Close();
CopyArea(§ion,12,sizeof(m_lastheader),GetTime());
section.OpenWrite("rb+");
m_lastheader.blocksize=FIRSTDBLOCKSIZE;
m_lastheader.fntail=FIRSTDBLOCKSIZE;
m_lastheader.offset=12;
m_lastheader.numfiles=0;
m_lastheader.nextblock=0;
section.Write(&m_lastheader,sizeof(m_lastheader));
section.Close();
/* allocate block */
dirblock=new char[m_lastheader.blocksize];
memset(dirblock,m_lastheader.blocksize,0);
memcpy(dirblock,&m_lastheader,sizeof(m_lastheader));
di.changed=false;
di.size=m_lastheader.blocksize;
di.offset=m_lastheader.offset;
di.data=dirblock;
m_dirblocks.SetEntry(m_numdirblocks,di);
++m_numdirblocks;
m_empty=false;
}
/* does this file already exist? */
bfe=Locate(fn);
if(bfe)
{
unsigned long woffset;
unsigned long deoffset;
/* if it is the same size or smaller then just update the */
/* length and time, otherwise add to end of file */
/* copy the entry into the di struct */
di=m_dirblocks.GetEntry(bfe->m_dirblocknum);
deoffset=bfe->m_diroffset-di.offset;
memcpy(&de,di.data+deoffset,sizeof(de));
/* update the file time */
de.time=ft;
/* was it at the end of the file? */
if((de.dataoffset+de.size)==m_curend)
{
/* overwrite old file and update new length of file */
m_curend+=(asize-de.size); /* update bigfile size */
de.size=asize; /* update the file size */
woffset=de.dataoffset; /* write at old place */
}
else if(asize<=de.size)
{
/* if equal or smaller then re-use the buffer */
m_curwaste+=(de.size-asize); /* add difference to waste */
de.size=asize; /* update the size */
woffset=de.dataoffset;
}
else /* add to end of file instead */
{
m_curwaste+=de.size; /* add old size to waste */
woffset=m_curend;
de.size=asize; /* update the size */
de.dataoffset=m_curend;
m_curend+=asize;
}
/* write large chunks, first */
crc=0;
CopyArea(§ion,woffset,asize,GetTime());
if(section.OpenWrite("rb+")==false)
return(false); /* error! */
if(af->Open()==false)
{
/* cannot open input file for read */
printf("Cannot open input file '%s' for read!\n",af->GetFilename()->GetString());
return(false);
}
while(asize>sizeof(copybuf))
{
af->Read(copybuf,(unsigned long)sizeof(copybuf));
crc=CrcBuffer(crc,copybuf,sizeof(copybuf));
section.Write(copybuf,sizeof(copybuf));
asize-=sizeof(copybuf);
};
/* write remainder */
if(asize>0)
{
af->Read(copybuf,asize);
crc=CrcBuffer(crc,copybuf,asize);
section.Write(copybuf,asize);
}
af->Close();
if(section.Close()==false)
return(false); /* write error, abort! */
de.crc=crc;
/* update directory entry */
/* copy directory entry into directory block */
memcpy(di.data+deoffset,&de,sizeof(de));
/* flag the directory block as being changed*/
di.changed=true;
m_dirblocks.SetEntry(bfe->m_dirblocknum,di);
/* flag the directory as changed */
m_dirchanged=true;
}
else
{
unsigned int namelen;
unsigned int desize;
unsigned int deoffset;
namelen=(unsigned int)strlen(fn)+1;
/* is there room in the current directory block? */
deoffset=sizeof(m_lastheader)+m_lastheader.numfiles*sizeof(BIGENTRY_DEF);
desize=sizeof(BIGENTRY_DEF)+namelen;
if((deoffset+desize)>m_lastheader.fntail)
{
/* ran out of space, add a new directory block */
/* make previous block link to new one */
di=m_dirblocks.GetEntry(m_numdirblocks-1);
m_lastheader.nextblock=m_curend;
memcpy(di.data,&m_lastheader,sizeof(m_lastheader));
di.changed=true;
m_dirblocks.SetEntry(m_numdirblocks-1,di);
/* generate a new block at the end of the file */
m_lastheader.blocksize=DBLOCKSIZE;
m_lastheader.fntail=DBLOCKSIZE;
m_lastheader.offset=m_curend; /* block is here */
m_lastheader.numfiles=0;
m_lastheader.nextblock=0;
/* update end of file variable */
m_curend+=DBLOCKSIZE;
deoffset=sizeof(m_lastheader);
/* allocate a new block */
dirblock=new char[m_lastheader.blocksize];
memset(dirblock,m_lastheader.blocksize,0);
memcpy(dirblock,&m_lastheader,sizeof(m_lastheader));
di.changed=true; /* write it to the file */
di.size=m_lastheader.blocksize;
di.offset=m_lastheader.offset;
di.data=dirblock;
m_dirblocks.SetEntry(m_numdirblocks,di);
++m_numdirblocks;
}
/* write the data file first, then update the directory and file headers */
assert(m_curend!=0,"Internal error!");
CopyArea(§ion,m_curend,asize,GetTime());
if(section.OpenWrite("rb+",asize)==false)
return(false);
/* write large chunks, first */
af->Open();
crc=0;
wasize=asize;
while(wasize>sizeof(copybuf))
{
af->Read(copybuf,(unsigned long)sizeof(copybuf));
crc=CrcBuffer(crc,copybuf,sizeof(copybuf));
section.Write(copybuf,sizeof(copybuf));
wasize-=sizeof(copybuf);
};
/* write remainder */
if(wasize>0)
{
af->Read(copybuf,asize);
crc=CrcBuffer(crc,copybuf,wasize);
section.Write(copybuf,wasize);
}
af->Close();
if(section.Close()==false)
return(false);
/* ok, fill in the directory entry */
m_lastheader.fntail-=namelen;
m_lastheader.numfiles+=1;
/* copy struct to the direcctory block */
di=m_dirblocks.GetEntry(m_numdirblocks-1);
memcpy(di.data,&m_lastheader,sizeof(m_lastheader));
di.changed=true;
m_dirblocks.SetEntry(m_numdirblocks-1,di);
de.nameoffset=m_lastheader.fntail;
de.dataoffset=m_curend;
de.size=asize;
de.time=ft;
de.crc=crc;
/* copy directory entry into directory block */
memcpy(di.data+deoffset,&de,sizeof(de));
/* copy the filename next */
memcpy(di.data+de.nameoffset,fn,namelen);
m_curend+=asize;
m_dirchanged=true;
}
if(updatedir==true)
UpdateDir();
return(true);
}
void BigFile::UpdateDir(void)
{
unsigned int b;
DIRINFO_DEF di;
DataHandle section;
if(m_dirchanged==true)
{
/* write directory blocks that have changed */
for(b=0;b<m_numdirblocks;++b)
{
di=m_dirblocks.GetEntry(b);
if(di.changed==true)
{
/* since each directory block can be sized differently, and encryption */
/* is based on the data size, we need to write each directory block in */
/* two chunks, first the header, then the variable size fileentry area */
CopyArea(§ion,di.offset+sizeof(BIGHEADER_DEF),di.size-sizeof(BIGHEADER_DEF),GetTime());
section.OpenWrite("rb+");
section.Write(di.data+sizeof(BIGHEADER_DEF),di.size-sizeof(BIGHEADER_DEF));
section.Close();
CopyArea(§ion,di.offset,sizeof(BIGHEADER_DEF),GetTime());
section.OpenWrite("rb+");
section.Write(di.data,sizeof(BIGHEADER_DEF));
section.Close();
/* clear the changed flag on this block since it has now been written */
di.changed=false;
m_dirblocks.SetEntry(b,di);
}
}
/* update header block of file */
CopyArea(§ion,0,12,GetTime());
section.OpenWrite("rb+");
section.Write("BIGF",4);
section.Write(&m_curend,4);
section.Write(&m_curwaste,4);
section.Close();
m_dirchanged=false;
}
}
#define MAXBUF 65536
bool BigFile::Extract(const char *name,const char *filename)
{
BigFileEntry *bfe;
FILE *f2;
char *buf;
unsigned int bufsize;
unsigned int readsize;
unsigned int left;
bool writeerror=false;
DataHandle section;
bfe=Locate(name);
if(!bfe)
return(false); /* error file doesn't exist */
CopyArea(§ion,bfe->m_offset,bfe->m_size,GetTime());
if(section.Open()==false)
return(false);
/* allocate buffer to copy into and out of */
left=bfe->m_size; /* bytes left to copy */
if(bfe->m_size>MAXBUF)
bufsize=MAXBUF;
else
bufsize=bfe->m_size;
buf=new char[bufsize]; /* alloc buffer to copy file via */
if(!buf)
return(false); /* not enough memory to copy file */
f2=fopen(filename,"wb");
if(!f2)
{
delete []buf;
return(false); /* error opening output file */
}
while(left>0 && writeerror==false)
{
if(left>bufsize)
readsize=bufsize;
else
readsize=left;
if(section.Read(buf,(unsigned long)readsize)!=readsize)
writeerror=true;
if(fwrite(buf,1,readsize,f2)!=readsize)
writeerror=true;
left-=readsize;
}
section.Close();
fclose(f2);
delete []buf;
if(writeerror)
return(false);
return(true); /* ok */
}
/* todo, only work in edit mode and flag dir as changed and call updatedir */
void BigFile::Delete(const char *fn)
{
BigFileEntry *bfe;
DIRINFO_DEF di;
assert(m_edit==true,"Error: file is not opened for edit, use Load(true)\n");
bfe=Locate(fn);
if(!bfe)
return;
/* clear the directory entry for this file and flag it for update */
di=m_dirblocks.GetEntry(bfe->m_dirblocknum);
memset(di.data+(bfe->m_diroffset-di.offset),0,sizeof(BIGENTRY_DEF));
di.changed=true;
m_dirblocks.SetEntry(bfe->m_dirblocknum,di);
m_dirchanged=true;
UpdateDir(); /* write to directory */
}
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
] | [
[
[
1,
639
]
]
] |
3de88a7d590cea40c07f1c2b4e6bdfeb6b6f6ffb | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Manager/ObjectManager.h | 2488a98454232e887b815c283f2163a0f6364aab | [] | no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 6,730 | h | /*******************************************************************************/
/**
* @file ObjectManager.h.
*
* @brief オブジェクト管理者クラステンプレート定義.
*
* @date 2008/07/16.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_OBJECTMANAGER_H_
#define _NGL_OBJECTMANAGER_H_
#include "DefaultDestroy.h"
#include <map>
namespace Ngl{
/**
* @class ObjectManager.
* @brief オブジェクト管理者クラステンプレート.
*
* @tparam ID 管理要素ID.
* @tparam Entity 管理要素.
* @tparam Destroy 削除ポリシー.
*
* 汎用オブジェクト管理者クラス。<br>
* EntityManagerと共通の部品を使って作成されています。<br>
* IDで要素を管理できるのが、EntityManagerと違うところ。<br>
*/
template
<
class ID,
class Entity,
class Destroy = DefaultDestroy,
class Map = std::map< ID, Entity >
>
class ObjectManager
{
public:
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
ObjectManager()
{}
/*=========================================================================*/
/**
* @brief デストラクタ
*
* @param[in] なし.
*/
~ObjectManager()
{
clear();
}
/*=========================================================================*/
/**
* @brief 要素を追加
*
* 指定IDのコンテナに要素を格納します。
* 同じIDの要素がすでに存在してた場合は、以前の要素を削除した後、新しい要素を設定します。
*
* @param[in] id 追加する要素ID.
* @param[in] entity 追加する要素.
* @return なし.
*/
void add( ID id, Entity entity )
{
remove( id );
entityContainer_[ id ] = entity;
}
/*=========================================================================*/
/**
* @brief 指定のIDが存在するか
*
* @param[in] id 検索するID.
* @retval true 存在していた.
* @retval false 存在していない.
*/
bool isExist( ID id )
{
if( entityContainer_.find( id ) != entityContainer_.end() ){
return true;
}
return false;
}
/*=========================================================================*/
/**
* @brief 訪問者を受け入れる
*
* 保持しているすべての要素を訪問します。
*
* @tparam Visitor 訪問者.
* @param[in] visitor 訪問者の参照.
* @return なし.
*/
template<class Visitor>
void accept( Visitor& visitor )
{
for( Map::iterator i( entityContainer_.begin() ); i != entityContainer_.end(); ++i ){
visitor.visit( i->second );
}
}
/*=========================================================================*/
/**
* @brief ペア訪問者の受け入れ
*
* 保持しているすべての要素をと要素を総当りで訪問します。
*
* @tparam PairVisitor ペア訪問者.
* @param[in] pair ペア訪問者の参照.
* @return なし.
*/
template<class PairVisitor>
void acceptPair( PairVisitor& pair )
{
for( Map::iterator i( entityContainer_.begin() ); i != entityContainer_.end(); ++i ){
Map::iterator j( i );
for( ++j; j != entityContainer_.end(); ++j ){
pair.visit( i->second, j->second );
}
}
}
/*=========================================================================*/
/**
* @brief 指定のIDを削除
*
* @param[in] id 削除するID.
* @return なし.
*/
void remove( ID id )
{
Map::iterator itor;
itor = entityContainer_.find( id );
if( itor != entityContainer_.end() ){
Destroy::destroy( itor->second );
entityContainer_.erase( itor );
}
}
/*=========================================================================*/
/**
* @brief 要素の削除
*
* すべての要素を評価者が評価します。<br>
* 評価が「真」の場合、その要素を削除します。
*
* @tparam Evaluator 評価者.
* @param[in] evaluator 評価者の参照.
* @return なし
*/
template<class Evaluator>
void remove( Evaluator& evaluator )
{
Map::iterator i( entityContainer_..begin() );
while( i != entityContainer_.end() ){
if( evaluator.evaluate( i->second ) == true ){
Destroy::destroy( i->second );
i = mEntityList.erase( i );
}
else{
++i;
}
}
}
/*=========================================================================*/
/**
* @brief 管理要素をすべて削除
*
* @param[in] なし.
* @return なし.
*/
void clear()
{
Map::iterator itor = entityContainer_.begin();
while( itor != entityContainer_.end() ){
Destroy::destroy( itor->second );
itor = entityContainer_.erase( itor );
}
}
/*=========================================================================*/
/**
* @brief 要素数を取得する
*
* @param[in] なし.
* @return 要素数.
*/
unsigned int size()
{
return (unsigned int)entityContainer_.size();
}
/*=========================================================================*/
/**
* @brief 要素が空か
*
* @param[in] なし.
* @retval true 要素が存在している.
* @retval false 要素が存在していない.
*/
bool empty()
{
return entityContainer_.empty();
}
/*=========================================================================*/
/**
* @brief [] 演算子オーバーロード
*
* idで指定した要素を取得する。
*
* @param[in] id 参照するID.
* @return idの要素.
*/
Entity& operator [] ( ID id )
{
return entityContainer_[ id ];
}
private:
/*=========================================================================*/
/**
* @brief コピーコンストラクタ(コピー禁止処理)
*
* @param[in] other コピーするオブジェクト.
*/
ObjectManager( const ObjectManager& other );
/*=========================================================================*/
/**
* @brief =演算子オーバーロード(コピー禁止処理)
*
* @param[in] other 代入するオブジェクト.
* @return 代入結果のオブジェクト.
*/
ObjectManager& operator = ( const ObjectManager& other );
private:
/** 要素コンテナ */
Map entityContainer_;
};
} // namespace Ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
] | [
[
[
1,
280
]
]
] |
3e8fb4c27ac440521186e7cca0aa3375b37b13cc | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/plugins/zerospu2/zerospu2.cpp | ab173893b19f3c88742b919c9ebc984521eaa532 | [] | no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,439 | cpp | /* ZeroSPU2
* Copyright (C) 2006-2010 zerofrog
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "zerospu2.h"
#ifdef _WIN32
#include "svnrev.h"
#endif
#include "Targets/SoundTargets.h"
#include <assert.h>
#include <stdlib.h>
#include "soundtouch/SoundTouch.h"
#include "soundtouch/WavFile.h"
char libraryName[256];
FILE *spu2Log;
Config conf;
ADMA adma[2];
u32 MemAddr[2];
u32 g_nSpuInit = 0;
u16 interrupt = 0;
s8 *spu2regs = NULL;
u16* spu2mem = NULL;
u16* pSpuIrq[2] = {NULL};
u32 dwNewChannel2[2] = {0}; // keeps track of what channels that have been turned on
u32 dwEndChannel2[2] = {0}; // keeps track of what channels have ended
u32 dwNoiseVal=1; // global noise generator
bool g_bPlaySound = true; // if true, will output sound, otherwise no
s32 iFMod[NSSIZE];
s32 s_buffers[NSSIZE][2]; // left and right buffers
// mixer thread variables
bool s_bThreadExit = true;
s32 s_nDropPacket = 0;
string s_strIniPath( "inis/" );
#ifdef _WIN32
LARGE_INTEGER g_counterfreq;
extern HWND hWMain;
HANDLE s_threadSPU2 = NULL;
DWORD WINAPI SPU2ThreadProc(LPVOID);
#else
#include <pthread.h>
pthread_t s_threadSPU2;
void* SPU2ThreadProc(void*);
#endif
AUDIOBUFFER s_pAudioBuffers[NSPACKETS];
s32 s_nCurBuffer = 0, s_nQueuedBuffers = 0;
s16* s_pCurOutput = NULL;
u32 g_startcount=0xffffffff;
u32 g_packetcount=0;
// time stretch variables
soundtouch::SoundTouch* pSoundTouch=NULL;
extern WavOutFile* g_pWavRecord; // used for recording
u64 s_GlobalTimeStamp = 0;
s32 s_nDurations[64]={0};
s32 s_nCurDuration=0;
s32 s_nTotalDuration=0;
s32 SPUCycles = 0, SPUWorkerCycles = 0;
s32 SPUStartCycle[2];
s32 SPUTargetCycle[2];
int ADMASWrite(int c);
void InitADSR();
// functions of main emu, called on spu irq
void (*irqCallbackSPU2)()=0;
#ifndef ENABLE_NEW_IOPDMA_SPU2
void (*irqCallbackDMA4)()=0;
void (*irqCallbackDMA7)()=0;
#endif
uptr g_pDMABaseAddr=0;
u32 RateTable[160];
// channels and voices
VOICE_PROCESSED voices[SPU_NUMBER_VOICES+1]; // +1 for modulation
static void InitLibraryName()
{
#ifdef _WIN32
#ifdef PUBLIC
// Public Release!
// Output a simplified string that's just our name:
strcpy( libraryName, "ZeroSPU2" );
#elif defined( SVN_REV_UNKNOWN )
// Unknown revision.
// Output a name that includes devbuild status but not
// subversion revision tags:
strcpy( libraryName, "ZeroSPU2"
# ifdef PCSX2_DEBUG
"-Debug"
# elif defined( ZEROSPU2_DEVBUILD )
"-Dev"
# endif
);
#else
// Use TortoiseSVN's SubWCRev utility's output
// to label the specific revision:
sprintf_s( libraryName, "ZeroSPU2 r%d%s"
# ifdef PCSX2_DEBUG
"-Debug"
# elif defined( ZEROSPU2_DEVBUILD )
"-Dev"
# endif
,SVN_REV,
SVN_MODS ? "m" : ""
);
#endif
#else
// I'll hook in svn version code later. --arcum42
strcpy( libraryName, "ZeroSPU2 Playground"
# ifdef PCSX2_DEBUG
"-Debug"
# elif defined( ZEROSPU2_DEVBUILD )
"-Dev"
# endif
);
# endif
}
u32 CALLBACK PS2EgetLibType()
{
return PS2E_LT_SPU2;
}
char* CALLBACK PS2EgetLibName()
{
InitLibraryName();
return libraryName;
}
u32 CALLBACK PS2EgetLibVersion2(u32 type)
{
return (SPU2_MINOR<<24) | (SPU2_VERSION<<16) | (SPU2_REVISION<<8) | SPU2_BUILD;
}
void __Log(char *fmt, ...)
{
va_list list;
if (!conf.Log || spu2Log == NULL) return;
va_start(list, fmt);
vfprintf(spu2Log, fmt, list);
va_end(list);
}
void __LogToConsole(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
if (!conf.Log || spu2Log == NULL)
vfprintf(spu2Log, fmt, list);
printf("ZeroSPU2: ");
vprintf(fmt, list);
va_end(list);
}
void CALLBACK SPU2setSettingsDir(const char* dir)
{
s_strIniPath = (dir==NULL) ? "inis/" : dir;
}
void InitApi()
{
// This is a placeholder till there is actually some way to choose Apis. For the moment, just
// Modify this so it does whichever one you want to use.
#ifdef _WIN32
InitDSound();
#else
#if defined(ZEROSPU2_ALSA)
InitAlsa();
#elif defined(ZEROSPU2_OSS)
InitOSS();
#elif defined(ZEROSPU2_PORTAUDIO)
InitPortAudio();
#endif
#endif
}
s32 CALLBACK SPU2init()
{
LOG_CALLBACK("SPU2init()\n");
spu2Log = fopen("logs/spu2.txt", "w");
if (spu2Log) setvbuf(spu2Log, NULL, _IONBF, 0);
SPU2_LOG("Spu2 null version %d,%d\n",SPU2_REVISION,SPU2_BUILD);
SPU2_LOG("SPU2init\n");
#ifdef _WIN32
QueryPerformanceFrequency(&g_counterfreq);
#endif
InitApi();
spu2regs = (s8*)malloc(0x10000);
spu2mem = (u16*)malloc(0x200000); // 2Mb
memset(spu2regs, 0, 0x10000);
memset(spu2mem, 0, 0x200000);
if ((spu2mem == NULL) || (spu2regs == NULL))
{
SysMessage("Error allocating Memory\n");
return -1;
}
memset(dwEndChannel2, 0, sizeof(dwEndChannel2));
memset(dwNewChannel2, 0, sizeof(dwNewChannel2));
memset(iFMod, 0, sizeof(iFMod));
memset(s_buffers, 0, sizeof(s_buffers));
InitADSR();
memset(voices, 0, sizeof(voices));
// last 24 channels have higher mem offset
for (s32 i = 0; i < 24; ++i)
voices[i+24].memoffset = 0x400;
// init each channel
for (u32 i = 0; i < ArraySize(voices); ++i)
{
voices[i].init(i);
}
return 0;
}
s32 CALLBACK SPU2open(void *pDsp)
{
LOG_CALLBACK("SPU2open()\n");
#ifdef _WIN32
hWMain = pDsp == NULL ? NULL : *(HWND*)pDsp;
if (!IsWindow(hWMain))
hWMain=GetActiveWindow();
#endif
LoadConfig();
SPUCycles = SPUWorkerCycles = 0;
interrupt = 0;
SPUStartCycle[0] = SPUStartCycle[1] = 0;
SPUTargetCycle[0] = SPUTargetCycle[1] = 0;
s_nDropPacket = 0;
if ( conf.options & OPTION_TIMESTRETCH )
{
pSoundTouch = new soundtouch::SoundTouch();
pSoundTouch->setSampleRate(SAMPLE_RATE);
pSoundTouch->setChannels(2);
pSoundTouch->setTempoChange(0);
pSoundTouch->setSetting(SETTING_USE_QUICKSEEK, 0);
pSoundTouch->setSetting(SETTING_USE_AA_FILTER, 1);
}
//conf.Log = 1;
g_bPlaySound = !(conf.options&OPTION_MUTE);
if ( g_bPlaySound && SetupSound() != 0 )
{
SysMessage("ZeroSPU2: Failed to initialize sound");
g_bPlaySound = false;
}
if ( g_bPlaySound ) {
// initialize the audio buffers
for (u32 i = 0; i < ArraySize(s_pAudioBuffers); ++i)
{
s_pAudioBuffers[i].pbuf = (u8*)_aligned_malloc(4 * NS_TOTAL_SIZE, 16); // 4 bytes for each sample
s_pAudioBuffers[i].len = 0;
}
s_nCurBuffer = 0;
s_nQueuedBuffers = 0;
s_pCurOutput = (s16*)s_pAudioBuffers[0].pbuf;
assert( s_pCurOutput != NULL);
for (s32 i = 0; i < ArraySize(s_nDurations); ++i)
{
s_nDurations[i] = NSFRAMES*1000;
}
s_nTotalDuration = ArraySize(s_nDurations)*NSFRAMES*1000;
s_nCurDuration = 0;
// launch the thread
s_bThreadExit = false;
#ifdef _WIN32
s_threadSPU2 = CreateThread(NULL, 0, SPU2ThreadProc, NULL, 0, NULL);
if ( s_threadSPU2 == NULL )
{
return -1;
}
#else
if ( pthread_create(&s_threadSPU2, NULL, SPU2ThreadProc, NULL) != 0 )
{
SysMessage("ZeroSPU2: Failed to create spu2thread\n");
return -1;
}
#endif
}
g_nSpuInit = 1;
return 0;
}
void CALLBACK SPU2close()
{
LOG_CALLBACK("SPU2close()\n");
g_nSpuInit = 0;
if ( g_bPlaySound && !s_bThreadExit ) {
s_bThreadExit = true;
printf("ZeroSPU2: Waiting for thread... ");
#ifdef _WIN32
WaitForSingleObject(s_threadSPU2, INFINITE);
CloseHandle(s_threadSPU2); s_threadSPU2 = NULL;
#else
pthread_join(s_threadSPU2, NULL);
#endif
printf("done\n");
}
RemoveSound();
delete g_pWavRecord; g_pWavRecord = NULL;
delete pSoundTouch; pSoundTouch = NULL;
for (u32 i = 0; i < ArraySize(s_pAudioBuffers); ++i)
{
_aligned_free(s_pAudioBuffers[i].pbuf);
}
memset(s_pAudioBuffers, 0, sizeof(s_pAudioBuffers));
}
void CALLBACK SPU2shutdown()
{
LOG_CALLBACK("SPU2shutdown()\n");
free(spu2regs); spu2regs = NULL;
free(spu2mem); spu2mem = NULL;
if (spu2Log) fclose(spu2Log);
}
void CALLBACK SPU2async(u32 cycle)
{
//LOG_CALLBACK("SPU2async()\n");
SPUCycles += cycle;
if (interrupt & (1<<2))
{
if (SPUCycles - SPUStartCycle[1] >= SPUTargetCycle[1])
{
interrupt &= ~(1<<2);
#ifndef ENABLE_NEW_IOPDMA_SPU2
irqCallbackDMA7();
#endif
}
}
if (interrupt & (1<<1))
{
if (SPUCycles - SPUStartCycle[0] >= SPUTargetCycle[0])
{
interrupt &= ~(1<<1);
#ifndef ENABLE_NEW_IOPDMA_SPU2
irqCallbackDMA4();
#endif
}
}
if ( g_nSpuInit )
{
while((SPUCycles-SPUWorkerCycles > 0) && (CYCLES_PER_MS < (SPUCycles - SPUWorkerCycles)))
{
SPU2Worker();
SPUWorkerCycles += CYCLES_PER_MS;
}
}
else
SPUWorkerCycles = SPUCycles;
}
void InitADSR() // INIT ADSR
{
u32 r,rs,rd;
s32 i;
memset(RateTable,0,sizeof(u32)*160); // build the rate table according to Neill's rules (see at bottom of file)
r=3;rs=1;rd=0;
for (i=32;i<160;i++) // we start at pos 32 with the real values... everything before is 0
{
if (r<0x3FFFFFFF)
{
r+=rs;
rd++;
if (rd==5)
{
rd=1;
rs*=2;
}
}
if (r>0x3FFFFFFF) r=0x3FFFFFFF;
RateTable[i]=r;
}
}
s32 MixADSR(VOICE_PROCESSED* pvoice) // MIX ADSR
{
u32 rateadd[8] = { 0, 4, 6, 8, 9, 10, 11, 12 };
if (pvoice->bStop) // should be stopped:
{
if (pvoice->ADSRX.ReleaseModeExp) // do release
{
s32 temp = ((pvoice->ADSRX.EnvelopeVol>>28)&0x7);
pvoice->ADSRX.EnvelopeVol-=RateTable[(4*(pvoice->ADSRX.ReleaseRate^0x1F)) - 0x18 + rateadd[temp] + 32];
}
else
{
pvoice->ADSRX.EnvelopeVol-=RateTable[(4*(pvoice->ADSRX.ReleaseRate^0x1F)) - 0x0C + 32];
}
// bIgnoreLoop sets EnvelopeVol to 0 anyways, so we can use one if statement rather then two.
if ((pvoice->ADSRX.EnvelopeVol<0) || (pvoice->bIgnoreLoop == 0))
{
pvoice->ADSRX.EnvelopeVol=0;
pvoice->bOn=false;
pvoice->pStart= (u8*)(spu2mem+pvoice->iStartAddr);
pvoice->pLoop= (u8*)(spu2mem+pvoice->iStartAddr);
pvoice->pCurr= (u8*)(spu2mem+pvoice->iStartAddr);
pvoice->bStop = true;
pvoice->bIgnoreLoop = false;
//pvoice->bReverb=0;
//pvoice->bNoise=0;
}
pvoice->ADSRX.lVolume=pvoice->ADSRX.EnvelopeVol>>21;
return pvoice->ADSRX.lVolume;
}
else // not stopped yet?
{
s32 temp = ((pvoice->ADSRX.EnvelopeVol>>28)&0x7);
switch (pvoice->ADSRX.State)
{
case 0: // -> attack
if (pvoice->ADSRX.AttackModeExp)
{
if (pvoice->ADSRX.EnvelopeVol<0x60000000)
pvoice->ADSRX.EnvelopeVol += RateTable[(pvoice->ADSRX.AttackRate^0x7F) - 0x10 + 32];
else
pvoice->ADSRX.EnvelopeVol += RateTable[(pvoice->ADSRX.AttackRate^0x7F) - 0x18 + 32];
}
else
{
pvoice->ADSRX.EnvelopeVol += RateTable[(pvoice->ADSRX.AttackRate^0x7F) - 0x10 + 32];
}
if (pvoice->ADSRX.EnvelopeVol<0)
{
pvoice->ADSRX.EnvelopeVol=0x7FFFFFFF;
pvoice->ADSRX.State=1;
}
break;
case 1: // -> decay
pvoice->ADSRX.EnvelopeVol-=RateTable[(4*(pvoice->ADSRX.DecayRate^0x1F)) - 0x18+ rateadd[temp] + 32];
if (pvoice->ADSRX.EnvelopeVol<0) pvoice->ADSRX.EnvelopeVol=0;
if (((pvoice->ADSRX.EnvelopeVol>>27)&0xF) <= pvoice->ADSRX.SustainLevel)
pvoice->ADSRX.State=2;
break;
case 2: // -> sustain
if (pvoice->ADSRX.SustainIncrease)
{
if ((pvoice->ADSRX.SustainModeExp) && (pvoice->ADSRX.EnvelopeVol>=0x60000000))
pvoice->ADSRX.EnvelopeVol+=RateTable[(pvoice->ADSRX.SustainRate^0x7F) - 0x18 + 32];
else
pvoice->ADSRX.EnvelopeVol+=RateTable[(pvoice->ADSRX.SustainRate^0x7F) - 0x10 + 32];
if (pvoice->ADSRX.EnvelopeVol<0) pvoice->ADSRX.EnvelopeVol=0x7FFFFFFF;
}
else
{
if (pvoice->ADSRX.SustainModeExp)
pvoice->ADSRX.EnvelopeVol-=RateTable[((pvoice->ADSRX.SustainRate^0x7F)) - 0x1B +rateadd[temp] + 32];
else
pvoice->ADSRX.EnvelopeVol-=RateTable[((pvoice->ADSRX.SustainRate^0x7F)) - 0x0F + 32];
if (pvoice->ADSRX.EnvelopeVol<0) pvoice->ADSRX.EnvelopeVol=0;
}
break;
default:
// This should never happen.
return 0;
}
pvoice->ADSRX.lVolume=pvoice->ADSRX.EnvelopeVol>>21;
return pvoice->ADSRX.lVolume;
}
return 0;
}
void MixChannels(s32 channel)
{
// mix all channels
s32 left_vol, right_vol;
ADMA *Adma;
if (channel == 0)
{
Adma = &adma[0];
left_vol = REG_C0_BVOLL;
right_vol = REG_C0_BVOLR;
}
else
{
Adma = &adma[1];
left_vol = REG_C1_BVOLL;
right_vol = REG_C1_BVOLR;
}
if ((spu2mmix(channel) & 0xF0) && spu2admas(channel))
{
for (u32 ns = 0; ns < NSSIZE; ns++)
{
u16 left_reg = 0x2000 + c_offset(channel) + Adma->Index;
u16 right_reg = left_reg + 0x200;
if ((spu2mmix(channel) & 0x80))
s_buffers[ns][0] += (((s16*)spu2mem)[left_reg]*(s32)spu2Ru16(left_vol))>>16;
if ((spu2mmix(channel) & 0x40))
s_buffers[ns][1] += (((s16*)spu2mem)[right_reg]*(s32)spu2Ru16(right_vol))>>16;
Adma->Index +=1;
MemAddr[channel] += 4;
if (Adma->Index == 128 || Adma->Index == 384)
{
if (ADMASWrite(channel))
{
if (interrupt & (0x2 * (channel + 1)))
{
interrupt &= ~(0x2 * (channel + 1));
WARN_LOG("Stopping double interrupt DMA7\n");
}
#ifndef ENABLE_NEW_IOPDMA_SPU2
if (channel == 0)
irqCallbackDMA4();
else
irqCallbackDMA7();
#endif
}
if (channel == 1) Adma->Enabled = 2;
}
if (Adma->Index == 512)
{
if ( Adma->Enabled == 2 ) Adma->Enabled = 0;
Adma->Index = 0;
}
}
}
}
// resamples pStereoSamples
void ResampleLinear(s16* pStereoSamples, s32 oldsamples, s16* pNewSamples, s32 newsamples)
{
for (s32 i = 0; i < newsamples; ++i)
{
s32 io = i * oldsamples;
s32 old = io / newsamples;
s32 rem = io - old * newsamples;
old *= 2;
s32 newsampL = pStereoSamples[old] * (newsamples - rem) + pStereoSamples[old+2] * rem;
s32 newsampR = pStereoSamples[old+1] * (newsamples - rem) + pStereoSamples[old+3] * rem;
pNewSamples[2 * i] = newsampL / newsamples;
pNewSamples[2 * i + 1] = newsampR / newsamples;
}
}
static __aligned16 s16 s_ThreadBuffer[NS_TOTAL_SIZE * 2 * 5];
// SoundTouch's INTEGER system is broken these days, so we'll need this to do float conversions...
static __aligned16 float s_floatBuffer[NS_TOTAL_SIZE * 2 * 5];
static __forceinline u32 GetNewSamples(s32 nReadBuf)
{
u32 NewSamples = s_pAudioBuffers[nReadBuf].avgtime / 1000;
s32 bytesbuf = SoundGetBytesBuffered() * 10;
if (bytesbuf < MaxBuffer)
{
NewSamples += 1;
}
else if (bytesbuf > MaxBuffer * 5)
{
// check the current timestamp, if too far apart, speed up audio
//WARN_LOG("making faster %d\n", timeGetTime() - s_pAudioBuffers[nReadBuf].timestamp);
NewSamples = NewSamples - ((bytesbuf - 400000) / 100000);
}
if (s_nDropPacket > 0)
{
s_nDropPacket--;
NewSamples -= 1;
}
return min(NewSamples * NSSIZE, NS_TOTAL_SIZE * 3);
}
static __forceinline void ExtractSamples()
{
// extract 2*NSFRAMES ms at a time
s32 nOutSamples;
do
{
nOutSamples = pSoundTouch->receiveSamples(s_floatBuffer, NS_TOTAL_SIZE * 5);
if ( nOutSamples > 0 )
{
for( s32 sx=0; sx<nOutSamples*2; sx++ )
s_ThreadBuffer[sx] = (s16)(s_floatBuffer[sx]*65536.0f);
SoundFeedVoiceData((u8*)s_ThreadBuffer, nOutSamples * 4);
}
} while (nOutSamples != 0);
}
// communicates with the audio hardware
#ifdef _WIN32
DWORD WINAPI SPU2ThreadProc(LPVOID)
#else
void* SPU2ThreadProc(void* lpParam)
#endif
{
s32 nReadBuf = 0;
while (!s_bThreadExit)
{
if (!(conf.options&OPTION_REALTIME))
{
while(s_nQueuedBuffers< 3 && !s_bThreadExit)
{
//Sleeping
Sleep(1);
if (s_bThreadExit) return NULL;
}
while( SoundGetBytesBuffered() > 72000 )
{
//Bytes buffered
Sleep(1);
if (s_bThreadExit) return NULL;
}
}
else
{
while(s_nQueuedBuffers< 1 && !s_bThreadExit)
{
//Sleeping
Sleep(1);
}
}
if (conf.options & OPTION_TIMESTRETCH)
{
u32 NewSamples = GetNewSamples(nReadBuf);
s32 OldSamples = s_pAudioBuffers[nReadBuf].len / 4;
if ((nReadBuf & 3) == 0) // wow, this if statement makes the whole difference
{
//SPU2_LOG("OldSamples = %d; NewSamples = %d/n", OldSamples, NewSamples);
float percent = ((float)OldSamples/(float)NewSamples - 1.0f) * 100.0f;
pSoundTouch->setTempoChange(percent);
}
for( s32 sx = 0; sx < OldSamples * 2; sx++ )
s_floatBuffer[sx] = ((s16*)s_pAudioBuffers[nReadBuf].pbuf)[sx]/65536.0f;
pSoundTouch->putSamples(s_floatBuffer, OldSamples);
ExtractSamples();
}
else
{
SoundFeedVoiceData(s_pAudioBuffers[nReadBuf].pbuf, s_pAudioBuffers[nReadBuf].len);
}
// don't go to the next buffer unless there is more data buffered
nReadBuf = (nReadBuf+1)%ArraySize(s_pAudioBuffers);
InterlockedExchangeAdd((long*)&s_nQueuedBuffers, -1);
if ( s_bThreadExit ) break;
}
return NULL;
}
// turn channels on
void SoundOn(s32 start,s32 end,u16 val) // SOUND ON PSX COMAND
{
for (s32 ch=start;ch<end;ch++,val>>=1) // loop channels
{
if ((val&1) && voices[ch].pStart) // mmm... start has to be set before key on !?!
{
voices[ch].bNew=true;
voices[ch].bIgnoreLoop = false;
dwNewChannel2[ch/24]|=(1<<(ch%24)); // clear end channel bit
}
}
}
// turn channels off
void SoundOff(s32 start,s32 end,u16 val) // SOUND OFF PSX COMMAND
{
for (s32 ch=start;ch<end;ch++,val>>=1) // loop channels
{
if (val&1) voices[ch].bStop=true; // && s_chan[i].bOn) mmm...
}
}
void FModOn(s32 start,s32 end,u16 val) // FMOD ON PSX COMMAND
{
s32 ch;
for (ch=start;ch<end;ch++,val>>=1) // loop channels
{
if (val&1)
{ // -> fmod on/off
if (ch>0)
{
voices[ch].bFMod=1; // --> sound channel
voices[ch-1].bFMod=2; // --> freq channel
}
}
else
voices[ch].bFMod=0; // --> turn off fmod
}
}
void VolumeOn(s32 start,s32 end,u16 val,s32 iRight) // VOLUME ON PSX COMMAND
{
s32 ch;
for (ch=start;ch<end;ch++,val>>=1) // loop channels
{
if (val&1)
{ // -> reverb on/off
if (iRight)
voices[ch].bVolumeR = true;
else
voices[ch].bVolumeL = true;
}
else
{
if (iRight)
voices[ch].bVolumeR = false;
else
voices[ch].bVolumeL = false;
}
}
}
void CALLBACK SPU2write(u32 mem, u16 value)
{
LOG_CALLBACK("SPU2write()\n");
u32 spuaddr;
SPU2_LOG("SPU2 write mem %x value %x\n", mem, value);
assert(C0_SPUADDR() < 0x100000);
assert(C1_SPUADDR() < 0x100000);
spu2Ru16(mem) = value;
u32 r = mem & 0xffff;
// channel info
if ((r<0x0180) || (r>=0x0400 && r<0x0580)) // u32s are always >= 0.
{
s32 ch=0;
if (r >= 0x400)
ch = ((r - 0x400) >> 4) + 24;
else
ch = (r >> 4);
VOICE_PROCESSED* pvoice = &voices[ch];
switch(r & 0x0f)
{
case 0:
case 2:
pvoice->SetVolume(mem & 0x2);
break;
case 4:
{
s32 NP;
if (value> 0x3fff)
NP=0x3fff; // get pitch val
else
NP=value;
pvoice->pvoice->pitch = NP;
NP = (SAMPLE_RATE * NP) / 4096L; // calc frequency
if (NP<1) NP = 1; // some security
pvoice->iActFreq = NP; // store frequency
break;
}
case 6:
{
pvoice->ADSRX.AttackModeExp=(value&0x8000)?1:0;
pvoice->ADSRX.AttackRate = ((value>>8) & 0x007f);
pvoice->ADSRX.DecayRate = (((value>>4) & 0x000f));
pvoice->ADSRX.SustainLevel = (value & 0x000f);
break;
}
case 8:
pvoice->ADSRX.SustainModeExp = (value&0x8000)?1:0;
pvoice->ADSRX.SustainIncrease= (value&0x4000)?0:1;
pvoice->ADSRX.SustainRate = ((value>>6) & 0x007f);
pvoice->ADSRX.ReleaseModeExp = (value&0x0020)?1:0;
pvoice->ADSRX.ReleaseRate = ((value & 0x001f));
break;
}
return;
}
// more channel info
if ((r>=0x01c0 && r<0x02E0)||(r>=0x05c0 && r<0x06E0))
{
s32 ch=0;
u32 rx=r;
if (rx>=0x400)
{
ch=24;
rx-=0x400;
}
ch += ((rx-0x1c0)/12);
rx -= (ch%24)*12;
VOICE_PROCESSED* pvoice = &voices[ch];
switch(rx)
{
case REG_VA_SSA:
pvoice->iStartAddr=(((u32)value&0x3f)<<16)|(pvoice->iStartAddr&0xFFFF);
pvoice->pStart=(u8*)(spu2mem+pvoice->iStartAddr);
break;
case REG_VA_SSA + 2:
pvoice->iStartAddr=(pvoice->iStartAddr & 0x3f0000) | (value & 0xFFFF);
pvoice->pStart=(u8*)(spu2mem+pvoice->iStartAddr);
break;
case REG_VA_LSAX:
pvoice->iLoopAddr =(((u32)value&0x3f)<<16)|(pvoice->iLoopAddr&0xFFFF);
pvoice->pLoop=(u8*)(spu2mem+pvoice->iLoopAddr);
pvoice->bIgnoreLoop=pvoice->iLoopAddr>0;
break;
case REG_VA_LSAX + 2:
pvoice->iLoopAddr=(pvoice->iLoopAddr& 0x3f0000) | (value & 0xFFFF);
pvoice->pLoop=(u8*)(spu2mem+pvoice->iLoopAddr);
pvoice->bIgnoreLoop=pvoice->iLoopAddr>0;
break;
case REG_VA_NAX:
// unused... check if it gets written as well
pvoice->iNextAddr=(((u32)value&0x3f)<<16)|(pvoice->iNextAddr&0xFFFF);
break;
case REG_VA_NAX + 2:
// unused... check if it gets written as well
pvoice->iNextAddr=(pvoice->iNextAddr & 0x3f0000) | (value & 0xFFFF);
break;
}
return;
}
// process non-channel data
switch(mem & 0xffff)
{
case REG_C0_SPUDATA:
spuaddr = C0_SPUADDR();
spu2mem[spuaddr] = value;
spuaddr++;
if (spu2attr0.irq && (C0_IRQA() == spuaddr))
{
IRQINFO |= 4;
SPU2_LOG("SPU2write:C0_CPUDATA interrupt\n");
irqCallbackSPU2();
}
if (spuaddr>0xFFFFE) spuaddr = 0x2800;
C0_SPUADDR_SET(spuaddr);
spu2stat_clear_80(0);
spu2attr1.irq = 0;
break;
case REG_C1_SPUDATA:
spuaddr = C1_SPUADDR();
spu2mem[spuaddr] = value;
spuaddr++;
if (spu2attr1.irq && (C1_IRQA() == spuaddr))
{
IRQINFO |= 8;
SPU2_LOG("SPU2write:C1_CPUDATA interrupt\n");
irqCallbackSPU2();
}
if (spuaddr>0xFFFFE) spuaddr = 0x2800;
C1_SPUADDR_SET(spuaddr);
spu2stat_clear_80(1);
spu2attr0.irq = 0;
break;
case REG_C0_IRQA_HI:
case REG_C0_IRQA_LO:
pSpuIrq[0] = spu2mem + C0_IRQA();
break;
case REG_C1_IRQA_HI:
case REG_C1_IRQA_LO:
pSpuIrq[1] = spu2mem + C1_IRQA();
break;
case REG_C0_SPUADDR_HI:
case REG_C1_SPUADDR_HI:
spu2Ru16(mem) = value&0xf;
break;
case REG_C0_CTRL:
spu2Ru16(mem) = value;
// clear interrupt
if (!(value & 0x40)) IRQINFO &= ~0x4;
break;
case REG_C1_CTRL:
spu2Ru16(mem) = value;
// clear interrupt
if (!(value & 0x40)) IRQINFO &= ~0x8;
break;
// Could probably simplify
case REG_C0_SPUON1: SoundOn(0,16,value); break;
case REG_C0_SPUON2: SoundOn(16,24,value); break;
case REG_C1_SPUON1: SoundOn(24,40,value); break;
case REG_C1_SPUON2: SoundOn(40,48,value); break;
case REG_C0_SPUOFF1: SoundOff(0,16,value); break;
case REG_C0_SPUOFF2: SoundOff(16,24,value); break;
case REG_C1_SPUOFF1: SoundOff(24,40,value); break;
case REG_C1_SPUOFF2: SoundOff(40,48,value); break;
// According to manual all bits are cleared by writing an arbitary value
case REG_C0_END1: dwEndChannel2[0] &= 0x00ff0000; break;
case REG_C0_END2: dwEndChannel2[0] &= 0x0000ffff; break;
case REG_C1_END1: dwEndChannel2[1] &= 0x00ff0000; break;
case REG_C1_END2: dwEndChannel2[1] &= 0x0000ffff; break;
case REG_C0_FMOD1: FModOn(0,16,value); break;
case REG_C0_FMOD2: FModOn(16,24,value); break;
case REG_C1_FMOD1: FModOn(24,40,value); break;
case REG_C1_FMOD2: FModOn(40,48,value); break;
case REG_C0_VMIXL1: VolumeOn(0,16,value,0); break;
case REG_C0_VMIXL2: VolumeOn(16,24,value,0); break;
case REG_C1_VMIXL1: VolumeOn(24,40,value,0); break;
case REG_C1_VMIXL2: VolumeOn(40,48,value,0); break;
case REG_C0_VMIXR1: VolumeOn(0,16,value,1); break;
case REG_C0_VMIXR2: VolumeOn(16,24,value,1); break;
case REG_C1_VMIXR1: VolumeOn(24,40,value,1); break;
case REG_C1_VMIXR2: VolumeOn(40,48,value,1); break;
}
assert( C0_SPUADDR() < 0x100000);
assert( C1_SPUADDR() < 0x100000);
}
u16 CALLBACK SPU2read(u32 mem)
{
LOG_CALLBACK("SPU2read()\n");
u32 spuaddr;
u16 ret = 0;
u32 r = mem & 0xffff; // register
// channel info
// if the register is any of the regs before core 0, or is somewhere between core 0 and 1...
if ((r < 0x0180) || (r >= 0x0400 && r < 0x0580)) // u32s are always >= 0.
{
s32 ch = 0;
if (r >= 0x400)
ch=((r - 0x400) >> 4) + 24;
else
ch = (r >> 4);
VOICE_PROCESSED* pvoice = &voices[ch];
if ((r&0x0f) == 10) return (u16)(pvoice->ADSRX.EnvelopeVol >> 16);
}
if ((r>=REG_VA_SSA && r<REG_A_ESA) || (r>=0x05c0 && r<0x06E0)) // some channel info?
{
s32 ch = 0;
u32 rx = r;
if (rx >= 0x400)
{
ch = 24;
rx -= 0x400;
}
ch += ((rx - 0x1c0) / 12);
rx -= (ch % 24) * 12;
VOICE_PROCESSED* pvoice = &voices[ch];
switch(rx)
{
case REG_VA_SSA:
ret = ((((uptr)pvoice->pStart-(uptr)spu2mem)>>17)&0x3F);
break;
case REG_VA_SSA + 2:
ret = ((((uptr)pvoice->pStart-(uptr)spu2mem)>>1)&0xFFFF);
break;
case REG_VA_LSAX:
ret = ((((uptr)pvoice->pLoop-(uptr)spu2mem)>>17)&0x3F);
break;
case REG_VA_LSAX + 2:
ret = ((((uptr)pvoice->pLoop-(uptr)spu2mem)>>1)&0xFFFF);
break;
case REG_VA_NAX:
ret = ((((uptr)pvoice->pCurr-(uptr)spu2mem)>>17)&0x3F);
break;
case REG_VA_NAX + 2:
ret = ((((uptr)pvoice->pCurr-(uptr)spu2mem)>>1)&0xFFFF);
break;
}
SPU2_LOG("SPU2 channel read mem %x: %x\n", mem, ret);
return ret;
}
switch(mem & 0xffff)
{
case REG_C0_SPUDATA:
spuaddr = C0_SPUADDR();
ret =spu2mem[spuaddr];
spuaddr++;
if (spuaddr > 0xfffff) spuaddr=0;
C0_SPUADDR_SET(spuaddr);
break;
case REG_C1_SPUDATA:
spuaddr = C1_SPUADDR();
ret = spu2mem[spuaddr];
spuaddr++;
if (spuaddr > 0xfffff) spuaddr=0;
C1_SPUADDR_SET(spuaddr);
break;
case REG_C0_END1: ret = (dwEndChannel2[0]&0xffff); break;
case REG_C1_END1: ret = (dwEndChannel2[1]&0xffff); break;
case REG_C0_END2: ret = (dwEndChannel2[0]>>16); break;
case REG_C1_END2: ret = (dwEndChannel2[1]>>16); break;
case REG_IRQINFO:
ret = IRQINFO;
break;
default:
ret = spu2Ru16(mem);
}
SPU2_LOG("SPU2 read mem %x: %x\n", mem, ret);
return ret;
}
void CALLBACK SPU2WriteMemAddr(int core, u32 value)
{
LOG_CALLBACK("SPU2WriteMemAddr(%d, %d)\n", core, value);
MemAddr[core] = g_pDMABaseAddr + value;
}
u32 CALLBACK SPU2ReadMemAddr(int core)
{
LOG_CALLBACK("SPU2ReadMemAddr(%d)\n", core);
return MemAddr[core] - g_pDMABaseAddr;
}
void CALLBACK SPU2setDMABaseAddr(uptr baseaddr)
{
LOG_CALLBACK("SPU2setDMABaseAddr()\n");
g_pDMABaseAddr = baseaddr;
}
#ifdef ENABLE_NEW_IOPDMA_SPU2
void CALLBACK SPU2irqCallback(void (*SPU2callback)())
{
LOG_CALLBACK("SPU2irqCallback()\n");
irqCallbackSPU2 = SPU2callback;
}
#else
void CALLBACK SPU2irqCallback(void (*SPU2callback)(),void (*DMA4callback)(),void (*DMA7callback)())
{
LOG_CALLBACK("SPU2irqCallback()\n");
irqCallbackSPU2 = SPU2callback;
irqCallbackDMA4 = DMA4callback;
irqCallbackDMA7 = DMA7callback;
}
#endif
s32 CALLBACK SPU2test()
{
LOG_CALLBACK("SPU2test()\n");
return 0;
}
int CALLBACK SPU2setupRecording(int start, void* pData)
{
LOG_CALLBACK("SPU2setupRecording()\n");
if ( start )
{
conf.options |= OPTION_RECORDING;
WARN_LOG("ZeroSPU2: started recording at %s\n", RECORD_FILENAME);
}
else
{
conf.options &= ~OPTION_RECORDING;
WARN_LOG("ZeroSPU2: stopped recording\n");
}
return 1;
}
void save_data(freezeData *data)
{
SPU2freezeData *spud;
spud = (SPU2freezeData*)data->data;
spud->version = 0x70000002;
memcpy(spud->spu2regs, spu2regs, 0x10000);
memcpy(spud->spu2mem, spu2mem, 0x200000);
spud->nSpuIrq[0] = (s32)(pSpuIrq[0] - spu2mem);
spud->nSpuIrq[1] = (s32)(pSpuIrq[1] - spu2mem);
memcpy(spud->dwNewChannel2, dwNewChannel2, sizeof(dwNewChannel2));
memcpy(spud->dwEndChannel2, dwEndChannel2, sizeof(dwEndChannel2));
spud->dwNoiseVal = dwNoiseVal;
spud->interrupt = interrupt;
memcpy(spud->iFMod, iFMod, sizeof(iFMod));
memcpy(spud->MemAddr, MemAddr, sizeof(MemAddr));
spud->adma[0] = adma[0];
spud->adma[1] = adma[1];
spud->AdmaMemAddr[0] = (u32)((uptr)adma[0].MemAddr - g_pDMABaseAddr);
spud->AdmaMemAddr[1] = (u32)((uptr)adma[1].MemAddr - g_pDMABaseAddr);
spud->SPUCycles = SPUCycles;
spud->SPUWorkerCycles = SPUWorkerCycles;
memcpy(spud->SPUStartCycle, SPUStartCycle, sizeof(SPUStartCycle));
memcpy(spud->SPUTargetCycle, SPUTargetCycle, sizeof(SPUTargetCycle));
for (u32 i = 0; i < ArraySize(s_nDurations); ++i)
{
s_nDurations[i] = NSFRAMES*1000;
}
s_nTotalDuration = ArraySize(s_nDurations)*NSFRAMES*1000;
s_nCurDuration = 0;
spud->voicesize = SPU_VOICE_STATE_SIZE;
for (u32 i = 0; i < ArraySize(voices); ++i)
{
memcpy(&spud->voices[i], &voices[i], SPU_VOICE_STATE_SIZE);
spud->voices[i].pStart = (u8*)((uptr)voices[i].pStart-(uptr)spu2mem);
spud->voices[i].pLoop = (u8*)((uptr)voices[i].pLoop-(uptr)spu2mem);
spud->voices[i].pCurr = (u8*)((uptr)voices[i].pCurr-(uptr)spu2mem);
}
g_startcount=0xffffffff;
s_GlobalTimeStamp = 0;
s_nDropPacket = 0;
}
void load_data(freezeData *data)
{
SPU2freezeData *spud;
spud = (SPU2freezeData*)data->data;
if (spud->version != 0x70000002)
{
ERROR_LOG("zerospu2: Sound data either corrupted or from another plugin. Ignoring.\n");
return;
}
memcpy(spu2regs, spud->spu2regs, 0x10000);
memcpy(spu2mem, spud->spu2mem, 0x200000);
pSpuIrq[0] = spu2mem + spud->nSpuIrq[0];
pSpuIrq[1] = spu2mem + spud->nSpuIrq[1];
memcpy(dwNewChannel2, spud->dwNewChannel2, sizeof(dwNewChannel2));
memcpy(dwEndChannel2, spud->dwEndChannel2, sizeof(dwEndChannel2));
dwNoiseVal = spud->dwNoiseVal;
interrupt = spud->interrupt;
memcpy(iFMod, spud->iFMod, sizeof(iFMod));
memcpy(MemAddr, spud->MemAddr, sizeof(MemAddr));
adma[0] = spud->adma[0];
adma[1] = spud->adma[1];
adma[0].MemAddr = (u16*)(g_pDMABaseAddr+spud->AdmaMemAddr[0]);
adma[1].MemAddr = (u16*)(g_pDMABaseAddr+spud->AdmaMemAddr[1]);
SPUCycles = spud->SPUCycles;
SPUWorkerCycles = spud->SPUWorkerCycles;
memcpy(SPUStartCycle, spud->SPUStartCycle, sizeof(SPUStartCycle));
memcpy(SPUTargetCycle, spud->SPUTargetCycle, sizeof(SPUTargetCycle));
for (u32 i = 0; i < ArraySize(voices); ++i)
{
memcpy(&voices[i], &spud->voices[i], min((s32)SPU_VOICE_STATE_SIZE, spud->voicesize));
voices[i].pStart = (u8*)((uptr)spud->voices[i].pStart+(uptr)spu2mem);
voices[i].pLoop = (u8*)((uptr)spud->voices[i].pLoop+(uptr)spu2mem);
voices[i].pCurr = (u8*)((uptr)spud->voices[i].pCurr+(uptr)spu2mem);
}
s_GlobalTimeStamp = 0;
g_startcount = 0xffffffff;
for (u32 i = 0; i < ArraySize(s_nDurations); ++i)
{
s_nDurations[i] = NSFRAMES*1000;
}
s_nTotalDuration = ArraySize(s_nDurations)*NSFRAMES*1000;
s_nCurDuration = 0;
s_nQueuedBuffers = 0;
s_nDropPacket = 0;
}
s32 CALLBACK SPU2freeze(int mode, freezeData *data)
{
LOG_CALLBACK("SPU2freeze()\n");
assert( g_pDMABaseAddr != 0 );
switch (mode)
{
case FREEZE_LOAD:
load_data(data);
break;
case FREEZE_SAVE:
save_data(data);
break;
case FREEZE_SIZE:
data->size = sizeof(SPU2freezeData);
break;
default:
break;
}
return 0;
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
] | [
[
[
1,
1323
]
]
] |
35948874541d13bdfb714484b008905786f97ef8 | 28bce07d0d419ba0ba2cb0531a8f99b9e3547efd | /graphalterations.h | c9d06d0509d9a009f0100793b115a04611cc4397 | [] | no_license | kempj/Algernon | 0e1fb9fab56827fad17ee498918583c7be855745 | 42991b7980a4b19c3d5499c3b209cf906440ce21 | refs/heads/master | 2020-06-04T19:20:31.453071 | 2010-09-06T15:13:55 | 2010-09-06T15:13:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,347 | h | #ifndef GRAPH_ALTERATIONS
#define GRAPH_ALTERATIONS 0
#include <vector>
#include <string>
#include <algorithm>
#include "graph.h"
#define SIZE_LIMIT 75
/*
NOTE: The 'void* arg' is used to pass custom arguments to functions. It
can be either hardcoded into parts of the algorithm or used when library
is used in conjuction with programs other than algernon. Algernon ALWAYS
passes a NULL to 'arg' if it is auto generating arguments.
For values of a,b,c, or d that must be boolean, if any number other than
0 or 1 is used, the function should leave the graph unchanged. This will
for better pattern recognition.
If any value is unreasonable, the graph should reamin unchanged. This will
allow the program to discard bad choices.
*/
void RemoveSpike (m3sgraph &g, m3sgraph &ng,
long long unsigned int a,
long long unsigned int b,
long long unsigned int c,
long long unsigned int d, void* arg)
{
/*
a - Length of Spikes removed
b - Remove all Spikes 1 for no, 2 for yes
c - Number of Spikes To remove(if b is 1)
d - Unused
*/
ng = g;
//Testing to make sure the inputs are sane
if(b > 2)
return;
if(c > 5)
return;
if(a > 3)
return;
if(b == 2 && c > 1)
return;
if(d > 1)
return;
ng.PopulateNeighborlist();
std::vector<NeighborData*>* neighbors = ng.GetNeighborListing();
int spikeArray[a];
int indexOfLastVertex, j;
bool completeSpike = false;
for(int i = 0; i < ng.GetSize(); i++)
{
//this loop goes through all the vertices and the if statement
// selects all of the pendants.
if((*neighbors)[i]->neighbors == 1)
{
indexOfLastVertex = i;
//This loop traverses the graph as long as the degree is two, until
// it reaches the spike length a.
for(j = 0; j < a - 1; j++)
{
spikeArray[j] = indexOfLastVertex;
//This if, elseif is needed so the program doesn't go back and forth between 2 vertices
// if the order of the elements in the list isn't consistent.
if((*neighbors)[indexOfLastVertex]->list[0] != indexOfLastVertex && (*neighbors)[(*neighbors)[indexOfLastVertex]->list[0]]->neighbors == 2)
{
indexOfLastVertex = (*neighbors)[indexOfLastVertex]->list[0];
}
else if((*neighbors)[(*neighbors)[indexOfLastVertex]->list[1]]->neighbors == 2)
{
indexOfLastVertex = (*neighbors)[indexOfLastVertex]->list[1];
}
else
{
continue;
}
//if this if statement is entered, then a spike has been found
// and is going to be deleted
if(j == a-2)
{
for(int k = 0; k < a-1; k++)
{
ng.RemoveVertex(spikeArray[k]);
}
}
}
}
}
//for 1:n, where n is spikelength
//check if degree of neighbor is 2
//if vertex was a spike of length n, then delete all of the nodes traversed
// store the vertices in an array length n
//
//do this for every vertex.
return;
}
void SpikeHighest (m3sgraph &g, m3sgraph &ng,
long long unsigned int a,
long long unsigned int b,
long long unsigned int c,
long long unsigned int d, void* arg)
{
/*
a - rank (i.e. 1st highest, 2nd highest,...)
b - number of such vertices to spike (next highest if no more a)
c - number of spikes per target - capped at size of graph or 5 wichever is higher
d - length of spike (i.e. p1, p2,p3) - capped at 5 i.e.
*/
ng = g;
//Testing to make sure the inputs are sane
//and limiting the length of spikes to 5
//JK - replacing all of the 5s with 3s
if(a>g.GetSize()||b>g.GetSize()||d>3)
return;
if(g.GetSize()>=3 && c > g.GetSize())
return;
if(g.GetSize()<3 && c > 3)
return;
std::vector<long long unsigned int> seq = g.GetDegSeq();
if(seq.size()==0)
return;
std::vector<long long unsigned int> seq2 = seq;
std::sort(seq2.begin(), seq2.end()); //lowest value on lowest index
long long unsigned int targetdeg = seq2[seq2.size()-1];
int count = 0; //vertices spiked - MAX b
int dchanges = 1;
int index;
for(index = seq2.size()-1; index>=0 && dchanges<a; index--)
{
if(seq2[index]!=targetdeg)
{
targetdeg = seq2[index];
dchanges++;
}
}
if(index!=seq2.size()-1)//index was changed
index++; //this compensates for the last index-- done before exiting
/*NOTE: The following are not adjusted so that
identical graphs are not created. If any argument
values are adjusted inside to function we risk
generating identical graphs and afffecting data.
i.e. if instead of exactly b, what ever is available
is used, there will be successful runs with highers b
values resulting in the same graphs.*/
if(dchanges<a)
return; //a is too high for this graph
if(b-1 > index)
return; //b is too high for this graph
int spikeindex;
while(count<b)
{
for(int i=0; i<seq.size()&&count<b; i++)
{
if(seq[i]==targetdeg)//snce new vertices are padded indices are still valid
{
for(long long unsigned int spikes = 0; spikes < c; spikes++)
{
spikeindex = g.GetSize() + (count*c*d) + spikes*d;
ng.AddVertex();
//std::cout << "-" << ng.GetG6() <<std::endl;
ng.SetEdge(spikeindex,i,true);
//std::cout << "--" << ng.GetG6() <<std::endl;
for(unsigned int len = 1; len < d; len++)
{
ng.AddVertex();
ng.SetEdge(spikeindex+len,spikeindex+len-1,true);
}
}
count++;
}
}
targetdeg--; //go to next highest degree
}
if(ng.GetSize()>SIZE_LIMIT)
ng = g;
return;
}
void ClonesToHighest (m3sgraph &g, m3sgraph &ng,
long long unsigned int a,
long long unsigned int b,
long long unsigned int c,
long long unsigned int d, void* arg)
{
//NOTE: It is simple and faster to copy SpikeHighest and just
//add to it. This implmentation is only a test.
//Similar to spiking except attaches clones of the orginal graph
//to the end of the spikes, on the vertex that corolates to the
//current spiked vertex
/*
a - rank (i.e. 1st highest, 2nd highest,...)
b - number of such vertices to spike (next highest if no more a)
c - number of spikes per target - capped at size of graph or 5 wichever is higher
d - length of spike (i.e. p1, p2,p3) - capped at 5 i.e.
*/
ng = g;
//JK - replacing all of the 5s with 3s
if(a>g.GetSize()||b>g.GetSize()||d>3)
return;
if(g.GetSize()>=3 && c > g.GetSize())
return;
if(g.GetSize()<3 && c > 3)
return;
std::vector<long long unsigned int> seq = g.GetDegSeq();
if(seq.size()==0)
return;
std::vector<long long unsigned int> seq2 = seq;
std::sort(seq2.begin(), seq2.end()); //lowest value on lowest index
long long unsigned int targetdeg = seq2[seq2.size()-1];
int count = 0; //vertices spiked - MAX b
int dchanges = 1;
int index;
for(index=seq2.size()-1; index>=0&&dchanges<a;index--)
{
if(seq2[index]!=targetdeg)
{
targetdeg = seq2[index];
dchanges++;
}
}
if(index!=seq2.size()-1)//index was changed
index++; //this compensates for the last index-- done before exiting
if(dchanges<a)
return; //a is too high for this graph
if(b-1 > index)
return; //b is too high for this graph
int spikeindex;
long long unsigned int gsize = g.GetSize();
while(count<b)
{
for(int i=0; i<seq.size()&&count<b; i++)
{
if(seq[i]==targetdeg)//since new vertices are padded indices are still valid
{
for(long long unsigned int spikes = 0; spikes < c; spikes++)
{
spikeindex = g.GetSize() + (count*c*(d+gsize-1)) + spikes*(d+gsize-1);
ng.AddVertex();
//std::cout << "-" << ng.GetG6() <<std::endl;
ng.SetEdge(spikeindex,i,true);
//std::cout << "--" << ng.GetG6() <<std::endl;
for(unsigned int len = 1; len < d; len++)
{
ng.AddVertex();
ng.SetEdge(spikeindex+len,spikeindex+len-1,true);
}
long long unsigned int tip = ng.GetSize()-1; //tip of spike
//////////////////////////////
bool isShort = false; //spike is short
if(tip == g.GetSize()+count*(d+g.GetSize()-1))
{
ng.SetEdge(i,tip,false);
isShort = true;
}
else
{
ng.SetEdge(tip-1,tip,false);
}
/////////////////////////////
for(long long unsigned int v = 0; v < gsize-1; v++)
{
ng.AddVertex();
}
/////////////////////////////
if(isShort)
{
ng.SetEdge(i,i+g.GetSize()+count*(d+g.GetSize()-1),true);
}
else
{
ng.SetEdge(tip-1,tip+i,true);
}
/////////////////////////////
for(long long unsigned int v = 0; v < gsize; v++)
{
for(long long unsigned int u = 0; u < v; u++)
{
if(g.GetEdge(v,u))
{
//ng.SetEdge(tip+((v+i)%gsize),tip+((i+u)%gsize),true);
ng.SetEdge(tip+v,tip+u,true);
}
}
}
}
count++;
}
}
targetdeg--; //go to next highest degree
}
if(ng.GetSize()>SIZE_LIMIT)
ng = g;
return;
}
void CliqueHighest (m3sgraph &g, m3sgraph &ng,
long long unsigned int a,
long long unsigned int b,
long long unsigned int c,
long long unsigned int d, void* arg)
{
/*
a - rank (i.e. 1st highest, 2nd highest,...)
b - number of such vertices (in addition to first) to form a clique with (next highest if no more a)
c - maximum number of cliques to form (currently unused)
d - ?????.
*/
ng = g;
if(a>g.GetSize()||b>g.GetSize()-1||d>1)
return; //imposible rank or impossible # of vertices to include or
//d is invalid so anything other than default value 1 is avoided
if(c>1)//currently unused
return;
std::vector<long long unsigned int> seq = g.GetDegSeq();
if(seq.size()==0)
return;
std::vector<long long unsigned int> seq2 = seq;
std::sort(seq2.begin(), seq2.end()); //lowest value on lowest index
long long unsigned int targetdeg = seq2[seq2.size()-1];
int count = 0; //vertices spiked - MAX b
int rank = 1; //first highest
int index;
for(index=seq2.size()-1; index>=0 && rank<a; index--)
{
if(seq2[index]!=targetdeg)
{
targetdeg = seq2[index];
rank++;
}
}
if(index!=seq2.size()-1)//index was changed
index++; //this compensates for the last index-- done before exiting
/*NOTE: The following are not adjusted so that
identical graphs are not created. If any argument
values are adjusted inside to function we risk
generating identical graphs and afffecting data.
i.e. if instead of exactly b, what ever is available
is used, there will be successful runs with highers b
values resulting in the same graphs.*/
if(rank<a)
return; //a is too high for this graph
if(b > index)
return; //b is too high for this graph
//index is the index of target deg in seq2
bool exists = false;
std::vector<int> targetlist;
for(int j=seq.size()-1; j>=0; j--) //adding first vertex
{
if(seq[j]==seq2[index])
{
targetlist.push_back(j);
index--;
j=-1;
}
}
while(targetlist.size()<=b)
{
for(int j=seq.size()-1; j>=0; j--)
{
if((seq[j]==seq2[index]))
{
for(int k=targetlist.size()-1; k>=0 && !exists; k--)
{
if(targetlist[k]==j)
exists = true;
}
if(!exists)
{
targetlist.push_back(j);
index--;
if(targetlist.size()==b+1)
j=-1;
}
exists = false;
}
}
}
for(int i=targetlist.size()-1; i>0; i--)
{
for(int j=i-1;j>=0;j--)
{
ng.SetEdge(i,j,true);
}
}
if(ng.GetSize()>SIZE_LIMIT)
ng = g;
return;
}
//********************************************
struct AlterationDef
{
std::string name;
void (*ptr) (m3sgraph &g, m3sgraph &ng,
long long unsigned int a,
long long unsigned int b,
long long unsigned int c,
long long unsigned int d, void* arg);
};
class AlterationLib
{
private:
std::vector<AlterationDef> list;
public:
AlterationLib();
int GetListSize();
std::string GetAlterationName(int index);
void DoAlteration(std::string name,
m3sgraph &graph,m3sgraph &ng,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
void DoAlteration(int s,
m3sgraph &graph,m3sgraph &ng,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
m3sgraph DoAlteration(std::string name,
m3sgraph &graph,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
m3sgraph DoAlteration(int s,
m3sgraph &graph,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
std::string DoAlteration(std::string name,
std::string g6,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
std::string DoAlteration(int s,
std::string g6,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr = NULL);
};
void AlterationLib::DoAlteration(std::string name,
m3sgraph &graph,m3sgraph &ng,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr)
{
for(int i=list.size()-1; i>=0; i--)
{
if(list[i].name==name)
{
list[i].ptr(graph,ng,a,b,c,d,ptr);
return;
}
}
}
void AlterationLib::DoAlteration(int s,
m3sgraph &graph,m3sgraph &ng,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr)
{
list[s].ptr(graph,ng,a,b,c,d,ptr);
}
m3sgraph AlterationLib::DoAlteration(std::string name,
m3sgraph &graph,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr)
{
m3sgraph ng;
DoAlteration(name,graph,ng,a,b,c,d,ptr);
return ng;
}
m3sgraph AlterationLib::DoAlteration(int s,
m3sgraph &graph,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr)
{
m3sgraph ng;
DoAlteration(s,graph,ng,a,b,c,d,ptr);
return ng;
}
std::string AlterationLib::DoAlteration(std::string name,
std::string g6,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr )
{
m3sgraph graph,ng;
graph.SetGraph(g6.c_str());
DoAlteration(name,graph,ng,a,b,c,d,ptr);
return ng.GetG6();
}
std::string AlterationLib::DoAlteration(int s,
std::string g6,
long long unsigned int a, long long unsigned int b,
long long unsigned int c, long long unsigned int d,
void* ptr)
{
m3sgraph graph,ng;
graph.SetGraph(g6.c_str());
DoAlteration(s,graph,ng,a,b,c,d,ptr);
return ng.GetG6();
}
int AlterationLib::GetListSize()
{
return list.size();
}
std::string AlterationLib::GetAlterationName(int index)
{
return list[index].name;
}
//********************************************
// Add pointer to the library
// at the end of the constructor below
//********************************************
AlterationLib::AlterationLib()
{
AlterationDef tmp;
tmp.name = "SpikeHighest";
tmp.ptr = SpikeHighest;
list.push_back(tmp);
tmp.name = "ClonesToHighest";
tmp.ptr = ClonesToHighest;
list.push_back(tmp);
tmp.name = "CliqueHighest";
tmp.ptr = CliqueHighest;
list.push_back(tmp);
tmp.name = "RemoveSpike";
tmp.ptr = RemoveSpike;
list.push_back(tmp);
}
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
8
],
[
10,
25
],
[
109,
125
],
[
128,
128
],
[
130,
130
],
[
132,
202
],
[
204,
224
],
[
227,
227
],
[
229,
229
],
[
231,
594
],
[
598,
600
]
],
[
[
9,
9
],
[
26,
108
],
[
126,
127
],
[
129,
129
],
[
131,
131
],
[
203,
203
],
[
225,
226
],
[
228,
228
],
[
230,
230
],
[
595,
597
]
]
] |
c3f4f1ef0e5d51552b6873b9d6d08fed56273a82 | 95a3e8914ddc6be5098ff5bc380305f3c5bcecb2 | /src/FusionForever_lib/Starfield.cpp | 872dd1ee6a96b153b6810a9cd1e6d086d7cbe7ce | [] | no_license | danishcake/FusionForever | 8fc3b1a33ac47177666e6ada9d9d19df9fc13784 | 186d1426fe6b3732a49dfc8b60eb946d62aa0e3b | refs/heads/master | 2016-09-05T16:16:02.040635 | 2010-04-24T11:05:10 | 2010-04-24T11:05:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,664 | cpp | #include "StdAfx.h"
#include "Starfield.h"
#include "Camera.h"
#include "Datastore.h"
static const float SF_PARALAX1 = 0.7f;
static const float SF_GRIDSIZE = 750.0f;
Starfield::Starfield()
{
for(int i = 0; i < SF_MAX_POINTS; i++)
{
stars_[i] = Vector3f(Random::RandomRange(0, SF_GRIDSIZE),
Random::RandomRange(0, SF_GRIDSIZE), 0);
}
}
Starfield::~Starfield(void)
{
}
void Starfield::DrawStarfield(Vector3f _position)
{
int max_index = static_cast<int>(SF_MAX_POINTS / pow(Camera::Instance().GetWidth() / SF_GRIDSIZE,2.0f));
if(max_index > SF_MAX_POINTS)
max_index = SF_MAX_POINTS;
if(max_index < 50)
max_index = 50;
glPushMatrix();
glColor3f(0.5f,0.5f,0.5f);
glPointSize(1);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, stars_);
glTranslatef(_position.x, _position.y, 0);
Vector3f offset = Vector3f(-fmodf(SF_PARALAX1 * _position.x, SF_GRIDSIZE),
-fmodf(SF_PARALAX1 * _position.y, SF_GRIDSIZE),
0);
glTranslatef(offset.x, offset.y,0);
int x_minus_times = static_cast<int>(((Camera::Instance().GetWidth() / 2.0f) / SF_GRIDSIZE) + 2) + 1;
int y_minus_times = static_cast<int>(((Camera::Instance().GetHeight() / 2.0f) / SF_GRIDSIZE) + 2) + 1;
float left = -SF_GRIDSIZE * x_minus_times;
for(int x = 0; x < x_minus_times * 2; x++)
{
float top = -SF_GRIDSIZE * y_minus_times;
for(int y = 0; y < y_minus_times * 2; y++)
{
glPushMatrix();
glTranslatef(left, top, 0);
glDrawArrays(GL_POINTS, 0, max_index);
glPopMatrix();
top += SF_GRIDSIZE;
}
left += SF_GRIDSIZE;
}
glPointSize(1);
glPopMatrix();
}
| [
"Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7",
"EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7"
] | [
[
[
1,
5
],
[
8,
22
],
[
24,
36
],
[
40,
43
],
[
45,
62
]
],
[
[
6,
7
],
[
23,
23
],
[
37,
39
],
[
44,
44
]
]
] |
911e6f1df78fa43f337a88b644619c69dd4214b7 | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /src/xmlwrapper.cpp | 4153c7a56f1fa7a3a0856a9f00eb58a4c5b9fa02 | [] | no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,388 | cpp | #include "xmlwrapper.h"
Ogre::Vector3 OgreXmlElement::AttributeAsVector3(Ogre::String attrName,Ogre::Vector3 def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseVector3(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
Ogre::Real OgreXmlElement::AttributeAsReal(Ogre::String attrName,Ogre::Real def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseReal(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
Ogre::String OgreXmlElement::AttributeAsString(Ogre::String attrName,Ogre::String def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
return Ogre::String(Attribute(attrName)->c_str());
}
int OgreXmlElement::AttributeAsInt(Ogre::String attrName,int def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseInt(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
unsigned int OgreXmlElement::AttributeAsUnsignedInt(Ogre::String attrName,unsigned int def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseUnsignedInt(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
Ogre::Quaternion OgreXmlElement::AttributeAsQuaternion(Ogre::String attrName,Ogre::Quaternion def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseQuaternion(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
Ogre::ColourValue OgreXmlElement::AttributeAsColour(Ogre::String attrName,Ogre::ColourValue def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseColourValue(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
bool OgreXmlElement::AttributeAsBool(Ogre::String attrName,bool def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseBool(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
Ogre::Radian OgreXmlElement::AttributeAsRadian(Ogre::String attrName,Ogre::Radian def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseAngle(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
long OgreXmlElement::AttributeAsLong(Ogre::String attrName,long def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseLong(Attribute(attrName)->c_str());
}
else
{
return def;
}
}
unsigned long OgreXmlElement::AttributeAsUnsignedLong(Ogre::String attrName,unsigned long def, bool toLowerCase)
{
if(toLowerCase)
Ogre::StringUtil::toLowerCase(attrName);
if(Attribute(attrName))
{
return Ogre::StringConverter::parseUnsignedLong(Attribute(attrName)->c_str());
}
else
{
return def;
}
} | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
] | [
[
[
1,
142
]
]
] |
1e46b3dfeac051c87948cddea1c400e9fba7d06c | fa134e5f64c51ccc1c2cac9b9cb0186036e41563 | /GT/Terrain.cpp | 2604e18d87a85c9be6e10298fb601e60c9fd9889 | [] | no_license | dlsyaim/gradthes | 70b626f08c5d64a1d19edc46d67637d9766437a6 | db6ba305cca09f273e99febda4a8347816429700 | refs/heads/master | 2016-08-11T10:44:45.165199 | 2010-07-19T05:44:40 | 2010-07-19T05:44:40 | 36,058,688 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,145 | cpp | #include "StdAfx.h"
#include <windows.h>
#include <gl/glut.h>
#include <vector>
#include "Terrain.h"
#include "Texture.h"
Terrain::Terrain(void)
{
terrainTex = new Texture();
pHeightMap = new BYTE[MAP_SIZE * MAP_SIZE];
}
Terrain::~Terrain(void)
{
if (terrainTex)
delete terrainTex;
if (pHeightMap)
delete[] pHeightMap;
}
void Terrain::LoadRawFile(LPSTR strName)
{
FILE *pFile = NULL;
pFile = fopen(strName, "rb"); // Open the file in binary mode.
if (pFile == NULL) // Check if the file is existing and opened.
{
MessageBox(NULL, "Failed to open the height map file!\nCan't open the height map.", "Error", MB_OK);
return;
}
fread( pHeightMap, 1, MAP_SIZE * MAP_SIZE, pFile ); // Load .raw file into pHeightMap array
if (ferror(pFile))
{
MessageBox(NULL, "Error reading terrain data!\nCan't get terrain data.", "Error", MB_OK);
}
fclose(pFile);
}
void Terrain::RenderHeightMap(void)
{
int X = 0, Y = 0; // The 2-D coordinates of points
int x, y, z; // The 3-D coordinates of points
BOOL bSwitchSides = FALSE;
if (!pHeightMap) // Check the pHeightMap
{
return;
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glBindTexture(GL_TEXTURE_2D, terrainTex->getTexId());
glBegin(GL_TRIANGLE_STRIP);
for (X = 0; X <= MAP_SIZE; X += STEP_SIZE)
{
if (bSwitchSides) // Check whether read the height map from the opposite direction or not
{
// Because we need to make the triangle to be ____, we must specify the (X, y, Y) first.
// Render the terrain in the current X coordinate
for (Y = MAP_SIZE; Y >= 0; Y -= STEP_SIZE)
{
// Get the lower-left point's (X, Y, Z)
x = X;
y = Height(X, Y);
z = Y;
SetTextureCoord((float)x, (float)z);
glVertex3i(x, y, z);
// Get the lower-right point's (X, Y, Z)
x = X + STEP_SIZE;
y = Height(X + STEP_SIZE, Y);
z = Y;
SetTextureCoord((float)x, (float)z);
glVertex3i(x, y, z);
}
} else {
for (Y = 0; Y <= MAP_SIZE; Y += STEP_SIZE)
{
// Because we need to make the triangle to be ____, we must specify the (X + STEP_SIZE, y, Y) first.
// Get the upper-right point's (X, Y, Z)
x = X + STEP_SIZE;
y = Height(X + STEP_SIZE, Y);
z = Y;
SetTextureCoord((float)x, (float)z);
glVertex3i(x, y, z);
// Get the upper-left point's (X, Y, Z)
x = X;
y = Height(X, Y);
z = Y;
SetTextureCoord((float)x, (float)z);
glVertex3i(x, y, z);
}
}
bSwitchSides = !bSwitchSides; // Change the direction of rendering
}
glEnd();
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
}
int Terrain::Height(int X, int Y)
{
int x = X % MAP_SIZE;
int y = Y % MAP_SIZE;
if (!pHeightMap)
return 0;
return pHeightMap[x + y * MAP_SIZE];
}
void Terrain::SetTextureCoord(float x, float z)
{
glTexCoord2f((float) x / (float) MAP_SIZE, - (float) z / (float) MAP_SIZE);
} | [
"[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6"
] | [
[
[
1,
128
]
]
] |
709cf200692b295995d73e210d5b2290929e8030 | 8ad5d6836fe4ad3349929802513272db86d15bc3 | /lib/Spin/Handlers/HTTPRequestHandler.cpp | b92038f70dcc2e50817a819412c05924f7973fd7 | [] | no_license | blytkerchan/arachnida | 90a72c27f0c650a6fbde497896ef32186c0219e5 | 468f4ef6c35452de3ca026af42b8eedcef6e4756 | refs/heads/master | 2021-01-10T21:43:51.505486 | 2010-03-12T04:02:19 | 2010-03-12T04:02:42 | 2,203,393 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | #include "HTTPRequestHandler.h"
namespace Spin
{
namespace Details
{
struct Request;
}
namespace Handlers
{
void HTTPRequestHandler::handle(const boost::shared_ptr< Details::Request > & request)
{
{
boost::mutex::scoped_lock lock(requests_lock_);
requests_.push_back(request);
}
requests_cond_.notify_one();
}
boost::shared_ptr< Details::Request > HTTPRequestHandler::getNextRequest()
{
boost::mutex::scoped_lock lock(requests_lock_);
while (requests_.empty())
requests_cond_.wait(lock);
boost::shared_ptr< Details::Request > retval(requests_.front());
requests_.pop_front();
return retval;
}
}
}
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
390e03668b675239c0a9c503aa9ade4d29054a32 | 5d3c1be292f6153480f3a372befea4172c683180 | /trunk/ProxyLauncher/Hardware Proxies/iStuff Mobile/Symbian/iStuffMobile/inc/iStuffMobileDocument.h | 13417642535d96f881dc42aca1bfdd38e28d50aa | [
"Artistic-2.0"
] | permissive | BackupTheBerlios/istuff-svn | 5f47aa73dd74ecf5c55f83765a5c50daa28fa508 | d0bb9963b899259695553ccd2b01b35be5fb83db | refs/heads/master | 2016-09-06T04:54:24.129060 | 2008-05-02T22:33:26 | 2008-05-02T22:33:26 | 40,820,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | h | /*
* Copyright (c) 2006
* Media informatics Department
* RWTH Aachen Germany
* http://media.informatik.rwth-aachen.de
*
* Redistribution and use of the source code and binary, with or without
* modification, are permitted under OPI Artistic License
* (http://www.opensource.org/licenses/artistic-license.php) provided that
* the source code retains the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Faraz Ahmed Memon
* Tico Ballagas
*
* Version: 1.0
*/
#ifndef ISTUFFMOBILEDOCUMENT_H
#define ISTUFFMOBILEDOCUMENT_H
#include <akndoc.h>
class CEikAppUi;
class CiStuffMobileDocument : public CAknDocument
{
public:
static CiStuffMobileDocument* NewL(CEikApplication& aApp);
virtual ~CiStuffMobileDocument();
private:
CiStuffMobileDocument(CEikApplication& aApp);
void ConstructL();
CEikAppUi* CreateAppUiL();
};
#endif | [
"hemig@2a53cb5c-8ff1-0310-8b75-b3ec22923d26"
] | [
[
[
1,
52
]
]
] |
b00ab970b6df3e1cdcdb99b0e0f22e3d57b57d58 | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleReflection/TEditAssetWindow.cpp | 53fbd25763942924b4bc62cc5b821b2705cd56ef | [] | no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | cpp | #include "TEditAssetWindow.h"
#include "TLReflection.h"
TLReflection::TEditAssetWindow::TEditAssetWindow(const TTypedRef& Asset) :
m_Asset ( Asset )
{
}
| [
"[email protected]"
] | [
[
[
1,
10
]
]
] |
affe446c42ec9871bad6e190a96558b03abce161 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kserver/cell/TypeDispatcher.h | 732b259c075d7a0aadad90af0fc6ccac4a7bc45c | [] | no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,323 | h | #pragma once
#include <kcore/sys/Tick.h>
#include <kcore/sys/FineTick.h>
#include <kserver/cell/Action.h>
#include <kserver/db/Transaction.h>
#include <hash_map>
namespace gk {
/**
* @class TypeDispatcher
*
* @brief Dispatches message or processing power to actions
*
* When message is arrived,
*
* [1] Hash map is searched for the type
* [2] If an Action is found, then the message is dispatched to the action
* [3] If an Action is finished, it is checked and cleaned up later in Run()
*/
class TypeDispatcher
{
public:
TypeDispatcher();
~TypeDispatcher();
/**
* @brief Initialize
*/
bool Init();
/**
* @brief Run periodically
*/
void Run();
/**
* @brief Subscribe for context
*
* @param type The type to handle
* @param action The action to dispatch
*/
void Subscribe( ushort type, ActionPtr action );
/**
* @brief Dispatch Message
*
* @param m The message to dispatch
*/
void Dispatch( MessagePtr m );
/**
* @brief Clean up
*/
void Fini();
private:
typedef std::vector<ActionPtr> ActionList;
typedef stdext::hash_map<uint, ActionList> ActionMap;
void processTick();
void processCleanup();
private:
ActionMap m_actions;
Tick m_tickCleanup;
Tick m_tick;
};
} // gk
| [
"darkface@localhost"
] | [
[
[
1,
73
]
]
] |
61de8a8a366a9f45c081405e97d8097846ad0d22 | c231342d4ae97bd2ff231079ca7fe33958bfd1f9 | /CGE/UI/Label.cpp | 06372efd132651c262bd79976fc25824042f1608 | [] | no_license | travisbhartwell/cyborus-game-engine | 121007acb012cebc9620b45abca5985cab56ed9e | e83d68ae34d17e537dde7739aec6f71677904048 | refs/heads/master | 2020-12-01T01:14:49.228467 | 2011-12-23T18:05:58 | 2011-12-23T18:05:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,699 | cpp | #include "Label.h"
namespace CGE
{
Label::Label(const Image& inImage, float inWidth, float inHeight)
{
mTexture.loadImage(inImage);
const float Min = 0.1f;
if (inWidth < Min) inWidth = Min;
if (inHeight < Min) inHeight = Min;
mRadiusX = inWidth / 2.0f;
mRadiusY = inHeight / 2.0f;
mClusterVBO.mount(mVertexVBO, 0);
mClusterVBO.mount(mTextureVBO, 1);
GLfloat vertices[4 * 2];
GLfloat* vertex = vertices;
GLfloat texCoords[4 * 2];
GLfloat* texCoord = texCoords;
*vertex++ = mRadiusX;
*vertex++ = mRadiusY;
*texCoord++ = 1.0f;
*texCoord++ = 0.0f;
*vertex++ = mRadiusX;
*vertex++ = -mRadiusY;
*texCoord++ = 1.0f;
*texCoord++ = 1.0f;
*vertex++ = -mRadiusX;
*vertex++ = -mRadiusY;
*texCoord++ = 0.0f;
*texCoord++ = 1.0f;
*vertex++ = -mRadiusX;
*vertex++ = mRadiusY;
*texCoord++ = 0.0f;
*texCoord++ = 0.0f;
mVertexVBO.loadData(vertices, 4, 2);
mTextureVBO.loadData(texCoords, 4, 2);
setPosition(0.0f, 0.0f);
}
Label::~Label()
{
//dtor
}
/** @brief display
*
* @todo: document this function
*/
void Label::display()
{
mTexture.bind();
mClusterVBO.display(GL_TRIANGLE_FAN, 0, 4);
}
/** @brief setPosition
*
* @todo: document this function
*/
void Label::setPosition(float inX, float inY)
{
mX = inX;
mY = inY;
mTransform.loadIdentity();
mTransform.translate(mX, mY, 0.0f);
}
}
| [
"[email protected]"
] | [
[
[
1,
79
]
]
] |
56eed854f0dd900bd53de7b0df1f2798e5f58bc4 | 7a2144d11ce57a5286381d91d71b15592de3e7eb | /glm/test/core/core_type_mat2x4.cpp | 88fa5cabf40b529977849994b4b027cec3d30c79 | [
"MIT"
] | permissive | ryanschmitty/RDSTracer | 25449db75d2caf2bdbed317f9fa271bb8deda67c | 19fddc911c7d193e055ff697c15d76b83ce0b33a | refs/heads/master | 2021-01-10T20:38:23.050262 | 2011-09-20T23:19:46 | 2011-09-20T23:19:46 | 1,627,984 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2008-08-31
// Updated : 2008-08-31
// Licence : This source is under MIT License
// File : test/core/type_mat2x4.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/glm.hpp>
static bool test_operators()
{
glm::mat2x4 m(1.0f);
glm::vec2 u(1.0f);
glm::vec4 v(1.0f);
float x = 1.0f;
glm::vec4 a = m * u;
glm::vec2 b = v * m;
glm::mat2x4 n = x / m;
glm::mat2x4 o = m / x;
glm::mat2x4 p = x * m;
glm::mat2x4 q = m * x;
bool R = m != q;
bool S = m == m;
return true;
}
int main()
{
bool Result = true;
Result = Result && test_operators();
assert(Result);
return Result;
}
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
e6a78ea7804851ba772646d2c536c031c0f43bf4 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKitTools/QtTestBrowser/webview.h | c2287c11ed55e238c467f03850d8d2f0188f47ca | [] | no_license | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,287 | h | /*
* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2009 Girish Ramakrishnan <[email protected]>
* Copyright (C) 2006 George Staikos <[email protected]>
* Copyright (C) 2006 Dirk Mueller <[email protected]>
* Copyright (C) 2006 Zack Rusin <[email protected]>
* Copyright (C) 2006 Simon Hausmann <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef webview_h
#define webview_h
#include "fpstimer.h"
#include "webpage.h"
#include <qwebview.h>
#include <qgraphicswebview.h>
#include <QGraphicsView>
#include <QGraphicsWidget>
#include <QTime>
class QStateMachine;
class WebViewTraditional : public QWebView {
Q_OBJECT
public:
WebViewTraditional(QWidget* parent) : QWebView(parent) {}
protected:
virtual void contextMenuEvent(QContextMenuEvent*);
virtual void mousePressEvent(QMouseEvent*);
};
class GraphicsWebView : public QGraphicsWebView {
Q_OBJECT
public:
GraphicsWebView(QGraphicsItem* parent = 0) : QGraphicsWebView(parent) {};
protected:
virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent*);
virtual void mousePressEvent(QGraphicsSceneMouseEvent*);
};
class WebViewGraphicsBased : public QGraphicsView {
Q_OBJECT
Q_PROPERTY(qreal yRotation READ yRotation WRITE setYRotation)
public:
WebViewGraphicsBased(QWidget* parent);
void setPage(QWebPage* page);
void setItemCacheMode(QGraphicsItem::CacheMode mode) { m_item->setCacheMode(mode); }
QGraphicsItem::CacheMode itemCacheMode() { return m_item->cacheMode(); }
void setFrameRateMeasurementEnabled(bool enabled);
bool frameRateMeasurementEnabled() const { return m_measureFps; }
virtual void resizeEvent(QResizeEvent*);
virtual void paintEvent(QPaintEvent* event);
void setResizesToContents(bool b);
bool resizesToContents() const { return m_resizesToContents; }
void setYRotation(qreal angle)
{
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
QRectF r = m_item->boundingRect();
m_item->setTransform(QTransform()
.translate(r.width() / 2, r.height() / 2)
.rotate(angle, Qt::YAxis)
.translate(-r.width() / 2, -r.height() / 2));
#endif
m_yRotation = angle;
}
qreal yRotation() const
{
return m_yRotation;
}
GraphicsWebView* graphicsWebView() const { return m_item; }
public slots:
void updateFrameRate();
void animatedFlip();
void animatedYFlip();
void contentsSizeChanged(const QSize&);
signals:
void currentFPSUpdated(int fps);
private:
GraphicsWebView* m_item;
int m_numPaintsTotal;
int m_numPaintsSinceLastMeasure;
QTime m_startTime;
QTime m_lastConsultTime;
QTimer* m_updateTimer;
bool m_measureFps;
qreal m_yRotation;
bool m_resizesToContents;
QStateMachine* m_machine;
FpsTimer m_fpsTimer;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
131
]
]
] |
a50d1ffd454e385454febf80e70f9db529980112 | 7d5bde00c1d3f3e03a0f35ed895068f0451849b2 | /main.cpp | b9f27ede78de23d32e7c3798638e6fb182ecc7bb | [] | no_license | jkackley/jeremykackley-dfjobs-improvment | 6638af16515d140e9d68c7872b11b47d4f6d7587 | 73f53a26daa7f66143f35956150c8fe2b922c2e2 | refs/heads/master | 2021-01-16T01:01:38.642050 | 2011-05-16T18:03:23 | 2011-05-16T18:03:23 | 32,128,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,125 | cpp | /*-
* Copyright (c) 2011, Derek Young
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include <QtGui/QApplication>
#include <QWaitCondition>
#include <QSettings>
#include <QFile>
#include <QtXml/QXmlDefaultHandler>
#include <QtXml/QXmlInputSource>
//#include <QDebug>
#include "mainwindow.h"
#include "dwarfforeman.h"
#include "formanthread.h"
dfsettings settings;
FormanThread formanThread;
QWaitCondition actionNeeded;
std::vector<dfjob *> dfjobs;
class DFJobParser : public QXmlDefaultHandler
{
public:
bool startDocument()
{
//qDebug("Starting document");
inDFJobs = false;
return true;
}
bool endElement( const QString&, const QString&, const QString &name )
{
//qDebug() << "endElement " << name;
if ( name == "dfjobs" )
{
inDFJobs = false;
return true;
}
if ( name == "dfjob" )
{
dfjobs.push_back(job);
return true;
}
return true;
}
bool startElement( const QString&, const QString&, const QString &name, const QXmlAttributes &attrs )
{
//qDebug() << "startElement " << name;
if ( name == "dfjobs" )
{
inDFJobs = true;
return true;
}
if ( name == "dfjob" )
{
job = new dfjob;
job->enabled = false;
job->all = false;
job->target = 0;
job->count = 0;
job->sourcecount = 0;
job->pending = 0;
job->stack = 1;
for( int i=0; i<attrs.count(); i++ )
{
if( attrs.localName( i ) == "name" )
job->name = attrs.value( i );
else if( attrs.localName( i ) == "category" )
job->catagory = attrs.value( i );
else if( attrs.localName( i ) == "type" )
job->type = (uint8_t) attrs.value( i ).toShort();
else if ( attrs.localName( i) == "reaction" )
job->reaction = attrs.value ( i ).toStdString();
else if ( attrs.localName( i ) == "stack" )
job->stack = attrs.value( i ).toUInt();
else if ( attrs.localName( i ) == "materialType" )
job->materialType = attrs.value (i).toStdString();
else if ( attrs.localName( i ) == "inorganic" )
job->inorganic = attrs.value (i).toStdString();
else if ( attrs.localName( i ) == "other" )
job->other = attrs.value (i).toStdString();
else if ( attrs.localName( i ) == "subtype" )
job->subtype = attrs.value (i).toStdString();
}
}
if ( name == "item" )
{
std::map<std::string, std::string> item;
for( int i=0; i<attrs.count(); i++ )
{
if( attrs.localName( i ) == "type" )
item["type"] = attrs.value( i ).toStdString();
else if( attrs.localName( i ) == "material" )
item["material"] = attrs.value( i ).toStdString();
}
job->result.push_back(item);
}
if ( name == "source" )
{
std::map<std::string, std::string> item;
for( int i=0; i<attrs.count(); i++ )
{
if( attrs.localName( i ) == "type" )
item["type"] = attrs.value( i ).toStdString();
else if( attrs.localName( i ) == "material" )
item["material"] = attrs.value( i ).toStdString();
}
job->source.push_back(item);
}
return true;
}
bool fatalError(const QXmlParseException &exception)
{
//qDebug() << "Parse error at line " << exception.lineNumber() << " column" << exception.columnNumber() << " " <<
// exception.message();
return false;
}
private:
bool inDFJobs;
dfjob *job;
};
int main(int argc, char *argv[])
{
settings.seconds=60;
settings.cutalltrees=false;
settings.gatherallplants=false;
settings.logenabled=false;
settings.buffer=5;
{
DFJobParser handler;
QFile file("dfjobs.xml");
QXmlInputSource source( &file );
QXmlSimpleReader reader;
reader.setContentHandler( &handler );
reader.setErrorHandler( &handler );
reader.parse( source );
}
QApplication a(argc, argv);
a.setApplicationName("dwarf-foreman");
MainWindow w;
w.show();
formanThread.start();
return a.exec();
}
| [
"Devek@localhost",
"devek@localhost"
] | [
[
[
1,
84
],
[
87,
88
],
[
90,
90
],
[
92,
103
],
[
112,
125
],
[
139,
162
],
[
164,
181
]
],
[
[
85,
86
],
[
89,
89
],
[
91,
91
],
[
104,
111
],
[
126,
138
],
[
163,
163
]
]
] |
1b542a84594652b05c05700fb01e90775db9233e | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/C++/vc源码/计算器/QiuXpButton.cpp | c9aa01eda69a5f7b65da5cdda62c1e3c66471d12 | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,290 | cpp | // QiuXpButton.cpp : implementation file
//
#include "stdafx.h"
#include "Calculator.h"
#include "QiuXpButton.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CQiuXpButton
CQiuXpButton::CQiuXpButton()
{
m_BoundryPen.CreatePen(PS_INSIDEFRAME | PS_SOLID, 1, RGB(0, 0, 0));
m_InsideBoundryPenLeft.CreatePen(PS_INSIDEFRAME | PS_SOLID, 3, RGB(250, 196, 88));
m_InsideBoundryPenRight.CreatePen(PS_INSIDEFRAME | PS_SOLID, 3, RGB(251, 202, 106));
m_InsideBoundryPenTop.CreatePen(PS_INSIDEFRAME | PS_SOLID, 2, RGB(252, 210, 121));
m_InsideBoundryPenBottom.CreatePen(PS_INSIDEFRAME | PS_SOLID, 2, RGB(229, 151, 0));
m_FillActive.CreateSolidBrush(RGB(223, 222, 236));
m_FillInactive.CreateSolidBrush(RGB(222, 223, 236));
m_InsideBoundryPenLeftSel.CreatePen(PS_INSIDEFRAME | PS_SOLID, 3, RGB(153, 198, 252));
m_InsideBoundryPenTopSel.CreatePen(PS_INSIDEFRAME | PS_SOLID, 2, RGB(162, 201, 255));
m_InsideBoundryPenRightSel.CreatePen(PS_INSIDEFRAME | PS_SOLID, 3, RGB(162, 189, 252));
m_InsideBoundryPenBottomSel.CreatePen(PS_INSIDEFRAME | PS_SOLID, 2, RGB(162, 201, 255));
m_bOver = m_bSelected = m_bTracking = m_bFocus = FALSE;
}
CQiuXpButton::~CQiuXpButton()
{
}
BEGIN_MESSAGE_MAP(CQiuXpButton, CButton)
//{{AFX_MSG_MAP(CQiuXpButton)
ON_WM_CREATE()
ON_WM_DRAWITEM()
ON_WM_MOUSEMOVE()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
ON_MESSAGE(WM_MOUSEHOVER, OnMouseHover)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CQiuXpButton message handlers
int CQiuXpButton::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CButton::OnCreate(lpCreateStruct) == -1)
return -1;
ModifyStyle(0, BS_OWNERDRAW);
return 0;
}
void CQiuXpButton::DoGradientFill(CDC *pDC, CRect* rect)
{
CBrush pBrush[64];
int nWidth = rect->Width(); //rect.right - rect.left;
int nHeight = rect->Height(); //.bottom - rect.top;
CRect rct;
for (int i = 0; i < 64; i ++)
{
if (m_bOver)
{
if (m_bFocus)
pBrush[i].CreateSolidBrush(RGB(255 - (i / 4), 255 - (i / 4), 255 - (i / 3)));
else
pBrush[i].CreateSolidBrush(RGB(255 - (i / 4), 255 - (i / 4), 255 - (i / 5)));
}
else
{
if (m_bFocus)
pBrush[i].CreateSolidBrush(RGB(255 - (i / 3), 255 - (i / 3), 255 - (i / 4)));
else
pBrush[i].CreateSolidBrush(RGB(255 - (i / 3), 255 - (i / 3), 255 - (i / 5)));
}
}
for (int i = rect->top; i <= nHeight + 2; i ++)
{
rct.SetRect(rect->left, i, nWidth + 2, i + 1);
pDC->FillRect(&rct, &pBrush[((i * 63) / nHeight)]);
}
for (int i = 0; i < 64; i ++)
pBrush[i].DeleteObject();
}
void CQiuXpButton::DrawInsideBorder(CDC *pDC, CRect* rect)
{
CPen *left, *right, *top, *bottom;
if (m_bSelected && !m_bOver)
{
left = & m_InsideBoundryPenLeftSel;
right = &m_InsideBoundryPenRightSel;
top = &m_InsideBoundryPenTopSel;
bottom = &m_InsideBoundryPenBottomSel;
}
else
{
left = &m_InsideBoundryPenLeft;
right = &m_InsideBoundryPenRight;
top = &m_InsideBoundryPenTop;
bottom = &m_InsideBoundryPenBottom;
}
CPoint oldPoint = pDC->MoveTo(rect->left, rect->bottom - 1);
CPen* hOldPen = pDC->SelectObject(left);
pDC->LineTo(rect->left, rect->top + 1);
pDC->SelectObject(*right);
pDC->MoveTo(rect->right - 1, rect->bottom - 1);
pDC->LineTo(rect->right - 1, rect->top);
pDC->SelectObject(*top);
pDC->MoveTo(rect->left - 1, rect->top);
pDC->LineTo(rect->right - 1, rect->top);
pDC->SelectObject(*bottom);
pDC->MoveTo(rect->left, rect->bottom);
pDC->LineTo(rect->right - 1, rect->bottom);
pDC->SelectObject(hOldPen);
pDC->MoveTo(oldPoint);
}
void CQiuXpButton::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
DrawItem(lpDrawItemStruct);
// CButton::OnDrawItem(nIDCtl, lpDrawItemStruct);
}
void CQiuXpButton::OnMouseMove(UINT nFlags, CPoint point)
{
if (!m_bTracking)
{
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.hwndTrack = m_hWnd;
tme.dwFlags = TME_LEAVE | TME_HOVER;
tme.dwHoverTime = 1;
m_bTracking = _TrackMouseEvent(&tme);
}
CButton::OnMouseMove(nFlags, point);
}
LRESULT CQiuXpButton::OnMouseLeave(WPARAM wParam, LPARAM lParam)
{
m_bOver = FALSE;
m_bTracking = FALSE;
InvalidateRect(NULL, FALSE);
return 0;
}
LRESULT CQiuXpButton::OnMouseHover(WPARAM wParam, LPARAM lParam)
{
m_bOver = TRUE;
InvalidateRect(NULL);
return 0;
}
void CQiuXpButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
HDC dc = lpDrawItemStruct->hDC;
CRect &rect = (CRect&) lpDrawItemStruct->rcItem;
CMemDC pDC(dc, NULL);
UINT state = lpDrawItemStruct->itemState;
POINT pt ;
TCHAR szText[MAX_PATH + 1];
::GetWindowText(m_hWnd, szText, MAX_PATH);
pt.x = 5;
pt.y = 5;
CPen* hOldPen = pDC.SelectObject(&m_BoundryPen);
pDC.RoundRect(&rect, pt);
if (state & ODS_FOCUS)
{
m_bFocus = TRUE;
m_bSelected = TRUE;
}
else
{
m_bFocus = FALSE;
m_bSelected = FALSE;
}
if (state & ODS_SELECTED || state & ODS_DEFAULT)
{
m_bFocus = TRUE;
}
pDC.SelectObject(hOldPen);
rect.DeflateRect(CSize(GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE)));
CBrush* hOldBrush;
if (m_bOver)
{
hOldBrush = pDC.SelectObject(&m_FillActive);
DoGradientFill(&pDC, &rect);
}
else
{
hOldBrush = pDC.SelectObject(&m_FillInactive);
DoGradientFill(&pDC, &rect);
}
if (m_bOver || m_bSelected)
{
DrawInsideBorder(&pDC, &rect);
}
pDC.SelectObject(hOldBrush);
if (szText!=NULL)
{
CFont* hFont = GetFont();
CFont* hOldFont = pDC.SelectObject(hFont);
CSize Extent = pDC.GetTextExtent(szText, lstrlen(szText));
CPoint pt( rect.CenterPoint().x - Extent.cx / 2, rect.CenterPoint().y - Extent.cy / 2);
if (state & ODS_SELECTED)
pt.Offset(1, 1);
int nMode = pDC.SetBkMode(TRANSPARENT);
if (state & ODS_DISABLED)
pDC.DrawState(pt, Extent, szText, DSS_DISABLED, TRUE, 0, (HBRUSH)NULL);
else
pDC.DrawState(pt, Extent, szText, DSS_NORMAL, TRUE, 0, (HBRUSH)NULL);
pDC.SelectObject(hOldFont);
pDC.SetBkMode(nMode);
}
}
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
239
]
]
] |
eee641f25e5c9afbc88ba45825933d8bea4bc4ba | 57f014e835e566614a551f70f2da15145c7683ab | /src/contour/GeneratedFiles/Release/moc_helpdialog.cpp | d2e845831f6a72f9267d66becfc914a953eaf20e | [] | no_license | vcer007/contour | d5c3a1bbd7f5c948fbda9d9bbc7d40333640568d | 6917e4b4f24882df2111ca4af5634645cb2700eb | refs/heads/master | 2020-05-30T05:35:15.107140 | 2011-05-23T12:59:00 | 2011-05-23T12:59:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'helpdialog.h'
**
** Created: Fri May 15 11:18:58 2009
** by: The Qt Meta Object Compiler version 59 (Qt 4.4.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../dialog/helpdialog.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'helpdialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 59
#error "This file was generated using the moc from 4.4.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_HelpDialog[] = {
// content:
1, // revision
0, // classname
0, 0, // classinfo
1, 10, // methods
0, 0, // properties
0, 0, // enums/sets
// slots: signature, parameters, type, tag, flags
12, 11, 11, 11, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_HelpDialog[] = {
"HelpDialog\0\0showHtml()\0"
};
const QMetaObject HelpDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_HelpDialog,
qt_meta_data_HelpDialog, 0 }
};
const QMetaObject *HelpDialog::metaObject() const
{
return &staticMetaObject;
}
void *HelpDialog::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_HelpDialog))
return static_cast<void*>(const_cast< HelpDialog*>(this));
if (!strcmp(_clname, "Ui::HelpDialog"))
return static_cast< Ui::HelpDialog*>(const_cast< HelpDialog*>(this));
return QDialog::qt_metacast(_clname);
}
int HelpDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: showHtml(); break;
}
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
73
]
]
] |
e32c3dfaabf9bb776f8a823021da979a16ebbb0c | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/UILayer/Lists/SearchListCtrl.h | e7f5d8f6838fb98a7f0aaa1739ee8845925061cb | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,873 | h | /*
* $Id: SearchListCtrl.h 14238 2009-07-08 10:04:38Z dgkang $
*
* this file is part of eMule
* Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
#include "MuleListCtrl.h"
#include "TitleMenu.h"
#include "ListCtrlItemWalk.h"
#define AVBLYSHADECOUNT 13
class CSearchList;
class CSearchFile;
class CToolTipCtrlX;
enum EFileSizeFormat {
fsizeDefault,
fsizeKByte,
fsizeMByte
};
struct SearchCtrlItem_Struct{
CSearchFile* value;
CSearchFile* owner;
uchar filehash[16];
uint16 childcount;
};
class CSortSelectionState{
public:
uint32 m_nSortItem;
bool m_bSortAscending;
uint32 m_nScrollPosition;
CArray<int, int> m_aSelectedItems;
};
class CFileSearch;
class CSearchListCtrl : public CMuleListCtrl, public CListCtrlItemWalk
{
DECLARE_DYNAMIC(CSearchListCtrl)
public:
CSearchListCtrl();
virtual ~CSearchListCtrl();
void Init(CSearchList* in_searchlist);
void CreateMenues();
void UpdateSources(const CSearchFile* toupdate);
void AddResult(const CSearchFile* toshow);
void RemoveResult(const CSearchFile* toremove);
void RemoveResults(uint32 nID);
void Localize();
void ShowResults(uint32 nResultsID,CFileSearch* pFileSearch=NULL);
void ShowFileSearchResults( CFileSearch* pFileSearch);
void ClearResultViewState(uint32 nResultsID);
void NoTabs() { m_nResultsID = 0; }
void UpdateSearch(CSearchFile* toupdate);
EFileSizeFormat GetFileSizeFormat() const { return m_eFileSizeFormat; }
void SetFileSizeFormat(EFileSizeFormat eFormat);
protected:
uint32 m_nResultsID;
CTitleMenu m_SearchFileMenu;
CSearchList* searchlist;
CToolTipCtrlX* m_tooltip;
CImageList m_ImageList;
COLORREF m_crSearchResultDownloading;
COLORREF m_crSearchResultDownloadStopped;
COLORREF m_crSearchResultKnown;
COLORREF m_crSearchResultShareing;
COLORREF m_crSearchResultCancelled;
COLORREF m_crShades[AVBLYSHADECOUNT];
EFileSizeFormat m_eFileSizeFormat;
CMap<int,int, CSortSelectionState*, CSortSelectionState*> m_mapSortSelectionStates;
COLORREF GetSearchItemColor(/*const*/ CSearchFile* src);
CString GetCompleteSourcesDisplayString(const CSearchFile* pFile, UINT uSources, bool* pbComplete = NULL) const;
void ExpandCollapseItem(int iItem, int iAction);
void HideSources(CSearchFile* toCollapse);
void SetStyle();
void SetHighlightColors();
void SetAllIcons();
CString FormatFileSize(ULONGLONG ullFileSize) const;
void GetItemDisplayText(const CSearchFile* src, int iSubItem, LPTSTR pszText, int cchTextMax) const;
bool IsFilteredItem(const CSearchFile* pSearchFile) const;
void DrawSourceParent(CDC *dc, int nColumn, LPRECT lpRect, /*const*/ CSearchFile* src);
void DrawSourceChild(CDC *dc, int nColumn, LPRECT lpRect, /*const*/ CSearchFile* src);
static int Compare(const CSearchFile* item1, const CSearchFile* item2, LPARAM lParamSort);
static int CompareChild(const CSearchFile* file1, const CSearchFile* file2, LPARAM lParamSort);
static int CALLBACK SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort);
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
DECLARE_MESSAGE_MAP()
afx_msg void OnSysColorChange();
afx_msg void OnColumnClick( NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/);
afx_msg void OnLvnDeleteAllItems(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnClick(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDblClick(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnLvnKeyDown(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnLvnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDestroy();
//共享文件列表中的评论,added by Chocobo on 2006.09.01
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
//VeryCD End
public:
afx_msg void OnNMClick(NMHDR *pNMHDR, LRESULT *pResult);
};
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
133
]
]
] |
4f4ef11ee6f4d1ea7259b6133f59aeebbec30c3d | 12ea67a9bd20cbeed3ed839e036187e3d5437504 | /winxgui/FreeCode2007/source/FCWizard/codeparser.h | c09cf5f4ea28a31f9aabdb8d67da551dd18537e9 | [] | no_license | cnsuhao/winxgui | e0025edec44b9c93e13a6c2884692da3773f9103 | 348bb48994f56bf55e96e040d561ec25642d0e46 | refs/heads/master | 2021-05-28T21:33:54.407837 | 2008-09-13T19:43:38 | 2008-09-13T19:43:38 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 13,907 | h | #ifndef _CODEPARSER_H__
#define _CODEPARSER_H__
//Code::Blocks Common
#include "./cbparser/parserthread.h"
//WTLHelper Common
#include "./resources/reshelper.h"
#include "./resources/Resources.h"
#include "./winx_event.h"
#include "./win32_notify.h"
#include "../public/qevent.h"
#include "./dspparser.h"
class codeparser
{
public:
CResources m_Res;
TokensArray m_Tokens;
winx_event_config m_winxev;
win32_notify_config m_notify;
public:
codeparser()
{
}
public:
bool WinxRemoveNotifyToken(Token * tk, QLib::Event<bool,Token*> AskRemove)
{
//is addnew token remove it
if (tk->m_TokenUpdate == tuAddnew)
{
if (tk->m_pParent != NULL)
{
tk->m_pParent->RemoveChild(tk);
}
m_Tokens.Remove(tk);
return true;
}
//is extern token set flag remove
else if (tk->m_TokenUpdate == tuNormal)
{
if (AskRemove(tk) == true)
{
tk->m_TokenUpdate = tuRemove;
return true;
}
}
return false;
}
Token * WinxAddNotifyToken(win32_notify_code * wnc, Token * tkcls, LPCSTR id, LPCTSTR func, bool bMenu)
{
Token * tk = new Token();
if (wnc->code == _T("COMMAND"))
{
tk->m_Name = _T("WINX_CMD");
tk->m_TokenKind = tkMapping;
tk->m_TokenUpdate = tuAddnew;
tk->m_Args = _T("(");
tk->m_Args += id;
tk->m_Args += _T(",");
tk->m_Args += func;
tk->m_Args += _T(")");
tk->m_String = _T("void ");
tk->m_String += func;
tk->m_String += _T("(HWND hWnd)");
}
else if (wnc->kind == wkCOMMAND)
{
tk->m_Name = _T("WINX_CMD_EX");
tk->m_Args = _T("(");
tk->m_Args += id;
tk->m_Args += _T(",");
tk->m_Args += wnc->code;
tk->m_Args += _T(",");
tk->m_Args += func;
tk->m_Args += _T(")");
tk->m_String = _T("void ");
tk->m_String += func;
tk->m_String += _T("(HWND hWnd)");
}
else if (wnc->kind == wkNOTIFY)
{
tk->m_Name = _T("WINX_NOTIFY");
tk->m_Args = _T("(");
tk->m_Args += id;
tk->m_Args += _T(",");
tk->m_Args += wnc->code;
tk->m_Args += _T(",");
tk->m_Args += func;
tk->m_Args += _T(")");
tk->m_String = _T("void ");
tk->m_String += func;
tk->m_String += _T("(HWND hWnd, LPNMHDR pnmh, LRESULT* pResult)");
}
tk->m_TokenKind = tkMapping;
tk->m_TokenUpdate = tuAddnew;
//save m_String is func name
if (tkcls)
{
tk->m_pParent = tkcls;
tkcls->AddChild(tk);
}
m_Tokens.Add(tk);
return tk;
}
Token * WinxAddEventToken(winx_event * ev, Token * tkcls)
{
//is remove reset flag normal
for (int i = 0; i < tkcls->m_Children.GetCount(); i++) {
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkFunction &&
(CString)tk->m_Name == ev->name) {
if (tk->m_TokenUpdate == tuRemove) {
tk->m_TokenUpdate = tuNormal;
}
return tk;
}
}
//add new token
Token * tk = new Token();
tk->m_Name = ev->name;
if (tkcls)
{
tk->m_pParent = tkcls;
tkcls->AddChild(tk);
}
tk->m_TokenKind = tkFunction;
tk->m_Scope = tsPublic;
tk->m_TokenUpdate = tuAddnew;
tk->m_Data = (void*)ev;
m_Tokens.Add(tk);
return tk;
}
bool WinxRemoveEventToken(Token * tk_ev, QLib::Event<bool,Token*> AskRemove)
{
Token * tkcls = tk_ev->m_pParent;
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkFunction &&
tk->m_Name == tk_ev->m_Name )
{
if (tk->m_TokenUpdate == tuAddnew)
{
if (tk->m_pParent != NULL) {
tk->m_pParent->RemoveChild(tk);
}
m_Tokens.Remove(tk);
return true;
}
else if (tk->m_TokenUpdate == tuNormal)
{
if (AskRemove(tk) == true)
{
tk->m_TokenUpdate = tuRemove;
return true;
}
}
}
}
return false;
}
bool WinxIsEventToken(Token * tk)
{
for (int i = 0; i < m_winxev.m_items.GetSize(); i++)
{
winx_event & ev = m_winxev.m_items[i];
if (ev.name == CString(tk->m_Name))
{
return true;
}
}
return false;
}
bool EnumWinxEventToken(Token * tkcls, QLib::Event<void,Token*> & Process)
{
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkFunction && WinxIsEventToken(tk))
{
Process(tk);
}
}
return true;
}
bool EnumProjectClass(QLib::Event<void,Token*> & Process)
{
for (int i = 0; i < m_Tokens.GetCount(); i++)
{
Token * tk = m_Tokens[i];
if (tk->m_TokenKind == tkClass)
{
Process(tk);
}
}
return true;
}
bool EnumWinxMessageToken(Token * tkcls, QLib::Event<void,Token*> & Process)
{
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkMapping)
{
if (tk->m_Name == _T("WINX_CMD") ||
tk->m_Name == _T("WINX_CMD_EX") ||
tk->m_Name == _T("WINX_CMD_NOARG") ||
tk->m_Name == _T("WINX_CMD_RANGE") ||
tk->m_Name == _T("WINX_CMD_NOTIFY") ||
tk->m_Name == _T("WINX_SYSCMD") ||
tk->m_Name == _T("WINX_NOTIFY") ||
tk->m_Name == _T("WINX_NOTIFY_RANGE") )
{
Process(tk);
}
}
}
return true;
}
bool EnumWinxProperty(Token * tkcls, QLib::Event<void,Token*> & Process)
{
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkMapping)
{
if (tk->m_Name == _T("WINX_CMD") ||
tk->m_Name == _T("WINX_CMD_EX") ||
tk->m_Name == _T("WINX_CMD_NOARG") ||
tk->m_Name == _T("WINX_CMD_RANGE") ||
tk->m_Name == _T("WINX_CMD_NOTIFY") ||
tk->m_Name == _T("WINX_SYSCMD") ||
tk->m_Name == _T("WINX_NOTIFY") ||
tk->m_Name == _T("WINX_NOTIFY_RANGE") ||
tk->m_Name == _T("WINX_UPDATEUI"))
{
continue;
}
else
{
Process(tk);
}
}
}
return true;
}
bool EnumControlNofity(win32_notify * wn, QLib::Event<void,win32_notify_code*> & Process)
{
if (wn == NULL) {
return false;
}
for (int i = 0; i < wn->codes.GetSize(); i++)
{
Process(&wn->codes[i]);
}
return true;
}
CString GetClassEnumIDD(Token * tkcls)
{
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == tkEnum &&
tk->m_Children.GetCount() ==1)
{
Token * tkidd = tk->m_Children[0];
if (tkidd->m_Name == _T("IDD"))
{
return tkidd->m_Args;
}
}
}
return _T("");
}
CResDialog * GetResDialog(Token * tkcls)
{
// CString enum_id = GetClassEnumIDD(tkcls);
for (int i = 0; i < m_Res.m_Dialogs.GetCount(); i++)
{
CResDialog & dlg = m_Res.m_Dialogs[i];
if (tkcls->m_AncestorsString.Find(dlg.m_ID) != -1)
{
return &dlg;
}
}
return NULL;
}
CResMenu * GetResDialogMenu(LPCTSTR menuID)
{
for (int i = 0; i < m_Res.m_Menus.GetCount(); i++)
{
const CResMenu & menu = m_Res.m_Menus.GetAt(i);
if (menu.m_ID == menuID)
{
return (CResMenu*)&menu;
}
}
return NULL;
}
win32_notify * GetResControlNotify(ResControl * ctrl)
{
return m_notify.get_notify_by_res(ctrl->m_Type);
}
win32_notify * GetResMenuNotify()
{
return m_notify.get_notify_by_name(_T("menu"));
}
Token * GetFirstTokenByName(Token * tkcls, LPCTSTR head, TokenKind kind = tkMapping)
{
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind == kind && tk->m_TokenUpdate == tuNormal)
{
if (tk->m_Name == head)
{
return tk;
}
}
}
return NULL;
}
bool EnumResDialog(QLib::Event<void,CResDialog *> Process)
{
for (int i = 0; i < m_Res.m_Dialogs.GetCount(); i++)
{
Process(&m_Res.m_Dialogs[i]);
}
return true;
}
bool EnumResMenu(QLib::Event<void,CResMenu *> Process)
{
for (int i = 0; i < m_Res.m_Menus.GetCount(); i++)
{
Process(&m_Res.m_Menus[i]);
}
return true;
}
bool EnumResDialogControl(const CResDialog * dlg, QLib::Event<void,const ResControl*> & Process)
{
for (int i = 0; i < dlg->GetCount(); i++)
{
if (dlg->GetAt(i).m_ID != _T("IDC_STATIC"))
Process(&dlg->GetAt(i));
}
return true;
}
bool EnumResMenuItem(const CResMenu * menu, QLib::Event<void,const ResMenuItem*> & Process)
{
for (int i = 0; i < menu->GetCount(); i++)
{
if (!menu->m_ID.IsEmpty())
Process(&menu->GetAt(i));
}
for (int j = 0; j < menu->m_SubMenus.GetCount(); j++)
{
const CResMenu & subMenu = menu->m_SubMenus.GetAt(j);
for (int k = 0; k < subMenu.GetCount(); k++)
{
if (!subMenu.GetAt(k).m_ID.IsEmpty())
Process(&subMenu.GetAt(k));
}
}
return true;
}
bool EnumWinxEventList(QLib::Event<void,winx_event*> & Process)
{
for (int i = 0; i < m_winxev.m_items.GetSize(); i++)
{
Process(&m_winxev.m_items[i]);
}
return true;
}
bool LoadRes(LPCTSTR lpszResource,bool bAppend = false)
{
return m_Res.Load(lpszResource,bAppend);
}
bool LoadCode(LPCTSTR lpszFileName, bool bAppend = false)
{
if (bAppend == false)
m_Tokens.Clear();
wxEvtHandler ev;
ParserThreadOptions op;
op.useBuffer = false;
op.bufferSkipBlocks = false;
op.wantPreprocessor = false;
bool flag;
bool bRet = false;
ParserThread * th = new ParserThread(&ev,&flag,lpszFileName,true,op,&m_Tokens);
bRet = th->Parse();
delete th;
return bRet;
}
//load vs60 dsp file and parser file
bool LoadVS606DSP(LPCTSTR lpszDspFileName)
{
m_Tokens.Clear();
m_Res.Clear();
dspparser dsp;
if (!dsp.load_dsp(lpszDspFileName))
return false;
CString file;
CSimpleArray<CString> ar1,ar2;
int i = 0;
for (i = 0; i < dsp.source.GetSize(); i++)
{
CString & tmp = dsp.source[i];
if (tmp.Left(1) == _T("\""))
{
file = tmp;
file.TrimLeft(_T("\""));
file.TrimRight(_T("\""));
}
else
file = dsp.root_path+tmp;
CString & ext = get_file_ext(file);
if (ext.CompareNoCase(_T(".rc")) == 0) {
LoadRes(file,true);
}
else if (ext.CompareNoCase(_T(".h")) == 0 ||
ext.CompareNoCase(_T(".hxx")) == 0 ||
ext.CompareNoCase(_T(".hpp")) == 0)
{
ar1.Add(file);
}
else if ( ext.CompareNoCase(_T(".cpp")) == 0 ||
ext.CompareNoCase(_T(".cxx")) == 0 ||
ext.CompareNoCase(_T(".c")) == 0 )
{
ar2.Add(file);
}
}
//frist parser .h
for (i = 0; i < ar1.GetSize(); i++)
{
LoadCode(ar1[i],true);
}
//then parser .cpp
for (i = 0; i < ar2.GetSize(); i++)
{
LoadCode(ar2[i],true);
}
return true;
}
//insert token
Token * GetLastTokenByScope(Token * tkcls, TokenScope Scope)
{
for (int i = tkcls->m_Children.GetCount()-1; i--; i >= 0)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenUpdate != tuAddnew &&
tk->m_Scope == Scope )
{
return tk;
}
}
return NULL;
}
//parser token and process winx kind token
void WinxParserKindToken()
{
for (int i = 0; i < m_Tokens.GetCount(); i++)
{
Token * tk = m_Tokens[i];
if (tk->m_TokenKind == tkClass)
{
WinxParserKindTokenHelper(tk);
}
}
}
void WinxParserKindTokenHelper(Token * tkcls)
{
Token * cmd = new Token();
cmd->m_TokenKind = tkWinxCmd;
Token * syscmd = new Token();
syscmd->m_TokenKind = tkWinxSyscmd;
Token * notify = new Token();
notify->m_TokenKind = tkWinxNotify;
Token * update = new Token();
update->m_TokenKind = tkWinxUpdate;
for (int i = 0; i < tkcls->m_Children.GetCount(); i++)
{
Token * tk = tkcls->m_Children[i];
if (tk->m_TokenKind != tkMapping)
continue;
if (tk->m_Name == _T("WINX_CMDS_BEGIN") ||
tk->m_Name == _T("WINX_CMDS_END") ||
tk->m_Name == _T("WINX_CMDS_BEGIN_EX") ||
tk->m_Name == _T("WINX_CMDS_END_EX") ||
tk->m_Name == _T("WINX_CMD") ||
tk->m_Name == _T("WINX_CMD_EX") ||
tk->m_Name == _T("WINX_CMD_NOARG") ||
tk->m_Name == _T("WINX_CMD_RANGE") ||
tk->m_Name == _T("WINX_CMD_NOTIFY") )
{
tk->m_pParent = cmd;
cmd->AddChild(tk);
}
else if (tk->m_Name == _T("WINX_SYSCMD_BEGIN") ||
tk->m_Name == _T("WINX_SYSCMD_END") ||
tk->m_Name == _T("WINX_SYSCMD") )
{
tk->m_pParent = syscmd;
syscmd->AddChild(tk);
}
else if (tk->m_Name == _T("WINX_NOTIFY_BEGIN") ||
tk->m_Name == _T("WINX_NOTIFY_END") ||
tk->m_Name == _T("WINX_NOTIFY") ||
tk->m_Name == _T("WINX_NOTIFY_RANGE") )
{
tk->m_pParent = notify;
notify->AddChild(tk);
}
else if (tk->m_Name == _T("WINX_UPDATEUI_BEGIN") ||
tk->m_Name == _T("WINX_UPDATEUI_END") ||
tk->m_Name == _T("WINX_UPDATEUI") )
{
tk->m_pParent = update;
update->AddChild(tk);
}
}
cmd->m_pParent = tkcls;
syscmd->m_pParent = tkcls;
notify->m_pParent = tkcls;
update->m_pParent = tkcls;
tkcls->AddChild(cmd);
tkcls->AddChild(syscmd);
tkcls->AddChild(notify);
tkcls->AddChild(update);
m_Tokens.Add(cmd);
m_Tokens.Add(syscmd);
m_Tokens.Add(notify);
m_Tokens.Add(update);
}
};
/*
//member function type
enum mf_type
{
mf_event,
mf_virtual,
mf_command,
mf_notify
};
struct MemberFunction
{
CString function;
mf_type type;
CString GetType()
{
switch(type)
{
case mf_event:
return _T("EVENT");
case mf_virtual:
return _T("VIRTUAL");
case mf_command:
return _T("COMMAND");
case mf_notify:
return _T("NOTIFY");
}
return _T("");
}
};
//元素,类,资源ID
struct cf_object
{
};
//重载消息
struct cf_message
{
};
//消息映射
struct cf_mapping
{
};
*/
#endif | [
"xushiweizh@86f14454-5125-0410-a45d-e989635d7e98"
] | [
[
[
1,
605
]
]
] |
46c5bd9493ceb22d073af930e43d87f53575fb60 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/StdAfx.h | 0b5fb88a385724629392bef3a01b1a34594311f7 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,239 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__A49FC39C_E359_437B_8811_949CAC05B162__INCLUDED_)
#define AFX_STDAFX_H__A49FC39C_E359_437B_8811_949CAC05B162__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "..\..\common\scd\scdlib\Scd_SHLB.h"
#ifdef _DEBUG
//#define _ATL_DEBUG_INTERFACES
//#define _ATL_DEBUG_REFCOUNT
//#define _ATL_DEBUG_QI
#endif
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#define _WIN32_DCOM // This includes new DCOM calls
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#include <comdef.h>
#import "c:\program files\common files\system\ado\msado15.dll" rename("EOF", "adEOF") no_implementation
#import "c:\Program Files\Common Files\system\ado\msadox.dll" no_implementation
#import "..\scdlib\vbscript.tlb" no_namespace rename("RGB","rgb")
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxtempl.h>
#include <afxole.h>
#include <afxconv.h>
#include <afxpriv.h>
//#define _ATL_APARTMENT_THREADED
#define _ATL_FREE_THREADED
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
class CSysCADModule : public CComModule
{
public:
LONG Unlock();
LONG Lock();
DWORD dwThreadID;
};
extern CSysCADModule _Module;
#include <atlcom.h>
#include <comdef.h>
#include "..\..\common\scd\scdlib\sc_defs.h"
#include "..\..\common\scd\scdlib\gpfuncs.h"
#pragma LIBCOMMENT("..\\..\\common\\com\\scdcom\\", "\\scdcom")
#pragma LIBCOMMENT("..\\..\\common\\scd\\scdlib\\", "\\scdlib")
#pragma LIBCOMMENT("..\\..\\common\\scd\\scexec\\", "\\scexec")
#pragma LIBCOMMENT("..\\..\\common\\scd\\flwlib\\", "\\flwlib")
#pragma LIBCOMMENT("..\\..\\common\\scd\\schist\\", "\\schist")
//#pragma LIBCOMMENT("..\\..\\scd\\scapp1\\", "\\scapp1")
#pragma LIBCOMMENT("..\\..\\common\\scd\\kwdb\\", "\\kwdb")
#pragma LIBCOMMENT("..\\..\\common\\com\\ScdIF\\", "\\ScdIF")
#pragma LIBCOMMENT("..\\..\\common\\com\\ScdMdl\\", "\\ScdMdl")
#pragma LIBCOMMENT("..\\..\\common\\com\\ScdSlv\\", "\\ScdSlv")
#pragma LIBCOMMENT("..\\CCDK\\", "\\CCDK" )
#include "..\..\Common\Com\ScdIF\ScdIF.h"
#include "..\..\Common\Com\ScdMdl\ScdMdl.h"
#include "..\..\Common\Com\ScdSlv\ScdSlv.h"
#include "ScdCOMTmpl.h"
//#include "syscad.h"
#include "..\..\Common\Scd\scdlib\scd_wm.h"
#include "..\..\Common\Com\scdif\scdcomcmds.h"
#include "..\..\Common\Com\scdif\scdcomevts.h"
#include "ScdCATIDS.h"
#include <vfw.h>
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__A49FC39C_E359_437B_8811_949CAC05B162__INCLUDED_)
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
14,
32
],
[
34,
60
],
[
63,
63
],
[
69,
70
],
[
72,
72
],
[
76,
76
],
[
78,
78
],
[
82,
84
],
[
88,
97
]
],
[
[
13,
13
],
[
33,
33
],
[
61,
62
],
[
64,
68
],
[
71,
71
],
[
73,
75
],
[
77,
77
],
[
79,
81
],
[
85,
87
]
]
] |
fc33734ad9b41ee6bf616b97fbbf22e4c66cc43c | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/gui/iguicombobox.cpp | eab097c566c709369d03bb184035b0a5cf9d5f9d | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,019 | cpp | #include"iguicombobox.h"
namespace Maid
{
IGUIComboBox::IGUIComboBox()
:m_State(STATE_NORMAL)
,m_SelectListMax(1)
,m_SelectID(0)
,m_MouseInID(0)
,m_SliderTop(0)
,m_SelectBoxOffset(0,0)
,m_SliderBarLength(1)
,m_SliderButtonLength(0)
,m_IsSliderButtonIn(false)
{
}
void IGUIComboBox::Insert( int id, IElement& parts )
{
MAID_ASSERT( m_ElementList.find(id)!=m_ElementList.end(), "id:" << id << "は存在しています" );
m_ElementList[id] = &parts;
if( m_ElementList.size()==1 )
{
SetSelectID(id);
}
}
void IGUIComboBox::Delete( int id )
{
m_ElementList.erase( m_ElementList.find(id) );
if( GetSelectID()==id )
{
if( !m_ElementList.empty() )
{
SetSelectID(m_ElementList.begin()->first);
}
}
}
void IGUIComboBox::DeleteAll()
{
m_ElementList.clear();
}
IGUIComboBox::STATE IGUIComboBox::GetState() const
{
return m_State;
}
void IGUIComboBox::ChangeState( STATE s )
{
m_State = s;
}
void IGUIComboBox::SetSelectID( int new_id )
{
const int old_id = GetSelectID();
if( old_id==new_id ) { return ; }
m_SelectID = new_id;
}
int IGUIComboBox::GetSelectID() const
{
MAID_ASSERT( m_ElementList.empty(), "まだ登録されていません" );
return m_SelectID;
}
void IGUIComboBox::SetSelectListMax( int count )
{
m_SelectListMax = count;
}
IGUIComboBox::IElement& IGUIComboBox::GetSelectElement()
{
for( ELEMENTLIST::iterator ite=m_ElementList.begin(); ite!=m_ElementList.end(); ++ite )
{
if( m_SelectID==ite->first ) { return *(ite->second); }
}
return m_Tmp;
}
void IGUIComboBox::SetSelectBoxOffset( const VECTOR2DI& offset )
{
m_SelectBoxOffset = offset;
}
const VECTOR2DI& IGUIComboBox::GetSelectBoxOffset() const
{
return m_SelectBoxOffset;
}
void IGUIComboBox::SetSliderOffset( const VECTOR2DI& offset )
{
m_SliderOffset = offset;
}
const VECTOR2DI& IGUIComboBox::GetSliderOffset() const
{
return m_SliderOffset;
}
void IGUIComboBox::SetSliderBarLength( int len )
{
m_SliderBarLength = len;
}
int IGUIComboBox::GetSliderBarLength() const
{
return m_SliderBarLength;
}
void IGUIComboBox::SetSliderButtonLength( int len )
{
m_SliderButtonLength = len;
}
int IGUIComboBox::GetSliderButtonLength() const
{
return m_SliderButtonLength;
}
bool IGUIComboBox::IsSliderButtonIn() const
{
return m_IsSliderButtonIn;
}
bool IGUIComboBox::LocalIsCollision( const POINT2DI& pos ) const
{
if( IsBoxCollision( pos ) ) { return true; }
if( GetState()==STATE_NORMAL ) { return false; }
// 項目選択時は、スライダ、選択項目も調べる
{
const POINT2DI SliderPos = pos - GetSliderOffset();
if( IsSliderButtonCollision( SliderPos ) ) { return true; }
if( IsSliderCollision( SliderPos ) ) { return true; }
}
POINT2DI ElementPos = pos - GetSelectBoxOffset();
ELEMENTLIST::const_iterator ite = GetSliderTopIte();
if( IsSelectBoxCollision( ElementPos ) ) { return true; }
int height = 0;
for( int i=0; i<m_SelectListMax; ++i )
{
if( ite==m_ElementList.end() ) { break; }
const IElement* p = ite->second;
if( p->IsCollision( ElementPos ) ) { return true; }
ElementPos.y -= p->GetBoxSize().h;
++ite;
}
return false;
}
void IGUIComboBox::OnUpdateFrame()
{
for( ELEMENTLIST::iterator ite=m_ElementList.begin(); ite!=m_ElementList.end(); ++ite )
{
ite->second->UpdateFrame();
}
}
IGUIComboBox::ELEMENTLIST::const_iterator IGUIComboBox::GetSliderTopIte() const
{
// 現在のスライダボタンの位置にある、elementを取得
ELEMENTLIST::const_iterator ite = m_ElementList.begin();
for( int i=0; i<m_SliderTop; ++i )
{
++ite;
}
return ite;
}
void IGUIComboBox::DrawElement( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
const STATE state = GetState();
// 選択項目の表示
// 一番上は現在選択されているもの
// 2行目以降はidの順に表示していく
// ただし2行目以降は状態で表示非表示が変わる
{
IElement& ele = GetSelectElement();
ele.DrawSelect( Target, Depth, pos );
}
if( state==STATE_NORMAL ) { return ; }
{
POINT2DI DrawPos = pos + GetSelectBoxOffset();
ELEMENTLIST::const_iterator ite = GetSliderTopIte();
for( int i=0; i<m_SelectListMax; ++i )
{
if( ite==m_ElementList.end() ) { break; }
const int id = ite->first;
IElement* pEle = ite->second;
const SIZE2DI size = pEle->GetBoxSize();
if( id==m_MouseInID ) { pEle->DrawMouseIn( Target, Depth, DrawPos ); }
else { pEle->DrawNormal( Target, Depth, DrawPos ); }
DrawPos.y += size.h;
++ite;
}
}
// スライダの表示
POINT2DI SliderPos = pos + GetSliderOffset();
DrawSlider( Target, Depth, SliderPos );
}
int IGUIComboBox::CalcSliderButtonOffset() const
{
if( (int)m_ElementList.size() <= m_SelectListMax ) { return 0; }
const int slidermax = m_ElementList.size()-m_SelectListMax;
const int slidernow = m_SliderTop;
const int height = GetSliderBarLength() - GetSliderButtonLength();
const int ret = height * slidernow / slidermax;
return ret;
}
int IGUIComboBox::CalcSliderValue( int PosY ) const
{
const int len = GetSliderBarLength()-GetSliderButtonLength();
const int value = m_ElementList.size()-m_SelectListMax;
const int no = PosY * value / len;
if( no<0 ) { return 0; }
return std::min(no,value);
}
IGUIComboBox::MESSAGERETURN IGUIComboBox::MessageExecuting( SPGUIPARAM& pParam )
{
switch( pParam->Message )
{
case IGUIParam::MESSAGE_MOUSEDOWN:
{
const GUIMESSAGE_MOUSEDOWN& m = static_cast<const GUIMESSAGE_MOUSEDOWN&>(*pParam);
const POINT2DI pos = CalcLocalPosition(m.Position);
switch( GetState() )
{
case STATE_NORMAL:
{
if( IsBoxCollision(pos) )
{
ChangeState(STATE_SELECTING);
}
}break;
case STATE_SELECTING:
{
const POINT2DI SliderPos = pos - GetSliderOffset();
if( IsSliderButtonCollision(SliderPos) )
{
ChangeState(STATE_SLIDERBUTTONDOWN);
}
else if( IsSliderCollision(SliderPos) )
{
m_SliderTop = CalcSliderValue( SliderPos.y );
}
else
{
// 押してマウス選択を決定する前に
// MESSAGE_MOUSEMOVE 側で決定できるのでここは無視する
}
}break;
case STATE_SLIDERBUTTONDOWN:
{
}break;
}
}break;
case IGUIParam::MESSAGE_MOUSEMOVE:
{
const GUIMESSAGE_MOUSEMOVE& p = static_cast<const GUIMESSAGE_MOUSEMOVE&>(*pParam);
const POINT2DI pos = CalcLocalPosition(p.Position);
m_IsSliderButtonIn = false;
switch( GetState() )
{
case STATE_NORMAL:
{
}break;
case STATE_SELECTING:
{
const POINT2DI SliderPos = pos - GetSliderOffset();
if( IsSliderButtonCollision(SliderPos) )
{
m_IsSliderButtonIn = true;
}
else if( IsSliderCollision(SliderPos) )
{
}
else
{
POINT2DI ElementPos = pos - GetSelectBoxOffset();
ELEMENTLIST::const_iterator ite = GetSliderTopIte();
for( int i=0; i<m_SelectListMax; ++i )
{
if( ite==m_ElementList.end() ) { break; }
const IElement* p = ite->second;
if( p->IsCollision( ElementPos ) )
{
m_MouseInID = ite->first;
break;
}
ElementPos.y -= p->GetBoxSize().h;
++ite;
}
}
}break;
case STATE_SLIDERBUTTONDOWN:
{
m_IsSliderButtonIn = true;
const POINT2DI SliderPos = pos - GetSliderOffset();
m_SliderTop = CalcSliderValue( SliderPos.y );
}break;
}
}break;
case IGUIParam::MESSAGE_MOUSEUP:
{
const GUIMESSAGE_MOUSEUP& m = static_cast<const GUIMESSAGE_MOUSEUP&>(*pParam);
const POINT2DI pos = CalcLocalPosition(m.Position);
switch( GetState() )
{
case STATE_NORMAL:
{
// なんもしない。する必要がない
}break;
case STATE_SELECTING:
{
// elementの中であがったらそれを選択
// そうでなかったら状態を維持
POINT2DI ElementPos = pos - GetSelectBoxOffset();
ELEMENTLIST::const_iterator ite = GetSliderTopIte();
for( int i=0; i<m_SelectListMax; ++i )
{
if( ite==m_ElementList.end() ) { break; }
const IElement* p = ite->second;
if( p->IsCollision( ElementPos ) )
{
m_SelectID = ite->first;
ChangeState(STATE_NORMAL);
GUIMESSAGE_COMBOBOX_CHANGEELEMENT mess;
mess.SelectID = m_SelectID;
PostMessage( mess );
break;
}
ElementPos.y -= p->GetBoxSize().h;
++ite;
}
}break;
case STATE_SLIDERBUTTONDOWN:
{
ChangeState(STATE_SELECTING);
}break;
}
}break;
case IGUIParam::MESSAGE_SETKEYBORDFOCUS:
{
if( GetState()!=STATE_NORMAL )
{
ChangeState(STATE_NORMAL);
}
}break;
}
return IGUIParts::MessageExecuting( pParam );
}
}
| [
"[email protected]",
"renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00"
] | [
[
[
1,
13
],
[
16,
146
],
[
149,
149
],
[
151,
153
],
[
157,
158
],
[
161,
162
],
[
174,
177
],
[
180,
184
],
[
201,
203
],
[
205,
211
],
[
213,
228
],
[
230,
230
],
[
233,
233
],
[
235,
236
],
[
238,
241
],
[
244,
245
],
[
248,
249
],
[
253,
254
],
[
258,
442
]
],
[
[
14,
15
],
[
147,
148
],
[
150,
150
],
[
154,
156
],
[
159,
160
],
[
163,
173
],
[
178,
179
],
[
185,
200
],
[
204,
204
],
[
212,
212
],
[
229,
229
],
[
231,
232
],
[
234,
234
],
[
237,
237
],
[
242,
243
],
[
246,
247
],
[
250,
252
],
[
255,
257
]
]
] |
af9c13303bc48017af211d34d3eb61c2f1ae990e | 8346a9e40ff890a56ec1a0b29e63ab6d2069a218 | /WebConfigCPP/Src/HTMLBuilder.cpp | 58b2d1cbdb366a4ae433299ecf74da47674eec3a | [
"MIT"
] | permissive | dave-mcclurg/web-config | 3f68c0ee14335396b66b17625c229e2d971b66f9 | 4174d087ca609725dd77a36fc16facd51c922400 | refs/heads/master | 2021-01-20T11:20:17.265829 | 2010-01-04T01:26:19 | 2010-01-04T01:26:19 | 32,268,994 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,516 | cpp | // WebConfig - Use a web browser to configure your application
// Copyright (c) 2009 David McClurg <[email protected]>
// Under the MIT License, details: License.txt.
#include "HTMLBuilder.h"
#include "Support/HttpUtility.h"
#include <cassert>
#include <stdarg.h>
using namespace std;
namespace WebConfig
{
/// <summary>
/// return string with formatted arguments
/// </summary>
string HtmlBuilder::fmt(const char* format, ...)
{
char temp[1024];
va_list args;
va_start (args, format);
vsprintf_s (temp, sizeof(temp), format, args);
va_end (args);
return string(temp);
}
/// <summary>
/// return html encoded text
/// </summary>
string HtmlBuilder::text(const std::string& str)
{
return HttpUtility::HtmlEncode(str);
}
/// <summary>
/// return html encoded attributes
/// </summary>
string HtmlBuilder::attr(const std::string& name, const std::string& value)
{
return fmt(" %s=\"%s\"", text(name).c_str(), text(value).c_str());
}
/// <summary>
/// open a tag with attributes
/// </summary>
/// <param name="tag">name of tag</param>
/// <param name="at">attributes for tag</param>
void HtmlBuilder::open(const std::string& tag, const std::string& at)
{
tagStack.push(tag);
append(fmt("<%s%s>\n", tag.c_str(), at.c_str()));
}
/// <summary>
/// open a tag with no attributes
/// </summary>
/// <param name="tag">name of tag</param>
void HtmlBuilder::open(const std::string& tag)
{
//hack to add doctype to beginning of html page
if (_stricmp(tag.c_str(), "html") == 0)
{
append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n");
}
tagStack.push(tag);
append(fmt("<%s>\n", tag.c_str()));
//hack to add meta info to head section
if (_stricmp(tag.c_str(), "head") == 0)
{
append("<META http-equiv=Content-Type content=\"text/html; charset=windows-1252\">\n");
}
}
/// <summary>
/// close a tag
/// </summary>
/// <param name="tag">name of tag</param>
void HtmlBuilder::close(const std::string& tag)
{
assert(!tagStack.empty());
string top = tagStack.top();
assert(top == tag);
append(fmt("</%s>\n", top.c_str()));
tagStack.pop();
}
/// <summary>
/// close all tags
/// </summary>
void HtmlBuilder::close_all()
{
while (!tagStack.empty())
{
close(tagStack.top());
}
}
/// <summary>
/// include javascript file
/// </summary>
/// <param name="name">path of javascript file</param>
void HtmlBuilder::include_js(const std::string& name)
{
append(fmt("<script%s></script>",
(attr("src", name) + attr("type", "text/javascript")).c_str()));
}
/// <summary>
/// include css file
/// </summary>
/// <param name="name">path of css file</param>
void HtmlBuilder::include_css(const std::string& name)
{
append(fmt("<link%s>",
(attr("rel", "stylesheet") +
attr("href", name) +
attr("type", "text/css")).c_str()));
}
/// <summary>
/// append a link
/// </summary>
/// <param name="url">location</param>
/// <param name="s">text</param>
void HtmlBuilder::link(const std::string& url, const std::string& s)
{
open("a", attr("href", url.c_str()));
append(s);
close("a");
}
/// <summary>
/// append an image
/// </summary>
/// <param name="src">path of image</param>
void HtmlBuilder::image(const std::string& src)
{
open("img", attr("src", src.c_str()));
close("img"); // proper close for XHTML
}
}
| [
"dave.mcclurg@d4c24e94-de21-11de-aa1f-bbd297b2055c"
] | [
[
[
1,
143
]
]
] |
6be77212bed35bbb4041eb2370775a5bfbf0b94a | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib-test/mgl_test/dshow_mp3.cpp | f9ce384c7592990667cf95841fd526cda712c70c | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,082 | cpp | #include "stdafx.h"
#include <DShow.h>
void main()
{
// DirectShowのインスタンス宣言
IGraphBuilder *p_graph=NULL;
IMediaControl *p_control=NULL;
IMediaEvent *p_event=NULL;
HRESULT hr; // 処理結果
long event_code; // イベントコード
// COMライブラリの初期化
hr=CoInitialize(NULL);
// フィルタグラフのインスタンスを生成
hr=CoCreateInstance(
CLSID_FilterGraph, // フィルタグラフのクラスID
NULL, // 非アグリゲートオブジェクト
CLSCTX_INPROC_SERVER, // 呼び出し側と同じプロセスで実行
IID_IGraphBuilder, // グラフビルダでオブジェクト間通信する
(void **)&p_graph); // インスタンスを入れるポインタ
// フィルタグラフからIMediaControlを取得する
hr=p_graph->QueryInterface(
IID_IMediaControl, //IMediaControlのインターフェース指定
(void **)&p_control); //IMediaControlを入れるポインタ
// フィルタグラフからIMediaEventを取得する
hr=p_graph->QueryInterface(
IID_IMediaEvent, //IMediaEventのインターフェース指定
(void **)&p_event); //IMediaEventを入れるポインタ
// 再生するファイルを指定する
hr=p_graph->RenderFile(
L"C:\\workdir\\testh.mp3", // メディアファイル名
NULL); // 予約(NULL固定)
// ファイルのレンダリングに成功したらグラフを実行する
if(SUCCEEDED(hr))
{
// グラフを実行する
hr=p_control->Run();
if( hr == S_OK )
{
// グラフの実行に成功したら完了するまでイベントを待つ
p_event->WaitForCompletion(
INFINITE, // イベントタイマー(無期限)
&event_code); // イベント結果コード
}
}
// IMediaControlを開放する
p_control->Release();
// IMediaEventを開放する
p_event->Release();
// フィルタグラフを開放する
p_graph->Release();
// COMライブラリを開放する
CoUninitialize();
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | [
[
[
1,
67
]
]
] |
d3261da4afad51461caba33cf30143f8557b9e2c | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/tlclasses/CMissile.h | 90b9d9d3e93662d3bf149e999689dde8c27cfa11 | [] | no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | #pragma once
#include "CPositionableObject.h"
namespace TLAPI {
#pragma pack(1)
struct CMissile : CPositionableObject
{
/*
PVOID vtable;
u32 unk0;
u64 guid0; // 0C27D3F5149C711DFh
u64 guid1; // 0FFFFFFFFFFFFFFFFh
u64 guid2; // 0C27D3F5149C711DFh
u64 guid3; // 0h
u32 unk1[2]; // 0,0
PVOID unk2;
float unk3; // 0.5
u32 unk4[7];
PVOID pOctree0;
u32 unk5;
PVOID pCResourceManager;
PVOID pOctree1;
PVOID pOctree2;
u32 unk6; // 100h
float unk7[26]; //
u32 unk8[7]; // 0,0,0,0,0,531h,0
PVOID pCParticle[3]; // 3 ptrs to CParticle
*/
};
#pragma pack()
};
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
] | [
[
[
1,
48
]
]
] |
dfa25f64ed4f459640a1229f5b25963cac53b188 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/console/Console_run.cpp | d49fc5f41ce290d2fa9d709b21459702e1268d97 | [] | no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,023 | cpp | #include <iostream>
#include <fstream>
#include <console/Console_run.h>
#include <gui/app/static/Application_settings.h>
#include <gui/app/Settings_table_model.h>
#include <windows.h>
Console_run::Console_run(int argc, char* argv[]) {
std::cout << std::endl << "Mesecina running in console mode..." << std::endl << std::endl;
logger.grab_cout();
this->argc = argc;
this->argv = argv;
}
Console_run::~Console_run() {
logger.release_cout();
}
QString Console_run::path_to_filename(const QString& path) {
return path.right(path.length() - path.lastIndexOf("/") - 1);
}
void Console_run::print_settings(QString start) {
std::cout << "Settings: " << std::endl;
std::vector<Application_setting>::iterator n_it, n_end =Application_settings::settings.end();
for (n_it = Application_settings::settings.begin(); n_it!=n_end; n_it++) {
if (n_it->name.startsWith(start)) {
std::cout << n_it->name.toStdString() << ": " << Application_settings::get_string_setting(n_it->name) << std::endl;
}
}
}
// command line arguments parsing functions
char* Console_run::get_param_variable(int argc, char *argv[], char* filter) {
for (int i=0; i<argc; i++) {
if (strcmp(argv[i], filter)==0 && argc > i+1)
if (i+1 < argc) return argv[i+1]; else return "";
}
return NULL;
}
bool Console_run::assign_int_parameter_if_exists(int argc, char *argv[], char* filter, int &variable) {
char* val = get_param_variable(argc, argv, filter);
if (val) { variable = atoi(val); return true; }
else return false;
}
bool Console_run::assign_float_parameter_if_exists(int argc, char *argv[], char* filter, double &variable) {
char* val = get_param_variable(argc, argv, filter);
if (val) { variable = atof(val); return true; }
else return false;
}
bool Console_run::assign_string_parameter_if_exists(int argc, char *argv[], char* filter, char* &variable) {
char* val = get_param_variable(argc, argv, filter);
if (val) { variable = val; return true; }
else return false;
} | [
"balint.miklos@localhost"
] | [
[
[
1,
57
]
]
] |
94df3fb39853dea261ae30f9c5da13a0f49ed84b | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /depends/ClanLib/src/Core/Text/string_ref16.cpp | 02887964126554733c1bd437a3d15c7ba73e0cdc | [] | no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,834 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "precomp.h"
#include "API/Core/Text/string_ref16.h"
#include "API/Core/Text/string_types.h"
#include "API/Core/Text/string_help.h"
#include "API/Core/System/memory_pool.h"
#ifndef WIN32
#include <string.h>
#endif
CL_StringRef16::CL_StringRef16(const wchar_t *wc_str)
: null_terminated(false), temporary(false)
{
this->data_ptr = (wchar_t *) wc_str;
this->data_length = (size_type) wcslen(wc_str);
}
CL_StringRef16::CL_StringRef16(const wchar_t *wc_str, size_type length, bool null_terminated)
: null_terminated(null_terminated), temporary(false)
{
this->data_ptr = (wchar_t *) wc_str;
this->data_length = length;
}
CL_StringRef16::CL_StringRef16()
: null_terminated(false), temporary(false)
{
}
CL_StringRef16::CL_StringRef16(const std::wstring &source)
: null_terminated(false), temporary(false)
{
this->data_length = source.length();
this->data_ptr = (wchar_t *) source.data();
}
CL_StringRef16::CL_StringRef16(const CL_StringRef16 &source)
: null_terminated(false), temporary(false)
{
this->data_ptr = (wchar_t *) source.data();
this->data_length = source.length();
}
CL_StringRef16::CL_StringRef16(const CL_StringData16 &source)
: null_terminated(false), temporary(false)
{
this->data_ptr = (wchar_t *) source.data();
this->data_length = source.length();
}
CL_StringRef16::CL_StringRef16(const char *c_str)
: null_terminated(false), temporary(false)
{
CL_String16 temp = CL_StringHelp::local8_to_ucs2(c_str);
create_temp(temp.data(), temp.length());
}
CL_StringRef16::CL_StringRef16(const char *c_str, size_type length, bool null_terminated)
: null_terminated(null_terminated), temporary(false)
{
CL_String16 temp = CL_StringHelp::local8_to_ucs2(CL_StringRef8(c_str, length, null_terminated));
create_temp(temp.data(), temp.length());
}
CL_StringRef16::~CL_StringRef16()
{
clear();
}
const wchar_t *CL_StringRef16::c_str() const
{
if (this->data_ptr == 0 && this->data_length == 0)
{
static const wchar_t empty_string[] = { 0 };
return empty_string;
}
if (!null_terminated)
create_temp(this->data_ptr, this->data_length);
return data();
}
void CL_StringRef16::set_length(size_type length)
{
this->data_length = length;
}
CL_StringRef16 &CL_StringRef16::operator =(const CL_StringRef16 &source)
{
if (&source == this)
return *this;
clear();
this->data_ptr = (wchar_t *) source.data();
this->data_length = source.length();
return *this;
}
CL_StringRef16 &CL_StringRef16::operator =(const CL_StringData16 &source)
{
if (&source == this)
return *this;
clear();
this->data_ptr = (wchar_t *) source.data();
this->data_length = source.length();
return *this;
}
CL_StringRef16 &CL_StringRef16::operator =(const char *c_str)
{
CL_String16 temp = CL_StringHelp::local8_to_ucs2(c_str);
create_temp(temp.data(), temp.length());
return *this;
}
CL_StringRef16 &CL_StringRef16::operator =(const wchar_t *c_str)
{
clear();
this->data_ptr = (wchar_t *) c_str;
this->data_length = (size_type) wcslen(c_str);
return *this;
}
void CL_StringRef16::clear() const
{
if (temporary)
CL_MemoryPool::get_temp_pool()->free(this->data_ptr);
temporary = false;
null_terminated = false;
this->data_ptr = 0;
this->data_length = 0;
}
void CL_StringRef16::create_temp(const wchar_t *data, size_type length) const
{
clear();
this->data_ptr = (wchar_t *) CL_MemoryPool::get_temp_pool()->alloc(sizeof(wchar_t) * (length + 1));
this->data_length = length;
memcpy(this->data_ptr, data, sizeof(wchar_t) * this->data_length);
this->data_ptr[this->data_length] = 0;
temporary = true;
null_terminated = true;
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
] | [
[
[
1,
169
]
]
] |
3a17f9320e0d1071fa217126c9dfa82753ac6f2b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/python/test/bienstman1.cpp | de748119beae265c780899f023c6eefc5f2df750 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | cpp | // Copyright David Abrahams 2004. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/reference_existing_object.hpp>
#include <boost/python/return_value_policy.hpp>
struct A {};
struct V
{
virtual void f() = 0;
const A* inside() {return &a;}
A a;
};
const A* outside(const V& v) {return &v.a;}
BOOST_PYTHON_MODULE(bienstman1_ext)
{
using namespace boost::python;
using boost::shared_ptr;
using boost::python::return_value_policy;
using boost::python::reference_existing_object;
class_<A>("A");
class_<V, boost::noncopyable>("V", no_init)
.def("inside", &V::inside,
return_value_policy<reference_existing_object>())
.def("outside", outside,
return_value_policy<reference_existing_object>())
;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
40
]
]
] |
16bd5babf4390b821aca5cbe232687248daf8c54 | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak.Toolkit/PrimitiveInfo.h | c949c0b592816f4de74e5fadc5b08766cb9f8b20 | [] | no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | h | #pragma once
#ifndef __HALAK_TOOLKIT_PRIMITIVEINFO_H__
#define __HALAK_TOOLKIT_PRIMITIVEINFO_H__
# include <Halak.Toolkit/FWD.h>
# include <Halak.Toolkit/TypeInfo.h>
namespace Halak
{
namespace Toolkit
{
class PrimitiveInfo : public TypeInfo
{
private:
PrimitiveInfo(int allocationSize);
virtual ~PrimitiveInfo();
private:
friend class TypeLibrary;
};
}
}
#endif | [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
310ddceb50f13e2f6e6602e51cd17efd930b505c | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/CryEngine/CryCommon/MultiThread.h | a166c96d08aa58bcdc0ec1a9c782a305eb82bf3c | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,400 | h | ////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2005.
// -------------------------------------------------------------------------
// File name: MultiThread.h
// Version: v1.00
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __MultiThread_h__
#define __MultiThread_h__
#pragma once
#define WRITE_LOCK_VAL (1<<16)
//as PowerPC operates via cache line reservation, lock variables should reside ion their own cache line
template <class T>
struct SAtomicVar
{
T val;
inline operator T()const{return val;}
inline operator T()volatile const{return val;}
inline void operator =(const T& rV){val = rV;return *this;}
inline void Assign(const T& rV){val = rV;}
inline void Assign(const T& rV)volatile{val = rV;}
inline T* Addr() {return &val;}
inline volatile T* Addr() volatile {return &val;}
inline bool operator<(const T& v)const{return val < v;}
inline bool operator<(const SAtomicVar<T>& v)const{return val < v.val;}
inline bool operator>(const T& v)const{return val > v;}
inline bool operator>(const SAtomicVar<T>& v)const{return val > v.val;}
inline bool operator<=(const T& v)const{return val <= v;}
inline bool operator<=(const SAtomicVar<T>& v)const{return val <= v.val;}
inline bool operator>=(const T& v)const{return val >= v;}
inline bool operator>=(const SAtomicVar<T>& v)const{return val >= v.val;}
inline bool operator==(const T& v)const{return val == v;}
inline bool operator==(const SAtomicVar<T>& v)const{return val == v.val;}
inline bool operator!=(const T& v)const{return val != v;}
inline bool operator!=(const SAtomicVar<T>& v)const{return val != v.val;}
inline T operator*(const T& v)const{return val * v;}
inline T operator/(const T& v)const{return val / v;}
inline T operator+(const T& v)const{return val + v;}
inline T operator-(const T& v)const{return val - v;}
inline bool operator<(const T& v)volatile const{return val < v;}
inline bool operator<(const SAtomicVar<T>& v)volatile const{return val < v.val;}
inline bool operator>(const T& v)volatile const{return val > v;}
inline bool operator>(const SAtomicVar<T>& v)volatile const{return val > v.val;}
inline bool operator<=(const T& v)volatile const{return val <= v;}
inline bool operator<=(const SAtomicVar<T>& v)volatile const{return val <= v.val;}
inline bool operator>=(const T& v)volatile const{return val >= v;}
inline bool operator>=(const SAtomicVar<T>& v)volatile const{return val >= v.val;}
inline bool operator==(const T& v)volatile const{return val == v;}
inline bool operator==(const SAtomicVar<T>& v)volatile const{return val == v.val;}
inline bool operator!=(const T& v)volatile const{return val != v;}
inline bool operator!=(const SAtomicVar<T>& v)volatile const{return val != v.val;}
inline T operator*(const T& v)volatile const{return val * v;}
inline T operator/(const T& v)volatile const{return val / v;}
inline T operator+(const T& v)volatile const{return val + v;}
inline T operator-(const T& v)volatile const{return val - v;}
}
;
typedef SAtomicVar<int> TIntAtomic;
typedef SAtomicVar<unsigned int> TUIntAtomic;
typedef SAtomicVar<float> TFloatAtomic;
#ifdef __SNC__
#ifndef __add_db16cycl__
#define __add_db16cycl__ __db16cyc();
#endif
#else
#define USE_INLINE_ASM
//#define ADD_DB16_CYCLES
#undef __add_db16cycl__
#ifdef ADD_DB16_CYCLES
#define __add_db16cycl__ __asm__ volatile("db16cyc");
#else
#define __add_db16cycl__
#endif
#endif
#if !defined(__SPU__)
void CrySpinLock(volatile int *pLock,int checkVal,int setVal);
void CryReleaseSpinLock(volatile int*, int);
#if !defined(PS3)
long CryInterlockedIncrement( int volatile *lpAddend );
long CryInterlockedDecrement( int volatile *lpAddend );
long CryInterlockedExchangeAdd(long volatile * lpAddend, long Value);
long CryInterlockedCompareExchange(long volatile * dst, long exchange, long comperand);
void* CryInterlockedCompareExchangePointer(void* volatile * dst, void* exchange, void* comperand);
#endif
void* CryCreateCriticalSection();
void CryCreateCriticalSectionInplace(void*);
void CryDeleteCriticalSection( void *cs );
void CryDeleteCriticalSectionInplace( void *cs );
void CryEnterCriticalSection( void *cs );
bool CryTryCriticalSection( void *cs );
void CryLeaveCriticalSection( void *cs );
ILINE void CrySpinLock(volatile int *pLock,int checkVal,int setVal)
{
#ifdef _CPU_X86
# ifdef __GNUC__
register int val;
__asm__ __volatile__ (
"0: mov %[checkVal], %%eax\n"
" lock cmpxchg %[setVal], (%[pLock])\n"
" jnz 0b"
: "=m" (*pLock)
: [pLock] "r" (pLock), "m" (*pLock),
[checkVal] "m" (checkVal),
[setVal] "r" (setVal)
: "eax", "cc", "memory"
);
# else //!__GNUC__
__asm
{
mov edx, setVal
mov ecx, pLock
Spin:
// Trick from Intel Optimizations guide
#ifdef _CPU_SSE
pause
#endif
mov eax, checkVal
lock cmpxchg [ecx], edx
jnz Spin
}
# endif //!__GNUC__
#else // !_CPU_X86
// NOTE: The code below will fail on 64bit architectures!
while(_InterlockedCompareExchange((volatile long*)pLock,setVal,checkVal)!=checkVal) ;
#endif
}
ILINE void CryReleaseSpinLock(volatile int *pLock,int setVal)
{
*pLock = setVal;
}
//////////////////////////////////////////////////////////////////////////
ILINE void CryInterlockedAdd(volatile int *pVal, int iAdd)
{
#ifdef _CPU_X86
# ifdef __GNUC__
__asm__ __volatile__ (
" lock add %[iAdd], (%[pVal])\n"
: "=m" (*pVal)
: [pVal] "r" (pVal), "m" (*pVal), [iAdd] "r" (iAdd)
);
# else
__asm
{
mov edx, pVal
mov eax, iAdd
lock add [edx], eax
}
# endif
#else
// NOTE: The code below will fail on 64bit architectures!
#if defined(_WIN64)
_InterlockedExchangeAdd((volatile long*)pVal,iAdd);
#else
InterlockedExchangeAdd((volatile long*)pVal,iAdd);
#endif
#endif
}
#endif //__SPU__
//special define to guard SPU driver compilation
#if !defined(JOB_LIB_COMP) && !defined(_SPU_JOB)
ILINE void CryReadLock(volatile int *rw, bool yield)
{
CryInterlockedAdd(rw,1);
#ifdef NEED_ENDIAN_SWAP
volatile char *pw=(volatile char*)rw+1;
{
for(;*pw;);
}
#else
volatile char *pw=(volatile char*)rw+2;
{
for(;*pw;);
}
#endif
}
ILINE void CryReleaseReadLock(volatile int* rw)
{
CryInterlockedAdd(rw,-1);
}
ILINE void CryWriteLock(volatile int* rw)
{
CrySpinLock(rw,0,WRITE_LOCK_VAL);
}
ILINE void CryReleaseWriteLock(volatile int* rw)
{
CryInterlockedAdd(rw,-WRITE_LOCK_VAL);
}
//////////////////////////////////////////////////////////////////////////
struct ReadLock
{
ILINE ReadLock(volatile int &rw)
{
CryInterlockedAdd(prw=&rw,1);
#ifdef NEED_ENDIAN_SWAP
volatile char *pw=(volatile char*)&rw+1; for(;*pw;);
#else
volatile char *pw=(volatile char*)&rw+2; for(;*pw;);
#endif
}
ILINE ReadLock(volatile int &rw, bool yield)
{
CryReadLock(prw=&rw, yield);
}
~ReadLock()
{
CryReleaseReadLock(prw);
}
private:
volatile int *prw;
};
struct ReadLockCond
{
ILINE ReadLockCond(volatile int &rw,int bActive)
{
if (bActive)
{
CryInterlockedAdd(&rw,1);
bActivated = 1;
#ifdef NEED_ENDIAN_SWAP
volatile char *pw=(volatile char*)&rw+1; for(;*pw;);
#else
volatile char *pw=(volatile char*)&rw+2; for(;*pw;);
#endif
}
else
{
bActivated = 0;
}
prw = &rw;
}
void SetActive(int bActive=1) { bActivated = bActive; }
void Release() { CryInterlockedAdd(prw,-bActivated); }
~ReadLockCond()
{
CryInterlockedAdd(prw,-bActivated);
}
private:
volatile int *prw;
int bActivated;
};
//////////////////////////////////////////////////////////////////////////
struct WriteLock
{
ILINE WriteLock(volatile int &rw) { CryWriteLock(&rw); prw=&rw; }
~WriteLock() { CryReleaseWriteLock(prw); }
private:
volatile int *prw;
};
//////////////////////////////////////////////////////////////////////////
struct WriteAfterReadLock
{
ILINE WriteAfterReadLock(volatile int &rw) { CrySpinLock(&rw,1,WRITE_LOCK_VAL+1); prw=&rw; }
~WriteAfterReadLock() { CryInterlockedAdd(prw,-WRITE_LOCK_VAL); }
private:
volatile int *prw;
};
//////////////////////////////////////////////////////////////////////////
struct WriteLockCond
{
ILINE WriteLockCond(volatile int &rw,int bActive=1)
{
if (bActive)
CrySpinLock(&rw,0,iActive=WRITE_LOCK_VAL);
else
iActive = 0;
prw = &rw;
}
ILINE WriteLockCond() { prw=&(iActive=0); }
~WriteLockCond() {
CryInterlockedAdd(prw,-iActive);
}
void SetActive(int bActive=1) { iActive = -bActive & WRITE_LOCK_VAL; }
void Release() { CryInterlockedAdd(prw,-iActive); }
volatile int *prw;
int iActive;
};
//////////////////////////////////////////////////////////////////////////
#endif//JOB_LIB_COMP
#endif // __MultiThread_h__
| [
"[email protected]"
] | [
[
[
1,
908
]
]
] |
0ade3d1c0cfe7a73bbf4d2c3d689bdf082fd049a | 9756190964e5121271a44aba29a5649b6f95f506 | /SimpleParam/Param/src/Numerical/MatrixConverter.cpp | 9e8f5f86812e6a77c2f6a4a25cdca670c3d477c4 | [] | no_license | feengg/Parameterization | 40f71bedd1adc7d2ccbbc45cc0c3bf0e1d0b1103 | f8d2f26ff83d6f53ac8a6abb4c38d9b59db1d507 | refs/heads/master | 2020-03-23T05:18:25.675256 | 2011-01-21T15:19:08 | 2011-01-21T15:19:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,222 | cpp | #include "MatrixConverter.h"
//////////////////////////////////////////////////////////////////////
// CMatrixConverter Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMatrixConverter::CMatrixConverter()
{
}
CMatrixConverter::~CMatrixConverter()
{
}
//////////////////////////////////////////////////////////////////////
// CMatrixConverter public methods
//////////////////////////////////////////////////////////////////////
void CMatrixConverter::CSparseMatrix2hjMatrix(matrix<double>& hjMatrix, CMeshSparseMatrix& csMatrix)
{
size_t row = csMatrix.GetRowNum();
size_t col = csMatrix.GetColNum();
hjMatrix = zeros<double>(row, col);
for (size_t i = 0; i < csMatrix.m_ColIndex.size(); i++)
{
IndexArray& colIndex = csMatrix.m_ColIndex[i];
for (size_t j = 0; j < colIndex.size(); j++)
{
hjMatrix(colIndex[j], i) = csMatrix.m_ColData[i][j];
}
}
// for (size_t i = 0; i < row; i++)
// {
// for (size_t j = 0; j < col; j++)
// {
// csMatrix.GetElement(i, j, value);
// hjMatrix(i, j) = value;
// }
// }
}
void CMatrixConverter::HjMatrix2CMatrix(matrix<double>& hjMatrix, CMatrix& cMatrix)
{
size_t row = hjMatrix.size(1);
size_t col = hjMatrix.size(2);
cMatrix.Init(row, col);
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
cMatrix.SetElement(i, j, hjMatrix(i, j));
}
}
}
void CMatrixConverter::CSparseMatrix2hjCscMatrix(hj::sparse::spm_csc<double>& hjcscMatrix, CMeshSparseMatrix& cMatrix)
{
/*
matrix<double> hjMatrix;
hj::sparse::spm_csc<double> cscMatrix;
CSparseMatrix2hjMatrix(hjMatrix, cMatrix);
hj::sparse::convert(hjMatrix, hjcscMatrix, SMALL_ZERO_EPSILON);
return;*/
//
cMatrix.MakeMatrixIndexLessSeq();
int i;
int m_Row = cMatrix.GetRowNum();
int m_Col = cMatrix.GetColNum();
int nnz = cMatrix.GetNZNum();
hjcscMatrix.resize(m_Row, m_Col, nnz);
//
int index = 0;
double value = 0;
for(i = 0; i < m_Col; ++ i)
{
(hjcscMatrix.ptr_)[i] = index;
size_t n = cMatrix.m_ColIndex[i].size();
for(size_t j = 0; j < n; ++ j)
{
(hjcscMatrix.idx_)[index] = cMatrix.m_ColIndex[i][j];
(hjcscMatrix.val_)[index ++] = cMatrix.m_ColData[i][j];
}
}
hjcscMatrix.ptr_[i] = nnz;
/*
// debug.
matrix<double> hjMatrix;
hj::sparse::spm_csc<double> cscMatrix;
CSparseMatrix2hjMatrix(hjMatrix, cMatrix);
hj::sparse::convert(hjMatrix, cscMatrix, SMALL_ZERO_EPSILON);
for(size_t i = 0; i < hjcscMatrix.idx_.size(); i++)
{
ASSERT(cscMatrix.idx_[i] == hjcscMatrix.idx_[i]);
}
for(size_t i = 0; i < hjcscMatrix.ptr_.size(); i++)
{
ASSERT(cscMatrix.ptr_[i] == hjcscMatrix.ptr_[i]);
}
for(size_t i = 0; i < hjcscMatrix.val_.size(); i++)
{
ASSERT(cscMatrix.val_[i] == hjcscMatrix.val_[i]);
}*/
}
void CMatrixConverter::CMatrix2hjMatrix(matrix<double>& hjMatrix, CMatrix& cMatrix)
{
size_t row = cMatrix.GetNumRows();
size_t col = cMatrix.GetNumColumns();
hjMatrix.resize(row, col);
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
hjMatrix(i, j) = cMatrix.GetElement(i, j);
}
}
} | [
"[email protected]"
] | [
[
[
1,
133
]
]
] |
df7d89a6aadb624255fed4e621f997a6a6f66669 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /older/tptest5/src/DialogAbout.cpp | 661eb2c5dae67aadb39ac6638d49efef7b92df97 | [] | no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,124 | cpp | #include "DialogAbout.h"
#include <wx/mimetype.h>
#include <wx/filefn.h>
BEGIN_EVENT_TABLE( DialogAbout, wxDialog )
EVT_PAINT(DialogAbout::OnPaint)
EVT_LEFT_DOWN(DialogAbout::OnLeftDown)
END_EVENT_TABLE()
#ifdef UNIX
#define DA_WIDTH 500
#define DA_HEIGHT 600
#endif
#ifdef WIN32
#define DA_WIDTH 420
#define DA_HEIGHT 600
#endif
DialogAbout::DialogAbout(wxWindow *parent)
: wxDialog(parent, wxID_ANY, wxString(wxT("Om TPTEST 5")), wxDefaultPosition, wxSize( DA_WIDTH, DA_HEIGHT ) )
{
m_Sizer = new wxGridBagSizer( 5, 5 );
wxImage::AddHandler( new wxJPEGHandler );
wxImage logo;
if( wxFile::Exists( wxT("GHNlogo.jpg") ) &&
logo.LoadFile(wxT("GHNlogo.jpg"), wxBITMAP_TYPE_JPEG ) )
{
m_ghnLogo = new wxBitmap( logo );
}
else
{
wxMessageDialog( this, wxT("Could not load GHN logo!") ) ;
this->m_ghnLogo = NULL;
}
wxString strAbout;
strAbout << TPTEST_VERSION_STRING << wxT("\n\n");
strAbout << wxT("TPTEST 5 är utvecklat av Gatorhole AB (www.gatorhole.com)") << wxT("\n");
strAbout << wxT("på uppdrag av II-Stiftelsen (www.iis.se), Konsumentverket (www.kov.se)") << wxT("\n");
strAbout << wxT("och Post- och Telestyrelsen (www.pts.se).") << wxT("\n\n");
strAbout << wxT("Stiftelsen Internetinfrastruktur (II-stiftelsen), Konsumentverket, \n");
strAbout << wxT("Post- och Telestyrelsen, IT-kommissionen, IP Performance Sverige AB,\n");
strAbout << wxT("Autonomica AB eller Netnod Internet Exchange AB ansvarar inte för att de\n");
strAbout << wxT("testresultat som levereras av TPTEST är korrekta. Stiftelsen \n");
strAbout << wxT("Internetinfrastruktur (II-stiftelsen), Konsumentverket, Post- och Telestyrelsen,\n");
strAbout << wxT("IT-kommissionen, IP Performance Sverige AB, Autonomica AB eller Netnod\n");
strAbout << wxT("Internet Exchange AB ansvarar inte för driftsäkerhet och tillgänglighet avseende\n");
strAbout << wxT("mätservrar eller masterserver, och inte heller för att TPTEST fortlöpande finns\n");
strAbout << wxT("tillgängligt, för att det fortlöpande finns användarstöd eller för uppdateringar\n");
strAbout << wxT("av programmet.\n");
strAbout << wxT("\n");
strAbout << wxT("Varje användare ansvarar själv för att programmet är korrekt konfigurerat för den\n");
strAbout << wxT("egna datorn. Stiftelsen Internetinfrastruktur (II-stiftelsen), Konsumentverket,\n");
strAbout << wxT("Post- och Telestyrelsen, IT-kommissionen, IP Performance Sverige AB, \n");
strAbout << wxT("Autonomica AB eller Netnod Internet Exchange AB tar inte ansvar för \n");
strAbout << wxT("klientprogrammets funktion i den individuella driftmiljön eller för fel som\n");
strAbout << wxT("programmet orsakar i operativsystem, andra applikationer eller hårdvara, inte\n");
strAbout << wxT("heller för skada som användaren orsakar på andra datorer genom användningen \n");
strAbout << wxT("av TPTEST.");
m_stxtAbout =
new wxStaticText( this,
-1,
strAbout,
wxDefaultPosition,
wxDefaultSize,
wxALIGN_CENTRE );
m_btnOk = new wxButton(this, wxID_CANCEL, wxT("&Ok") );
m_Sizer->Add( m_stxtAbout, wxGBPosition( 0, 0 ), wxDefaultSpan, wxALIGN_CENTER | wxALL, 10 );
m_Sizer->Add( m_btnOk, wxGBPosition( 1, 0 ), wxDefaultSpan, wxALIGN_CENTER | wxALL, 10 );
this->SetSizer( m_Sizer );
m_Sizer->SetSizeHints( this );
}
DialogAbout::~DialogAbout(void)
{
delete m_ghnLogo;
delete m_stxtAbout;
delete m_btnOk;
}
void DialogAbout::OnLeftDown( wxMouseEvent &event )
{
if( event.m_x > 320 &&
event.m_x < 400 &&
event.m_y > 330 &&
event.m_y < 354 )
{
wxString strHelpURL = wxT("http://www.ghn.se");
wxMimeTypesManager manager;
wxFileType * filetype = manager.GetFileTypeFromExtension( wxT("html") );
wxString command = filetype->GetOpenCommand( strHelpURL );
wxExecute(command);
}
event.Skip();
}
void DialogAbout::OnPaint( wxPaintEvent &WXUNUSED(event) )
{
wxPaintDC dc(this);
if( this->m_ghnLogo != NULL )
{
dc.DrawBitmap( *this->m_ghnLogo, 320, 330 );
}
}
| [
"[email protected]"
] | [
[
[
1,
118
]
]
] |
d943bdd4db8df7f7224285dd3d93b0121b9c3835 | 1c7a59d0c11a63605e234e8d4b01365cc3ae1090 | /include/Viewer/PickHandler.h | 0b428ccdcd1aa7d72515634ba9999ea7708d3469 | [] | no_license | TomasHurban/3dsoftviz | 67cc0bec79778a8ba955df3e2403b8df486a14c3 | d94719599abedba86d449bbee6a6bc74333e37a1 | refs/heads/master | 2021-01-24T05:25:05.776927 | 2010-12-04T22:17:48 | 2010-12-04T22:17:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,892 | h | /**
* PickHandler.h
* Projekt 3DVisual
*/
#ifndef VIEWER_PICK_HANDLER_DEF
#define VIEWER_PICK_HANDLER_DEF 1
#include <osgGA/GUIEventHandler>
#include <osgGA/GUIEventAdapter>
#include <osgGA/GUIActionAdapter>
#include <osgViewer/Viewer>
#include <osg/ref_ptr>
#include <osg/Geode>
#include <osg/StateSet>
#include <osg/Vec3f>
#include "Data/Node.h"
#include "Data/Edge.h"
#include "Viewer/CameraManipulator.h"
#include "Viewer/CoreGraph.h"
#include <QLinkedList>
namespace Vwr
{
/**
* \class PickHandler
* \brief Handles picking events
* \author Michal Paprcka
* \date 29. 4. 2010
*/
class PickHandler : public QObject, public osgGA::GUIEventHandler
{
Q_OBJECT
public:
/**
* \class PickMode
* \brief Picking modes
* \author Michal Paprcka
* \date 29. 4. 2010
*/
class PickMode
{
public:
/**
* const int NONE
* \brief no picking
*/
static const int NONE = 0;
/**
* const int SINGLE
* \brief picking single object
*/
static const int SINGLE = 1;
/**
* const int MULTI
* \brief multiobject picking
*/
static const int MULTI = 2;
};
/**
* \class SelectionType
* \brief Selection types
* \author Michal Paprcka
* \date 29. 4. 2010
*/
class SelectionType
{
public:
/**
* const int ALL
* \brief picking all
*/
static const int ALL = 0;
/**
* const int NODE
* \brief picking nodes
*/
static const int NODE = 1;
/**
* const int EDGE
* \brief picking edges
*/
static const int EDGE = 2;
};
/**
* \fn public constructor PickHandler(Vwr::CameraManipulator * cameraManipulator, Vwr::CoreGraph * coreGraph)
* \brief Creates picking handler
* \param cameraManipulator camera manipulator
* \param coreGraph core graph
*/
PickHandler(Vwr::CameraManipulator * cameraManipulator, Vwr::CoreGraph * coreGraph);
/**
* \fn public virtual handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief Handles events
* \param ea const event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn public toggleSelectedNodesFixedState(bool isFixed)
* \brief Sets fixed state to picked nodes
* \param isFixed fixed state
*/
void toggleSelectedNodesFixedState(bool isFixed);
/**
* \fn inline public setPickMode( int pickMode )
* \brief Sets pick mode
* \param pickMode
*/
void setPickMode( int pickMode ) { this->pickMode = pickMode; }
/**
* \fn inline public setSelectionType( int selectionType )
* \brief Sets selection type
* \param selectionType
*/
void setSelectionType( int selectionType ) { this->selectionType = selectionType; }
/**
* \fn inline public constant getSelectionType
* \brief Returns selection type
* \return int selection type
*/
int getSelectionType() const { return selectionType; }
/**
* \fn public getSelectionCenter(bool nodesOnly)
* \brief Returns selection mass center
* \param nodesOnly if true, mass will be calculated form nodes only
* \return osg::Vec3
*/
osg::Vec3 getSelectionCenter(bool nodesOnly);
/**
* \fn inline public getSelectedNodes
* \brief Returns selected nodes
* \return QLinkedList<osg::ref_ptr<Data::Node> > * selected nodes
*/
QLinkedList<osg::ref_ptr<Data::Node> > * getSelectedNodes() { return &pickedNodes; }
/**
* \fn inline public getSelectedEdges
* \brief Returns selected edges
* \return QLinkedList<osg::ref_ptr<Data::Edge> > * selected edges
*/
QLinkedList<osg::ref_ptr<Data::Edge> > * getSelectedEdges() { return &pickedEdges; }
protected:
// Store mouse xy location for button press & move events.
float _mX,_mY;
float origin_mX, origin_mY, origin_mX_normalized, origin_mY_normalized;
/**
* bool leftButtonPressed
* \brief true, if left mouse button pressed
*/
bool leftButtonPressed;
// Perform a pick operation.
bool pick(const double xMin, const double yMin, const double xMax, const double yMax, osgViewer::Viewer* viewer);
private:
/**
* Vwr::CameraManipulator * cameraManipulator
* \brief camera manipulator
*/
Vwr::CameraManipulator * cameraManipulator;
/**
* Vwr::CoreGraph * coreGraph
* \brief core graph
*/
Vwr::CoreGraph * coreGraph;
/**
* Util::ApplicationConfig * appConf
* \brief application configuration
*/
Util::ApplicationConfig * appConf;
/**
* QLinkedList<osg::ref_ptr<Data::Node> > pickedNodes
* \brief picked nodes list
*/
QLinkedList<osg::ref_ptr<Data::Node> > pickedNodes;
/**
* QLinkedList<osg::ref_ptr<Data::Edge> > pickedEdges
* \brief picked edges list
*/
QLinkedList<osg::ref_ptr<Data::Edge> > pickedEdges;
/**
* osg::ref_ptr group
* \brief custom node group
*/
osg::ref_ptr<osg::Group> group;
/**
* bool isCtrlPressed
* \brief true, if ctrl was pressed
*/
bool isCtrlPressed;
/**
* bool isShiftPressed
* \brief true, if shift was pressed
*/
bool isShiftPressed;
/**
* bool isAltPressed
* \brief true, if alt was pressed
*/
bool isAltPressed;
/**
* bool isDrawingSelectionQuad
* \brief true, if selection quad is benign drawn
*/
bool isDrawingSelectionQuad;
/**
* bool isDragging
* \brief true, if user is dragging mouse
*/
bool isDragging;
/**
* bool isManipulatingNodes
* \brief true, if user is manipulating nodes
*/
bool isManipulatingNodes;
/**
* osg::ref_ptr<osg::Geode> selectionQuad
* \brief selection quad geode
*/
osg::ref_ptr<osg::Geode> selectionQuad;
/**
* \fn private doSinglePick(osg::NodePath nodePath, unsigned int primitiveIndex)
* \brief Picks single object on screen
* \param nodePath pick nodepath
* \param primitiveIndex picked primitive index
* \return bool true, if object was picked
*/
bool doSinglePick(osg::NodePath nodePath, unsigned int primitiveIndex);
/**
* \fn private doNodePick(osg::NodePath nodePath)
* \brief Picks single node
* \param nodePath pick nodepath
* \return bool true, if node was picked
*/
bool doNodePick(osg::NodePath nodePath);
/**
* \fn private doEdgePick(osg::NodePath nodePath, unsigned int primitiveIndex)
* \brief Picks single edge
* \param nodePath pick nodepath
* \param primitiveIndex picked primitive index
* \return bool
*/
bool doEdgePick(osg::NodePath nodePath, unsigned int primitiveIndex);
/**
* \fn private dragNode(osgViewer::Viewer * viewer)
* \brief Drags selected nodes
* \param viewer current viewer
* \return bool true, if nodes were dragged
*/
bool dragNode(osgViewer::Viewer * viewer);
/**
* int pickMode
* \brief current pick mode
*/
int pickMode;
/**
* int selectionType
* \brief current selection type
*/
int selectionType;
/**
* \fn private drawSelectionQuad(float origin_mX, float origin_mY, osgViewer::Viewer * viewer)
* \brief draws selection quad
* \param origin_mX star position
* \param origin_mY end position
* \param viewer current viewer
*/
void drawSelectionQuad(float origin_mX, float origin_mY, osgViewer::Viewer * viewer);
/**
* \fn private unselectPickedNodes(osg::ref_ptr<Data::Node> node = 0)
* \brief unselects picked nodes. If null, all nodes will be unselected.
* \param node nodes to unselect
*/
void unselectPickedNodes(osg::ref_ptr<Data::Node> node = 0);
/**
* \fn private unselectPickedEdges(osg::ref_ptr<Data::Edge> edge = 0)
* \brief unselects picked edges. If null, all edges will be unselected.
* \param edge edges to unselect
*/
void unselectPickedEdges(osg::ref_ptr<Data::Edge> edge = 0);
/**
* \fn private setSelectedNodesInterpolation(bool state)
* \brief sets interpolation state to selected nodes
* \param state interpolation state
*/
void setSelectedNodesInterpolation(bool state);
/**
* \fn private handlePush( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles push event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handlePush( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleDoubleclick( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles doubleclick event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleDoubleclick( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleDrag( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles drag event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleDrag( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleMove( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles move event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleMove( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleRelease( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles release event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleRelease( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleKeyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles keyup event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleKeyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* \fn private handleKeyDown( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
* \brief handles keydown event
* \param ea event adapter
* \param aa action adapter
* \return bool true, if event was handled
*/
bool handleKeyDown( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa );
/**
* const osgGA::GUIEventAdapter * eaPush
* \brief variable for storing event for detecting double click
*/
const osgGA::GUIEventAdapter * eaPush;
/**
* const osgGA::GUIEventAdapter * eaRel
* \brief variable for storing event for detecting double click
*/
const osgGA::GUIEventAdapter * eaRel;
/**
* osgGA::GUIActionAdapter * aaPush
* \brief variable for storing event for detecting double click
*/
osgGA::GUIActionAdapter * aaPush;
/**
* osgGA::GUIActionAdapter * aaRel
* \brief variable for storing event for detecting double click
*/
osgGA::GUIActionAdapter * aaRel;
/**
* QTimer timer
* \brief timer for detecting double click
*/
QTimer * timer;
public slots:
/**
* \fn public mouseTimerTimeout
* \brief called when user don't double click
*/
void mouseTimerTimeout();
};
}
#endif
| [
"kapec@genepool.(none)"
] | [
[
[
1,
456
]
]
] |
5c751e72b640cccd1b8c56ac3d2400322f6edeb6 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/ControllerQt/Visualization/HeaderedWidget.h | 34659fa45e78a3c0828bf64cf902b173185907ca | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,363 | h | /**
* @file HeaderedWidget.h
* Declaration of class HeaderedWidget.
*
* @author Colin Graf
*/
#ifndef HeaderedWidget_H
#define HeaderedWidget_H
#include <QScrollArea>
class QHeaderView;
class QScrollArea;
class QBoxLayout;
class QStandardItemModel;
/**
* @class HeaderedWidget
*
* Defines a QWidget that contains a QHeaderView and another QWidget
*/
class HeaderedWidget : public QScrollArea
{
public:
/**
* Constructor.
* @param parent The parent widget.
* @param f Some window flags.
*/
HeaderedWidget(QWidget* parent = 0);
/**
* Sets the content Widget of this HeaderedWidget.
* @param widget The widget.
*/
void setWidget(QWidget* widget);
/**
* Returns the header view of this widget.
* @return The header view.
*/
QHeaderView* getHeaderView();
/**
* Sets the header labels of the header view.
* @param headerLabels A list of column descriptions.
* @param aligns The align of each label (e.g. "lrrcrr") or 0.
*/
void setHeaderLabels(const QStringList& headerLabels, const char* aligns = 0);
protected:
QHeaderView* headerView; /**< The header view. */
QStandardItemModel* headerItemModel; /**< A simple item model for the header view. */
virtual void resizeEvent(QResizeEvent* event);
virtual QSize sizeHint () const;
};
#endif
| [
"alon@rogue.(none)"
] | [
[
[
1,
63
]
]
] |
0012f4b958cc5f25361790a2a9f0c052752ceb5a | 1e01b697191a910a872e95ddfce27a91cebc57dd | /Scripts/Tutorial/GettingStarted/Cpp/Planet.cpp | db03e5adb92cc0ca4478b3be637dd647c716a93a | [] | no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | //note: Visual C++-specific pragma must be added to prevent from intempestive warnings
//note: about template class instantiation of \samp{std::vector<\textit{T}>} in DEBUG mode!
#ifdef WIN32
#pragma warning(disable : 4786)
#endif
//##protect##"include files"
//##protect##"include files"
#include "Planet.h"
Planet::Planet() : _dDiameter(0.0) {
}
Planet::~Planet() {
}
double Planet::getDistanceToSun(int iDay, int iMonth, int iYear) {
//##protect##"getDistanceToSun.int.int.int"
//##protect##"getDistanceToSun.int.int.int"
}
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
] | [
[
[
1,
21
]
]
] |
a86f1013867fa126445a95bf4491a12db68399f0 | 927e18c69355c4bf87b59dffefe59c2974e86354 | /super-go-proj/SgPointArray.h | 32309fcdf5ff40685bd824975ea0e63ba1a05683 | [] | no_license | lqhl/iao-gim-ca | 6fc40adc91a615fa13b72e5b4016a8b154196b8f | f177268804d1ba6edfd407fa44a113a44203ec30 | refs/heads/master | 2020-05-18T17:07:17.972573 | 2011-06-17T03:54:51 | 2011-06-17T03:54:51 | 32,191,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,895 | h | //----------------------------------------------------------------------------
/** @file SgPointArray.h
Array indexed by points. */
//----------------------------------------------------------------------------
#ifndef SG_POINTARRAY_H
#define SG_POINTARRAY_H
#include <iomanip>
#include <iostream>
#include <sstream>
#include "SgArray.h"
#include "SgPoint.h"
//----------------------------------------------------------------------------
/** An array of SG_MAXPOINT values of type T, indexed by SgPoint.
Also enforces that all elements are initialized in the constructor,
either with T(0), if T can be constructed in such a way or be providing
an initialization value. */
template<class T>
class SgPointArray
: public SgArray<T,SG_MAXPOINT>
{
public:
/** Constructor; values are initialized by default value. */
SgPointArray();
/** Constructor; values are initialized by init value. */
SgPointArray(const T& value);
/** Constructor; initialized as copy of other point array. */
SgPointArray(const SgPointArray& pointArray);
};
template<class T>
inline SgPointArray<T>::SgPointArray()
{
}
template<class T>
inline SgPointArray<T>::SgPointArray(const T& value)
: SgArray<T,SG_MAXPOINT>(value)
{
}
template<class T>
inline SgPointArray<T>::SgPointArray(const SgPointArray& pointArray)
: SgArray<T,SG_MAXPOINT>(pointArray)
{
}
//----------------------------------------------------------------------------
/** Write a point array.
Computes the maximum string representation length of each element in the
array to write out aligned columns with minimum space in between. */
template<typename T>
class SgWritePointArray
{
public:
SgWritePointArray(const SgPointArray<T>& array, SgGrid boardSize)
: m_boardSize(boardSize),
m_array(array)
{
}
std::ostream& Write(std::ostream& out) const;
private:
SgGrid m_boardSize;
const SgPointArray<T>& m_array;
};
template<typename T>
std::ostream& SgWritePointArray<T>::Write(std::ostream& out) const
{
std::ostringstream buffer;
int maxLength = 0;
for (SgGrid row = 1; row <= m_boardSize; ++row)
for (SgGrid col = 1; col <= m_boardSize; ++col)
{
buffer.str("");
buffer << m_array[SgPointUtil::Pt(col, row)];
int length = static_cast<int>(buffer.str().length());
maxLength = std::max(maxLength, length);
}
for (SgGrid row = m_boardSize; row >= 1; --row)
{
for (SgGrid col = 1; col <= m_boardSize; ++col)
{
SgPoint point = SgPointUtil::Pt(col, row);
out << std::setw(maxLength) << m_array[point];
if (col < m_boardSize)
out << ' ';
}
out << '\n';
}
return out;
}
/** @relatesalso SgWritePointArray */
template<typename T>
std::ostream& operator<<(std::ostream& out,
const SgWritePointArray<T>& write)
{
return write.Write(out);
}
//----------------------------------------------------------------------------
/** Write a float point array.
Enhanced version of SgWritePointArray for float or double types.
Allows to specify some formatting options for floating point numbers. */
template<typename FLOAT>
class SgWritePointArrayFloat
{
public:
SgWritePointArrayFloat(const SgPointArray<FLOAT>& array, SgGrid boardSize,
bool fixed, int precision)
: m_fixed(fixed),
m_precision(precision),
m_boardSize(boardSize),
m_array(array)
{
}
std::ostream& Write(std::ostream& out) const;
private:
bool m_fixed;
int m_precision;
SgGrid m_boardSize;
const SgPointArray<FLOAT>& m_array;
};
template<typename FLOAT>
std::ostream& SgWritePointArrayFloat<FLOAT>::Write(std::ostream& out) const
{
SgPointArray<std::string> stringArray;
std::ostringstream buffer;
if (m_fixed)
buffer << std::fixed;
buffer << std::setprecision(m_precision);
for (SgGrid row = 1; row <= m_boardSize; ++row)
for (SgGrid col = 1; col <= m_boardSize; ++col)
{
buffer.str("");
SgPoint p = SgPointUtil::Pt(col, row);
buffer << m_array[p];
stringArray[p] = buffer.str();
}
out << SgWritePointArray<std::string>(stringArray, m_boardSize);
return out;
}
/** @relatesalso SgWritePointArrayFloat */
template<typename FLOAT>
std::ostream& operator<<(std::ostream& out,
const SgWritePointArrayFloat<FLOAT>& write)
{
return write.Write(out);
}
//----------------------------------------------------------------------------
#endif // SG_POINTARRAY_H
| [
"[email protected]"
] | [
[
[
1,
171
]
]
] |
543140bcd2444536a5d6cb36462c3fb124466f15 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/lambda/test/constructor_tests.cpp | 777af3f6097ef85d5aeece0885a449705ad5698f | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,501 | cpp | // constructor_tests.cpp -- The Boost Lambda Library ------------------
//
// Copyright (C) 2000-2003 Jaakko Järvi ([email protected])
// Copyright (C) 2000-2003 Gary Powell ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see www.boost.org
// -----------------------------------------------------------------------
#include <boost/test/minimal.hpp> // see "Header Implementation Option"
#include "boost/lambda/lambda.hpp"
#include "boost/lambda/bind.hpp"
#include "boost/lambda/construct.hpp"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace boost::lambda;
using namespace std;
template<class T>
bool check_tuple(int n, const T& t)
{
return (t.get_head() == n) && check_tuple(n+1, t.get_tail());
}
template <>
bool check_tuple(int n, const null_type& ) { return true; }
void constructor_all_lengths()
{
bool ok;
ok = check_tuple(
1,
bind(constructor<tuple<int> >(),
1)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int> >(),
1, 2)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int> >(),
1, 2, 3)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int> >(),
1, 2, 3, 4)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int, int> >(),
1, 2, 3, 4, 5)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7, 8)()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
bind(constructor<tuple<int, int, int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7, 8, 9)()
);
BOOST_TEST(ok);
}
void new_ptr_all_lengths()
{
bool ok;
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int> >(),
1))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int> >(),
1, 2))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int> >(),
1, 2, 3))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int> >(),
1, 2, 3, 4))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int, int> >(),
1, 2, 3, 4, 5))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7, 8))()
);
BOOST_TEST(ok);
ok = check_tuple(
1,
*(bind(new_ptr<tuple<int, int, int, int, int, int, int, int, int> >(),
1, 2, 3, 4, 5, 6, 7, 8, 9))()
);
BOOST_TEST(ok);
}
class is_destructor_called {
bool& b;
public:
is_destructor_called(bool& bb) : b(bb) { b = false; }
~is_destructor_called() { b = true; }
};
void test_destructor ()
{
char space[sizeof(is_destructor_called)];
bool flag;
is_destructor_called* idc = new(space) is_destructor_called(flag);
BOOST_TEST(flag == false);
bind(destructor(), _1)(idc);
BOOST_TEST(flag == true);
idc = new(space) is_destructor_called(flag);
BOOST_TEST(flag == false);
bind(destructor(), _1)(*idc);
BOOST_TEST(flag == true);
}
class count_deletes {
public:
static int count;
~count_deletes() { ++count; }
};
int count_deletes::count = 0;
void test_news_and_deletes ()
{
int* i[10];
for_each(i, i+10, _1 = bind(new_ptr<int>(), 2));
int count_errors = 0;
for_each(i, i+10, (*_1 == 2) || ++var(count_errors));
BOOST_TEST(count_errors == 0);
count_deletes* ct[10];
for_each(ct, ct+10, _1 = bind(new_ptr<count_deletes>()));
count_deletes::count = 0;
for_each(ct, ct+10, bind(delete_ptr(), _1));
BOOST_TEST(count_deletes::count == 10);
}
void test_array_new_and_delete()
{
count_deletes* c;
(_1 = bind(new_array<count_deletes>(), 5))(c);
count_deletes::count = 0;
bind(delete_array(), _1)(c);
BOOST_TEST(count_deletes::count == 5);
}
void delayed_construction()
{
vector<int> x(3);
vector<int> y(3);
fill(x.begin(), x.end(), 0);
fill(y.begin(), y.end(), 1);
vector<pair<int, int> > v;
transform(x.begin(), x.end(), y.begin(), back_inserter(v),
bind(constructor<pair<int, int> >(), _1, _2) );
}
int test_main(int, char *[]) {
constructor_all_lengths();
new_ptr_all_lengths();
delayed_construction();
test_destructor();
test_news_and_deletes();
test_array_new_and_delete();
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
261
]
]
] |
ea168bf0c7153be3e3a75e6f5bdc5310a0aabcba | 63fc6506b8e438484a013b3c341a1f07f121686b | /addons/ofxVectorMath/src/ofxVec2f.h | 4827d5548651df9f6ab1757aae6accfbd7ba3d03 | [] | no_license | progen/ofx-dev | c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8 | 45125fcab657715abffc7e84819f8097d594e28c | refs/heads/master | 2021-01-20T07:15:39.755316 | 2009-03-03T22:33:37 | 2009-03-03T22:33:37 | 140,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,993 | h | #ifndef _OFX_VEC2f
#define _OFX_VEC2f
#include "ofConstants.h"
class ofxVec2f : public ofPoint {
public:
ofxVec2f( float _x=0.0f, float _y=0.0f ) {
x = _x;
y = _y;
}
// Getters and Setters.
//
//
void set( float _x, float _y ) {
x = _x;
y = _y;
}
void set( const ofPoint& vec ) {
x = vec.x;
y = vec.y;
}
float &operator[]( const int& i ) {
switch(i) {
case 0: return x;
case 1: return y;
default: return x;
}
}
// Check similarity/equality.
//
//
bool operator==( const ofPoint& vec ) {
return (x == vec.x) && (y == vec.y);
}
bool operator!=( const ofPoint& vec ) {
return (x != vec.x) || (y != vec.y);
}
bool match( const ofPoint& vec, float tollerance=0.0001 ) {
return (fabs(x - vec.x) < tollerance)
&& (fabs(y - vec.y) < tollerance);
}
/**
* Checks if vectors look in the same direction.
* Tollerance is specified in degree.
*/
bool align( const ofxVec2f& vec, float tollerance=0.0001 ) const {
return fabs( this->angle( vec ) ) < tollerance;
}
// Overloading for any type to any type
//
//
void operator=( const ofPoint& vec ){
x = vec.x;
y = vec.y;
}
ofxVec2f operator+( const ofPoint& vec ) const {
return ofxVec2f( x+vec.x, y+vec.y);
}
ofxVec2f& operator+=( const ofPoint& vec ) {
x += vec.x;
y += vec.y;
return *this;
}
ofxVec2f operator-( const ofPoint& vec ) const {
return ofxVec2f(x-vec.x, y-vec.y);
}
ofxVec2f& operator-=( const ofPoint& vec ) {
x -= vec.x;
y -= vec.y;
return *this;
}
ofxVec2f operator*( const ofPoint& vec ) const {
return ofxVec2f(x*vec.x, y*vec.y);
}
ofxVec2f& operator*=( const ofPoint& vec ) {
x*=vec.x;
y*=vec.y;
return *this;
}
ofxVec2f operator/( const ofPoint& vec ) const {
return ofxVec2f( vec.x!=0 ? x/vec.x : x , vec.y!=0 ? y/vec.y : y);
}
ofxVec2f& operator/=( const ofPoint& vec ) {
vec.x!=0 ? x/vec.x : x;
vec.y!=0 ? y/vec.y : y;
return *this;
}
//operator overloading for float
//
//
void operator=( const float f){
x = f;
y = f;
}
ofxVec2f operator+( const float f ) const {
return ofxVec2f( x+f, y+f);
}
ofxVec2f& operator+=( const float f ) {
x += f;
y += f;
return *this;
}
ofxVec2f operator-( const float f ) const {
return ofxVec2f( x-f, y-f);
}
ofxVec2f& operator-=( const float f ) {
x -= f;
y -= f;
return *this;
}
ofxVec2f operator-() const {
return ofxVec2f(-x, -y);
}
ofxVec2f operator*( const float f ) const {
return ofxVec2f(x*f, y*f);
}
ofxVec2f& operator*=( const float f ) {
x*=f;
y*=f;
return *this;
}
ofxVec2f operator/( const float f ) const {
if(f == 0) return ofxVec2f(x, y);
return ofxVec2f(x/f, y/f);
}
ofxVec2f& operator/=( const float f ) {
if(f == 0) return *this;
x/=f;
y/=f;
return *this;
}
ofxVec2f rescaled( const float length ) const {
float l = (float)sqrt(x*x + y*y);
if( l > 0 )
return ofxVec2f( (x/l)*length, (y/l)*length );
else
return ofxVec2f();
}
ofxVec2f& rescale( const float length ) {
float l = (float)sqrt(x*x + y*y);
if (l > 0) {
x = (x/l)*length;
y = (y/l)*length;
}
return *this;
}
// Rotation
//
//
ofxVec2f rotated( float angle ) const {
float a = angle * DEG_TO_RAD;
return ofxVec2f( x*cos(a) - y*sin(a),
x*sin(a) + y*cos(a) );
}
ofxVec2f& rotate( float angle ) {
float a = angle * DEG_TO_RAD;
float xrot = x*cos(a) - y*sin(a);
y = x*sin(a) + y*cos(a);
x = xrot;
return *this;
}
// Normalization
//
//
ofxVec2f normalized() const {
float length = (float)sqrt(x*x + y*y);
if( length > 0 ) {
return ofxVec2f( x/length, y/length );
} else {
return ofxVec2f();
}
}
ofxVec2f& normalize() {
float length = (float)sqrt(x*x + y*y);
if( length > 0 ) {
x /= length;
y /= length;
}
return *this;
}
// Limit length.
//
//
ofxVec2f limited(float max) const {
float length = (float)sqrt(x*x + y*y);
if( length > max && length > 0 ) {
return ofxVec2f( (x/length)*max, (y/length)*max );
} else {
return ofxVec2f( x, y );
}
}
ofxVec2f& limit(float max) {
float length = (float)sqrt(x*x + y*y);
if( length > max && length > 0 ) {
x = (x/length)*max;
y = (y/length)*max;
}
return *this;
}
// Perpendicular normalized vector.
//
//
ofxVec2f perpendiculared() const {
float length = (float)sqrt( x*x + y*y );
if( length > 0 )
return ofxVec2f( -(y/length), x/length );
else
return ofxVec2f();
}
ofxVec2f& perpendicular() {
float length = (float)sqrt( x*x + y*y );
if( length > 0 ) {
x = -(y/length);
y = x/length;
}
return *this;
}
// Length
//
//
float length() const {
return (float)sqrt( x*x + y*y );
}
float lengthSquared() const {
return (float)(x*x + y*y);
}
/**
* Angle (deg) between two vectors.
* This is a signed relative angle between -180 and 180.
*/
float angle( const ofxVec2f& vec ) const {
return atan2( x*vec.y-y*vec.x, x*vec.x + y*vec.y )*RAD_TO_DEG;
}
/**
* Dot Product.
*/
float dot( const ofxVec2f& vec ) const {
return x*vec.x + y*vec.y;
}
};
// Non-Member operators
//
//
static inline ofxVec2f operator+( float f, const ofxVec2f& vec ) {
return ofxVec2f( f+vec.x, f+vec.y);
}
static inline ofxVec2f operator-( float f, const ofxVec2f& vec ) {
return ofxVec2f( f-vec.x, f-vec.y);
}
static inline ofxVec2f operator*( float f, const ofxVec2f& vec ) {
return ofxVec2f( f*vec.x, f*vec.y);
}
static inline ofxVec2f operator/( float f, const ofxVec2f& vec ) {
return ofxVec2f( f/vec.x, f/vec.y);
}
#endif
| [
"[email protected]"
] | [
[
[
1,
336
]
]
] |
3b7ca7dc7bc43bbdcdd5b64dc549d333e0a1dcf9 | 56c17f756480a02c77aecc69b217c29294f4c180 | /Src/Libs/Rastering/QbertBox.h | 8d1961909a2a9e17c845d44281f9e19cc4618298 | [] | no_license | sangongs/qbert3d | 5fd88b9720b68ca7617a8c5510568911b3dc34c5 | 296b78451b73032e16e64ae1cc4f0200ef7ca734 | refs/heads/master | 2021-01-10T04:02:37.685309 | 2008-09-12T16:13:04 | 2008-09-12T16:13:04 | 46,944,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | h | #pragma once
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/tuple/tuple.hpp"
#include "GameObject.h"
namespace BGComplete
{
class QbertBox : public GameObject
{
friend class QbertModel;
int _face;
bool _isVisited;
bool _isOnPerimeter;
public:
QbertBox(const std::string& name, int face, bool isPerimeter,
float x, float y, float z, float xRotate = 0, float yRotate = 0, float zRotate = 0)
: GameObject(name, NULL, x, y, z, xRotate, yRotate, zRotate), _face(face), _isVisited(false), _isOnPerimeter(isPerimeter) {}
bool IsOnPerimeter() {return _isOnPerimeter;}
};
typedef boost::shared_ptr<QbertBox> QbertBox_ptr;
typedef boost::tuple<QbertBox_ptr, Math::Point3D, Math::Point3D> AppearanceBox; //Point3D upDIrection, Point3D faceDirection;
typedef boost::shared_ptr<std::vector<AppearanceBox>> VecOfAppearanceBox_ptr;
}
| [
"iliagore@97581c8e-fe54-0410-aa42-dd6ba39e7182"
] | [
[
[
1,
30
]
]
] |
aac145400040f7585d98072e4b30c8d1b2e8c66e | 85ee7e4ebdc4323939a5381ef0ec1d296412533b | /source/Scenes/NatureLabScene.cpp | 8f64a22947d1c2d474312a2669a4940da57bcb8f | [
"MIT"
] | permissive | hyperiris/praetoriansmapeditor | af71ab5d9174dfed1f4d8a4c751d92275eb541f2 | e6f7c7bc913fb911632a738a557b5f2eb4d4fc57 | refs/heads/master | 2016-08-10T22:40:11.230823 | 2008-10-24T05:09:54 | 2008-10-24T05:09:54 | 43,621,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,155 | cpp | #include "NatureLabScene.h"
#include "../Databases/ModelDatabase.h"
#include "../Nodes/TransformGroup.h"
#include "../Geometry/Geometry.h"
#include "../Kernel/Gateway.h"
#include "../Geometry/Model.h"
#include "../Managers/ManagersUtils.h"
NatureLabScene::NatureLabScene(const char* name) : Scene(name)
{
angle = 0.0f;
resolution = 128;
startIndex = 0;
endIndex = 0;
currentGroup = 0;
rootGroup = 0;
camDistance = 8.0f;
drawBounds = false;
drawAxis = false;
capacity = 0;
}
bool NatureLabScene::initialize()
{
Scene::initialize();
glDisable(GL_CULL_FACE);
rootGroup = new TransformGroup();
offscreenTexture.create2DShell("NatureOffscreenTexture", resolution, resolution, GL_RGBA8, GL_RGBA, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
currentInfo.texture.create2DShell("NatureCurrentTexture", 256, 256, GL_RGBA8, GL_RGBA, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
GUIButton* btn;
GUIPanel* btnPanel = (GUIPanel*) gui.getWidgetByCallbackString("GeosetPanel");
if (btnPanel)
for (int i = 0; i < 14; i++)
{
GSElementInfo info;
String btnName(String("GSBTN_") + i);
buttonTextures[i].create2DShell(String("NL") + btnName, resolution, resolution, GL_RGB8, GL_RGB, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
btn = (GUIButton*) gui.getWidgetByCallbackString(btnName);
btn->setTexture(buttonTextures[i]);
info.index = i;
info.texture = buttonTextures[i];
//info.coords = rectangle;
elementInfoAVLTree.insertKeyAndValue(btnName, info);
}
GSElementInfo elementInfo;
const Array <ICString>* namelist = Gateway::getNatureDatabase()->getNamesList();
for (size_t i = 0; i < namelist->length(); i++)
{
elementInfo.index = i;
elementInfo.name = namelist->at(i).c_str();
elementInfoList.append(elementInfo);
if (i < 14)
{
drawFullScreenImage(elementInfo);
offscreenTexture.copyCurrentBuffer();
updateOffscreenTexture(&buttonTextures[i]);
endIndex++;
++capacity;
}
}
if (currentSetLabel = (GUILabel*) gui.getWidgetByCallbackString("SetCounter"))
currentSetLabel->setLabelString(String("Models ") + endIndex + String("/") + int(elementInfoList.length()));
modelNameLabel = (GUILabel*) gui.getWidgetByCallbackString("ModelNameLabel");
modelTriLabel = (GUILabel*) gui.getWidgetByCallbackString("ModelTriLabel");
modelWidthLabel = (GUILabel*) gui.getWidgetByCallbackString("ModelWidthLabel");
modelHeightLabel = (GUILabel*) gui.getWidgetByCallbackString("ModelHeightLabel");
modelPropsPanel = (GUIPanel*) gui.getWidgetByCallbackString("ModelPropsPanel");
grid.setOffsetY(-0.01f);
grid.loadTexture("laboratory_ground.jpg");
grid.setup(64);
grid.applyGaussianDistribution(1.0f, 6.0f);
return true;
}
void NatureLabScene::beginScene()
{
Scene::beginScene();
glClearColor(0,0,0,1);
//mouseVisible = Gateway::getConfiguration().enableCursor;
if (modelPropsPanel)
modelPropsPanel->setVisible(false);
GUICheckBox* checkBox;
if (checkBox = (GUICheckBox*) gui.getWidgetByCallbackString("BoundsCheckbox"))
checkBox->setChecked(false);
if (checkBox = (GUICheckBox*) gui.getWidgetByCallbackString("AxisCheckbox"))
checkBox->setChecked(false);
if (checkBox = (GUICheckBox*) gui.getWidgetByCallbackString("PropsCheckbox"))
checkBox->setChecked(false);
drawBounds = false;
drawAxis = false;
}
void NatureLabScene::endScene()
{
}
void NatureLabScene::actionPerformed(GUIEvent &evt)
{
const String &callbackString = evt.getCallbackString();
GUIRectangle *sourceRectangle = evt.getEventSource();
int widgetType = sourceRectangle->getWidgetType();
if (widgetType == CHECK_BOX)
{
GUICheckBox *checkBox = (GUICheckBox*) sourceRectangle;
if (checkBox->isClicked())
{
if (callbackString == "BoundsCheckbox")
{
drawBounds = checkBox->isChecked();
return;
}
if (callbackString == "AxisCheckbox")
{
drawAxis = checkBox->isChecked();
return;
}
if (callbackString == "PropsCheckbox")
{
modelPropsPanel->setVisible(checkBox->isChecked());
return;
}
}
}
if (widgetType == SLIDER)
{
GUISlider* slider = (GUISlider*) sourceRectangle;
if (callbackString == "WindFactorSlider")
slider->setLabelString(String("Wind factor: ") + slider->getProgress());
}
if (widgetType == BUTTON)
{
GUIButton *button = (GUIButton*) sourceRectangle;
if (button->isClicked())
{
if (callbackString == "Previous")
{
previousGroup();
return;
}
if (callbackString == "Next")
{
nextGroup();
return;
}
if (callbackString == "Start")
{
firstGroup();
return;
}
if (callbackString == "End")
{
lastGroup();
return;
}
if (callbackString == "AcceptButton")
{
if (TransformGroup* group = rootGroup->getGroup(currentInfo.name))
{
TransformGroup* rgroup = new TransformGroup();
rgroup->addChild(new TransformGroup(*group));
if (GUISlider* slider = (GUISlider*) gui.getWidgetByCallbackString("WindFactorSlider"))
currentInfo.windFactor = slider->getProgress();
Gateway::setActiveNatureElement(currentInfo);
Gateway::setActiveNature(rgroup);
sceneController.execute(callbackString);
}
return;
}
GSElementInfo* info = getGSElementInfo(callbackString);
if (info)
{
TransformGroup* activeGroup = rootGroup->getGroup(info->name);
if (activeGroup)
{
if (currentGroup)
currentGroup->setVisible(false);
activeGroup->setVisible(true);
Tuple3f groupExtents = activeGroup->getBoundsDescriptor().getExtents();
grid.applyGaussianDistribution(1.0f, groupExtents.getLengthSquared());
currentGroup = activeGroup;
camDistance = groupExtents.getLength() * 2;
if (modelNameLabel)
modelNameLabel->setLabelString(String("Name: ") + activeGroup->getName());
if (modelTriLabel)
modelTriLabel->setLabelString(String("Triangles: ") + int(activeGroup->getTriangleCount()));
if (modelWidthLabel)
modelWidthLabel->setLabelString(String("Width: ") + groupExtents.x * 2);
if (modelHeightLabel)
modelHeightLabel->setLabelString(String("Height: ") + groupExtents.y * 2);
currentInfo.activeGroup = activeGroup;
}
else
camDistance = 8.0f;
}
sceneController.execute(callbackString);
}
}
}
void NatureLabScene::update(const FrameInfo &frameInfo)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const FrameInfo* info = &frameInfo;
orbitCamera(info->m_Interval);
camera.update(info->m_Interval);
frustum.update();
grid.draw();
if (drawAxis)
axis.draw();
rootGroup->render(FRONT_TO_BACK|SORTED_BY_TEXTURE|ALL_EFFECTS);
if (currentGroup && drawBounds)
{
glColor3f(1,1,1);
currentGroup->renderAABB();
}
Renderer::enter2DMode(info->m_Width, info->m_Height);
gui.render(info->m_Interval);
Renderer::exit2DMode();
}
void NatureLabScene::reset()
{
camera.setViewerPosition(Tuple3f(8, 12, 8));
camera.setFocusPosition(Tuple3f(0, 0, 0));
camera.setUpDirection(Tuple3f(0, 1, 0));
camera.setTranslationSpeed(0.03f);
camera.update(0);
frustum.update();
}
void NatureLabScene::orbitCamera(float tick)
{
angle += 0.5f * tick;
if (angle > 360.0f)
angle = angle - 360.0f;
float theta = fastSin(angle);
camera.setViewerPosition(Tuple3f(camDistance * fastCos(angle), 0.7f * (camDistance + camDistance * 0.45f * theta), camDistance * theta));
}
void NatureLabScene::handleKeyEvent(KeyEvent evt, int extraInfo)
{
Scene::handleKeyEvent(evt, extraInfo);
}
void NatureLabScene::previousGroup()
{
startIndex = clamp(startIndex - capacity, 0, (int) elementInfoList.length());
endIndex = clamp(startIndex + capacity, 0, (int) elementInfoList.length());
flushUnusedGroups();
rootGroup->destroy();
updateButtonTextures(startIndex, endIndex);
updateLabels();
}
void NatureLabScene::nextGroup()
{
int i, j, end;
startIndex = clamp(startIndex + capacity, 0, (int) elementInfoList.length());
startIndex = (int) floor((float)startIndex / capacity) * capacity;
endIndex = clamp(startIndex + capacity, 0, (int) elementInfoList.length());
flushUnusedGroups();
rootGroup->destroy();
updateButtonTextures(startIndex, endIndex);
end = startIndex + capacity;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
offscreenTexture.copyCurrentBuffer();
for (i = endIndex, j = capacity - (end - endIndex); i != end; i++, j++)
updateOffscreenTexture(&buttonTextures[j]);
updateLabels();
}
void NatureLabScene::firstGroup()
{
int i, j, end;
startIndex = 0;
endIndex = clamp(startIndex + capacity, 0, (int) elementInfoList.length());
flushUnusedGroups();
rootGroup->destroy();
updateButtonTextures(startIndex, endIndex);
end = startIndex + capacity;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
offscreenTexture.copyCurrentBuffer();
for (i = endIndex, j = capacity - (end - endIndex); i != end; i++, j++)
updateOffscreenTexture(&buttonTextures[j]);
updateLabels();
}
void NatureLabScene::lastGroup()
{
int i, j, end;
startIndex = elementInfoList.length() - (elementInfoList.length() % capacity);
endIndex = clamp(startIndex + capacity, 0, (int) elementInfoList.length());
flushUnusedGroups();
rootGroup->destroy();
updateButtonTextures(startIndex, endIndex);
end = startIndex + capacity;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
offscreenTexture.copyCurrentBuffer();
for (i = endIndex, j = capacity - (end - endIndex); i != end; i++, j++)
updateOffscreenTexture(&buttonTextures[j]);
updateLabels();
}
void NatureLabScene::updateLabels()
{
if (currentSetLabel)
currentSetLabel->setLabelString(String("Models ") + endIndex + String("/") + int(elementInfoList.length()));
if (modelNameLabel)
modelNameLabel->setLabelString("Name: ");
if (modelTriLabel)
modelTriLabel->setLabelString(String("Triangles: "));
if (modelWidthLabel)
modelWidthLabel->setLabelString(String("Width: "));
if (modelHeightLabel)
modelHeightLabel->setLabelString(String("Height: "));
}
void NatureLabScene::flushUnusedGroups()
{
PrototypeInfo* info;
for (unsigned int i = 0; i < rootGroup->getGroupsCount(); i++)
{
info = PrototypeManager::getPrototypeInfo(rootGroup->getGroup(i)->getName());
if (info)
info->decreaseUserCount();
}
currentGroup = 0;
}
void NatureLabScene::drawFullScreenImage(const GSElementInfo& info)
{
Tuple3f cen;
Tuple4i viewport;
Tuple3f minp, minP, maxP;
float xscale, yscale, maxlen;
TransformGroup *proto = 0;
TransformGroup *group = 0;
PrototypeInfo* protoinfo;
proto = Gateway::getNaturePrototype(info.name);
if (!proto)
{
glClearColor(0,0,0,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return;
}
protoinfo = PrototypeManager::getPrototypeInfo(proto->getName());
protoinfo->increaseUserCount();
group = new TransformGroup(*proto);
group->setVisible(true);
minp = group->getBoundsDescriptor().getMinEndAABB();
cen = group->getBoundsDescriptor().getCenterAABB();
group->getTransform().setTranslations(0, -minp.y, 0);
group->getTransform().rotateY(90.0f * DEG2RAD);
group->updateBoundsDescriptor();
rootGroup->addChild(group);
minP = group->getBoundsDescriptor().getMinEndAABB();
maxP = group->getBoundsDescriptor().getMaxEndAABB();
xscale = (maxP.x - minP.x);
yscale = (maxP.y - minP.y);
maxlen = xscale > yscale ? xscale : yscale;
glClearColor(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(-maxlen/2, maxlen/2, minP.y, minP.y + maxlen, 1000, -1000);
glGetIntegerv(GL_VIEWPORT, viewport);
glViewport(0, 0, resolution, resolution);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
rootGroup->render(FRONT_TO_BACK|SORTED_BY_TEXTURE|ALL_EFFECTS);
group->getTransform().setIdentity();
group->setVisible(false);
glClearColor(0,0,0,1);
glViewport(0, 0, viewport.z, viewport.w);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void NatureLabScene::updateButtonTextures(unsigned int st, unsigned int en)
{
for (int i = st, j = 0; i != en; i++, j++)
{
drawFullScreenImage(elementInfoList(i));
offscreenTexture.copyCurrentBuffer();
updateOffscreenTexture(&buttonTextures[j]);
}
}
void NatureLabScene::updateOffscreenTexture(Texture *targetTexture)
{
Tuple4i viewport;
glGetIntegerv(GL_VIEWPORT, viewport);
glViewport(0, 0, resolution, resolution);
Renderer::enter2DMode();
offscreenTexture.activate();
drawFullScreenQuad(resolution, resolution);
targetTexture->copyCurrentBuffer();
offscreenTexture.deactivate();
Renderer::exit2DMode();
glViewport(0, 0, viewport.z, viewport.w);
}
void NatureLabScene::drawFullScreenQuad(int width, int height)
{
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 1.0f);
glVertex2i(0, 0);
glTexCoord2f(0.0f, 0.0f);
glVertex2i(0, height);
glTexCoord2f(1.0f, 1.0f);
glVertex2i(width, 0);
glTexCoord2f(1.0f, 0.0f);
glVertex2i(width, height);
glEnd();
}
GSElementInfo* NatureLabScene::getGSElementInfo(const char* name)
{
unsigned int index = elementInfoList.length();
String key;
if (elementInfoAVLTree.find(name, key))
{
index = (int) floor((float)startIndex/capacity) * capacity + elementInfoAVLTree[key].index;
currentInfo.coords = elementInfoAVLTree[key].coords;
currentInfo.texture = elementInfoAVLTree[key].texture;
currentInfo.index = index < elementInfoList.length() ? index : currentInfo.index;
currentInfo.name = index < elementInfoList.length() ? elementInfoList(currentInfo.index).name : "";
currentInfo.activeGroup = currentGroup;
}
return index < elementInfoList.length() ? ¤tInfo : 0;
}
NatureLabScene::~NatureLabScene()
{
deleteObject(rootGroup);
}
| [
"kwantum26@d2fd1b2e-92ce-11dd-9977-cddf1a87921b"
] | [
[
[
1,
530
]
]
] |
ded7a2d136cbb4467c8bc2efdb0c13de694a2ab3 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /tags/pyplusplus_dev_0.9.5/unittests/data/classes_to_be_exported.hpp | 9622181789b8251d2b184258e970eeecb47ea02e | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,233 | hpp | // Copyright 2004-2008 Roman Yakovenko.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __classes_to_be_exported_hpp__
#define __classes_to_be_exported_hpp__
namespace classes{
namespace fundamentals{
struct fundamental1{};
struct fundamental2{};
}
namespace hierarchical{
struct fruit{};
struct apple : public fruit{};
}
namespace noncopyables{
class noncopyable1{
public:
noncopyable1(){}
private:
noncopyable1( const noncopyable1& );
};
}
namespace abstracts{
class abstract{
public:
abstract(){}
abstract(int){}
abstract(int, double, const abstract&){}
public:
virtual int pure_virtual(const abstract& ) const = 0;
virtual bool overloaded_virtual(){ return true;}
virtual bool overloaded_virtual(int){ return true;}
virtual int overloaded_pure_virtual(int) const = 0;
virtual void overloaded_pure_virtual(double) const = 0;
virtual int some_virtual(){ return 1; }
};
}
namespace constructors{
struct constructor1{
constructor1(){}
constructor1( const constructor1& ){}
constructor1(int x, int y){}
constructor1(int y, const constructor1& x ){}
constructor1( const double ){}
struct internal_data{};
constructor1( const internal_data ){}
};
}
namespace scope_based{
struct scope_based_exposer{
enum EColor{ red, green, blue };
scope_based_exposer(EColor c=blue){}
};
}
namespace protected_static{
class protected_static_t{
protected:
static int identity(int x){ return x; }
int invert_sign(int x){ return -1*x; }
};
};
namespace non_public_hierarchy{
struct protected_base{};
struct protected_derived : protected protected_base{};
}
}//classes
namespace pyplusplus{ namespace aliases{
typedef classes::hierarchical::apple the_tastest_fruit;
typedef classes::protected_static::protected_static_t PROTECTED_STATIC_T_1;
typedef classes::protected_static::protected_static_t PROTECTED_STATIC_T_2;
}}
#endif//__classes_to_be_exported_hpp__
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
109
]
]
] |
e69bbd8c314dbc3ab61ab98e9c2a7b7dbb963aee | 06b171ab4f8c38a5e6fe759fc9ec1351a0451db6 | /sample.cpp | eeaf2c6d9154e94478b0c4a56b6f3821921fffa3 | [] | no_license | cagsworld/Sample | 9257f88debff201ec657ea99d6079fa801701b36 | 9dc860ae93904e8cb337245ab01827a2a5883c5d | refs/heads/master | 2016-09-06T18:26:18.979793 | 2010-07-05T01:25:02 | 2010-07-05T01:25:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,215 | cpp | //////////////////////////////////////////////////////////
// import.cpp
// Function:
// Uses FTP to get BCP files from remote server and
// bulk load records into SQL Tables
//////////////////////////////////////////////////////////
// Include db-libary headers
#include <sybfront.h>
#include <sybdb.h>
#include <syberror.h>
// Include file io routines
#include <time.h>
#include <fcntl.h>
#include <io.h>
#include <fstream.h>
#include <windows.h>
#include <errno.h>
// Include FTP library header
#include <winftp32.h>
// A few defines
#define ERROR_PREFIX szSystem << " " << TimeStamp() << " Error from import.exe: "
#define WARNING_PREFIX szSystem << " " << TimeStamp() << " Alert from import.exe: "
#define INFO_PREFIX szSystem << " " << TimeStamp() << " Info from import.exe: "
#define MAXLOGSIZE 200 // 200 bytes, change to 10 mb for production
#define MAXERRSIZE 100 // 100 bytes, change to 1 mb for production
// Function prototypes
BOOL OpenLogFiles();
BOOL CheckArgs(int, char **);
BOOL DBConnect(char *szServer, char *szUser, char *szPswd);
int BCPInRecords(ifstream bcpInfile, char *szExtSystem);
BOOL ftp_exist(int hndl, CHAR * szFile);
void ShowUsage();
char *TimeStamp();
long FileSize(char *);
int err_handler(DBPROCESS *dbproc, int severity, int dberr,
int oserr, char *dberrstr, char *oserrstr);
int msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity,
char *msgtext, char *srvname, char *procname, DBUSMALLINT line);
// Module level vars
ofstream logfile, errfile; // handle to log and error file used by many functions
char szTimeStamp[19]; // used to stamp time in messages to log and error file
char *szSystem; // used for system abrev in messages to log and error file
char buffer[256]; // utility string buffer
LOGINREC *login; // the login information
DBPROCESS *dbproc; // the connection with SQL Server
extern int errno;
void main(int argc, char *argv[])
{
ifstream bcpInfile; // local import file holding records to bcp to x_import table
int hndl; // file handle
char szXfrFile[128]; // holds name of delimited import file
char szTmpFile[128]; // holds name of renamed delimited import file
char szXfrLocalFile[128]; // holds name of delimited import file with local dir prepended
int intBcpCount; // number of rows bcp'd
// Open import log and import error log files
if ( !OpenLogFiles() )
return;
if ( argc >= 7 )
szSystem = argv[7];
else
szSystem = "";
// Check if user wants help or if incorrect args entered
if ( !CheckArgs(argc, argv) )
return;
// Create transfer filenames
wsprintf(szXfrFile, "%s_cags.xfr", argv[7] );
wsprintf(szTmpFile, "%s_cags.yyy", argv[7] );
// Connect to database and init db structures
if ( !DBConnect(argv[1], argv[2], argv[3]) )
return;
//
// Check if local wms_cags.xfr exists to BCP records into import table
//
wsprintf(szXfrLocalFile, "%s%s", "./transfer/", szXfrFile );
if ( FileSize(szXfrLocalFile) > -1 ) // file exists
{
// Open local wms_cags.xfr
bcpInfile.open(szXfrLocalFile, ios::nocreate, filebuf::sh_none);
if ( !bcpInfile.is_open() )
{
// Failed open so get out and retry on next run
errfile << ERROR_PREFIX << "failed to open bcp input file" << endl;
return;
}
else
{
// Call bcp routines to move data from import file into x_import table
// Note: If migrated to another RDBMS most changes will be to this function
if ( (intBcpCount = BCPInRecords(bcpInfile, argv[7])) != -1 )
{
// Delete local import file now that its records are in import table
bcpInfile.close();
f_deletefile(szXfrLocalFile);
logfile << INFO_PREFIX << "successfull BCP of " << intBcpCount
<< " records into import table" << endl;
}
else
{
// Failed bcp so don't delete and get out to retry on next run
bcpInfile.close();
errfile << ERROR_PREFIX << "failed BCP of import file to import table" << endl;
return;
}
}
}
else
{
if ( FileSize(szXfrLocalFile) == -1 )
logfile << WARNING_PREFIX << "no records to import from " << szXfrLocalFile << " this run" << endl;
else
errfile << ERROR_PREFIX << "error opening local import file " << szXfrLocalFile << endl;
}
//
// Logon to ftp server to get remote wms_cags.xfr to be bcp'd next import run
//
hndl = ftp_login(argv[4], argv[5], argv[6], "");
if ( hndl == -1 )
{
errfile << ERROR_PREFIX << "failed ftp_login" << endl;
return;
}
// Set current remote transfer directory
if ( ftp_cd(hndl, argv[8]) == -1 )
{
errfile << ERROR_PREFIX << "failed ftp_cd to " << argv[8] << endl;
return;
}
// Check for no left over records from prior import and new records to import
if ( !ftp_exist(hndl, szTmpFile) && ftp_exist(hndl, szXfrFile) )
{
// If so, then rename prior to ftp_get to prevent contention with remote site
if ( ftp_rename(hndl, szXfrFile, szTmpFile) == -1 )
{
// ftp_rename failed so just log message and try again next invocation
errfile << ERROR_PREFIX << "failed ftp_remame of "
<< szXfrFile << " to " << szTmpFile
<< " will retry next run" << endl;
return;
}
}
// Check for either left over records or new records in tmp file to import
if ( ftp_exist(hndl, szTmpFile) )
{
// If so, then ftp them to local directory
if ( ftp_get(hndl, szTmpFile, szXfrLocalFile) == -1 )
{
// ftp_get failed so do nothing here and retry next invovation
errfile << ERROR_PREFIX << "failed ftp_get of " << szTmpFile
<< " will retry next run" << endl;
}
else
{
if ( ftp_delete(hndl, szTmpFile) == -1 )
{
// ftp_delete failed so delete local to prevent re-importing next invocation
f_deletefile(szXfrLocalFile);
errfile << ERROR_PREFIX << "failed ftp_delete of " << szTmpFile << endl;
}
else
{
// successfull FTP
logfile << INFO_PREFIX << "successfull FTP from remote site to "
<< szXfrLocalFile << endl;
}
}
}
else
logfile << WARNING_PREFIX << "no records to ftp from remote site this run" << endl;
// Close opened objects
if ( !logfile.is_open() )
logfile.close();
if ( !errfile.is_open() )
errfile.close();
dbexit(); // close database connection
ftp_quit(hndl); // close ftp connection
}
BOOL OpenLogFiles()
{
// Open import log file
if ( FileSize("./log/import.log") > MAXLOGSIZE )
// Truncate before writing
logfile.open("./log/import.log", ios::out);
else
// Append to existing
logfile.open("./log/import.log", ios::app);
if ( !logfile.is_open() )
{
cerr << "Could not open 'import.log'" << endl;
return FALSE;
}
// Open import error file
if ( FileSize("./log/import.err") > MAXERRSIZE )
// Truncate before writing
errfile.open("./log/import.err", ios::out);
else
// Append to existing
errfile.open("./log/import.err", ios::app);
if ( !errfile.is_open() )
{
cerr << "Could not open 'import.err'" << endl;
return FALSE;
}
return TRUE;
}
BOOL DBConnect(char *szServer, char *szUser, char *szPswd)
{
// Initialize DB-Library
if ( dbinit() == FAIL )
return FALSE;
// Install user-supplied error-handling and message-handling
dberrhandle((EHANDLEFUNC)err_handler);
dbmsghandle((MHANDLEFUNC)msg_handler);
// Allocate and init LOGINREC structure used to open a connection to SQL Server
login = dblogin();
DBSETLUSER(login, szUser); // "sa"
DBSETLPWD(login, szPswd); // ""
DBSETLAPP(login, "cags_import_bcp");
// Enable bulk copy for this connection
BCP_SETL(login, TRUE);
// Get a connection to the database.
if ((dbproc = dbopen(login, szServer)) == (DBPROCESS *) NULL) // "cgserver"
{
errfile << ERROR_PREFIX << "can't connect to server" << endl;
return FALSE;
}
// Make cags the current database
if ( dbuse(dbproc, "cags") == FAIL )
{
errfile << ERROR_PREFIX << "can't make cags current database." << endl;
return FALSE;
}
return TRUE;
}
int BCPInRecords(ifstream bcpInfile, char *szExtSystem)
{
int intImportCount = 0;
// Get current server datetime
DBDATETIME dtCurDateTime;
dtCurDateTime.dtdays = 0;
dbcmd(dbproc, "select getdate()");
dbsqlexec(dbproc);
if (dbresults(dbproc) == SUCCEED)
if (dbnextrow(dbproc) != NO_MORE_ROWS)
dbconvert(dbproc, SYBDATETIME, (dbdata(dbproc, 1)),
(DBINT)-1, SYBDATETIME, (BYTE*)&dtCurDateTime, (DBINT)-1);
if ( dtCurDateTime.dtdays == 0 )
return -1;
// Call bcp_init
if ( bcp_init(dbproc, "cags..x_import", NULL, "bcp_err.out", DB_IN) != SUCCEED )
{
errfile << ERROR_PREFIX << "failed bcp_init" << endl;
return -1;
}
bcp_bind(dbproc, (BYTE*)szExtSystem, 0, -1, (BYTE*)"", 1, SYBCHAR, 1);
bcp_bind(dbproc, (BYTE*)&dtCurDateTime, 0, -1, NULL, 0, SYBDATETIME, 2);
bcp_bind(dbproc, (BYTE*)&intImportCount, 0, -1, NULL, 0, SYBINT2, 3);
bcp_bind(dbproc, (BYTE*)buffer, 0, -1, (BYTE*)"", 1, SYBVARCHAR, 4);
while ( !bcpInfile.eof() )
{
bcpInfile.getline(buffer, 255);
// cout << buffer << endl;
intImportCount++;
// Bulk copy it into the database */
bcp_sendrow(dbproc);
}
// Close the bulk copy process so all the changes are committed
return bcp_done(dbproc);
}
BOOL ftp_exist(int hndl, CHAR * szFile)
{
if ( (ftp_ls(hndl, szFile, "NUL") == -1) && (ftp_replycode(hndl) == 550) )
return FALSE;
else
return TRUE;
}
BOOL CheckArgs(int argc, char *argv[])
{
// User requesting help?
if ( argc > 0 )
{
if ((lstrcmp(argv[1], "/?") == 0) ||
(lstrcmp(argv[1], "?") == 0) ||
(lstrcmp(argv[1], "-?") == 0) ||
(lstrcmp(argv[1], "help") == 0) ||
(lstrcmp(argv[1], "/help") == 0) ||
(lstrcmp(argv[1], "/HELP") == 0) ||
(lstrcmp(argv[1], "HELP") == 0))
{
ShowUsage();
return FALSE;
}
}
// Correct number of parameters specified on command line??
if ( argc != 9 )
{
cout << "Error: Wrong number of paramters" << endl << endl;
errfile << ERROR_PREFIX << "wrong number of command line parameters" << endl;
ShowUsage();
return FALSE;
}
return TRUE;
}
void ShowUsage()
{
cout << "Syntax:" << endl << " import" << endl ;
cout << " <db_serv> <db_user> <db_pswd> <ftp_serv> <ftp_user> <ftp_pswd> <ext_sys> <ftp_alias_dir>" << endl << endl;
cout << "For Example:" << endl;
cout << " import my_server, my_user, my_pswd, ftpvax cags_user cags_pswd cags" << endl << endl;
cout << "Assumptions: program is invoked from interfaces dir" << endl;
}
char *TimeStamp()
{
char dbuffer [9];
char tbuffer [9];
_strdate(dbuffer);
_strtime(tbuffer);
wsprintf(szTimeStamp, "%s %s", dbuffer, tbuffer);
return szTimeStamp;
}
long FileSize(char * szFile)
{
int fh;
long fl;
fh = _open( szFile, _O_RDONLY );
if( fh == -1 )
{
if ( errno == ENOENT )
return -1; // no file
else
return -2; // open error
}
else
{
fl = _filelength( fh );
_close( fh );
return fl;
}
}
int err_handler(DBPROCESS *dbproc, int severity, int dberr,
int oserr, char *dberrstr, char *oserrstr)
{
if ((dbproc == NULL) || (DBDEAD(dbproc)))
return(INT_EXIT);
else
{
errfile << ERROR_PREFIX << "DB-Library error: " << dberrstr << endl;
if (oserr != DBNOERR)
errfile << ERROR_PREFIX << "Operating-system error: " << oserrstr << endl;
return(INT_CANCEL);
}
}
int msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity,
char *msgtext, char *srvname, char *procname, DBUSMALLINT line)
{
// If it's a database change message, we'll ignore it.
// Also ignore language change message.
if (msgno == 5701 || msgno == 5703)
return(0);
errfile << ERROR_PREFIX << "Msg " << msgno
<< ", Level " << severity
<< ", State "<< msgstate << endl;
if (strlen(srvname) > 0)
errfile << "Server " << srvname;
if (strlen(procname) > 0)
errfile << " Procedure " << procname;
if (line > 0)
errfile << " Line " << line << endl;
errfile << msgtext << endl;
return(0);
}
| [
"[email protected]"
] | [
[
[
1,
432
]
]
] |
5d513fe9f1ed2a907fbf52b7e00b8df7d9aa1667 | 20c74d83255427dd548def97f9a42112c1b9249a | /src/roadfighter/playermanager.h | d154aa029d3bcad0133f256deca87ec38185e0fd | [] | no_license | jonyzp/roadfighter | 70f5c7ff6b633243c4ac73085685595189617650 | d02cbcdcfda1555df836379487953ae6206c0703 | refs/heads/master | 2016-08-10T15:39:09.671015 | 2011-05-05T12:00:34 | 2011-05-05T12:00:34 | 54,320,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | h | #ifndef PLAYERMANAGER_H
#define PLAYERMANAGER_H
#include "interactive-object-manager.h"
#include "playercar.h"
using namespace std;
class PlayerManager : InteractiveObjectManager
{
public:
PlayerManager();
PlayerManager(PlayerCar *player);
~PlayerManager();
void setPlayer(PlayerCar *player);
PlayerCar *getPlayer();
virtual void init();
virtual void spawn();
virtual void display();
virtual void update();
virtual void cleanup();
void reinit();
void checkCollision(vector<InteractiveObject*> &ObjectsOnScreen);
private:
PlayerCar *player;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
f348fc6cf2490f892e641b75ff88494985bb3211 | 960a896c95a759a41a957d0e7dbd809b5929c999 | /Game/weapon.cpp | 54f2bd4cb070f4213089914c89f91978ccd91f02 | [] | no_license | WSPSNIPER/dangerwave | 8cbd67a02eb45563414eaf9ecec779cc1a7f09d5 | 51af1171880104aa823f6ef8795a2f0b85b460d8 | refs/heads/master | 2016-08-12T09:50:00.996204 | 2010-08-24T22:55:52 | 2010-08-24T22:55:52 | 48,472,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,045 | cpp |
#include"weapon.hpp"
void Weapon::Reload()
{
if(reload_time_wait.GetElapsedTime() < _reloadSpeed && _reloading)//while reload time hasnt come..
{
// this gets the number of bullets in a mag and checks if its full or not
if(_ammo / _mag == _clipSize) //if the current clip is full
{
_reloading = false; //dont reload
}
else
{
_reloading = true;
}
}
else
{
//if pasted or equal to reload time and is till in realoading process...
_reloading = false;//ends he reloading process
_ammoleft -= _clipSize; // basically tells you how much ammo
//in total are in all the mags left.
_ammo = _ammomax; // sets ammo back to max
_fireCount = 0;
}
}
void Weapon::Shoot(sf::Vector2f player, sf::Vector2f Target)
{
if(!_reloading) //if not reloading..
{
if(_ammo / _mag < 1) //if you have a dont have ammo
{
Reload(); // reload weapon
}
else
{
if(rate.GetElapsedTime() > _rateOfFire) // if you are ready to shoot
{
rate.Reset(); // reset counter
_shooting = false; //set status as not shooting.
_fireCount++; //increases the number of bullets fired.
}
else//if time hasnt come to shoot again...
{
_shooting = true; //shooting is till true..
}
}
}
}
/*Weapon::Weapon(cell::Entity* owner)
{
_owner = owner;
}*/
void Weapon::ConnectToEntity(cell::Entity* NewOwner)
{
_owner = NewOwner;
/*for(int a; a < _mag; a++)
{
int i = 0;
//BulletManager::KillBullet(bullet[a]);
}*/
}
void Weapon::DisconnectFromEntity(cell::Entity* OldOwner)
{
_owner = NULL;
}
void Weapon::Render(sf::RenderWindow &window)
{
//_Slope(window.GetInput().GetMouseX(),window.GetInput().GetMouseY())
}
| [
"michaelbond2008@e78017d1-81bd-e181-eab4-ba4b7880cff6",
"lukefangel@e78017d1-81bd-e181-eab4-ba4b7880cff6"
] | [
[
[
1,
64
],
[
66,
68
],
[
70,
79
]
],
[
[
65,
65
],
[
69,
69
]
]
] |
b86fd86eeafcbba4e4faa3dc9c23e4f5fbfe3476 | 3a51ec54347b68d287c5e82b8271c65b969f1b22 | /Perl/EmbPerl/plhv.cpp | 4ad534ae4841da283794f15c47fb98ba916e6702 | [] | no_license | BackupTheBerlios/unisimu-svn | f5c35f3a7eb4ce54b1245db1884f75cf5b8cd34c | 105243c5b17e372bc13a9fbb9656ffdc09458cd5 | refs/heads/master | 2020-04-19T06:46:59.930863 | 2008-07-04T08:30:28 | 2008-07-04T08:30:28 | 40,801,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,347 | cpp | //: plhv.cpp
//: implementation for the Perl::HV class
//: v0.03
//: Agent2002. All rights reserved.
//: 04-04-17 04-04-17
#include "embperl.h"
#include "plproxy.hpp"
#include <string.h>
//#include <eprintf.h>
typedef SV* old_SV_ptr;
typedef HV* old_HV_ptr;
typedef HE* old_HE_ptr;
extern "C" PerlInterpreter* my_perl;
namespace Perl {
HV::HV(){
// initialize the Perl interpreter:
Interp::init();
m_c_hv_ptr = Perl_newHV( my_perl );
}
HV::HV( const HV& val ){
m_c_hv_ptr = val.m_c_hv_ptr;
}
bool HV::store( const string& key, const SV& val ){
SV temp = val;
old_SV_ptr* pp = Perl_hv_store( my_perl,
(old_HV_ptr)m_c_hv_ptr,
key.c_str(),
strlen( key.c_str() ),
(old_SV_ptr)temp.m_c_sv_ptr,
0 );
if( pp == NULL ){
temp.decRefCount();
return false;
}
return true;
}
SV HV::fetch( const string& key ){
old_SV_ptr* pp = Perl_hv_fetch( my_perl,
(old_HV_ptr)m_c_hv_ptr,
key.c_str(),
strlen( key.c_str() ),
0 );
if( pp == NULL ){
SV sv;
sv = SV( proxy_sv_undef_ptr(), 0 );
store( key, sv );
return sv;
}
return SV( *pp, 0 );
}
SV HV::operator[]( const string& key ){
return fetch(key);
}
SV HV::remove( const string& key ){
SV retval( Perl_hv_delete( my_perl,
(old_HV_ptr)m_c_hv_ptr,
key.c_str(),
strlen( key.c_str() ),
0 ),
0 );
return retval;
}
void HV::undef(){
Perl_hv_undef( my_perl, (old_HV_ptr)m_c_hv_ptr );
}
void HV::clear(){
Perl_hv_clear( my_perl, (old_HV_ptr)m_c_hv_ptr );
}
int HV::iterator::count(){
return m_count;
}
bool HV::iterator::moveNext(){
void* p = Perl_hv_iternext( my_perl, (old_HV_ptr)m_table );
if( p == NULL )
return false;
m_entry = p;
return true;
}
SV HV::iterator::curVal(){
void* c_sv_ptr = Perl_hv_iterval( my_perl,
(old_HV_ptr)m_table,
(old_HE_ptr)m_entry );
return HV::newSV( c_sv_ptr );
}
string HV::iterator::curKey( int* retlen ){
if( retlen == NULL ){
int len;
char* retval = Perl_hv_iterkey( my_perl,
(old_HE_ptr)m_entry,
&len );
if( retval[len] != '\0' )
return NULL;
return retval;
}
return Perl_hv_iterkey( my_perl,
(old_HE_ptr)m_entry,
retlen );
}
HV::iterator::iterator( void* table, int count ){
m_table = table;
m_count = count;
m_entry = NULL;
}
HV::iterator HV::getIterator(){
int count = Perl_hv_iterinit( my_perl,
(old_HV_ptr)m_c_hv_ptr );
return HV::iterator( m_c_hv_ptr, count );
}
ostream& operator<<( ostream& os, const HV& hv ){
HV temp = hv;
HV::iterator it = temp.getIterator();
int len = it.count();
if( len == 0 )
return os << "()";
string s = "(";
for( int i = 0; i < len - 1; i++ ){
it.moveNext();
s += (string)it.curKey() + "=>" + (string)it.curVal();
s += ",";
}
it.moveNext();
s += (string)it.curKey() + "=>" + (string)it.curVal();
s += ")";
return os << s;
}
HV::HV( void* c_hv_ptr ){
Interp::init();
m_c_hv_ptr = c_hv_ptr;
}
SV HV::newSV( void* c_sv_ptr ){
return SV( c_sv_ptr, 0 );
}
} // namespace Perl
| [
"agent@625e195c-0704-0410-94f2-f261ee9f2fe7"
] | [
[
[
1,
159
]
]
] |
e40cceab8a67e96d5fcb2e0857d41977d8677a5b | ee065463a247fda9a1927e978143186204fefa23 | /Src/Application/QtTemp/moc/moc_IWrapper.cpp | 878fb2f663682119be8867dd7895470fab706935 | [] | no_license | ptrefall/hinsimviz | 32e9a679170eda9e552d69db6578369a3065f863 | 9caaacd39bf04bbe13ee1288d8578ece7949518f | refs/heads/master | 2021-01-22T09:03:52.503587 | 2010-09-26T17:29:20 | 2010-09-26T17:29:20 | 32,448,374 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,678 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'IWrapper.h'
**
** Created: Sat 25. Sep 14:05:26 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../QtExtensions/IWrapper.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'IWrapper.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_IWrapper[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
22, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
16, 10, 9, 9, 0x0a,
44, 38, 9, 9, 0x0a,
70, 38, 9, 9, 0x0a,
96, 38, 9, 9, 0x0a,
119, 38, 9, 9, 0x0a,
147, 142, 9, 9, 0x0a,
172, 38, 9, 9, 0x0a,
198, 38, 9, 9, 0x0a,
224, 38, 9, 9, 0x0a,
250, 38, 9, 9, 0x0a,
276, 38, 9, 9, 0x0a,
302, 38, 9, 9, 0x0a,
328, 38, 9, 9, 0x0a,
354, 38, 9, 9, 0x0a,
380, 38, 9, 9, 0x0a,
406, 38, 9, 9, 0x0a,
433, 38, 9, 9, 0x0a,
460, 38, 9, 9, 0x0a,
487, 38, 9, 9, 0x0a,
514, 38, 9, 9, 0x0a,
541, 38, 9, 9, 0x0a,
568, 38, 9, 9, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_IWrapper[] = {
"IWrapper\0\0state\0slotStateChanged(int)\0"
"value\0slotDValueChanged(double)\0"
"slotFValueChanged(double)\0"
"slotIValueChanged(int)\0slotUValueChanged(int)\0"
"text\0slotTextChanged(QString)\0"
"slot1ValueChanged(double)\0"
"slot2ValueChanged(double)\0"
"slot3ValueChanged(double)\0"
"slot4ValueChanged(double)\0"
"slot5ValueChanged(double)\0"
"slot6ValueChanged(double)\0"
"slot7ValueChanged(double)\0"
"slot8ValueChanged(double)\0"
"slot9ValueChanged(double)\0"
"slot10ValueChanged(double)\0"
"slot11ValueChanged(double)\0"
"slot12ValueChanged(double)\0"
"slot13ValueChanged(double)\0"
"slot14ValueChanged(double)\0"
"slot15ValueChanged(double)\0"
"slot16ValueChanged(double)\0"
};
const QMetaObject IWrapper::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_IWrapper,
qt_meta_data_IWrapper, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &IWrapper::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *IWrapper::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *IWrapper::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_IWrapper))
return static_cast<void*>(const_cast< IWrapper*>(this));
return QObject::qt_metacast(_clname);
}
int IWrapper::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: slotStateChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: slotDValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 2: slotFValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 3: slotIValueChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: slotUValueChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 5: slotTextChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 6: slot1ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 7: slot2ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 8: slot3ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 9: slot4ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 10: slot5ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 11: slot6ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 12: slot7ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 13: slot8ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 14: slot9ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 15: slot10ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 16: slot11ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 17: slot12ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 18: slot13ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 19: slot14ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 20: slot15ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
case 21: slot16ValueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
default: ;
}
_id -= 22;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df"
] | [
[
[
1,
141
]
]
] |
c1c687df4b8826f3730bf027ebe8a2133caae0a0 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/geometries/witness_2/Witness_2_implement.h | 6e36331895ba27c0f8a52394fe7b92b3b1bb26c7 | [] | no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,685 | h | /* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info: http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: Union_of_balls_2.h 737 2009-05-16 15:40:46Z miklosb $
*/
#include "Witness_2.h"
#include "Witness_landmark_set_2.h"
#include "layers\Landmark_delaunay_layer_2.h"
#include <constants.h>
#include <gui/app/static/Application_settings.h>
template <class K>
Witness_2<K>::Witness_2() : Geometry(), has_points(false) {
//triangulation_source = _triangulation_source;
//layer_name = _layer_name;
GL_draw_layer_2* landmark_point_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("Landmarks", this, "Set of landmarks", true, false, false, false);
add_layer(landmark_point_layer);
GL_draw_layer_2* landmark_delaunay_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("L Delaunay", this, "Delaunay of landmarks", false, false, false, false);
add_layer(landmark_delaunay_layer);
GL_draw_layer_2* landmark_voronoi_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("L Voronoi", this, "Voronoi of landmarks", false, true, false, false);
add_layer(landmark_voronoi_layer);
GL_draw_layer_2* witness_reconstr_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("Witness reconstruction", this, "Witness complex based curve reconstruction", false, false, true, false);
add_layer(witness_reconstr_layer);
GL_draw_layer_2* witness_ma_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("Witness medial axis", this, "Witness complex based medial axis approximation", false, true, true, false);
add_layer(witness_ma_layer);
GL_draw_layer_2* witness_maf_layer = new Landmark_delaunay_layer_2<Witness_2<K> >("Witness full medial axis", this, "Witness complex based medial axis approximation - exterior included", false, true, true, true);
add_layer(witness_maf_layer);
add_evolution("Landmark maxmin");
Application_settings::add_double_setting("witness-complex-min-landmarks-percentage",0);
}
template <class K>
Witness_2<K>::~Witness_2() {
}
template <class K>
Geometry* Witness_2<K>::clone() {
Witness_2* new_witness_2 = new Witness_2();
new_witness_2->witness_landmark_set = witness_landmark_set;
//new_witness_2->points = points;
new_witness_2->has_points = has_points;
return new_witness_2;
}
template <class K>
void Witness_2<K>::apply_modification(const std::string& name) {
if (name == "Landmark maxmin") {
Witness_landmark_set* wls = get_witness_landmark_set();
Witness_handle ph = wls->next_landmark_max_min();
wls->add_landmark(ph);
}
}
template <class K>
void Witness_2<K>::application_settings_changed(const QString& settings_name) {
if (settings_name=="witness-complex-min-landmarks-percentage") {
Witness_landmark_set* wls = get_witness_landmark_set();
size_t min_landmarks = (size_t)
(wls->number_of_witnesses() * Application_settings::get_double_setting("witness-complex-min-landmarks-percentage")/100.0);
if (min_landmarks > wls->number_of_witnesses()) return;
while (wls->landmark_list().size() < min_landmarks) {
Witness_handle ph = wls->next_landmark_max_min();
wls->add_landmark(ph);
}
// std::cout << "Landmark points " << wls->landmark_list().size() << std::endl;
invalidate_cache();
has_points = true;
// emit announce_structure_changed(SHARED_LANDMARK_TRIANGULATION);
emit do_widget_repaint();
}
}
template <class K>
void Witness_2<K>::receive_structure_changed(const std::string& name) {
if (name == SHARED_POINTS) {
invalidate_cache();
}
}
template <class K>
std::list<std::string> Witness_2<K>::offer_structures() {
std::list<std::string> res;
res.push_back(SHARED_LANDMARK_TRIANGULATION);
// res.push_back(WITNESS_TRIANGULATION);
// res.push_back(WITNESS_POINT_LIST);
// res.push_back(LANDMARK_POINT_LIST);
return res;
}
template <class K>
void* Witness_2<K>::give_structure(const std::string& name) {
if (name == SHARED_LANDMARK_TRIANGULATION) {
return get_witness_complex_triangulation();
//} else if (name == WITNESS_TRIANGULATION) {
// return witness_landmark_set.witness_triangulation();
//} else if (name == WITNESS_POINT_LIST) {
// return get_witness_point_list();
//} else if (name == LANDMARK_POINT_LIST) {
// return &witness_landmark_set.landmark_list();
} else {
return 0;
}
}
template <class K>
typename Witness_2<K>::Witness_landmark_set* Witness_2<K>::get_witness_landmark_set() {
if (!has_points) {
//std::cout << LOG_GREEN << "get points from the power_crust" << std::endl;
void* p = request_structure(SHARED_POINTS);
if (!p) std::cout << LOG_ERROR << "Error input points from Power_crust_2, activate a power crust geometry!" << std::endl;
else {
std::list<Point_2>* ps = static_cast<std::list<Point_2>*>(p);
witness_landmark_set.clear_all();
std::list<Point_2>::iterator p_it, p_end = ps->end();
for (p_it = ps->begin(); p_it != p_end; ++p_it)
witness_landmark_set.add_witness(*p_it);
has_points = true;
}
}
return &witness_landmark_set;
}
template <class K>
typename Witness_2<K>::Witness_complex_triangulation * Witness_2<K>::get_witness_complex_triangulation() {
get_witness_landmark_set(); // make sure we have the points
return witness_landmark_set.witness_complex_triangulation();
}
template <class K>
void Witness_2<K>::invalidate_cache() {
invalidate_all_layers();
has_points = false;
emit announce_structure_changed(SHARED_LANDMARK_TRIANGULATION);
}
| [
"balint.miklos@localhost"
] | [
[
[
1,
150
]
]
] |
53818c7ece32723c0ea99edcbfa94ef2de0a4f96 | 53ee90fbc1011cb17ba013d0a49812697d4e6130 | /MootoritePlaat/MootoriteJaam/CMagnetSensor.cpp | 67d681f9cdd03e827b9256d742799512d74d696d | [] | no_license | janoschtraumstunde/Robin | c3f68667c37c44e19473119b4b9b9be0fe2fb57f | bd691cbd2a0091e5100df5dfe1268d27c99b39f6 | refs/heads/master | 2021-01-12T14:06:44.095094 | 2010-12-09T14:34:27 | 2010-12-09T14:34:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | cpp | #include <WProgram.h>
#include "CMagnetSensor.h"
#include "ArduinoPins.h"
MagnetSensor::MagnetSensor(int slaveSelect, int sck, int miso) {
pinMode(slaveSelect, OUTPUT);
digitalWrite(slaveSelect, HIGH); // HIGH - disable device
sensor = MLX90316();
sensor.attach(slaveSelect, sck, miso);
}
void MagnetSensor::update() {
currentAngle = sensor.readAngle();
calculateNewPosition(currentAngle);
}
void MagnetSensor::calculateNewPosition(int angle) {
if (angle < 0) // angle should be between 0..3600, otherwise an error occurred
return;
int delta = angle - anglePrevious;
if (abs(delta) < 10) // only count changes larger than 1 degree
return;
anglePrevious = angle;
if (delta <= -1800) {
knownAngle += 3600;
}
else if (delta >= 1800) {
knownAngle -= 3600;
}
positionTotal = -(knownAngle + angle - angleInitial);
}
void MagnetSensor::reset() {
angleInitial = sensor.readAngle();
anglePrevious = angleInitial;
knownAngle = 0;
positionTotal = 0;
}
long MagnetSensor::getPositionTotal() {
return positionTotal;
}
long MagnetSensor::getCurrentDelta() {
return getPositionTotal() - positionPrevious;
}
void MagnetSensor::resetCurrentDelta() {
positionPrevious = getPositionTotal();
}
| [
"[email protected]"
] | [
[
[
1,
58
]
]
] |
44692a6ecae6e485601bde9a58e7c0e9374c0d72 | ea2ebb5e92b4391e9793c5a326d0a31758c2a0ec | /Bomberman/Bomberman/TrigBomb.cpp | 80671327a78e344bec6e49427fcfbfebffa8fe1b | [] | no_license | weimingtom/bombman | d0f022541e9c550af7c6dbd26481771c94828460 | d73ee4c680423a79826187013d343111a62f89b7 | refs/heads/master | 2021-01-10T01:36:39.712497 | 2011-05-01T07:03:16 | 2011-05-01T07:03:16 | 44,462,509 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101 | cpp | #include "TrigBomb.h"
void TrigBomb::Init( FSM* fsm )
{
}
State* TrigBomb::Update()
{
} | [
"yvetterowe1116@d9104e88-05a6-3fce-0cda-3a6fd9c40cd8"
] | [
[
[
1,
11
]
]
] |
78eeaf66fce92bd9edda7188fb991b18812f879d | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/RollupCtrl/RollupCtrl.cpp | 2729daa44575fa414274b59a53d5d913ab90d58a | [] | no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,135 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// RollupCtrl.cpp
//
//
// Code Johann Nadalutti
// Mail: [email protected]
//
//////////////////////////////////////////////////////////////////////////////
//
// This code is free for personal and commercial use, providing this
// notice remains intact in the source files and all eventual changes are
// clearly marked with comments.
//
// No warrantee of any kind, express or implied, is included with this
// software; use at your own risk, responsibility for damages (if any) to
// anyone resulting from the use of this software rests entirely with the
// user.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RollupCtrl.h"
#pragma warning( disable : 4312 4311 )
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CRollupCtrl Message Map
BEGIN_MESSAGE_MAP(CRollupCtrl, CWnd)
//{{AFX_MSG_MAP(CRollupCtrl)
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_MOUSEWHEEL()
ON_WM_CONTEXTMENU()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRollupCtrl Implementation
IMPLEMENT_DYNCREATE(CRollupCtrl, CWnd)
//---------------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------------
CRollupCtrl::CRollupCtrl()
{
m_strMyClass = AfxRegisterWndClass(
CS_VREDRAW | CS_HREDRAW,
(HCURSOR)::LoadCursor(NULL, IDC_ARROW),
(HBRUSH)(COLOR_BTNSHADOW),
NULL);
m_StartYPos = m_PageHeight = 0;
m_nColumnWidth=200;
m_bEnabledAutoColumns=FALSE;
}
//---------------------------------------------------------------------------
// Destructor
//---------------------------------------------------------------------------
CRollupCtrl::~CRollupCtrl()
{
//Remove all pages allocations
for (int i=0; i<m_PageList.GetSize(); i++)
{
RC_PAGEINFO* pi = m_PageList[i];
if (pi->pwndButton) delete pi->pwndButton;
if (pi->pwndGroupBox) delete pi->pwndGroupBox;
if (pi->pwndTemplate)
{
if (pi->bAutoDestroyTpl) {
pi->pwndTemplate->DestroyWindow();
delete pi->pwndTemplate;
} else {
//pi->pwndTemplate->ShowWindow(SW_HIDE);
::SetWindowLong(pi->pwndTemplate->m_hWnd, DWL_DLGPROC, (LONG)pi->pOldDlgProc);
}
}
delete pi;
}
}
//---------------------------------------------------------------------------
// Create
//---------------------------------------------------------------------------
BOOL CRollupCtrl::Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID)
{
BOOL bRet = CWnd::Create(m_strMyClass, _T("RollupCtrl"), dwStyle, rect, pParentWnd, nID);
return bRet;
}
//---------------------------------------------------------------------------
// Function name : InsertPage
// Description : return -1 if an error occurs
//---------------------------------------------------------------------------
int CRollupCtrl::InsertPage(const TCHAR* caption, UINT nIDTemplate, int idx)
{
if (idx>0 && idx>=m_PageList.GetSize()) idx=-1;
//Create Template
CDialog* wndtemplate = new CDialog(nIDTemplate, this);
BOOL b = wndtemplate->Create(nIDTemplate, this);
if (!b) { delete wndtemplate; return -1; }
//Insert Page
return _InsertPage(caption, wndtemplate, idx, TRUE);
}
//---------------------------------------------------------------------------
// Function name : InsertPage
// Description : return -1 if an error occurs
//---------------------------------------------------------------------------
int CRollupCtrl::InsertPage(const TCHAR* caption, UINT nIDTemplate, CRuntimeClass* rtc, int idx)
{
if (idx>0 && idx>=m_PageList.GetSize()) idx=-1;
//Create Template
ASSERT(rtc!=NULL);
CDialog* wndtemplate = (CDialog*)rtc->CreateObject();
BOOL b = wndtemplate->Create(nIDTemplate, this);
if (!b) { delete wndtemplate; return -1; }
//Insert Page
return _InsertPage(caption, wndtemplate, idx, TRUE);
}
//---------------------------------------------------------------------------
// Function name : InsertPage
// Description : return -1 if an error occurs
// Make sure template had WS_CHILD style
//---------------------------------------------------------------------------
int CRollupCtrl::InsertPage(LPCTSTR caption, CDialog* pwndTemplate, BOOL bAutoDestroyTpl, int idx)
{
if (!pwndTemplate) return -1;
if (idx>0 && idx>=m_PageList.GetSize()) idx=-1;
//Insert Page
return _InsertPage(caption, pwndTemplate, idx, bAutoDestroyTpl);
}
//---------------------------------------------------------------------------
// Function name : _InsertPage
// Description : Called by InsertPage(...) methods
// Return -1 if an error occurs
//---------------------------------------------------------------------------
int CRollupCtrl::_InsertPage(const TCHAR* caption, CDialog* pwndTemplate, int idx, BOOL bAutoDestroyTpl)
{
ASSERT(pwndTemplate!=NULL);
ASSERT(pwndTemplate->m_hWnd!=NULL);
//Get client rect
CRect r; GetClientRect(r);
//Create GroupBox
CButton* groupbox = new CButton;
groupbox->Create(_T(""), WS_CHILD|BS_GROUPBOX, r, this, 0 );
//Create Button
CButton* but = new CButton;
but->Create(caption, WS_CHILD|BS_AUTOCHECKBOX|BS_PUSHLIKE|BS_FLAT, r, this, 0 );
//Change Button's font
HFONT hfont= (HFONT)::GetStockObject(DEFAULT_GUI_FONT);
CFont* font = CFont::FromHandle(hfont);
but->SetFont(font);
//Add page at pagelist
RC_PAGEINFO* pi = new RC_PAGEINFO;
pi->cstrCaption = caption;
pi->bExpanded = FALSE;
pi->bEnable = TRUE;
pi->pwndTemplate = pwndTemplate;
pi->pwndButton = but;
pi->pwndGroupBox = groupbox;
pi->pOldDlgProc = (WNDPROC)::GetWindowLong(pwndTemplate->m_hWnd, DWL_DLGPROC);
pi->pOldButProc = (WNDPROC)::GetWindowLong(but->m_hWnd, GWL_WNDPROC);
pi->bAutoDestroyTpl = bAutoDestroyTpl;
int newidx;
if (idx<0) newidx = (int)m_PageList.Add(pi);
else { m_PageList.InsertAt(idx, pi); newidx=idx; }
//Set Dlg Window datas
::SetWindowLong(pwndTemplate->m_hWnd, GWL_USERDATA, (LONG)m_PageList[newidx]);
::SetWindowLong(pwndTemplate->m_hWnd, DWL_USER, (LONG)this);
//Set But Window data
::SetWindowLong(but->m_hWnd, GWL_USERDATA, (LONG)m_PageList[newidx]);
//SubClass Template window proc
::SetWindowLong(pwndTemplate->m_hWnd, DWL_DLGPROC, (LONG)CRollupCtrl::DlgWindowProc);
//SubClass Button window proc
::SetWindowLong(but->m_hWnd, GWL_WNDPROC, (LONG)CRollupCtrl::ButWindowProc);
//Update
m_PageHeight+=RC_PGBUTTONHEIGHT+(RC_GRPBOXINDENT/2);
RecalLayout();
return newidx;
}
//---------------------------------------------------------------------------
// Function name : RemovePage
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::RemovePage(int idx)
{
if (idx>=m_PageList.GetSize() || idx<0) return;
//Remove
_RemovePage(idx);
//Update
RecalLayout();
}
//---------------------------------------------------------------------------
// Function name : RemoveAllPages
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::RemoveAllPages()
{
//Remove all
while (m_PageList.GetSize()) _RemovePage(0);
//Update
RecalLayout();
}
//---------------------------------------------------------------------------
// Function name : _RemovePage
// Description : Called by RemovePage or RemoveAllPages methods
//---------------------------------------------------------------------------
void CRollupCtrl::_RemovePage(int idx)
{
RC_PAGEINFO* pi = m_PageList[idx];
//Get Page Rect
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
//Update PageHeight
m_PageHeight-=RC_PGBUTTONHEIGHT+(RC_GRPBOXINDENT/2);
if (pi->bExpanded) m_PageHeight-=tr.Height();
//Remove wnds
if (pi->pwndButton) delete pi->pwndButton;
if (pi->pwndGroupBox) delete pi->pwndGroupBox;
if (pi->pwndTemplate)
{
if (pi->bAutoDestroyTpl) {
pi->pwndTemplate->DestroyWindow();
delete pi->pwndTemplate;
} else {
pi->pwndTemplate->ShowWindow(SW_HIDE);
::SetWindowLong(pi->pwndTemplate->m_hWnd, DWL_DLGPROC, (LONG)pi->pOldDlgProc);
}
}
//Remove page from array
m_PageList.RemoveAt(idx);
//Delete pageinfo
delete pi;
}
//---------------------------------------------------------------------------
// Function name : ExpandPage
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::ExpandPage(int idx, BOOL bExpand, BOOL bScrollToPage)
{
if (idx>=m_PageList.GetSize() || idx<0) return;
//Expand-collapse
_ExpandPage(m_PageList[idx], bExpand);
//Update
RecalLayout();
//Scroll to this page (Automatic page visibility)
if (bScrollToPage&&bExpand) ScrollToPage(idx, FALSE);
}
//---------------------------------------------------------------------------
// Function name : ExpandAllPages
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::ExpandAllPages(BOOL bExpand)
{
//Expand-collapse All
for (int i=0; i<m_PageList.GetSize(); i++)
_ExpandPage(m_PageList[i], bExpand);
//Update
RecalLayout();
}
//---------------------------------------------------------------------------
// Function name : _ExpandPage
// Description : Called by ExpandPage or ExpandAllPages methods
//---------------------------------------------------------------------------
void CRollupCtrl::_ExpandPage(RC_PAGEINFO* pi, BOOL bExpand)
{
//Check if we need to change state
if (pi->bExpanded==bExpand) return;
if (!pi->bEnable) return;
//Get Page Rect
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
//Expand-collapse
pi->bExpanded = bExpand;
if (bExpand) m_PageHeight+=tr.Height();
else m_PageHeight-=tr.Height();
}
//---------------------------------------------------------------------------
// Function name : EnablePage
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::EnablePage(int idx, BOOL bEnable)
{
if (idx>=m_PageList.GetSize() || idx<0) return;
//Enable-Disable
_EnablePage(m_PageList[idx], bEnable);
//Update
RecalLayout();
}
//---------------------------------------------------------------------------
// Function name : EnableAllPages
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::EnableAllPages(BOOL bEnable)
{
//Enable-disable All
for (int i=0; i<m_PageList.GetSize(); i++)
_EnablePage(m_PageList[i], bEnable);
//Update
RecalLayout();
}
//---------------------------------------------------------------------------
// Function name : _EnablePage
// Description : Called by EnablePage or EnableAllPages methods
//---------------------------------------------------------------------------
void CRollupCtrl::_EnablePage(RC_PAGEINFO* pi, BOOL bEnable)
{
//Check if we need to change state
if (pi->bEnable==bEnable) return;
//Get Page Rect
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
//Change state
pi->bEnable = bEnable;
if (pi->bExpanded) { m_PageHeight-=tr.Height(); pi->bExpanded=FALSE; }
}
//---------------------------------------------------------------------------
// Function name : ScrollToPage
// Description : Scroll a page at the top of the RollupCtrl if bAtTheTop=TRUE
// or just ensure page visibility into view if bAtTheTop=FALSE
//---------------------------------------------------------------------------
void CRollupCtrl::ScrollToPage(int idx, BOOL bAtTheTop)
{
if (idx>=m_PageList.GetSize() || idx<0) return;
//Get page infos
RC_PAGEINFO* pi = m_PageList[idx];
//Get windows rect
CRect r; GetWindowRect(&r);
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
//Check page visibility
if (bAtTheTop || ((tr.bottom>r.bottom) || (tr.top<r.top)))
{
//Compute new m_nStartYPos
pi->pwndButton->GetWindowRect(&tr);
m_StartYPos-= (tr.top-r.top);
//Update
RecalLayout();
}
}
//---------------------------------------------------------------------------
// Function name : MovePageAt
// Description : newidx can be equal to -1 (move at end)
// Return -1 if an error occurs
//---------------------------------------------------------------------------
int CRollupCtrl::MovePageAt(int idx, int newidx)
{
if (idx==newidx) return -1;
if (idx>=m_PageList.GetSize() || idx<0) return -1;
if (newidx>0 && newidx>=m_PageList.GetSize()) newidx=-1;
//Remove page from its old position
RC_PAGEINFO* pi = m_PageList[idx];
m_PageList.RemoveAt(idx);
//Insert at its new position
int retidx;
if (newidx<0) retidx = (int)m_PageList.Add(pi);
else { m_PageList.InsertAt(newidx, pi); retidx=newidx; }
//Update
RecalLayout();
return retidx;
}
//---------------------------------------------------------------------------
// Function name : IsPageExpanded
// Description :
//---------------------------------------------------------------------------
BOOL CRollupCtrl::IsPageExpanded(int idx)
{
if (idx>=m_PageList.GetSize() || idx<0) return FALSE;
return m_PageList[idx]->bExpanded;
}
//---------------------------------------------------------------------------
// Function name : IsPageEnabled
// Description :
//---------------------------------------------------------------------------
BOOL CRollupCtrl::IsPageEnabled(int idx)
{
if (idx>=m_PageList.GetSize() || idx<0) return FALSE;
return m_PageList[idx]->bEnable;
}
//---------------------------------------------------------------------------
// Function name : RecalLayout
// Description :
//---------------------------------------------------------------------------
void CRollupCtrl::RecalLayout()
{
//Check StartPosY
CRect r; GetClientRect(&r);
int BottomPagePos = m_StartYPos+m_PageHeight;
int nWidth = r.Width();
int nHeight = r.Height();
if (BottomPagePos<nHeight) m_StartYPos = nHeight-m_PageHeight;
if (m_StartYPos>0) m_StartYPos = 0;
////////////////////////////////////////////
//Calc new pages's positions
// used column sub-divisions if necessary
int nPageWidth = nWidth-RC_SCROLLBARWIDTH;
if (m_bEnabledAutoColumns)
{
nPageWidth=m_nColumnWidth;
if (nPageWidth>nWidth-RC_SCROLLBARWIDTH)
nPageWidth=nWidth-RC_SCROLLBARWIDTH;
}
int posx=0;
int posy=0;
int nMaxHeight=-1;
CArray<CPoint, CPoint&> carrayPos;
for (int i=0; i<m_PageList.GetSize(); i++)
{
RC_PAGEINFO* pi = m_PageList[i];
//Page Height
int nCurPageHeight=RC_PGBUTTONHEIGHT+(RC_GRPBOXINDENT/2);
if (pi->bExpanded && pi->bEnable)
{
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
nCurPageHeight+=tr.Height();
}
//Split to a new column ?
if (m_bEnabledAutoColumns && ((nWidth-posx-m_nColumnWidth-RC_SCROLLBARWIDTH )>m_nColumnWidth) && i!=0 && (posy+(nCurPageHeight/2))>nHeight)
{
posx+=m_nColumnWidth; //New column
posy=0;
}
CPoint cpos(posx, posy);
carrayPos.Add(cpos);
posy+=nCurPageHeight;
if (posy>nMaxHeight) nMaxHeight=posy;
}
if (nMaxHeight!=-1)
{
m_PageHeight=nMaxHeight;
BottomPagePos = m_StartYPos+m_PageHeight;
if (BottomPagePos<nHeight) m_StartYPos = nHeight-m_PageHeight;
if (m_StartYPos>0) m_StartYPos = 0;
}
////////////////////////////////////////////
//Update children windows position
HDWP hdwp = BeginDeferWindowPos((int)m_PageList.GetSize()*3); //*3 for pwndButton+pwndTemplate+pwndGroupBox
if (hdwp)
{
int posx=0;
int posy=m_StartYPos;
for (int i=0; i<m_PageList.GetSize(); i++)
{
RC_PAGEINFO* pi = m_PageList[i];
posx=carrayPos[i].x;
posy=carrayPos[i].y+m_StartYPos;
//Enable-Disable Button
pi->pwndButton->SetCheck(pi->bEnable&pi->bExpanded);
pi->pwndButton->EnableWindow(pi->bEnable);
//Update Button's position and size
//Expanded
if (pi->bExpanded && pi->bEnable)
{
CRect tr; pi->pwndTemplate->GetWindowRect(&tr);
//Update GroupBox position and size
DeferWindowPos(hdwp, pi->pwndGroupBox->m_hWnd, 0, posx+2, posy, nPageWidth-3, tr.Height()+RC_PGBUTTONHEIGHT+RC_GRPBOXINDENT-4, SWP_NOZORDER|SWP_SHOWWINDOW);
//Update Template position and size
DeferWindowPos(hdwp, pi->pwndTemplate->m_hWnd, 0, posx+RC_GRPBOXINDENT, posy+RC_PGBUTTONHEIGHT, nPageWidth-(RC_GRPBOXINDENT*2), tr.Height(), SWP_NOZORDER);
//Update Button's position and size
DeferWindowPos(hdwp, pi->pwndButton->m_hWnd, 0, posx+RC_GRPBOXINDENT, posy, nPageWidth-(RC_GRPBOXINDENT*2), RC_PGBUTTONHEIGHT, SWP_NOZORDER|SWP_SHOWWINDOW);
//Collapsed
} else {
//Update GroupBox position and size
DeferWindowPos(hdwp, pi->pwndGroupBox->m_hWnd, 0, posx+2, posy, nPageWidth-3, 16, SWP_NOZORDER|SWP_SHOWWINDOW);
//Update Template position and size
DeferWindowPos(hdwp, pi->pwndTemplate->m_hWnd, 0, posx+RC_GRPBOXINDENT, 0, 0, 0,SWP_NOZORDER|SWP_HIDEWINDOW|SWP_NOSIZE|SWP_NOMOVE);
//Update Button's position and size
DeferWindowPos(hdwp, pi->pwndButton->m_hWnd, 0, posx+RC_GRPBOXINDENT, posy, nPageWidth-(RC_GRPBOXINDENT*2), RC_PGBUTTONHEIGHT, SWP_NOZORDER|SWP_SHOWWINDOW);
}
}
EndDeferWindowPos(hdwp);
}
////////////////////////////////////////////
//Update children windows visibility
hdwp = BeginDeferWindowPos((int)m_PageList.GetSize());
if (hdwp)
{
for (int i=0; i<m_PageList.GetSize(); i++){
RC_PAGEINFO* pi = m_PageList[i];
//Expanded
if (pi->bExpanded && pi->bEnable) {
DeferWindowPos(hdwp, pi->pwndTemplate->m_hWnd, 0, 0, 0, 0, 0, SWP_NOZORDER|SWP_SHOWWINDOW|SWP_NOSIZE|SWP_NOMOVE);
//Collapsed
} else {
DeferWindowPos(hdwp, pi->pwndTemplate->m_hWnd, 0, 0, 0, 0, 0, SWP_NOZORDER|SWP_HIDEWINDOW|SWP_NOSIZE|SWP_NOMOVE);
}
}
EndDeferWindowPos(hdwp);
}
//////////////////////////////////////////
//Update Scroll Bar
CRect br = CRect(r.right-RC_SCROLLBARWIDTH,r.top, r.right, r.bottom);
InvalidateRect(&br, FALSE);
UpdateWindow();
}
//---------------------------------------------------------------------------
// Function name : GetPageIdxFromButtonHWND
// Description : Return -1 if matching hwnd not found
//---------------------------------------------------------------------------
int CRollupCtrl::GetPageIdxFromButtonHWND(HWND hwnd)
{
//Search matching button's hwnd
for (int i=0; i<m_PageList.GetSize(); i++)
if (hwnd==m_PageList[i]->pwndButton->m_hWnd) return i;
return -1;
}
//---------------------------------------------------------------------------
// Function name : GetPageInfo
// Description : Return -1 if an error occurs
//---------------------------------------------------------------------------
const RC_PAGEINFO* CRollupCtrl::GetPageInfo(int idx)
{
if (idx>=m_PageList.GetSize() || idx<0) return (RC_PAGEINFO*)-1;
return m_PageList[idx];
}
//---------------------------------------------------------------------------
// Function name : EnableAutoColumns
// Description : ...
//---------------------------------------------------------------------------
void CRollupCtrl::EnableAutoColumns(BOOL bEnable)
{
if (m_bEnabledAutoColumns!=bEnable)
{
m_bEnabledAutoColumns=bEnable;
RecalLayout();
}
}
//---------------------------------------------------------------------------
// Function name : SetColumnWidth
// Description : ...
//---------------------------------------------------------------------------
BOOL CRollupCtrl::SetColumnWidth(int nWidth)
{
if (nWidth>RC_MINCOLUMNWIDTH)
{
m_nColumnWidth=nWidth;
RecalLayout();
return TRUE;
}
return FALSE;
}
//---------------------------------------------------------------------------
// Function name : SetPageCaption
// Description : ...
//---------------------------------------------------------------------------
BOOL CRollupCtrl::SetPageCaption(int idx, LPCTSTR caption)
{
if (idx>=m_PageList.GetSize() || idx<0) return FALSE;
m_PageList[idx]->pwndButton->SetWindowText(caption);
m_PageList[idx]->cstrCaption = caption;
return TRUE;
}
//---------------------------------------------------------------------------
// SubClasser
//---------------------------------------------------------------------------
LRESULT CALLBACK CRollupCtrl::DlgWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
RC_PAGEINFO* pi = (RC_PAGEINFO*)GetWindowLong(hWnd, GWL_USERDATA);
CRollupCtrl* _this = (CRollupCtrl*)GetWindowLong(hWnd, DWL_USER);
CRect r; _this->GetClientRect(&r);
if (_this->m_PageHeight>r.Height()) //Can Scroll ?
{
switch (uMsg) {
case WM_MBUTTONDOWN:
case WM_LBUTTONDOWN: {
CPoint pos; GetCursorPos(&pos);
_this->m_OldMouseYPos = pos.y;
::SetCapture(hWnd);
::SetFocus(_this->m_hWnd);
break; }
case WM_MBUTTONUP:
case WM_LBUTTONUP:
if (::GetCapture()==hWnd) ::ReleaseCapture();
break;
case WM_MOUSEMOVE: {
if ((wParam==MK_LBUTTON||wParam==MK_MBUTTON) && ::GetCapture()==hWnd) {
CPoint pos; GetCursorPos(&pos);
_this->m_StartYPos+=(pos.y-_this->m_OldMouseYPos);
_this->RecalLayout();
_this->m_OldMouseYPos = pos.y;
//return 0;
}
break;}
case WM_SETCURSOR:
{
if ((HWND)wParam==hWnd) { ::SetCursor(::LoadCursor(NULL, RC_CURSOR)); return TRUE; }
break;
}
}//switch(uMsg)
}
return ::CallWindowProc(pi->pOldDlgProc, hWnd, uMsg, wParam, lParam);
}
//---------------------------------------------------------------------------
// Button SubClasser
//---------------------------------------------------------------------------
LRESULT CALLBACK CRollupCtrl::ButWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg==WM_SETFOCUS) return FALSE;
RC_PAGEINFO* pi = (RC_PAGEINFO*)GetWindowLong(hWnd, GWL_USERDATA);
return ::CallWindowProc(pi->pOldButProc, hWnd, uMsg, wParam, lParam);
}
/////////////////////////////////////////////////////////////////////////////
// CRollupCtrl message handlers
//---------------------------------------------------------------------------
// OnCommand
//---------------------------------------------------------------------------
BOOL CRollupCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
if (LOWORD(wParam)==RC_MID_COLLAPSEALL) {
ExpandAllPages(FALSE);
return TRUE;
} else if (LOWORD(wParam)==RC_MID_EXPANDALL) {
ExpandAllPages(TRUE);
return TRUE;
} else if (LOWORD(wParam)>=RC_MID_STARTPAGES
&& LOWORD(wParam)<RC_MID_STARTPAGES+GetPagesCount())
{
int idx = LOWORD(wParam)-RC_MID_STARTPAGES;
ExpandPage(idx, !IsPageExpanded(idx) );
} else if (HIWORD(wParam)==BN_CLICKED) {
int idx = GetPageIdxFromButtonHWND((HWND)lParam);
if (idx!=-1) {
RC_PAGEINFO* pi = m_PageList[idx];
ExpandPage(idx, !pi->bExpanded);
SetFocus();
return TRUE;
}
}
return CWnd::OnCommand(wParam, lParam);
}
//---------------------------------------------------------------------------
// OnPaint
//---------------------------------------------------------------------------
void CRollupCtrl::OnPaint()
{
CPaintDC dc(this);
//Draw ScrollBar
CRect r; GetClientRect(&r);
CRect br = CRect(r.right-RC_SCROLLBARWIDTH,r.top, r.right, r.bottom);
dc.DrawEdge(&br, EDGE_RAISED, BF_RECT );
int SB_Pos = 0;
int SB_Size = 0;
int ClientHeight = r.Height()-4;
if (m_PageHeight>r.Height()) {
SB_Size = ClientHeight-(((m_PageHeight-r.Height())*ClientHeight)/m_PageHeight);
SB_Pos = -(m_StartYPos*ClientHeight)/m_PageHeight;
} else {
SB_Size = ClientHeight;
}
br.left +=2;
br.right -=1;
br.top = SB_Pos+2;
br.bottom = br.top+SB_Size;
dc.FillSolidRect(&br, RC_SCROLLBARCOLOR);
dc.FillSolidRect(CRect(br.left,2,br.right,br.top), RGB(0,0,0));
dc.FillSolidRect(CRect(br.left,br.bottom,br.right,2+ClientHeight), RGB(0,0,0));
// Do not call CWnd::OnPaint() for painting messages
}
//---------------------------------------------------------------------------
// OnSize
//---------------------------------------------------------------------------
void CRollupCtrl::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
RecalLayout();
}
//---------------------------------------------------------------------------
// OnLButtonDown
//---------------------------------------------------------------------------
void CRollupCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
CRect r; GetClientRect(&r);
if (m_PageHeight>r.Height())
{
//Click on scroll bar client rect
CRect br = CRect(r.right-RC_SCROLLBARWIDTH,r.top, r.right, r.bottom);
if ((nFlags&MK_LBUTTON) && br.PtInRect(point)) {
SetCapture();
int ClientHeight = r.Height()-4;
int SB_Size = ClientHeight-(((m_PageHeight-r.Height())*ClientHeight)/m_PageHeight);
int SB_Pos = -(m_StartYPos*ClientHeight)/m_PageHeight;
//Click inside scrollbar cursor
if ((point.y<(SB_Pos+SB_Size)) && (point.y>SB_Pos)) {
m_SBOffset = SB_Pos-point.y+1;
//Click outside scrollbar cursor (2 cases => above or below cursor)
} else {
int distup = point.y-SB_Pos;
int distdown = (SB_Pos+SB_Size)-point.y;
if (distup<distdown) m_SBOffset = 0; //above
else m_SBOffset = -SB_Size; //below
}
//Calc new m_StartYPos from mouse pos
int TargetPos = point.y + m_SBOffset;
m_StartYPos=-(TargetPos*m_PageHeight)/(ClientHeight);
//Update
RecalLayout();
}
//Click on scroll bar up button
br = CRect(r.right-RC_SCROLLBARWIDTH,r.top, r.right, r.top);
if ((nFlags&MK_LBUTTON) && br.PtInRect(point)) {
m_StartYPos+=32;
RecalLayout();
}
//Click on scroll bar down button
br = CRect(r.right-RC_SCROLLBARWIDTH,r.bottom, r.right, r.bottom);
if ((nFlags&MK_LBUTTON) && br.PtInRect(point)) {
m_StartYPos-=32;
RecalLayout();
}
}
CWnd::OnLButtonDown(nFlags, point);
}
//---------------------------------------------------------------------------
// OnLButtonUp
//---------------------------------------------------------------------------
void CRollupCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
ReleaseCapture();
CWnd::OnLButtonUp(nFlags, point);
}
//---------------------------------------------------------------------------
// OnMouseMove
//---------------------------------------------------------------------------
void CRollupCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
CRect r; GetClientRect(&r);
if (m_PageHeight>r.Height())
{
if ((nFlags&MK_LBUTTON) && (GetCapture()==this)) {
//Calc new m_StartYPos from mouse pos
int ClientHeight = r.Height() - 4;
int TargetPos = point.y + m_SBOffset;
m_StartYPos=-(TargetPos*m_PageHeight)/ClientHeight;
//Update
RecalLayout();
}
}
CWnd::OnMouseMove(nFlags, point);
}
//---------------------------------------------------------------------------
// OnMouseWheel
//---------------------------------------------------------------------------
BOOL CRollupCtrl::OnMouseWheel( UINT nFlags, short zDelta, CPoint pt)
{
m_StartYPos+=(zDelta/4);
RecalLayout();
return CWnd::OnMouseWheel(nFlags, zDelta, pt);
}
//---------------------------------------------------------------------------
// OnContextMenu
//---------------------------------------------------------------------------
void CRollupCtrl::OnContextMenu( CWnd* /*pWnd*/, CPoint pos )
{
//TRACE("CRollupCtrl::OnContextMenu\n");
if (m_cmenuCtxt.m_hMenu) m_cmenuCtxt.DestroyMenu();
if (m_cmenuCtxt.CreatePopupMenu())
{
GetCursorPos(&pos); //Cursor position even with keyboard 'Context key'
m_cmenuCtxt.AppendMenu(MF_STRING, RC_MID_EXPANDALL, _T("Ouvrir les pages...") );
m_cmenuCtxt.AppendMenu(MF_STRING, RC_MID_COLLAPSEALL, _T("Fermer les pages...") );
m_cmenuCtxt.AppendMenu(MF_SEPARATOR,0, _T("") );
//Add all pages with checked style for expanded ones
for (int i=0; i<m_PageList.GetSize(); i++) {
CString cstrPageName;
m_PageList[i]->pwndButton->GetWindowText(cstrPageName);
m_cmenuCtxt.AppendMenu(MF_STRING, RC_MID_STARTPAGES+i, cstrPageName);
if (m_PageList[i]->bExpanded)
m_cmenuCtxt.CheckMenuItem(RC_MID_STARTPAGES+i, MF_CHECKED);
}
m_cmenuCtxt.TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, pos.x, pos.y, this);
}
}
| [
"[email protected]"
] | [
[
[
1,
974
]
]
] |
ceadc9b5b0f8e390881a0c31d673310f7e3c662a | 06b2d2df5f39e37b74b68a56381c7eabb8c44e3c | /Transmit.cpp | 8a86f65565bc73d79de9c3078f5bbefe46be5f31 | [] | no_license | wonjb/wprobot | e6ccf1badcd1801d9a1be4b8aba7a05b5c8f296b | 5f1a133c1681925f028514dd2d86d03947471bee | refs/heads/master | 2021-01-01T05:40:23.339929 | 2008-09-05T09:12:48 | 2008-09-05T09:12:48 | 34,102,331 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,472 | cpp | #include "stdafx.h"
#include "Transmit.h"
#include "wpRobot(ver2.0).h"
#include "wpRobot(ver2.0)Dlg.h"
CTransmit::CTransmit()
: m_handPt(CHandPoint::NOTHING)
, m_pastPt(CHandPoint::NOTHING)
{
}
CTransmit::~CTransmit(void)
{
}
void CTransmit::Initalize()
{
setWindowRegn();
}
void CTransmit::setWindowRegn()
{
m_winRegn = ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->m_paint.getMSPaintRegn();
}
void CTransmit::setHandPointer(CHandPoint handPt)
{
m_handPt = handPt;
}
void CTransmit::Transmit()
{
transmitWindow();
m_pastPt = m_handPt;
}
void CTransmit::transmitWindow()
{
////////// 여러번 나오는 현상을 막기위한!
// TCHAR buf[256] = {0,};
// static int n, test = 0;
// if(m_pastPt.m_mode == m_handPt.m_mode && m_handPt.m_mode == CHandPoint::CLEAR)
// {
// ++n, ++test;
// swprintf(buf, sizeof(buf), _T("통신 Connecting...%d"), n/10);
// ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(buf);
// if(n == 100)
// {
// m_robot.CComStart() == TRUE ? ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 Start!"))
// : ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 End!"));
// n = 0;
// }
// }
// else if(m_pastPt.m_mode == m_handPt.m_mode)
// ++test;
// else
// n = 0, test = 0;
// if(test < 10)
// return;
// ////////// Hardware 와 Test하기 위해!
m_robot.CComStart() == TRUE ? ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 Start!"))
: ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 End!"));
///////////////
m_robot.SendPointer(0,0);
::Sleep(4000);
m_robot.SendPointer(200,0);
::Sleep(4000);
// m_robot.SendPointer(0,200);
// ::Sleep(4000);
// m_robot.SendPointer(0,40);
// ::Sleep(4000);
// m_robot.SendPointer(0,60);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
// m_robot.SendPointer(0,0);
// ::Sleep(4000);
///////////////
////////// Software 정말 소스!
// if(m_pastPt.m_mode == m_handPt.m_mode && (m_handPt.m_mode != CHandPoint::DRAW && m_handPt.m_mode != CHandPoint::MOVE))
// return;
//
// m_pParam.m_address = this;
// m_pParam.m_rt = m_winRegn;
// CMSPaint* pPaint = &(((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->m_paint);
// switch(m_handPt.m_mode)
// {
// case CHandPoint::CIRCLE : ::CloseHandle(::CreateThread(NULL, NULL, CallBackDrawCIRCLE, &m_pParam, 0, 0));
// return;
// case CHandPoint::RECT : ::CloseHandle(::CreateThread(NULL, NULL, CallBackDrawRECT, &m_pParam, 0, 0));
// return;
// case CHandPoint::TRIANGE: ::CloseHandle(::CreateThread(NULL, NULL, CallBackDrawTRIANGLE, &m_pParam, 0, 0));
// return;
// case CHandPoint::STAR : ::CloseHandle(::CreateThread(NULL, NULL, CallBackDrawSTAR, &m_pParam, 0, 0));
// return;
// case CHandPoint::DRAW : pPaint->clickPointer(m_handPt.m_nX,m_handPt.m_nY);
// m_robot.SendPointer(m_handPt.m_nX,m_handPt.m_nY);
// break;
// case CHandPoint::MOVE : pPaint->movePointer(m_handPt.m_nX,m_handPt.m_nY);
// m_robot.SetColor(pPaint->inColorRegn(m_handPt.m_nX,m_handPt.m_nY));
// break;
// case CHandPoint::CLEAR : m_robot.CComStart() == TRUE ? ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 Start!"))
// : ((CwpRobotver20Dlg*)(theApp.m_pMainWnd))->SetWindowText(_T("Robot 통신 End!"));
// pPaint->InitializeRegn();
// break;
// case CHandPoint::SETTING:
// break;
// }
}
void CTransmit::convertCIRCLE(CRect regn)
{
int x, y, tx, ty;
double pi = 3.1415;
int radius = 50;
CwpRobotver20Dlg* pDlg = (CwpRobotver20Dlg*)(theApp.m_pMainWnd);
tx = (int)(m_handPt.m_nX + radius*cos(360*pi/180));
ty = (int)(m_handPt.m_nY - radius*sin(360*pi/180));
pDlg->m_paint.movePointer(tx, ty);
for(double theta = 0; theta <= 360; ++theta)
{
x = (int)(m_handPt.m_nX + radius*cos(theta*pi/180));
y = (int)(m_handPt.m_nY - radius*sin(theta*pi/180));
pDlg->m_paint.clickPointer(x, y);
m_robot.SendPointer(x, y);
tx = x, ty = y;
}
}
void CTransmit::convertRECT(CRect regn)
{
int x, y, tx, ty;
int w = 70, h = 50;
CwpRobotver20Dlg* pDlg = (CwpRobotver20Dlg*)(theApp.m_pMainWnd);
tx = (int)(m_handPt.m_nX - w);
ty = (int)(m_handPt.m_nY - h);
pDlg->m_paint.movePointer(tx, ty);
x = (int)(m_handPt.m_nX + w);
y = (int)(m_handPt.m_nY - h);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX + w);
y = (int)(m_handPt.m_nY + h);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - w);
y = (int)(m_handPt.m_nY + h);
pDlg->m_paint.clickPointer(x, y);
pDlg->m_paint.clickPointer(tx, ty);
}
void CTransmit::convertTRIANGLE(CRect regn)
{
int x, y, tx, ty;
int radius = 50;
CwpRobotver20Dlg* pDlg = (CwpRobotver20Dlg*)(theApp.m_pMainWnd);
tx = (int)(m_handPt.m_nX);
ty = (int)(m_handPt.m_nY - radius);
pDlg->m_paint.movePointer(tx, ty);
x = (int)(m_handPt.m_nX + 25*sqrt(3.f));
y = (int)(m_handPt.m_nY + 25);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - 25*sqrt(3.f));
y = (int)(m_handPt.m_nY + 25);
pDlg->m_paint.clickPointer(x, y);
pDlg->m_paint.clickPointer(tx, ty);
}
void CTransmit::convertSTAR(CRect regn)
{
int x, y, tx, ty;
CwpRobotver20Dlg* pDlg = (CwpRobotver20Dlg*)(theApp.m_pMainWnd);
tx = (int)(m_handPt.m_nX);
ty = (int)(m_handPt.m_nY - 50);
pDlg->m_paint.movePointer(tx, ty);
x = (int)(m_handPt.m_nX + 20);
y = (int)(m_handPt.m_nY - 20);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX + 50);
y = (int)(m_handPt.m_nY - 10);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX + 20);
y = (int)(m_handPt.m_nY + 30);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX + 30);
y = (int)(m_handPt.m_nY + 50);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX);
y = (int)(m_handPt.m_nY + 25);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - 30);
y = (int)(m_handPt.m_nY + 50);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - 20);
y = (int)(m_handPt.m_nY + 30);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - 50);
y = (int)(m_handPt.m_nY - 10);
pDlg->m_paint.clickPointer(x, y);
x = (int)(m_handPt.m_nX - 20);
y = (int)(m_handPt.m_nY - 20);
pDlg->m_paint.clickPointer(x, y);
pDlg->m_paint.clickPointer(tx, ty);
}
DWORD WINAPI CallBackDrawCIRCLE(LPVOID lpParam)
{
PARAM* pParam = (PARAM*)lpParam;
((CTransmit*)(pParam->m_address))->convertCIRCLE(pParam->m_rt);
return 0;
}
DWORD WINAPI CallBackDrawRECT(LPVOID lpParam)
{
PARAM* pParam = (PARAM*)lpParam;
((CTransmit*)(pParam->m_address))->convertRECT(pParam->m_rt);
return 0;
}
DWORD WINAPI CallBackDrawTRIANGLE(LPVOID lpParam)
{
PARAM* pParam = (PARAM*)lpParam;
((CTransmit*)(pParam->m_address))->convertTRIANGLE(pParam->m_rt);
return 0;
}
DWORD WINAPI CallBackDrawSTAR(LPVOID lpParam)
{
PARAM* pParam = (PARAM*)lpParam;
((CTransmit*)(pParam->m_address))->convertSTAR(pParam->m_rt);
return 0;
} | [
"[email protected]@d3b47800-9755-0410-939a-5b8eb3d84ce7"
] | [
[
[
1,
277
]
]
] |
9a4b5e905739c0d000e15d35c378f4a70ba6dc2b | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/gameplay/src/ncgamecamera/ncgamecamera_cmds.cc | dd07f442f1299afed5ebb084f9ce9810907f4ad8 | [] | no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,043 | cc | #include "precompiled/pchgameplay.h"
//------------------------------------------------------------------------------
// ncgamecamera_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "ncgamecamera/ncgamecamera.h"
#include "napplication/nappviewport.h"
//-----------------------------------------------------------------------------
NSCRIPT_INITCMDS_BEGIN(ncGameCamera)
NSCRIPT_ADDCMD_COMPOBJECT('DNBL', void, Enable, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DDBL', void, Disable, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DIND', const bool, IsEnabled, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSCT', void, SetCameraType, 1, (const ncGameCamera::type), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGCT', const ncGameCamera::type, GetCameraType, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSAC', void, SetAttributes, 1, (const int), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGAC', const int, GetAttributes, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DAAC', void, AddAttributes, 1, (const int), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DRAC', void, RemoveAttributes, 1, (const int), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSAP', void, SetAnchorPoint, 1, (nEntityObject*), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGAP', nEntityObject*, GetAnchorPoint, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSCO', void, SetCameraOffset, 1, (const vector3&), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGCO', const vector3&, GetCameraOffset, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSHH', void, SetHeight, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGHH', const float, GetHeight, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSDD', void, SetDistance, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGDD', const float, GetDistance, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSRR', void, SetRoute, 1, (const int), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGRR', const int, GetRoute, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DUCC', void, Update, 1, (const nTime&), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSVP', void, SetViewPort, 1, (nAppViewport*), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGVP', nAppViewport*, GetViewPort, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DLAT', void, LookAt, 1, (nEntityObject*), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DBLD', void, Build, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSST', void, SetStep, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGST', const float, GetStep, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSTX', void, SetTranspositionXType, 1, (const ncGameCamera::transition), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGTX', const ncGameCamera::transition, GetTranspositionXType, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSTY', void, SetTranspositionYType, 1, (const ncGameCamera::transition), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGTY', const ncGameCamera::transition, GetTranspositionYType, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSTZ', void, SetTranspositionZType, 1, (const ncGameCamera::transition), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGTZ', const ncGameCamera::transition, GetTranspositionZType, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSDA', void, SetDampeningPosition, 1, (const vector3&), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGDA', const vector3&, GetDampeningPosition, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSDO', void, SetDampeningOrientation, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGDO', const float, GetDampeningOrientation, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSMX', void, SetMaxDistance, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGMX', const float, GetMaxDistance, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSMN', void, SetMinDistance, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGMN', const float, GetMinDistance, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSOT', void, SetTranspositionOrientationType, 1, (const ncGameCamera::transition), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGOT', const ncGameCamera::transition, GetTranspositionOrientationType, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DSLO', void, SetLookAtOffset, 1, (const float), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('DGLO', const float, GetLookAtOffset, 0, (), 0, ());
NSCRIPT_INITCMDS_END()
//-----------------------------------------------------------------------------
/**
object persistency
*/
bool ncGameCamera::SaveCmds(nPersistServer *ps)
{
if( !nComponentObject::SaveCmds(ps) )
{
return false;
}
nCmd* cmd(0);
// set camera type
cmd = ps->GetCmd( this->entityObject, 'DSCT');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( int(this->GetCameraType()) );
ps->PutCmd(cmd);
// set attributes
cmd = ps->GetCmd( this->entityObject, 'DSAC');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( this->GetAttributes() );
ps->PutCmd(cmd);
// set camera offset
cmd = ps->GetCmd( this->entityObject, 'DSCO');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetCameraOffset().x );
cmd->In()->SetF( this->GetCameraOffset().y );
cmd->In()->SetF( this->GetCameraOffset().z );
ps->PutCmd(cmd);
// set step
cmd = ps->GetCmd( this->entityObject, 'DSTP');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetStep() );
ps->PutCmd(cmd);
// set kind of dampening in X
cmd = ps->GetCmd( this->entityObject, 'DSTX');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( this->GetTranspositionXType() );
ps->PutCmd(cmd);
// set kind of dampening in Y
cmd = ps->GetCmd( this->entityObject, 'DSTY');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( this->GetTranspositionYType() );
ps->PutCmd(cmd);
// set kind of dampening in Z
cmd = ps->GetCmd( this->entityObject, 'DSTZ');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( this->GetTranspositionZType() );
ps->PutCmd(cmd);
// set dampening position
cmd = ps->GetCmd( this->entityObject, 'DSDA');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetDampeningPosition().x );
cmd->In()->SetF( this->GetDampeningPosition().y );
cmd->In()->SetF( this->GetDampeningPosition().z );
ps->PutCmd(cmd);
// sets the dampening for the orientation
cmd = ps->GetCmd( this->entityObject, 'DSDO');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetDampeningOrientation() );
ps->PutCmd(cmd);
// sets the max distance of the camera
cmd = ps->GetCmd( this->entityObject, 'DSMX');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetMaxDistance() );
ps->PutCmd(cmd);
// sets the min distance of the camera
cmd = ps->GetCmd( this->entityObject, 'DSMN');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetMinDistance() );
ps->PutCmd(cmd);
// sets the orientation transition type
cmd = ps->GetCmd( this->entityObject, 'DSOT');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetI( this->GetTranspositionOrientationType() );
ps->PutCmd(cmd);
// sets the lookat offset in y axis
cmd = ps->GetCmd( this->entityObject, 'DSLO');
n_assert2( cmd, "Error command not found" );
cmd->In()->SetF( this->GetLookAtOffset() );
ps->PutCmd(cmd);
return true;
}
//-----------------------------------------------------------------------------
// EOF
//-----------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
198
]
]
] |
c05a4e717391fcbb78c2ec19a8dc16220ed46103 | 8a0a81978126520c0bfa0d2ad6bd1d35236f1aa2 | /SegmentationRegional/Dep/qwtplot3d-0.2.7/qwtplot3d/examples/mesh2/src/mesh2mainwindow.cpp | bc919db964789a7f8e7d54fd54dcfac83abc3685 | [
"Zlib"
] | permissive | zjucsxxd/BSplineLevelSetRegionalSegmentation | a64b4a096f65736659b6c74dce7cd973815b9a2c | a320ade9386861657476cca7fce97315de5e3e31 | refs/heads/master | 2021-01-20T23:03:26.244747 | 2011-12-10T13:10:56 | 2011-12-10T13:10:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,330 | cpp | #include <qmetaobject.h>
#include <qframe.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qaction.h>
#include <qmenubar.h>
#if QT_VERSION < 0x040000
#include <qpopupmenu.h>
#endif
#include <qtoolbar.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qfiledialog.h>
#include <qstatusbar.h>
#include <qfileinfo.h>
#include <qslider.h>
#include <qtimer.h>
#include <qcombobox.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qcolordialog.h>
#include <qfontdialog.h>
#include "mesh2mainwindow.h"
#include "functions.h"
#include "colormapreader.h"
#include "lightingdlg.h"
#include "femreader.h"
#include "../../../include/qwt3d_io.h"
#include "../../../include/qwt3d_io_gl2ps.h"
#include "../../../include/qwt3d_io_reader.h"
using namespace Qwt3D;
using namespace std;
bool Mesh2MainWindow::connectA (const QObject* sender, const char * slot)
{
#if QT_VERSION < 0x040000
return connect( sender, SIGNAL( activated() ), this, slot );
#else
return connect( sender, SIGNAL( triggered() ), this, slot );
#endif
}
bool Mesh2MainWindow::connectAG (const QObject* sender, const char * slot)
{
#if QT_VERSION < 0x040000
return connect( sender, SIGNAL( selected( QAction* ) ), this, slot ) ;
#else
return connect( sender, SIGNAL( triggered( QAction* ) ), this, slot ) ;
#endif
}
Mesh2MainWindow::~Mesh2MainWindow()
{
delete dataWidget;
}
Mesh2MainWindow::Mesh2MainWindow( QWidget* parent )
: DummyBase( parent )
{
#if QT_VERSION < 0x040000
setCaption("Mesh2");
QGridLayout *grid = new QGridLayout( frame, 0, 0 );
#else
setupWorkaround(this);
setupUi(this);
QGridLayout *grid = new QGridLayout( frame );
#endif
col_ = 0;
legend_ = false;
redrawWait = 50;
activeCoordSystem = None;
dataWidget = new SurfacePlot(frame);
grid->addWidget( dataWidget, 0, 0 );
connectAG( coord, SLOT( pickCoordSystem( QAction* ) ) );
connectAG( plotstyle, SLOT( pickPlotStyle( QAction* ) ) );
connectA( axescolor, SLOT( pickAxesColor() ) );
connectA( backgroundcolor, SLOT( pickBgColor() ) );
connectAG( floorstyle, SLOT( pickFloorStyle( QAction* ) ) );
connectA( meshcolor, SLOT( pickMeshColor() ) );
connectA( numbercolor, SLOT( pickNumberColor() ) );
connectA( labelcolor, SLOT( pickLabelColor() ) );
connectA( titlecolor, SLOT( pickTitleColor() ) );
connectA( datacolor, SLOT( pickDataColor() ) );
connect( lighting, SIGNAL( clicked() ), this, SLOT( pickLighting() ) );
connectA( resetcolor, SLOT( resetColors() ) );
connectA( numberfont, SLOT( pickNumberFont() ) );
connectA( labelfont, SLOT( pickLabelFont() ) );
connectA( titlefont, SLOT( pickTitleFont() ) );
connectA( resetfont, SLOT( resetFonts() ) );
connect( animation, SIGNAL( toggled(bool) ) , this, SLOT( toggleAnimation(bool) ) );
connectA( dump, SLOT( dumpImage() ) );
connectA( openFile, SLOT( open() ) );
//connect(openFile, SIGNAL(triggered()), this, SLOT(open()));
connectA( openMeshFile, SLOT( openMesh() ) );
// only EXCLUSIVE groups emit selected :-/
connect( left, SIGNAL( toggled( bool ) ), this, SLOT( setLeftGrid( bool ) ) );
connect( right, SIGNAL( toggled( bool ) ), this, SLOT( setRightGrid( bool ) ) );
connect( ceil, SIGNAL( toggled( bool ) ), this, SLOT( setCeilGrid( bool ) ) );
connect( floor, SIGNAL( toggled( bool ) ), this, SLOT( setFloorGrid( bool ) ) );
connect( back, SIGNAL( toggled( bool ) ), this, SLOT( setBackGrid( bool ) ) );
connect( front, SIGNAL( toggled( bool ) ), this, SLOT( setFrontGrid( bool ) ) );
timer = new QTimer( this );
connect( timer, SIGNAL(timeout()), this, SLOT(rotate()) );
resSlider->setRange(1,70);
connect( resSlider, SIGNAL(valueChanged(int)), dataWidget, SLOT(setResolution(int)) );
connect( dataWidget, SIGNAL(resolutionChanged(int)), resSlider, SLOT(setValue(int)) );
resSlider->setValue(1);
connect( offsSlider, SIGNAL(valueChanged(int)), this, SLOT(setPolygonOffset(int)) );
connect(normButton, SIGNAL(clicked()), this, SLOT(setStandardView()));
QString qwtstr(" qwtplot3d ");
qwtstr += QString::number(QWT3D_MAJOR_VERSION) + ".";
qwtstr += QString::number(QWT3D_MINOR_VERSION) + ".";
qwtstr += QString::number(QWT3D_PATCH_VERSION) + " ";
QLabel* info = new QLabel(qwtstr, statusBar());
statusBar()->addWidget(info, 0);
filenameWidget = new QLabel(" ", statusBar());
statusBar()->addWidget(filenameWidget,0);
dimWidget = new QLabel("", statusBar());
statusBar()->addWidget(dimWidget,0);
rotateLabel = new QLabel("", statusBar());
statusBar()->addWidget(rotateLabel,0);
shiftLabel = new QLabel("", statusBar());
statusBar()->addWidget(shiftLabel,0);
scaleLabel = new QLabel("", statusBar());
statusBar()->addWidget(scaleLabel,0);
zoomLabel = new QLabel("", statusBar());
statusBar()->addWidget(zoomLabel,0);
connect(dataWidget, SIGNAL(rotationChanged(double,double,double)),this,SLOT(showRotate(double,double,double)));
connect(dataWidget, SIGNAL(vieportShiftChanged(double,double)),this,SLOT(showShift(double,double)));
connect(dataWidget, SIGNAL(scaleChanged(double,double,double)),this,SLOT(showScale(double,double,double)));
connect(dataWidget, SIGNAL(zoomChanged(double)),this,SLOT(showZoom(double)));
connect(functionCB, SIGNAL(activated(const QString&)), this, SLOT(createFunction(const QString&)));
connect(psurfaceCB, SIGNAL(activated(const QString&)), this, SLOT(createPSurface(const QString&)));
connect(projection, SIGNAL( toggled(bool) ), this, SLOT( toggleProjectionMode(bool)));
connect(colorlegend, SIGNAL( toggled(bool) ), this, SLOT( toggleColorLegend(bool)));
connect(autoscale, SIGNAL( toggled(bool) ), this, SLOT( toggleAutoScale(bool)));
connect(shader, SIGNAL( toggled(bool) ), this, SLOT( toggleShader(bool)));
connect(mouseinput, SIGNAL( toggled(bool) ), dataWidget, SLOT( enableMouse(bool)));
connect(lightingswitch, SIGNAL( toggled(bool) ), this, SLOT( enableLighting(bool)));
connect(normals, SIGNAL( toggled(bool) ), this, SLOT( showNormals(bool)));
connect(normalsquality, SIGNAL(valueChanged(int)), this, SLOT(setNormalQuality(int)) );
connect(normalslength, SIGNAL(valueChanged(int)), this, SLOT(setNormalLength(int)) );
setStandardView();
dataWidget->coordinates()->setLineSmooth(true);
dataWidget->coordinates()->setGridLinesColor(RGBA(0.35,0.35,0.35,1));
dataWidget->enableMouse(true);
dataWidget->setKeySpeed(15,20,20);
lightingdlg_ = new LightingDlg( this );
lightingdlg_->assign( dataWidget);
#if QT_VERSION < 0x040000 //todo - restore, when Qt4 re-implements preview functionality
datacolordlg_ = new QFileDialog( this );
QDir dir("./../../data/colormaps");
if (dir.exists("./../../data/colormaps"))
datacolordlg_->setDir("./../../data/colormaps");
datacolordlg_->setFilter("Colormap files (*.map *.MAP)");
colormappv_ = new ColorMapPreview;
datacolordlg_->setContentsPreviewEnabled( TRUE );
datacolordlg_->setContentsPreview( colormappv_, colormappv_ );
datacolordlg_->setPreviewMode( QFileDialog::Contents );
connect(datacolordlg_, SIGNAL(fileHighlighted(const QString&)), this, SLOT(adaptDataColors(const QString&)));
#else
//connect(datacolordlg_, SIGNAL(filesSelected(const QStringList&)), this, SLOT(adaptDataColors4(const QStringList&)));
#endif
connect(filetypeCB, SIGNAL(activated(const QString&)), this, SLOT(setFileType(const QString&)));
filetypeCB->clear();
QStringList list = IO::outputFormatList();
#if QT_VERSION < 0x040000
filetypeCB->insertStringList(list);
#else
filetypeCB->insertItems(0,list);
#endif
filetype_ = filetypeCB->currentText();
dataWidget->setTitleFont( "Arial", 14, QFont::Normal );
grids->setEnabled(false);
PixmapWriter* pmhandler = (PixmapWriter*)IO::outputHandler("JPEG");
if (!pmhandler)
pmhandler = (PixmapWriter*)IO::outputHandler("jpeg"); //Qt4 naming scheme change
if (pmhandler)
pmhandler->setQuality(70);
VectorWriter* handler = (VectorWriter*)IO::outputHandler("PDF");
handler->setTextMode(VectorWriter::TEX);
handler = (VectorWriter*)IO::outputHandler("EPS");
handler->setTextMode(VectorWriter::TEX);
handler = (VectorWriter*)IO::outputHandler("EPS_GZ");
if (handler) // with zlib support only
handler->setTextMode(VectorWriter::TEX);
}
void Mesh2MainWindow::open()
{
#if QT_VERSION < 0x040000
QString s = QFileDialog::getOpenFileName( "../../data", "GridData Files (*.mes *.MES)", this );
#else
QString s = QFileDialog::getOpenFileName( this, "", "../../data", "GridData Files (*.mes *.MES)");
#endif
if ( s.isEmpty() || !dataWidget)
return;
QFileInfo fi( s );
#if QT_VERSION < 0x040000
QString ext = fi.extension(); // ext = "gz"
QToolTip::add(filenameWidget, s);
#else
filenameWidget->setToolTip(s);
QString ext = fi.suffix();
#endif
filenameWidget->setText(fi.fileName());
qApp->processEvents(); // enforces repaint;
if (IO::load(dataWidget, s, ext))
{
double a = dataWidget->facets().first;
double b = dataWidget->facets().second;
dimWidget->setText(QString("Cells ") + QString::number(a*b)
+ " (" + QString::number(a) + "x" + QString::number(b) +")" );
dataWidget->setResolution(3);
}
for (unsigned i=0; i!=dataWidget->coordinates()->axes.size(); ++i)
{
dataWidget->coordinates()->axes[i].setMajors(4);
dataWidget->coordinates()->axes[i].setMinors(5);
dataWidget->coordinates()->axes[i].setLabelString("");
}
updateColorLegend(4,5);
pickCoordSystem(activeCoordSystem);
dataWidget->showColorLegend(legend_);
}
void Mesh2MainWindow::createFunction(QString const& name)
{
dataWidget->makeCurrent();
dataWidget->legend()->setScale(LINEARSCALE);
for (unsigned i=0; i!=dataWidget->coordinates()->axes.size(); ++i)
{
dataWidget->coordinates()->axes[i].setMajors(7);
dataWidget->coordinates()->axes[i].setMinors(5);
}
if (name == QString("LevelSetFunctionSurface"))
{
LevelSetFunctionSurface rosenbrock(*dataWidget);
rosenbrock.setMesh(50,51);
rosenbrock.setDomain(-1.73,1.55,-1.5,1.95);
rosenbrock.setMinZ(-100);
rosenbrock.create();
dataWidget->coordinates()->axes[Z1].setScale(LOG10SCALE);
dataWidget->coordinates()->axes[Z2].setScale(LOG10SCALE);
dataWidget->coordinates()->axes[Z3].setScale(LOG10SCALE);
dataWidget->coordinates()->axes[Z4].setScale(LOG10SCALE);
dataWidget->legend()->setScale(LOG10SCALE);
}
else if (name == QString("Hat"))
{
Hat hat(*dataWidget);
hat.setMesh(51,72);
hat.setDomain(-1.5,1.5,-1.5,1.5);
hat.create();
}
else if (name == QString("Ripple"))
{
Ripple ripple(*dataWidget);
ripple.setMesh(120,120);
ripple.create();
}
else if (name == QString("Saddle"))
{
Saddle saddle;
saddle.setMesh(71,71);
double dom = 2.5;
saddle.setDomain(-dom, dom, -dom, dom);
saddle.assign(*dataWidget);
saddle.create();
}
else if (name == QString("Sombrero"))
{
Mex mex;
mex.setMesh(91,91);
double dom = 15;
mex.setDomain(-dom, dom, -dom, dom);
mex.create(*dataWidget);
}
double a = dataWidget->facets().first;
double b = dataWidget->facets().second;
dimWidget->setText(QString("Cells ") + QString::number(a*b)
+ " (" + QString::number(a) + "x" + QString::number(b) +")" );
updateColorLegend(7,5);
dataWidget->coordinates()->axes[X1].setLabelString(QString("X1"));
dataWidget->coordinates()->axes[X2].setLabelString(QString("X2"));
dataWidget->coordinates()->axes[X3].setLabelString(QString("X3"));
dataWidget->coordinates()->axes[X4].setLabelString(QString("X4"));
dataWidget->coordinates()->axes[Y1].setLabelString(QString("Y1"));
dataWidget->coordinates()->axes[Y2].setLabelString(QString("Y2"));
dataWidget->coordinates()->axes[Y3].setLabelString(QString("Y3"));
dataWidget->coordinates()->axes[Y4].setLabelString(QString("Y4"));
dataWidget->coordinates()->axes[Z1].setLabelString(QString("Z1"));
dataWidget->coordinates()->axes[Z2].setLabelString(QString("Z2"));
dataWidget->coordinates()->axes[Z3].setLabelString(QString("Z3"));
dataWidget->coordinates()->axes[Z4].setLabelString(QString("Z4"));
pickCoordSystem(activeCoordSystem);
}
void Mesh2MainWindow::createPSurface(QString const& name)
{
dataWidget->makeCurrent();
if (name == QString("Torus"))
{
Torus sf(*dataWidget);
sf.create();
}
else if (name == QString("Seashell"))
{
Seashell ss(*dataWidget);
ss.create();
}
else if (name == QString("Boy"))
{
Boy boy(*dataWidget);
boy.create();
}
else if (name == QString("Dini"))
{
Dini dini(*dataWidget);
dini.create();
}
else if (name == QString("Cone"))
{
TripleField conepos;
CellField conecell;
createCone(conepos,conecell);
dataWidget->loadFromData(conepos, conecell);
}
for (unsigned i=0; i!=dataWidget->coordinates()->axes.size(); ++i)
{
dataWidget->coordinates()->axes[i].setMajors(7);
dataWidget->coordinates()->axes[i].setMinors(5);
}
double a = dataWidget->facets().first;
double b = dataWidget->facets().second;
dimWidget->setText(QString("Cells ") + QString::number(a*b)
+ " (" + QString::number(a) + "x" + QString::number(b) +")" );
updateColorLegend(7,5);
dataWidget->coordinates()->axes[X1].setLabelString(QString("X1"));
dataWidget->coordinates()->axes[X2].setLabelString(QString("X2"));
dataWidget->coordinates()->axes[X3].setLabelString(QString("X3"));
dataWidget->coordinates()->axes[X4].setLabelString(QString("X4"));
dataWidget->coordinates()->axes[Y1].setLabelString(QString("Y1"));
dataWidget->coordinates()->axes[Y2].setLabelString(QString("Y2"));
dataWidget->coordinates()->axes[Y3].setLabelString(QString("Y3"));
dataWidget->coordinates()->axes[Y4].setLabelString(QString("Y4"));
dataWidget->coordinates()->axes[Z1].setLabelString(QString("Z1"));
dataWidget->coordinates()->axes[Z2].setLabelString(QString("Z2"));
dataWidget->coordinates()->axes[Z3].setLabelString(QString("Z3"));
dataWidget->coordinates()->axes[Z4].setLabelString(QString("Z4"));
pickCoordSystem(activeCoordSystem);
}
void Mesh2MainWindow::pickCoordSystem( QAction* action)
{
if (!action || !dataWidget)
return;
activeCoordSystem = action;
dataWidget->setTitle("QwtPlot3D (Use Ctrl-Alt-Shift-LeftBtn-Wheel or keyboard)");
if (!dataWidget->hasData())
{
double l = 0.6;
dataWidget->createCoordinateSystem(Triple(-l,-l,-l), Triple(l,l,l));
for (unsigned i=0; i!=dataWidget->coordinates()->axes.size(); ++i)
{
dataWidget->coordinates()->axes[i].setMajors(4);
dataWidget->coordinates()->axes[i].setMinors(5);
}
}
if (action == Box || action == Frame)
{
if (action == Box)
dataWidget->setCoordinateStyle(BOX);
if (action == Frame)
dataWidget->setCoordinateStyle(FRAME);
grids->setEnabled(true);
}
else if (action == None)
{
dataWidget->setTitle("QwtPlot3D (Use Ctrl-Alt-Shift-LeftBtn-Wheel or keyboard)");
dataWidget->setCoordinateStyle(NOCOORD);
grids->setEnabled(false);
}
}
void Mesh2MainWindow::pickPlotStyle( QAction* action )
{
if (!action || !dataWidget)
return;
if (action == polygon)
{
dataWidget->setPlotStyle(FILLED);
}
else if (action == filledmesh)
{
dataWidget->setPlotStyle(FILLEDMESH);
}
else if (action == wireframe)
{
dataWidget->setPlotStyle(WIREFRAME);
}
else if (action == hiddenline)
{
dataWidget->setPlotStyle(HIDDENLINE);
}
else if (action == pointstyle)
{
dataWidget->setPlotStyle(Qwt3D::POINTS);
// Cone d(len,32);
// CrossHair d(0.003,0,true,false);
// dataWidget->setPlotStyle(d);
}
else
{
dataWidget->setPlotStyle(NOPLOT);
}
dataWidget->updateData();
dataWidget->updateGL();
}
void
Mesh2MainWindow::pickFloorStyle( QAction* action )
{
if (!action || !dataWidget)
return;
if (action == floordata)
{
dataWidget->setFloorStyle(FLOORDATA);
}
else if (action == flooriso)
{
dataWidget->setFloorStyle(FLOORISO);
}
else
{
dataWidget->setFloorStyle(NOFLOOR);
}
dataWidget->updateData();
dataWidget->updateGL();
}
void Mesh2MainWindow::setLeftGrid(bool b)
{
setGrid(Qwt3D::LEFT,b);
}
void Mesh2MainWindow::setRightGrid(bool b)
{
setGrid(Qwt3D::RIGHT,b);
}
void Mesh2MainWindow::setCeilGrid(bool b)
{
setGrid(Qwt3D::CEIL,b);
}
void Mesh2MainWindow::setFloorGrid(bool b)
{
setGrid(Qwt3D::FLOOR,b);
}
void Mesh2MainWindow::setFrontGrid(bool b)
{
setGrid(Qwt3D::FRONT,b);
}
void Mesh2MainWindow::setBackGrid(bool b)
{
setGrid(Qwt3D::BACK,b);
}
void Mesh2MainWindow::setGrid(Qwt3D::SIDE s, bool b)
{
if (!dataWidget)
return;
int sum = dataWidget->coordinates()->grids();
if (b)
sum |= s;
else
sum &= ~s;
dataWidget->coordinates()->setGridLines(sum!=Qwt3D::NOSIDEGRID, sum!=Qwt3D::NOSIDEGRID, sum);
dataWidget->updateGL();
}
void Mesh2MainWindow::resetColors()
{
if (!dataWidget)
return;
const RGBA axc = RGBA(0,0,0,1);
const RGBA bgc = RGBA(1.0,1.0,1.0,1.0);
const RGBA msc = RGBA(0,0,0,1);
const RGBA nuc = RGBA(0,0,0,1);
const RGBA lbc = RGBA(0,0,0,1);
const RGBA tc = RGBA(0,0,0,1);
dataWidget->coordinates()->setAxesColor(axc);
dataWidget->setBackgroundColor(bgc);
dataWidget->setMeshColor(msc);
dataWidget->updateData();
dataWidget->coordinates()->setNumberColor(nuc);
dataWidget->coordinates()->setLabelColor(lbc);
dataWidget->setTitleColor(tc);
col_ = new StandardColor(dataWidget);
dataWidget->setDataColor(col_);
dataWidget->updateData();
dataWidget->updateNormals();
dataWidget->updateGL();
}
void Mesh2MainWindow::pickAxesColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->coordinates()->setAxesColor(rgb);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickBgColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->setBackgroundColor(rgb);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickMeshColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->setMeshColor(rgb);
dataWidget->updateData();
dataWidget->updateGL();
}
void Mesh2MainWindow::pickNumberColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->coordinates()->setNumberColor(rgb);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickLabelColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->coordinates()->setLabelColor(rgb);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickTitleColor()
{
QColor c = QColorDialog::getColor( Qt::white, this );
if ( !c.isValid() )
return;
RGBA rgb = Qt2GL(c);
dataWidget->setTitleColor(rgb);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickLighting()
{
lightingdlg_->show();
}
void Mesh2MainWindow::pickDataColor()
{
#if QT_VERSION < 0x040000
datacolordlg_->show();
#else
QString s = QFileDialog::getOpenFileName( this, "", "./../../data/colormaps", "Colormap files (*.map *.MAP)");
adaptDataColors(s);
#endif
}
void Mesh2MainWindow::adaptDataColors(const QString& fileName)
{
ColorVector cv;
if (!openColorMap(cv, fileName))
return;
col_ = new StandardColor(dataWidget);
col_->setColorVector(cv);
dataWidget->setDataColor(col_);
dataWidget->updateData();
dataWidget->updateNormals();
dataWidget->showColorLegend(legend_);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickNumberFont()
{
bool ok;
QFont font = QFontDialog::getFont(&ok, this );
if ( !ok )
{
return;
}
dataWidget->coordinates()->setNumberFont(font);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickLabelFont()
{
bool ok;
QFont font = QFontDialog::getFont(&ok, this );
if ( !ok )
{
return;
}
dataWidget->coordinates()->setLabelFont(font);
dataWidget->updateGL();
}
void Mesh2MainWindow::pickTitleFont()
{
bool ok;
QFont font = QFontDialog::getFont(&ok, this );
if ( !ok )
{
return;
}
dataWidget->setTitleFont(font.family(), font.pointSize(), font.weight(), font.italic());
}
void Mesh2MainWindow::resetFonts()
{
dataWidget->coordinates()->setNumberFont(QFont("Courier", 12));
dataWidget->coordinates()->setLabelFont(QFont("Courier", 14, QFont::Bold));
dataWidget->setTitleFont( "Arial", 14, QFont::Normal );
dataWidget->updateGL();
}
void Mesh2MainWindow::setStandardView()
{
dataWidget->setRotation(30,0,15);
dataWidget->setViewportShift(0.05,0);
dataWidget->setScale(1,1,1);
dataWidget->setZoom(0.95);
}
void Mesh2MainWindow::dumpImage()
{
static int counter = 0;
if (!dataWidget)
return;
QString name;
name = QString("dump_") + QString::number(counter++) + ".";
if (filetype_ == "PS_GZ")
name += "ps.gz";
else if (filetype_ == "EPS_GZ")
name += "eps.gz";
else
name += filetype_;
#if QT_VERSION < 0x040000
IO::save(dataWidget, name.lower(), filetype_);
#else
VectorWriter* vw = (VectorWriter*)IO::outputHandler("PDF");
if (vw)
vw->setSortMode(VectorWriter::BSPSORT);
IO::save(dataWidget, name.toLower(), filetype_);
#endif
}
/*!
Turns animation on or off
*/
void Mesh2MainWindow::toggleAnimation(bool val)
{
if ( val )
{
timer->start( redrawWait ); // Wait this many msecs before redraw
}
else
{
timer->stop();
}
}
void Mesh2MainWindow::rotate()
{
if (!dataWidget)
return;
dataWidget->setRotation(
int(dataWidget->xRotation() + 1) % 360,
int(dataWidget->yRotation() + 1) % 360,
int(dataWidget->zRotation() + 1) % 360
);
}
void
Mesh2MainWindow::toggleProjectionMode(bool val)
{
dataWidget->setOrtho(val);
}
void
Mesh2MainWindow::toggleColorLegend(bool val)
{
legend_ = val;
dataWidget->showColorLegend(val);
}
void
Mesh2MainWindow::toggleAutoScale(bool val)
{
dataWidget->coordinates()->setAutoScale(val);
dataWidget->updateGL();
}
void
Mesh2MainWindow::toggleShader(bool val)
{
if (val)
dataWidget->setShading(GOURAUD);
else
dataWidget->setShading(FLAT);
}
void
Mesh2MainWindow::setPolygonOffset(int val)
{
dataWidget->setPolygonOffset(val / 10.0);
dataWidget->updateData();
dataWidget->updateGL();
}
void
Mesh2MainWindow::showRotate(double x, double y, double z)
{
rotateLabel->setText(" Angles (" + QString::number(x,'g',3) + " ,"
+ QString::number(y,'g',3) + " ,"
+ QString::number(z,'g',3) + ")");
}
void
Mesh2MainWindow::showShift(double x, double y)
{
shiftLabel->setText(" Shifts (" + QString::number(x,'g',3) + " ,"
+ QString::number(y,'g',3) + " )"
);
}
void
Mesh2MainWindow::showScale(double x, double y, double z)
{
scaleLabel->setText(" Scales (" + QString::number(x,'g',3) + " ,"
+ QString::number(y,'g',3) + " ,"
+ QString::number(z,'g',3) + ")");
}
void
Mesh2MainWindow::showZoom(double z)
{
zoomLabel->setText(" Zoom " + QString::number(z,'g',3));
}
void Mesh2MainWindow::openMesh()
{
#if QT_VERSION < 0x040000
QString data(QFileDialog::getOpenFileName( "../../data", "nodes (*.nod)", this ) );
QString edges( QFileDialog::getOpenFileName( "../../data", "connectivities (*.cel)", this ) );
#else
QString data( QFileDialog::getOpenFileName( this, "", "../../data", "nodes (*.nod)") );
QString edges( QFileDialog::getOpenFileName( this, "", "../../data", "connectivities (*.cel)") );
#endif
if ( data.isEmpty() || edges.isEmpty() || !dataWidget)
return;
TripleField vdata;
CellField vpoly;
readNodes(vdata, QWT3DLOCAL8BIT(data), NodeFilter());
readConnections(vpoly, QWT3DLOCAL8BIT(edges), CellFilter());
dataWidget->loadFromData(vdata, vpoly);
dimWidget->setText(QString("Cells ") + QString::number(dataWidget->facets().first));
for (unsigned i=0; i!=dataWidget->coordinates()->axes.size(); ++i)
{
dataWidget->coordinates()->axes[i].setMajors(4);
dataWidget->coordinates()->axes[i].setMinors(5);
dataWidget->coordinates()->axes[i].setLabelString(QString(""));
}
updateColorLegend(4,5);
pickCoordSystem(activeCoordSystem);
}
void
Mesh2MainWindow::showNormals(bool val)
{
dataWidget->showNormals(val);
dataWidget->updateNormals();
dataWidget->updateGL();
}
void
Mesh2MainWindow::setNormalLength(int val)
{
dataWidget->setNormalLength(val / 400.);
dataWidget->updateNormals();
dataWidget->updateGL();
}
void
Mesh2MainWindow::setNormalQuality(int val)
{
dataWidget->setNormalQuality(val);
dataWidget->updateNormals();
dataWidget->updateGL();
}
bool
Mesh2MainWindow::openColorMap(ColorVector& cv, QString fname)
{
if (fname.isEmpty())
return false;
ifstream file(QWT3DLOCAL8BIT(fname));
if (!file)
return false;
RGBA rgb;
cv.clear();
while ( file )
{
file >> rgb.r >> rgb.g >> rgb.b;
file.ignore(1000,'\n');
if (!file.good())
break;
else
{
rgb.a = 1;
rgb.r /= 255;
rgb.g /= 255;
rgb.b /= 255;
cv.push_back(rgb);
}
}
return true;
}
void
Mesh2MainWindow::updateColorLegend(int majors, int minors)
{
dataWidget->legend()->setMajors(majors);
dataWidget->legend()->setMinors(minors);
double start, stop;
dataWidget->coordinates()->axes[Z1].limits(start,stop);
dataWidget->legend()->setLimits(start, stop);
}
void Mesh2MainWindow::setFileType(QString const& name)
{
filetype_ = name;
}
void Mesh2MainWindow::enableLighting(bool val)
{
dataWidget->enableLighting(val);
dataWidget->illuminate(0);
dataWidget->updateGL();
}
| [
"[email protected]"
] | [
[
[
1,
956
]
]
] |
20d99f4dc5dae3e75afe7fafb6dfef6a8c62b53d | 58ef4939342d5253f6fcb372c56513055d589eb8 | /ScheduleKiller/source/Views/inc/SettingScreenView.h | c370c5d780ab3e53c0f11157253b09f2597b5e90 | [] | no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | h | /*
============================================================================
Name : SettingScreenView.h
Author : zengcity
Copyright : Your copyright notice
Description : Declares view class for application.
============================================================================
*/
#ifndef SETTINGSCREENVIEW_H
#define SETTINGSCREENVIEW_H
// INCLUDES
#include <aknview.h>
#include "SettingScreenContainer.h"
// CONSTANTS
// FORWARD DECLARATIONS
// CLASS DECLARATION
/**
* CSettingScreenView view class.
*
*/
class CSettingScreenView : public CAknView
{
public:
// Constructors and destructor
~CSettingScreenView();
static CSettingScreenView* NewL();
static CSettingScreenView* NewLC();
public:
TUid Id() const;
void HandleCommandL(TInt aCommand);
void HandleStatusPaneSizeChange();
private:
CSettingScreenView();
void ConstructL();
protected:
void DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId,
const TDesC8& aCustomMessage);
void DoDeactivate();
private:
CSettingScreenContainer * iContainer;
};
#endif
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
] | [
[
[
1,
54
]
]
] |
109b727ea2655ee6615cac974ff987495633e303 | f0c08b3ddefc91f1fa342f637b0e947a9a892556 | /branches/develop/calcioIA/GlutApp/GLDraw.cpp | 627dba04bcebd456a3566f02eb167cef008123f2 | [] | no_license | BackupTheBerlios/coffeestore-svn | 1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f | ddee83284fe9875bf0d04e6b7da7a2113e85a040 | refs/heads/master | 2021-01-01T05:30:22.345767 | 2009-10-11T08:55:35 | 2009-10-11T08:55:35 | 40,725,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | cpp | #include "GLDraw.h"
#include "Ball.h"
#include "Player.h"
#include "Team.h"
#include "Field.h"
#include "Game.h"
#include <GL/glut.h>
#include <cmath>
void GLDraw::draw(const Ball& ball)
{
glPushAttrib(GL_CURRENT_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
drawFilledCircle(ball.position(), ball.radius());
glPopAttrib();
}
void GLDraw::draw(const Team& team)
{
glPushAttrib(GL_CURRENT_BIT);
if (team.color() == Team::Color_RED)
glColor3f(1.0f,0.0f,0.0f);
if (team.color() == Team::Color_BLUE)
glColor3f(0.0f,0.0f,1.0f);
for (Team::PlayersConstIterator it = team.playersBegin(); it != team.playersEnd(); ++it)
draw(*(*it));
glPopAttrib();
}
void GLDraw::draw(const Player& player)
{
drawFilledCircle(player.position(), player.radius());
}
void GLDraw::drawFilledCircle(const Point& point, float radius)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef(point.x(), point.y(), 0.0f);
glScalef(450.0f/800.0f,1.0f,1.0f);
glBegin(GL_POLYGON);
const float deg2rad = M_PI/180.0f;
for (int i = 0; i < 360; i++)
{
float degInRad = i*deg2rad;
glVertex2f(cos(degInRad) * radius, sin(degInRad) * radius);
}
glEnd();
glPopMatrix();
}
void GLDraw::drawWire(const Rectangle& rectangle)
{
glBegin(GL_LINE_LOOP);
glVertex2f(rectangle.a().x(), rectangle.a().y());
glVertex2f(rectangle.c().x(), rectangle.a().y());
glVertex2f(rectangle.c().x(), rectangle.c().y());
glVertex2f(rectangle.a().x(), rectangle.c().y());
glEnd();
}
void GLDraw::draw(const Line& line)
{
glBegin(GL_LINES);
glVertex2f(line.a().x(), line.a().y());
glVertex2f(line.b().x(), line.b().y());
glEnd();
}
void GLDraw::draw(const Field& field)
{
glPushAttrib(GL_CURRENT_BIT);
glColor3f(1.0f,1.0f,1.0f);
drawWire(field.boxLeft());
drawWire(field.boxRight());
drawWire(field.corner());
draw(field.mid());
glPopAttrib();
}
void GLDraw::draw(const Game& game)
{
draw(game.teamRed());
draw(game.teamBlue());
draw(game.field());
draw(game.ball());
}
| [
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
] | [
[
[
1,
102
]
]
] |
79b8255c98d5af749b5fc1257ad0ce83adf49743 | 61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935 | /patoGUI/mainwindow.h | 8ff7d12437b0c8fe8b70362acc6a1f8a07a0f93d | [] | no_license | matherthal/pato-scm | 172497f3e5c6d71a2cbbd2db132282fb36ba4871 | ba573dad95afa0c0440f1ae7d5b52a2736459b10 | refs/heads/master | 2020-05-20T08:48:12.286498 | 2011-11-25T11:05:23 | 2011-11-25T11:05:23 | 33,139,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void setWorkspaceModel(const QString &str);
void enableActions();
void help();
//void log();
//void addFile();
//void update();
//void executeCheckout();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"rafael@Micro-Mariana"
] | [
[
[
1,
29
]
]
] |
bfe34877210f769512fabfe35462361f1816792c | 729fbfae883f0f1a7330f62255656b5ed3d51ee6 | /BeijingApp/src/addons/ofxCubeMapRenderer/src/ofxCubeMapRenderer.h | cf3c1fc84102351b6e2e0743f09a77de211ef001 | [] | no_license | jjzhang166/CreatorsProjectDev | 76d3481f9c6d290485718b96d8e06c1df2676ceb | bf0250731d22a42d7b9b6821aff98fcd663d68c1 | refs/heads/master | 2021-12-02T03:12:33.528110 | 2010-09-02T23:33:55 | 2010-09-02T23:33:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h | #pragma once
#include "ofMain.h"
#include "ofxFbo.h"
class ofxCubeMapRenderer {
public:
ofxCubeMapRenderer();
void setup(int cubeSize);
void render();
void draw();
virtual void drawScene() = 0;
protected:
void renderDirection(ofTexture& target,
float targetX, float targetY, float targetZ,
float upX, float upY, float upZ);
void pushEverything();
void popEverything();
int cubeSize;
ofxFbo fbo;
ofTexture frontView, leftView, backView, rightView, upView, downView;
};
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
225f061058faf6603b5fbf0b13c03edebe575b8b | fbf246f1ea06a14b61bf04f20d9bf90b9ff73ef5 | /GameAndWatch/include/devices/dev_pirate.h | 7c28389ce9e6dd27eae8dce2f76abd02491fabae | [] | no_license | biappi/GameAndWatch | e503f4ebabb326a45c81380f32358f9f810c9b2d | a586b16a48727b587253f1b95c89cf40fb4429d6 | refs/heads/master | 2020-09-21T14:02:05.733066 | 2011-08-31T16:16:23 | 2011-08-31T16:16:23 | 2,295,881 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | #ifndef H__DEV_PIRATE__H
#define H__DEV_PIRATE__H
#include "devices/deveng_vtech_monkey.h"
class GW_Game_Pirate_Info : public GW_Game_Info
{
public:
GW_Game_Pirate_Info(const string &platformdatapath) :
GW_Game_Info("pirate", "Time & Fun - Pirate", "pirate",
platformdatapath,
"bg.bmp", true, GW_Platform_RGB_create(255, 0, 255)) {}
virtual GW_Game *create();
};
class GW_Game_Pirate : public GW_GameEngine_VTech_Monkey
{
public:
GW_Game_Pirate();
};
#endif //H__DEV_PIRATE__H
| [
"[email protected]"
] | [
[
[
1,
25
]
]
] |
f58cce42664c1b80c6b91b501ad675debc985a4e | 65dee2b7ed8a91f952831525d78bfced5abd713f | /winmob/XfMobile_WM6/Gamepe/SHA1.cpp | c99a6fabc2b2bdd0a13c904842460c77275e7dd1 | [] | no_license | felixnicitin1968/XFMobile | 0249f90f111f0920a423228691bcbef0ecb0ce23 | 4a442d0127366afa9f80bdcdaaa4569569604dac | refs/heads/master | 2016-09-06T05:02:18.589338 | 2011-07-05T17:25:39 | 2011-07-05T17:25:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,083 | cpp | /*
100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <[email protected]>
Version 1.5 - 2005-01-01
- 64-bit compiler compatibility added
- Made variable wiping optional (define SHA1_WIPE_VARIABLES)
- Removed unnecessary variable initializations
- ROL32 improvement for the Microsoft compiler (using _rotl)
======== Test Vectors (from FIPS PUB 180-1) ========
SHA1("abc") =
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") =
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1(A million repetitions of "a") =
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/
#include "stdafx.h"
#include "SHA1.h"
#define SHA1_MAX_FILE_BUFFER 8000
// Rotate x bits to the left
#ifndef ROL32
#ifdef _MSC_VER
#define ROL32(_val32, _nBits) _rotl(_val32, _nBits)
#else
#define ROL32(_val32, _nBits) (((_val32)<<(_nBits))|((_val32)>>(32-(_nBits))))
#endif
#endif
#ifdef SHA1_LITTLE_ENDIAN
#define SHABLK0(i) (m_block->l[i] = \
(ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF))
#else
#define SHABLK0(i) (m_block->l[i])
#endif
#define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ m_block->l[(i+8)&15] \
^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1))
// SHA-1 rounds
#define _R0(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
#define _R1(v,w,x,y,z,i) { z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5); w=ROL32(w,30); }
#define _R2(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5); w=ROL32(w,30); }
#define _R3(v,w,x,y,z,i) { z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5); w=ROL32(w,30); }
#define _R4(v,w,x,y,z,i) { z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5); w=ROL32(w,30); }
CSHA1::CSHA1()
{
m_block = (SHA1_WORKSPACE_BLOCK *)m_workspace;
Reset();
}
CSHA1::~CSHA1()
{
Reset();
}
void CSHA1::Reset()
{
// SHA1 initialization constants
m_state[0] = 0x67452301;
m_state[1] = 0xEFCDAB89;
m_state[2] = 0x98BADCFE;
m_state[3] = 0x10325476;
m_state[4] = 0xC3D2E1F0;
m_count[0] = 0;
m_count[1] = 0;
}
void CSHA1::Transform(UINT_32 *state, UINT_8 *buffer)
{
// Copy state[] to working vars
UINT_32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
memcpy(m_block, buffer, 64);
// 4 rounds of 20 operations each. Loop unrolled.
_R0(a,b,c,d,e, 0); _R0(e,a,b,c,d, 1); _R0(d,e,a,b,c, 2); _R0(c,d,e,a,b, 3);
_R0(b,c,d,e,a, 4); _R0(a,b,c,d,e, 5); _R0(e,a,b,c,d, 6); _R0(d,e,a,b,c, 7);
_R0(c,d,e,a,b, 8); _R0(b,c,d,e,a, 9); _R0(a,b,c,d,e,10); _R0(e,a,b,c,d,11);
_R0(d,e,a,b,c,12); _R0(c,d,e,a,b,13); _R0(b,c,d,e,a,14); _R0(a,b,c,d,e,15);
_R1(e,a,b,c,d,16); _R1(d,e,a,b,c,17); _R1(c,d,e,a,b,18); _R1(b,c,d,e,a,19);
_R2(a,b,c,d,e,20); _R2(e,a,b,c,d,21); _R2(d,e,a,b,c,22); _R2(c,d,e,a,b,23);
_R2(b,c,d,e,a,24); _R2(a,b,c,d,e,25); _R2(e,a,b,c,d,26); _R2(d,e,a,b,c,27);
_R2(c,d,e,a,b,28); _R2(b,c,d,e,a,29); _R2(a,b,c,d,e,30); _R2(e,a,b,c,d,31);
_R2(d,e,a,b,c,32); _R2(c,d,e,a,b,33); _R2(b,c,d,e,a,34); _R2(a,b,c,d,e,35);
_R2(e,a,b,c,d,36); _R2(d,e,a,b,c,37); _R2(c,d,e,a,b,38); _R2(b,c,d,e,a,39);
_R3(a,b,c,d,e,40); _R3(e,a,b,c,d,41); _R3(d,e,a,b,c,42); _R3(c,d,e,a,b,43);
_R3(b,c,d,e,a,44); _R3(a,b,c,d,e,45); _R3(e,a,b,c,d,46); _R3(d,e,a,b,c,47);
_R3(c,d,e,a,b,48); _R3(b,c,d,e,a,49); _R3(a,b,c,d,e,50); _R3(e,a,b,c,d,51);
_R3(d,e,a,b,c,52); _R3(c,d,e,a,b,53); _R3(b,c,d,e,a,54); _R3(a,b,c,d,e,55);
_R3(e,a,b,c,d,56); _R3(d,e,a,b,c,57); _R3(c,d,e,a,b,58); _R3(b,c,d,e,a,59);
_R4(a,b,c,d,e,60); _R4(e,a,b,c,d,61); _R4(d,e,a,b,c,62); _R4(c,d,e,a,b,63);
_R4(b,c,d,e,a,64); _R4(a,b,c,d,e,65); _R4(e,a,b,c,d,66); _R4(d,e,a,b,c,67);
_R4(c,d,e,a,b,68); _R4(b,c,d,e,a,69); _R4(a,b,c,d,e,70); _R4(e,a,b,c,d,71);
_R4(d,e,a,b,c,72); _R4(c,d,e,a,b,73); _R4(b,c,d,e,a,74); _R4(a,b,c,d,e,75);
_R4(e,a,b,c,d,76); _R4(d,e,a,b,c,77); _R4(c,d,e,a,b,78); _R4(b,c,d,e,a,79);
// Add the working vars back into state
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
// Wipe variables
#ifdef SHA1_WIPE_VARIABLES
a = b = c = d = e = 0;
#endif
}
// Use this function to hash in binary data and strings
void CSHA1::Update(UINT_8 *data, UINT_32 len)
{
UINT_32 i, j;
j = (m_count[0] >> 3) & 63;
if((m_count[0] += len << 3) < (len << 3)) m_count[1]++;
m_count[1] += (len >> 29);
if((j + len) > 63)
{
i = 64 - j;
memcpy(&m_buffer[j], data, i);
Transform(m_state, m_buffer);
for( ; i + 63 < len; i += 64) Transform(m_state, &data[i]);
j = 0;
}
else i = 0;
memcpy(&m_buffer[j], &data[i], len - i);
}
// Hash in file contents
bool CSHA1::HashFile(char *szFileName)
{
unsigned long ulFileSize, ulRest, ulBlocks;
unsigned long i;
UINT_8 uData[SHA1_MAX_FILE_BUFFER];
FILE *fIn;
if(szFileName == NULL) return false;
fIn = fopen(szFileName, "rb");
if(fIn == NULL) return false;
fseek(fIn, 0, SEEK_END);
ulFileSize = (unsigned long)ftell(fIn);
fseek(fIn, 0, SEEK_SET);
if(ulFileSize != 0)
{
ulBlocks = ulFileSize / SHA1_MAX_FILE_BUFFER;
ulRest = ulFileSize % SHA1_MAX_FILE_BUFFER;
}
else
{
ulBlocks = 0;
ulRest = 0;
}
for(i = 0; i < ulBlocks; i++)
{
fread(uData, 1, SHA1_MAX_FILE_BUFFER, fIn);
Update((UINT_8 *)uData, SHA1_MAX_FILE_BUFFER);
}
if(ulRest != 0)
{
fread(uData, 1, ulRest, fIn);
Update((UINT_8 *)uData, ulRest);
}
fclose(fIn); fIn = NULL;
return true;
}
void CSHA1::Final()
{
UINT_32 i;
UINT_8 finalcount[8];
for(i = 0; i < 8; i++)
finalcount[i] = (UINT_8)((m_count[((i >= 4) ? 0 : 1)]
>> ((3 - (i & 3)) * 8) ) & 255); // Endian independent
Update((UINT_8 *)"\200", 1);
while ((m_count[0] & 504) != 448)
Update((UINT_8 *)"\0", 1);
Update(finalcount, 8); // Cause a SHA1Transform()
for(i = 0; i < 20; i++)
{
m_digest[i] = (UINT_8)((m_state[i >> 2] >> ((3 - (i & 3)) * 8) ) & 255);
}
// Wipe variables for security reasons
#ifdef SHA1_WIPE_VARIABLES
i = 0;
memset(m_buffer, 0, 64);
memset(m_state, 0, 20);
memset(m_count, 0, 8);
memset(finalcount, 0, 8);
Transform(m_state, m_buffer);
#endif
}
// Get the final hash as a pre-formatted string
void CSHA1::ReportHash(char *szReport, unsigned char uReportType)
{
unsigned char i;
char szTemp[16];
if(szReport == NULL) return;
if(uReportType == REPORT_HEX)
{
sprintf(szTemp, "%02X", m_digest[0]);
strcat(szReport, szTemp);
for(i = 1; i < 20; i++)
{
sprintf(szTemp, " %02X", m_digest[i]);
strcat(szReport, szTemp);
}
}
else if(uReportType == REPORT_DIGIT)
{
sprintf(szTemp, "%u", m_digest[0]);
strcat(szReport, szTemp);
for(i = 1; i < 20; i++)
{
sprintf(szTemp, " %u", m_digest[i]);
strcat(szReport, szTemp);
}
}
else strcpy(szReport, "Error: Unknown report type!");
}
// Get the raw message digest
void CSHA1::GetHash(UINT_8 *puDest)
{
memcpy(puDest, m_digest, 20);
}
| [
"[email protected]"
] | [
[
[
1,
261
]
]
] |
f61eb5c1a17874a9876fc1d2c30c955fd63f9b3f | ffe0a7d058b07d8f806d610fc242d1027314da23 | /V3e/mc/src/irc/IRCCmdw.h | 4f844d6382862b677782f410137b43ad608935a2 | [] | no_license | Cybie/mangchat | 27bdcd886894f8fdf2c8956444450422ea853211 | 2303d126245a2b4778d80dda124df8eff614e80e | refs/heads/master | 2016-09-11T13:03:57.386786 | 2009-12-13T22:09:37 | 2009-12-13T22:09:37 | 32,145,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83 | h | #pragma once
class IRCCmdw
{
public:
IRCCmdw(void);
~IRCCmdw(void);
}; | [
"cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd"
] | [
[
[
1,
8
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.